Search is not available for this dataset
text string | meta dict |
|---|---|
/*
* mixmax.c
* MIXMAX, A Pseudo-Random Number Generator
*
* Copyright Konstantin Savvidy.
*
* Free to use, academic or commercial. Do not redistribute without permission.
*
* G.K.Savvidy and N.G.Ter-Arutyunian,
* On the Monte Carlo simulation of physical systems,
* J.Comput.Phys. 97, 566 (1991);
* Preprint EPI-865-16-86, Yerevan, Jan. 1986
*
* K.Savvidy
* The MIXMAX random number generator
* Comp. Phys. Commun. 196 (2015), pp 161–165
* http://dx.doi.org/10.1016/j.cpc.2015.06.003
*
*/
#include <stdio.h>
#include <stdint.h>
#ifndef MIXMAX_H_
#define MIXMAX_H_
#define USE_INLINE_ASM
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _N
#define N 240
/* The currently recommended generator is the three-parameter MIXMAX with
N=240, s=487013230256099140, m=2^51+1
Other newly recommended N are N=8, 17 and 240,
as well as the ordinary MIXMAX with N=256 and s=487013230256099064
Since the algorithm is linear in N, the cost per number is almost independent of N.
*/
#else
#define N _N
#endif
#ifndef __LP64__
typedef uint64_t myuint;
//#warning but no problem, 'myuint' is 'uint64_t'
#else
typedef unsigned long long int myuint;
//#warning but no problem, 'myuint' is 'unsigned long long int'
#endif
struct rng_state_st
{
myuint V[N];
myuint sumtot;
int counter;
FILE* fh;
};
typedef struct rng_state_st rng_state_t; // C struct alias
int rng_get_N(void); // get the N programmatically, useful for checking the value for which the library was compiled
rng_state_t *rng_alloc(); /* allocate the state */
int rng_free(rng_state_t* X); /* free memory occupied by the state */
rng_state_t *rng_copy(myuint *Y); /* init from vector, takes the vector Y,
returns pointer to the newly allocated and initialized state */
void read_state(rng_state_t* X, const char filename[] );
void print_state(rng_state_t* X);
int iterate(rng_state_t* X);
myuint iterate_raw_vec(myuint* Y, myuint sumtotOld);
// FUNCTIONS FOR SEEDING
typedef uint32_t myID_t;
void seed_uniquestream(rng_state_t* X, myID_t clusterID, myID_t machineID, myID_t runID, myID_t streamID );
/*
best choice: will make a state vector from which you can get at least 10^100 numbers
guaranteed mathematically to be non-colliding with any other stream prepared from another set of 32bit IDs,
so long as it is different by at least one bit in at least one of the four IDs
-- useful if you are running a parallel simulation with many clusters, many CPUs each
*/
void seed_spbox(rng_state_t* X, myuint seed); // non-linear method, makes certified unique vectors, probability for streams to collide is < 1/10^4600
void seed_vielbein(rng_state_t* X, unsigned int i); // seeds with the i-th unit vector, i = 0..N-1, for testing only
// FUNCTIONS FOR GETTING RANDOM NUMBERS
#ifdef __MIXMAX_C
myuint get_next(rng_state_t* X); // returns 64-bit int, which is between 1 and 2^61-1 inclusive
double get_next_float(rng_state_t* X); // returns double precision floating point number in (0,1]
#endif //__MIXMAX_C
void fill_array(rng_state_t* X, unsigned int n, double *array); // fastest method: set n to a multiple of N (e.g. n=256)
void iterate_and_fill_array(rng_state_t* X, double *array); // fills the array with N numbers
myuint precalc(rng_state_t* X);
/* needed if the state has been changed by something other than iterate, but no worries, seeding functions call this for you when necessary */
myuint apply_bigskip(myuint* Vout, myuint* Vin, myID_t clusterID, myID_t machineID, myID_t runID, myID_t streamID );
// applies a skip of some number of steps calculated from the four IDs
void branch_inplace( rng_state_t* Xin, myID_t* ID ); // almost the same as apply_bigskip, but in-place and from a vector of IDs
#define BITS 61
/* magic with Mersenne Numbers */
#define M61 2305843009213693951ULL
myuint modadd(myuint foo, myuint bar);
myuint modmulM61(myuint s, myuint a);
myuint fmodmulM61(myuint cum, myuint s, myuint a);
#define MERSBASE M61 //xSUFF(M61)
#define MOD_PAYNE(k) ((((k)) & MERSBASE) + (((k)) >> BITS) ) // slightly faster than my old way, ok for addition
#define MOD_REM(k) ((k) % MERSBASE ) // latest Intel CPU is supposed to do this in one CPU cycle, but on my machines it seems to be 20% slower than the best tricks
#define MOD_MERSENNE(k) MOD_PAYNE(k)
//#define INV_MERSBASE (0x1p-61)
#define INV_MERSBASE (0.4336808689942017736029811203479766845703E-18)
//const double INV_MERSBASE=(0.4336808689942017736029811203479766845703E-18); // gives "duplicate symbol" error
// the charpoly is irreducible for the combinations of N and SPECIAL
#if (N==256)
#define SPECIALMUL 0
#define SPECIAL 487013230256099064 // s=487013230256099064, m=1 -- good old MIXMAX
#define MOD_MULSPEC(k) fmodmulM61( 0, SPECIAL , (k) )
#elif (N==8)
#define SPECIALMUL 53 // m=2^53+1
#define SPECIAL 0
#elif (N==17)
#define SPECIALMUL 36 // m=2^36+1, other valid possibilities are m=2^13+1, m=2^19+1, m=2^24+1
#define SPECIAL 0
#elif (N==40)
#define SPECIALMUL 42 // m=2^42+1
#define SPECIAL 0
#elif (N==60)
#define SPECIALMUL 52 // m=2^52+1
#define SPECIAL 0
#elif (N==96)
#define SPECIALMUL 55 // m=2^55+1
#define SPECIAL 0
#elif (N==120)
#define SPECIALMUL 51 // m=2^51+1 and a SPECIAL=+1 (!!!)
#define SPECIAL 1
#define MOD_MULSPEC(k) (k)
#elif (N==240)
#define SPECIALMUL 51 // m=2^51+1 and a SPECIAL=487013230256099140
#define SPECIAL 487013230256099140ULL
#define MOD_MULSPEC(k) fmodmulM61( 0, SPECIAL , (k) )
#elif (N==44851)
#define SPECIALMUL 0
#define SPECIAL -3
#define MOD_MULSPEC(k) MOD_MERSENNE(3*(MERSBASE-(k)))
#else
#warning Not a verified N, you are on your own!
#define SPECIALMUL 58
#define SPECIAL 0
#endif // list of interesting N for modulus M61 ends here
inline myuint get_next_inlined(rng_state_t* X) { // forward output
int i;
i=X->counter;
if (i<=(N-1) ){
X->counter++;
return X->V[i];
}else{
X->sumtot = iterate_raw_vec(X->V, X->sumtot);
X->counter=2;
return X->V[1];
}
}
// inline myuint get_next_inlined(rng_state_t* X) { // backward output, slightly faster
// int i;
// i=X->counter;
//
// if ( i!=0 ){
// X->counter--;
// return X->V[i];
// }else{
// X->sumtot = iterate_raw_vec(X->V, X->sumtot);
// X->counter=N-2;
// return X->V[N-1];
// }
// }
inline double get_next_float_inlined(rng_state_t* X){
/* cast to signed int trick suggested by Andrzej Görlich */
int64_t Z=(int64_t)get_next_inlined(X);
double F;
#if defined(__GNUC__) && (__GNUC__ < 5) && (!defined(__ICC)) && defined(__x86_64__) && defined(__SSE2_MATH__) && defined(USE_INLINE_ASM)
#warning Using the inline assembler
/* using SSE inline assemly to zero the xmm register, just before int64 -> double conversion,
not really necessary in GCC-5 or better, but huge penalty on earlier compilers
*/
__asm__ __volatile__("pxor %0, %0; "
:"=x"(F)
);
#endif
F=Z;
return F*INV_MERSBASE;
}
#ifndef __MIXMAX_C // c++ can put code into header files, why cant we? (with the inline declaration, should be safe from duplicate-symbol error)
#define get_next(X) get_next_inlined(X)
#define get_next_float(X) get_next_float_inlined(X) // get_next_float_packbits(X) //
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
inline double convert1double(uint64_t u){
const double one = 1;
const uint64_t onemask = *(uint64_t*)&one;
uint64_t tmp = (u>>9) | onemask; // must not have bits higher than 52 !
double d = *(double*)&tmp;
return d-1.0;
}
inline double get_next_float_packbits(rng_state_t* X){
uint64_t Z=get_next_inlined(X); // must not have bits higher than 52 !
return convert1double(Z);
}
#pragma GCC diagnostic pop
#endif // __MIXMAX_C
// ERROR CODES - exit() is called with these
#define ARRAY_INDEX_OUT_OF_BOUNDS 0xFF01
#define SEED_WAS_ZERO 0xFF02
#define ERROR_READING_STATE_FILE 0xFF03
#define ERROR_READING_STATE_COUNTER 0xFF04
#define ERROR_READING_STATE_CHECKSUM 0xFF05
#ifdef __cplusplus
}
#endif
//#define HOOKUP_GSL 1
#ifdef HOOKUP_GSL // if you need to use mixmax through GSL, pass -DHOOKUP_GSL=1 to the compiler
#ifndef __MIXMAX_C
#include <gsl/gsl_rng.h>
unsigned long gsl_get_next(void *vstate);
double gsl_get_next_float(void *vstate);
void seed_for_gsl(void *vstate, unsigned long seed);
static const gsl_rng_type mixmax_type =
{"MIXMAX", /* name */
MERSBASE, /* RAND_MAX */
1, /* RAND_MIN */
sizeof (rng_state_t),
&seed_for_gsl,
&gsl_get_next,
&gsl_get_next_float
};
unsigned long gsl_get_next(void *vstate) {
rng_state_t* X= (rng_state_t*)vstate;
return (unsigned long)get_next(X);
}
double gsl_get_next_float(void *vstate) {
rng_state_t* X= (rng_state_t*)vstate;
return ( (double)get_next(X)) * INV_MERSBASE;
}
void seed_for_gsl(void *vstate, unsigned long seed){
rng_state_t* X= (rng_state_t*)vstate;
seed_spbox(X,(myuint)seed);
}
const gsl_rng_type *gsl_rng_mixmax = &mixmax_type;
#endif // HOOKUP_GSL
#endif // not inside __MIXMAX_C
#endif // closing MIXMAX_H_
| {
"alphanum_fraction": 0.6719636776,
"avg_line_length": 32.0894039735,
"ext": "h",
"hexsha": "8669c377f29ba438f9c85d1a60007d215adf75fe",
"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": "8f9e7af78f010f44fda81a4ab064e32421a205f9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ruicamposcolabpt/MontyCarlo",
"max_forks_repo_path": "MontyCarlo/external/mixmax_release_200final/mixmax.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9",
"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": "ruicamposcolabpt/MontyCarlo",
"max_issues_repo_path": "MontyCarlo/external/mixmax_release_200final/mixmax.h",
"max_line_length": 164,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ruicamposcolabpt/MontyCarlo",
"max_stars_repo_path": "MontyCarlo/external/mixmax_release_200final/mixmax.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2755,
"size": 9691
} |
/* poly/solve_quadratic.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.
*/
/* solve_quadratic.c - finds the real roots of a x^2 + b x + c = 0 */
#include <config.h>
#include <math.h>
#include <gsl/gsl_poly.h>
int
gsl_poly_solve_quadratic (double a, double b, double c,
double *x0, double *x1)
{
double disc = b * b - 4 * a * c;
if (a == 0) /* Handle linear case */
{
if (b == 0)
{
return 0;
}
else
{
*x0 = -c / b;
return 1;
};
}
if (disc > 0)
{
if (b == 0)
{
double r = fabs (0.5 * sqrt (disc) / a);
*x0 = -r;
*x1 = r;
}
else
{
double sgnb = (b > 0 ? 1 : -1);
double temp = -0.5 * (b + sgnb * sqrt (disc));
double r1 = temp / a ;
double r2 = c / temp ;
if (r1 < r2)
{
*x0 = r1 ;
*x1 = r2 ;
}
else
{
*x0 = r2 ;
*x1 = r1 ;
}
}
return 2;
}
else if (disc == 0)
{
*x0 = -0.5 * b / a ;
*x1 = -0.5 * b / a ;
return 2 ;
}
else
{
return 0;
}
}
| {
"alphanum_fraction": 0.4982508746,
"avg_line_length": 23.2674418605,
"ext": "c",
"hexsha": "8af69dbe6baa1476654e95138a9a000b2c82efc8",
"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/poly/solve_quadratic.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/poly/solve_quadratic.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/poly/solve_quadratic.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": 589,
"size": 2001
} |
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#include "su2_matrix.c"
#ifndef gauge_config
#include "config.h"
#define gauge_config 1
#define sq(x) ((x)*(x))
#define cb(x) ((x)*(x)*(x))
#endif
int acc, tot; // acceptance rate
#define FORWARD 1 //true
#define BACKWARD 0 //false
// Access pattern methods --------------------------------------------------
// index of link site=(t,x,y,z) in direction dir
int index(const int* site, int dir){
return dir+site[0]*4+site[1]*N*4+site[2]*N*N*4+site[3]*N*N*N*4;
}
// shift site array by one to direction dir
void shift(int* site, int dir, int forward){
if(forward == 1){
site[dir] = (site[dir]+1)%N;
}else{
site[dir] = (site[dir]-1+N)%N;
}
}
// end of access pattern methods -------------------------------------------
// Plaquette methods -------------------------------------------------------
// plaquette operator at site (t,x,y,z) in plane (mu,nu)
// normally mu>nu
double plaquette(const su2_matrix* links, int mu, int nu, int* site){
su2_matrix A,B,C,D;
A = links[index(site,mu)];
shift(site,mu,FORWARD);
B = links[index(site,nu)];
shift(site,mu,BACKWARD);
shift(site,nu,FORWARD);
C = su2_inv(links[index(site,mu)]);
shift(site,nu,BACKWARD); // restore site position
D = su2_inv(links[index(site,nu)]);
A = su2_mul(A,B);
A = su2_mul(A,C);
A = su2_mul(A,D);
return su2_trace(A)/2.0;
}
double plaquette_mean(const su2_matrix* links, int mu, int nu){
double mean = 0;
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
for(int t=0;t<N;t++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
mean += plaquette(links,mu,nu,site);
}
}
}
}
return mean / (N*N*N*N);
}
// end of plaquette methods ------------------------------------------------
// Metropolis update --------------------------------------------------------
void do_hb_update(su2_matrix* links, const gsl_rng* r, const su2_matrix* rands, int* site, int dir);
double action(su2_matrix* links, int* site, int dir);
// the big loop
void hb_update(su2_matrix* links, const gsl_rng* r, const su2_matrix* rands){
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
for(int t=0;t<N;t++){
for(int dir=0;dir<4;dir++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
do_hb_update(links,r,rands,site,dir);
}
}
}
}
}
}
// update
void do_hb_update(su2_matrix* links, const gsl_rng* r, const su2_matrix* rands, int* site, int dir){
if(verbose) {printf("Updating {%d, %d, %d, %d} direction %d",site[0],site[1],site[2],site[3],dir);getchar();}
double dS,action_old;
su2_matrix link_old;
for(int times=0; times<Nk; times++){
action_old = action(links,site,dir);
link_old = links[index(site,dir)];
links[index(site,dir)]=su2_mul(links[index(site,dir)],rands[gsl_rng_uniform_int(r, 50)]);
dS = action(links,site,dir)-action_old;
if(verbose) {printf("Old action = %f, ",action_old); su2_print(link_old); getchar();}
if(verbose) {printf("New action = %f, ",action_old+dS); su2_print(links[index(site,dir)]); getchar();}
acc++;tot++;
if(dS>0){
if(exp(-dS)<gsl_rng_uniform(r)){
acc--;
links[index(site,dir)]=link_old; // revert update
if(verbose) {printf("Reverted"); getchar();}
}
}
}
}
// calculating the action
// for each direction we need to find plaquette at 2 sites in each of the 3 planes
// mu > nu
double action(su2_matrix* links, int* site, int dir){
int mu,nu;
double result=0;
for(int k=0; k<4; k++){
if(k==dir) continue; // loop over planes
if(k>dir){mu=k; nu=dir;} // mu=larger number
if(k<dir){mu=dir; nu=k;}
result += plaquette(links, mu,nu,site);
shift(site,k,BACKWARD); // shift to the perpendicular direction backwards
result += plaquette(links, mu,nu,site);
shift(site,k,FORWARD); // shift it back
}
return -beta*result;
}
// end of heat bath update -------------------------------------------------
// Wilson loop -------------------------------------------------------------
double wloop(int r, int t, int mu,const su2_matrix* links, int* site){
su2_matrix A[(r+t)*2];
// bottom side
for(int i=0;i<t;i++){
A[i]=links[index(site,0)];
shift(site,0,FORWARD);
}
// right side
for(int i=0;i<r;i++){
A[t+i]=links[index(site,mu)];
shift(site,mu,FORWARD);
}
// top side
for(int i=0;i<t;i++){
shift(site,0,BACKWARD);
A[t+r+i]=su2_inv(links[index(site,0)]);
}
// left side
for(int i=0;i<r;i++){
shift(site,mu,BACKWARD);
A[t+r+t+i]=su2_inv(links[index(site,mu)]);
}
// multiply
for(int i=1;i<2*(r+t);i++){
A[0]=su2_mul(A[0],A[i]);
}
return su2_trace(A[0])/2.0;
}
double wloop_mean(int wR, int wT, const su2_matrix* links){
double mean = 0;
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
for(int t=0;t<N;t++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
for(int mu=1;mu<4;mu++){
mean += wloop(wR,wT,mu,links,site);
}
}
}
}
}
return mean/ (3*N*N*N*N); // 3 directions & N^3 sites
}
// end of Wilson loop ------------------------------------------------------
| {
"alphanum_fraction": 0.5515501081,
"avg_line_length": 26.2938388626,
"ext": "c",
"hexsha": "da53334449c4e6417c2d5b61772bbc49eab82b2b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "uchuutamashi/lqcd",
"max_forks_repo_path": "su2/su2_utils.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "uchuutamashi/lqcd",
"max_issues_repo_path": "su2/su2_utils.c",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "uchuutamashi/lqcd",
"max_stars_repo_path": "su2/su2_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1696,
"size": 5548
} |
/**
*
* @file qwrapper_dpotrf.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:56 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_dlauum(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int n, int nb,
double *A, int lda)
{
DAG_CORE_LAUUM;
QUARK_Insert_Task(quark, CORE_dlauum_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &n, VALUE,
sizeof(double)*nb*nb, A, INOUT,
sizeof(int), &lda, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlauum_quark = PCORE_dlauum_quark
#define CORE_dlauum_quark PCORE_dlauum_quark
#endif
void CORE_dlauum_quark(Quark *quark)
{
PLASMA_enum uplo;
int N;
double *A;
int LDA;
quark_unpack_args_4(quark, uplo, N, A, LDA);
LAPACKE_dlauum_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, A, LDA);
}
| {
"alphanum_fraction": 0.5427380125,
"avg_line_length": 27.1509433962,
"ext": "c",
"hexsha": "ab122805fa8c2a0fd9cc5c3462134fb6df19549e",
"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_dlauum.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_dlauum.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlauum.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 405,
"size": 1439
} |
#include <gsl/gsl_complex.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_halfcomplex.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_statistics_float.h>
#include <stdio.h>
int vector_float_convolve(int cs, const float* c, int as, const float* a, int rs, float* r)
{
int h = cs / 2;
int li, ri;
int i,j;
for (i = 0; i < cs; i++) {
li = i - h;
ri = i + h;
r[i] = 0;
for (j = (li >= 0 ? li : 0); j < (ri < as ? ri : (as - 1)); j++) {
r[i] += a[j]*c[j+h+1];
}
}
return 0;
}
int vector_double_convolve(int cs, const double* c, int as, const double* a, int rs, double* r)
{
int h = cs / 2;
int li, ri;
int i,j;
for (i = 0; i < cs; i++) {
li = i - h;
ri = i + h;
r[i] = 0;
for (j = (li >= 0 ? li : 0); j < (ri < as ? ri : (as - 1)); j++) {
r[i] += a[j]*c[j+h+1];
}
}
return 0;
}
int vector_complex_convolve(int cs, const gsl_complex* c, int as, const gsl_complex* a, int rs, gsl_complex* r)
{
int h = cs / 2;
int li, ri;
int i,j;
for (i = 0; i < cs; i++) {
li = i - h;
ri = i + h;
r[i].dat[0] = 0;
r[i].dat[1] = 0;
for (j = (li >= 0 ? li : 0); j < (ri < as ? ri : (as - 1)); j++) {
r[i].dat[0] += a[j].dat[0]*c[j+h+1].dat[0]-a[j].dat[1]*c[j+h+1].dat[1];
r[i].dat[1] += a[j].dat[0]*c[j+h+1].dat[1]+a[j].dat[1]*c[j+h+1].dat[0];
}
}
return 0;
}
int filter_double(int ls, const double* l, int ks, const double* k, int vs, const double* v, int rs, double* r)
{
if (ls > vs || ks > vs) return 2000; // BAD_SIZE
int i,j;
double L = l[0];
double K = k[0];
int N = ls - 1;
int M = ks - 1;
for (i = 0; i < vs; i++) {
r[i] = 0;
for (j = 0; j < N; j++) {
if (i - j > 0) r[i] -= (l[j+1])*v[i-j];
}
for (j = 0; j < M; j++) {
if (i - j > 0) r[i] += (k[j+1])*r[i-j];
}
}
return 0;
}
int filter_float(int ls, const float* l, int ks, const float* k, int vs, const float* v, int rs, float* r)
{
if (ls > vs || ks > vs) return 2000; // BAD_SIZE
int i,j;
float L = l[0];
float K = k[0];
int N = ls - 1;
int M = ks - 1;
for (i = 0; i < vs; i++) {
r[i] = 0;
for (j = 0; j < N; j++) {
if (i - j > 0) r[i] -= (l[j+1])*v[i-j];
}
for (j = 0; j < M; j++) {
if (i - j > 0) r[i] += (k[j+1])*r[i-j];
}
}
return 0;
}
int hilbert(int rs, gsl_complex* r)
{
int s = rs;
gsl_fft_complex_wavetable * wavetable = gsl_fft_complex_wavetable_alloc (s);
gsl_fft_complex_workspace * workspace = gsl_fft_complex_workspace_alloc (s);
// forward fourier transform
gsl_fft_complex_forward ((double*)r, 1, s, wavetable, workspace);
// zero negative coefficients and double positive
int i;
int m = s/2;
for (i = 1; i < s; i++) {
if (i <= m) {
r[i].dat[0] *= 2;
r[i].dat[1] *= 2;
}
else if (s % 2 == 0 && i == m+1) {
}
else {
r[i].dat[0] = 0;
r[i].dat[1] = 0;
}
}
// inverse fourier transform
gsl_fft_complex_inverse ((double*)r, 1, s, wavetable, workspace);
gsl_fft_complex_wavetable_free (wavetable);
gsl_fft_complex_workspace_free (workspace);
return 0;
}
int pwelch(int w, int vs, const gsl_complex* v, int rs, double* r)
{
if (w > vs) return 2000; // BAD_SIZE
int i,j;
int fs = w;
int num_windows = vs / fs; // ignore end
double s[fs];
for (i = 0; i < fs; i++) s[i] = 0;
gsl_fft_complex_wavetable * wavetable = gsl_fft_complex_wavetable_alloc (fs);
gsl_fft_complex_workspace * workspace = gsl_fft_complex_workspace_alloc (fs);
gsl_complex* f = malloc(sizeof(gsl_complex)*fs);
gsl_vector_view F = gsl_vector_view_array((double*)f, 2*fs);
gsl_vector_view X;
for (i = 0; i < num_windows; i++) {
X = gsl_vector_view_array((double*)(&v[i*fs]), 2*fs); // v is gsl_complex*
gsl_blas_dcopy(&X.vector,&F.vector);
gsl_fft_complex_forward ((double*)f, 1, fs, wavetable, workspace);
for (j = 0; j < fs; j++) s[j] += f[j].dat[0]*f[j].dat[0] + f[j].dat[1]*f[j].dat[1];
}
for (j = 0; j < rs; j++) {
if (j == 0) r[j] = s[j];
else if (j == (rs-1)) r[j] = s[j];
else r[j] = s[j] + s[fs-j+1];
r[j] /= num_windows;
r[j] = sqrt(r[j]);
}
gsl_fft_complex_wavetable_free (wavetable);
gsl_fft_complex_workspace_free (workspace);
free(f);
return 0;
}
int hamming_double(int rs, double* r)
{
int i;
for (i = 0; i < rs; i++) r[i] = 0.54 - 0.46 * cos(2*M_PI*i/rs);
return 0;
}
int hamming_float(int rs, float* r)
{
int i;
for (i = 0; i < rs; i++) r[i] = 0.54 - 0.46 * cos(2*M_PI*i/rs);
return 0;
}
int real_poly_complex_eval(int cs, const double* c, int zs, const gsl_complex* z, int rs, gsl_complex* r)
{
int i;
for (i = 0; i < zs; i++)
r[i] = gsl_poly_complex_eval(c,cs,z[i]);
return 0;
}
int complex_power_double(int cs, const gsl_complex* c, int rs, double* r)
{
if (rs != cs) return 2000; // BAD_SIZE
int i;
for (i = 0; i < cs; i++)
r[i] = c[i].dat[0]*c[i].dat[0] + c[i].dat[1]*c[i].dat[1];
return 0;
}
int complex_power_float(int cs, const gsl_complex* c, int rs, float* r)
{
if (rs != cs) return 2000; // BAD_SIZE
int i;
for (i = 0; i < cs; i++)
r[i] = c[i].dat[0]*c[i].dat[0] + c[i].dat[1]*c[i].dat[1];
return 0;
}
int downsample_double(int n, int xs, const double* x, int rs, double* r)
{
if (rs != xs/n) return 2000; // BAD_SIZE
int i;
for (i = 0; i < rs; i++)
r[i] = x[i*n];
return 0;
}
int downsample_float(int n, int xs, const float* x, int rs, float* r)
{
if (rs != xs/n) return 2000; // BAD_SIZE
int i;
for (i = 0; i < rs; i++)
r[i] = x[i*n];
return 0;
}
int vector_diff_double(int xs, const double* x, int rs, double* r)
{
if (rs != xs - 1) return 2000; // BAD_SIZE
int i;
for (i = 0; i < rs; i++)
r[i] = x[i+1] - x[i];
return 0;
}
int vector_diff_float(int xs, const float* x, int rs, float* r)
{
if (rs != xs - 1) return 2000; // BAD_SIZE
int i;
for (i = 0; i < rs; i++)
r[i] = x[i+1] - x[i];
return 0;
}
int unwrap_double(int xs, const double* x, int rs, double* r)
{
if (rs != xs) return 2000; // BAD_SIZE
int i;
r[0] = x[0];
double c = 0;
int tmp;
for (i = 1; i < rs; i++) {
tmp = x[i-1] - x[i];
if (tmp > M_PI) {
r[i] = 2*M_PI;
}
else if (tmp < (-M_PI)) {
r[i] = -2*M_PI;
}
else {
r[i] = 0;
}
c += r[i];
r[i] = c + x[i];
}
return 0;
}
int unwrap_float(int xs, const float* x, int rs, float* r)
{
if (rs != xs) return 2000; // BAD_SIZE
int i;
r[0] = x[0];
double c = 0;
int tmp;
for (i = 1; i < rs; i++) {
tmp = x[i-1] - x[i];
if (tmp > M_PI) {
r[i] = 2*M_PI;
}
else if (tmp < (-M_PI)) {
r[i] = -2*M_PI;
}
else {
r[i] = 0;
}
c += r[i];
r[i] = c + x[i];
}
return 0;
}
int cross_covariance_double(int max_lag,
double* sx,
double* sy,
int xs, const double* x,
int ys, const double* y,
int rs, double* r)
{
if (xs != ys) return 2000; // BAD_SIZE
if (rs != 2*max_lag) return 2000; // BAD_SIZE
double mx = gsl_stats_mean(x,1,xs);
double my = gsl_stats_mean(y,1,ys);
*sx = gsl_stats_sd(x,1,xs);
*sy = gsl_stats_sd(y,1,ys);
int delay;
int i, j;
double sxy;
for (delay=-max_lag; delay < max_lag; delay++) {
sxy = 0;
for (i=0;i<xs;i++) {
j = i+delay;
if (j < 0 || j >= xs) sxy += (x[i]-mx)*(-my);
else sxy += (x[i]-mx)*(y[j]-my);
/* or should it be:
if (j < 0 || j >= xs) continue;
else sxy += (x[i]-mx)*(y[j]-my);
*/
}
r[delay+max_lag] = sxy/xs;
}
return 0;
}
int cross_covariance_float(int max_lag,
float* sx,
float* sy,
int xs, const float* x,
int ys, const float* y,
int rs, double* r)
{
if (xs != ys) return 2000; // BAD_SIZE
if (rs != 2*max_lag) return 2000; // BAD_SIZE
float mx = gsl_stats_float_mean(x,1,xs);
float my = gsl_stats_float_mean(y,1,ys);
*sx = gsl_stats_float_sd(x,1,xs);
*sy = gsl_stats_float_sd(y,1,ys);
int delay;
int i, j;
float sxy;
for (delay=-max_lag; delay < max_lag; delay++) {
sxy = 0;
for (i=0;i<xs;i++) {
j = i+delay;
if (j < 0 || j >= xs) sxy += (x[i]-mx)*(-my);
else sxy += (x[i]-mx)*(y[j]-my);
/* or should it be:
if (j < 0 || j >= xs) continue;
else sxy += (x[i]-mx)*(y[j]-my);
*/
}
r[delay+max_lag] = sxy/xs;
}
return 0;
}
int cum_sum_double(int xs, const double* x, int rs, double* r)
{
int i;
r[0] = x[0];
for (i=1;i<xs;i++) {
r[i] = r[i-1]+x[i];
}
return 0;
}
int cum_sum_float(int xs, const float* x, int rs, float* r)
{
int i;
r[0] = x[0];
for (i=1;i<xs;i++) {
r[i] = r[i-1]+x[i];
}
return 0;
}
| {
"alphanum_fraction": 0.5170098478,
"avg_line_length": 19.6395604396,
"ext": "c",
"hexsha": "9e67266bc4774a649c7d47afd2b915c77282cb71",
"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": "94bb05e77053a9284be98c281e0a21544437072b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "amcphail/hsignal",
"max_forks_repo_path": "lib/Numeric/Signal/signal-aux.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b",
"max_issues_repo_issues_event_max_datetime": "2015-10-30T23:38:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-30T11:41:03.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "amcphail/hsignal",
"max_issues_repo_path": "lib/Numeric/Signal/signal-aux.c",
"max_line_length": 111,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "amcphail/hsignal",
"max_stars_repo_path": "lib/Numeric/Signal/signal-aux.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-28T23:12:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-27T06:50:42.000Z",
"num_tokens": 3461,
"size": 8936
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C code headers for the implementation of the Fourier domain response for LISA-like detectors
*
*/
#ifndef _LISAFDRESPONSE_H
#define _LISAFDRESPONSE_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#include "waveform.h"
#include "EOBNRv2HMROMstruct.h"
#include "LISAgeometry.h"
#if defined(__cplusplus)
extern "C" {
#elif 0
} /* so that editors will match preceding brace */
#endif
/**************************************************/
/**************** Prototypes **********************/
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle - here simplified version for just the y_21 observable */
int LISASimFDResponse21(
LISAconstellation *variant, /* Provides specifics on the variant of LISA */
struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input/Output: list of modes in Frequency-domain amplitude and phase form as produced by the ROM, and output after FD response processing */
const double inclination, /* Inclination of the source */
const double lambda, /* First angle for the position in the sky */
const double beta, /* Second angle for the position in the sky */
const double psi); /* Polarization angle */
//WARNING: tRef is ignored for now in the response - i.e. set to 0
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle */
int LISASimFDResponsey12(
LISAconstellation *variant, /* Provides specifics on the variant of LISA */
struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */
struct tagListmodesCAmpPhaseFrequencySeries **listy12, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the y12 observable */
const double torb, /* Reference orbital time - tf as read from the hlm gives t-tinj, this arg allows to pass tinj to the response */
const double lambda, /* First angle for the position in the sky */
const double beta, /* Second angle for the position in the sky */
const double inclination, /* Inclination of the source */
const double psi, /* Polarization angle */
const int tagfrozenLISA, /* Tag to treat LISA as frozen at its torb configuration */
const ResponseApproxtag responseapprox); /* Tag to select possible low-f approximation level in FD response */
//WARNING: tRef is ignored for now in the response - i.e. set to 0
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle */
int LISASimFDResponseTDI3Chan(
int tagtRefatLISA, /* 0 to measure Tref from SSB arrival, 1 at LISA guiding center */
LISAconstellation *variant, /* Provides specifics on the variant of LISA */
struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */
struct tagListmodesCAmpPhaseFrequencySeries **listTDI1, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 1 */
struct tagListmodesCAmpPhaseFrequencySeries **listTDI2, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 2 */
struct tagListmodesCAmpPhaseFrequencySeries **listTDI3, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 3 */
const double torb, /* Reference orbital time - tf as read from the hlm gives t-tinj, this arg allows to pass tinj to the response */
const double lambda, /* First angle for the position in the sky */
const double beta, /* Second angle for the position in the sky */
const double inclination, /* Inclination of the source */
const double psi, /* Polarization angle */
const double m1, /* m1 in solar masses - used for resampling */
const double m2, /* m2 in solar masses - used for resampling */
const double maxf, /* Maximal frequency to consider - used to ignore hard-to-resolve response at f>1Hz - NOTE: for now, no recomputation of the boundary, so when not resampling can lose a bit of support between the last frequency point covered and maxf */
const TDItag tditag, /* Selector for the set of TDI observables */
const int tagfrozenLISA, /* Tag to treat LISA as frozen at its torb configuration */
const ResponseApproxtag responseapprox); /* Tag to select possible low-f approximation level in FD response */
// int LISASimFDResponseTDI1Chan(
// struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */
// struct tagListmodesCAmpPhaseFrequencySeries **listTDI, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 1 */
// const double tRef, /* Time at coalescence */
// const double lambda, /* First angle for the position in the sky */
// const double beta, /* Second angle for the position in the sky */
// const double inclination, /* Inclination of the source */
// const double psi, /* Polarization angle */
// const double maxf, /* Maximal frequency to consider - used to ignore hard-to-resolve response at f>1Hz - NOTE: for now, no recomputation of the boundary, so when not resampling can lose a bit of support between the last frequency point covered and maxf */
// const TDItag tditag); /* Selector for the set of TDI observables */
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _LISAFDRESPONSE_H */
| {
"alphanum_fraction": 0.6197903014,
"avg_line_length": 66.9298245614,
"ext": "h",
"hexsha": "0a3a2e84833ed4f67e76dcccd676499f599b4d98",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "LISAsim/LISAFDresponse.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": "LISAsim/LISAFDresponse.h",
"max_line_length": 301,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "LISAsim/LISAFDresponse.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 1556,
"size": 7630
} |
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "inout_aper.h"
#include "aper_conf.h"
#include <gsl/gsl_multifit_nlin.h>
#include "trfit_utils.h"
#define AXE_IMAGE_PATH "AXE_IMAGE_PATH"
#define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH"
#define AXE_CONFIG_PATH "AXE_CONFIG_PATH"
int
main(int argc, char *argv[])
{
char *opt;
char grism_image[MAXCHAR];
char grism_image_path[MAXCHAR];
char conf_file[MAXCHAR];
char conf_file_path[MAXCHAR];
char aper_file[MAXCHAR];
char aper_file_path[MAXCHAR];
int i, j;
int num;
object **oblist;
observation *obs;
aperture_conf *conf;
double exptime;
gsl_vector *fit_result;
if ((argc < 1) || (opt = get_online_option("help", argc, argv))) {
fprintf(stdout,
"aXe_TFIT Version %s:\n"
"\n", RELEASE);
exit(1);
}
fprintf(stdout, "aXe_TFIT: Starting...\n");
// Get the data file name
strcpy(grism_image, argv[1]);
// Get the configuration file name
strcpy(conf_file, argv[2]);
build_path(AXE_CONFIG_PATH, conf_file, conf_file_path);
// Read the configuration file
conf = get_aperture_descriptor(conf_file_path);
// Determine where the various extensions are in the FITS file
build_path(AXE_IMAGE_PATH, grism_image, grism_image_path);
get_extension_numbers(grism_image_path, conf, conf->optkey1, conf->optval1);
// Get or set up the name of the output Aperture File
if ((opt = get_online_option ("in_AF", argc, argv)))
{
/* get it */
strcpy (aper_file, opt);
strcpy (aper_file_path, opt);
}
else {
// Build aperture file name
replace_file_extension (grism_image, aper_file, ".fits",
".OAF", conf->science_numext);
build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);
}
fprintf(stdout,
"aXe_TFIT: Input configuration file name: %s\n",
conf_file_path);
fprintf(stdout,
"aXe_TFIT: Input data file name: %s\n",
grism_image_path);
fprintf(stdout,
"aXe_TFIT: SCI extension number: %d\n",
conf->science_numext);
fprintf(stdout,
"aXe_TFIT: ERR extension number: %d\n",
conf->errors_numext);
fprintf(stdout,
"aXe_TFIT: DQ extension number: %d\n",
conf->dq_numext);
fprintf(stdout,
"aXe_TFIT: DQ mask: %d\n",
conf->dqmask);
fprintf(stdout,
"aXe_TFIT: Input aperture file name: %s\n",
aper_file_path);
fprintf(stdout, "\n\n");
/* Loading the observation data */
fprintf(stdout, "aXe_TFIT: ");
//
// try to get the descriptor 'exptime' from the 'sci'-extension
//
exptime = (double)get_float_from_keyword(grism_image_path,
conf->science_numext,
conf->exptimekey);
if (isnan(exptime))
exptime = (double)get_float_from_keyword(grism_image_path, 1,
conf->exptimekey);
if (isnan(exptime))
exptime = 1.0;
// Load an image from AXE_DATA_PATH
obs = load_image_t(grism_image_path, conf->science_numext,
conf->errors_numext, conf->dq_numext,
conf->dqmask, exptime, conf->rdnoise);
// Loading the object list
fprintf(stdout, "aXe_TFIT: Loading object list...");
oblist = file_to_object_list_seq(aper_file_path, obs);
fprintf(stdout, "%d objects loaded.\n", object_list_size(oblist));
// initialize the counter
i = 0;
// check whether there are apertures
if (oblist != NULL) {
// go over all apertures
while (oblist[i] != NULL) {
// print the current aperture ID
fprintf(stdout, "aXe_TFIT: Fitting object ID:%d", oblist[i]->ID);
// go over all beams
for (j = 0; j < oblist[i]->nbeams; j++) {
// skip beam if ignore flag for thisbeam is set
if (oblist[i]->beams[j].ignore !=0 || oblist[i]->beams[j].ID != 0)
{
/*fprintf(stdout,", %c ( Ignored )",
BEAM(oblist[i]->beams[j].ID));*/
continue;
}
// print the current beam ID
/*fprintf(stdout, ", %c (Fitted)", BEAM(oblist[i]->beams[j].ID));*/
// fit the trace of the beam, modify the
// beam definition with the new values
// oblist[i]->beams[j].refpoint.y = fit_beamtrace(conf, obs, j, oblist[i]->beams[j]);
fit_result = fit_beamtrace(conf, obs, j, oblist[i]->beams[j]);
oblist[i]->beams[j].refpoint.x = gsl_vector_get(fit_result,0);
oblist[i]->beams[j].refpoint.y = gsl_vector_get(fit_result,1);
oblist[i]->beams[j].width = gsl_vector_get(fit_result,4);
gsl_vector_free(fit_result);
}
// give feedback on the progress,
// enhance the counter
fprintf(stdout, " Done.\n");
i++;
}
}
// write the modified beam definitions
// to an OAF file
fprintf (stdout, "aXe_TFIT: Writing new aperture file...");fflush(stdout);
num = object_list_to_file (oblist, aper_file_path, 1);
fprintf (stdout, "%d beams written.\n", num);
// release the memory
free_observation(obs);
if (oblist != NULL){
free_oblist(oblist);}
// print a last status message and exit
fprintf(stdout, "aXe_TFIT: Done...\n");
exit(0);
}
| {
"alphanum_fraction": 0.6399766219,
"avg_line_length": 26.8743455497,
"ext": "c",
"hexsha": "8c0d1a0060b82e00e2ba91ba6c0ad27740e71de1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/aXe_TFIT.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/aXe_TFIT.c",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/aXe_TFIT.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1473,
"size": 5133
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "compearth.h"
#ifdef COMPEARTH_USE_MKL
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#endif
#include <mkl_lapacke.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <lapacke.h>
#endif
/*!
* @brief Convert from moment tnesor to scalar seismic moment.
*
* @param[in] nm Number of moment tensors.
* @param[in] im0 =1 for Silver and Jordan (1982) formula. \n
* =2 for GCMT formula. \n
* =3 for old `Caltech Way.'
* @param[in] M [nm x 6] array of moment tensors packed
* {M11, M22, M33, M12, M13, M23} with leading
* dimension 6. The Mij element should be of units
* of Newton-meters (although it should not affect
* the function here).
*
* @param[out] M0 Scalar moments with units of Newton-meters. This
* is an array of dimension [nm].
*
* @result 0 indicates success.
*
* @author Carl Tape and translated to C by Ben Baker
*
* @copyright MIT
*
*/
int compearth_CMT2m0(const int nm, const int im0,
const double *__restrict__ M,
double *__restrict__ M0)
{
double Mt9[9], lams[3], work[100], M11, M22, M33, M12, M13, M23;
const double sqrt2i = 1.0/sqrt(2.0);
const int lwork = 100;
int i, ierr, info;
ierr = 0;
if (im0 == 2 || im0 == 3)
{
for (i=0; i<nm; i++)
{
// Fill upper-triangle; column 1
Mt9[0] = M[6*i];
Mt9[1] = 0.0;
Mt9[2] = 0.0;
// column 2
Mt9[3] = M[6*i+3];
Mt9[4] = M[6*i+1];
Mt9[5] = 0.0;
// column 3
Mt9[6] = M[6*i+4];
Mt9[7] = M[6*i+5];
Mt9[8] = M[6*i+2];
// get eigenvalues in ascending order
info = LAPACKE_dsyev_work(LAPACK_COL_MAJOR, 'N', 'U', 3,
Mt9, 3, lams, work, lwork);
if (info != 0)
{
fprintf(stderr, "%s: Error computing eigenvalues\n", __func__);
return -1;
}
// GCMT double couple formulation
if (im0 == 2)
{
M0[i] = 0.5*(fabs(lams[0]) + fabs(lams[2]));
}
else
{
M0[i] = fabs(lams[2]);
if (fabs(lams[0]) > fabs(lams[2])){M0[i] = fabs(lams[0]);}
}
}
}
// Silver and Jordan
else if (im0 == 1)
{
for (i=0; i<nm; i++)
{
M11 = M[6*i];
M22 = M[6*i+1];
M33 = M[6*i+2];
M12 = M[6*i+3];
M13 = M[6*i+4];
M23 = M[6*i+5];
M0[i] = sqrt2i*sqrt(( M11*M11 + M22*M22 + M33*M33
+ 2.0*(M12*M12 + M13*M13 + M23*M23)));
}
}
else
{
fprintf(stderr, "%s: Invalid magnitude type %d\n", __func__, im0);
for (i=0; i<nm; i++){M0[i] = 0.0;}
return -1;
}
return ierr;
}
| {
"alphanum_fraction": 0.4703703704,
"avg_line_length": 29.4545454545,
"ext": "c",
"hexsha": "4d0befecfd474c4061d55f5d8724348c3468146b",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z",
"max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "carltape/mtbeach",
"max_forks_repo_path": "c_src/CMT2m0.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "carltape/mtbeach",
"max_issues_repo_path": "c_src/CMT2m0.c",
"max_line_length": 79,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OUCyf/mtbeach",
"max_stars_repo_path": "c_src/CMT2m0.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z",
"num_tokens": 985,
"size": 3240
} |
/*****************
* @file leastsq.h
* @date 4/1/08
* @author Douglas Applegate
*
* @brief Provides a wrapper around the GSL libraries for fitting functions
*****************/
//CVSID $Id: leastsq.h,v 1.1 2008-04-04 01:43:12 mallen Exp $
////////////////////////////////////////////////////
#ifndef LEASTSQ_H
#define LEASTSQ_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
/**
* Function prototype for fitting function and its derivative
* @param double x position at which to evaluate function
* @param const double* parameter values to use in evaluation
*/
typedef double (*FitFunction_t)(double, const double*);
/**
* Provides non-linear fitting functionality
*/
class Leastsq {
public:
/**
* Initializes object with basic fit information
* @param fitFunc function to fit to data
* @param dfitFunc array of fit function derivatives, one for each param
* @param nparams number of parameters that fitFunc and dfitFunc accept
*/
Leastsq(FitFunction_t fitFunc,
FitFunction_t* dfitFunc,
int nparams);
/**
* Default constructor
*/
virtual ~Leastsq();
/**
* Fits function to the given data, starting at initial guess
* @param x x values of data
* @param y y values of data
* @param ndata number of data points
* @param guess initial parameter values for fit
*
* @returns status status code for fit. 1 == fit ran fine
*/
int doFit(const double* x, const double* y, int ndata, double* guess);
/////GETTERS
double numParams() const {return _nparams;};
const double** covarMatrix() const {
return const_cast<const double**>(_covar);
};
double chisq() const {return _chisq;};
const double* parameters() const {
return const_cast<const double*>(_parameters);
};
protected:
/////INSTANCE METHODS
int gslFitFunction(const gsl_vector* x,
void* params,
gsl_vector* result);
int gslDFitFunction(const gsl_vector* x,
void* params,
gsl_matrix* J);
/////Instance Variables
FitFunction_t _fitFunc; ///< Function to fit to data
FitFunction_t* _dfitFunc; ///< Analytical derivative of fitFunc
int _nparams; ///< Number of parameters in fitFunc and dfitFunc
double** _covar; ///< Covariance Matrix
double _chisq; ///< Chisq or residual from fit
double* _parameters; ///< Best fit parameters
const double* _x; ///< x values of data
const double* _y; ///< y values of data
int _ndata; ///< number of data
};
#endif
| {
"alphanum_fraction": 0.6522085157,
"avg_line_length": 23.9333333333,
"ext": "h",
"hexsha": "c31d660915d62537efd277bc0fa984816d0704fb",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-10-12T00:36:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-15T21:19:11.000Z",
"max_forks_repo_head_hexsha": "9693e8562022cc97bf5a96427e22965e1a5e8497",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "deapplegate/wtgpipeline",
"max_forks_repo_path": "sfdir/leastsq.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "9693e8562022cc97bf5a96427e22965e1a5e8497",
"max_issues_repo_issues_event_max_datetime": "2021-07-09T17:05:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-11T00:11:39.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "deapplegate/wtgpipeline",
"max_issues_repo_path": "sfdir/leastsq.h",
"max_line_length": 75,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9693e8562022cc97bf5a96427e22965e1a5e8497",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "deapplegate/wtgpipeline",
"max_stars_repo_path": "sfdir/leastsq.h",
"max_stars_repo_stars_event_max_datetime": "2019-03-15T04:01:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-15T04:01:19.000Z",
"num_tokens": 649,
"size": 2513
} |
/*! @copyright (c) 2017 King Abdullah University of Science and
* Technology (KAUST). All rights reserved.
*
* STARS-H is a software package, provided by King Abdullah
* University of Science and Technology (KAUST)
*
* @file testing/mpi_cauchy.c
* @version 1.3.0
* @author Aleksandr Mikhalev
* @date 2017-11-07
* */
#ifdef MKL
#include <mkl.h>
#else
#include <cblas.h>
#include <lapacke.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <starsh.h>
#include <starsh-cauchy.h>
int main(int argc, char **argv)
{
MPI_Init(&argc, &argv);
int mpi_size, mpi_rank;
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
if(argc < 5)
{
if(mpi_rank == 0)
{
printf("%d arguments provided, but 4 are needed\n", argc-1);
printf("mpi_cauchy N block_size maxrank tol\n");
}
MPI_Finalize();
return 1;
}
int N = atoi(argv[1]), block_size = atoi(argv[2]);
int maxrank = atoi(argv[3]);
double tol = atof(argv[4]);
int onfly = 0;
char dtype = 'd', symm = 'N';
int ndim = 2;
STARSH_int shape[2] = {N, N};
int info;
srand(0);
// Init STARS-H
info = starsh_init();
if(info != 0)
{
MPI_Finalize();
return 1;
}
// Generate data for spatial statistics problem
STARSH_cauchy *data;
STARSH_kernel *kernel;
info = starsh_application((void **)&data, &kernel, N, dtype, STARSH_CAUCHY,
STARSH_CAUCHY_KERNEL1, 0);
if(info != 0)
{
MPI_Finalize();
return 1;
}
// Init problem with given data and kernel and print short info
STARSH_problem *P;
info = starsh_problem_new(&P, ndim, shape, symm, dtype, data, data,
kernel, "Cauchy example");
if(info != 0)
{
MPI_Finalize();
return 1;
}
if(mpi_rank == 0)
starsh_problem_info(P);
// Init plain clusterization and print info
STARSH_cluster *C;
info = starsh_cluster_new_plain(&C, data, N, block_size);
if(info != 0)
{
MPI_Finalize();
return 1;
}
if(mpi_rank == 0)
starsh_cluster_info(C);
// Init tlr division into admissible blocks and print short info
STARSH_blrf *F;
STARSH_blrm *M;
info = starsh_blrf_new_tlr_mpi(&F, P, symm, C, C);
if(info != 0)
{
MPI_Finalize();
return 1;
}
if(mpi_rank == 0)
starsh_blrf_info(F);
// Approximate each admissible block
MPI_Barrier(MPI_COMM_WORLD);
double time1 = MPI_Wtime();
info = starsh_blrm_approximate(&M, F, maxrank, tol, onfly);
if(info != 0)
{
MPI_Finalize();
return 1;
}
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
starsh_blrf_info(F);
starsh_blrm_info(M);
}
if(mpi_rank == 0)
printf("TIME TO APPROXIMATE: %e secs\n", time1);
// Measure approximation error
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime();
double rel_err = starsh_blrm__dfe_mpi(M);
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
printf("TIME TO MEASURE ERROR: %e secs\nRELATIVE ERROR: %e\n",
time1, rel_err);
if(rel_err/tol > 10.)
{
printf("Resulting relative error is too big\n");
MPI_Finalize();
return 1;
}
}
if(rel_err/tol > 10.)
{
MPI_Finalize();
return 1;
}
// Measure time for 10 BLRM matvecs and for 10 BLRM TLR matvecs
double *x, *y, *y_tlr;
int nrhs = 1;
x = malloc(N*nrhs*sizeof(*x));
y = malloc(N*nrhs*sizeof(*y));
y_tlr = malloc(N*nrhs*sizeof(*y_tlr));
if(mpi_rank == 0)
{
int iseed[4] = {0, 0, 0, 1};
LAPACKE_dlarnv_work(3, iseed, N*nrhs, x);
cblas_dscal(N*nrhs, 0.0, y, 1);
cblas_dscal(N*nrhs, 0.0, y_tlr, 1);
}
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime();
for(int i = 0; i < 10; i++)
starsh_blrm__dmml_mpi(M, nrhs, 1.0, x, N, 0.0, y, N);
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
printf("TIME FOR 10 BLRM MATVECS: %e secs\n", time1);
}
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime();
for(int i = 0; i < 10; i++)
starsh_blrm__dmml_mpi_tlr(M, nrhs, 1.0, x, N, 0.0, y_tlr, N);
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
cblas_daxpy(N, -1.0, y, 1, y_tlr, 1);
printf("TIME FOR 10 TLR MATVECS: %e secs\n", time1);
printf("MATVEC DIFF: %e\n", cblas_dnrm2(N, y_tlr, 1)
/cblas_dnrm2(N, y, 1));
}
MPI_Finalize();
return 0;
}
| {
"alphanum_fraction": 0.5682382134,
"avg_line_length": 27.0167597765,
"ext": "c",
"hexsha": "3092d3545312593487eefeddc0adfa9e1c0205cb",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-11-09T10:54:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-09T10:54:18.000Z",
"max_forks_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "wawando/stars-h",
"max_forks_repo_path": "testing/mpi_cauchy.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4",
"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": "wawando/stars-h",
"max_issues_repo_path": "testing/mpi_cauchy.c",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "wawando/stars-h",
"max_stars_repo_path": "testing/mpi_cauchy.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1530,
"size": 4836
} |
#ifndef OPENMC_TALLIES_FILTER_DELAYEDGROUP_H
#define OPENMC_TALLIES_FILTER_DELAYEDGROUP_H
#include <vector>
#include <gsl/gsl>
#include "openmc/tallies/filter.h"
namespace openmc {
//==============================================================================
//! Bins outgoing fission neutrons in their delayed groups.
//!
//! The get_all_bins functionality is not actually used. The bins are manually
//! iterated over in the scoring subroutines.
//==============================================================================
class DelayedGroupFilter : public Filter
{
public:
//----------------------------------------------------------------------------
// Constructors, destructors
~DelayedGroupFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override {return "delayedgroup";}
void from_xml(pugi::xml_node node) override;
void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match)
const override;
void to_statepoint(hid_t filter_group) const override;
std::string text_label(int bin) const override;
//----------------------------------------------------------------------------
// Accessors
const std::vector<int>& groups() const { return groups_; }
void set_groups(gsl::span<int> groups);
private:
//----------------------------------------------------------------------------
// Data members
std::vector<int> groups_;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_DELAYEDGROUP_H
| {
"alphanum_fraction": 0.5181644359,
"avg_line_length": 27.5263157895,
"ext": "h",
"hexsha": "64bdd3398565cf33a29f23459a0ef5632d2fb709",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z",
"max_forks_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mehmeturkmen/openmc",
"max_forks_repo_path": "include/openmc/tallies/filter_delayedgroup.h",
"max_issues_count": 9,
"max_issues_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d",
"max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mehmeturkmen/openmc",
"max_issues_repo_path": "include/openmc/tallies/filter_delayedgroup.h",
"max_line_length": 84,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Hit-Weixg/openmc",
"max_stars_repo_path": "include/openmc/tallies/filter_delayedgroup.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z",
"num_tokens": 291,
"size": 1569
} |
/*
Copyright (C) 2020 David Cornu
for the Convolutional Interactive Artificial
Neural Networks by/for Astrophysicists (CIANNA) Code
(https://github.com/Deyht/CIANNA)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef DEFS_H
#define DEFS_H
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <tgmath.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#ifdef comp_CUDA
#ifdef CUDA
#include <cuda_runtime.h>
#include <cublas_v2.h>
#if defined(GEN_VOLTA) || defined(GEN_AMPERE)
#include <cuda_fp16.h>
#endif
#if defined(GEN_AMPERE)
#include <cuda_bf16.h>
#endif
#include <curand.h>
#include <curand_kernel.h>
#endif
#endif
#ifdef BLAS
#include <cblas.h>
#endif
#ifdef OPEN_MP
#include <omp.h>
#endif
static const double two_pi = 2.0*3.14159265358979323846;
#endif //DEFS_H
| {
"alphanum_fraction": 0.7477203647,
"avg_line_length": 18.5352112676,
"ext": "h",
"hexsha": "169d3ef388323681dba7bf2f3d5866e6046f2129",
"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": "84c2cd94e91af1114aaed1251e36e1a2669e4c82",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Deyht/CIANNA",
"max_forks_repo_path": "src/defs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "84c2cd94e91af1114aaed1251e36e1a2669e4c82",
"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": "Deyht/CIANNA",
"max_issues_repo_path": "src/defs.h",
"max_line_length": 73,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "84c2cd94e91af1114aaed1251e36e1a2669e4c82",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Deyht/CIANNA",
"max_stars_repo_path": "src/defs.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-09T14:12:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-03T14:52:41.000Z",
"num_tokens": 353,
"size": 1316
} |
/*****************************************************************************
*
* Rokko: Integrated Interface for libraries of eigenvalue decomposition
*
* Copyright (C) 2012-2014 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>
*
* 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)
*
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <lapacke.h>
#define N 5
int main() {
int i, j, info;
double w[N];
double a[N][N] = {
5, 4, 3, 2, 1,
4, 4, 3, 2, 1,
3, 3, 3, 2, 1,
2, 2, 2, 2, 1,
1, 1, 1, 1, 1
};
info = LAPACKE_dsyev(LAPACK_ROW_MAJOR, 'V', 'U', N, a[0], N, w);
printf("Eigenvalues of Frank matrix: ");
for (i = 0; i < N; ++i) {
printf(" %6.2f", w[i]);
}
printf("\n");
printf("Eigenvectors of Frank matrix (column by column):\n");
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
printf(" %6.2f", a[i][j]);
}
printf("\n");
}
return 0;
}
| {
"alphanum_fraction": 0.4815837937,
"avg_line_length": 25.2558139535,
"ext": "c",
"hexsha": "82eb6520a32422a3a7780ae823698fd3ff695055",
"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": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "wistaria/rokko",
"max_forks_repo_path": "example/cxx/dense/dsyev.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "wistaria/rokko",
"max_issues_repo_path": "example/cxx/dense/dsyev.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "wistaria/rokko",
"max_stars_repo_path": "example/cxx/dense/dsyev.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 375,
"size": 1086
} |
//------------------------------------------------------------------------------
// Util.h
// Various utility functions and basic types used throughout the library.
//
// File is under the MIT license; see LICENSE for details.
//------------------------------------------------------------------------------
#pragma once
#include <climits> // for type size macros
#include <cstddef> // for std::byte
#include <cstdint> // for sized integer types
#include <new> // for placement new
#include <optional> // for std::optional
#include <string_view> // for std::string_view
#include <utility> // for many random utility functions
#include <variant> // for std::variant
using std::byte;
using std::int16_t;
using std::int32_t;
using std::int64_t;
using std::int8_t;
using std::intptr_t;
using std::nullptr_t;
using std::optional;
using std::ptrdiff_t;
using std::size_t;
using std::string_view;
using std::uint16_t;
using std::uint32_t;
using std::uint64_t;
using std::uint8_t;
using std::uintptr_t;
using namespace std::literals;
#if !defined(ASSERT_ENABLED)
# if !defined(NDEBUG)
# define ASSERT_ENABLED 1
# endif
#endif
#if ASSERT_ENABLED
# if defined(__GNUC__) || defined(__clang__)
# define ASSERT_FUNCTION __PRETTY_FUNCTION__
# elif defined(_MSC_VER)
# define ASSERT_FUNCTION __FUNCSIG__
# elif defined(__SUNPRO_CC)
# define ASSERT_FUNCTION __func__
# else
# define ASSERT_FUNCTION __FUNCTION__
# endif
# define ASSERT(cond) \
do { \
if (!(cond)) \
slang::assert::assertFailed(#cond, __FILE__, __LINE__, ASSERT_FUNCTION); \
} while (false)
#else
# define ASSERT(cond) \
do { \
(void)sizeof(cond); \
} while (false)
#endif
#define THROW_UNREACHABLE \
throw std::logic_error(std::string(__FILE__) + ":" + std::to_string(__LINE__) + ": " + \
"Default case should be unreachable!")
#define __ENUM_ELEMENT(x) x,
#define __ENUM_STRING(x) #x,
#define ENUM(name, elements) \
enum class name { elements(__ENUM_ELEMENT) }; \
inline string_view toString(name e) { \
static const char* strings[] = { elements(__ENUM_STRING) }; \
return strings[static_cast<std::underlying_type_t<name>>(e)]; \
} \
inline std::ostream& operator<<(std::ostream& os, name e) { return os << toString(e); }
#define ENUM_MEMBER(name, elements) \
enum name { elements(__ENUM_ELEMENT) }; \
friend string_view toString(name e) { \
static const char* strings[] = { elements(__ENUM_STRING) }; \
return strings[static_cast<std::underlying_type_t<name>>(e)]; \
}
#include <gsl/gsl>
using gsl::finally;
using gsl::make_span;
using gsl::not_null;
using gsl::span;
// Compiler-specific macros for warnings and suppressions
#ifdef __clang__
# define NO_SANITIZE(warningName) __attribute__((no_sanitize(warningName)))
#else
# define NO_SANITIZE(warningName)
#endif
#include <bitmask.hpp>
using bitmask_lib::bitmask;
#include <nlohmann/json_fwd.hpp>
using json = nlohmann::json;
#define HAS_METHOD_TRAIT(name) \
template<typename, typename T> \
struct has_##name { \
static_assert(always_false<T>::value, \
"Second template parameter needs to be of function type."); \
}; \
template<typename C, typename Ret, typename... Args> \
struct has_##name<C, Ret(Args...)> { \
private: \
template<typename T> \
static constexpr auto check(T*) -> \
typename std::is_same<decltype(std::declval<T>().name(std::declval<Args>()...)), \
Ret>::type; \
template<typename> \
static constexpr std::false_type check(...); \
typedef decltype(check<C>(0)) type; \
\
public: \
static constexpr bool value = type::value; \
}; \
template<typename C, typename Ret, typename... Args> \
static constexpr bool has_##name##_v = has_##name<C, Ret(Args...)>::value
namespace slang {
template<typename T>
struct always_false : std::false_type {};
/// Converts a span of characters into a string_view.
inline string_view to_string_view(span<char> text) {
return string_view(text.data(), (size_t)text.size());
}
inline void hash_combine(size_t&) {
}
/// Hash combining function, based on the function from Boost.
template<typename T, typename... Rest>
inline void hash_combine(size_t& seed, const T& v, Rest... rest) {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
hash_combine(seed, rest...);
}
namespace assert {
class AssertionException : public std::logic_error {
public:
AssertionException(const std::string& message) : std::logic_error(message) {}
};
[[noreturn]] void assertFailed(const char* expr, const char* file, int line, const char* func);
} // namespace assert
} // namespace slang
namespace detail {
template<typename Tuple, size_t Index = std::tuple_size<Tuple>::value - 1>
struct HashValueImpl {
static void apply(size_t& seed, const Tuple& tuple) {
HashValueImpl<Tuple, Index - 1>::apply(seed, tuple);
slang::hash_combine(seed, std::get<Index>(tuple));
}
};
template<typename Tuple>
struct HashValueImpl<Tuple, 0> {
static void apply(size_t& seed, const Tuple& tuple) {
slang::hash_combine(seed, std::get<0>(tuple));
}
};
} // namespace detail
namespace std {
template<typename... TT>
struct hash<std::tuple<TT...>> {
size_t operator()(const std::tuple<TT...>& tt) const {
size_t seed = 0;
::detail::HashValueImpl<std::tuple<TT...>>::apply(seed, tt);
return seed;
}
};
} // namespace std
| {
"alphanum_fraction": 0.4890599676,
"avg_line_length": 37.9692307692,
"ext": "h",
"hexsha": "896aa8e9164c79cb4389ae7233f07211760f45a7",
"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": "e65f5f68029fadd5986ba453f415f00d6259d9c5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jrrk/slang",
"max_forks_repo_path": "include/slang/util/Util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e65f5f68029fadd5986ba453f415f00d6259d9c5",
"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": "jrrk/slang",
"max_issues_repo_path": "include/slang/util/Util.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e65f5f68029fadd5986ba453f415f00d6259d9c5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jrrk/slang",
"max_stars_repo_path": "include/slang/util/Util.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1398,
"size": 7404
} |
#ifndef RECTREE_H
#define RECTREE_H
#include "tree.h"
#include "recedge.h"
#include "weakarg.h"
#include "mpiutils.h"
#include "wargxml.h"
#include <gsl/gsl_randist.h>
#define MAXNODES 100000
using namespace std;
namespace weakarg
{
class Param;
/**
@brief Recombinant tree using Tree class
*/
class RecTree:public Tree
{
friend class RecTreeAux;
protected:
// Variables
std::vector<std::vector<int> > tabSons;///<Contains the branching order for the current local tree
std::vector<std::vector<double> > tabSonsDist;///<Contains the distances for the current local tree
std::vector<int> tabNode;///<Used only in makeLocalTree (made global for speed)
std::vector<int> tabRec;///<Used only in makeLocalTree (made global for speed)
std::vector<int> tabFather;///<Used only in makeLocalTree (made global for speed)
std::vector<double> age;///<Used only in makeLocalTree (made global for speed)
std::vector<int> tabEdge;///<Used only in makeLocalTree (made global for speed)
std::vector<bool> sameLTasPrev;///<Indicates for each site whether the local tree is the same as that of the previous site
unsigned int L;///< Number of sites in the sequences
std::vector<RecEdge *> edge;///< The recombinant edges
// Functions
int randomActiveNode(std::vector<int> nodelist);///<Returns a random node id from a vector of indicators for alive (-1 for not alive at current time)
int getEdgeCoal(std::vector<int> nl,int k,double* time);///<Returns the node the recombinant edge is from and sets the time
int moveClonalFixFrom(std::vector<int> ornodes=std::vector<int>(0));///< Fixes all from times to be in to valid nodes and reinstates **the vector ornodes. returns the number of recedges moved to younger nodes - number moved to older nodes (or -1 if this is not calculated)
void updateEdgeTimes(int e,double reldist);///moves an edge when its node changes by proportion reldist
void scaleEdges(int which, double dist);///<Scales the recedges "to" on edge which by an amount dist
void fixFromTimes(int affedge,double dist);///<Fixes from times when we've moved edge affedge an amount dist
void fixToTimes(int which, double dist);///<Fixes "to" times when we've changed an node time implicitly
void swapEdge(int a, int b);///<Swaps two edges in the edge list (ordering only)
void swapEdgeTo(int a, int b);///<Swaps the edges going to *two specified --nodes--*
void orderEdges(int which);///<Checks that the edge which is in the correct place in the list (from 0.. which)
inline int orderNodes(int which, double dist)
{
return(orderNodes(which,dist,-1));
}///<places a node in a new place in the list (updated to account for recedges);
int orderNodes(int which, double dist, int oldwhich);///<places a node in a new place in the list (updated to account for recedges); a known position is a positive oldwhich...
void swapNode(int a, int b);///<Swaps two nodes in the list (updated to maintain recedges going to them)
int lastCommonAncestor(int s1,int s2);///< USES TABNODES AND TABFATHER! Returns the last common ancestor index of the tabnodes ASSUMING the current local tree.
void makeLocalTreeKeepingFathers(unsigned int site);///< Makes a version of the local tree that has the fathers but is unoptimised
double pairwiseDist(int s1,int s2);///< Returns the pairwise distance between two sequences accounting for recombination. SAME WARNINGS AS lastCommonAncestor!
public:
// Constructors and destructors:
RecTree(unsigned int numsites,WargXml *infile,bool addedges=true,bool forceages=true,bool isfinal=true,std::streampos itstart=-1);///<Creates a tree from an output file
RecTree(unsigned int numsites,std::string newick,bool isFilename=true,bool forceages=true);///<Creates a tree from a Newick file
RecTree(int n,double rho,double delta,std::vector<int> blocks);///<Creates a Coalescent tree with recombinant edges by simulation
void dropEdges(double rho,double delta,vector<int> blocks);
RecTree(Data * data,double rho,double delta,vector<int> blocks);///<Creates UPGMA tree
RecTree(RecTree *intree,string newick,bool isFilename=false,bool forceages=true);/// Copies a rectree
RecTree(const RecTree& rt);///< Copy constructor
void assign(const RecTree& rt);
~RecTree();
// Part of the simulation initialisation:
void setBlock(unsigned int* gstart,unsigned int* gend,double delta,std::vector<int> *blocks);///<Sets the start and end positions of a recombinant block based on geometric distribution and independent blocks
int getEdgeCoal(double* time);///<Returns the node the recombinant edge is from and sets the time
// Part of the likelihood/prior calculation:
double priorEdge(int e,Param * param) const;///<Returns the LOG prior of a given edge number in rectree
double priorEdge(RecEdge* edge0,Param * param) const;///FMA_CHANGES: Computes prior of edge not in rectree
double priorEdge(double tFrom,double tTo) const;///<Returns the UNLOGGED prior of a given edge
double prior(Param * param) const;///<Returns the value of the prior function
void makeLocalTree(unsigned int site,double thetaPerSite);///<Evaluates the local tree at the given site
// Tests:
void testEdges() const;///<Tests recedges arrive in between the ages of the nodes they go to
void testTree();///<Checks ages increase in the tree for all sites.
inline bool sameLocalTreeAsPrev(unsigned int site) const
{
return sameLTasPrev[site];
}///<Returns true if the local tree of site is the same as that of site-1
void calcSameLTasPrev(unsigned int site);///<Estimate if the LT is the same as the previous one
// Information functions:
inline Node * getRoot(){return(root);}
inline double getEdgeTimeAbsFrom(int e) const
{
return edge[e]->getTimeFrom()+nodes[edge[e]->getEdgeFrom()]->getAge();
}
;///<Returns the absolute age of the origin of a recombinant edge
inline double getEdgeTimeAbsTo (int e) const
{
return edge[e]->getTimeTo ()+nodes[edge[e]->getEdgeTo ()]->getAge();
}
;///<Returns the absolute age of the destination of a recombinant edge
inline int getL() const
{
return L;
}///<Returns the total size of the alignment
inline RecEdge*getRecEdge(int w) const
{
return edge[w];
}///<Returns the w-th recombinant edge
inline int getSon (int i, unsigned int site,bool isLeft,double *dist) const
{
site=0;
*dist=tabSonsDist[i][isLeft];
return tabSons[i][isLeft];
};
///<Returns the left daughter node for a given local site and node (NULL if no left daughter)
inline int affecting(unsigned int site) const
{
int a=0;
for (unsigned int i=0;i<edge.size();i++)
if (edge[i]->affectsSite(site))
a++;
return a;
}
;///<Returns the number of edges affecting a site
inline int numRecEdge() const
{
return edge.size();
}///<Returns the number of recombinant edges
int numRecEdgeOnBranch(int b) const
{
int r=0;
for (unsigned int i=0;i<edge.size();i++)
if (edge[i]->getEdgeTo()==b)
r++;
return r;
}///<Returns the number of recedges on a given branch
std::vector<int> alive(double t) const;///<Returns the branches alive at a given time
bool isThere(int start,int end,int e,double time1,double time2) const;///<Returns yes if there is an edge with departure or arrival on branch e and between time1 and time2, and which affects material that intersects [start;end]
inline RecEdge* getEdge(int i) const
{
return(edge[i]);
}///<Returns the edge with index i
double getEdgeTreeTime(int i) const;///<Returns the time an edge spans in the tree
vector<int> getAffEdges(vector<int> * samplespace);///<Calculates the recedges relevent to a set of clonal edges
void updateList(int which, int newloc,vector<int> * list);///<Updates a list of edges when which was moved to newloc
int sampleEdge(vector<int> * samplespace=NULL);///<Samples a random edge that (optionally) interacts with a specific set of clonal edges
// Modification functions:
void addEdgesFromFile(WargXml *infile,int siteoffset=0);///< adds edges to the rectree from the specified warg XML file (which is set to an iteration). Adds a "siteoffset" to add edges from different runs on different genes
int addRecEdge(double tfrom,double tto,unsigned int gstart,unsigned int gend,int edgefrom,int edgeto);///<Adds an recombination edge to the tree
int addRecEdge_FMA(double tfrom,double tto,unsigned int gstart,unsigned int gend,int edgefrom,int edgeto);///FMA_CHANGES: <Adds an recombination edge to the tree
int addRecEdge(unsigned int gstart,unsigned int gend,int edgefrom,int edgeto);///< Adds a recombination edge with random start and end times between given edges
int addRecEdge(std::string res,int sitesoffset=0);///<Add recedge from our output format
void remRecEdge(int which);///<Removes a recombinant edge
void setStart(int edge,int start);///<Sets the starting point of the given recedge
void setEnd(int edge,int end);///<Sets the ending point of the given recedge
void changeAge(int which,double dist);///<Changes the "which" node age, maintaining edge times
inline void changeEdgeNodeFrom(int e,int newnode)
{
edge[e]->setTimeFrom(getEdgeTimeAbsFrom(e)-getNode(newnode)->getAge(),newnode);
}///<changes the node to without changing the absolute time of the edge
inline void changeEdgeNodeTo(int e,int newnode)
{
edge[e]->setTimeTo(getEdgeTimeAbsTo(e)-getNode(newnode)->getAge(),newnode);
}///<changes the node to without changing the absolute time of the edge
void chooseNodePath(int which, double dist, vector<int> *listLR, vector<int> *affedges);///< Sets up a specified order for which nodes to swap when they are disordered
int moveNodeTime(int which, int *whichto,double dist,int oldwhich, vector<int> *listLR, vector<int> *affedges);///<Updates the node list when the node which is moved a distance dist number of recedges moved to younger nodes - number moved to older nodes. edits affedges to make it the a vector of affected edges
void moveEdges(int e1,int e2,double t1=0.0,double t2=-1.0);///<Moves all edge events on e1 between absolute times t1..t2 onto edge e2, maintaining their absolute times (t2=-1 means no upper limit)
// Information functions
std::vector<std::vector<double> > pairwiseDistanceMatrix(long site);///< returns a pairwise distance matrix for a given site
};
} // end namespace weakarg
#endif
| {
"alphanum_fraction": 0.7175130695,
"avg_line_length": 58.8571428571,
"ext": "h",
"hexsha": "af7139ff3c6e895bee11ab3f7c06f23502d2824d",
"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": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "fmedina7/ClonOr_cpp",
"max_forks_repo_path": "ClonOr_cpp/rectree.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"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": "fmedina7/ClonOr_cpp",
"max_issues_repo_path": "ClonOr_cpp/rectree.h",
"max_line_length": 316,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "fmedina7/ClonOr_cpp",
"max_stars_repo_path": "ClonOr_cpp/rectree.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2640,
"size": 10712
} |
/* specfunc/log.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_log.h"
#include "error.h"
#include "chebyshev.h"
#include "cheb_eval.c"
/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/
/* Chebyshev expansion for log(1 + x(t))/x(t)
*
* x(t) = (4t-1)/(2(4-t))
* t(x) = (8x+1)/(2(x+2))
* -1/2 < x < 1/2
* -1 < t < 1
*/
static double lopx_data[21] = {
2.16647910664395270521272590407,
-0.28565398551049742084877469679,
0.01517767255690553732382488171,
-0.00200215904941415466274422081,
0.00019211375164056698287947962,
-0.00002553258886105542567601400,
2.9004512660400621301999384544e-06,
-3.8873813517057343800270917900e-07,
4.7743678729400456026672697926e-08,
-6.4501969776090319441714445454e-09,
8.2751976628812389601561347296e-10,
-1.1260499376492049411710290413e-10,
1.4844576692270934446023686322e-11,
-2.0328515972462118942821556033e-12,
2.7291231220549214896095654769e-13,
-3.7581977830387938294437434651e-14,
5.1107345870861673561462339876e-15,
-7.0722150011433276578323272272e-16,
9.7089758328248469219003866867e-17,
-1.3492637457521938883731579510e-17,
1.8657327910677296608121390705e-18
};
static cheb_series lopx_cs = {
lopx_data,
20,
-1, 1,
10
};
/* Chebyshev expansion for (log(1 + x(t)) - x(t))/x(t)^2
*
* x(t) = (4t-1)/(2(4-t))
* t(x) = (8x+1)/(2(x+2))
* -1/2 < x < 1/2
* -1 < t < 1
*/
static double lopxmx_data[20] = {
-1.12100231323744103373737274541,
0.19553462773379386241549597019,
-0.01467470453808083971825344956,
0.00166678250474365477643629067,
-0.00018543356147700369785746902,
0.00002280154021771635036301071,
-2.8031253116633521699214134172e-06,
3.5936568872522162983669541401e-07,
-4.6241857041062060284381167925e-08,
6.0822637459403991012451054971e-09,
-8.0339824424815790302621320732e-10,
1.0751718277499375044851551587e-10,
-1.4445310914224613448759230882e-11,
1.9573912180610336168921438426e-12,
-2.6614436796793061741564104510e-13,
3.6402634315269586532158344584e-14,
-4.9937495922755006545809120531e-15,
6.8802890218846809524646902703e-16,
-9.5034129794804273611403251480e-17,
1.3170135013050997157326965813e-17
};
static cheb_series lopxmx_cs = {
lopxmx_data,
19,
-1, 1,
9
};
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
#ifndef HIDE_INLINE_STATIC
int
gsl_sf_log_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= 0.0) {
DOMAIN_ERROR(result);
}
else {
result->val = log(x);
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
int
gsl_sf_log_abs_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x == 0.0) {
DOMAIN_ERROR(result);
}
else {
result->val = log(fabs(x));
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
#endif
int
gsl_sf_complex_log_e(const double zr, const double zi, gsl_sf_result * lnr, gsl_sf_result * theta)
{
/* CHECK_POINTER(lnr) */
/* CHECK_POINTER(theta) */
if(zr != 0.0 || zi != 0.0) {
const double ax = fabs(zr);
const double ay = fabs(zi);
const double min = GSL_MIN(ax, ay);
const double max = GSL_MAX(ax, ay);
lnr->val = log(max) + 0.5 * log(1.0 + (min/max)*(min/max));
lnr->err = 2.0 * GSL_DBL_EPSILON * fabs(lnr->val);
theta->val = atan2(zi, zr);
theta->err = GSL_DBL_EPSILON * fabs(lnr->val);
return GSL_SUCCESS;
}
else {
DOMAIN_ERROR_2(lnr, theta);
}
}
int
gsl_sf_log_1plusx_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= -1.0) {
DOMAIN_ERROR(result);
}
else if(fabs(x) < GSL_ROOT6_DBL_EPSILON) {
const double c1 = -0.5;
const double c2 = 1.0/3.0;
const double c3 = -1.0/4.0;
const double c4 = 1.0/5.0;
const double c5 = -1.0/6.0;
const double c6 = 1.0/7.0;
const double c7 = -1.0/8.0;
const double c8 = 1.0/9.0;
const double c9 = -1.0/10.0;
const double t = c5 + x*(c6 + x*(c7 + x*(c8 + x*c9)));
result->val = x * (1.0 + x*(c1 + x*(c2 + x*(c3 + x*(c4 + x*t)))));
result->err = GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else if(fabs(x) < 0.5) {
double t = 0.5*(8.0*x + 1.0)/(x+2.0);
gsl_sf_result c;
cheb_eval_e(&lopx_cs, t, &c);
result->val = x * c.val;
result->err = fabs(x * c.err);
return GSL_SUCCESS;
}
else {
result->val = log(1.0 + x);
result->err = GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
int
gsl_sf_log_1plusx_mx_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= -1.0) {
DOMAIN_ERROR(result);
}
else if(fabs(x) < GSL_ROOT5_DBL_EPSILON) {
const double c1 = -0.5;
const double c2 = 1.0/3.0;
const double c3 = -1.0/4.0;
const double c4 = 1.0/5.0;
const double c5 = -1.0/6.0;
const double c6 = 1.0/7.0;
const double c7 = -1.0/8.0;
const double c8 = 1.0/9.0;
const double c9 = -1.0/10.0;
const double t = c5 + x*(c6 + x*(c7 + x*(c8 + x*c9)));
result->val = x*x * (c1 + x*(c2 + x*(c3 + x*(c4 + x*t))));
result->err = GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else if(fabs(x) < 0.5) {
double t = 0.5*(8.0*x + 1.0)/(x+2.0);
gsl_sf_result c;
cheb_eval_e(&lopxmx_cs, t, &c);
result->val = x*x * c.val;
result->err = x*x * c.err;
return GSL_SUCCESS;
}
else {
const double lterm = log(1.0 + x);
result->val = lterm - x;
result->err = GSL_DBL_EPSILON * (fabs(lterm) + fabs(x));
return GSL_SUCCESS;
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_log(const double x)
{
EVAL_RESULT(gsl_sf_log_e(x, &result));
}
double gsl_sf_log_abs(const double x)
{
EVAL_RESULT(gsl_sf_log_abs_e(x, &result));
}
double gsl_sf_log_1plusx(const double x)
{
EVAL_RESULT(gsl_sf_log_1plusx_e(x, &result));
}
double gsl_sf_log_1plusx_mx(const double x)
{
EVAL_RESULT(gsl_sf_log_1plusx_mx_e(x, &result));
}
| {
"alphanum_fraction": 0.6504277222,
"avg_line_length": 25.6394052045,
"ext": "c",
"hexsha": "ca612721f0b1ad3b1a766634b6821367a8bd12bd",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/log.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/specfunc/log.c",
"max_line_length": 98,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/log.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": 2598,
"size": 6897
} |
static char help[] =
"Coupled reaction-diffusion equations (Pearson 1993). Option prefix -ptn_.\n"
"Demonstrates form F(t,Y,dot Y) = G(t,Y) where F() is IFunction and G() is\n"
"RHSFunction(). Implements IJacobian(). Defaults to ARKIMEX (= adaptive\n"
"Runge-Kutta implicit-explicit) TS type.\n\n";
// compare runs with
// -dm_mat_type aij|baij|sbaij
// -dm_mat_type sbaij -ksp_type cg -pc_type icc # 20% speed up?
#include <petsc.h>
typedef struct {
double u, v;
} Field;
typedef struct {
double L, // domain side length
Du, // diffusion coefficient: u equation
Dv, // v equation
phi, // "dimensionless feed rate" (F in Pearson 1993)
kappa; // "dimensionless rate constant" (k in Pearson 1993)
} PatternCtx;
extern PetscErrorCode InitialState(DM, Vec, double, PatternCtx*);
extern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, double, Field**,
Field**, PatternCtx*);
extern PetscErrorCode FormIFunctionLocal(DMDALocalInfo*, double, Field**, Field**,
Field **, PatternCtx*);
extern PetscErrorCode FormIJacobianLocal(DMDALocalInfo*, double, Field**, Field**,
double, Mat, Mat, PatternCtx*);
int main(int argc,char **argv)
{
PetscErrorCode ierr;
PatternCtx user;
TS ts;
Vec x;
DM da;
DMDALocalInfo info;
double noiselevel = -1.0; // negative value means no initial noise
PetscInitialize(&argc,&argv,(char*)0,help);
// parameter values from pages 21-22 in Hundsdorfer & Verwer (2003)
user.L = 2.5;
user.Du = 8.0e-5;
user.Dv = 4.0e-5;
user.phi = 0.024;
user.kappa = 0.06;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "ptn_", "options for patterns", ""); CHKERRQ(ierr);
ierr = PetscOptionsReal("-noisy_init",
"initialize u,v with this much random noise (e.g. 0.2) on top of usual initial values",
"pattern.c",noiselevel,&noiselevel,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-L","square domain side length; recommend L >= 0.5",
"pattern.c",user.L,&user.L,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-Du","diffusion coefficient of first equation",
"pattern.c",user.Du,&user.Du,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-Dv","diffusion coefficient of second equation",
"pattern.c",user.Dv,&user.Dv,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-phi","dimensionless feed rate (=F in (Pearson, 1993))",
"pattern.c",user.phi,&user.phi,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-kappa","dimensionless rate constant (=k in (Pearson, 1993))",
"pattern.c",user.kappa,&user.kappa,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_PERIODIC, DM_BOUNDARY_PERIODIC,
DMDA_STENCIL_BOX, // for 9-point stencil
3,3,PETSC_DECIDE,PETSC_DECIDE,
2, 1, // degrees of freedom, stencil width
NULL,NULL,&da); CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMDASetFieldName(da,0,"u"); CHKERRQ(ierr);
ierr = DMDASetFieldName(da,1,"v"); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
if (info.mx != info.my) {
SETERRQ(PETSC_COMM_WORLD,1,"pattern.c requires mx == my");
}
ierr = DMDASetUniformCoordinates(da, 0.0, user.L, 0.0, user.L, -1.0, -1.0); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"running on %d x %d grid with square cells of side h = %.6f ...\n",
info.mx,info.my,user.L/(double)(info.mx)); CHKERRQ(ierr);
//STARTTSSETUP
ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);
ierr = TSSetDM(ts,da); CHKERRQ(ierr);
ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);
ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES,
(DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr);
ierr = DMDATSSetIFunctionLocal(da,INSERT_VALUES,
(DMDATSIFunctionLocal)FormIFunctionLocal,&user); CHKERRQ(ierr);
ierr = DMDATSSetIJacobianLocal(da,
(DMDATSIJacobianLocal)FormIJacobianLocal,&user); CHKERRQ(ierr);
ierr = TSSetType(ts,TSARKIMEX); CHKERRQ(ierr);
ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);
ierr = TSSetMaxTime(ts,200.0); CHKERRQ(ierr);
ierr = TSSetTimeStep(ts,5.0); CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);
ierr = TSSetFromOptions(ts);CHKERRQ(ierr);
//ENDTSSETUP
ierr = DMCreateGlobalVector(da,&x); CHKERRQ(ierr);
ierr = InitialState(da,x,noiselevel,&user); CHKERRQ(ierr);
ierr = TSSolve(ts,x); CHKERRQ(ierr);
VecDestroy(&x); TSDestroy(&ts); DMDestroy(&da);
return PetscFinalize();
}
// Formulas from page 22 of Hundsdorfer & Verwer (2003). Interpretation here is
// to always generate 0.5 x 0.5 non-trivial patch in (0,L) x (0,L) domain.
PetscErrorCode InitialState(DM da, Vec Y, double noiselevel, PatternCtx* user) {
PetscErrorCode ierr;
DMDALocalInfo info;
int i,j;
double sx,sy;
const double ledge = (user->L - 0.5) / 2.0, // nontrivial initial values on
redge = user->L - ledge; // ledge < x,y < redge
DMDACoor2d **aC;
Field **aY;
ierr = VecSet(Y,0.0); CHKERRQ(ierr);
if (noiselevel > 0.0) {
// noise added to usual initial condition is uniform on [0,noiselevel],
// independently for each location and component
ierr = VecSetRandom(Y,NULL); CHKERRQ(ierr);
ierr = VecScale(Y,noiselevel); CHKERRQ(ierr);
}
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = DMDAGetCoordinateArray(da,&aC); CHKERRQ(ierr);
ierr = DMDAVecGetArray(da,Y,&aY); CHKERRQ(ierr);
for (j = info.ys; j < info.ys+info.ym; j++) {
for (i = info.xs; i < info.xs+info.xm; i++) {
if ((aC[j][i].x >= ledge) && (aC[j][i].x <= redge)
&& (aC[j][i].y >= ledge) && (aC[j][i].y <= redge)) {
sx = sin(4.0 * PETSC_PI * aC[j][i].x);
sy = sin(4.0 * PETSC_PI * aC[j][i].y);
aY[j][i].v += 0.5 * sx * sx * sy * sy;
}
aY[j][i].u += 1.0 - 2.0 * aY[j][i].v;
}
}
ierr = DMDAVecRestoreArray(da,Y,&aY); CHKERRQ(ierr);
ierr = DMDARestoreCoordinateArray(da,&aC); CHKERRQ(ierr);
return 0;
}
// in system form F(t,Y,dot Y) = G(t,Y), compute G():
// G^u(t,u,v) = - u v^2 + phi (1 - u)
// G^v(t,u,v) = + u v^2 - (phi + kappa) v
//STARTRHSFUNCTION
PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info,
double t, Field **aY, Field **aG, PatternCtx *user) {
int i, j;
double uv2;
for (j = info->ys; j < info->ys + info->ym; j++) {
for (i = info->xs; i < info->xs + info->xm; i++) {
uv2 = aY[j][i].u * aY[j][i].v * aY[j][i].v;
aG[j][i].u = - uv2 + user->phi * (1.0 - aY[j][i].u);
aG[j][i].v = + uv2 - (user->phi + user->kappa) * aY[j][i].v;
}
}
return 0;
}
//ENDRHSFUNCTION
// in system form F(t,Y,dot Y) = G(t,Y), compute F():
// F^u(t,u,v,u_t,v_t) = u_t - D_u Laplacian u
// F^v(t,u,v,u_t,v_t) = v_t - D_v Laplacian v
//STARTIFUNCTION
PetscErrorCode FormIFunctionLocal(DMDALocalInfo *info,
double t, Field **aY, Field **aYdot, Field **aF,
PatternCtx *user) {
int i, j;
const double h = user->L / (double)(info->mx),
Cu = user->Du / (6.0 * h * h),
Cv = user->Dv / (6.0 * h * h);
double u, v, lapu, lapv;
for (j = info->ys; j < info->ys + info->ym; j++) {
for (i = info->xs; i < info->xs + info->xm; i++) {
u = aY[j][i].u;
v = aY[j][i].v;
lapu = aY[j+1][i-1].u + 4.0*aY[j+1][i].u + aY[j+1][i+1].u
+ 4.0*aY[j][i-1].u - 20.0*u + 4.0*aY[j][i+1].u
+ aY[j-1][i-1].u + 4.0*aY[j-1][i].u + aY[j-1][i+1].u;
lapv = aY[j+1][i-1].v + 4.0*aY[j+1][i].v + aY[j+1][i+1].v
+ 4.0*aY[j][i-1].v - 20.0*v + 4.0*aY[j][i+1].v
+ aY[j-1][i-1].v + 4.0*aY[j-1][i].v + aY[j-1][i+1].v;
aF[j][i].u = aYdot[j][i].u - Cu * lapu;
aF[j][i].v = aYdot[j][i].v - Cv * lapv;
}
}
return 0;
}
//ENDIFUNCTION
// in system form F(t,Y,dot Y) = G(t,Y), compute combined/shifted
// Jacobian of F():
// J = (shift) dF/d(dot Y) + dF/dY
//STARTIJACOBIAN
PetscErrorCode FormIJacobianLocal(DMDALocalInfo *info,
double t, Field **aY, Field **aYdot, double shift,
Mat J, Mat P, PatternCtx *user) {
PetscErrorCode ierr;
int i, j, s, c;
const double h = user->L / (double)(info->mx),
Cu = user->Du / (6.0 * h * h),
Cv = user->Dv / (6.0 * h * h);
double val[9], CC;
MatStencil col[9], row;
for (j = info->ys; j < info->ys + info->ym; j++) {
row.j = j;
for (i = info->xs; i < info->xs + info->xm; i++) {
row.i = i;
for (c = 0; c < 2; c++) { // u,v equations are c=0,1
row.c = c;
CC = (c == 0) ? Cu : Cv;
for (s = 0; s < 9; s++)
col[s].c = c;
col[0].i = i; col[0].j = j;
val[0] = shift + 20.0 * CC;
col[1].i = i-1; col[1].j = j; val[1] = - 4.0 * CC;
col[2].i = i+1; col[2].j = j; val[2] = - 4.0 * CC;
col[3].i = i; col[3].j = j-1; val[3] = - 4.0 * CC;
col[4].i = i; col[4].j = j+1; val[4] = - 4.0 * CC;
col[5].i = i-1; col[5].j = j-1; val[5] = - CC;
col[6].i = i-1; col[6].j = j+1; val[6] = - CC;
col[7].i = i+1; col[7].j = j-1; val[7] = - CC;
col[8].i = i+1; col[8].j = j+1; val[8] = - CC;
ierr = MatSetValuesStencil(P,1,&row,9,col,val,INSERT_VALUES); CHKERRQ(ierr);
}
}
}
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
//ENDIJACOBIAN
| {
"alphanum_fraction": 0.5505180116,
"avg_line_length": 41.9163346614,
"ext": "c",
"hexsha": "c15d0152a9e43788fc3a4c6d64b0104faafb67be",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch5/pattern.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch5/pattern.c",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch5/pattern.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3530,
"size": 10521
} |
#include <stdlib.h>
#include <gsl/block/gsl_block.h>
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/block/init_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE | {
"alphanum_fraction": 0.7684210526,
"avg_line_length": 19,
"ext": "c",
"hexsha": "ffe5d38c2053dafeaa3e4e5312319676da984314",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/init.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/init.c",
"max_line_length": 34,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/init.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 47,
"size": 190
} |
/*
* Copyright (c) 2020 Microsoft. All rights reserved.
*/
#pragma once
// a place for frequently used types, especially ones relied on for interfaces
// eg gsl::span<uint8_t> etc
#include "machine.h"
#include <vector>
#include <gsl/span>
#include <gsl/span_ext>
#include <gsl/util>
#include <type_traits> // for make_unsigned
template <typename T>
T RemoveUnsigned(typename std::make_unsigned<T>::type val) {
return gsl::narrow_cast<T>(val);
}
template <typename T> typename std::make_unsigned<T>::type MakeUnsigned(T val) {
return gsl::narrow_cast<typename std::make_unsigned<T>::type>(val);
}
// encapsulate some memory which may be written, use instead of a ptr, len
using MemRef = gsl::span<uint8_t>;
using MemRefSizeType = MemRef::size_type;
using SignedMemRef = gsl::span<char>;
using SignedMemRefSizeType = SignedMemRef::size_type;
using MemVector = std::vector<uint8_t>;
// encapsulate some read only memory
using CMemRef = gsl::span<const uint8_t>;
using CSignedMemRef = gsl::span<const char>;
// from any old class T make a span covering uint8_ts
// intended for the Params classes.
template <class T> MemRef MakeMemRef(T *p) noexcept {
void *ptr = p;
static_assert(sizeof(*p) != 1);
return MemRef(static_cast<uint8_t *>(ptr), sizeof(*p));
}
template <class T> MemRef MakeMemRef(T *p, size_t len) noexcept {
void *ptr = p;
return MemRef(static_cast<uint8_t *>(ptr), len);
}
template <class T> CMemRef MakeCMemRef(const T *p, size_t len) noexcept {
const void *ptr = p;
return CMemRef(static_cast<const uint8_t *>(ptr), len);
}
template <class T> CMemRef MakeCMemRef(const T *p) noexcept {
const void *ptr = p;
return CMemRef(static_cast<const uint8_t *>(ptr), sizeof(*p));
}
template <class T, size_t TLength>
CMemRef MakeCMemRef2(const T (&p)[TLength]) noexcept {
const void *ptr = p;
return CMemRef(static_cast<const uint8_t *>(ptr), TLength);
}
template <class T> SignedMemRef MakeSignedMemRef(T *p) noexcept {
void *ptr = p;
static_assert(sizeof(*p) != 1);
return SignedMemRef(static_cast<char *>(ptr), sizeof(*p));
}
template <class T> SignedMemRef MakeSignedMemRef(T *p, size_t len) noexcept {
void *ptr = p;
return SignedMemRef(static_cast<char *>(ptr), len);
}
template <class T> CSignedMemRef MakeCSignedMemRef(T *p) noexcept {
const void *ptr = p;
static_assert(sizeof(*p) != 1);
return CSignedMemRef(static_cast<const char *>(ptr), sizeof(*p));
}
template <class T> CSignedMemRef MakeCSignedMemRef(T *p, size_t len) noexcept {
const void *ptr = p;
return CSignedMemRef(static_cast<const char *>(ptr), len);
}
// T will needs top be copyable
template <class T> T ReHydrate(CMemRef source) noexcept {
const void *ptr = source.data();
const T *tInPlace = static_cast<const T *>(ptr);
T ret = *tInPlace;
return ret;
}
// Work around C4686
using _FixedLengthString = std::array<char, 1024>;
class FixedLengthString : public _FixedLengthString {
using _FixedLengthString::_FixedLengthString;
};
// helper for HexDump
void HexByte(uint8_t byte, char &c1, char &c2);
// hex dump a block of memory into another block of memory.
size_t HexDump(CMemRef src, SignedMemRef dst);
template <class T, int LEN> struct IsPODEtc {
static constexpr bool value =
sizeof(T) == LEN && std::is_pod<T>::value && std::is_trivial<T>::value &&
std::is_trivially_copyable<T>::value && std::is_standard_layout<T>::value;
};
/*
Compile time protection against objects being different between the
host and HW.
usage - put something like the following outside the class:
static_assert(OkAsParam<MyClass, 666>::value);
*/
template <class T, int LEN> struct SizeIsOK {
static constexpr bool value = sizeof(T) == LEN;
};
template <class T> struct LayoutIsOK {
// These two checks fail for most of our types as they have user provided
// default ctors or members with default initialisers.
// static_assert(std::is_pod<T>::value);
// static_assert(std::is_trivial<T>::value);
static constexpr bool value =
// but anything we can serialise by copying must be trivially copyable
std::is_trivially_copyable<T>::value &&
// and must be standard layout, ie if you can't pass it to a C program
// what hope is there that you can pass it over the wire to the HW.
std::is_standard_layout<T>::value;
};
template <class T, int LEN> struct OkAsParam {
static constexpr bool value = SizeIsOK<T, LEN>::value && LayoutIsOK<T>::value;
};
// Thinking about labeling classes explicitly. TBC, ignore for now.
class CannotBeSerialsed {
public:
constexpr bool canBeSerialised() const { return false; }
};
class CanBeSerialsed {
public:
constexpr bool canBeSerialised() const { return true; }
};
| {
"alphanum_fraction": 0.7123548046,
"avg_line_length": 28.8719512195,
"ext": "h",
"hexsha": "1af6fb13db72e95a4c633a2d54f6ae305222e68d",
"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": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7",
"max_forks_repo_path": "src/common/common.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6",
"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": "verified-HRoT/Verified-DICE-for-STM32H7",
"max_issues_repo_path": "src/common/common.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7",
"max_stars_repo_path": "src/common/common.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1268,
"size": 4735
} |
#ifndef QDM_TAU_H
#define QDM_TAU_H 1
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
typedef struct {
bool use_table;
double low;
double high;
size_t spline_df;
const gsl_vector *knots;
gsl_vector *reset;
gsl_matrix *ispline_table;
gsl_matrix *mspline_table;
} qdm_tau;
qdm_tau *
qdm_tau_alloc(
int use_table,
double low,
double high,
size_t spline_df,
const gsl_vector *knots
);
void
qdm_tau_free(
qdm_tau *t
);
double
qdm_tau_ispline_mmm(
const qdm_tau *t,
const double value,
const gsl_vector *mmm
);
double
qdm_tau_mspline_mmm(
const qdm_tau *t,
const double value,
const gsl_vector *mmm
);
double
qdm_tau_find(
const qdm_tau *t,
const double v,
const gsl_vector *mmm
);
#endif /* QDM_TAU_H */
| {
"alphanum_fraction": 0.6918392205,
"avg_line_length": 13.6833333333,
"ext": "h",
"hexsha": "fb4de5186116e366a4f5203b99265780fac5b235",
"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/tau.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/tau.h",
"max_line_length": 28,
"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/tau.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 252,
"size": 821
} |
// Implementation of the interface in float_image.h.
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <setjmp.h>
#include <glib.h>
#if GLIB_CHECK_VERSION (2, 6, 0)
# include <glib/gstdio.h>
#endif
#include <gsl/gsl_spline.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_math.h>
#include "asf.h"
#include "asf_tiff.h"
#include "asf_jpeg.h"
#include "float_image.h"
#ifndef linux
#ifndef darwin
#ifndef win32
static double
round (double arg)
{
return floor (arg + 0.5);
}
#endif // #ifndef win32
#endif // #ifndef darwin
#endif // #ifndef linux
#include "asf_glib.h"
// Default cache size to use is 16 megabytes.
static const size_t default_cache_size = 16 * 1048576;
// This class wide data element keeps track of the number of temporary
// tile files opened by the current process, in order to give them
// unique names.
static unsigned long current_tile_file_number = 0;
#ifndef win32
// We need to ensure that multiple threads trying to create their own
// images concurently don't end up with the same temporary file names.
G_LOCK_DEFINE_STATIC (current_tile_file_number);
// We don't want to let multiple threads twiddle the signal block mask
// concurrently, or we might end up with the wrong set of signals
// blocked. This lock is used to gaurantee this can't happen (see the
// usage for a better explanation).
G_LOCK_DEFINE_STATIC (signal_block_activity);
#endif
// Return a FILE pointer refering to a new, already unlinked file in a
// location which hopefully has enough free space to serve as a block
// cache.
static FILE *
initialize_tile_cache_file (GString **tile_file_name)
{
// Create the temporary tile oriented storage file. This gets
// filled in in different ways depending on which creation routine
// we are using.
g_assert(*tile_file_name == NULL);
*tile_file_name = g_string_new ("");
// Here we do a slightly weird thing: if the current directory is
// writable, we create a temporary file in the current directory.
// We do this because the temporary file could well be pretty big
// and /tmp often maps to a small file system. The idea is that the
// directory the user is in is more likely to have the extra space
// required to hold the temporary file. Of course, if they have
// been carefully calculating their space requirements, they may be
// disappointed. We use a weird name that no sane user would ever
// use for one of their files, we hope.
#ifndef win32
G_LOCK (current_tile_file_number);
g_assert (sizeof (long) >= sizeof (pid_t));
#endif
g_string_append_printf (*tile_file_name,
".float_image_tile_file_%ld_%lu",
(long) getpid (),
current_tile_file_number);
//g_free (current_dir);
// This hard coded limit on the current number used to uniqueify
// file names limits us to creating no more than ULONG_MAX instances
// during a process.
g_assert (current_tile_file_number < ULONG_MAX);
current_tile_file_number++;
#ifndef win32
G_UNLOCK (current_tile_file_number);
// We block signals while we create and unlink this file, so we
// don't end up leaving a huge temporary file somewhere.
// Theoretically, two parallel instantiations of image could end up
// in a race condition which would result in all signals ending up
// blocked after both were done with this section, so we consider
// this section critical and protect it with a lock.
G_LOCK (signal_block_activity);
sigset_t all_signals, old_set;
int return_code = sigfillset (&all_signals);
g_assert (return_code == 0);
return_code = sigprocmask (SIG_SETMASK, &all_signals, &old_set);
#endif
// now open new tile file in the tmp dir
FILE *tile_file = fopen_tmp_file ((*tile_file_name)->str, "w+b");
if ( tile_file == NULL ) {
if ( errno != EACCES ) {
g_warning ("couldn't create file in tmp directory (%s), and it wasn't"
"just a permissions problem", get_asf_tmp_dir());
}
else {
// Couldn't open in current directory, so try using tmpfile,
// which opens the file in the standardish place for the system.
// See the comment above about why opening in /tmp or the like
// is potentially bad.
tile_file = tmpfile ();
g_assert (tile_file != NULL);
}
}
else {
// the open-then-delete trick does not seem to work on MinGW
#ifndef win32
return_code = unlink_tmp_file ((*tile_file_name)->str);
g_assert (return_code == 0);
#endif
}
g_assert (tile_file != NULL);
#ifndef win32
return_code = sigprocmask (SIG_SETMASK, &old_set, NULL);
G_UNLOCK (signal_block_activity);
#endif
return tile_file;
}
// This routine does the work common to several of the differenct
// creation routines. Basicly, it does everything but fill in the
// contents of the disk tile store.
static FloatImage *
initialize_float_image_structure (ssize_t size_x, ssize_t size_y)
{
// Allocate instance memory.
FloatImage *self = g_new0 (FloatImage, 1);
// Validate and remember image size.
g_assert (size_x > 0 && size_y > 0);
self->size_x = size_x;
self->size_y = size_y;
// Greater of size_x and size_y.
size_t largest_dimension = (size_x > size_y ? size_x : size_y);
// If we can fit the entire image in a single square tile, then we
// want just a single big tile and we won't need to bother with the
// cache file since it won't ever be used, so we do things slightly
// differently. FIXME: it would be slightly better to also detect
// and specially handle the case where we have long narrow images
// that can fit in a single stip of tiles in the cache.
if ( largest_dimension * largest_dimension * sizeof (float)
<= default_cache_size ) {
self->cache_space = largest_dimension * largest_dimension * sizeof (float);
self->cache_area = self->cache_space / sizeof (float);
self->tile_size = largest_dimension;
self->cache_size_in_tiles = 1;
self->tile_count_x = 1;
self->tile_count_y = 1;
self->tile_count = 1;
self->tile_area = self->tile_size * self->tile_size;
self->cache = g_new (float, self->cache_area);
self->tile_addresses = g_new0 (float *, self->tile_count);
g_assert (NULL == 0x0); // Ensure g_new0 effectively sets to NULL.
// The tile queue shouldn't ever be needed in this case.
self->tile_queue = NULL;
// The tile file shouldn't ever be needed, so we set it to NULL to
// indicate this to a few other methods that use it directly, and
// to hopefully ensure that it triggers an exception if it is
// used.
self->tile_file = NULL;
// Objects are born with one reference.
self->reference_count = 1;
return self;
}
// The default cache size compiled into the class.
self->cache_space = default_cache_size;
// Memory cache space, in pixels.
g_assert (self->cache_space % sizeof (float) == 0);
self->cache_area = self->cache_space / sizeof (float);
// How small do our tiles have to be on a side to fit two full rows
// of them in the memory cache? This is slightly tricky. In order
// to provide the services promised in the interface, we need to
// solve
//
// 2 * pow (t, 2) * ceil ((double)largest_dimension / t)
// <= self->cache_area
//
// for tile size t. I don't know the closed form solution if there
// is one, so toss out the ceil() and solve the easier
//
// 2 * pow (t, 2) * ((double)largest_dimension / t) <= self->cache_area
//
// and then decrement t iteratively until things work.
self->tile_size = self->cache_area / (2 * largest_dimension);
while ( (2 * self->tile_size * self->tile_size
* ceil ((double) largest_dimension / self->tile_size))
> self->cache_area ) {
self->tile_size--;
}
// If we end up with a tile size of 0, it means we tried to create a
// truly gigantic image (compared to the size of the tile cache at
// least. Really, if we end up with a sufficiently small tile size,
// there probably isn't much point in going on. Picking an
// arbitrary tile size to call too small is tricky, but we do it
// anyway :).
const size_t minimum_tile_size = 4;
g_assert (self->tile_size >= minimum_tile_size);
// Area of tiles, in pixels.
self->tile_area = (size_t) (self->tile_size * self->tile_size);
// Number of tiles which will fit in image cache.
self->cache_size_in_tiles = self->cache_area / self->tile_area;
// Can we fit at least as much as we intended in the cache?
g_assert (self->cache_size_in_tiles
>= 2 * (size_t) ceil ((double) largest_dimension
/ self->tile_size));
// Number of tiles image has been split into in x and y directions.
self->tile_count_x = (size_t) ceil ((double) self->size_x / self->tile_size);
self->tile_count_y = (size_t) ceil ((double) self->size_y / self->tile_size);
// Total number of image tiles image has been split into.
self->tile_count = self->tile_count_x * self->tile_count_y;
// We want to be able to pack a tile number into a pointer later, so
// we need it to fit into an integer.
g_assert (self->tile_count < INT_MAX);
// Did all that math work?
g_assert (self->tile_size * self->cache_size_in_tiles / 2
>= largest_dimension);
g_assert (self->cache_size_in_tiles * self->tile_area <= self->cache_area);
// Allocate memory for the in-memory cache.
self->cache = g_new (float, self->cache_area);
// Do we want to do mlock() here maybe?
// The addresses in the cache of the starts of each of the tiles.
// This array contains flattened tile addresses in the same way that
// image memory normally uses flattened pixel addresses, e.g. the
// address of tile x = 2, y = 4 is stored at self->tile_addresses[4
// * self->tile_count_x + 2]. If a tile isn't in the cache, the
// address is NULL (meaning it will have to be loaded).
self->tile_addresses = g_new0 (float *, self->tile_count);
g_assert (NULL == 0x0); // Ensure g_new0 effectively sets to NULL.
// Create a queue in order to keep track of which tile was loaded
// longest ago.
self->tile_queue = g_queue_new ();
// Get a new empty tile cache file pointer.
self->tile_file_name = NULL;
self->tile_file = initialize_tile_cache_file (&(self->tile_file_name));
// Objects are born with one reference.
self->reference_count = 1;
return self;
}
FloatImage *
float_image_thaw (FILE *file_pointer)
{
FILE *fp = file_pointer; // Convenience alias.
g_assert (file_pointer != NULL);
FloatImage *self = g_new0 (FloatImage, 1);
size_t read_count = fread (&(self->size_x), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->size_y), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->cache_space), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->cache_area), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_size), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_count_x), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_count_y), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_count), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_area), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
// The cache isn't serialized -- its a bit of a pain and probably
// almost never worth it.
self->cache = g_new (float, self->cache_area);
self->tile_addresses = g_new0 (float *, self->tile_count);
// We don't actually keep the tile queue in the serialized instance,
// but if the serialized pointer to it is NULL, we know we aren't
// using a tile cache file (i.e. the whole image fits in the memory
// cache).
read_count = fread (&(self->tile_queue), sizeof (GQueue *), 1, fp);
g_assert (read_count == 1);
// If there was no cache file...
if ( self->tile_queue == NULL ) {
// The tile_file structure field should also be NULL.
self->tile_file = NULL;
// we restore the file directly into the first and only tile (see
// the end of the float_image_new method).
self->tile_addresses[0] = self->cache;
read_count = fread (self->tile_addresses[0], sizeof (float),
self->tile_area, fp);
g_assert (read_count == self->tile_area);
}
// otherwise, an empty tile queue needs to be initialized, and the
// remainder of the serialized version is the tile block cache.
else {
self->tile_queue = g_queue_new ();
self->tile_file_name = NULL;
self->tile_file = initialize_tile_cache_file (&(self->tile_file_name));
float *buffer = g_new (float, self->tile_area);
size_t ii;
for ( ii = 0 ; ii < self->tile_count ; ii++ ) {
read_count = fread (buffer, sizeof (float), self->tile_area, fp);
g_assert (read_count == self->tile_area);
size_t write_count = fwrite (buffer, sizeof (float), self->tile_area,
self->tile_file);
if ( write_count < self->tile_area ) {
if ( feof (self->tile_file) ) {
fprintf (stderr,
"Premature end of file while trying to thaw FloatImage "
"instance\n");
}
else {
g_assert (ferror (self->tile_file));
fprintf (stderr,
"Error writing tile cache file for FloatImage instance "
"during thaw: %s\n", strerror (errno));
}
exit (EXIT_FAILURE);
}
g_assert (write_count == self->tile_area);
}
g_free (buffer);
}
// We didn't call initialize_float_image_structure directly or
// indirectly for this creation method, so we still have to set the
// reference count appropriately.
self->reference_count = 1;
return self;
}
FloatImage *
float_image_new (ssize_t size_x, ssize_t size_y)
{
g_assert (size_x > 0 && size_y > 0);
FloatImage *self = initialize_float_image_structure (size_x, size_y);
// If we need a tile file for an image of this size, prepare it.
if ( self->tile_file != NULL ) {
// The total width or height of all the tiles is probably greater
// than the width or height of the image itself.
size_t total_width = self->tile_count_x * self->tile_size;
size_t total_height = self->tile_count_y * self->tile_size;
// Fill the file full of zeros. FIXME: there is almost certainly
// a faster way to ensure that we have the disk space we need.
float *zero_line = g_new0 (float, total_width);
g_assert (0.0 == 0x0); // Ensure the g_new0 did what we think.
// We don't have to write in tile order because its all zeros anyway.
size_t ii;
for ( ii = 0 ; ii < total_height ; ii++ ) {
size_t write_count = fwrite (zero_line, sizeof (float), total_width,
self->tile_file);
// If we wrote less than expected,
if ( write_count < total_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for FloatImage instance: %s\n",
strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
// Done with the line of zeros.
g_free (zero_line);
}
// Everything fits in the cache (at the moment this means everything
// fits in the first tile, which is a bit of a FIXME), so just put
// it there.
else {
self->tile_addresses[0] = self->cache;
size_t ii, jj;
for ( ii = 0 ; ii < self->tile_size ; ii++ ) {
for ( jj = 0 ; jj < self->tile_size ; jj++ ) {
self->tile_addresses[0][ii * self->tile_size + jj] = 0.0;
}
}
}
return self;
}
FloatImage *
float_image_new_with_value (ssize_t size_x, ssize_t size_y, float value)
{
g_assert (size_x > 0 && size_y > 0);
FloatImage *self = initialize_float_image_structure (size_x, size_y);
// If we need a tile file for an image of this size, prepare it.
if ( self->tile_file != NULL ) {
// The total width or height of all the tiles is probably greater
// than the width or height of the image itself.
size_t total_width = self->tile_count_x * self->tile_size;
size_t total_height = self->tile_count_y * self->tile_size;
// Fill the file full of the given value.
float *value_line = g_new (float, total_width);
size_t ii;
for ( ii = 0 ; ii < total_width ; ii++ ) {
value_line[ii] = value;
}
// We don't have to write in tile order because the values are all
// the same anyway.
for ( ii = 0 ; ii < total_height ; ii++ ) {
size_t write_count = fwrite (value_line, sizeof (float), total_width,
self->tile_file);
// If we wrote less than expected,
if ( write_count < total_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for FloatImage instance: %s\n",
strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
// Done with the line of values.
g_free (value_line);
}
// Everything fits in the cache (at the moment this means everything
// fits in the first tile, which is a bit of a FIXME), so just put
// it there.
else {
self->tile_addresses[0] = self->cache;
size_t ii, jj;
for ( ii = 0 ; ii < self->tile_size ; ii++ ) {
for ( jj = 0 ; jj < self->tile_size ; jj++ ) {
self->tile_addresses[0][ii * self->tile_size + jj] = value;
}
}
}
return self;
}
// Swap the byte order of a 32 bit value, hopefully converting from
// big endian to little endian or vice versa. There is unfortunately
// some question whether or not this always works right for floating
// point values.
static void
swap_bytes_32 (unsigned char *in)
{
g_assert (sizeof (unsigned char) == 1);
int tmp = in[0];
in[0] = in[3];
in[3] = tmp;
tmp = in[1];
in[1] = in[2];
in[2] = tmp;
}
// Swap the byte order of a 16 bit value, hopefully converting from
// big endian to little endian or vice versa.
//static void
//swap_bytes_16 (unsigned char *in)
//{
// g_assert (sizeof (unsigned char) == 1);
// int tmp = in[0];
// in[0] = in[1];
// in[1] = tmp;
//}
FloatImage *
float_image_new_from_memory (ssize_t size_x, ssize_t size_y, float *buffer)
{
g_assert (size_x > 0 && size_y > 0);
// FIXME: this is an inefficient implementation.
FloatImage *self = float_image_new (size_x, size_y);
ssize_t ii, jj;
for ( ii = 0 ; ii < size_x ; ii++ ) {
for ( jj = 0 ; jj < size_y ; jj++ ) {
float_image_set_pixel (self, ii, jj, buffer[jj * size_x + ii]);
}
}
return self;
}
FloatImage *
float_image_copy (FloatImage *model)
{
g_assert (model->reference_count > 0); // Harden against missed ref=1 in new
// FIXME: this could obviously be optimized a lot by copying the
// existed tile file, etc.
FloatImage *self = float_image_new (model->size_x, model->size_y);
size_t ii, jj;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
float_image_set_pixel (self, jj, ii,
float_image_get_pixel (model, jj, ii));
}
}
return self;
}
// Bilinear interpolation for a point delta_x, delta_y from the lower
// left corner between values ul (upper left), ur (upper right), etc.
// The corner are considered to be corners of a unit square.
static float
bilinear_interpolate (double delta_x, double delta_y, float ul, float ur,
float ll, float lr)
{
float lv = ll + (lr - ll) * delta_x; // Lower value.
float uv = ul + (ur - ul) * delta_x; // Upper value.
return lv + (uv - lv) * delta_y;
}
FloatImage *
float_image_new_from_model_scaled (FloatImage *model, ssize_t scale_factor)
{
g_assert (model->reference_count > 0); // Harden against missed ref=1 in new
g_assert (model->size_x > 0 && model->size_y > 0);
g_assert (scale_factor > 0);
g_assert (scale_factor % 2 == 1);
FloatImage *self
= float_image_new (round ((double) model->size_x / scale_factor),
round ((double) model->size_y / scale_factor));
// Form an averaging kernel of the required size.
size_t kernel_size = scale_factor;
gsl_matrix_float *averaging_kernel
= gsl_matrix_float_alloc (kernel_size, kernel_size);
float kernel_value = 1.0 / ((float)kernel_size * kernel_size);
size_t ii, jj; // Index values.
for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {
for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {
gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);
}
}
// "Sample" the model by applying the averaging kernel, putting
// results into the new image.
size_t sample_stride = scale_factor;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
float pv = float_image_apply_kernel (model, jj * sample_stride,
ii * sample_stride,
averaging_kernel);
float_image_set_pixel (self, jj, ii, pv);
}
}
return self;
}
FloatImage *
float_image_new_subimage (FloatImage *model, ssize_t x, ssize_t y,
ssize_t size_x, ssize_t size_y)
{
g_assert (model->reference_count > 0); // Harden against missed ref=1 in new
// Upper left corner must be in model.
g_assert (x >= 0 && y >= 0);
// Size of image to be created must be strictly positive.
g_assert (size_x >= 1 && size_y >= 1);
// Given model must be big enough to allow a subimage of the
// requested size to fit.
g_assert (model->size_x <= SSIZE_MAX && model->size_y <= SSIZE_MAX);
g_assert (x + size_x <= (ssize_t) model->size_x);
g_assert (y + size_y <= (ssize_t) model->size_y);
FloatImage *self = float_image_new (size_x, size_y);
// Copy the image pixels from the model.
ssize_t ii, jj;
for ( ii = 0 ; ii < (ssize_t) self->size_x ; ii++ ) {
for ( jj = 0 ; jj < (ssize_t) self->size_y ; jj++ ) {
float pv = float_image_get_pixel (model, x + ii, y + jj);
float_image_set_pixel (self, ii, jj, pv);
}
}
return self;
}
// Return true iff file is size or larger.
static gboolean
is_large_enough (const char *file, off_t size)
{
struct stat stat_buffer;
#if GLIB_CHECK_VERSION(2, 6, 0)
int return_code = g_stat (file, &stat_buffer);
if ( return_code != 0 ) {
g_error ("Couldn't g_stat file %s: %s", file, strerror (errno));
}
#else
int return_code = stat (file, &stat_buffer);
if ( return_code != 0 ) {
g_error ("Couldn't stat file %s: %s", file, strerror (errno));
}
#endif
return stat_buffer.st_size >= size;
}
FloatImage *
float_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file,
off_t offset, float_image_byte_order_t byte_order)
{
g_assert (size_x > 0 && size_y > 0);
// Check in advance if the source file looks big enough (we will
// still need to check return codes as we read() data, of course).
//g_assert (is_large_enough (file, offset + ((off_t) size_x * size_y
// * sizeof (float))));
// Open the file to read data from.
FILE *fp = fopen (file, "rb");
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
FloatImage *self = float_image_new_from_file_pointer (size_x, size_y, fp,
offset, byte_order);
// Close file we read image from.
int return_code = fclose (fp);
g_assert (return_code == 0);
return self;
}
// Return true iff byte_order is not the native byte order on the
// current platform.
static gboolean
non_native_byte_order (float_image_byte_order_t byte_order)
{
return ((G_BYTE_ORDER == G_LITTLE_ENDIAN
&& byte_order == FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN)
|| (G_BYTE_ORDER == G_BIG_ENDIAN
&& byte_order == FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN));
}
FloatImage *
float_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y,
FILE *file_pointer, off_t offset,
float_image_byte_order_t byte_order)
{
g_assert (size_x > 0 && size_y > 0);
FloatImage *self = initialize_float_image_structure (size_x, size_y);
FILE *fp = file_pointer; // Convenience alias.
// Seek to the indicated offset in the file.
int return_code = FSEEK64 (fp, offset, SEEK_CUR);
g_assert (return_code == 0);
// If we need a tile file for an image of this size, we will load
// the data straight into it.
if ( self->tile_file != NULL ) {
// We will read the input image data in horizontal stips one tile
// high. Note that we probably won't be able to entirely fill the
// last tiles in each dimension with real data, since the image
// sizes rarely divide evenly by the numbers of tiles. So we fill
// it with zeros instead. The data off the edges of the image
// should never be accessed directly anyway.
// Some data for doing zero fill. If the tiles are bigger than
// the image itself, we need to make the available zero fill the
// size of the tile instead of the size of the file.
g_assert (self->tile_size <= SSIZE_MAX);
float *zero_line = g_new0 (float, (size_x > (ssize_t) self->tile_size ?
(size_t) size_x : self->tile_size));
g_assert (0.0 == 0x0);
// Buffer capable of holding a full strip.
float *buffer = g_new (float, self->tile_size * self->size_x);
// Reorganize data into tiles in tile oriented disk file.
size_t ii = 0;
for ( ii = 0 ; ii < self->tile_count_y ; ii++ ) {
asfPercentMeter((float)ii/(self->tile_count_y-1));
// The "effective_height" of the strip is the portion of the
// strip for which data actually exists. If the effective
// height is less than self->tile>size, we will have to add some
// junk to fill up the extra part of the tile (which should
// never be accessed).
size_t effective_height;
if ( ii < self->tile_count_y - 1
|| self->size_y % self->tile_size == 0 ) {
effective_height = self->tile_size;
}
else {
effective_height = self->size_y % self->tile_size;
}
// Total area of the current strip.
size_t strip_area = effective_height * self->size_x;
// Read one strip of tiles worth of data from the file.
size_t read_count = fread (buffer, sizeof (float), strip_area, fp);
g_assert (read_count == strip_area);
// Convert from the byte order on disk to the host byte order,
// if necessary. Doing this with floats is somewhat
// questionable apparently: major libraries don't seem to
// support it with their macros, and the perl documentation says
// it can't be done in a truly portable way... but it seems to
// work.
if ( non_native_byte_order (byte_order) ) {
// Floats better be four bytes for this to work.
g_assert (sizeof (float) == 4);
size_t idx;
for ( idx = 0 ; idx < strip_area ; idx++ ) {
swap_bytes_32 ((unsigned char *) &(buffer[idx]));
}
}
// Write data from the strip into the tile store.
size_t jj;
for ( jj = 0 ; jj < self->tile_count_x ; jj++ ) {
// This is roughly analogous to effective_height.
size_t effective_width;
if ( jj < self->tile_count_x - 1
|| self->size_x % self->tile_size == 0) {
effective_width = self->tile_size;
}
else {
effective_width = self->size_x % self->tile_size;
}
size_t write_count; // For return of fwrite() calls.
size_t kk;
for ( kk = 0 ; kk < effective_height ; kk++ ) {
write_count
= fwrite (buffer + kk * self->size_x + jj * self->tile_size,
sizeof (float), effective_width, self->tile_file);
// If we wrote less than expected,
if ( write_count < effective_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for FloatImage instance: "
"%s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
if ( effective_width < self->tile_size ) {
// Amount we have left to write to fill out the last tile.
size_t edge_width = self->tile_size - effective_width;
write_count = fwrite (zero_line, sizeof (float), edge_width,
self->tile_file);
// If we wrote less than expected,
if ( write_count < edge_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for FloatImage "
"instance: %s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
}
// Finish writing the bottom of the tile for which there is no
// image data (should only happen if we are on the last strip of
// tiles).
for ( ; kk < self->tile_size ; kk++ ) {
g_assert (ii == self->tile_count_y - 1);
write_count = fwrite (zero_line, sizeof (float), self->tile_size,
self->tile_file);
// If we wrote less than expected,
if ( write_count < self->tile_size ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for FloatImage instance: "
"%s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
}
}
// Did we write the correct total amount of data?
g_assert (FTELL64 (self->tile_file)
== (off_t) (self->tile_area * self->tile_count * sizeof (float)));
// Free temporary buffers.
g_free (buffer);
g_free (zero_line);
}
// Everything fits in the cache (at the moment this means everything
// fits in the first tile, which is a bit of a FIXME), so just put
// it there.
else {
self->tile_addresses[0] = self->cache;
size_t ii;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
// Address where the current row of pixels should end up.
float *row_address = self->tile_addresses[0] + ii * self->tile_size;
// Read the data.
size_t read_count = fread (row_address, sizeof (float), self->size_x,
fp);
g_assert (read_count == self->size_x);
// Convert from the byte order on disk to the host byte order,
// if necessary. Doing this with floats is somewhat
// questionable: major libraries don't seem to support it with
// their macros, and the perl documentation says it can't be
// done in a truly portable way... but it seems to work.
if ( non_native_byte_order (byte_order) ) {
g_assert (sizeof (float) == 4);
size_t jj;
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
swap_bytes_32 ((unsigned char *) &(row_address[jj]));
}
}
}
}
return self;
}
FloatImage *
float_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y,
ssize_t original_size_x,
ssize_t original_size_y,
const char *file, off_t offset,
float_image_byte_order_t byte_order)
{
g_assert (size_x > 0 && size_y > 0);
g_assert (original_size_x > 0 && original_size_y > 0);
// Image can only be scaled down with this routine, not up.
g_assert (size_x < original_size_x);
g_assert (size_y < original_size_y);
// Check in advance if the source file looks big enough (we will
// still need to check return codes as we read() data, of course).
g_assert (is_large_enough (file,
offset + ((off_t) original_size_x
* original_size_y
* sizeof (float))));
// Find the stride that we need to use in each dimension to evenly
// cover the original image space.
double stride_x = (size_x == 1 ? 0.0
: (double) (original_size_x - 1) / (size_x - 1));
double stride_y = (size_y == 1 ? 0.0
: (double) (original_size_y - 1) / (size_y - 1));
// Open the file to read data from.
FILE *fp = fopen (file, "rb");
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
// We will do a row at a time to save some possibly expensive
// seeking. So here we have an entire row worth of upper lefts,
// upper rights, etc.
float *uls = g_new (float, size_x);
float *urs = g_new (float, size_x);
float *lls = g_new (float, size_x);
float *lrs = g_new (float, size_x);
// Results of bilinear interpolation for the current row.
float *interpolated_values = g_new (float, size_x);
// We will write the reduced resolution version of the image into a
// temporary file so we can leverage the new_from_file method and
// avoid trying to stick the whole reduced resolution image in
// memory.
FILE *reduced_image = tmpfile ();
ssize_t ii, jj;
for ( ii = 0 ; ii < size_y ; ii++ ) {
size_t read_count; // For fread calls.
int return_code; // For FSEEK64 calls.
// Input image y index of row above row of interest.
ssize_t in_ray = floor (ii * stride_y);
// Due to the vagaries of floating point arithmetic, we might run
// past the index of our last pixel by a little bit, so we correct.
if ( in_ray >= original_size_y - 1 ) {
// We better not be much over the last index though.
g_assert (in_ray < original_size_y);
// The index should be an integer, so floor should fix us up.
in_ray = floor (in_ray);
g_assert (in_ray == original_size_y - 1);
}
g_assert (in_ray < original_size_y);
// Input image y index of row below row of interest. If we would
// be off the image, we just take the last row a second time, and
// let the interpolation work things out.
ssize_t in_rby;
if ( in_ray == original_size_y - 1 ) {
in_rby = in_ray;
}
else {
in_rby = in_ray + 1;
}
// Fetch the row above.
for ( jj = 0 ; jj < size_x ; jj++ ) {
// Input image indicies of current upper left corner pixel.
ssize_t in_ul_x = floor (jj * stride_x);
// Watch for floating point inexactness (see comment above).
if ( G_UNLIKELY (in_ul_x >= original_size_x - 1) ) {
g_assert (in_ul_x < original_size_x);
in_ul_x = floor (in_ul_x);
g_assert (in_ul_x == original_size_x - 1);
}
g_assert (in_ul_x < original_size_x);
size_t in_ul_y = in_ray;
off_t sample_offset
= offset + sizeof (float) * ((off_t) in_ul_y * original_size_x
+ in_ul_x);
return_code = FSEEK64 (fp, sample_offset, SEEK_SET);
g_assert (return_code == 0);
read_count = fread (&(uls[jj]), sizeof (float), 1, fp);
g_assert (read_count == 1);
// If the upper left pixel was the last pixel in the input image,
if ( in_ul_x == original_size_x - 1 ) {
// just treat it as the upper right as well,
urs[jj] = uls[jj];
}
// otherwise read the next pixel as the upper right pixel.
else {
read_count = fread (&(urs[jj]), sizeof (float), 1, fp);
g_assert (read_count == 1);
}
}
// Fetch the row below.
for ( jj = 0 ; jj < size_x ; jj++ ) {
// Input image indicies of the lower left corner pixel.
ssize_t in_ll_x = floor (jj * stride_x);
// Watch for floating point inexactness (see comment above).
if ( G_UNLIKELY (in_ll_x >= original_size_y - 1) ) {
g_assert (in_ll_x < original_size_x);
in_ll_x = floor (in_ll_x);
g_assert (in_ll_x == original_size_x - 1);
}
g_assert (in_ll_x < original_size_x);
size_t in_ll_y = in_rby;
off_t sample_offset
= offset + sizeof (float) * ((off_t) in_ll_y * original_size_x
+ in_ll_x);
return_code = FSEEK64 (fp, sample_offset, SEEK_SET);
g_assert (return_code == 0);
read_count = fread (&(lls[jj]), sizeof (float), 1, fp);
g_assert (read_count == 1);
// If the lower left pixel was the last pixel in the input image,
if ( in_ll_x == original_size_x - 1 ) {
// just treat it as the lower right as well,
lrs[jj] = lls[jj];
}
// otherwise read the next pixel as the lower right pixel.
else {
read_count = fread (&(lrs[jj]), sizeof (float), 1, fp);
g_assert (read_count == 1);
}
}
// If things aren't in the native byte order, we must byte swap them.
if ( non_native_byte_order (byte_order) ) {
for ( jj = 0 ; jj < size_x ; jj++ ) {
g_assert (sizeof (float) == 4);
swap_bytes_32 ((unsigned char *) &(uls[jj]));
swap_bytes_32 ((unsigned char *) &(urs[jj]));
swap_bytes_32 ((unsigned char *) &(lls[jj]));
swap_bytes_32 ((unsigned char *) &(lrs[jj]));
}
}
// Perform the interpolation.
for ( jj = 0 ; jj < size_x ; jj++ ) {
double delta_x = stride_x * jj - floor (stride_x * jj);
double delta_y = -(stride_y * ii - floor (stride_y * ii));
interpolated_values[jj] = bilinear_interpolate (delta_x, delta_y,
uls[jj], urs[jj],
lls[jj], lrs[jj]);
}
size_t write_count = fwrite (interpolated_values, sizeof (float), size_x,
reduced_image);
g_assert (write_count == (size_t) size_x);
}
// We are done with the temporary buffers.
g_free (interpolated_values);
g_free (lrs);
g_free (lls);
g_free (urs);
g_free (uls);
// Reposition to the beginning of the temporary file to fit with
// operation of new_from_file_pointer method.
int return_code = FSEEK64 (reduced_image, (off_t) 0, SEEK_SET);
g_assert (return_code == 0);
// The file we have written should be in host byte order, so we need
// to determine what that is so we can re-read it correctly.
float_image_byte_order_t host_byte_order;
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
host_byte_order = FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN;
#elif G_BYTE_ORDER == G_BIG_ENDIAN
host_byte_order = FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN;
#else
# error
#endif
// Slurp the scaled file back in as an instance.
FloatImage *self
= float_image_new_from_file_pointer (size_x, size_y, reduced_image,
(off_t) 0, host_byte_order);
// Now that we have an instantiated version of the image we are done
// with this temporary file.
return_code = fclose (reduced_image);
return self;
}
// Returns a new FloatImage, for the image corresponding to the given metadata.
FloatImage *
float_image_new_from_metadata(meta_parameters *meta, const char *file)
{
//return float_image_new_from_file(meta->general->sample_count,
// meta->general->line_count, file, 0,
// FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);
return float_image_band_new_from_metadata(meta, 0, file);
}
// Returns a new FloatImage, for the image band corresponding to the
// given metadata.
FloatImage *
float_image_band_new_from_metadata(meta_parameters *meta,
int band, const char *file)
{
int nl = meta->general->line_count;
int ns = meta->general->sample_count;
FILE * fp = FOPEN(file, "rb");
FloatImage * fi = float_image_new(ns, nl);
int i,j;
float *buf = MALLOC(sizeof(float)*ns);
for (i = 0; i < nl; ++i) {
get_float_line(fp, meta, i+band*nl, buf);
for (j = 0; j < ns; ++j)
if (meta->general->radiometry >= r_SIGMA_DB &&
meta->general->radiometry <= r_GAMMA_DB)
float_image_set_pixel(fi, j, i, pow(10, buf[j]/10.0));
else
float_image_set_pixel(fi, j, i, buf[j]);
asfPercentMeter((float)i/(float)(nl-1));
}
free(buf);
fclose(fp);
return fi;
}
// Copy the contents of tile with flattened offset tile_offset from
// the memory cache to the disk file. Its probably easiest to
// understand this function by looking at how its used.
static void
cached_tile_to_disk (FloatImage *self, size_t tile_offset)
{
// If we aren't using a tile file, this operation doesn't make
// sense.
g_assert (self->tile_file != NULL);
// We must have a legitimate tile_offset.
g_assert (tile_offset < self->tile_count);
// The tile we are trying to copy from cache to disk must be loaded
// in the cache for this operation to make sense.
g_assert (self->tile_addresses[tile_offset] != NULL);
int return_code
= FSEEK64 (self->tile_file,
(off_t) tile_offset * self->tile_area * sizeof (float),
SEEK_SET);
g_assert (return_code == 0);
size_t write_count = fwrite (self->tile_addresses[tile_offset],
sizeof (float), self->tile_area,
self->tile_file);
g_assert (write_count == self->tile_area);
}
// Return true iff tile (x, y) is already loaded into the memory cache.
static gboolean
tile_is_loaded (FloatImage *self, ssize_t x, ssize_t y)
{
g_assert ( x >= 0 && (size_t) x < self->tile_count_x
&& y >= 0 && (size_t) y < self->tile_count_y );
size_t tile_offset = self->tile_count_x * y + x;
return self->tile_addresses[tile_offset] != NULL;
}
// Load (currently unloaded) tile (x, y) from disk cache into memory
// cache, possibly displacing the oldest tile already loaded, updating
// the load order queue, and returning the address of the tile loaded.
static float *
load_tile (FloatImage *self, ssize_t x, ssize_t y)
{
// Make sure we haven't screwed up somehow and not created a tile
// file when in fact we should have.
g_assert (self->tile_file != NULL);
g_assert (!tile_is_loaded (self, x, y));
// Address into which tile gets loaded (to be returned).
float *tile_address;
// Offset of tile in flattened array.
size_t tile_offset = self->tile_count_x * y + x;
// We have to check and see if we have to displace an already loaded
// tile or not.
if ( self->tile_queue->length == self->cache_size_in_tiles ) {
// Displace tile loaded longest ago.
size_t oldest_tile
= GPOINTER_TO_INT (g_queue_pop_tail (self->tile_queue));
cached_tile_to_disk (self, oldest_tile);
tile_address = self->tile_addresses[oldest_tile];
self->tile_addresses[oldest_tile] = NULL;
}
else {
// Load tile into first free slot.
tile_address = self->cache + self->tile_queue->length * self->tile_area;
}
// Put the new tile address into the index, and put the index into
// the load order queue.
self->tile_addresses[tile_offset] = tile_address;
// Stash in queue by converting to a pointer (so it must fit in an int).
g_assert (tile_offset < INT_MAX);
g_queue_push_head (self->tile_queue,
GINT_TO_POINTER ((int) tile_offset));
// Load the tile data.
int return_code
= FSEEK64 (self->tile_file,
(off_t) tile_offset * self->tile_area * sizeof (float),
SEEK_SET);
g_assert (return_code == 0);
clearerr (self->tile_file);
size_t read_count = fread (tile_address, sizeof (float), self->tile_area,
self->tile_file);
if ( read_count < self->tile_area ) {
if ( ferror (self->tile_file) ) {
perror ("error reading tile cache file");
g_assert_not_reached ();
}
if ( feof (self->tile_file) ) {
fprintf (stderr,
"nothing left to read in tile cache file at offset %lld\n",
FTELL64 (self->tile_file));
g_assert_not_reached ();
}
}
g_assert (read_count == self->tile_area);
return tile_address;
}
float
float_image_get_pixel (FloatImage *self, ssize_t x, ssize_t y)
{
// Are we at a valid image pixel?
asfRequire (x >= 0 && (size_t) x < self->size_x,
"%d >= 0 && %d < %d\n"
"Invalid pixel index in the x dimension\n",
(int)x, (int)x, (int)(self->size_x));
asfRequire (y >= 0 && (size_t) y < self->size_y,
"%d >= 0 && %d < %d\n"
"Invalid pixel index in the y dimension\n",
(int)y, (int)y, (int)(self->size_y));
// Get the pixel coordinates, including tile and pixel-in-tile.
g_assert (sizeof (long int) >= sizeof (size_t));
ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);
// Offset of tile x, y, where tiles are viewed as pixels normally are.
size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;
// Address of data for tile containing pixel of interest (may still
// have to be loaded from disk cache).
float *tile_address = self->tile_addresses[tile_offset];
// Load the tile containing the pixel of interest if necessary.
if ( G_UNLIKELY (tile_address == NULL) ) {
tile_address = load_tile (self, pc_x.quot, pc_y.quot);
}
// Return pixel of interest.
return tile_address[self->tile_size * pc_y.rem + pc_x.rem];
}
void
float_image_set_pixel (FloatImage *self, ssize_t x, ssize_t y, float value)
{
// Are we at a valid image pixel?
g_assert (x >= 0 && (size_t) x <= self->size_x);
g_assert (y >= 0 && (size_t) y <= self->size_y);
// Get the pixel coordinates, including tile and pixel-in-tile.
g_assert (sizeof (long int) >= sizeof (size_t));
ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);
// Offset of tile x, y, where tiles are viewed as pixels normally are.
size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;
// Address of data for tile containing pixel of interest (may still
// have to be loaded from disk cache).
float *tile_address = self->tile_addresses[tile_offset];
// Load the tile containing the pixel of interest if necessary.
if ( G_UNLIKELY (tile_address == NULL) ) {
tile_address = load_tile (self, pc_x.quot, pc_y.quot);
}
// Set pixel of interest.
tile_address[self->tile_size * pc_y.rem + pc_x.rem] = value;
}
void
float_image_get_region (FloatImage *self, ssize_t x, ssize_t y, ssize_t size_x,
ssize_t size_y, float *buffer)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
g_assert (size_x >= 0);
g_assert (x >= 0);
g_assert ((size_t) x + (size_t) size_x - 1 < self->size_x);
g_assert (size_y >= 0);
g_assert (y >= 0);
g_assert ((size_t) y + (size_t) size_y - 1 < self->size_y);
ssize_t ii, jj; // Index variables.
for ( ii = 0 ; ii < size_y ; ii++ ) {
for ( jj = 0 ; jj < size_x ; jj++ ) {
// We are essentially returning a subimage from the big image.
// These are the indicies in the big image (self) of the current
// pixel.
size_t ix = x + jj, iy = y + ii;
buffer[ii * size_x + jj] = float_image_get_pixel (self, ix, iy);
}
}
}
void
float_image_set_region (FloatImage *self, size_t x, size_t y, size_t size_x,
size_t size_y, float *buffer)
{
g_assert_not_reached (); // Stubbed out for now.
self = self; x = x; y = y; size_x = size_x, size_y = size_y; buffer = buffer;
}
void
float_image_get_row (FloatImage *self, size_t row, float *buffer)
{
float_image_get_region (self, 0, row, self->size_x, 1, buffer);
}
float
float_image_get_pixel_with_reflection (FloatImage *self, ssize_t x, ssize_t y)
{
// Reflect at image edges as advertised.
if ( x < 0 ) {
x = -x;
}
else if ( (size_t) x >= self->size_x ) {
x = self->size_x - 2 - (x - self->size_x);
}
if ( y < 0 ) {
y = -y;
}
else if ( (size_t) y >= self->size_y ) {
y = self->size_y - 2 - (y - self->size_y);
}
return float_image_get_pixel (self, x, y);
}
void
float_image_statistics (FloatImage *self, float *min, float *max,
float *mean, float *standard_deviation, float mask)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
*min = FLT_MAX;
*max = -FLT_MAX;
// Buffer for one row of samples.
float *row_buffer = g_new (float, self->size_x);
// Its best to keep track of things internally using doubles in
// order to minimize error buildup.
double mean_as_double = 0;
double s = 0;
size_t sample_count = 0; // Samples considered so far.
size_t ii, jj;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
asfPercentMeter((double)ii/(double)(self->size_y));
float_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
float cs = row_buffer[jj]; // Current sample.
if ( !isnan (mask) && (gsl_fcmp (cs, mask, 0.00000000001) == 0) )
continue;
if ( G_UNLIKELY (cs < *min) ) { *min = cs; }
if ( G_UNLIKELY (cs > *max) ) { *max = cs; }
double old_mean = mean_as_double;
mean_as_double += (cs - mean_as_double) / (sample_count + 1);
s += (cs - old_mean) * (cs - mean_as_double);
sample_count++;
}
}
asfPercentMeter(1.0);
g_free (row_buffer);
if (*min == FLT_MAX || *max == -FLT_MAX)
asfPrintError ("Image did not contain any valid data!\n");
double standard_deviation_as_double = sqrt (s / (sample_count - 1));
g_assert (fabs (mean_as_double) <= FLT_MAX);
g_assert (fabs (standard_deviation_as_double) <= FLT_MAX);
*mean = mean_as_double;
*standard_deviation = standard_deviation_as_double;
}
int
float_image_band_statistics (FloatImage *self, meta_stats *stats,
int line_count, int band_no, float mask)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
stats->min = FLT_MAX;
stats->max = -FLT_MAX;
// Buffer for one row of samples.
float *row_buffer = g_new (float, self->size_x);
// Its best to keep track of things internally using doubles in
// order to minimize error buildup.
double mean_as_double = 0;
double s = 0;
size_t sample_count = 0; // Samples considered so far.
size_t ii, jj;
for ( ii = (band_no * line_count); // 0-ordered band number times lines is offset into image
ii < ((size_t)band_no+1) * line_count && ii < self->size_y;
ii++ )
{
asfPercentMeter( (double)(ii - band_no*line_count)/(double)line_count );
float_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
float cs = row_buffer[jj]; // Current sample.
if ( !isnan (mask) && (gsl_fcmp (cs, mask, 0.00000000001) == 0) )
continue;
if ( G_UNLIKELY (cs < stats->min) ) { stats->min = cs; }
if ( G_UNLIKELY (cs > stats->max) ) { stats->max = cs; }
double old_mean = mean_as_double;
mean_as_double += (cs - mean_as_double) / (sample_count + 1);
s += (cs - old_mean) * (cs - mean_as_double);
sample_count++;
}
}
asfPercentMeter(1.0);
g_free (row_buffer);
if (stats->min == FLT_MAX || stats->max == -FLT_MAX)
return 1;
double standard_deviation_as_double = sqrt (s / (sample_count - 1));
if (fabs (mean_as_double) > FLT_MAX ||
fabs (standard_deviation_as_double) > FLT_MAX)
return 1;
stats->mean = mean_as_double;
stats->std_deviation = standard_deviation_as_double;
return 0;
}
void
float_image_statistics_with_mask_interval (FloatImage *self, float *min,
float *max, float *mean,
float *standard_deviation,
double interval_start,
double interval_end)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
*min = FLT_MAX;
*max = -FLT_MAX;
// Buffer for one row of samples.
float *row_buffer = g_new (float, self->size_x);
// Its best to keep track of things internally using doubles in
// order to minimize error buildup.
double mean_as_double = 0;
double s = 0;
size_t sample_count = 0; // Samples considered so far.
size_t ii, jj;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
float_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
float cs = row_buffer[jj]; // Current sample.
// If in the mask interval, do not consider this pixel any further.
if ( cs >= interval_start && cs <= interval_end ) {
continue;
}
if ( G_UNLIKELY (cs < *min) ) { *min = cs; }
if ( G_UNLIKELY (cs > *max) ) { *max = cs; }
double old_mean = mean_as_double;
mean_as_double += (cs - mean_as_double) / (sample_count + 1);
s += (cs - old_mean) * (cs - mean_as_double);
sample_count++;
}
}
g_free (row_buffer);
if (*min == FLT_MAX || *max == -FLT_MAX)
asfPrintError ("Image did not contain any valid data!\n");
double standard_deviation_as_double = sqrt (s / (sample_count - 1));
g_assert (fabs (mean_as_double) <= FLT_MAX);
g_assert (fabs (standard_deviation_as_double) <= FLT_MAX);
*mean = mean_as_double;
*standard_deviation = standard_deviation_as_double;
}
void
float_image_approximate_statistics (FloatImage *self, size_t stride,
float *mean, float *standard_deviation,
float mask)
{
// Rows and columns of samples that fit in image given stride
// stride.
size_t sample_columns = ceil (self->size_x / stride);
size_t sample_rows = ceil (self->size_y / stride);
// Total number of samples.
size_t sample_count = sample_columns * sample_rows;
// Create an image holding the sample values.
FloatImage *sample_image = float_image_new (sample_columns, sample_rows);
// Load the sample values.
size_t current_sample = 0;
size_t ii;
for ( ii = 0 ; ii < sample_columns ; ii++ ) {
size_t jj;
for ( jj = 0 ; jj < sample_rows ; jj++ ) {
double sample = float_image_get_pixel (self, ii * stride, jj * stride);
float_image_set_pixel (sample_image, ii, jj, sample);
current_sample++;
}
}
// Ensure that we got the right number of samples in our image.
g_assert (current_sample == sample_count);
// Compute the exact statistics of the sampled version of the image.
// The _statistics method wants to compute min and max, so we let
// it, even though we don't do anything with them (since they are
// inaccurate).
float min, max;
float_image_statistics (sample_image, &min, &max, mean, standard_deviation,
mask);
float_image_free (sample_image);
}
void
float_image_approximate_statistics_with_mask_interval
(FloatImage *self, size_t stride, float *mean, float *standard_deviation,
double interval_start, double interval_end)
{
// This method is a trivial clone-and-modify of
// float_image_approximate_statistics, but it is totally untested at
// the moment.
g_assert_not_reached ();
// Rows and columns of samples that fit in image given stride
// stride.
size_t sample_columns = ceil (self->size_x / stride);
size_t sample_rows = ceil (self->size_y / stride);
// Total number of samples.
size_t sample_count = sample_columns * sample_rows;
// Create an image holding the sample values.
FloatImage *sample_image = float_image_new (sample_columns, sample_rows);
// Load the sample values.
size_t current_sample = 0;
size_t ii;
for ( ii = 0 ; ii < sample_columns ; ii++ ) {
size_t jj;
for ( jj = 0 ; jj < sample_rows ; jj++ ) {
double sample = float_image_get_pixel (self, ii * stride, jj * stride);
float_image_set_pixel (sample_image, ii, jj, sample);
current_sample++;
}
}
// Ensure that we got the right number of samples in our image.
g_assert (current_sample == sample_count);
// Compute the exact statistics of the sampled version of the image.
// The _statistics method wants to compute min and max, so we let
// it, even though we don't do anything with them (since they are
// inaccurate).
float min, max;
float_image_statistics_with_mask_interval (sample_image, &min, &max,
mean, standard_deviation,
interval_start, interval_end);
float_image_free (sample_image);
}
gsl_histogram *
float_image_gsl_histogram (FloatImage *self, float min, float max,
size_t num_bins)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
// Initialize the histogram.
gsl_histogram *hist = gsl_histogram_alloc (num_bins);
gsl_histogram_set_ranges_uniform (hist, min, max);
// Buffer for one row of samples.
float *row_buffer = g_new (float, self->size_x);
// Populate the histogram over every sample in the image.
size_t ii, jj;
for (ii = 0 ; ii < self->size_y ; ii++ ) {
float_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
gsl_histogram_increment (hist, row_buffer[jj]);
}
}
g_free (row_buffer);
return hist;
}
float
float_image_apply_kernel (FloatImage *self, ssize_t x, ssize_t y,
gsl_matrix_float *kernel)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
g_assert (x >= 0 && (size_t) x < self->size_x);
g_assert (y >= 0 && (size_t) y < self->size_y);
g_assert (kernel->size2 % 2 == 1);
g_assert (kernel->size2 == kernel->size1);
size_t ks = kernel->size2; // Kernel size.
float sum = 0; // Result.
size_t ii;
for ( ii = 0 ; ii < kernel->size1 ; ii++ ) {
ssize_t iy = y - ks / 2 + ii; // Current image y pixel index.
size_t jj;
for ( jj = 0 ; jj < kernel->size2 ; jj++ ) {
ssize_t ix = x - ks / 2 + jj; // Current image x pixel index
sum += (gsl_matrix_float_get (kernel, jj, ii)
* float_image_get_pixel_with_reflection (self, ix, iy));
}
}
return sum;
}
float
float_image_sample (FloatImage *self, float x, float y,
float_image_sample_method_t sample_method)
{
g_assert (x >= 0.0 && x <= (double) self->size_x - 1.0);
g_assert (y >= 0.0 && y <= (double) self->size_y - 1.0);
switch ( sample_method ) {
case FLOAT_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR:
return float_image_get_pixel (self, round (x), round (y));
break;
case FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR:
{
// Indicies of points we are interpolating between (x below, y
// below, etc., where below is interpreted in the numerical
// sense, not the image orientation sense.).
size_t xb = floor (x), yb = floor (y), xa = ceil (x), ya = ceil (y);
size_t ts = self->tile_size; // Convenience alias.
// Offset of xb, yb, etc. relative to tiles they lie in.
size_t xbto = xb % ts, ybto = yb % ts, xato = xa % ts, yato = ya % ts;
// Values of points we are interpolating between.
float ul, ur, ll, lr;
// If the points were are interpolating between don't span a
// tile edge, we load them straight from tile memory to save
// some time.
if ( G_LIKELY ( xbto != ts - 1 && xato != 0
&& ybto != ts - 1 && yato != 0) ) {
// The tile indicies.
size_t tx = xb / ts, ty = yb / ts;
// Tile offset in flattened list of tile addresses.
size_t tile_offset = ty * self->tile_count_x + tx;
float *tile_address = self->tile_addresses[tile_offset];
if ( G_UNLIKELY (tile_address == NULL) ) {
tile_address = load_tile (self, tx, ty);
}
ul = tile_address[ybto * self->tile_size + xbto];
ur = tile_address[ybto * self->tile_size + xato];
ll = tile_address[yato * self->tile_size + xbto];
lr = tile_address[yato * self->tile_size + xato];
}
else {
// We are spanning a tile edge, so we just get the pixels
// using the inefficient but easy get_pixel method.
ul = float_image_get_pixel (self, floor (x), floor (y));
ur = float_image_get_pixel (self, ceil (x), floor (y));
ll = float_image_get_pixel (self, floor (x), ceil (y));
lr = float_image_get_pixel (self, ceil (x), ceil (y));
}
// Upper and lower values interpolated in the x direction.
float ux = ul + (ur - ul) * (x - floor (x));
float lx = ll + (lr - ll) * (x - floor (x));
return ux + (lx - ux) * (y - floor (y));
}
break;
case FLOAT_IMAGE_SAMPLE_METHOD_BICUBIC:
{
static gboolean first_time_through = TRUE;
// Splines in the x direction, and their lookup accelerators.
static double *x_indicies;
static double *values;
static gsl_spline **xss;
static gsl_interp_accel **xias;
// Spline between splines in the y direction, and lookup accelerator.
static double *y_spline_indicies;
static double *y_spline_values;
static gsl_spline *ys;
static gsl_interp_accel *yia;
// All these splines have size 4.
const size_t ss = 4;
size_t ii; // Index variable.
if ( first_time_through ) {
// Allocate memory for the splines in the x direction.
x_indicies = g_new (double, ss);
values = g_new (double, ss);
xss = g_new (gsl_spline *, ss);
xias = g_new (gsl_interp_accel *, ss);
for ( ii = 0 ; ii < ss ; ii++ ) {
xss[ii] = gsl_spline_alloc (gsl_interp_cspline, ss);
xias[ii] = gsl_interp_accel_alloc ();
}
// Allocate memory for the spline in the y direction.
y_spline_indicies = g_new (double, ss);
y_spline_values = g_new (double, ss);
ys = gsl_spline_alloc (gsl_interp_cspline, ss);
yia = gsl_interp_accel_alloc ();
first_time_through = FALSE;
}
// Get the values for the nearest 16 points.
size_t jj; // Index variable.
for ( ii = 0 ; ii < ss ; ii++ ) {
for ( jj = 0 ; jj < ss ; jj++ ) {
x_indicies[jj] = floor (x) - 1 + jj;
values[jj]
= float_image_get_pixel_with_reflection (self, x_indicies[jj],
floor (y) - 1 + ii);
}
gsl_spline_init (xss[ii], x_indicies, values, ss);
}
// Set up the spline that runs in the y direction.
for ( ii = 0 ; ii < ss ; ii++ ) {
y_spline_indicies[ii] = floor (y) - 1 + ii;
y_spline_values[ii] = gsl_spline_eval (xss[ii], x, xias[ii]);
}
gsl_spline_init (ys, y_spline_indicies, y_spline_values, ss);
return (float) gsl_spline_eval (ys, y, yia);
}
break;
default:
g_assert_not_reached ();
return -42; // Reassure the compiler.
}
}
gboolean
float_image_equals (FloatImage *self, FloatImage *other, float epsilon)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
// Compare image sizes.
if ( self->size_x != other->size_x ) {
return FALSE;
}
if ( self->size_y != other->size_y ) {
return FALSE;
}
size_t sz_x = self->size_x; // Convenience alias.
size_t sz_y = self->size_y;
// Compare image pixels.
size_t ii, jj;
for ( ii = 0 ; ii < sz_y ; ii++ ) {
for ( jj = 0 ; jj < sz_x ; jj++ ) {
if ( G_UNLIKELY (gsl_fcmp (float_image_get_pixel (self, jj, ii),
float_image_get_pixel (other, jj, ii),
epsilon) != 0) ) {
return FALSE;
}
}
}
return TRUE;
}
// Flip an image about a horizontal line through the center of the image
void
float_image_flip_y(FloatImage *self)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
size_t ii, jj;
for (jj = 0; jj < self->size_y / 2; ++jj) {
size_t jj2 = self->size_y - 1 - jj;
for (ii = 0; ii < self->size_x; ++ii) {
float a = float_image_get_pixel(self, ii, jj);
float b = float_image_get_pixel(self, ii, jj2);
float_image_set_pixel(self, ii, jj, b);
float_image_set_pixel(self, ii, jj2, a);
}
}
}
// Flip an image about a vertical line through the center of the image
void
float_image_flip_x(FloatImage *self)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
size_t ii, jj;
for (ii = 0; ii < self->size_x / 2; ++ii) {
size_t ii2 = self->size_x - 1 - ii;
for (jj = 0; jj < self->size_y; ++jj) {
float a = float_image_get_pixel(self, ii, jj);
float b = float_image_get_pixel(self, ii2, jj);
float_image_set_pixel(self, ii, jj, b);
float_image_set_pixel(self, ii2, jj, a);
}
}
}
// Bring the tile cache file on the disk fully into sync with the
// latest image data stored in the memory cache.
static void
synchronize_tile_file_with_memory_cache (FloatImage *self)
{
// If we aren't using a tile file, this operation doesn't make
// sense.
g_assert (self->tile_file != NULL);
guint ii;
for ( ii = 0 ; ii < self->tile_queue->length ; ii++ ) {
size_t tile_offset = GPOINTER_TO_INT (g_queue_peek_nth (self->tile_queue,
ii));
cached_tile_to_disk (self, tile_offset);
}
}
void
float_image_freeze (FloatImage *self, FILE *file_pointer)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
FILE *fp = file_pointer; // Convenience alias.
g_assert (file_pointer != NULL);
size_t write_count = fwrite (&(self->size_x), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->size_y), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->cache_space), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->cache_area), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_size), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_count_x), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_count_y), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_count), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_area), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
// We don't bother serializing the cache -- its a pain to keep track
// of and probably almost never worth it.
// We write the tile queue pointer away, so that when we later thaw
// the serialized version, we can tell if a cache file is in use or
// not (if it isn't tile_queue will be NULL).
write_count = fwrite (&(self->tile_queue), sizeof (GQueue *), 1, fp);
g_assert (write_count == 1);
// If there was no cache file...
if ( self->tile_queue == NULL ) {
// We store the contents of the first tile and are done.
write_count = fwrite (self->tile_addresses[0], sizeof (float),
self->tile_area, fp);
if ( write_count < self->tile_area ) {
if ( ferror (fp) ) {
fprintf (stderr, "Error writing serialized FloatImage instance during "
"freeze: %s\n", strerror (errno));
exit (EXIT_FAILURE);
}
}
g_assert (write_count == self->tile_area);
}
// otherwise, the in memory cache needs to be copied into the tile
// file and the tile file saved in the serialized version of self.
else {
synchronize_tile_file_with_memory_cache (self);
float *buffer = g_new (float, self->tile_area);
size_t ii;
off_t tmp = FTELL64 (self->tile_file);
int return_code = FSEEK64 (self->tile_file, 0, SEEK_SET);
g_assert (return_code == 0);
for ( ii = 0 ; ii < self->tile_count ; ii++ ) {
size_t read_count = fread (buffer, sizeof (float), self->tile_area,
self->tile_file);
g_assert (read_count == self->tile_area);
write_count = fwrite (buffer, sizeof (float), self->tile_area, fp);
g_assert (write_count == self->tile_area);
}
return_code = FSEEK64 (self->tile_file, tmp, SEEK_SET);
g_assert (return_code == 0);
g_free (buffer);
}
}
int
float_image_band_store(FloatImage *self, const char *file,
meta_parameters *meta, int append_flag)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
// Give status
if (meta->general->band_count == 1)
asfPrintStatus("Storing image ...\n");
else
asfPrintStatus("Storing band ...\n");
// Establish byte order
/*
float_image_byte_order_t byte_order = 0;
if (strcmp(meta->general->system, "big_ieee") == 0)
byte_order = FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN;
else if (strcmp(meta->general->system, "lil_ieee") == 0)
byte_order = FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN;
*/
// Open the file to write to.
FILE *fp = fopen (file, append_flag ? "ab" : "wb");
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
// We will write the image data in horizontal stips one line at a time.
float *line_buffer = g_new (float, self->size_x);
// Sanity check
if (meta->general->line_count != (int)self->size_y ||
meta->general->sample_count != (int)self->size_x)
{
asfPrintError("Inconsistency between metadata and image!\n"
"Metadata says: %dx%d LxS, image has %dx%d\n"
"Possibly did not write metadata before storing image.\n",
meta->general->line_count, meta->general->sample_count,
self->size_y, self->size_x);
}
// Reorganize data into tiles in tile oriented disk file.
int ii;
for ( ii = 0 ; ii < (int)self->size_y ; ii++ ) {
float_image_get_row (self, ii, line_buffer);
// Write the data.
put_float_line(fp, meta, ii, line_buffer);
}
// Done with the line buffer.
g_free (line_buffer);
// Close file being written.
int return_code = fclose (fp);
g_assert (return_code == 0);
// Return success code.
return 0;
}
int
float_image_store (FloatImage *self, const char *file,
float_image_byte_order_t byte_order)
{
meta_parameters *meta;
meta = meta_read(file);
//float_image_byte_order_t meta_byte_order = 0;
//if (strcmp(meta->general->system, "big_ieee") == 0)
// meta_byte_order = FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN;
//else if (strcmp(meta->general->system, "lil_ieee") == 0)
// meta_byte_order = FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN;
//if (meta_byte_order != byte_order)
// asfPrintWarning("Passed-in byte order overriden by metadata!\n");
int ret = float_image_band_store(self, file, meta, 0);
meta_free(meta);
return ret;
}
/*
* JPEG ERROR HANDLING:
*
* Override the "error_exit" method so that control is returned to the
* library's caller when a fatal error occurs, rather than calling exit()
* as the standard error_exit method does.
*
* We use C's setjmp/longjmp facility to return control. This means that the
* routine which calls the JPEG library must first execute a setjmp() call to
* establish the return point. We want the replacement error_exit to do a
* longjmp(). But we need to make the setjmp buffer accessible to the
* error_exit routine. To do this, we make a private extension of the
* standard JPEG error handler object. (If we were using C++, we'd say we
* were making a subclass of the regular error handler.)
*
* Here's the extended error handler struct:
*/
struct my_error_mgr {
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct my_error_mgr * my_error_ptr;
METHODDEF(void)
my_error_exit (j_common_ptr cinfo)
{
/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
my_error_ptr myerr = (my_error_ptr) cinfo->err;
/* Always display the message. */
/* We could postpone this until after returning, if we chose. */
(*cinfo->err->output_message) (cinfo);
/* Return control to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
int
float_image_export_as_jpeg (FloatImage *self, const char *file,
size_t max_dimension, double mask)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
//size_t scale_factor; // Scale factor to use for output image.
float fscale_factor;
size_t scale_factor;
if ( self->size_x > self->size_y ) {
//scale_factor = ceil ((double) self->size_x / max_dimension);
fscale_factor = (float)self->size_x / (float)max_dimension;
}
else {
//scale_factor = ceil ((double) self->size_y / max_dimension);
fscale_factor = (float)self->size_y / (float)max_dimension;
}
// We want the scale factor to be odd, so that we can easily use a
// standard kernel to average things.
//if ( scale_factor % 2 == 0 ) {
//scale_factor++;
//}
// Output JPEG x and y dimensions.
scale_factor = (size_t)(fscale_factor + 0.5);
if (scale_factor < 1) {
// Someone tried to _grow_ the image rather than shrink it ...unsupported at this time!
asfPrintWarning("Maximum dimension that was selected is larger than the maximum\n"
"dimension in the image. Only scaling down is supported. Defaulting to a\n"
"scale factor of 1.0 (maintain original size.)\n");
}
scale_factor = scale_factor < 1 ? 1 : scale_factor;
size_t osx = (size_t)((float)self->size_x / (float)scale_factor);
size_t osy = (size_t)((float)self->size_y / (float)scale_factor);
while ((osx >= MIN_DIMENSION || osy >= MIN_DIMENSION) &&
(osx % 2 == 0 || osy % 2 == 0) &&
scale_factor != 1)
{
// Fine tune scale factor until output image dimensions are odd
// in both directions so an odd-sized filter kernel will fit (odd
// sized kernels have a center pixel)
fscale_factor += 0.25;
scale_factor = (size_t)(fscale_factor + 0.5);
osx = (size_t)((float)self->size_x / (float)scale_factor);
osy = (size_t)((float)self->size_y / (float)scale_factor);
}
asfRequire(osx >= MIN_DIMENSION || osy >= MIN_DIMENSION, "Output dimensions too small");
size_t kernel_size = scale_factor;
kernel_size = kernel_size % 2 ? kernel_size : kernel_size - 1;
// Number of pixels in output image.
size_t pixel_count = osx * osy;
// Pixels of the output image.
unsigned char *pixels = g_new (unsigned char, pixel_count);
JSAMPLE test_jsample; // For verifying properties of JSAMPLE type.
/* Here are some very funky checks to try to ensure that the JSAMPLE
really is the type we expect, so we can scale properly. */
g_assert (sizeof (unsigned char) == 1);
g_assert (sizeof (unsigned char) == sizeof (JSAMPLE));
test_jsample = 0;
test_jsample--;
g_assert (test_jsample == UCHAR_MAX);
// Stuff needed by libjpeg.
struct jpeg_compress_struct cinfo;
struct my_error_mgr jerr;
//cinfo.err = jpeg_std_error (&jerr);
jpeg_create_compress (&cinfo);
// Open output file.
FILE *fp = fopen (file, "wb");
if ( fp == NULL ) {
printf("Error opening file %s: %s\n", file, strerror(errno));
return FALSE;
}
/* We set up the normal JPEG error routines, then override error_exit. */
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object, close the input file, and return.
*/
jpeg_destroy_compress(&cinfo);
g_free(pixels);
fclose(fp);
return 1;
}
// Connect jpeg output to the output file to be used.
jpeg_stdio_dest (&cinfo, fp);
// Set image parameters that libjpeg needs to know about.
cinfo.image_width = osx;
cinfo.image_height = osy;
cinfo.input_components = 1; // Grey scale => 1 color component / pixel.
cinfo.in_color_space = JCS_GRAYSCALE;
jpeg_set_defaults (&cinfo); // Use default compression parameters.
// Reassure libjpeg that we will be writing a complete JPEG file.
jpeg_start_compress (&cinfo, TRUE);
// Gather image statistics so we know how to map image values into
// the output.
float min, max, mean, standard_deviation;
float_image_statistics (self, &min, &max, &mean, &standard_deviation, mask);
// If the statistics don't work, something is beastly wrong and we
// don't want to deal with it.
#ifndef solaris
#ifndef win32
// Solaris doesn't have isfinite().
g_assert (isfinite (min) && isfinite (max) && isfinite (mean)
&& isfinite (standard_deviation));
#endif
#endif
// If min == max, the pixel values are all the same. There is no
// reason to average or scale anything, so we don't. There is a
// good chance that the user would like zero to correspond to black,
// so we do that. Anything else will be pure white.
if ( min == max ) {
// FIXME: this path is broken. The trouble is that much of the
// stuff after this if branch shouldn't happen if we do this, but
// some of it should. So for now its disabled.
g_assert_not_reached ();
unsigned char oval; // Output value to use.
if ( min == 0.0 ) {
oval = 0;
}
else {
oval = UCHAR_MAX;
}
size_t ii, jj;
for ( ii = 0 ; ii < osy ; ii++ ) {
for ( jj = 0 ; jj < osx ; jj++ ) {
pixels[ii * osx + jj] = oval;
}
}
}
// Range of input pixel values which are to be linearly scaled into
// the output (values outside this range will be clamped).
double lin_min = mean - 2 * standard_deviation;
double lin_max = mean + 2 * standard_deviation;
// As advertised, we will average pixels together.
//g_assert (scale_factor % 2 != 0);
//size_t kernel_size = scale_factor;
gsl_matrix_float *averaging_kernel = NULL;
size_t ii, jj;
if (scale_factor > 1) {
averaging_kernel = gsl_matrix_float_alloc (kernel_size, kernel_size);
float kernel_value = 1.0 / ((float)kernel_size * kernel_size);
for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {
for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {
gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);
}
}
}
// Sample input image, putting scaled results into output image.
size_t sample_stride = scale_factor;
for ( ii = 0 ; ii < osy ; ii++ ) {
for ( jj = 0 ; jj < osx ; jj++ ) {
// Input image average pixel value.
float ival;
if (scale_factor > 1) {
ival = float_image_apply_kernel (self, jj * sample_stride,
ii * sample_stride,
averaging_kernel);
}
else if (scale_factor == 1) {
ival = float_image_get_pixel(self, jj, ii);
}
else {
asfPrintError("Invalid scale factor. Scale factor must be 1 or greater.\n");
}
unsigned char oval; // Output value.
if (!meta_is_valid_double(ival)) {
oval = 0;
}
else if ( ival < lin_min ) {
oval = 0;
}
else if ( ival > lin_max) {
oval = UCHAR_MAX;
}
else {
int oval_int
= round (((ival - lin_min) / (lin_max - lin_min)) * UCHAR_MAX);
// Make sure we haven't screwed up the scaling.
g_assert (oval_int >= 0 && oval_int <= UCHAR_MAX);
oval = oval_int;
}
pixels[ii * osx + jj] = oval;
}
}
if (averaging_kernel != NULL) gsl_matrix_float_free(averaging_kernel);
// Write the jpeg, one row at a time.
const int rows_to_write = 1;
JSAMPROW *row_pointer = g_new (JSAMPROW, rows_to_write);
while ( cinfo.next_scanline < cinfo.image_height ) {
int rows_written;
row_pointer[0] = &(pixels[cinfo.next_scanline * osx]);
rows_written = jpeg_write_scanlines (&cinfo, row_pointer, rows_to_write);
g_assert (rows_written == rows_to_write);
}
g_free (row_pointer);
// Finsh compression and close the jpeg.
jpeg_finish_compress (&cinfo);
int return_code = fclose (fp);
g_assert (return_code == 0);
jpeg_destroy_compress (&cinfo);
g_free (pixels);
return 0; // Return success indicator.
}
int
float_image_export_as_jpeg_with_mask_interval (FloatImage *self,
const char *file,
ssize_t max_dimension,
double interval_start,
double interval_end)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
size_t scale_factor; // Scale factor to use for output image.
if ( self->size_x > self->size_y ) {
scale_factor = ceil ((double) self->size_x / max_dimension);
}
else {
scale_factor = ceil ((double) self->size_y / max_dimension);
}
// We want the scale factor to be odd, so that we can easily use a
// standard kernel to average things.
if ( scale_factor % 2 == 0 ) {
scale_factor++;
}
// Output JPEG x and y dimensions.
size_t osx = self->size_x / scale_factor;
size_t osy = self->size_y / scale_factor;
// Number of pixels in output image.
size_t pixel_count = osx * osy;
// Pixels of the output image.
unsigned char *pixels = g_new (unsigned char, pixel_count);
JSAMPLE test_jsample; // For verifying properties of JSAMPLE type.
/* Here are some very funky checks to try to ensure that the JSAMPLE
really is the type we expect, so we can scale properly. */
g_assert (sizeof (unsigned char) == 1);
g_assert (sizeof (unsigned char) == sizeof (JSAMPLE));
test_jsample = 0;
test_jsample--;
g_assert (test_jsample == UCHAR_MAX);
// Stuff needed by libjpeg.
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error (&jerr);
jpeg_create_compress (&cinfo);
// Open output file.
FILE *fp = fopen (file, "wb");
if ( fp == NULL ) { perror ("error opening file"); }
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
// Connect jpeg output to the output file to be used.
jpeg_stdio_dest (&cinfo, fp);
// Set image parameters that libjpeg needs to know about.
cinfo.image_width = osx;
cinfo.image_height = osy;
cinfo.input_components = 1; // Grey scale => 1 color component / pixel.
cinfo.in_color_space = JCS_GRAYSCALE;
jpeg_set_defaults (&cinfo); // Use default compression parameters.
// Reassure libjpeg that we will be writing a complete JPEG file.
jpeg_start_compress (&cinfo, TRUE);
// Gather image statistics so we know how to map image values into
// the output.
float min, max, mean, standard_deviation;
float_image_statistics_with_mask_interval (self, &min, &max, &mean,
&standard_deviation,
interval_start,
interval_end);
// If the statistics don't work, something is beastly wrong and we
// don't want to deal with it.
#ifndef solaris
#ifndef win32
// Solaris doesn't have isfinite().
g_assert (isfinite (min) && isfinite (max) && isfinite (mean)
&& isfinite (standard_deviation));
#endif
#endif
// If min == max, the pixel values are all the same. There is no
// reason to average or scale anything, so we don't. There is a
// good chance that the user would like zero to correspond to black,
// so we do that. Anything else will be pure white.
if ( min == max ) {
// FIXME: this path seems to be broken somehow -- we end up with
// jpegs of size zero.
g_assert_not_reached ();
unsigned char oval; // Output value to use.
if ( min == 0.0 ) {
oval = 0;
}
else {
oval = UCHAR_MAX;
}
size_t ii, jj;
for ( ii = 0 ; ii < osy ; ii++ ) {
for ( jj = 0 ; jj < osx ; jj++ ) {
pixels[ii * osx + jj] = oval;
}
}
return 0;
}
// Range of input pixel values which are to be linearly scaled into
// the output (values outside this range will be clamped).
double lin_min = mean - 2 * standard_deviation;
double lin_max = mean + 2 * standard_deviation;
// As advertised, we will average pixels together.
g_assert (scale_factor % 2 != 0);
size_t kernel_size = scale_factor;
gsl_matrix_float *averaging_kernel
= gsl_matrix_float_alloc (kernel_size, kernel_size);
float kernel_value = 1.0 / ((float)kernel_size * kernel_size);
size_t ii, jj; // Index values.
for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {
for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {
gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);
}
}
// Sample input image, putting scaled results into output image.
size_t sample_stride = scale_factor;
for ( ii = 0 ; ii < osy ; ii++ ) {
for ( jj = 0 ; jj < osx ; jj++ ) {
// Input image average pixel value.
float ival = float_image_apply_kernel (self, jj * sample_stride,
ii * sample_stride,
averaging_kernel);
unsigned char oval; // Output value.
if ( ival < lin_min ) {
oval = 0;
}
else if ( ival > lin_max) {
oval = UCHAR_MAX;
}
else {
int oval_int
= round (((ival - lin_min) / (lin_max - lin_min)) * UCHAR_MAX);
// Make sure we haven't screwed up the scaling.
g_assert (oval_int >= 0 && oval_int <= UCHAR_MAX);
oval = oval_int;
}
pixels[ii * osx + jj] = oval;
}
}
// Write the jpeg, one row at a time.
const int rows_to_write = 1;
JSAMPROW *row_pointer = g_new (JSAMPROW, rows_to_write);
while ( cinfo.next_scanline < cinfo.image_height ) {
int rows_written;
row_pointer[0] = &(pixels[cinfo.next_scanline * osx]);
rows_written = jpeg_write_scanlines (&cinfo, row_pointer, rows_to_write);
g_assert (rows_written == rows_to_write);
}
g_free (row_pointer);
// Finsh compression and close the jpeg.
jpeg_finish_compress (&cinfo);
int return_code = fclose (fp);
g_assert (return_code == 0);
jpeg_destroy_compress (&cinfo);
g_free (pixels);
return 0; // Return success indicator.
}
int
float_image_export_as_tiff (FloatImage *self, const char *file,
size_t max_dimension, double mask)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
size_t scale_factor; // Scale factor to use for output image.
if ( self->size_x > self->size_y ) {
scale_factor = ceil ((double) self->size_x / max_dimension);
}
else {
scale_factor = ceil ((double) self->size_y / max_dimension);
}
// We want the scale factor to be odd, so that we can easily use a
// standard kernel to average things.
if ( scale_factor % 2 == 0 ) {
scale_factor++;
}
// Output JPEG x and y dimensions.
size_t osx = self->size_x / scale_factor;
size_t osy = self->size_y / scale_factor;
// Number of pixels in output image.
size_t pixel_count = osx * osy;
// Pixels of the output image.
unsigned char *pixels = g_new (unsigned char, pixel_count);
// Stuff needed by libtiff
TIFF *otif = NULL;
// Open output file.
otif = TIFFOpen(file, "wb");
if (otif == NULL ) {
asfPrintError("Error opening TIFF file %s: %s\n", file, strerror(errno));
return FALSE;
}
// Initialize the TIFF file
TIFFSetField(otif, TIFFTAG_SUBFILETYPE, 0);
TIFFSetField(otif, TIFFTAG_IMAGEWIDTH, osx);
TIFFSetField(otif, TIFFTAG_IMAGELENGTH, osy);
TIFFSetField(otif, TIFFTAG_BITSPERSAMPLE, 8); // byte greyscale
TIFFSetField(otif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
TIFFSetField(otif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(otif, TIFFTAG_SAMPLESPERPIXEL, 1);
TIFFSetField(otif, TIFFTAG_ROWSPERSTRIP, 1);
TIFFSetField(otif, TIFFTAG_XRESOLUTION, 1.0);
TIFFSetField(otif, TIFFTAG_YRESOLUTION, 1.0);
TIFFSetField(otif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_NONE);
TIFFSetField(otif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(otif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
// Gather image statistics so we know how to map image values into
// the output.
float min, max, mean, standard_deviation;
float_image_statistics (self, &min, &max, &mean, &standard_deviation, mask);
// If the statistics don't work, something is beastly wrong and we
// don't want to deal with it.
#ifndef solaris
#ifndef win32
// Solaris doesn't have isfinite().
g_assert (isfinite (min) && isfinite (max) && isfinite (mean)
&& isfinite (standard_deviation));
#endif
#endif
// If min == max, the pixel values are all the same. There is no
// reason to average or scale anything, so we don't. There is a
// good chance that the user would like zero to correspond to black,
// so we do that. Anything else will be pure white.
if ( min == max ) {
// FIXME: this path is broken. The trouble is that much of the
// stuff after this if branch shouldn't happen if we do this, but
// some of it should. So for now its disabled.
g_assert_not_reached ();
unsigned char oval; // Output value to use.
if ( min == 0.0 ) {
oval = 0;
}
else {
oval = UCHAR_MAX;
}
size_t ii, jj;
for ( ii = 0 ; ii < osy ; ii++ ) {
for ( jj = 0 ; jj < osx ; jj++ ) {
pixels[ii * osx + jj] = oval;
}
}
}
// Range of input pixel values which are to be linearly scaled into
// the output (values outside this range will be clamped).
double lin_min = mean - 2 * standard_deviation;
double lin_max = mean + 2 * standard_deviation;
// As advertised, we will average pixels together.
g_assert (scale_factor % 2 != 0);
size_t kernel_size = scale_factor;
gsl_matrix_float *averaging_kernel
= gsl_matrix_float_alloc (kernel_size, kernel_size);
float kernel_value = 1.0 / ((float)kernel_size * kernel_size);
size_t ii, jj; // Index values.
for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {
for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {
gsl_matrix_float_set (averaging_kernel, ii, jj, kernel_value);
}
}
// Sample input image, putting scaled results into output image.
size_t sample_stride = scale_factor;
for ( ii = 0 ; ii < osy ; ii++ ) {
for ( jj = 0 ; jj < osx ; jj++ ) {
// Input image average pixel value.
float ival = float_image_apply_kernel (self, jj * sample_stride,
ii * sample_stride,
averaging_kernel);
unsigned char oval; // Output value.
if (!meta_is_valid_double(ival)) {
oval = 0;
}
else if ( ival < lin_min ) {
oval = 0;
}
else if ( ival > lin_max) {
oval = UCHAR_MAX;
}
else {
int oval_int
= round (((ival - lin_min) / (lin_max - lin_min)) * UCHAR_MAX);
// Make sure we haven't screwed up the scaling.
g_assert (oval_int >= 0 && oval_int <= UCHAR_MAX);
oval = oval_int;
}
pixels[ii * osx + jj] = oval;
}
}
gsl_matrix_float_free(averaging_kernel);
// Write the tiff, one row at a time.
unsigned char *byte_line=NULL;
for (ii=0; ii<osy; ii++) {
byte_line = (unsigned char*)(&pixels[ii*osx]);
TIFFWriteScanline(otif, byte_line, ii, 0);
}
// Finalize the TIFF
if (otif != NULL) {
TIFFClose (otif);
}
g_free (pixels);
return 0; // Return success indicator.
}
int
float_image_export_as_csv (FloatImage *self, const char * filename)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
size_t ii, jj;
g_assert (self->size_x < 256);
g_assert (self->size_y < 256);
FILE *fout = fopen (filename, "wt");
if ( fout == NULL ) {
printf("Attempting to create csv file: %s\n", filename);
perror ("error opening file");
}
for (ii = 0; ii < self->size_x; ++ii) {
for (jj = 0; jj < self->size_y; ++jj) {
fprintf(fout, "%5.3f%c", float_image_get_pixel(self, ii, jj),
jj == self->size_y - 1 ? '\n' : ',');
}
}
fclose(fout);
return 0;
}
size_t
float_image_get_cache_size (FloatImage *self)
{
g_assert_not_reached (); // Stubbed out for now.
// Compiler reassurance.
self = self;
return 0;
}
void
float_image_set_cache_size (FloatImage *self, size_t size)
{
g_assert_not_reached (); // Stubbed out for now.
// Compiler reassurance.
self = self; size = size;
}
FloatImage *
float_image_ref (FloatImage *self)
{
g_assert (self->reference_count > 0); // Harden against missed ref=1 in new
self->reference_count++;
return self;
}
void
float_image_unref (FloatImage *self)
{
self->reference_count--;
if ( self->reference_count == 0 ) {
float_image_free (self);
}
}
void
float_image_free (FloatImage *self)
{
// Close the tile file (which shouldn't have to remove it since its
// already unlinked), if we were ever using it.
if ( self->tile_file != NULL ) {
int return_code = fclose (self->tile_file);
g_assert (return_code == 0);
}
// Deallocate dynamic memory.
g_free (self->tile_addresses);
// If we didn't need a tile file, we also won't have a tile queue.
if ( self->tile_queue != NULL ) {
g_queue_free (self->tile_queue);
}
g_free (self->cache);
if (self->tile_file_name) {
// On Windows (mingw), we delete the file now, since it isn't
// automatically deleted on close.
#ifdef win32
int return_code = unlink_tmp_file (self->tile_file_name->str);
g_assert (return_code == 0);
#endif
g_string_free(self->tile_file_name, TRUE);
}
g_free (self);
}
| {
"alphanum_fraction": 0.6352059688,
"avg_line_length": 34.4344978166,
"ext": "c",
"hexsha": "90d911df9b5ff1a56a549c0240d95f1df74ea4cd",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/libasf_raster/float_image.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/libasf_raster/float_image.c",
"max_line_length": 94,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/libasf_raster/float_image.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 25391,
"size": 94626
} |
// Copyright 2021 atframework
// Created by owent on 2016-05-21
#pragma once
#include <string>
#include <gsl/select-gsl.h>
#include <log/log_wrapper.h>
#include "atframe/atapp_config.h"
namespace atapp {
namespace protocol {
class atapp_log;
class atapp_log_category;
class atapp_log_sink;
} // namespace protocol
} // namespace atapp
namespace atapp {
class log_sink_maker {
public:
using log_reg_t = std::function<util::log::log_wrapper::log_handler_t(
util::log::log_wrapper &, int32_t, const ::atapp::protocol::atapp_log &,
const ::atapp::protocol::atapp_log_category &, const ::atapp::protocol::atapp_log_sink &)>;
private:
log_sink_maker();
~log_sink_maker();
public:
static LIBATAPP_MACRO_API gsl::string_view get_file_sink_name();
static LIBATAPP_MACRO_API log_reg_t get_file_sink_reg();
static LIBATAPP_MACRO_API gsl::string_view get_stdout_sink_name();
static LIBATAPP_MACRO_API log_reg_t get_stdout_sink_reg();
static LIBATAPP_MACRO_API gsl::string_view get_stderr_sink_name();
static LIBATAPP_MACRO_API log_reg_t get_stderr_sink_reg();
static LIBATAPP_MACRO_API gsl::string_view get_syslog_sink_name();
static LIBATAPP_MACRO_API log_reg_t get_syslog_sink_reg();
};
} // namespace atapp
| {
"alphanum_fraction": 0.7693535515,
"avg_line_length": 25.06,
"ext": "h",
"hexsha": "f3a3046d3dbbc8dae428d8474c6ded55f8438203",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z",
"max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "atframework/libatapp",
"max_forks_repo_path": "include/atframe/atapp_log_sink_maker.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"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": "atframework/libatapp",
"max_issues_repo_path": "include/atframe/atapp_log_sink_maker.h",
"max_line_length": 97,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "atframework/libatapp",
"max_stars_repo_path": "include/atframe/atapp_log_sink_maker.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z",
"num_tokens": 323,
"size": 1253
} |
/*
Simulation of a network of FitzHugh-Nagumo neurons, coupled by excitatory
chemical synapses, receiving decorrelated, random input spiketrains with
both excitatory and inhibitory components.
The simulation was written by Ekkehard Ullner in 2013.
This is a modified version of E.U.'s original, stand-alone program,
for use as a library (e.g. via the ctypes ffi in Python).
Changelog:
- Various simulation parameters are exposed (to allow arbitrary network topologies,
input patterns, neuron parameters etc.)
- results are written to a provided buffer instead of text files
- the non-free and problematic[0] "Numerical Recipes" RAN1 random number generator
was replaced with a Mersenne Twister rng from the GNU scientific library.
- cosmetics and a minimum of documentation (i.e. the comments)
C Korndoerfer 2014
[0 "Random Numbers in Scientific Computing: An Introduction", Katzgraber, 2010
http://arxiv.org/pdf/1005.4117.pdf]
The MIT License (MIT)
Copyright (c) 2013,2014 Ekkehard Ullner, Clemens Korndörfer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICU
LAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <time.h>
#include <assert.h>
void sagwas(){
puts("simulation version Oct 12 2016");
}
/* function simulate
* ------------------
* Runs a single network simulation with the given parameters and writes the resulting
* voltage traces into a given buffer.
*
* Parameters:
*
* N: Number of rows i in the simulated grid of neurons. (regardless of network topology,
* the network is a 'grid' where each node is adressed by an (i,j) coordinate.)
* M: number of columns j in the grid
*
* limit: max. simulation time
* rec_resolution: to store only every ~'th simulation step.
*
* KT: maximum number of coupled neighbors of any node (degree of the network)
* connection: function pointer, where
* connection(i,j,l, '0' | '1') must return the first (second) coordinate of the l'th afferent to cell ij
* connection(i,j,l, 's') must return the strength of that connection
*
* outputbuffer: array of shape (M,N,limit) in which simulation results will be written in row first order
*
* inputc: array of shape (M,N) in row-first order. modulates the rate of input pulses fed into
* each cell, values within [0,1]. aka "the stimulus".
* laminex: firing rate "lambda_in,ex", the base rate of excitatory input spikes modulated by inputc
* lamini: firing rate "lambda_in,in", the base rate of inhibitory input spikes modulated by inputc
*
* double fhn_a: parameter a of the FHN neuron
* double fhn_eps: parameter epsilon of the FHN neuron
*
* double con_upstr_exc: synapse conductance "g^{up,ex}" of the excitatory random external inputs.
* double con_upstr_inh: synapse conductance "g^{up,in}" of the inhibitory random external inputs.
*
* seed: a random seed > 0
*
* delta_t : integration step width
*
* Return: None (simulation results are passed back as a side effect, by filling the provided output buffer)
*/
void simulate(int M,
int N,
int limit,
int rec_resolution,
int KT,
double (*connection)(int,int,int,char),
double* outputbuffer,
double* debug_outbuf,
double* inputc_exc,
double* inputc_inh,
double laminex,
double lamini,
double fhn_a,
double fhn_eps,
double con_upstr_exc,
double con_upstr_inh,
double taus,
double alp,
double bet,
double tauni,
double ani,
double bni,
double tauna,
double ana,
double bna,
int seed,
int verbose,
double delta_t){
// say hello & show the current input pattern.
if (verbose){
printf(" simulation with seed %d\n",seed);
printf("laminex: %f\nlamini: %f\nfhn_a: %f\nfhn_eps: %f\ncon_upstr_exc: %f\ncon_upstr_inh: %f\ntaus: %f\nalp: %f\
\nbet: %f\ntauni: %f\nani: %f\nbni: %f\ntauna: %f\nana: %f\nbna: %f\n", laminex, lamini, fhn_a, fhn_eps, con_upstr_exc,
con_upstr_inh, taus, alp, bet, tauni, ani, bni, tauna, ana, bna);
int i1,j1;
int print_exc, print_inh;
for (j1 = 0; j1<M; j1++ ){
for (i1 = 0; i1<N; i1++ ){
print_exc = inputc_exc[i1 + N*j1] > 0;
print_inh = inputc_inh[i1 + N*j1] > 0;
if (print_exc && print_inh) printf(" ±");
else if (print_exc) printf(" +");
else if (print_inh) printf(" -");
else printf(" .");
}
printf("\n");
}
}
assert(seed>0);
gsl_rng* rng = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(rng, seed);
// Initialisations & constant parameters:
// neuron model:
double xold[N][M],xh[N][M],xnew[N][M]; // activation variable (previous value, intermediate value, new value)
double yold[N][M],yh[N][M],ynew[N][M]; // recovery variable (previous value, intermediate value, new value)
double Isyn[N][M], Ihsyn[N][M]; // lateral input current (Ihsyn: intermediate value)
// lateral synapses:
double rold[N][M],rh[N][M],rnew[N][M]; // fraction of open receptors (previous value, intermediate value, new value).
// more precisely: r[i][j] is the fraction of open receptors at synapses anywhere in the network
// that are the target of neuron (i,j). Since all synapses have the same rise and decay constants
// alpha and beta, the effect of a spike at neuron i,j is the same at all of its target synapses.
// We can therefore write the fractions of open receptors of all these target synapses as a
// single variable r[i][j], associated with the source neuron i,j.
double Tl[N][M]; // spike arrival times "T_j" (indexing follows the same logic as r[][])
double Hs[N][M]; // transmitter concentrations "[T]_j" (...here, too)
double Vsyn = 0.0; // synaptic reversal potential
// double taus = 0.01; // duration of transmitter presence after spike
double Tm = 1.0; // maximum transmitter concentration
// double alp = 8.0; // rising time constant of fraction of open receptors
// double bet = 8.0; // decay time constant of fraction of open receptors
// activatory external input synapses:
double rnoa[N][M],rnha[N][M],rnna[N][M]; // fraction of open receptors
double Tnla[N][M],Hna[N][M]; // spike arrival times and transmitter concentrations
double Vna = 0.0; // synaptic reversal potential
// double tauna = 0.01; // duration of transmitter presence after spike
double Tna = 1.0; // maximum transmitter concentration
// double ana = 8.0; // rising time constant of fraction of open receptors
// double bna = 8.0; // decay time constant of fraction of open receptors
// inhibitory external input synapses:
double rnoi[N][M],rnhi[N][M],rnni[N][M]; // fraction of open receptors (previous value, intermediate value, new value)
double Tnli[N][M],Hni[N][M]; // spike arrival times and transmitter concentrations
double Vni = - 2.1; // synaptic reversal potential
// double tauni = 0.01; // duration of transmitter presence after spike
double Tni = 1.0; // maximum transmitter concentration
// double ani = 8.0; // rising time constant of fraction of open receptors
// double bni = 8.0; // decay time constant of fraction of open receptors
// misc:
double xth = 1.0; // spike detection threshold
long step; // simulation step count
// double delta_t = 0.001; // integration step width
// double delta_t = 0.01; // integration step width
double current_time = 0.0; // simulation time, in some irrelevant real - numbered unit
long i,j,l; // various loop variables over network nodes. don't ask me why those were chosen as long ints.
int p1[N][M][KT],p2[N][M][KT]; // lookup tables holding the first (p1) and second (p2) coordinate of the KT'th afferent to neuron N,M
float conductance_net[N][M][KT]; // lookup table: synapse conductance of the KT'th afferent to neuron N,M
double in_exc[N][M]; // excitatory stimulus strength (input noise rate modulation) for neuron N,M
double in_inh[N][M]; // inhibitory ...
// remaining initialisations:
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
in_exc[i][j] = inputc_exc[i + N * j];
in_inh[i][j] = inputc_inh[i + N * j];
xold[i][j] = -1.05 + 0.2 * (gsl_rng_uniform(rng) - 0.5);
yold[i][j] = -0.66 + 0.2 * (gsl_rng_uniform(rng) - 0.5);
rold[i][j] = 0.0;
rnoa[i][j] = 0.0;
rnoi[i][j] = 0.0;
Tl[i][j] = -2 * taus;
Hs[i][j] = 0.0;
Isyn[i][j] = 0.0;
Ihsyn[i][j] = 0.0;
Tnla[i][j] = -2 * tauna;
Tnli[i][j] = -2 * tauni;
Hna[i][j] = 0.0;
Hni[i][j] = 0.0;
// network connectivity lookup tables:
for (l = 0;l<KT;l++ ){
p1[i][j][l] = (int)connection(j,i,l,'0');
p2[i][j][l] = (int)connection(j,i,l,'1');
conductance_net[i][j][l] = connection(j,i,l,'s');
}}}
// begin stepwise integration.
for(step = 1;step<= limit;step++ ){
if (verbose && (step % (limit/100) == 0)){
printf("\r...%d%%",(int)(100 * step/(double)limit));
fflush(stdout);
}
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
// set transmitter presence if there was a spike recently,
// ...for synapses within the network..
if (Tl[i][j] + taus>current_time) Hs[i][j] = 1.0 * Tm;
else Hs[i][j] = 0.0;
// ..for activatory external input synapses..
if (Tnla[i][j] + tauna>current_time) Hna[i][j] = 1.0 * Tna;
else Hna[i][j] = 0.0;
// ..and for inhibitory external input synapses.
if (Tnli[i][j] + tauni>current_time) Hni[i][j] = 1.0 * Tni;
else Hni[i][j] = 0.0;
// collect lateral synaptic currents (for first integration step)
Isyn[i][j] = 0.0;
for (l = 0;l<KT;l++ ){
if(p1[i][j][l]<N && p2[i][j][l]<M)
Isyn[i][j] += conductance_net[i][j][l] * rold[p1[i][j][l]][p2[i][j][l]] * (xold[i][j] - Vsyn);
// Here, we add input currents to neuron (i,j) that depend mostly on
// r[ p1[i][j][l] ][ p2[i][j][l] ], that is, on the fraction of open
// receptors of those synapses targeted by neighbours projecting
// to neuron i,j. These synapses have a high fraction of open receptors
// if their source neuron recently fired a spike. Thus, input currents
// flow to neuron (i,j) if its neighbours have recently fired a spike.
}
}}
// first integration step
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
//FHN neuron: eps * (dx/dt) = x - x^3 / 3 - y
xh[i][j] = xold[i][j] + ( (1./fhn_eps) * (xold[i][j] - xold[i][j] * xold[i][j] * xold[i][j]/3. - yold[i][j]) ) * delta_t;
xh[i][j] += - (1./fhn_eps) * Isyn[i][j] * delta_t;
//FHN neuron: (dy/dt) = x + a
yh[i][j] = yold[i][j] + (xold[i][j] + fhn_a) * delta_t;
// fraction of open receptors.. dr/dt = alpha [T] (1 - r) - beta r
// ..of synapses within the network:
rh[i][j] = rold[i][j] + (alp * Hs[i][j] * (1 - rold[i][j]) - bet * rold[i][j]) * delta_t;
// ..of synapses receiving external noise, activatory:
rnha[i][j] = rnoa[i][j] + (ana * Hna[i][j] * (1 - rnoa[i][j]) - bna * rnoa[i][j]) * delta_t;
// ..of synapses receiving external noise, inhibitory:
rnhi[i][j] = rnoi[i][j] + (ani * Hni[i][j] * (1 - rnoi[i][j]) - bni * rnoi[i][j]) * delta_t;
// directly add input currents from the external noise synapses to the neuron's activation variable:
xh[i][j] -= (1./fhn_eps) * con_upstr_exc * rnoa[i][j] * (xold[i][j] - Vna) * delta_t;
xh[i][j] -= (1./fhn_eps) * con_upstr_inh * rnoi[i][j] * (xold[i][j] - Vni) * delta_t;
}}
// collect updated lateral synaptic currents
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
Ihsyn[i][j] = 0.0;
for (l = 0;l<KT;l++ ){
if(p1[i][j][l]<N && p2[i][j][l]<M)
Ihsyn[i][j] += conductance_net[i][j][l] * rh[p1[i][j][l]][p2[i][j][l]] * (xh[i][j] - Vsyn);
}
}}
// second integration step
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
//FHN neuron: eps * (dx/dt) = x - x^3 / 3 - y
xnew[i][j] = xold[i][j] + 0.5 * ((1./fhn_eps) * (xold[i][j] - xold[i][j] * xold[i][j] * xold[i][j]/3. - yold[i][j] + xh[i][j] - xh[i][j] * xh[i][j] * xh[i][j]/3. - yh[i][j])) * delta_t;
xnew[i][j] += - (1./fhn_eps) * 0.5 * (Isyn[i][j] + Ihsyn[i][j]) * delta_t;
//FHN neuron: (dy/dt) = x + a
ynew[i][j] = yold[i][j] + 0.5 * (xold[i][j] + fhn_a + xh[i][j] + fhn_a) * delta_t;
// fraction of open receptors.. dr/dt = alpha [T] (1 - r) - beta r
// ..of synapses within the network:
rnew[i][j] = rold[i][j] + 0.5 * (alp * Hs[i][j] * (1 - rold[i][j]) - bet * rold[i][j] + alp * Hs[i][j] * (1 - rh[i][j]) - bet * rh[i][j]) * delta_t;
// ..of synapses receiving external noise, activatory:
rnna[i][j] = rnoa[i][j] + 0.5 * (ana * Hna[i][j] * (1 - rnoa[i][j]) - bna * rnoa[i][j] + ana * Hna[i][j] * (1 - rnha[i][j]) - bna * rnha[i][j]) * delta_t;
// ..of synapses receiving external noise, inhibitory:
rnni[i][j] = rnoi[i][j] + 0.5 * (ani * Hni[i][j] * (1 - rnoi[i][j]) - bni * rnoi[i][j] + ani * Hni[i][j] * (1 - rnhi[i][j]) - bni * rnhi[i][j]) * delta_t;
// directly add input currents from the external noise synapses to the neuron's activation variable:
xnew[i][j] -= 0.5 * (1./fhn_eps) * con_upstr_exc * (rnoa[i][j] * (xold[i][j] - Vna) + rnha[i][j] * (xh[i][j] - Vna)) * delta_t;
xnew[i][j] -= 0.5 * (1./fhn_eps) * con_upstr_inh * (rnoi[i][j] * (xold[i][j] - Vni) + rnhi[i][j] * (xh[i][j] - Vni)) * delta_t;
}}
// identify spike times & prepare next step
current_time = delta_t * step;
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
// note spike times within the network
if(xold[i][j]<xth && xnew[i][j] >= xth){
Tl[i][j] = current_time;
}
// sample random spike times for activatory external input
if(gsl_rng_uniform(rng) <= (laminex * (double)in_exc[i][j]) * delta_t){
Tnla[i][j] = current_time;
}
// sample random spike times for inhibitory external input
if(gsl_rng_uniform(rng)<= (lamini * (double)in_inh[i][j]) * delta_t){
Tnli[i][j] = current_time;
}
// swap
xold[i][j] = xnew[i][j];
yold[i][j] = ynew[i][j];
rold[i][j] = rnew[i][j];
rnoa[i][j] = rnna[i][j];
rnoi[i][j] = rnni[i][j];
}}
// write the current network state into the provided output buffer.
// This is a 3D array of shape (M,N,limit) in row first order,
// so it has strides proportional to (N * limit, limit, 1).
// ..and we write only every rec_resolution'th step.
int limit_rec = limit/rec_resolution;
if (step % rec_resolution == 0) {
int linearind = 0;
for(int oi = 0; oi < M; oi++ ) {
for(int oj = 0; oj < N; oj++ ) {
linearind = oi * limit_rec * N + oj * limit_rec + (step/rec_resolution) - 1;
outputbuffer[linearind] = xnew[oj][oi];
debug_outbuf[linearind] = ynew[oj][oi];
}
}
}
} // end of integration loop
if (verbose){
printf("\033[2K");
fflush(stdout);
}
gsl_rng_free(rng);
}
// helper function to play with the random number generator.
void rantest(long seed,int N,double * out){
gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); // initialize a mersenne twister rng
gsl_rng_set(rng, seed); // seed it
double number = - 1;
for(int i = 0; i<N; i++ ){
number = gsl_rng_uniform(rng); // sample a number
printf("%ld %f\n",seed,number);
out[i] = number;
}
puts(" - - - ");
gsl_rng_free(rng);
}
| {
"alphanum_fraction": 0.556861673,
"avg_line_length": 44.3932038835,
"ext": "c",
"hexsha": "c1431d162198541461c65b9a8ad23c341ba62f3e",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-12-21T13:40:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-19T14:21:23.000Z",
"max_forks_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cknd/synchrony",
"max_forks_repo_path": "libHC/ekkesim/src/simulation.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "cknd/synchrony",
"max_issues_repo_path": "libHC/ekkesim/src/simulation.c",
"max_line_length": 203,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cknd/synchrony",
"max_stars_repo_path": "libHC/ekkesim/src/simulation.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-08T20:59:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-16T11:32:03.000Z",
"num_tokens": 5370,
"size": 18290
} |
/* Starting from version 7.8, MATLAB BLAS expects ptrdiff_t arguments for integers */
#if MATLAB_VERSION >= 0x0708
#include <stddef.h>
#include <stdlib.h>
#endif
#include <string.h>
/* Define MX_HAS_INTERLEAVED_COMPLEX for version <9.4 */
#ifndef MX_HAS_INTERLEAVED_COMPLEX
#define MX_HAS_INTERLEAVED_COMPLEX 0
#endif
/* Starting from version 7.6, MATLAB BLAS is seperated */
#if MATLAB_VERSION >= 0x0705
#include <blas.h>
#else
#define dcabs1 FORTRAN_WRAPPER(dcabs1)
extern doublereal dcabs1(
doublereal *z
);
#endif
#include <lapack.h>
#include "f2c.h"
#define cgeqpb FORTRAN_WRAPPER(cgeqpb)
int cgeqpb(integer *, integer *, integer *, integer *,
complex *, integer *, complex *, integer *, integer *,
real *, real *, integer *, real *, complex *, integer *,
real *, integer *);
#define cgeqpc FORTRAN_WRAPPER(cgeqpc)
int cgeqpc(integer *, integer *, integer *, integer *, complex *,
integer *, complex *, integer *, integer *, integer *, real *,
integer *, integer *, complex *, complex *, real *, real *,
complex *, integer *, real *);
#define cgeqpw FORTRAN_WRAPPER(cgeqpw)
int cgeqpw(integer *, integer *, integer *, integer *, integer *,
complex *, integer *, integer *, real *, complex *, real *, real *,
complex *, complex *, real *);
#define cgeqpx FORTRAN_WRAPPER(cgeqpx)
int cgeqpx(integer*, integer*, integer*, integer*, complex*,
integer*, complex*, integer*, integer*, real*, real*, integer*,
real*, complex*, integer*, real*, integer*);
#define cgeqpy FORTRAN_WRAPPER(cgeqpy)
int cgeqpy(integer*, integer*, integer*, integer*, complex*,
integer*, complex*, integer*, integer*, real*, real*, integer*,
real*, complex*, integer*, real*, integer*);
#define clasmx FORTRAN_WRAPPER(clasmx)
doublereal clasmx(integer *);
#define clauc1 FORTRAN_WRAPPER(clauc1)
logical clauc1(integer *, complex *, real *, complex *, complex *, real *);
#define ctrqpx FORTRAN_WRAPPER(ctrqpx)
int ctrqpx(integer *, integer *, integer *, integer *, complex *,
integer *, complex *, integer *, integer *, real *, real *,
integer *, real *, complex *, real *, integer *);
#define ctrqpy FORTRAN_WRAPPER(ctrqpy)
int ctrqpy(integer *, integer *, integer *, integer *,
complex *, integer *, complex *c, integer *, integer *,
real *, real *, integer *, real *, complex *, real *, integer *);
#define ctrqxc FORTRAN_WRAPPER(ctrqxc)
int ctrqxc(integer *, integer *, integer *, integer *, complex *,
integer *, complex *, integer *, integer *, integer *, real *,
real *, real *, complex *, real *, integer *);
#define cglbif FORTRAN_WRAPPER(cglbif)
int cglbif(integer *, integer *, integer *, integer *,
complex *, integer *, complex *, integer *, integer *,
real *, integer *, logical *, complex *, real *, integer *);
#define ccniif FORTRAN_WRAPPER(ccniif)
int ccniif(integer *, integer *, integer *, integer *,
complex *, integer *, complex *, integer *, integer *,
real *, real *, integer *, logical *, complex *, real *, integer *);
#define cgret FORTRAN_WRAPPER(cgret)
int cgret(integer *, integer *, integer *, integer *,
complex *, integer *, complex *, integer *, complex *,
real *, integer *);
#define shess FORTRAN_WRAPPER(shess)
int chess(integer *, integer *, integer *, integer *,
complex *, integer *, complex *, integer *,
complex *, real *, integer *);
#define ctrqyc FORTRAN_WRAPPER(ctrqyc)
int ctrqyc(integer *, integer *, integer *, integer *,
complex *, integer *, complex *, integer *, integer *,
integer *, real *, real *, real *, complex *, real *, integer *);
#define ctrrnk FORTRAN_WRAPPER(ctrrnk)
int ctrrnk(integer *, complex *, integer *, real *, integer *, complex *, integer *);
#define dgeqpb FORTRAN_WRAPPER(dgeqpb)
int dgeqpb(integer *, integer *, integer *,
integer *, doublereal *, integer *, doublereal *, integer *,
integer *, doublereal *, doublereal *, integer *, doublereal *,
doublereal *, integer *, integer *);
#define dgeqpc FORTRAN_WRAPPER(dgeqpc)
int dgeqpc(integer *, integer *, integer *,
integer *, doublereal *, integer *, doublereal *, integer *,
integer *, integer *, doublereal *, integer *, integer *,
doublereal *, doublereal *, doublereal *, doublereal *,
doublereal *, integer *);
#define dgeqpw FORTRAN_WRAPPER(dgeqpw)
int dgeqpw(integer *, integer *, integer *,
integer *, integer *, doublereal *, integer *, integer *,
doublereal *, doublereal *, doublereal *, doublereal *,
doublereal *, doublereal *);
#define dgeqpx FORTRAN_WRAPPER(dgeqpx)
int dgeqpx(integer*, integer*, integer*, integer*, doublereal*,
integer*, doublereal*, integer*, integer*, doublereal*,
doublereal*, integer*, doublereal*, doublereal*, integer*,
integer*);
#define dgeqpy FORTRAN_WRAPPER(dgeqpy)
int dgeqpy(integer*, integer*, integer*, integer*, doublereal*,
integer*, doublereal*, integer*, integer*, doublereal*,
doublereal*, integer*, doublereal*, doublereal*, integer*,
integer*);
#define dlasmx FORTRAN_WRAPPER(dlasmx)
doublereal dlasmx(integer *);
#define dlauc1 FORTRAN_WRAPPER(dlauc1)
logical dlauc1(integer *, doublereal *, doublereal *, doublereal *,
doublereal *, doublereal *);
#define dtrqpx FORTRAN_WRAPPER(dtrqpx)
int dtrqpx(integer *, integer *, integer *, integer *,
doublereal *, integer *, doublereal *, integer *, integer *,
doublereal *, doublereal *, integer *, doublereal *, doublereal *,
integer *, integer *);
#define dtrqpy FORTRAN_WRAPPER(dtrqpy)
int dtrqpy(integer *, integer *, integer *, integer *,
doublereal *, integer *, doublereal *, integer *, integer *,
doublereal *, doublereal *, integer *, doublereal *, doublereal *,
integer *, integer *);
#define dtrqxc FORTRAN_WRAPPER(dtrqxc)
int dtrqxc(integer *, integer *, integer *, integer *, doublereal *,
integer*, doublereal *, integer *, integer *, integer *,
doublereal *, doublereal *, doublereal *, doublereal *, integer *);
#define dcniif FORTRAN_WRAPPER(dcniif)
int dcniif(integer *, integer *, integer *, integer *,
doublereal *, integer *, doublereal *, integer *, integer *,
doublereal *, doublereal *, integer *, logical *, doublereal *,
integer *);
#define dglbif FORTRAN_WRAPPER(dglbif)
int dglbif(integer *, integer *, integer *, integer *,
doublereal *, integer *, doublereal *, integer *, integer *,
doublereal *, integer *, logical *, doublereal *, integer *);
#define dgret FORTRAN_WRAPPER(dgret)
int dgret(integer *, integer *, integer *, integer *,
doublereal *, integer *, doublereal *, integer *,
doublereal *, integer *);
#define dhess FORTRAN_WRAPPER(dhess)
int dhess(integer *, integer *, integer *, integer *,
doublereal *, integer *, doublereal *, integer *,
doublereal *, integer *);
#define dtrqyc FORTRAN_WRAPPER(dtrqyc)
int dtrqyc(integer *, integer *, integer *, integer *, doublereal *,
integer*, doublereal *, integer *, integer *, integer *,
doublereal *, doublereal *, doublereal *, doublereal *, integer *);
#define dtrrnk FORTRAN_WRAPPER(dtrrnk)
int dtrrnk(integer *, doublereal *, integer *,
doublereal *, integer *, doublereal *, integer *);
#define sgeqpb FORTRAN_WRAPPER(sgeqpb)
int sgeqpb(integer *, integer *, integer *, integer *, real *,
integer *, real *, integer *, integer *, real *, real *, integer *,
real *, real *, integer *, integer *);
#define sgeqpc FORTRAN_WRAPPER(sgeqpc)
int sgeqpc(integer *, integer *, integer *, integer *, real *,
integer *, real *, integer *, integer *, integer *, real *,
integer *, integer *, real *, real *, real *, real *, real *, integer *);
#define sgeqpw FORTRAN_WRAPPER(sgeqpw)
int sgeqpw(integer *, integer *, integer *, integer *,
integer *, real *, integer *, integer *, real *, real *, real *,
real *, real *, real *);
#define sgeqpx FORTRAN_WRAPPER(sgeqpx)
int sgeqpx(integer*, integer*, integer*, integer*, real*, integer*,
real*, integer*, integer*, real*, real*, integer*, real*, real*,
integer*, integer*);
#define sgeqpy FORTRAN_WRAPPER(sgeqpy)
int sgeqpy(integer*, integer*, integer*, integer*, real*, integer*,
real*, integer*, integer*, real*, real*, integer*, real*, real*,
integer*, integer*);
#define slasmx FORTRAN_WRAPPER(slasmx)
doublereal slasmx(integer *);
#define slauc1 FORTRAN_WRAPPER(slauc1)
logical slauc1(integer *, real *, real *, real *, real *, real *);
#define strqpx FORTRAN_WRAPPER(strqpx)
int strqpx(integer *, integer *, integer *, integer *, real *,
integer *, real *, integer *, integer *, real *, real *, integer *,
real *, real *, integer *, integer *);
#define strqpy FORTRAN_WRAPPER(strqpy)
int strqpy(integer *, integer *, integer *, integer *, real *,
integer *, real *, integer *, integer *, real *, real *, integer *,
real *, real *, integer *, integer *);
#define strqxc FORTRAN_WRAPPER(strqxc)
int strqxc(integer *, integer *, integer *, integer *, real *,
integer *, real *, integer *, integer *, integer *, real *,
real *, real *, real *, integer *);
#define sglbif FORTRAN_WRAPPER(sglbif)
int sglbif(integer *, integer *, integer *, integer *,
real *, integer *, real *, integer *, integer *,
real *, integer *, logical *, real *, integer *);
#define scniif FORTRAN_WRAPPER(scniif)
int scniif(integer *, integer *, integer *, integer *,
real *, integer *, real *, integer *, integer *,
real *, real *, integer *, logical *, real *, integer *);
#define sgret FORTRAN_WRAPPER(sgret)
int sgret(integer *, integer *, integer *, integer *,
real *, integer *, real *, integer *, real *, integer *);
#define shess FORTRAN_WRAPPER(shess)
int shess(integer *, integer *, integer *, integer *,
real *, integer *, real *, integer *, real *, integer *);
#define strqyc FORTRAN_WRAPPER(strqyc)
int strqyc(integer *, integer *, integer *, integer *, real *,
integer *, real *, integer *, integer *, integer *, real *,
real *, real *, real *, integer *);
#define strrnk FORTRAN_WRAPPER(strrnk)
int strrnk(integer *, real *, integer *, real *,
integer *, real *, integer *);
#define zgeqpb FORTRAN_WRAPPER(zgeqpb)
int zgeqpb(integer *, integer *, integer *, integer *, doublecomplex *,
integer *, doublecomplex *, integer *, integer *, doublereal *,
doublereal *, integer *, doublereal *, doublecomplex *, integer *,
doublereal *, integer *);
#define zgeqpc FORTRAN_WRAPPER(zgeqpc)
int zgeqpc(integer *, integer *, integer *, integer *, doublecomplex *,
integer *, doublecomplex *, integer *, integer *, integer *, doublereal *,
integer *, integer *, doublecomplex *, doublecomplex *, doublereal *, doublereal *,
doublecomplex *, integer *, doublereal *);
#define zgeqpw FORTRAN_WRAPPER(zgeqpw)
int zgeqpw(integer *, integer *, integer *, integer *, integer *,
doublecomplex *, integer *, integer *, doublereal *, doublecomplex *,
doublereal *, doublereal *, doublecomplex *, doublecomplex *, doublereal *);
#define zgeqpx FORTRAN_WRAPPER(zgeqpx)
int zgeqpx(integer*, integer*, integer*, integer*, doublecomplex*,
integer*, doublecomplex*, integer*, integer*, doublereal*,
doublereal*, integer*, doublereal*, doublecomplex*, integer*,
doublereal*, integer*);
#define zgeqpy FORTRAN_WRAPPER(zgeqpy)
int zgeqpy(integer*, integer*, integer*, integer*, doublecomplex*,
integer*, doublecomplex*, integer*, integer*, doublereal*,
doublereal*, integer*, doublereal*, doublecomplex*, integer*,
doublereal*, integer*);
#define zlasmx FORTRAN_WRAPPER(zlasmx)
doublereal zlasmx(integer *i);
#define zlauc1 FORTRAN_WRAPPER(zlauc1)
logical zlauc1(integer *, doublecomplex *, doublereal *,
doublecomplex *, doublecomplex *, doublereal *);
#define ztrqpx FORTRAN_WRAPPER(ztrqpx)
int ztrqpx(integer *, integer *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, integer*,
integer *, doublereal *, doublereal *, integer *, doublereal *,
doublecomplex *, doublereal *, integer *);
#define ztrqpy FORTRAN_WRAPPER(ztrqpy)
int ztrqpy(integer *, integer *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, integer*,
integer *, doublereal *, doublereal *, integer *, doublereal *,
doublecomplex *, doublereal *, integer *);
#define ztrqxc FORTRAN_WRAPPER(ztrqxc)
int ztrqxc(integer *, integer *, integer *, integer *, doublecomplex *,
integer *, doublecomplex *, integer *, integer *, integer *,
doublereal *, doublereal *, doublereal *, doublecomplex *,
doublereal *, integer *);
#define zcniif FORTRAN_WRAPPER(zcniif)
int zcniif(integer *, integer *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *, integer *,
doublereal *, doublereal *, integer *, logical *, doublecomplex *,
doublereal *, integer *);
#define zglbif FORTRAN_WRAPPER(zglbif)
int zglbif(integer *, integer *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *, integer *,
doublereal *, integer *, logical *, doublecomplex *, doublereal *,
integer *);
#define zgret FORTRAN_WRAPPER(zgret)
int zgret(integer *, integer *, integer *, integer *,
doublecomplex *, integer *,doublecomplex *, integer *,
doublecomplex *, doublereal *, integer *);
#define dzhess FORTRAN_WRAPPER(dhess)
int zhess(integer *, integer *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *,
doublecomplex *, doublereal *, integer *);
#define ztrqyc FORTRAN_WRAPPER(ztrqyc)
int ztrqyc(integer *, integer *, integer *, integer *, doublecomplex *,
integer *, doublecomplex *, integer *, integer *, integer *,
doublereal *, doublereal *, doublereal *, doublecomplex *,
doublereal *, integer *);
#define ztrrnk FORTRAN_WRAPPER(ztrrnk)
int ztrrnk(integer *, doublecomplex *, integer *,
doublereal *, integer *, doublecomplex *, integer *);
| {
"alphanum_fraction": 0.6326876185,
"avg_line_length": 42.5475504323,
"ext": "h",
"hexsha": "67ae66c2d6e80802a302ca1da951b06053e476c7",
"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": "6b8e644c12b01aba4ae8de858f90e9c5955571f3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwoodsawyer/rrqr",
"max_forks_repo_path": "rrqr.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6b8e644c12b01aba4ae8de858f90e9c5955571f3",
"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": "iwoodsawyer/rrqr",
"max_issues_repo_path": "rrqr.h",
"max_line_length": 92,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6b8e644c12b01aba4ae8de858f90e9c5955571f3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwoodsawyer/rrqr",
"max_stars_repo_path": "rrqr.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3546,
"size": 14764
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for the conversion between time scales.
*
*/
#ifndef _TIMECONVERSION_H
#define _TIMECONVERSION_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include "constants.h"
/*************************/
/****** Prototypes ******/
/* Function computing the gmst angle from the gps time */
double gmst_angle_from_gpstime(const double gpstime); /* gpstime in seconds */
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _TIMECONVERSION_H */
| {
"alphanum_fraction": 0.6986444213,
"avg_line_length": 19.18,
"ext": "h",
"hexsha": "2eaea088cb592422fdc8941c862c56200812094a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "tools/timeconversion.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": "tools/timeconversion.h",
"max_line_length": 78,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "tools/timeconversion.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 240,
"size": 959
} |
/* ode-initval/test_odeiv.c
*
* Copyright (C) 2004 Tuomo Keskitalo
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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.
*/
/* Some functions and tests based on test.c by G. Jungman.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_odeiv.h>
#include "odeiv_util.h"
/* Maximum number of ODE equations */
#define MAXEQ 4
/* RHS for f=2. Solution y = 2 * t + t0 */
int
rhs_linear (double t, const double y[], double f[], void *params)
{
f[0] = 2.0;
return GSL_SUCCESS;
}
int
jac_linear (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
dfdy[0] = 0.0;
dfdt[0] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_lin = {
rhs_linear,
jac_linear,
1,
0
};
/* RHS for f=y. Equals y=exp(t) with initial value y(0)=1.0 */
int
rhs_exp (double t, const double y[], double f[], void *params)
{
f[0] = y[0];
return GSL_SUCCESS;
}
int
jac_exp (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
dfdy[0] = y[0];
dfdt[0] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_exp = {
rhs_exp,
jac_exp,
1,
0
};
/* RHS for f0 = -y1, f1 = y0
equals y = [cos(t), sin(t)] with initial values [1, 0]
*/
int
rhs_sin (double t, const double y[], double f[], void *params)
{
f[0] = -y[1];
f[1] = y[0];
return GSL_SUCCESS;
}
int
jac_sin (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
dfdy[0] = 0.0;
dfdy[1] = -1.0;
dfdy[2] = 1.0;
dfdy[3] = 0.0;
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_sin = {
rhs_sin,
jac_sin,
2,
0
};
/* Sine/cosine with random failures */
int
rhs_xsin (double t, const double y[], double f[], void *params)
{
static int n = 0;
n++;
if (n > 40 && n < 65) {
f[0] = GSL_NAN;
f[1] = GSL_NAN;
return GSL_EFAILED;
}
f[0] = -y[1];
f[1] = y[0];
return GSL_SUCCESS;
}
int
jac_xsin (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
static int n = 0;
n++;
if (n > 50 && n < 55) {
dfdy[0] = GSL_NAN;
dfdy[1] = GSL_NAN;
dfdy[2] = GSL_NAN;
dfdy[3] = GSL_NAN;
dfdt[0] = GSL_NAN;
dfdt[1] = GSL_NAN;
return GSL_EFAILED;
}
dfdy[0] = 0.0;
dfdy[1] = -1.0;
dfdy[2] = 1.0;
dfdy[3] = 0.0;
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_xsin = {
rhs_xsin,
jac_xsin,
2,
0
};
/* RHS for classic stiff example
dy0 / dt = 998 * y0 + 1998 * y1 y0(0) = 1.0
dy1 / dt = -999 * y0 - 1999 * y1 y1(0) = 0.0
solution is
y0 = 2 * exp(-t) - exp(-1000 * t)
y1 = - exp(-t) + exp(-1000 * t)
*/
int
rhs_stiff (double t, const double y[], double f[], void *params)
{
f[0] = 998.0 * y[0] + 1998.0 * y[1];
f[1] = -999.0 * y[0] - 1999.0 * y[1];
return GSL_SUCCESS;
}
int
jac_stiff (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
dfdy[0] = 998.0;
dfdy[1] = 1998.0;
dfdy[2] = -999.0;
dfdy[3] = -1999.0;
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_stiff = {
rhs_stiff,
jac_stiff,
2,
0
};
/* van Der Pol oscillator:
f0 = y1 y0(0) = 1.0
f1 = -y0 + mu * y1 * (1 - y0^2) y1(0) = 0.0
*/
int
rhs_vanderpol (double t, const double y[], double f[], void *params)
{
const double mu = 10.0;
f[0] = y[1];
f[1] = -y[0] + mu * y[1] * (1.0 - y[0]*y[0]);
return GSL_SUCCESS;
}
int
jac_vanderpol (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
const double mu = 10.0;
dfdy[0] = 0.0;
dfdy[1] = 1.0;
dfdy[2] = -2.0 * mu * y[0] * y[1] - 1.0;
dfdy[3] = mu * (1.0 - y[0] * y[0]);
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_vanderpol = {
rhs_vanderpol,
jac_vanderpol,
2,
0
};
/* The Oregonator - chemical Belusov-Zhabotinskii reaction
y0(0) = 1.0, y1(0) = 2.0, y2(0) = 3.0
*/
int
rhs_oregonator (double t, const double y[], double f[], void *params)
{
const double c1=77.27;
const double c2=8.375e-6;
const double c3=0.161;
f[0] = c1 * (y[1] + y[0] * (1 - c2 * y[0] - y[1]));
f[1] = 1/c1 * (y[2] - y[1] * (1 + y[0]));
f[2] = c3 * (y[0] - y[2]);
return GSL_SUCCESS;
}
int
jac_oregonator (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
const double c1=77.27;
const double c2=8.375e-6;
const double c3=0.161;
dfdy[0] = c1 * (1 - 2 * c2 * y[0] - y[1]);
dfdy[1] = c1 * (1 - y[0]);
dfdy[2] = 0.0;
dfdy[3] = 1/c1 * (-y[1]);
dfdy[4] = 1/c1 * (-1 - y[0]);
dfdy[5] = 1/c1;
dfdy[6] = c3;
dfdy[7] = 0.0;
dfdy[8] = -c3;
dfdt[0] = 0.0;
dfdt[1] = 0.0;
dfdt[2] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_oregonator = {
rhs_oregonator,
jac_oregonator,
3,
0
};
/* Volterra-Lotka predator-prey model
f0 = (a - b * y1) * y0 y0(0) = 3.0
f1 = (-c + d * y0) * y1 y1(0) = 1.0
*/
int
rhs_vl (double t, const double y[], double f[], void *params)
{
const double a = 1.0;
const double b = 1.0;
const double c = 1.0;
const double d = 1.0;
f[0] = (a - b * y[1]) * y[0];
f[1] = (-c + d * y[0]) * y[1];
return GSL_SUCCESS;
}
int
jac_vl (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
const double a = 1.0;
const double b = 1.0;
const double c = 1.0;
const double d = 1.0;
dfdy[0] = a - b * y[1];
dfdy[1] = -b * y[0];
dfdy[2] = d * y[1];
dfdy[3] = -c + d * y[0];
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_vl = {
rhs_vl,
jac_vl,
2,
0
};
/* Stiff trigonometric example
f0 = -50 * (y0 - cos(t)) y0(0) = 0.0
*/
int
rhs_stifftrig (double t, const double y[], double f[], void *params)
{
f[0] = -50 * (y[0] - cos(t));
return GSL_SUCCESS;
}
int
jac_stifftrig (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
dfdy[0] = -50;
dfdt[0] = -50 * sin(t);
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_stifftrig = {
rhs_stifftrig,
jac_stifftrig,
1,
0
};
/* E5 - a stiff badly scaled chemical problem by Enright, Hull &
Lindberg (1975): Comparing numerical methods for stiff systems of
ODEs. BIT, vol. 15, pp. 10-48.
f0 = -a * y0 - b * y0 * y2 y0(0) = 1.76e-3
f1 = a * y0 - m * c * y1 * y2 y1(0) = 0.0
f2 = a * y0 - b * y0 * y2 - m * c * y1 * y2 + c * y3 y2(0) = 0.0
f3 = b * y0 * y2 - c * y3 y3(0) = 0.0
*/
int
rhs_e5 (double t, const double y[], double f[], void *params)
{
const double a = 7.89e-10;
const double b = 1.1e7;
const double c = 1.13e3;
const double m = 1.0e6;
f[0] = -a * y[0] - b * y[0] * y[2];
f[1] = a * y[0] - m * c * y[1] * y[2];
f[3] = b * y[0] * y[2] - c * y[3];
f[2] = f[1] - f[3];
return GSL_SUCCESS;
}
int
jac_e5 (double t, const double y[], double *dfdy, double dfdt[],
void *params)
{
const double a = 7.89e-10;
const double b = 1.1e7;
const double c = 1.13e3;
const double m = 1.0e6;
dfdy[0] = -a - b * y[2];
dfdy[1] = 0.0;
dfdy[2] = -b * y[0];
dfdy[3] = 0.0;
dfdy[4] = a;
dfdy[5] = -m * c * y[2];
dfdy[6] = -m * c * y[1];
dfdy[7] = 0.0;
dfdy[8] = a - b * y[2];
dfdy[9] = -m * c * y[2];
dfdy[10] = -b * y[0] - m * c * y[1];
dfdy[11] = c;
dfdy[12] = b * y[2];
dfdy[13] = 0.0;
dfdy[14] = b * y[0];
dfdy[15] = -c;
dfdt[0] = 0.0;
dfdt[1] = 0.0;
dfdt[2] = 0.0;
dfdt[3] = 0.0;
return GSL_SUCCESS;
}
gsl_odeiv_system rhs_func_e5 = {
rhs_e5,
jac_e5,
4,
0
};
void
test_odeiv_stepper (const gsl_odeiv_step_type *T, const gsl_odeiv_system *sys,
const double h, const double t, const char desc[],
const double ystart[], const double yfin[],
const double relerr)
{
/* tests stepper T with one fixed length step advance of system sys
and compares with given values yfin
*/
double y[MAXEQ] = {0.0};
double yerr[MAXEQ] = {0.0};
size_t ne = sys->dimension;
size_t i;
gsl_odeiv_step *step = gsl_odeiv_step_alloc (T, ne);
DBL_MEMCPY (y, ystart, MAXEQ);
{
int s = gsl_odeiv_step_apply (step, t, h, y, yerr, 0, 0, sys);
if (s != GSL_SUCCESS)
{
gsl_test(s, "test_odeiv_stepper: %s step_apply returned %d", desc, s);
}
}
for (i = 0; i < ne; i++)
{
gsl_test_rel (y[i], yfin[i], relerr,
"%s %s step(%d)",
gsl_odeiv_step_name (step), desc,i);
}
gsl_odeiv_step_free (step);
}
void
test_stepper (const gsl_odeiv_step_type *T)
{
/* Tests stepper T with a step of selected systems */
double y[MAXEQ] = {0.0};
double yfin[MAXEQ] = {0.0};
/* Step length */
double h;
/* Required tolerance */
double err_target;
/* linear */
h = 1e-1;
err_target = 1e-10;
y[0] = 0.58;
yfin[0] = y[0] + 2 * h;
test_odeiv_stepper (T, &rhs_func_lin, h, 0.0, "linear",
y, yfin, err_target);
/* exponential */
h = 1e-4;
err_target = 1e-8;
y[0] = exp(2.7);
yfin[0] = exp(2.7 + h);
test_odeiv_stepper (T, &rhs_func_exp, h, 2.7, "exponential",
y, yfin, err_target);
/* cosine-sine */
h = 1e-3;
err_target = 1e-6;
y[0] = cos(1.2);
y[1] = sin(1.2);
yfin[0] = cos(1.2 + h);
yfin[1] = sin(1.2 + h);
test_odeiv_stepper (T, &rhs_func_sin, h, 1.2, "cosine-sine",
y, yfin, err_target);
/* classic stiff */
h = 1e-7;
err_target = 1e-4;
y[0] = 1.0;
y[1] = 0.0;
{
const double e1 = exp (-h);
const double e2 = exp (-1000.0 * h);
yfin[0] = 2.0 * e1 - e2;
yfin[1] = -e1 + e2;
}
test_odeiv_stepper (T, &rhs_func_stiff, h, 0.0, "classic_stiff",
y, yfin, err_target);
}
void
test_evolve_system (const gsl_odeiv_step_type * T,
const gsl_odeiv_system * sys,
double t0, double t1, double hstart,
double y[], double yfin[],
double err_target, const char *desc)
{
/* Tests system sys with stepper T. Step length is controlled by
error estimation from the stepper.
*/
int steps = 0;
size_t i;
double t = t0;
double h = hstart;
/* Tolerance factor in testing errors */
const double factor = 10;
gsl_odeiv_step * step = gsl_odeiv_step_alloc (T, sys->dimension);
gsl_odeiv_control *c =
gsl_odeiv_control_standard_new (err_target, err_target, 1.0, 0.0);
gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc (sys->dimension);
while (t < t1)
{
int s = gsl_odeiv_evolve_apply (e, c, step, sys, &t, t1, &h, y);
if (s != GSL_SUCCESS && sys != &rhs_func_xsin)
{
gsl_test(s, "%s evolve_apply returned %d",
gsl_odeiv_step_name (step), s);
break;
}
if (steps > 100000)
{
gsl_test(GSL_EFAILED,
"%s evolve_apply reached maxiter",
gsl_odeiv_step_name (step));
break;
}
steps++;
}
/* err_target is target error of one step. Test if stepper has made
larger error than (tolerance factor times) the number of steps
times the err_target */
for (i = 0; i < sys->dimension; i++)
{
gsl_test_abs (y[i], yfin[i], factor * e->count * err_target,
"%s %s evolve(%d)",
gsl_odeiv_step_name (step), desc, i);
}
gsl_odeiv_evolve_free (e);
gsl_odeiv_control_free (c);
gsl_odeiv_step_free (step);
}
int
sys_driver (const gsl_odeiv_step_type * T,
const gsl_odeiv_system * sys,
double t0, double t1, double hstart,
double y[], double epsabs, double epsrel,
const char desc[])
{
/* This function evolves a system sys with stepper T from t0 to t1.
Step length is varied via error control with possibly different
absolute and relative error tolerances.
*/
int s = 0;
int steps = 0;
double t = t0;
double h = hstart;
gsl_odeiv_step * step = gsl_odeiv_step_alloc (T, sys->dimension);
gsl_odeiv_control *c =
gsl_odeiv_control_standard_new (epsabs, epsrel, 1.0, 0.0);
gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc (sys->dimension);
while (t < t1)
{
s = gsl_odeiv_evolve_apply (e, c, step, sys, &t, t1, &h, y);
if (s != GSL_SUCCESS)
{
gsl_test(s, "sys_driver: %s evolve_apply returned %d",
gsl_odeiv_step_name (step), s);
break;
}
if (steps > 1e7)
{
gsl_test(GSL_EMAXITER,
"sys_driver: %s evolve_apply reached maxiter at t=%g",
gsl_odeiv_step_name (step), t);
s = GSL_EMAXITER;
break;
}
steps++;
}
gsl_test(s, "%s %s [%g,%g], %d steps completed",
gsl_odeiv_step_name (step), desc, t0, t1, steps);
gsl_odeiv_evolve_free (e);
gsl_odeiv_control_free (c);
gsl_odeiv_step_free (step);
return s;
}
void
test_compare_vanderpol (void)
{
/* Compares output of van Der Pol oscillator with several steppers */
/* system dimension */
const size_t sd = 2;
const gsl_odeiv_step_type *steppers[20];
const gsl_odeiv_step_type **T;
/* Required error tolerance for each stepper. */
double err_target[20];
/* number of ODE solvers */
const size_t ns = 11;
/* initial values for each ode-solver */
double y[11][2];
double *yp = &y[0][0];
size_t i, j, k;
int status = 0;
/* Parameters for the problem and stepper */
const double start = 0.0;
const double end = 100.0;
const double epsabs = 1e-8;
const double epsrel = 1e-8;
const double initstepsize = 1e-5;
/* Initialize */
steppers[0] = gsl_odeiv_step_rk2;
err_target[0] = 1e-6;
steppers[1] = gsl_odeiv_step_rk4;
err_target[1] = 1e-6;
steppers[2] = gsl_odeiv_step_rkf45;
err_target[2] = 1e-6;
steppers[3] = gsl_odeiv_step_rkck;
err_target[3] = 1e-6;
steppers[4] = gsl_odeiv_step_rk8pd;
err_target[4] = 1e-6;
steppers[5] = gsl_odeiv_step_rk2imp;
err_target[5] = 1e-5;
steppers[6] = gsl_odeiv_step_rk2simp;
err_target[6] = 1e-5;
steppers[7] = gsl_odeiv_step_rk4imp;
err_target[7] = 1e-6;
steppers[8] = gsl_odeiv_step_bsimp;
err_target[8] = 1e-7;
steppers[9] = gsl_odeiv_step_gear1;
err_target[9] = 1e-2;
steppers[10] = gsl_odeiv_step_gear2;
err_target[10] = 1e-6;
steppers[11] = 0;
T = steppers;
for (i = 0; i < ns; i++)
{
y[i][0] = 1.0;
y[i][1] = 0.0;
}
/* Call each solver for the problem */
i = 0;
while (*T != 0)
{
{
int s = sys_driver (*T, &rhs_func_vanderpol,
start, end, initstepsize, &yp[i],
epsabs, epsrel, "vanderpol");
if (s != GSL_SUCCESS)
{
status++;
}
}
T++;
i += sd;
}
if (status != GSL_SUCCESS)
{
return;
}
/* Compare results */
T = steppers;
for (i = 0; i < ns; i++)
for (j = i+1; j < ns; j++)
for (k = 0; k < sd; k++)
{
const double val1 = yp[sd * i + k];
const double val2 = yp[sd * j + k];
gsl_test_abs (val1, val2,
( GSL_MAX(err_target[i], err_target[j]) ),
"%s/%s vanderpol",
T[i]->name, T[j]->name);
}
}
void
test_compare_oregonator (void)
{
/* Compares output of the Oregonator with several steppers */
/* system dimension */
const size_t sd = 3;
const gsl_odeiv_step_type *steppers[20];
const gsl_odeiv_step_type **T;
/* Required error tolerance for each stepper. */
double err_target[20];
/* number of ODE solvers */
const size_t ns = 2;
/* initial values for each ode-solver */
double y[2][3];
double *yp = &y[0][0];
size_t i, j, k;
int status = 0;
/* Parameters for the problem and stepper */
const double start = 0.0;
const double end = 360.0;
const double epsabs = 1e-8;
const double epsrel = 1e-8;
const double initstepsize = 1e-5;
/* Initialize */
steppers[0] = gsl_odeiv_step_rk2simp;
err_target[0] = 1e-6;
steppers[1] = gsl_odeiv_step_bsimp;
err_target[1] = 1e-6;
steppers[2] = 0;
T = steppers;
for (i = 0; i < ns; i++)
{
y[i][0] = 1.0;
y[i][1] = 2.0;
y[i][2] = 3.0;
}
/* Call each solver for the problem */
i = 0;
while (*T != 0)
{
{
int s = sys_driver (*T, &rhs_func_oregonator,
start, end, initstepsize, &yp[i],
epsabs, epsrel, "oregonator");
if (s != GSL_SUCCESS)
{
status++;
}
}
T++;
i += sd;
}
if (status != GSL_SUCCESS)
{
return;
}
/* Compare results */
T = steppers;
for (i = 0; i < ns; i++)
for (j = i+1; j < ns; j++)
for (k = 0; k < sd; k++)
{
const double val1 = yp[sd * i + k];
const double val2 = yp[sd * j + k];
gsl_test_rel (val1, val2,
( GSL_MAX(err_target[i], err_target[j]) ),
"%s/%s oregonator",
T[i]->name, T[j]->name);
}
}
void
test_evolve_linear (const gsl_odeiv_step_type * T, double h, double err)
{
double y[1];
double yfin[1];
y[0] = 1.0;
yfin[0] = 9.0;
test_evolve_system (T, &rhs_func_lin, 0.0, 4.0, h, y, yfin, err,
"linear[0,4]");
}
void
test_evolve_exp (const gsl_odeiv_step_type * T, double h, double err)
{
double y[1];
double yfin[1];
y[0] = 1.0;
yfin[0] = exp (2.0);
test_evolve_system (T, &rhs_func_exp, 0.0, 2.0, h, y, yfin, err,
"exp[0,2]");
}
void
test_evolve_sin (const gsl_odeiv_step_type * T, double h, double err)
{
double y[2];
double yfin[2];
y[0] = 1.0;
y[1] = 0.0;
yfin[0] = cos (2.0);
yfin[1] = sin (2.0);
test_evolve_system (T, &rhs_func_sin, 0.0, 2.0, h, y, yfin, err,
"sine[0,2]");
}
void
test_evolve_xsin (const gsl_odeiv_step_type * T, double h, double err)
{
double y[2];
double yfin[2];
y[0] = 1.0;
y[1] = 0.0;
yfin[0] = cos (2.0);
yfin[1] = sin (2.0);
test_evolve_system (T, &rhs_func_xsin, 0.0, 2.0, h, y, yfin, err,
"sine[0,2] w/errors");
}
void
test_evolve_stiff1 (const gsl_odeiv_step_type * T, double h, double err)
{
double y[2];
double yfin[2];
y[0] = 1.0;
y[1] = 0.0;
{
double arg = 1.0;
double e1 = exp (-arg);
double e2 = exp (-1000.0 * arg);
yfin[0] = 2.0 * e1 - e2;
yfin[1] = -e1 + e2;
}
test_evolve_system (T, &rhs_func_stiff, 0.0, 1.0, h, y, yfin, err,
"stiff[0,1]");
}
void
test_evolve_stiff5 (const gsl_odeiv_step_type * T, double h, double err)
{
double y[2];
double yfin[2];
y[0] = 1.0;
y[1] = 0.0;
{
double arg = 5.0;
double e1 = exp (-arg);
double e2 = exp (-1000.0 * arg);
yfin[0] = 2.0 * e1 - e2;
yfin[1] = -e1 + e2;
}
test_evolve_system (T, &rhs_func_stiff, 0.0, 5.0, h, y, yfin, err,
"stiff[0,5]");
}
int
main (void)
{
int i;
struct ptype
{
const gsl_odeiv_step_type *type;
double h;
}
p[20];
p[0].type = gsl_odeiv_step_rk2;
p[0].h = 1.0e-3;
p[1].type = gsl_odeiv_step_rk4;
p[1].h = 1.0e-3;
p[2].type = gsl_odeiv_step_rkf45;
p[2].h = 1.0e-3;
p[3].type = gsl_odeiv_step_rkck;
p[3].h = 1.0e-3;
p[4].type = gsl_odeiv_step_rk8pd;
p[4].h = 1.0e-3;
p[5].type = gsl_odeiv_step_rk2imp;
p[5].h = 1.0e-3;
p[6].type = gsl_odeiv_step_rk2simp;
p[6].h = 1.0e-3;
p[7].type = gsl_odeiv_step_rk4imp;
p[7].h = 1.0e-3;
p[8].type = gsl_odeiv_step_bsimp;
p[8].h = 1.0e-3;
p[9].type = gsl_odeiv_step_gear1;
p[9].h = 1.0e-3;
p[10].type = gsl_odeiv_step_gear2;
p[10].h = 1.0e-3;
p[11].type = 0;
gsl_ieee_env_setup ();
for (i = 0; p[i].type != 0; i++)
{
test_stepper(p[i].type);
}
for (i = 0; p[i].type != 0; i++)
{
test_evolve_linear (p[i].type, p[i].h, 1e-10);
test_evolve_exp (p[i].type, p[i].h, 1e-6);
test_evolve_sin (p[i].type, p[i].h, 1e-8);
test_evolve_xsin (p[i].type, p[i].h, 1e-8);
test_evolve_stiff1 (p[i].type, p[i].h, 1e-7);
test_evolve_stiff5 (p[i].type, p[i].h, 1e-7);
}
test_compare_vanderpol();
test_compare_oregonator();
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.5717673248,
"avg_line_length": 20.0426770126,
"ext": "c",
"hexsha": "7fb6001a1990a93bde3b74abc8d9edac9216c039",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/ode-initval/test.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/ode-initval/test.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/ode-initval/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 8150,
"size": 20664
} |
/*
* 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 widget_c3b57c97_cea3_4794_b683_762a7b11af49_h
#define widget_c3b57c97_cea3_4794_b683_762a7b11af49_h
#include <gslib/std.h>
#include <gslib/dvt.h>
#include <gslib/uuid.h>
#include <ariel/sysop.h>
#include <ariel/painter.h>
__ariel_begin__
class wsys_manager;
class widget:
public dvt_holder
{
friend class wsys_manager;
public:
widget(wsys_manager* m);
virtual ~widget();
virtual void* query_interface(const uuid& uid);
virtual bool create(widget* ptr, const gchar* name, const rect& rc, uint style);
virtual void close();
virtual void show(bool b);
virtual void enable(bool b);
virtual void move(const rect& rc);
virtual void refresh(const rect& rc, bool imm = false);
virtual void draw(painter* paint) {}
virtual widget* capture(bool b);
virtual widget* focus();
virtual bool hit_test(const point& pt) { return (_style & sm_hitable) != 0; }
public:
enum laytag
{
lay_before,
lay_after,
lay_first,
lay_last,
};
virtual void lay(widget* ptr, laytag t);
public:
virtual void on_press(uint um, unikey uk, const point& pt);
virtual void on_click(uint um, unikey uk, const point& pt);
virtual void on_hover(uint um, const point& pt);
virtual void on_leave(uint um, const point& pt);
virtual void on_keydown(uint um, unikey uk) {}
virtual void on_keyup(uint um, unikey uk) {}
virtual void on_char(uint um, uint ch) {}
virtual void on_caret() {}
virtual void on_capture(bool b) {}
virtual void on_focus(bool b) {}
virtual void on_accelerator(unikey key, uint mask) {}
protected:
wsys_manager* _manager;
string _name;
uint _style;
rect _pos;
bool _visible;
bool _enabled;
public:
const string& get_name() const { return _name; }
const rect& get_rect() const { return _pos; }
rectf get_rectf() const { return to_rectf(get_rect()); }
bool is_visible() const { return _visible && (_style & sm_visible); }
bool is_enabled() const { return _enabled; }
bool is_focused() const;
void hide() { show(false); }
void disable() { enable(false); }
point& to_global(point& pt) const;
rect& to_global(rect& rc) const;
point& to_local(point& pt) const;
rect& to_local(rect& rc) const;
void move(const point& pt);
void resize(int w, int h);
void refresh(bool imm);
int get_width() const { return _pos.width(); }
int get_height() const { return _pos.height(); }
wsys_manager* get_manager() const { return _manager; }
bool register_accelerator(unikey key, uint mask);
widget* unregister_accelerator(unikey key, uint mask);
protected:
widget* _prev;
widget* _next;
widget* _child;
widget* _last_child;
widget* _parent;
public:
widget* get_parent() const { return _parent; }
widget* get_prev() const { return _prev; }
widget* get_next() const { return _next; }
widget* get_child() const { return _child; }
widget* get_last_child() const { return _last_child; }
public:
template<class _lamb>
static int traverse_widget(widget* w, _lamb trav_to_stop)
{
assert(w);
for(auto* p = w; p; p = p->get_next()) {
if(auto r = trav_to_stop(p))
return r;
}
return 0;
}
template<class _lamb>
static int traverse_widget_reversed(widget* w, _lamb trav_to_stop)
{
assert(w);
for(auto* p = w; p; p = p->get_prev()) {
if(auto r = trav_to_stop(p))
return r;
}
return 0;
}
template<class _lamb>
int traverse_child_widget(_lamb trav_to_stop) { return traverse_widget(_child, trav_to_stop); }
template<class _lamb>
int traverse_child_widget_reversed(_lamb trav_to_stop) { return traverse_widget_reversed(_last_child, trav_to_stop); }
};
class button:
public widget
{
public:
typedef widget superref;
typedef button self;
public:
button(wsys_manager* m);
virtual ~button();
virtual void draw(painter* paint) override;
virtual void enable(bool b) override;
virtual void on_press(uint um, unikey uk, const point& pt) override;
virtual void on_click(uint um, unikey uk, const point& pt) override;
virtual void on_hover(uint um, const point& pt) override;
virtual void on_leave(uint um, const point& pt) override;
protected:
virtual void set_press();
virtual void set_normal();
virtual void set_hover();
virtual void set_gray();
protected:
texture2d* _source;
texture2d* _bkground;
bool _4states;
public:
void set_image(texture2d* img, bool fs = false);
enum btnstate
{
bs_none = 0,
bs_press,
bs_hover,
bs_normal,
};
void set_btnstate(btnstate bs) { _btnstate = bs; }
btnstate get_btnstate() const { return _btnstate; }
protected:
btnstate _btnstate;
};
class edit_line:
public widget
{
public:
typedef widget superref;
typedef edit_line self;
public:
edit_line(wsys_manager* m);
virtual void draw(painter* paint) override;
virtual void on_press(uint um, unikey uk, const point& pt) override;
virtual void on_click(uint um, unikey uk, const point& pt) override;
virtual void on_hover(uint um, const point& pt) override;
virtual void on_char(uint um, uint ch) override;
virtual void on_keydown(uint um, unikey uk) override;
virtual void on_caret() override;
virtual void on_focus(bool b) override;
protected:
bool _caret_on;
int _caretpos;
string _textbuf;
int _sel_start;
int _sel_end;
public:
virtual void set_text(const gchar* str);
virtual void set_caret(int n);
virtual void set_select(int start, int end);
virtual void replace_select(const gchar* str);
protected:
virtual void draw_background(painter* paint);
virtual void draw_normal_text(painter* paint);
virtual void draw_select_text(painter* paint);
virtual void draw_caret(painter* paint);
public:
void set_font(const font& ft) { _font = ft; }
void set_bkground(texture2d* ptr) { _bkground = ptr; }
void set_text_color(color cr) { _txtcolor = cr; }
void set_select_color(color cr) { _selcolor = cr; }
void set_caret_color(color cr) { _crtcolor = cr; }
const gchar* get_text() const { return _textbuf.c_str(); }
void del_select();
int hit_char(point pt);
int prev_char(int pos);
int next_char(int pos);
int prev_logic_char(int pos);
int next_logic_char(int pos);
bool no_select() const { return _sel_start == -1 || _sel_start == _sel_end; }
protected:
texture2d* _bkground;
color _txtcolor;
color _selcolor;
color _crtcolor;
font _font;
protected:
int trim_if_overrun(bool alarm);
};
typedef system_driver wsys_driver;
typedef system_notify wsys_notify;
class timer:
public dvt_holder
{
public:
timer(wsys_manager* mgr);
void start(int elapse);
void start_single(int elapse);
void set_user_data(uint usd) { _userdata = usd; }
uint get_user_data() const { return _userdata; }
public:
virtual ~timer();
virtual void on_timer(uint tid) {}
virtual void on_notified(); /* CANNOT be used by connect notify */
protected:
wsys_driver* _driver;
uint _userdata;
int _elapse;
bool _single;
private:
void initialize(wsys_driver* drv);
};
struct accel_key
{
unikey key;
uint mask;
public:
accel_key(): key((unikey)-1), mask(0) {} /* invalid */
accel_key(unikey k, uint m): key(k), mask(m) {}
bool is_valid() const { return key != (unikey)-1; }
bool operator == (const accel_key& that) const { return key == that.key && mask == that.mask; }
bool from_string(const string& str);
const string& to_string(string& str) const;
};
class wsys_manager:
public wsys_notify
{
public:
wsys_manager();
void set_wsysdrv(wsys_driver* drv);
void set_painter(painter* paint);
painter* get_painter() const { return _painter; }
wsys_driver* get_driver() const { return _driver; }
void initialize(const rect& rc);
protected:
wsys_driver* _driver;
painter* _painter;
dirty_list _dirty;
int _width;
int _height;
timer* _caret;
public:
void set_dimension(int w, int h);
int get_width() const { return _width; }
int get_height() const { return _height; }
void refresh() { _dirty.set_whole(); }
void refresh(const rect& rc, bool imm = false);
void update();
void update(widget* w);
widget* hit_test(point pt) { return hit_test(_root, pt); }
widget* hit_test(widget* ptr, point pt);
widget* hit_proc(const point& pt, point& pt1);
widget* set_capture(widget* ptr, bool b);
widget* set_focus(widget* ptr);
void on_caret(uint);
widget* get_capture() const { return _capture; }
widget* get_focus() const { return _focus; }
void set_cursor(cursor_type curty);
void reset_cursor() { set_cursor(cur_arrow); }
public:
virtual ~wsys_manager();
virtual void on_show(bool b) override;
virtual void on_create(wsys_driver* ptr, const rect& rc) override;
virtual void on_close() override;
virtual void on_resize(const rect& rc) override;
virtual void on_paint(const rect& rc) override;
virtual void on_halt() override;
virtual void on_resume() override;
virtual bool on_mouse_down(uint um, unikey uk, const point& pt) override;
virtual bool on_mouse_up(uint um, unikey uk, const point& pt) override;
virtual bool on_mouse_move(uint um, const point& pt) override;
virtual bool on_key_down(uint um, unikey uk) override;
virtual bool on_key_up(uint um, unikey uk) override;
virtual bool on_char(uint um, uint ch) override;
virtual void on_timer(uint tid) override;
protected:
widget* _hover;
widget* _capture;
widget* _focus;
widget* _root;
private:
typedef unordered_map<string, widget*> widget_map;
widget_map _widget_map;
public:
template<class _ctor>
_ctor* add_widget(widget* ptr, const gchar* name, const rect& rc, uint style)
{
if(name && name[0] && _widget_map.find(name) != _widget_map.end())
return nullptr;
if(!ptr && _root)
ptr = _root;
_ctor* p = new _ctor(this);
assert(p);
if(!p->create(ptr, name ? name : _t(""), rc, style)) {
delete p;
return nullptr;
}
if(name && name[0]) {
_widget_map.insert(
std::make_pair(name, p)
);
}
if(!ptr && !_root)
_root = p;
return p;
}
widget* get_root() const { return _root; }
widget* find_widget(const string& name);
bool remove_widget(widget* ptr);
bool remove_widget(const string& name);
protected:
bool remove_widget_internal(widget* ptr);
public:
void set_ime(widget* ptr, point pt, const font& ft);
void set_clipboard(clipfmt fmt, const void* ptr, int size);
int get_clipboard(clipfmt fmt, const void*& ptr);
int get_clipboard(clipboard_list& cl, int c);
protected:
struct accel_key_hasher { size_t operator()(const accel_key& kval) const { return hash_bytes((const byte*)&kval, sizeof(kval)); } };
typedef unordered_map<accel_key, widget*, accel_key_hasher> accel_map;
friend bool try_proceed_accelerator(const accel_map&, unikey, uint);
accel_map _accel_map;
public:
bool register_accelerator(widget* w, unikey key, uint mask);
widget* unregister_accelerator(unikey key, uint mask);
};
extern const uuid uuid_widget;
__ariel_end__
#endif
| {
"alphanum_fraction": 0.633691599,
"avg_line_length": 32.3333333333,
"ext": "h",
"hexsha": "41e97c1c282cc8c95ca1ebb3f48fc758de588a0f",
"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/widget.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/widget.h",
"max_line_length": 137,
"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/widget.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": 3312,
"size": 13677
} |
#pragma once
#include "Type/peColor.h"
#include "Type\peBitmask.h"
#include "peCoreDefs.h"
#include <glm/detail/type_vec2.hpp>
#undef max
#include <gsl.h>
#include <random>
#pragma warning(push)
#pragma warning(disable : 4251)
/*
* Everything in here is taking more or less one-to-one from 'Physically based
* rendering' (Pharr, Humphreys, 2010)
*/
namespace pe {
struct Sample;
class peCoordSys;
//! \brief Represents a color spectrum. We will use RGB with floating-point
//! precision here
using Spectrum_t = RGB_32BitFloat;
//! \brief Types of BRDFs and BTDFs
enum class BxDFType {
Reflection = 1 << 0,
Transmission = 1 << 1,
Diffuse = 1 << 2,
Glossy = 1 << 3,
Specular = 1 << 4,
AllTypes = Diffuse | Glossy | Specular,
AllReflection = Reflection | AllTypes,
AllTransmission = Transmission | AllTypes,
All = AllReflection | AllTransmission
};
template <> struct EnableEnumBitmask<BxDFType> : std::true_type {};
//! \brief BRDF or BTDF base class
class PE_CORE_API peBxDF {
public:
virtual ~peBxDF() = default;
explicit peBxDF(BxDFType type);
bool HasFlags(BxDFType flags) const;
auto Type() const { return _type; }
//! \brief Evaluate this BxDF for the given outgoing and incoming vectors
//! \param wo Outgoing vector
//! \param wi Incoming vector
//! \returns Value of the distribution function for the two vectors
virtual Spectrum_t Eval(const glm::vec3 &wo, const glm::vec3 &wi) const = 0;
//! \brief Sampling function for BxDF distributions that utilize delta
//! distributions. Here, the incident direction wi cannot
//! be known to the user, hence the BxDF computes it
//! \param wo Outgoing vector
//! \param wi Incoming vector, will be computed by the BxDF
//! \param rnd1 First uniform random variable
//! \param rnd2 Second uniform random variable
//! \param pdf Probability density function for this BxDF and the given pair
//! of vectors \returns Value of the distribution function for the two vectors
virtual Spectrum_t Sample_f(const glm::vec3 &wo, glm::vec3 &wi,
const float rnd1, const float rnd2,
float &pdf) const;
//! \brief Computes the hemishperical-directional reflectance, which is the
//! total reflection in the given direction due to constant illumination over
//! the hemisphere. Not every BxDF will be able to compute this in closed
//! form, so they will use something like a monte carlo algorithm to compute
//! it, hence the <paramref name="samples"/> member
//! \param wo Outgoing vector
//! \param samples Samples
//! \returns Hemispherical reflection around <paramref name="wo"/>
virtual Spectrum_t rho(const glm::vec3 &wo,
const gsl::span<glm::vec2> &samples) const;
//! \brief Computes the hemispherical-hemispherical reflectance, which is the
//! fraction of incident light reflected by the surface when the incident
//! light is the same from all directions. Not every BxDF will be able to
//! compute this in closed form, so they will use something like a monte carlo
//! algorithm to compute it
//! \param samples1 First set of samples for monte carlo method
//! \param samples2 Second set of samples for monte carlo method
//! \returns Direction-independent reflectance
virtual Spectrum_t rho(const gsl::span<glm::vec2> &samples1,
const gsl::span<glm::vec2> &samples2) const;
//! \brief Returns the probability density function for the given pairs of
//! vectors \param wo Outgoing vector in shading space \param wi Incoming
//! vector in shading space \returns PDF
virtual float Pdf(const glm::vec3 &wo, const glm::vec3 &wi) const;
private:
const BxDFType _type;
};
#pragma region Fresnel
//! \brief Helper class to encapsulate fresnel reflectance
struct PE_CORE_API peFresnel {
virtual ~peFresnel() {}
virtual Spectrum_t Eval(float cosi) const = 0;
};
//! \brief Fresnel reflectance for a conductor
class PE_CORE_API peFresnelConductor : public peFresnel {
public:
//! \brief Initializes this FresnelConductor structure with the given index of
//! refraction and absorption
//! \param eta Index of refraction of conductor
//! \param k Absorption index of conductor
peFresnelConductor(const Spectrum_t &eta, const Spectrum_t &k);
Spectrum_t Eval(float cosi) const override;
private:
const Spectrum_t _eta;
const Spectrum_t _k;
};
//! \brief Fresnel reflectance for dielectric material
class PE_CORE_API peFresnelDielectric : public peFresnel {
public:
//! \brief Initializes this FresnelDielectric structure with the given
//! incident and transmitted medium indices of refraction
//! \param etaIncident Index of refraction for incident material
//! \param etaTransmitted Index of refraction for transmitted material
peFresnelDielectric(float etaIncident, float etaTransmitted);
Spectrum_t Eval(float cosi) const override;
private:
const float _etaIndicent, _etaTransmitted;
};
#pragma endregion
//! \brief BRDF for specular reflection
class PE_CORE_API peSpecularReflection : public peBxDF {
public:
peSpecularReflection(const Spectrum_t &spectrum, const peFresnel &fresnel);
Spectrum_t Eval(const glm::vec3 &wo, const glm::vec3 &wi) const override;
Spectrum_t Sample_f(const glm::vec3 &wo, glm::vec3 &wi, const float rnd1,
const float rnd2, float &pdf) const override;
private:
const Spectrum_t _color;
const peFresnel &_fresnel;
};
//! \brief Lambertian diffuse reflection
class PE_CORE_API peLambert : public peBxDF {
public:
explicit peLambert(const Spectrum_t &color);
Spectrum_t Eval(const glm::vec3 &wo, const glm::vec3 &wi) const override;
Spectrum_t rho(const glm::vec3 &wo,
const gsl::span<glm::vec2> &samples) const override;
Spectrum_t rho(const gsl::span<glm::vec2> &samples1,
const gsl::span<glm::vec2> &samples2) const override;
private:
const Spectrum_t _color;
};
//! \brief Random values for BSDF sampling
struct PE_CORE_API BSDFSample {
BSDFSample() = default;
BSDFSample(const glm::vec2 &dir, float component);
template <typename Rnd> explicit BSDFSample(Rnd &rng) {
std::uniform_real_distribution<float> dist{0.f, 1.f};
dir = {dist(rng), dist(rng)};
component = dist(rng);
}
glm::vec2 dir;
float component;
};
//! \brief Bidirectional scattering distribution function. Determines surface
//! properties of an object
class PE_CORE_API BSDF {
public:
BSDF();
BSDF(const BSDF &other);
BSDF(BSDF &&other) noexcept;
BSDF &operator=(const BSDF &);
BSDF &operator=(BSDF &&) noexcept;
void Add(peBxDF const *bxdf);
uint32_t NumBxDFs() const;
uint32_t NumBxDFsWithFlags(BxDFType flags) const;
//! \brief Evaluate the BSDF for the given set of incoming and outgoing
//! vectors \param outgoingWorld Outgoing vector in world space \param
//! incomingWorld Incoming vector in world space \param shadingCoordSys
//! Shading coordinate system \param flags Types of BxDFs to sample \param
//! geometricNormal The normal of the actual geometry for the evaluated point
//! \returns Evaluated spectrum
Spectrum_t Eval(const glm::vec3 &outgoingWorld,
const glm::vec3 &incomingWorld,
const peCoordSys &shadingCoordSys,
const glm::vec3 &geometricNormal, BxDFType flags) const;
//! \brief Sample this BSDF by evaluating a random BxDF
Spectrum_t Sample_f(const glm::vec3 &wo, glm::vec3 &wi,
const peCoordSys &shadingCoordSys,
const glm::vec3 &geometryNormal, const BSDFSample &sample,
float &pdf, BxDFType flags, BxDFType &sampledType) const;
//! \brief Sums up the hemispherical-hemispherical reflectance values of
//! all assigned BxDFs \param rnd Random number generator for monte carlo
//! method \param flags Types of BxDFs to sample \param sqrtSamples
//! Sampling parameter for monte carlo \returns Summed reflectance
Spectrum_t rho(std::default_random_engine &rnd,
BxDFType flags = BxDFType::All,
uint32_t sqrtSamples = 6) const;
//! \brief Sums up the hemispherical-directional reflectance values of all
//! assigned BxDFs \param wo Outgoing direction \param rnd Random number
//! generator for monte carlo method \param flags Types of BxDFs to sample
//! \param sqrtSamples Sampling parameter for monte carlo
//! \returns Summed reflectance
Spectrum_t rho(const glm::vec3 &wo, std::default_random_engine &rnd,
BxDFType flags = BxDFType::All,
uint32_t sqrtSamples = 6) const;
//! \brief Probability density function of this BSDF for the given pair of
//! vectors \param wo Outgoing vector in world space \param wi Incoming vector
//! in world space
float Pdf(const glm::vec3 &wo, const glm::vec3 &wi,
const peCoordSys &shadingCoordSys,
BxDFType flags = BxDFType::All) const;
private:
constexpr static size_t MaxBxDF = 8;
uint32_t _numBxdfs;
std::array<peBxDF const *, MaxBxDF> _bxdfs;
};
#pragma region HelperFunctions
//! \brief Computes fresnel reflectance for dielectric materials
//! \param cosIncident Cosine of angle of incident direction
//! \param cosTransmitted Cosine of angle of transmitted direction
//! \param etaIncident Index of refraction for incident medium
//! \param etaTransmitted Index of refraction for transmitted medium
//! \returns Fresnel reflectance
Spectrum_t PE_CORE_API FresnelDielectric(float cosIncident,
float cosTransmitted,
const Spectrum_t &etaIncident,
const Spectrum_t &etaTransmitted);
//! \brief Computes the fresnel reflectance for a conducting material
//! \param cosIndicent Cosine of the angle of incident direction
//! \param eta Index of refraction of the conductor
//! \param k Absorption coefficient
//! \returns Fresnel reflectance
Spectrum_t PE_CORE_API FresnelConductor(float cosIndicent,
const Spectrum_t &eta,
const Spectrum_t &k);
//! \brief Helper to evaluate fresnel shading for dieletric materials
//! \param cosIncident Cosine of angle of incident direction
//! \param etaIncident Index of refraction of incident medium
//! \param etaTransmitted Index of refraction of transmitted medium
//! \returns Fresnel reflectance
Spectrum_t PE_CORE_API EvalFresnelDielectric(float cosIncident,
float etaIncident,
float etaTransmitted);
#pragma endregion
} // namespace pe
#pragma warning(pop)
| {
"alphanum_fraction": 0.7023942094,
"avg_line_length": 37.9436619718,
"ext": "h",
"hexsha": "5e4e74eda0aa09dfa14ff56d1d40873ba17030a5",
"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": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Mortano/Prismatic",
"max_forks_repo_path": "PrismaticCore/Headers/Rendering/Utility/peBxDF.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64",
"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": "Mortano/Prismatic",
"max_issues_repo_path": "PrismaticCore/Headers/Rendering/Utility/peBxDF.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Mortano/Prismatic",
"max_stars_repo_path": "PrismaticCore/Headers/Rendering/Utility/peBxDF.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2630,
"size": 10776
} |
//
// Created by karl_ on 2020-5-3.
//
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#include <core/color-space.h>
#include <imgproc/histogram-equalization.h>
#include "color-convert.h"
// ref: https://www.math.uci.edu/icamp/courses/math77c/demos/hist_eq.pdf
static void
histeq(double const *src, unsigned src_stride, double *dst, unsigned dst_stride, size_t area, unsigned range) {
unsigned *cdf;
size_t i;
cdf = calloc(range, sizeof(unsigned));
for (i = 0; i < area; ++i) {
cdf[(int) (src[i * src_stride] * range)] += 1;
}
for (i = 1; i < range; ++i) {
cdf[i] += cdf[i - 1];
}
for (i = 0; i < area; ++i) {
dst[i * dst_stride] = floor((double) (range - 1) * cdf[(int) (src[i * src_stride] * range)] / area) / range;
}
free(cdf);
}
static gboolean histeq_grayscale(CoreImage *src, CoreImage **dst) {
gdouble *src_data_cast = NULL;
gdouble *dst_data_cast = NULL;
gpointer src_data, dst_data;
CoreSize *size = NULL;
guint8 channel;
gsize i, area;
CoreColorSpace color_space;
CorePixelType pixel_type;
gdouble range, inv_range;
g_return_val_if_fail(src != NULL, FALSE);
g_return_val_if_fail(dst != NULL, FALSE);
channel = core_image_get_channel(src);
g_return_val_if_fail(channel == 1, FALSE);
src = g_object_ref(src);
src_data = core_image_get_data(src);
size = core_image_get_size(src);
area = core_size_get_area(size);
color_space = core_image_get_color_space(src);
pixel_type = core_image_get_pixel_type(src);
range = core_pixel_get_range(pixel_type);
inv_range = 1.0 / range;
/* cast to double and normalize pixel data to [0, 1] */
if (core_pixel_is_double(pixel_type)) {
src_data_cast = src_data;
} else if (core_pixel_is_uint8(pixel_type)) {
src_data_cast = g_malloc(sizeof(gdouble) * area);
for (i = 0; i < area; ++i) {
src_data_cast[i] = ((guint8 *) src_data)[i] * inv_range;
}
} else {
g_return_val_if_fail(FALSE, FALSE);
}
dst_data_cast = g_malloc(sizeof(gdouble) * area);
/* run the algorithm */
histeq(src_data_cast, 1, dst_data_cast, 1, area, 256);
/* cast back to uchar */
if (core_pixel_is_double(pixel_type)) {
/* exactly do nothing */
} else if (core_pixel_is_uint8(pixel_type)) {
/* reuse allocated memory */
for (i = 0; i < area; ++i) {
((guint8 *) dst_data_cast)[i] = dst_data_cast[i] * 255.0;
}
} else {
g_return_val_if_fail(FALSE, FALSE);
}
dst_data = dst_data_cast;
if (core_pixel_is_uint8(pixel_type)) {
/* release useless memory, can be removed for speed */
dst_data = g_realloc(dst_data, sizeof(guint8) * area);
}
if (*dst == NULL) {
*dst = core_image_new_with_data(dst_data, color_space, pixel_type, size, FALSE);
} else {
core_image_assign_data(*dst, dst_data, color_space, pixel_type, size, FALSE);
}
/* free allocated additional memory */
if (core_pixel_is_uint8(pixel_type)) {
g_free(src_data_cast);
}
g_object_unref(size);
g_object_unref(src);
return TRUE;
}
static gboolean histeq_hsl(CoreImage *src, CoreImage **dst) {
gdouble *src_data, *dst_data;
CoreSize *size;
gsize area, block_size;
src_data = core_image_get_data(src);
size = core_image_get_size(src);
area = core_size_get_area(size);
block_size = area * 3 * sizeof(gdouble);
dst_data = g_malloc(block_size);
memcpy(dst_data, src_data, block_size);
histeq(src_data + 2, 3, dst_data + 2, 3, area, 255);
if (*dst == NULL) {
*dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE);
} else {
core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE);
}
g_object_unref(size);
}
gboolean imgproc_histogram_equalization(CoreImage *src, CoreImage **dst) {
CoreColorSpace src_color_space = core_image_get_color_space(src);
CoreImage *dummy = NULL;
gboolean ret;
if (src_color_space == CORE_COLOR_SPACE_GRAY_SCALE) {
ret = histeq_grayscale(src, dst);
} else {
if (src_color_space == CORE_COLOR_SPACE_RGB) {
imgproc_to_HSL(src, &dummy);
} else {
dummy = g_object_ref(src);
}
ret = histeq_hsl(dummy, dst);
g_object_unref(dummy);
if (src_color_space == CORE_COLOR_SPACE_RGB) {
imgproc_to_RGB(*dst, dst);
}
}
return ret;
}
| {
"alphanum_fraction": 0.614198183,
"avg_line_length": 31.9797297297,
"ext": "c",
"hexsha": "2526733226a04c49b317549dad62410a97cddc57",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2020-06-07T11:19:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-30T14:45:36.000Z",
"max_forks_repo_head_hexsha": "cb40bfe3b46b2cd06e871eb059e12b19a7cac5dd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Mr9567/EasyPhotoshop",
"max_forks_repo_path": "imgproc/histogram-equalization.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "cb40bfe3b46b2cd06e871eb059e12b19a7cac5dd",
"max_issues_repo_issues_event_max_datetime": "2020-06-08T09:03:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-06T06:45:05.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Mr9567/EasyPhotoshop",
"max_issues_repo_path": "imgproc/histogram-equalization.c",
"max_line_length": 117,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "cb40bfe3b46b2cd06e871eb059e12b19a7cac5dd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Mr9567/EasyPhotoshop",
"max_stars_repo_path": "imgproc/histogram-equalization.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-06T01:09:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-04T15:33:41.000Z",
"num_tokens": 1257,
"size": 4733
} |
/******************************************************************************
* *
* DECS.H *
* *
* GLOBAL MACROS, FUNCTION DEFINITIONS, INCLUDES, AND DECLARATIONS *
* *
******************************************************************************/
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_vector.h>
#include <limits.h>
#include <math.h>
#include <mpi.h>
#include <omp.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "constants.h"
#include "params.h"
/*******************************************************************************
PRE-PROCESSOR MAGIC :
*******************************************************************************/
#define XSTR(x) STR(x)
#define STR(x) #x
/*******************************************************************************
CONSTANTS :
*******************************************************************************/
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923132169164
#endif
#ifndef M_SQRT2
#define M_SQRT2 1.4142135623730950488016887242
#endif
/*******************************************************************************
COMPILE-TIME PARAMETERS :
*******************************************************************************/
// Number of active zones on each MPI process
#define N1 (N1TOT / N1CPU)
#define N2 (N2TOT / N2CPU)
#define N3 (N3TOT / N3CPU)
// Max size for 1D slice is NMAX
#define N12 (N1 > N2 ? N1 : N2)
#define NMAX (N12 > N3 ? N12 : N3)
#define NDIM (4) // Number of total dimensions
#define NPG (5) // Number of positions on grid for grid functions
#define NG (3) // Number of ghost zones
#define N123G \
((N1 + 2 * NG) * (N2 + 2 * NG) * \
(N3 + 2 * NG)) // total number of cells on a cpu
// Fixup parameters
// rho_flor = RHOMIN / pow(r, -FLOOR_POWER)
#define FLR_POWER1 (2.)
#define FLR_POWER2 (2.)
#define FLR_R0 (50.) // TODO change this?
#define RHOMINLIMIT (1.e-17)
#define UUMINLIMIT (1.e-3 * RHOMINLIMIT)
#define RHOMIN (1.e-5)
#define UUMIN (1.e-3 * RHOMIN)
#define BSQORHOMAX (50.)
#define BSQOUMAX (2500.)
#define RHOEPS (0.9)
#define UORHOMAX (50.)
#define COLD_FLOORS (1)
#define ATM_THRESH (0.1)
// Numerical convenience to represent a small (<< 1) non-zero quantity
#define SMALL (1.e-20)
#define ABSURDLY_LARGE (1.e100)
// Maximum value of gamma, the Lorentz factor
#define GAMMAMAX (50.)
// Maximum fractional increase in timestep per timestep
#define SAFE (1.3)
// Superphoton diagnostics
#define MAXNSCATT (3)
// Chosen to give some wiggle room
// in scattering stability criterion
#define SCATT_BIAS_SAFETY (0.75) // (0.9/RAD_SCATT_TYPES)
//#define NUMIN (1.e10)
//#define NUMAX (1.e25)
//#define NU_BINS_SPEC (200)
//#define NTH (8)
//#define NPHI (8)
// Whether to move polar axis slightly off of coordinate singularity
#define COORDSINGFIX 1
#define SINGSMALL (1.E-20)
// Whether to record a representative sample of superphoton positions
#define TRACK_PH (0)
// I/O format strings
#define FMT_DBL_OUT "%28.18e"
#define FMT_INT_OUT "%10d"
#define STRLEN (2048)
// Reconstruction algorithms
#define LINEAR (0)
#define PPM (1)
#define WENO (2)
#define MP5 (3)
// Primitive and conserved variables
#define RHO (0)
#define UU (1)
#define U1 (2)
#define U2 (3)
#define U3 (4)
#define B1 (5)
#define B2 (6)
#define B3 (7)
#define NVAR_BASE (B3 + 1)
// Passive variables (if present)
#define PASSIVE_START (NVAR_BASE)
#define PASSIVE_STOP (NVAR_BASE + NVAR_PASSIVE)
#define PASSTYPE_INTRINSIC (0)
#define PASSTYPE_NUMBER (1)
#if EOS == EOS_TYPE_TABLE
#define YE (PASSIVE_START)
#define YE_EM (YE + 1)
#if METRIC == MKS
#define ATM (YE + 2)
#define IS_ATM (0.0)
#define NOT_ATM (1.0)
#endif // METRIC
#endif // EOS_TYPE_TABLE
#if ELECTRONS
#define KEL (B3 + NVAR_PASSIVE + 1)
#define KTOT (B3 + NVAR_PASSIVE + 2)
#define NVAR (NVAR_BASE + NVAR_PASSIVE + 2)
#else
#define NVAR (NVAR_BASE + NVAR_PASSIVE)
#endif
// NETRINOS
#define RATYPE_NONE (0)
#define RADTYPE_LIGHT (1)
#define RADTYPE_NEUTRINOS (2)
#define RAD_TYPE_START (0)
#define TYPE_TRACER (-1)
#if RADIATION == RADTYPE_NEUTRINOS
#define RAD_NUM_TYPES (3)
#define NU_ELECTRON (0)
#define ANTINU_ELECTRON (1)
#define NU_HEAVY (2)
#if MULTISCATT_TEST
#define RAD_SCATT_TYPES (3)
#else
#define RAD_SCATT_TYPES (4) // TODO: Should be 5, including electrons
#define RSCATT_TYPE_P (0)
#define RSCATT_TYPE_N (1)
#define RSCATT_TYPE_A (2)
#define RSCATT_TYPE_ALPHA (3)
#define RSCATT_TYPE_E (4) // TOOD: implement me
#endif
#define NRADCOMP (2)
#define RADG_YE (4)
#define RADG_YE_EM (5)
#elif RADIATION == RADTYPE_LIGHT
#define RAD_NUM_TYPES (1)
#define RAD_SCATT_TYPES (1)
#define NRADCOMP (0)
#define PHOTON (0)
#else
#define RAD_NUM_TYPES (0)
#define RAD_SCATT_TYPES (0)
#define NRADCOMP (0)
#endif
#define DLEPTON_THRESH (1e-10)
// EOS
#define EOS_TYPE_GAMMA (0)
#define EOS_TYPE_POLYTROPE (1)
#define EOS_TYPE_TABLE (2)
#if EOS == EOS_TYPE_GAMMA
#define EOS_NUM_EXTRA (0)
#define POLYTROPE_FALLBACK (0)
#elif EPS == EOS_TYPE_POLYTROPE
#define EOS_NUM_EXTRA (0)
#define POLYTROPE_FALLBACK (0)
#elif EOS == EOS_TYPE_TABLE
#if GAMMA_FALLBACK
#define POLYTROPE_FALLBACK (0)
// #define POLYTROPE_FALLBACK (1)
#else
#define POLYTROPE_FALLBACK (1)
#endif // GAMMA_FALLBACK
#define EOS_NUM_EXTRA (3)
#define EOS_LRHO (0)
#define EOS_LT (1)
#define EOS_YE (2)
// mass fractions
#define NUM_MASS_FRACTIONS (4)
#define MF_XA (0)
#define MF_XH (1)
#define MF_XN (2)
#define MF_XP (3)
#endif // EOS
// Centering of grid functions
#define FACE1 (0)
#define FACE2 (1)
#define FACE3 (2)
#define CORN (3)
#define CENT (4)
#define FACESTART (FACE1)
#define FACEEND (FACE3 + 1)
#define PGSTART (FACE1)
#define PGEND (NPG)
// Slope limiter
#define MC (0)
#define VANL (1)
#define MINM (2)
// Fluid and radiation boundaries
#define BC_OUTFLOW (0)
#define BC_PERIODIC (1)
#define BC_POLAR (2)
#define BC_PROB (3)
#define BC_ESCAPE (4)
#define BC_CAMERA (5)
#define BC_EQUILIB (6)
// Metric
#define MINKOWSKI (0)
#define SPHERICAL (1)
#define MKS (2)
// Diagnostic calls
#define DIAG_INIT (0)
#define DIAG_DUMP (1)
#define DIAG_LOG (2)
#define DIAG_FINAL (3)
// Types of restarts
#define RESTART_TEMP (0)
#define RESTART_PERM (1)
// Failure modes
#define FAIL_UTOPRIM (0)
#define FAIL_VCHAR_DISCR (1)
#define FAIL_COEFF_NEG (2)
#define FAIL_COEFF_SUP (3)
#define FAIL_GAMMA (4)
#define FAIL_METRIC (5)
// Geodesic integration and interpolation
#define PUSH_FAIL (0)
#define PUSH_SUCCESS (1)
#define SPH_INTERP_FAIL (0)
#define SPH_INTERP_SUCCESS (1)
// Root finding
#define ROOT_SUCCESS (1)
#define ROOT_FAIL (0)
#define FCOUNT_NBINS (6)
#define FCOUNT_MORE (FCOUNT_NBINS - 1)
// Timers
#define TIMER_UPDATE (0)
#define TIMER_FLUXCALC (1)
#define TIMER_FIXUP (2)
#define TIMER_BOUND (3)
#define TIMER_DIAG (4)
#define TIMER_OUT (5)
#define TIMER_ELECTRON (6)
#define TIMER_MAKE (7)
#define TIMER_PUSH (8)
#define TIMER_INTERACT (9)
#define TIMER_MICRO (10)
#define TIMER_ALL (11)
#define NUM_TIMERS (12)
// Units
#define NEED_UNITS (RADIATION || EOS == EOS_TYPE_TABLE)
/*******************************************************************************
GLOBAL ARRAYS
*******************************************************************************/
typedef double grid_prim_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NVAR];
typedef double grid_double_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];
typedef double grid_radtype_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]
[RAD_NUM_TYPES];
typedef double grid_fourvector_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]
[NDIM];
typedef double grid_radg_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]
[NDIM + NRADCOMP];
typedef double grid_tensor_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM]
[NDIM];
typedef int grid_int_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];
typedef double grid_eosvar_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]
[EOS_NUM_EXTRA];
typedef void (*passive_init_ftype)(int, int, int, double *, double *);
typedef double (*hc_ftype)(double, double);
extern grid_prim_type P; // Primitive variables
extern grid_prim_type F1; // X1 fluxes
extern grid_prim_type F2; // X2 fluxes
extern grid_prim_type F3; // X3 fluxes
extern grid_prim_type Ph; // Half-step primitives
extern grid_prim_type Psave; // Half-step primitives
extern grid_int_type pflag; // Failure points
extern grid_int_type fail_save;
extern grid_int_type fixup_required;
extern grid_fourvector_type jcon;
extern grid_eosvar_type extra; // extra variables needed by EOS
#if RADIATION
extern grid_radg_type radG; // Radiation four-force
extern grid_radg_type radG_int; // ...integrated
extern grid_radg_type radG_buf; // ...buffer for communication
extern grid_tensor_type Rmunu; // Radiation stress-energy tensor
extern grid_int_type Nsph;
extern grid_double_type nph;
extern struct of_photon **photon_lists;
extern struct of_photon **photon_mpi_lists;
#if DIAGNOSTICS_USE_RADTYPES
#define NULNU_IDX0 (RAD_NUM_TYPES)
#else
#define NULNU_IDX0 (MAXNSCATT + 1)
#endif
extern double nuLnu[NULNU_IDX0][NTH][NPHI][NU_BINS_SPEC];
#if RADIATION == RADTYPE_NEUTRINOS
extern double rad_type_counts[RAD_NUM_TYPES];
extern double lepton_tot, lepton_last, dlepton_tot, dlepton_perc;
extern double lepton_gas, lepton_rad;
extern double lepton_lost, lepton_lost_step, lepton_lost_local;
#endif
extern double Jrad[MAXNSCATT + 2][N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];
extern double Jrad_buf[MAXNSCATT + 2][N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];
extern double dtau_avg[RAD_SCATT_TYPES + 1][N1 + 2 * NG][N2 + 2 * NG]
[N3 + 2 * NG];
extern double en_int_avg[RAD_SCATT_TYPES + 1][N1 + 2 * NG][N2 + 2 * NG]
[N3 + 2 * NG];
extern grid_int_type Nem, Nabs, Nsc;
extern grid_radtype_type Nem_phys, Nabs_phys, radtype_buf;
extern grid_int_type Nsuper;
extern grid_double_type Esuper;
extern grid_prim_type psupersave;
#endif // RADIATION
// Default initialization is 0, which in this case is
// PASSTYPE_INTRINSIC, i.e., volume densities.
extern int passive_type[NVAR_PASSIVE];
extern char passive_name[NVAR_PASSIVE][STRLEN];
extern passive_init_ftype do_passive_fixup[NVAR_PASSIVE];
#if ELECTRONS
extern grid_double_type Qvisc, Qcoul;
#endif // ELECTRONS
/*******************************************************************************
GLOBAL VARIABLES SECTION
*******************************************************************************/
// Command line arguments
extern char outputdir[STRLEN], dumpdir[STRLEN], restartdir[STRLEN];
extern char xmfdir[STRLEN];
#if RADIATION && TRACERS
extern char tracerdir[STRLEN];
#endif
extern char init_from_grmhd[STRLEN];
extern char metric[STRLEN], reconstruction[STRLEN];
extern char eos[STRLEN], nulnutype[STRLEN];
extern int tracers;
// path for eos
#if EOS == EOS_TYPE_TABLE
extern char eospath[STRLEN];
#endif
// opacity table paths
#if RADIATION
#if (RADIATION == RADTYPE_NEUTRINOS)
#if BURROWS_OPACITIES
extern char opac_param_file[STRLEN];
extern char opac_file[STRLEN];
#endif // BURROWS
#if HDF5_OPACITIES
extern char opac_file[STRLEN];
#endif // hdf5
#endif // neutrinos
#endif // radiation
// Physics parameters
extern double a;
#if EOS == EOS_TYPE_GAMMA || GAMMA_FALLBACK
extern double gam;
#endif
#if EOS == EOS_TYPE_POLYTROPE
extern double poly_K, poly_gam;
#endif
#if POLYTROPE_FALLBACK
extern double rho_poly_thresh;
#endif
extern double M_unit;
extern double Reh;
extern double Risco;
#if NEED_UNITS
extern double mbh, Mbh, L_unit, T_unit, M_unit, RHO_unit, U_unit, B_unit;
#endif
#if EOS == EOS_TYPE_TABLE
extern double TEMP_unit;
#endif
#if RADIATION
extern double Ne_unit, Thetae_unit, kphys_to_num;
extern double tp_over_te, thetae_max, sigma_max, kdotk_tol;
#endif
// Numerical parameters
extern double Rin, Rout, Rout_vis, hslope;
extern double poly_norm, poly_xt, poly_alpha, mks_smooth;
#if RADIATION
extern double Rout_rad;
extern double nph_per_proc;
extern double tune_emiss, t_tune_emiss, dt_tune_emiss;
extern double tune_scatt, t_tune_scatt, dt_tune_scatt;
extern int made_tune_proc, abs_tune_proc, scatt_tune_proc;
extern double numin, numax;
extern double kappa;
extern double startx_rad[NDIM], stopx_rad[NDIM];
extern double wgtC;
extern int step_made, step_abs, step_scatt, step_lost, step_rec, step_tot;
extern int tracer_tot, tracer_tot_all, ntcr_per_proc;
extern int step_sent, step_rcvd, step_fail;
extern int step_made_all, step_abs_all, step_scatt_all, step_lost_all;
extern int step_rec_all, step_sent_all, step_rcvd_all, step_tot_all;
extern int step_fail_all;
extern int step_tot_max, step_tot_min;
extern double load_imbalance;
extern double Nph_to_track;
extern double sim_vol;
#if FLATEMISS
extern double cnu_flat;
#endif // FLATEMISS
#if MULTISCATT_TEST
extern double ms_theta_nu0, ms_delta0;
#endif // MULTISCATT_TEST
#endif // RADIATION
#if ELECTRONS
extern double tptemin, tptemax;
#endif
extern double cour;
#if RADIATION
extern double cour_cool;
#endif
extern double dV, dx[NDIM], startx[NDIM], stopx[NDIM], startx_proc[NDIM],
stopx_proc[NDIM];
extern double x1Min, x1Max, x2Min, x2Max, x3Min, x3Max;
extern double dt, dtsave;
extern double t, tf;
extern int nstep;
extern int is_restart;
// Output parameters
extern double DTd;
extern double DTl;
extern double DTr;
extern int DNr;
extern int DTp;
extern int DTf;
extern double DTw;
extern int dump_cnt;
extern int rdump_cnt;
extern double tdump, trestart, tlog;
extern double root_fcount[FCOUNT_NBINS];
// Global flags
extern int failed;
extern int lim;
// Diagnostics
extern double mdot, mdot_eh;
extern double edot, edot_eh;
extern double ldot, ldot_eh;
extern int icurr, jcurr, kcurr;
// Parallelism
extern int nthreads;
// Electrons
#if ELECTRONS
extern double game, gamp;
extern double fel0;
#endif
// Set global variables that indicate current local metric, etc.
struct of_geom {
double gcon[NDIM][NDIM];
double gcov[NDIM][NDIM];
double g;
double alpha;
};
struct of_state {
double ucon[NDIM];
double ucov[NDIM];
double bcon[NDIM];
double bcov[NDIM];
};
#if RADIATION
// WARNING: if you change struct_of_photon, be sure to change
// the the photon hdf5 and MPI types in io.c and mpi.c
#define NSUP 3
struct of_photon {
// NSUP >=3 X^{\mu}, K^{\mu}, K_{\mu} so photon data always available anywhere
// between n and n+1
double X[NSUP][NDIM];
double Kcov[NSUP][NDIM];
double Kcon[NSUP][NDIM];
double w;
double KdotKprev;
// radiation type. For neutrinos, flavor. Always active.
// Not always important.
// TODO: make sure to always set type when it's needed.
int type;
int nscatt;
int origin[NDIM];
double t0;
int is_tracked;
struct of_photon *next;
};
#define PH_ELEM (11)
struct of_track_photon {
double X1;
double X2;
double X3;
int nscatt;
};
struct of_microphysics {
#if RADIATION == RADTYPE_NEUTRINOS
double rho;
double T;
double Ye;
double Abar, Zbar;
double Xi[NUM_MASS_FRACTIONS];
#if BURROWS_OPACITIES || HDF5_OPACITIES
double jgrp[RAD_NUM_TYPES][NU_BINS + 1];
double alphagrp[RAD_NUM_TYPES][NU_BINS + 1];
#endif
#else // RADTYPE_LIGHT
double Thetae;
double Ne;
#endif
// needed for Bk-angle (which isn't really needed for neutrinos, but
// this is the easy engineering solution)
double B;
};
typedef double (*dsdom_ftype)(
double, double, const struct of_microphysics *, int, int);
#endif // RADIATION
#if EOS == EOS_TYPE_TABLE
struct of_adiabat {
double s, ye;
double lrho_min, lrho_max;
int imin, imax;
double hm1_min, hm1_max;
double *lT;
};
#endif
#if EOS == EOS_TYPE_TABLE || HDF_OPACITIES || BURROWS_OPACITIES
struct of_tablebounds {
int Nrho, NT, NYe;
double lrho_min, lrho_max, dlrho;
double lT_min, lT_max, dlT;
double Ye_min, Ye_max, dYe;
};
#endif
// More grid functions. Axisymmetry assumed.
extern double conn[N1 + 2 * NG][N2 + 2 * NG][NDIM][NDIM][NDIM];
extern struct of_geom ggeom[N1 + 2 * NG][N2 + 2 * NG][NPG];
#if RADIATION
// extern double dt_light, dt_light_min;
extern double dt_light[N1 + 2 * NG][N2 + 2 * NG], dt_light_min;
extern struct of_microphysics m_grd[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];
extern grid_fourvector_type Ucon_grd, Ucov_grd, Bcon_grd, Bcov_grd;
#endif
// MPI-specific stuff
extern int global_start[NDIM];
extern int global_stop[NDIM];
/*******************************************************************************
MACROS
*******************************************************************************/
#define ILOOP for (int i = 0 + NG; i < N1 + NG; i++)
#define ILOOPALL for (int i = 0; i < N1 + 2 * NG; i++)
#define JLOOP for (int j = 0 + NG; j < N2 + NG; j++)
#define JLOOPALL for (int j = 0; j < N2 + 2 * NG; j++)
#define KLOOP for (int k = 0 + NG; k < N3 + NG; k++)
#define KLOOPALL for (int k = 0; k < N3 + 2 * NG; k++)
#define ZLOOP \
for (int i = 0 + NG; i < N1 + NG; i++) \
for (int j = 0 + NG; j < N2 + NG; j++) \
for (int k = 0 + NG; k < N3 + NG; k++)
#define ZLOOPALL ILOOPALL JLOOPALL KLOOPALL
#define ISLOOP(istart, istop) for (int i = istart + NG; i <= istop + NG; i++)
#define JSLOOP(jstart, jstop) for (int j = jstart + NG; j <= jstop + NG; j++)
#define KSLOOP(kstart, kstop) for (int k = kstart + NG; k <= kstop + NG; k++)
#define ZSLOOP(istart, istop, jstart, jstop, kstart, kstop) \
for (int i = istart + NG; i <= istop + NG; i++) \
for (int j = jstart + NG; j <= jstop + NG; j++) \
for (int k = kstart + NG; k <= kstop + NG; k++)
// Loop over faces
#define FACELOOP for (int face = FACESTART; face < FACEEND; face++)
// Loop over all locations
#define LOCLOOP for (int loc = PGSTART; loc < PGEND; loc++)
// Loop over primitive variables
#define PLOOP for (int ip = 0; ip < NVAR; ip++)
#define BASELOOP for (int ip = 0; ip < NVAR_BASE; ip++)
// Loop over spacetime indices
#define DLOOP1 for (int mu = 0; mu < NDIM; mu++)
#define DLOOP2 \
for (int mu = 0; mu < NDIM; mu++) \
for (int nu = 0; nu < NDIM; nu++)
#define DLOOP3 \
for (int mu = 0; mu < NDIM; mu++) \
for (int nu = 0; nu < NDIM; nu++) \
for (int sigma = 0; sigma < NDIM; sigma++)
// spacelike indices
#define SDLOOP for (int mu = 1; mu < NDIM; mu++)
// Loop over extra variables
// TODO: Figure out how to make this conditionally defined. ~JMM
#define EOS_ELOOP for (int e = 0; e < EOS_NUM_EXTRA; e++)
// Loop over passive scalars
#define PASSLOOP for (int ipass = PASSIVE_START; ipass < PASSIVE_STOP; ipass++)
#define PASSELEM(ipass) (ipass - PASSIVE_START)
#define PASSTYPE(ipass) (passive_type[PASSELEM(ipass)])
#define PASSNAME(ipass) (passive_name[PASSELEM(ipass)])
#define TYPELOOP for (int itp = RAD_TYPE_START; itp < RAD_NUM_TYPES; itp++)
#define SCATTLOOP for (int iscatt = 0; iscatt < RAD_SCATT_TYPES; iscatt++)
#define JRADLOOP for (int n = 0; n < MAXNSCATT + 2; n++)
#define NULOOP for (int inu = 0; inu < NU_BINS + 1; inu++)
#define MY_MIN(fval1, fval2) (((fval1) < (fval2)) ? (fval1) : (fval2))
#define MY_MAX(fval1, fval2) (((fval1) > (fval2)) ? (fval1) : (fval2))
#define MY_SIGN(fval) (((fval) < 0.) ? -1. : 1.)
#define delta(i, j) ((i == j) ? 1. : 0.)
#define dot(a, b) (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3])
/*******************************************************************************
FUNCTION DECLARATIONS
*******************************************************************************/
// bounds.c
void bound_prim(grid_prim_type prim);
void fix_flux(grid_prim_type F1, grid_prim_type F2, grid_prim_type F3);
#if RADIATION
void bound_superphotons(grid_prim_type P, double t, double dt);
void polar_fix(double X[NDIM], struct of_photon *ph);
int rad_error_check(struct of_photon **ph);
// int rad_boundary_transport(double X[NDIM], double Kcov[NDIM]);
void bound_rad_transport(
double X[NDIM], struct of_photon *ph, int is_transported);
int bound_rad_isactive(double X[NDIM], struct of_photon *ph);
int rad_mpi_transport(struct of_photon **ph, struct of_photon **prev,
struct of_photon **head, double X[NDIM], int active);
#endif
// coord.c
void coord(int i, int j, int k, int loc, double X[NDIM]);
double r_of_X(const double X[NDIM]);
double th_of_X(const double X[NDIM]);
void jac_harm_to_bl(
const double X[NDIM], double Jcov[NDIM][NDIM], double Jcon[NDIM][NDIM]);
void jac_bl_to_cart(
const double X[NDIM], double Jcov[NDIM][NDIM], double Jcon[NDIM][NDIM]);
void jac_harm_to_cart(
const double X[NDIM], double Jcov[NDIM][NDIM], double Jcon[NDIM][NDIM]);
void set_dxdX(double X[NDIM], double dxdX[NDIM][NDIM]);
void bl_coord(const double X[NDIM], double *r, double *th);
int bl_i_of_r(double r);
void cart_coord(const double X[NDIM], double Xcart[NDIM]);
void set_gcov(double X[NDIM], double gcov[NDIM][NDIM]);
void set_metric(double X[NDIM], struct of_geom *g);
void set_points();
void zero_arrays(void);
void set_grid(void);
void cart_to_sph(const double X[NDIM], double *r, double *th, double *ph);
// current.c
void current_calc();
// diag.c
void reset_log_variables();
void reset_dump_variables();
void diag(int call_code);
void fail(int fail_type);
void area_map(int i, int j, int k, grid_prim_type prim);
void diag_flux(grid_prim_type F1, grid_prim_type F2, grid_prim_type F3);
double flux_ct_divb(int i, int j, int k);
#if RADIATION
void record_superphoton(double X[NDIM], struct of_photon *ph);
void bin_all_superphotons();
void report_load_imbalance();
#if RADIATION == RADTYPE_NEUTRINOS
void print_rad_types();
void count_leptons(grid_prim_type P, double dt, int nstep);
#endif
#endif
// electrons.c
#if ELECTRONS
void init_electrons();
void heat_electrons(
grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt);
double get_fel(int i, int j, int k, double p[NVAR]);
#if RADIATION
void coulomb(
grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt);
void apply_rad_force_e(
grid_prim_type Prh, grid_prim_type Pr, grid_radg_type radG, double Dt);
#endif // RADIATION
void fixup_electrons(grid_prim_type p);
#endif
// emissivity.c
#if RADIATION
double jnu(double nu, int type, const struct of_microphysics *m, double theta);
double Jnu(double nu, int type, const struct of_microphysics *m);
double get_J(struct of_microphysics *m);
void init_emissivity();
#endif
// eos.c
void init_EOS();
double EOS_bad_eos_error();
double EOS_get_gamma(const double *extra);
double EOS_pressure_rho0_u(double rho, double u, const double *extra);
double EOS_pressure_rho0_w(double rho, double w, double gamma,
const struct of_geom *geom, double *extra);
double EOS_enthalpy_rho0_u(double rho, double u, const double *extra);
double EOS_sound_speed_rho0_u(double rho, double u, const double *extra);
void EOS_set_floors(double scale, double rho, double u, double bsq,
double *rhoflr, double *uflr, const double *extra);
double EOS_entropy_rho0_u(double rho, double u, const double *extra);
double EOS_adiabatic_constant(double rho, double u, const double *extra);
double EOS_temperature(double rho, double u, const double *extra);
double EOS_u_press(double press, double rho, double *extra);
#if RADIATION
double EOS_u_N_Theta(double rho, double N, double Theta, double *extra);
double EOS_pressure_N_Theta(double N, double Theta);
double EOS_Theta_unit();
#endif // RADIATION
// eos_gamma.c
#if EOS == EOS_TYPE_GAMMA || GAMMA_FALLBACK
double EOS_Gamma_pressure_rho0_u(double rho, double u);
double EOS_Gamma_pressure_rho0_w(double rho, double w);
double EOS_Gamma_entropy_rho0_u(double rho, double u);
double EOS_Gamma_enthalpy_rho0_u(double rho, double u);
double EOS_Gamma_adiabatic_constant_rho0_u(double rho, double u);
double EOS_Gamma_sound_speed_rho0_u(double rho, double u);
void EOS_Gamma_set_floors(double scale, double rho, double u, double bsq,
double *rhoflr, double *uflr);
double EOS_Gamma_rho_floor(double scale, double bsq);
double EOS_Gamma_u_floor(double scale, double bsq);
double EOS_Gamma_u_scale(double rho);
double EOS_Gamma_u_press(double press);
double EOS_Gamma_temp(double rho, double u);
#if RADIATION
double EOS_Gamma_Theta_unit();
#endif // RADIATION
#endif // EOS_TYPE_GAMMA
// eos_poly.c
#if EOS == EOS_TYPE_POLYTROPE || POLYTROPE_FALLBACK
double EOS_Poly_pressure_rho0_u(double rho, double u, double K, double Gam);
double EOS_Poly_pressure_rho0_w(double rho, double w, double K, double Gam);
double EOS_Poly_enthalpy_rho0_u(double rho, double u, double K, double Gam);
double EOS_Poly_entropy_rho0_u(double rho, double u, double K, double Gam);
double EOS_Poly_sound_speed_rho0_u(double rho, double u, double K, double Gam);
void EOS_Poly_set_floors(double scale, double rho, double u, double bsq,
double *rhoflr, double *uflr);
double EOS_Poly_rho_floor(double scale, double bsq);
double EOS_Poly_u_floor(double scale, double bsq);
double EOS_Poly_adiabatic_constant(double rho, double u, double K, double Gam);
#endif // EOS_TYPE_POLY
// eos_stellar_collapse.c
#if EOS == EOS_TYPE_TABLE
void EOS_SC_init(char *name);
void EOS_SC_fill(double *restrict p, double *restrict eos);
double EOS_SC_pressure_rho0_u(double lrho, double lT, double ye);
double EOS_SC_pressure_rho0_w(double rho, double w, double ye, double *lTold);
double EOS_SC_specific_enthalpy_rho0_u(double lrho, double lT, double ye);
double EOS_SC_sound_speed(double lrho, double lT, double ye);
double EOS_SC_entropy(double lrho, double lT, double ye);
double EOS_SC_gamma(double lrho, double lT, double ye);
double EOS_SC_temperature(double lT);
double EOS_SC_get_u_of_T(double rho, double T, double ye);
double EOS_SC_u_press(double press, double rho, double ye, double *lTold);
void EOS_SC_mass_fractions(double Xi[NUM_MASS_FRACTIONS], const double *extra);
void EOS_SC_avg_ions(double *Abar, double *Zbar, const double *extra);
void EOS_SC_set_floors(double scale, double rho, double u, double ye,
double bsqr, double *rhoflr, double *uflr);
double EOS_SC_rho_floor(double scale, double bsq);
double EOS_SC_u_floor(double scale, double bsq, double ye);
double EOS_SC_get_min_lrho();
double EOS_SC_get_min_rho();
double EOS_SC_get_min_lT();
double EOS_SC_get_minu(double rho, double ye, double scale);
void EOS_SC_get_polytrope(
double lrho, double lT, double ye, double *poly_K, double *poly_gamma);
double EOS_SC_hm1_min_adiabat(const struct of_adiabat *a);
int EOS_SC_find_adiabat_1d(double s, double ye, struct of_adiabat *a);
void EOS_SC_print_adiabat(const struct of_adiabat *a);
void EOS_SC_adiabat_free(struct of_adiabat *a);
void EOS_SC_isoentropy_hm1(double hm1, const struct of_adiabat *a,
double *lrho_guess, double *rho, double *u);
void do_ye_fixup(
int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);
void do_ye_em_fixup(
int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);
void do_atm_fixup(
int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);
void EOS_SC_get_bounds(struct of_tablebounds *b);
void EOS_SC_print_table_mins();
#endif // EOS_TYPE_TABLE
// estimate_thetae.c
#if RADIATION
double get_Thetae_est(int i, int j, int k);
void estimate_Thetae(
grid_prim_type P, grid_eosvar_type extra, double t, double dt);
#endif
// fixup.c
void fixup(grid_prim_type pv, grid_eosvar_type extra);
double get_scale(int i, int j, int k);
void fixup1zone(
int i, int j, int k, double pv[NVAR], double extra[EOS_NUM_EXTRA]);
void fixup_utoprim(grid_prim_type pv, grid_eosvar_type extra);
// interact.c
#if RADIATION
void interact(grid_prim_type P, grid_eosvar_type extra, double t, double dt);
#endif
// input.c
void init_params(char *pfname);
void set_param(char *key, void *data);
// io.c
// void set_core_params();
// void set_param(char *key, void *data);
// void read_params(char *pfname);
void init_io();
void init_fluid_restart();
#if RADIATION
void track_ph();
#if TRACERS
void dump_tracers();
#endif
#endif
void dump_grid();
void dump();
void restart_write(int restart_type);
void restart_read(char *fname);
int restart_init();
// make_superphotons.c
#if RADIATION
void make_superphotons(
grid_prim_type Prad, grid_eosvar_type extra, double t, double dt);
void set_weight(grid_prim_type Prad, grid_eosvar_type extra);
void get_dnz(grid_prim_type Prad, grid_eosvar_type extra);
#endif
// metric.c
double gcon_func(double lgcov[][NDIM], double lgcon[][NDIM]);
void conn_func(double *X, struct of_geom *geom, double conn[][NDIM][NDIM]);
void lower(double ucon[NDIM], double gcov[NDIM][NDIM], double ucov[NDIM]);
void raise(double ucov[NDIM], double gcon[NDIM][NDIM], double ucon[NDIM]);
struct of_geom *get_geometry(int ii, int jj, int kk, int loc);
void blgset(int i, int j, struct of_geom *geom);
double bl_gdet_func(double r, double th);
void bl_gcov_func(double r, double th, double gcov[][NDIM]);
void bl_gcon_func(double r, double th, double gcon[][NDIM]);
double MINOR(double m[16], int r0, int r1, int r2, int c0, int c1, int c2);
void adjoint(double m[16], double adjOut[16]);
double determinant(double m[16]);
double invert(double *m, double *invOut);
// mpi.c
void init_mpi();
void sync_mpi_boundaries_X1L(grid_prim_type Pr);
void sync_mpi_boundaries_X1R(grid_prim_type Pr);
void sync_mpi_boundaries_X2L(grid_prim_type Pr);
void sync_mpi_boundaries_X2R(grid_prim_type Pr);
void sync_mpi_boundaries_X3L(grid_prim_type Pr);
void sync_mpi_boundaries_X3R(grid_prim_type Pr);
#if RADIATION
void sync_radG();
void sync_Jrad();
void sync_radtype_vec(grid_radtype_type v);
void sync_mpi_photons(
struct of_photon **ph_mpi, grid_prim_type P, double t, double dt);
void mpi_reduce_nuLnu();
#endif
int mpi_nprocs();
double mpi_max(double f);
double mpi_min(double f);
int mpi_max_int(int f);
double mpi_reduce(double f);
int mpi_reduce_int(int f);
void mpi_dbl_allreduce_array(double *A, int size);
int mpi_io_proc();
void mpi_int_broadcast(int *val);
void mpi_int_broadcast_array(int *val, int size);
void mpi_int_broadcast_proc(int *val, int root);
void mpi_dbl_broadcast(double *val);
void mpi_allgather_int1(int *buffer, int element);
int mpi_accumulate_int(int my_val);
double mpi_io_reduce(double val);
double mpi_io_max(double val);
int mpi_myrank();
void mpi_sync_output();
void mpi_barrier();
int mpi_is_periodic(int dir);
// opac_emis_neutrino.c
#if RADIATION
#if RADIATION == RADTYPE_NEUTRINOS && BURROWS_OPACITIES
void init_opac_emis_burrows();
void fill_opac_emis_burrows(struct of_microphysics *m);
double jnu_burrows(double nu, int type, const struct of_microphysics *m);
double Jnu_burrows(double nu, int type, const struct of_microphysics *m);
double int_jnudnudOmega_burrows(const struct of_microphysics *m);
double alpha_nu_burrows(double nu, int type, const struct of_microphysics *m);
void test_opac_emis();
#if EOS == EOS_TYPE_TABLE
void opac_emis_to_hdf(const char *name, const struct of_tablebounds *b);
#endif // EOS
#endif // Burrows opacities
#if RADIATION == RADTYPE_NEUTRINOS && HDF5_OPACITIES
void init_opac_emis_hdf(char *name);
void fill_opac_emis_hdf(struct of_microphysics *m);
double jnu_hdf(double nu, int type, const struct of_microphysics *m);
double Jnu_hdf(double nu, int type, const struct of_microphysics *m);
double int_jnudnudOmega_hdf(const struct of_microphysics *m);
double alpha_nu_hdf(double nu, int type, const struct of_microphysics *m);
#endif // HDF opacities
#endif // RADIATION
// passive.c
//#if NVAR_PASSIVE > 0
void fixup_passive(
int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);
void init_passives();
void name_passives();
//#endif
// phys.c
void primtoflux(double *pr, struct of_state *q, int dir, int magnetic,
struct of_geom *geom, double *flux);
void bcon_calc(double *pr, double *ucon, double *ucov, double *bcon);
void mhd_calc(double *pr, int dir, int magnetic, struct of_state *q,
double *extra, double *mhd);
void source(double *ph, struct of_geom *geom, int ii, int jj, double *dU,
double Dt, double *extra);
double bsq_calc(double *pr, struct of_geom *geom);
void get_state(double *pr, struct of_geom *geom, struct of_state *q);
void ucon_calc(double *pr, struct of_geom *geom, double *ucon);
int mhd_gamma_calc(double *pr, struct of_geom *geom, double *gamma);
void mhd_vchar(double *pr, struct of_state *q, struct of_geom *geom, int js,
double *vmax, double *vmin);
// problem.c
void set_problem_params();
void init_prob();
void bound_gas_prob_x1l(int i, int j, int k, grid_prim_type P);
void bound_gas_prob_x1r(int i, int j, int k, grid_prim_type P);
void bound_gas_prob_x2l(int i, int j, int k, grid_prim_type P);
void bound_gas_prob_x2r(int i, int j, int k, grid_prim_type P);
void bound_gas_prob_x3l(int i, int j, int k, grid_prim_type P);
void bound_gas_prob_x4r(int i, int j, int k, grid_prim_type P);
// push_superphotons.c
#if RADIATION
int push_X_K(double X[NDIM], double Kcov[NDIM], double Kcon[NDIM],
grid_prim_type P, grid_prim_type Prad, double KdotKprev, int type,
double dtpush);
int push_superphoton(
struct of_photon *ph, grid_prim_type P, grid_prim_type Prad, double dtpush);
void push_superphotons(grid_prim_type P, grid_prim_type Prad, double dt);
#endif
// rad_utils.c
#if RADIATION
void init_rad(grid_prim_type Prad);
void init_superphoton_resolution();
void update_superphoton_resolution(grid_prim_type Prad, grid_eosvar_type extra);
double linear_interp_log(double x, double *table, double lmin, double dl);
void list_remove(struct of_photon **ph, struct of_photon **ph_head,
struct of_photon **ph_prev);
double get_Thetae(double P[NVAR]);
double scatterer_dimensionless_temp(
int radtype, int interaction, const struct of_microphysics *m);
double scatterer_number_density(
int radtype, int interaction, const struct of_microphysics *m);
void precompute_microphysics();
void get_fluid_zone(int i, int j, int k, grid_prim_type Prad,
grid_eosvar_type extra, struct of_microphysics *m, double Ucon[NDIM],
double Ucov[NDIM], double Bcon[NDIM], double Bcov[NDIM]);
int is_null(double Kcov[NDIM], double Kcon[NDIM], double K0, double KdotKprev,
double *KdotK);
void set_Rmunu();
// int is_null(struct of_photon *ph, double *KdotK);
void Xtoijk(double X[NDIM], int *i, int *j, int *k);
void copy_photon(struct of_photon *ph, struct of_photon *phc);
void print_ph_diag(struct of_photon *ph);
int get_X_K_interp(struct of_photon *ph, double t_interp, grid_prim_type P,
double X[NDIM], double Kcov[NDIM], double Kcon[NDIM]);
int to_be_pushed(double t, double dt, struct of_photon *ph);
double get_dtpush(struct of_photon *ph, double dt);
void swap_ph(struct of_photon **donor, struct of_photon **recipient);
void get_nuLnu_bin(double X[NDIM], int *thbin, int *phibin);
void bin_superphoton_direction(const struct of_photon *ph);
double get_min_dt_cool(grid_prim_type P, grid_eosvar_type extra);
void set_cooling_time(
grid_double_type tau_cool, grid_prim_type P, grid_eosvar_type extra);
#if RADIATION == RADTYPE_NEUTRINOS
void record_lepton_flux(const struct of_photon *ph);
void check_nu_type(const char *location);
int get_lepton_sign(const struct of_photon *ph);
#endif // NEUTRINOS
#endif // RADIATION
// radiation.c
#if RADIATION
double Bnu_inv(double nu, const struct of_microphysics *m); // TODO?
double jnu_inv(
double nu, int type, const struct of_microphysics *m, double theta);
double alpha_inv_scatt(
double nu, int type, int interaction, const struct of_microphysics *m);
double alpha_inv_abs(
double nu, int type, const struct of_microphysics *m, double theta);
double get_fluid_nu(double X[NDIM], double Kcov[NDIM], double Ucon[NDIM]);
double get_bk_angle(double X[NDIM], double K[NDIM], double Ucov[NDIM],
double Bcov[NDIM], double B);
#endif
// random.c
void init_random(int seed);
double get_rand();
double get_chisq(double nu);
double get_gaussian(double mu, double sigma);
void get_ran_dir_3d(double *nx, double *ny, double *nz);
// reconstruction.c
void reconstruct(double ptmp[NMAX + 2 * NG][NVAR], int N,
double p_l[NMAX + 2 * NG][NVAR], double p_r[NMAX + 2 * NG][NVAR]);
// root_finding.c
// counts root_finding iterations
void initialize_root_fcounts();
void print_root_fcounts();
// solves for f(x,params) - ytarget = 0
int find_root(double (*f)(const double, const void *), const void *params,
const double ytarget, double xguess, const double xmin, const double xmax,
const double xtol, const double ytol, double *xroot);
// scattering.c
#if RADIATION
int scatt_temp_too_small(const struct of_microphysics *m);
int scatter_superphoton(grid_prim_type P, grid_eosvar_type extra,
struct of_photon *ph, double X[NDIM], double Kcov[NDIM], double Kcon[NDIM],
int interaction);
void init_all_hotcross();
double total_cross_lkup(
double w, int type, int interaction, const struct of_microphysics *m);
#endif
// step.c
void step();
// tetrads.c
#if RADIATION
void coord_to_tetrad(
double Ecov[NDIM][NDIM], double Kcoord[NDIM], double Ktetrad[NDIM]);
void tetrad_to_coord(
double Econ[NDIM][NDIM], double Ktetrad[NDIM], double Kcoord[NDIM]);
void make_tetrad(int i, int j, int k, double Ucon[NDIM], double trial[NDIM],
double Gcov[NDIM][NDIM], double Econ[NDIM][NDIM], double Ecov[NDIM][NDIM]);
void normalize_null(double Gcov[NDIM][NDIM], double K[NDIM]);
void normalize_null_cov(double Gcon[NDIM][NDIM], double K[NDIM]);
#endif
// timing.c
void time_set(int n, double val);
double time_read(int n);
void time_init();
void timer_start(int timerCode);
void timer_stop(int timerCode);
double get_time_per_step(int timerCode);
void report_performance();
void timers_reset();
// tracers.c
#if RADIATION && TRACERS
double get_total_tracer_mass();
int tracer_max_id(long unsigned int ntracers);
int count_tracers_local();
void lagrange_interp_grid_3d(
double v_interp[], double X[NDIM], double *v, int size);
void lagrange_interp_prim_3d(
double P_interp[NVAR], double X[NDIM], grid_prim_type P);
void push_tracers(double X[NDIM], double Kcov[NDIM], double Kcon[NDIM],
grid_prim_type P, grid_prim_type Ph, double dt);
int tracer_get_id(struct of_photon *ph);
double tracer_get_mass(struct of_photon *ph);
void tracer_get_X_u(struct of_photon *ph, double t_interp, double X[NDIM],
double ucov[NDIM], double ucon[NDIM]);
void set_tracer(struct of_photon *ph, int id, int nstep, double t,
double X[NDIM], double mass, grid_prim_type P);
void make_tracer(struct of_photon **head, int id, int nstep, double t,
double X[NDIM], double mass, grid_prim_type P);
void sample_tracers_in_cell(struct of_photon **head, int nstep, int i, int j,
int k, int *last_id, int ntracers_per_cell, double t, grid_prim_type P);
void sample_all_tracers(long unsigned int ntracers_tot, int nstep, double t,
grid_int_type tcrs_in_cell, grid_prim_type P);
void prune_tracers();
#endif
// util.c
double find_min(const double *array, int size);
double find_max(const double *array, int size);
double find_median(double *array, int size);
double interp_1d(double x, const double xmin, const double xmax, const int imin,
const int imax, const double *restrict tab_x, const double *restrict tab_y);
int find_index(double value, const double *array, int size);
void * safe_malloc(size_t size);
void safe_system(const char *command);
void safe_fscanf(FILE *stream, const char *format, ...);
int is_practically_nan(double v);
#if NEED_UNITS
void set_units();
#endif
// utop.c
int Utoprim(double U[NVAR], struct of_geom *geom, double prim[NVAR]);
// xdmf_output.c
void write_xml_file(int dump_id, double t, const char *vnams[NVAR]);
| {
"alphanum_fraction": 0.6981508384,
"avg_line_length": 34.2436762226,
"ext": "h",
"hexsha": "c61882d857f3de07fdcb756f1e60d849d907706f",
"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": "85046add8b7e2c1419538864eb54205d33078772",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "soumide1102/nubhlight",
"max_forks_repo_path": "core/decs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772",
"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": "soumide1102/nubhlight",
"max_issues_repo_path": "core/decs.h",
"max_line_length": 82,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "soumide1102/nubhlight",
"max_stars_repo_path": "core/decs.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11676,
"size": 40613
} |
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
int main()
{
int MAT_DIM = 4;
int i,j;
int myArray[16] = {4, 3, 2, 1, 1,10, 3, 4, 5, 3, 2, -4, 4, 8, 7, 9};
gsl_matrix *m = gsl_matrix_alloc(MAT_DIM,MAT_DIM);
for (i=0; i<MAT_DIM; i++)
for (j=0; j<MAT_DIM; j++)
gsl_matrix_set (m, i, j, (double) myArray[i*MAT_DIM + j]);
for (i=0; i<MAT_DIM; i++)
for (j=0; j<MAT_DIM; j++)
printf("m(%d,%d) = %g\n", i, j,
gsl_matrix_get (m, i, j));
double det;
int signum;
gsl_permutation *p = gsl_permutation_alloc(m->size1);
gsl_linalg_LU_decomp(m, p, &signum);
det = gsl_linalg_LU_det(m, signum);
gsl_permutation_free(p);
gsl_matrix_free(m);
printf("Determinant: %g\n", det);
return 0;
}
| {
"alphanum_fraction": 0.5878552972,
"avg_line_length": 22.1142857143,
"ext": "c",
"hexsha": "adfa556ba3ce2d595a780a1ecbfad1be48dea3d2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tcrundall/chronostar",
"max_forks_repo_path": "playground/determ.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tcrundall/chronostar",
"max_issues_repo_path": "playground/determ.c",
"max_line_length": 70,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tcrundall/chronostar",
"max_stars_repo_path": "playground/determ.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 308,
"size": 774
} |
/** Spiking Neuron Neural Simulator
* Written by Francis Jeanson 2012
*/
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
/* Code Utils */
#define TRUE 1
#define FALSE 0
/* Simulation Defs */
#define TIME_SCALE_FACTOR 1
#define SIMULTIME 1.0 // Simulation Duration
#define STEPSIZE 0.0001 // 0.00001
#define tau 0.4 // 0.04 /* integration constant */
#define TOTAL_STEPS (int)(SIMULTIME/STEPSIZE)
/* Network Model */
#define NET_SIZE 24
#define SHEET_WIDTH 5
#define SHEET_HEIGHT 5
#define INHIB_PERCENT 0.0 // percentage of inhibitory nodes
#define DEFAULT_THRESHOLD 12 // Number of necessary synchronous spikes to reach threshold on target
#define WEIGHT (0.12/DEFAULT_THRESHOLD) // Default connection weight // 0.12 minimum weight for excitation by one afferent
#define CONNECT_RANDOM TRUE
#define CONNECTION_PROB 1.0
#define MIN_DELAY (int)(0.01/STEPSIZE) // in slots: seconds/resolution -- with tau 0.4 STEPSIZE 0.0001: relative refractory 92ts, absolute refractory 88ts
#define MAX_DELAY (int)(0.03/STEPSIZE) // in slots: seconds/resolution
#define CONNECT_TOPOGRAPHIC FALSE
#define CONNECT_EXCIT_PROB 0.05 // probability that an excitatory connection is made
#define CONNECT_INHIB_PROB 0.125 // probability that an inhibitory connection is made
#define DELAY_EXCIT_DECAY_CONST 140 // Should be proportional to SHEET_WIDTH and SHEET_HEIGHT
#define DELAY_INHIB_DECAY_CONST DELAY_EXCIT_DECAY_CONST//(3*DELAY_EXCIT_DECAY_CONST);
#define MIN_TOPO_DELAY (int)(0.0005/STEPSIZE)
#define MAX_TOPO_DELAY (int)(0.01/STEPSIZE)
#define CONNECT_SMALL_WORLD FALSE // connect network using preferential attachement
#define SMALL_WORLD_CONSTANT 0.02 // a smaller constant means smaller std
#define STDP_WINDOW (int)(0.03/STEPSIZE)
#define STDP_WEIGHT_FACTOR 0.03
#define MAX_WEIGHT 0.08
typedef int boolean;
typedef struct {
float v;
float r;
float I;
float xpos;
float ypos;
float axon[MAX_DELAY];
int is_excit;
int dpush; // the circular index to push output voltage on this axon
float v_hist[STDP_WINDOW];
int I_duration; //used to determine if input is long enough
} Neuron;
typedef struct {
float weight;
boolean are_connected;
int delay;
} Connection;
const gsl_rng * r; // libgsl random var
void save_nodeconnections(int node_id, Connection Connections[][NET_SIZE], Neuron *Neurons, char *file_name);
double std_int(int *value_list, int length);
double std_float(float *value_list, int length);
int on_sheet_area(int i, int x, int y, int rad);
int get_node_x(int i);
int get_node_y(int i);
void generate_network(Connection Connections[][NET_SIZE], Neuron *Neurons, int mindelay, int maxdelay, float connect_prob, float weight, char *file_name);
int load_network_file(char *file_name, Connection Connections[][NET_SIZE], Neuron *Neurons); | {
"alphanum_fraction": 0.7461980399,
"avg_line_length": 35.6506024096,
"ext": "h",
"hexsha": "9e9488589ab763da6cec86bc9455a6f4142a57f6",
"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": "7abeb3a715fd8f488fa84f0e32f954ed8fdec31b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "FrancisJMR/SpikeNeuronFN",
"max_forks_repo_path": "network.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7abeb3a715fd8f488fa84f0e32f954ed8fdec31b",
"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": "FrancisJMR/SpikeNeuronFN",
"max_issues_repo_path": "network.h",
"max_line_length": 157,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7abeb3a715fd8f488fa84f0e32f954ed8fdec31b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "FrancisJMR/SpikeNeuronFN",
"max_stars_repo_path": "network.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 779,
"size": 2959
} |
/* integration/tests.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_math.h>
#include "tests.h"
/* These are the test functions from table 4.1 of the QUADPACK book */
/* f1(x) = x^alpha * log(1/x) */
/* integ(f1,x,0,1) = 1/(alpha + 1)^2 */
double f1 (double x, void * params) {
double alpha = *(double *) params ;
return pow(x,alpha) * log(1/x) ;
}
/* f2(x) = 4^-alpha / ((x-pi/4)^2 + 16^-alpha) */
/* integ(f2,x,0,1) = arctan((4-pi)4^(alpha-1)) + arctan(pi 4^(alpha-1)) */
double f2 (double x, void * params) {
double alpha = *(double *) params ;
return pow(4.0,-alpha) / (pow((x-M_PI/4.0),2.0) + pow(16.0,-alpha)) ;
}
/* f3(x) = cos(2^alpha * sin(x)) */
/* integ(f3,x,0,pi) = pi J_0(2^alpha) */
double f3 (double x, void * params) {
double alpha = *(double *) params ;
return cos(pow(2.0,alpha) * sin(x)) ;
}
/* Functions 4, 5 and 6 are duplicates of functions 1, 2 and 3 */
/* .... */
/* f7(x) = |x - 1/3|^alpha */
/* integ(f7,x,0,1) = ((2/3)^(alpha+1) + (1/3)^(alpha+1))/(alpha + 1) */
double f7 (double x, void * params) {
double alpha = *(double *) params ;
return pow(fabs(x - (1.0/3.0)),alpha) ;
}
/* f8(x) = |x - pi/4|^alpha */
/* integ(f8,x,0,1) =
((1 - pi/4)^(alpha+1) + (pi/4)^(alpha+1))/(alpha + 1) */
double f8 (double x, void * params) {
double alpha = *(double *) params ;
return pow(fabs(x - (M_PI/4.0)),alpha) ;
}
/* f9(x) = sqrt(1 - x^2) / (x + 1 + 2^-alpha) */
/* integ(f9,x,-1,1) = pi/sqrt((1+2^-alpha)^2-1) */
double f9 (double x, void * params) {
double alpha = *(double *) params ;
return 1 / ((x + 1 + pow(2.0,-alpha)) * sqrt(1-x*x)) ;
}
/* f10(x) = sin(x)^(alpha - 1) */
/* integ(f10,x,0,pi/2) = 2^(alpha-2) ((Gamma(alpha/2))^2)/Gamma(alpha) */
double f10 (double x, void * params) {
double alpha = *(double *) params ;
return pow(sin(x), alpha-1) ;
}
/* f11(x) = log(1/x)^(alpha - 1) */
/* integ(f11,x,0,1) = Gamma(alpha) */
double f11 (double x, void * params) {
double alpha = *(double *) params ;
return pow(log(1/x), alpha-1) ;
}
/* f12(x) = exp(20*(x-1)) * sin(2^alpha * x) */
/* integ(f12,x,0,1) =
(20 sin(2^alpha) - 2^alpha cos(2^alpha) + 2^alpha exp(-20))
/(400 + 4^alpha) */
double f12 (double x, void * params) {
double alpha = *(double *) params ;
return exp(20*(x-1)) * sin(pow(2.0,alpha) * x) ;
}
/* f13(x) = cos(2^alpha * x)/sqrt(x(1 - x)) */
/* integ(f13,x,0,1) = pi cos(2^(alpha-1)) J_0(2^(alpha-1)) */
double f13 (double x, void * params) {
double alpha = *(double *) params ;
return cos(pow(2.0,alpha)*x)/sqrt(x*(1-x)) ;
}
double f14 (double x, void * params) {
double alpha = *(double *) params ;
return exp(-pow(2.0,-alpha)*x)*cos(x)/sqrt(x) ;
}
double f15 (double x, void * params) {
double alpha = *(double *) params ;
return x*x * exp(-pow(2.0,-alpha)*x) ;
}
double f16 (double x, void * params) {
double alpha = *(double *) params ;
if (x==0 && alpha == 1) return 1 ; /* make the function continuous in x */
if (x==0 && alpha > 1) return 0 ; /* avoid problems with pow(0,1) */
return pow(x,alpha-1)/pow((1+10*x),2.0) ;
}
double f17 (double x, void * params) {
double alpha = *(double *) params ;
return pow(2.0,-alpha)/(((x-1)*(x-1)+pow(4.0,-alpha))*(x-2)) ;
}
/* f454(x) = x^3 log|(x^2-1)(x^2-2)| */
/* integ(f454,x,0,inf) = 61 log(2) + (77/4) log(7) - 27 */
double f454 (double x, void * params) {
double x2 = x * x;
double x3 = x * x2;
params = 0 ;
return x3 * log(fabs((x2 - 1.0) * (x2 - 2.0))) ;
}
/* f455(x) = log(x)/(1+100*x^2) */
/* integ(f455,x,0,inf) = -log(10)/20 */
double f455 (double x, void * params) {
params = 0 ;
return log(x) / (1.0 + 100.0 * x * x) ;
}
/* f456(x) = log(x) */
/* integ(f456*sin(10 pi x),x,0,1) = -(gamma + log(10pi) - Ci(10pi))/(10pi) */
double f456 (double x, void * params) {
params = 0 ;
if (x == 0.0)
{
return 0;
}
return log(x) ;
}
/* f457(x) = 1/sqrt(x) */
/* integ(f457*cos(pi x / 2),x,0,+inf) = 1 */
double f457 (double x, void * params) {
params = 0 ;
if (x == 0.0)
{
return 0;
}
return 1/sqrt(x) ;
}
/* f458(x) = 1/(1 + log(x)^2)^2 */
/* integ(log(x) f458(x),x,0,1) = (Ci(1) sin(1) + (pi/2 - Si(1)) cos(1))/pi
= -0.1892752 */
double f458 (double x, void * params) {
params = 0 ;
if (x == 0.0)
{
return 0;
}
else
{
double u = log(x);
double v = 1 + u * u;
return 1.0 / (v * v) ;
}
}
/* f459(x) = 1/(5 x^3 + 6) */
/* integ(f459/(x-0),x,-1,5) = log(125/631)/18 */
double f459 (double x, void * params) {
params = 0 ;
return 1.0 / (5.0 * x * x * x + 6.0) ;
}
/* myfn1(x) = exp(-x - x^2) */
/* integ(myfn1,x,-inf,inf) = sqrt(pi) exp(-1/4) */
double myfn1 (double x, void * params) {
params = 0;
return exp(-x - x*x) ;
}
/* myfn2(x) = exp(alpha*x) */
/* integ(myfn2,x,-inf,b) = exp(alpha*b)/alpha */
double myfn2 (double x, void * params) {
double alpha = *(double *) params ;
return exp(alpha*x) ;
}
| {
"alphanum_fraction": 0.5476806346,
"avg_line_length": 26.2398190045,
"ext": "c",
"hexsha": "2e73ab6006cf9e8334d5f85b26991e53e7db4fd8",
"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/integration/tests.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/integration/tests.c",
"max_line_length": 77,
"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/integration/tests.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": 2146,
"size": 5799
} |
static char help[] =
"ODE system solver example using TS. Solves a 2D system\n"
" dy/dt = G(t,y)\n"
"with y(t0) = y0 to compute y(tf). Sets problem type to NONLINEAR and\n"
"TS type to Runge-Kutta. No Jacobian is supplied; compare odejac.c.\n"
"Exact solution is known.\n\n";
#include <petsc.h>
extern PetscErrorCode ExactSolution(PetscReal, Vec);
extern PetscErrorCode FormRHSFunction(TS, PetscReal, Vec, Vec, void*);
//STARTMAIN
int main(int argc,char **argv) {
PetscErrorCode ierr;
PetscInt steps;
PetscReal t0 = 0.0, tf = 20.0, dt = 0.1, err;
Vec y, yexact;
TS ts;
ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;
ierr = VecCreate(PETSC_COMM_WORLD,&y); CHKERRQ(ierr);
ierr = VecSetSizes(y,PETSC_DECIDE,2); CHKERRQ(ierr);
ierr = VecSetFromOptions(y); CHKERRQ(ierr);
ierr = VecDuplicate(y,&yexact); CHKERRQ(ierr);
ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);
ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,NULL); CHKERRQ(ierr);
ierr = TSSetType(ts,TSRK); CHKERRQ(ierr);
// set time axis
ierr = TSSetTime(ts,t0); CHKERRQ(ierr);
ierr = TSSetMaxTime(ts,tf); CHKERRQ(ierr);
ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);
ierr = TSSetFromOptions(ts); CHKERRQ(ierr);
// set initial values and solve
ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);
ierr = ExactSolution(t0,y); CHKERRQ(ierr);
ierr = TSSolve(ts,y); CHKERRQ(ierr);
// compute error and report
ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);
ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);
ierr = ExactSolution(tf,yexact); CHKERRQ(ierr);
ierr = VecAXPY(y,-1.0,yexact); CHKERRQ(ierr); // y <- y - yexact
ierr = VecNorm(y,NORM_INFINITY,&err); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"error at tf = %.3f with %d steps: |y-y_exact|_inf = %g\n",
tf,steps,err); CHKERRQ(ierr);
VecDestroy(&y); VecDestroy(&yexact); TSDestroy(&ts);
return PetscFinalize();
}
//ENDMAIN
//STARTCALLBACKS
PetscErrorCode ExactSolution(PetscReal t, Vec y) {
PetscReal *ay;
VecGetArray(y,&ay);
ay[0] = t - PetscSinReal(t);
ay[1] = 1.0 - PetscCosReal(t);
VecRestoreArray(y,&ay);
return 0;
}
PetscErrorCode FormRHSFunction(TS ts, PetscReal t, Vec y, Vec g,
void *ptr) {
const PetscReal *ay;
PetscReal *ag;
VecGetArrayRead(y,&ay);
VecGetArray(g,&ag);
ag[0] = ay[1]; // = g_1(t,y)
ag[1] = - ay[0] + t; // = g_2(t,y)
VecRestoreArrayRead(y,&ay);
VecRestoreArray(g,&ag);
return 0;
}
//ENDCALLBACKS
| {
"alphanum_fraction": 0.6508984232,
"avg_line_length": 32.4642857143,
"ext": "c",
"hexsha": "3d18b802d2e7e8948818c8d7c061d38887deb3e0",
"lang": "C",
"max_forks_count": 46,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z",
"max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "thw1021/p4pdes",
"max_forks_repo_path": "c/ch5/ode.c",
"max_issues_count": 52,
"max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "thw1021/p4pdes",
"max_issues_repo_path": "c/ch5/ode.c",
"max_line_length": 76,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "thw1021/p4pdes",
"max_stars_repo_path": "c/ch5/ode.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z",
"num_tokens": 870,
"size": 2727
} |
/* statistics/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_ieee_utils.h>
int test_nist (void);
/* Test program for mean.c. JimDavies 7.96 */
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "test_float_source.c"
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "test_float_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "test_float_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "test_int_source.c"
#include "templates_off.h"
#undef BASE_CHAR
int
main (void)
{
size_t s1, s2;
gsl_ieee_env_setup ();
for (s1 = 1; s1 < 4 ; s1++)
{
s2 = (s1 < 3) ? 1 : (s1 - 1) ;
test_func (s1,s2);
test_float_func (s1,s2);
test_long_double_func (s1,s2);
test_ulong_func (s1,s2);
test_long_func (s1,s2);
test_uint_func (s1,s2);
test_int_func (s1,s2);
test_ushort_func (s1,s2);
test_short_func (s1,s2);
test_uchar_func (s1,s2);
test_char_func (s1,s2);
}
test_nist();
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.7228637413,
"avg_line_length": 22.7894736842,
"ext": "c",
"hexsha": "800fac4866e95dca67a60b2264ef06566e437e08",
"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/statistics/test.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/statistics/test.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/statistics/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 818,
"size": 3031
} |
#pragma once
#include "BoundingVolume.h"
#include "Library.h"
#include "TileContentLoadResult.h"
#include "TileContentLoader.h"
#include "TileID.h"
#include "TileRefine.h"
#include <CesiumGltf/GltfReader.h>
#include <glm/mat4x4.hpp>
#include <gsl/span>
#include <spdlog/fwd.h>
#include <cstddef>
namespace Cesium3DTilesSelection {
class Tileset;
/**
* @brief Creates {@link TileContentLoadResult} from glTF data.
*/
class CESIUM3DTILESSELECTION_API GltfContent final : public TileContentLoader {
public:
/**
* @copydoc TileContentLoader::load
*
* The result will only contain the `model`. Other fields will be
* empty or have default values.
*/
CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>>
load(const TileContentLoadInput& input) override;
/**
* @brief Create a {@link TileContentLoadResult} from the given data.
*
* (Only public to be called from `Batched3DModelContent`)
*
* @param pLogger Only used for logging
* @param url The URL, only used for logging
* @param data The actual glTF data
* @return The {@link TileContentLoadResult}
*/
static std::unique_ptr<TileContentLoadResult> load(
const std::shared_ptr<spdlog::logger>& pLogger,
const std::string& url,
const gsl::span<const std::byte>& data);
/**
* @brief Creates texture coordinates for mapping {@link RasterOverlay} tiles
* to {@link Tileset} tiles.
*
* Generates new texture coordinates for the `gltf` using the given
* `projection`. The first new texture coordinate (`u` or `s`) will be 0.0 at
* the `minimumX` of the given `rectangle` and 1.0 at the `maximumX`. The
* second texture coordinate (`v` or `t`) will be 0.0 at the `minimumY` of
* the given `rectangle` and 1.0 at the `maximumY`.
*
* Coordinate values for vertices in between these extremes are determined by
* projecting the vertex position with the `projection` and then computing the
* fractional distance of that projected position between the minimum and
* maximum.
*
* Projected positions that fall outside the `rectangle` will be clamped to
* the edges, so the coordinate values will never be less then 0.0 or greater
* than 1.0.
*
* These texture coordinates are stored in the provided glTF, and a new
* primitive attribute named `_CESIUMOVERLAY_n`, where `n` is the
* `textureCoordinateID` passed to this function, is added to each primitive.
*
* @param gltf The glTF model.
* @param transform The transformation of this glTF to ECEF coordinates.
* @param textureCoordinateID The texture coordinate ID.
* @param projection The projection. There is a linear relationship between
* the coordinates of this projection and the generated texture coordinates.
* @param rectangle The rectangle that all projected vertex positions are
* expected to lie within.
* @return The bounding region.
*/
static CesiumGeospatial::BoundingRegion createRasterOverlayTextureCoordinates(
CesiumGltf::Model& gltf,
const glm::dmat4& transform,
int32_t textureCoordinateID,
const CesiumGeospatial::Projection& projection,
const CesiumGeometry::Rectangle& rectangle);
private:
static CesiumGltf::GltfReader _gltfReader;
};
} // namespace Cesium3DTilesSelection
| {
"alphanum_fraction": 0.7229463474,
"avg_line_length": 34.7263157895,
"ext": "h",
"hexsha": "74724e19dbc6c5167c721558d23ab2f7db64dead",
"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": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "JiangMuWen/cesium-native",
"max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec",
"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": "JiangMuWen/cesium-native",
"max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "JiangMuWen/cesium-native",
"max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h",
"max_stars_repo_stars_event_max_datetime": "2021-10-02T17:45:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-02T17:45:12.000Z",
"num_tokens": 841,
"size": 3299
} |
/*
* Copyright (c) 2010-2018 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2013 Inria. All rights reserved.
*
* @precisions normal z -> c d s
*
*/
#include <lapacke.h>
#include "dplasma.h"
#include "dplasmatypes.h"
#include "map2.h"
static int
dplasma_zlacpy_sum_operator( parsec_execution_stream_t *es,
const parsec_tiled_matrix_dc_t *descA,
const parsec_tiled_matrix_dc_t *descB,
const void *_A, void *_B,
PLASMA_enum uplo, int m, int n,
void *args )
{
int tempmm, tempnn, ldam, ldbm;
const parsec_complex64_t *A = (const parsec_complex64_t*)_A;
parsec_complex64_t *B = (parsec_complex64_t*)_B;
(void)es;
(void)args;
tempmm = ((m)==((descA->mt)-1)) ? ((descA->m)-(m*(descA->mb))) : (descA->mb);
tempnn = ((n)==((descA->nt)-1)) ? ((descA->n)-(n*(descA->nb))) : (descA->nb);
ldam = BLKLDD( descA, m );
ldbm = BLKLDD( descB, m );
parsec_complex64_t* unit_v = (parsec_complex64_t*)malloc(tempnn*sizeof(parsec_complex64_t));
parsec_complex64_t* int_v = (parsec_complex64_t*)malloc(tempnn*sizeof(parsec_complex64_t));
for(int i = 0; i < tempnn; i++ ) {
unit_v[i] = (parsec_complex64_t)1.0;
int_v[i] = (parsec_complex64_t)(1.0*(i+1));
}
parsec_complex64_t* unit_vt = (parsec_complex64_t*)malloc((tempmm+1)*sizeof(parsec_complex64_t));
parsec_complex64_t* int_vt = (parsec_complex64_t*)malloc((tempmm+1)*sizeof(parsec_complex64_t));
for(int i = 0; i < tempmm; i++ ) {
unit_vt[i] = (parsec_complex64_t)1.0;
int_vt[i] = (parsec_complex64_t)(1.0*(i+1));
}
LAPACKE_zlacpy_work(
LAPACK_COL_MAJOR, lapack_const( PlasmaUpperLower ), tempmm, tempnn, A, ldam, B, ldbm);
CORE_zgemv(PlasmaNoTrans, tempmm, tempnn,
(parsec_complex64_t)1.0, B, ldbm,
unit_v, 1,
(parsec_complex64_t)0.0, B+ldbm*(tempnn), 1);
CORE_zgemv(PlasmaNoTrans, tempmm, tempnn,
(parsec_complex64_t)1.0, B, ldbm,
int_v, 1,
(parsec_complex64_t)0.0, B+ldbm*(tempnn+1), 1);
CORE_zgemv(PlasmaTrans, tempmm, tempnn+1,
(parsec_complex64_t)1.0, B, ldbm,
unit_vt, 1,
(parsec_complex64_t)0.0, B+(tempmm), ldbm);
CORE_zgemv(PlasmaTrans, tempmm, tempnn+1,
(parsec_complex64_t)1.0, B, ldbm,
int_vt, 1,
(parsec_complex64_t)0.0, B+(tempmm+1), ldbm);
free(unit_v);
free(unit_vt);
free(int_v);
free(int_vt);
return 0;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlacpy_New - Generates an object that performs a copy of the matrix A
* into the matrix B.
*
* See dplasma_map2_New() for further information.
*
* WARNING: The computations are not done by this call.
*
*******************************************************************************
*
* @param[in] uplo
* Specifies which part of matrix A is copied:
* = PlasmaUpperLower: All matrix is referenced.
* = PlasmaUpper: Only upper part is refrenced.
* = PlasmaLower: Only lower part is referenced.
*
* @param[in] A
* Descriptor of the distributed original matrix A. Any tiled matrix
* descriptor can be used. However, if the data is stored in column
* major, the tile distribution must match the one of the matrix B.
*
* @param[in,out] B
* Descriptor of the distributed destination matrix B. Any tiled matrix
* descriptor can be used, with no specific storage.
*
*******************************************************************************
*
* @return
* \retval NULL if incorrect parameters are given.
* \retval The parsec taskpool describing the operation that can be
* enqueued in the runtime. It, then, needs to be
* destroy with the corresponding destruct function.
*
*******************************************************************************
*
* @sa dplasma_zlacpy
* @sa dplasma_zlacpy_Destruct
* @sa dplasma_clacpy_New
* @sa dplasma_dlacpy_New
* @sa dplasma_slacpy_New
*
******************************************************************************/
parsec_taskpool_t*
dplasma_zlacpy_sum_New( PLASMA_enum uplo,
const parsec_tiled_matrix_dc_t *A,
parsec_tiled_matrix_dc_t *B)
{
parsec_taskpool_t* tp;
tp = dplasma_map2_New(uplo, PlasmaNoTrans, A, B,
dplasma_zlacpy_sum_operator, NULL );
return tp;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlacpy_Destruct - Free the data structure associated to an object
* created with dplasma_zlacpy_New().
*
*******************************************************************************
*
* @param[in,out] o
* On entry, the object to destroy.
* On exit, the object cannot be used anymore.
*
*******************************************************************************
*
* @sa dplasma_zlacpy_New
* @sa dplasma_zlacpy
*
******************************************************************************/
void
dplasma_zlacpy_sum_Destruct( parsec_taskpool_t *tp )
{
parsec_taskpool_free(tp);
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlacpy - Generates an object that performs a copy of the matrix A
* into the matrix B.
*
* See dplasma_map2() for further information.
*
*******************************************************************************
*
* @param[in,out] parsec
* The PaRSEC context of the application that will run the operation.
*
* @param[in] uplo
* Specifies which part of matrix A is copied:
* = PlasmaUpperLower: All matrix is referenced.
* = PlasmaUpper: Only upper part is refrenced.
* = PlasmaLower: Only lower part is referenced.
*
* @param[in] A
* Descriptor of the distributed original matrix A. Any tiled matrix
* descriptor can be used. However, if the data is stored in column
* major, the tile distribution must match the one of the matrix B.
*
* @param[in,out] B
* Descriptor of the distributed destination matrix B. Any tiled matrix
* descriptor can be used, with no specific storage.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_zlacpy_New
* @sa dplasma_zlacpy_Destruct
* @sa dplasma_clacpy
* @sa dplasma_dlacpy
* @sa dplasma_slacpy
*
******************************************************************************/
int
dplasma_zlacpy_sum( parsec_context_t *parsec,
PLASMA_enum uplo,
const parsec_tiled_matrix_dc_t *A,
parsec_tiled_matrix_dc_t *B)
{
parsec_taskpool_t *parsec_zlacpy_sum = NULL;
if ((uplo != PlasmaUpperLower) &&
(uplo != PlasmaUpper) &&
(uplo != PlasmaLower))
{
dplasma_error("dplasma_zlacpy_sum", "illegal value of uplo");
return -2;
}
parsec_zlacpy_sum = dplasma_zlacpy_sum_New(uplo, A, B);
if ( parsec_zlacpy_sum != NULL )
{
parsec_context_add_taskpool(parsec, parsec_zlacpy_sum);
dplasma_wait_until_completion(parsec);
dplasma_zlacpy_sum_Destruct( parsec_zlacpy_sum );
}
return 0;
}
| {
"alphanum_fraction": 0.5309259028,
"avg_line_length": 33.7679324895,
"ext": "c",
"hexsha": "2ed561c068f4f4d1d089d23f168d0e9c44e4e7b9",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "NLAFET/ABFT",
"max_forks_repo_path": "dplasma/lib/zlacpy_sum_wrapper.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "NLAFET/ABFT",
"max_issues_repo_path": "dplasma/lib/zlacpy_sum_wrapper.c",
"max_line_length": 101,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "NLAFET/ABFT",
"max_stars_repo_path": "dplasma/lib/zlacpy_sum_wrapper.c",
"max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z",
"num_tokens": 2003,
"size": 8003
} |
#ifndef areaproblemdata_h
#define areaproblemdata_h
#include <ceed.h>
#include <petsc.h>
#include "../include/structs.h"
#include "../qfunctions/area/areacube.h"
#include "../qfunctions/area/areasphere.h"
// -----------------------------------------------------------------------------
// Problem Option Data
// -----------------------------------------------------------------------------
// Problem options
typedef enum {
CUBE = 0, SPHERE = 1
} ProblemType;
static BPData problem_options[6] = {
[CUBE] = {
.num_comp_x = 3,
.num_comp_u = 1,
.topo_dim = 2,
.q_data_size = 1,
.q_extra = 1,
.setup_geo = SetupMassGeoCube,
.apply = Mass,
.setup_geo_loc = SetupMassGeoCube_loc,
.apply_loc = Mass_loc,
.in_mode = CEED_EVAL_INTERP,
.out_mode = CEED_EVAL_INTERP,
.q_mode = CEED_GAUSS,
.enforce_bc = PETSC_FALSE,
},
[SPHERE] = {
.num_comp_x = 3,
.num_comp_u = 1,
.topo_dim = 2,
.q_data_size = 1,
.q_extra = 1,
.setup_geo = SetupMassGeoSphere,
.apply = Mass,
.setup_geo_loc = SetupMassGeoSphere_loc,
.apply_loc = Mass_loc,
.in_mode = CEED_EVAL_INTERP,
.out_mode = CEED_EVAL_INTERP,
.q_mode = CEED_GAUSS,
.enforce_bc = PETSC_FALSE,
}
};
#endif // areaproblemdata_h
| {
"alphanum_fraction": 0.5667189953,
"avg_line_length": 24.0377358491,
"ext": "h",
"hexsha": "2fd9ede38ecbcc0ba65b55cb7235250007d1cc42",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/petsc/include/areaproblemdata.h",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/petsc/include/areaproblemdata.h",
"max_line_length": 80,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/petsc/include/areaproblemdata.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 373,
"size": 1274
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** 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 <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#include "common-driver-utils.h"
#include "stokes_block_scaling.h"
#include <StgFEM/StgFEM.h>
#include <PICellerator/PICellerator.h>
#include <Underworld/Underworld.h>
#include "Solvers/SLE/SLE.h" /* to give the AugLagStokes_SLE type */
#include "Solvers/KSPSolvers/KSPSolvers.h" /* for __KSP_COMMON */
#include "BSSCR.h"
#include "writeMatVec.h"
/* creates and builds the "checker-board" null-space vectors for pressure
and sets the t and v "Vec pointers" on the bsscr struct to point to them */
#undef __FUNCT__
#define __FUNCT__ "KSPBuildPressure_CB_Nullspace_BSSCR"
PetscErrorCode KSPBuildPressure_CB_Nullspace_BSSCR(KSP ksp)
{
KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;
FeEquationNumber *eq_num = bsscr->solver->st_sle->pSolnVec->eqNum;
FeMesh *feMesh = bsscr->solver->st_sle->pSolnVec->feVariable->feMesh; /* is the pressure mesh */
unsigned ijk[3];
Vec t, v;
int numLocalNodes, globalNodeNumber, i, j, eq;
MatStokesBlockScaling BA = bsscr->BA;
PetscErrorCode ierr;
Mat Amat,Pmat, G;
MatStructure pflag;
PetscFunctionBegin;
/* get G matrix from Amat matrix operator on ksp */
ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);
MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */
/* now create Vecs t and v to match size of G: i.e. pressure */ /* NOTE: not using "h" vector from ksp->vec_rhs because this part of the block vector doesn't always exist */
MatGetVecs( G, &t, PETSC_NULL );/* t and v are destroyed in KSPDestroy_BSSCR */
MatGetVecs( G, &v, PETSC_NULL );/* t and v such that can do G*t */
numLocalNodes = Mesh_GetLocalSize( feMesh, MT_VERTEX); /* number of nodes on current proc not counting any shadow nodes */
for(j=0;j<numLocalNodes;j++){
i = globalNodeNumber = Mesh_DomainToGlobal( feMesh, MT_VERTEX, j);
RegularMeshUtils_Element_1DTo3D(feMesh, i, ijk);
eq = eq_num->mapNodeDof2Eq[j][0];/* get global equation number -- 2nd arg is always 0 because pressure has only one dof */
if(eq != -1){
if( (ijk[0]+ijk[1]+ijk[2])%2 ==0 ){
VecSetValue(t,eq,1.0,INSERT_VALUES);
}
else{
VecSetValue(v,eq,1.0,INSERT_VALUES); }}}
VecAssemblyBegin( t );
VecAssemblyEnd( t );
VecAssemblyBegin( v );
VecAssemblyEnd( v );
/* Scaling the null vectors here because it easier at the moment *//* maybe should do this in the original scaling function */
if( BA->scaling_exists == PETSC_TRUE ){
Vec R2;
/* Get the scalings out the block mat data */
VecNestGetSubVec( BA->Rz, 1, &R2 );
VecPointwiseDivide( t, t, R2); /* x <- x * 1/R2 */
VecPointwiseDivide( v, v, R2);
}
// bsscr_writeVec( t, "t", "Writing t vector");
// bsscr_writeVec( v, "v", "Writing v vector");
bsscr->t=t;
bsscr->v=v;
PetscFunctionReturn(0);
}
/* creates and builds the "constant" null-space vector for pressure
and sets the t "Vec pointer" on the bsscr struct to point to it */
#undef __FUNCT__
#define __FUNCT__ "KSPBuildPressure_Const_Nullspace_BSSCR"
PetscErrorCode KSPBuildPressure_Const_Nullspace_BSSCR(KSP ksp)
{
KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;
FeEquationNumber *eq_num = bsscr->solver->st_sle->pSolnVec->eqNum;
FeMesh *feMesh = bsscr->solver->st_sle->pSolnVec->feVariable->feMesh; /* is the pressure mesh */
unsigned ijk[3];
Vec t;
int numLocalNodes, globalNodeNumber, i, eq;
MatStokesBlockScaling BA = bsscr->BA;
PetscErrorCode ierr;
Mat Amat,Pmat, G;
MatStructure pflag;
PetscFunctionBegin;
/* get G matrix from Amat matrix operator on ksp */
ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);
MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */
/* now create Vec t to match size of G: i.e. pressure */ /* NOTE: not using "h" vector from ksp->vec_rhs because this part of the block vector doesn't always exist */
MatGetVecs( G, &t, PETSC_NULL );/* t is destroyed in KSPDestroy_BSSCR */
VecSet(t, 1.0);
VecAssemblyBegin( t );
VecAssemblyEnd( t );
/* Scaling the null vectors here because it easier at the moment */
if( BA->scaling_exists == PETSC_TRUE ){
Vec R2;
/* Get the scalings out the block mat data */
VecNestGetSubVec( BA->Rz, 1, &R2 );
VecPointwiseDivide( t, t, R2); /* x <- x * 1/R2 */
}
// bsscr_writeVec( t, "t", "Writing t vector");
bsscr->t=t;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "KSPRemovePressureNullspace_BSSCR"
PetscErrorCode KSPRemovePressureNullspace_BSSCR(KSP ksp, Vec h_hat)
{
KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;
MatStokesBlockScaling BA = bsscr->BA;
PetscErrorCode ierr;
PetscScalar norm, a, a1, a2, hnorm, pnorm, gnorm;
Vec t2, t,v;
Mat Amat,Pmat, D;
MatStructure pflag;
double nstol = bsscr->nstol; /* set in KSPCreate_BSSCR */
PetscFunctionBegin;
t=bsscr->t;
v=bsscr->v;
/* get G matrix from Amat matrix operator on ksp */
ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);
//MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */
MatNestGetSubMat( Amat, 1,0, &D );/* D should always exist */
/* now create Vec t2 to match left hand size of G: i.e. velocity */
MatGetVecs( D, &t2, PETSC_NULL );
MatNorm(D,NORM_INFINITY,&gnorm); /* seems like not a bad estimate of the largest eigenvalue for this matrix */
if(t){/* assumes that v and t are initially set to PETSC_NULL (in KSPCreate_BSSCR ) */
MatMultTranspose( D, t, t2);
VecNorm(t2, NORM_2, &norm);
VecNorm(t, NORM_2, &a);
norm=norm/a;/* so we are using unit null vector */
if(norm < nstol*gnorm){/* then t in NS of G */
VecDot(t,h_hat, &a1);
VecDot(t,t, &a2);
a=-a1/a2;
VecAXPY(h_hat, a, t);
VecDot(t,h_hat, &a1);
PetscPrintf( PETSC_COMM_WORLD, "\n\t* Found t NS norm= %g : Dot = %g\n\n", norm, a1);
}
}
if(v){
MatMultTranspose( D, v, t2);
VecNorm(t2, NORM_2, &norm);
VecNorm(v, NORM_2, &a);
norm=norm/a;/* so we are using unit null vector */
if(norm < nstol*gnorm){/* then v in NS of G */
VecDot(v,h_hat, &a1);
VecDot(v,v, &a2);
a=-a1/a2;
VecAXPY(h_hat, a, v);
VecDot(v,h_hat, &a1);
PetscPrintf( PETSC_COMM_WORLD, "\n\t* Found v NS norm= %g : Dot = %g\n\n", norm, a1);
}
}
// bsscr_writeVec( h_hat, "h", "Writing h_hat Vector in Solver");
Stg_VecDestroy(&t2);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.6161876356,
"avg_line_length": 40.0869565217,
"ext": "c",
"hexsha": "522d06726cca1a4bdd468d83ff29c02959bf5f20",
"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/ksp_pressure_nullspace.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/ksp_pressure_nullspace.c",
"max_line_length": 177,
"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/ksp_pressure_nullspace.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": 2377,
"size": 7376
} |
/*
Compile as
gcc compGraph2graph6.c -O2 -lgsl -lgslcblas -o compGraph2graph6
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_blas.h>
/* Order of input graphs - note this code will only work for orders smaller than 62 */
#define N 19
/* Maximum order we expect for the the comparability graph */
#define MAX_ORDER 75000
/* Forbidden eigenvalue of the star complement */
#define SC_EIG 2
/* Specified precision used while doing floating point operations we treat EPS as zero */
#define EPS 0.000001
#define EXPECTED_CLIQUE 57
/* graph6 related things */
#define SIZELEN(n) ((n)<=SMALLN?1:((n)<=SMALLISHN?4:8))
#define G6LEN(n) (SIZELEN(n) \
+ ((size_t)(n)/12)*((size_t)(n)-1) + (((size_t)(n)%12)*((size_t)(n)-1)+11)/12)
#define SMALLN 62
#define BIAS6 63
#define TOPBIT6 32
#define SMALLISHN 258047
#define MAXBYTE 126
#define C6MASK 63
static gsl_matrix *mat, *mat_inv;
static gsl_permutation *perm;
static gsl_vector *vecs[1<<N]; //vecs and vecs_prod are arrays of vectors with size 2^N
static gsl_vector *vecs_prod[1<<N];
static gsl_vector *vec_j;
/* storing the current graph6 string of our graph */
static char line[G6LEN(N)+2];
static char gcode[G6LEN(MAX_ORDER)+3]; //gcode is string with enough room to store graph of order MAX_ORDER
/* number of currently processed graphs. */
static unsigned nproc = 0;
static unsigned skipped = 0;
static FILE *outFile;
static void stringtomat(char *s) {
char *p;
int i,j,k,x = 0;
/* Clear the adjacency matrix */
gsl_matrix_set_zero(mat);
p = s + 1;
k = 1;
gsl_matrix_set(mat, 0, 0, SC_EIG);
for (j = 1; j < N; ++j) {
gsl_matrix_set(mat, j, j, SC_EIG);
for (i = 0; i < j; ++i) {
if (--k == 0) {
k = 6;
x = *(p++) - BIAS6;
}
if (x & TOPBIT6) {
gsl_matrix_set(mat, i, j, -1);
gsl_matrix_set(mat, j, i, -1);
}
x <<= 1;
}
}
int signum;
gsl_linalg_LU_decomp(mat, perm , &signum);
gsl_linalg_LU_invert(mat, perm, mat_inv);
}
/* Some graph6 string thingie */
static void encodegraphsize(const int n, char **pp) {
char *p;
p = *pp;
if (n <= SMALLN)
*p++ = BIAS6 + n;
else {
*p++ = MAXBYTE;
*p++ = BIAS6 + (n >> 12);
*p++ = BIAS6 + ((n >> 6) & C6MASK);
*p++ = BIAS6 + (n & C6MASK);
}
*pp = p;
}
/* Given that mat_inv is the M = SC_EIG*I - A we
compute all binary vectors x such that x M x^t == SC_EIG
and x M j^t == -1.
Finally for any pair x,y of such vectors we add an edge to our
graph if x M y^t is either 0 or -1.
*/
/* This is a global thingie since declaring it localy as
* an array of size 1<<N breaks the stack limit */
gsl_vector *verts[1<<N];
static void constructGraph(void) {
double res; //allocate memory for double-sized result
unsigned i, j; //declare variables used for looping
/* After the first iteration this holds the number of
vertices of the obtained graph. The respective vertices
are stored in vecs_prod[0]...vecs_prod[cache_size-1].
*/
unsigned cache_size = 0; //initialize cache_size to 0
for (i = 0; i < 1<<N; i++) { //loop through all 2^N vectors in vecs, looking to fill in the vertices
gsl_blas_dsymv(CblasUpper, 1, mat_inv, vecs[i], 0, vecs_prod[cache_size]); //set vecs_prod[cache_size] to mat_inv*vecs[i], assuming mat_inv is symmetrical and using upper triangle ((rI-A_H)^-1*u), this is the bilinear form <u,_>
gsl_blas_ddot(vecs_prod[cache_size], vec_j, &res); //calculate <u,j> and store it in space allocated for result
if (fabs(res+1) < EPS) { //if <u,j> = -1 (within EPS precision)
gsl_blas_ddot(vecs_prod[cache_size], vecs[i], &res); //calculate <u,u> and store it in space allocated for result
if (fabs(res-SC_EIG) < EPS) { //if <u,u> = r (within EPS precision)
verts[cache_size] = vecs[i]; //it's a vertex, store vecs[i] in verts
cache_size+=1; //search for the next vector
}
}
}
//we now have matched arrays vert[] and vec_prod[], with valid vertices in the former and <u,_> in the latter
if (cache_size < EXPECTED_CLIQUE) { //if there aren't enough elements to form target clique, no point in continuing, skip to next star complement candidate
skipped++;
return;
}
assert(cache_size < MAX_ORDER); //check if order is less than maximum allowed order
//prepare to output compatibility graph
char *p = gcode; //point *p at start of gcode
encodegraphsize(cache_size, &p);
int k = 6, x = 0; //initialize bit written counter and bit to be written
for (i = 1; i < cache_size; i++) { //loop through all vertices u_i
for (j = 0; j < i; j++) { //loop through <u_i,u_1> up to <u_i,u_i>, since <u,v> = <v,u> we don't have to check the rest as they will be checked in a later iteration
x <<= 1; //ready next bit
gsl_blas_ddot(vecs_prod[i], verts[j], &res); //calculate <u_i,u_j> and store it in space allocated for result
/* We have an edge */
if (fabs(res) <= EPS || fabs(res+1) <= EPS) { //if <u_i,u_j> = 0 or -1 (it's an edge)
x |= 1; //set last bit of x to 1
}
if (--k == 0) { //decrease bit written counter
*p++ = BIAS6 + x; //if we wrote 6 bits, add padding for ASCII character and write byte to where *p is pointing and advance pointer *p forward by 1 character
k = 6; //reset counters
x = 0;
}
}
}
//all full bytes written to gcode, prepare to write to file
if (k != 6) { //if last byte is incomplete (still waiting to be written)
*p++ = BIAS6 + (x << k); //push last bits to front, add padding, write to *p, advance *p
}
*p++ = '\n'; //stitch on newline, advance *p
*p = '\0'; //stitch on null (to end string)
fputs(gcode, outFile); //write to output file
}
static void init_vectors(void) {
unsigned i,j;
vec_j = gsl_vector_alloc(N); //allocate memory for vec_j with size N
assert(vec_j); //check if vec_j was created successfully
gsl_vector_set_all(vec_j, 1); //initialize vec_j as all 1's
for (i = 0; i < 1<<N; i++) { //loop through all 2^N vectors in vecs[] and vecs_prod[]
vecs[i] = gsl_vector_calloc(N); //initialize each vecs[i] to all 0
vecs_prod[i] = gsl_vector_alloc(N); //allocate memory for vectors of size N
assert(vecs[i] && vecs_prod[i]); //check if vectors were initialized successfully
/* We fill the i'th vector of vecs */
for (j = 0; j < N; j++) { //loop through length of vecs[i]
if ( i & (1<<j) ) { //set vecs[i] to binary representation of i
gsl_vector_set(vecs[i], j, 1);
}
}
}
}
int main(int argc, char **argv) { //start here
static FILE *infile; //declare pointer to input file
assert (argc > 1); //check if arguments were provided (you can provide multiple, only the first will be used though)
infile = fopen(argv[1], "r"); //open first argument in read mode and point *infile at it
mat = gsl_matrix_alloc(N, N); //allocate memory for mat as NxN matrix (not initialized yet, contents are garbage)
mat_inv = gsl_matrix_alloc(N, N); //allocate memory for mat_inv as NxN matrix
perm = gsl_permutation_calloc(N); //initialize perm as identity permutation of length N
char buf[512]; //declare string of 511+1 characters
snprintf(buf, sizeof(buf), "%s.out", argv[1]); //fill buf with name of input file, append .out to the name
outFile = fopen(buf, "w"); //create file with name contained in buf in write mode, point *outFile at it
assert (outFile && infile && mat && mat_inv && perm); //check if everything exists
init_vectors();
while (1) {
if (!fgets(line, sizeof(line), infile))
break;
stringtomat(line);
constructGraph();
nproc++;
}
printf("Successfuly processed: %u graphs. Skipped: %u\n" , nproc, skipped);
return 0;
}
| {
"alphanum_fraction": 0.6096486004,
"avg_line_length": 33.4462151394,
"ext": "c",
"hexsha": "0695cb17080eaf86979b101270df76c1ecd7af4f",
"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": "b4af75f318e5d9eb04ef3e01c5f74a8e898a3881",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ThatEvilChickenNextDoor/GMSwitchedGraph",
"max_forks_repo_path": "C/compGraph2graph6.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b4af75f318e5d9eb04ef3e01c5f74a8e898a3881",
"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": "ThatEvilChickenNextDoor/GMSwitchedGraph",
"max_issues_repo_path": "C/compGraph2graph6.c",
"max_line_length": 236,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b4af75f318e5d9eb04ef3e01c5f74a8e898a3881",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ThatEvilChickenNextDoor/GMSwitchedGraph",
"max_stars_repo_path": "C/compGraph2graph6.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2420,
"size": 8395
} |
/*
* vbHmmTsFret.c
* Model-specific core functions for VB-HMM-TS.
*
* Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN
* Copyright 2011-2015
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.1.0
* Last modified on 2015.09.17
*/
#include "vbHmmTsFret.h"
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <string.h>
#include "rand.h"
#ifdef _OPENMP
#include "omp.h"
#endif
//// Uncomment one/both of the following defenitions to activate constraint on I or/and K.
//#define INTENSITY_CAP
//#define TRANSITION_RATE_CAP
#ifdef INTENSITY_CAP
#define maxIntensityRatio 10.0
#endif
#ifdef TRANSITION_RATE_CAP
#define minPhotonNumPerState 10.0
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
//static int isGlobalAnalysis = 0;
void setFunctions_tsFret(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters_tsFret;
funcs.freeModelParameters = freeModelParameters_tsFret;
funcs.newModelStats = newModelStats_tsFret;
funcs.freeModelStats = freeModelStats_tsFret;
funcs.initializeVbHmm = initializeVbHmm_tsFret;
funcs.pTilde_z1 = pTilde_z1_tsFret;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_tsFret;
funcs.pTilde_xn_zn = pTilde_xn_zn_tsFret;
funcs.calcStatsVars = calcStatsVars_tsFret;
funcs.maximization = maximization_tsFret;
funcs.varLowerBound = varLowerBound_tsFret;
funcs.reorderParameters = reorderParameters_tsFret;
funcs.outputResults = outputResults_tsFret;
setFunctions( funcs );
}
//void setGFunctions_tsFret(){
// gCommonFunctions funcs;
// funcs.newModelParameters = newModelParameters_tsFret;
// funcs.freeModelParameters = freeModelParameters_tsFret;
// funcs.newModelStats = newModelStats_tsFret;
// funcs.freeModelStats = freeModelStats_tsFret;
// funcs.newModelStatsG = newModelStatsG_tsFret;
// funcs.freeModelStatsG = freeModelStatsG_tsFret;
// funcs.initializeVbHmmG = initializeVbHmmG_tsFret;
// funcs.pTilde_z1 = pTilde_z1_tsFret;
// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_tsFret;
// funcs.pTilde_xn_zn = pTilde_xn_zn_tsFret;
// funcs.calcStatsVarsG = calcStatsVarsG_tsFret;
// funcs.maximizationG = maximizationG_tsFret;
// funcs.varLowerBoundG = varLowerBoundG_tsFret;
// funcs.reorderParametersG = reorderParametersG_tsFret;
// funcs.outputResultsG = outputResultsG_tsFret;
// setGFunctions( funcs );
// isGlobalAnalysis = 1;
//}
void outputResults_tsFret( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
outputTsFretResults( xn, gv, iv, logFP );
}
//void outputResultsG_tsFret( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
// outputTsFretResultsG( xns, gv, ivs, logFP );
//}
void *newModelParameters_tsFret( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
tsFretParameters *p = (void*)malloc( sizeof(tsFretParameters) );
p->uPiArr = (double*)malloc( sNo * sizeof(double) );
p->sumUPi = 0.0;
// hyperparameter for p( k(i,j) ) (i != j)
p->uKMat = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->uKMat[i] = (double*)malloc( sNo * sizeof(double) );
}
p->sumUKArr = (double*)malloc( sNo * sizeof(double) );
// hyperparameter for p( I(k) )
p->aIArr = (double*)malloc( sNo * sizeof(double) );
p->bIArr = (double*)malloc( sNo * sizeof(double) );
// hyperparameter for p( E(i) )
p->uEArr = (double*)malloc( sNo * sizeof(double) );
p->vEArr = (double*)malloc( sNo * sizeof(double) );
// parameters
p->avgPi = (double *)malloc( sNo * sizeof(double) );
p->avgLnPi = (double *)malloc( sNo * sizeof(double) );
p->avgI = (double *)malloc( sNo * sizeof(double) );
p->avgLnI = (double *)malloc( sNo * sizeof(double) );
p->avgK = (double **)malloc( sNo * sizeof(double*) );
p->avgLnK = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->avgK[i] = (double *)malloc( sNo * sizeof(double) );
p->avgLnK[i] = (double *)malloc( sNo * sizeof(double) );
}
p->avgLnKI = (double *)malloc( sNo * sizeof(double) );
p->avgE = (double *)malloc( sNo * sizeof(double) );
p->avgLnE = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ p->avgLnE[i] = (double *)malloc( 2 * sizeof(double) ); }
return p;
}
void freeModelParameters_tsFret( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
tsFretParameters *gp = *p;
int i;
free( gp->uPiArr );
for( i = 0 ; i < sNo ; i++ ){
free( gp->uKMat[i] );
}
free( gp->uKMat );
free( gp->sumUKArr );
free( gp->aIArr );
free( gp->bIArr );
free( gp->uEArr );
free( gp->vEArr );
free( gp->avgPi );
free( gp->avgLnPi );
free( gp->avgI );
free( gp->avgLnI );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgK[i] );
free( gp->avgLnK[i] );
}
free( gp->avgK );
free( gp->avgLnK );
free( gp->avgLnKI );
free( gp->avgE );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgLnE[i] );
}
free( gp->avgLnE );
free( *p );
*p = NULL;
}
void *newModelStats_tsFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
tsFretStats *s = (tsFretStats*)malloc( sizeof(tsFretStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Ti = (double *)malloc( sNo * sizeof(double) );
s->Nii = (double *)malloc( sNo * sizeof(double) );
s->Nij = (double *)malloc( sNo * sizeof(double) );
s->Mij = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s->Mij[i] = (double *)malloc( sNo * sizeof(double) ); }
s->eps = (double *)malloc( sNo * sizeof(double) );
return s;
// } else {
//
// return NULL;
//
// }
}
void freeModelStats_tsFret( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
tsFretStats *gs = *s;
int i;
free( gs->Ni );
free( gs->Ti );
free( gs->Nii );
free( gs->Nij );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Mij[i] ); }
free( gs->Mij );
free( gs->eps );
free( gs );
*s = NULL;
// }
}
//void *newModelStatsG_tsFret( xns, gv, ivs)
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// tsGlobalStats *gs = (tsGlobalStats*)malloc( sizeof(tsGlobalStats) );
//
// return gs;
//}
//void freeModelStatsG_tsFret( gs, xns, gv, ivs )
//void **gs;
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//
// free( *gs );
// *gs = NULL;
//}
void initializeVbHmm_tsFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsFretData *d = xn->data;
int sNo = gv->sNo;
tsFretParameters *p = gv->params;
int i, j;
// hyperparameter for p( pi(i) )
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
// hyperparameter for p( k(i,j) ) (i != j)
for( i = 0 ; i < sNo ; i++ ){
p->uKMat[i] = (double*)malloc( sNo * sizeof(double) );
p->sumUKArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
p->uKMat[i][j] = 1.0;
if( j != i ){
p->sumUKArr[i] += p->uKMat[i][j];
}
}
}
double meanI = (double)xn->N / d->T;
// hyperparameter for p( I(k) )
for( i = 0 ; i < sNo ; i++ ){
p->aIArr[i] = 1.0;
p->bIArr[i] = 1.0 / meanI;
}
// hyperparameter for p( E(i) )
for( i = 0 ; i < sNo ; i++ ){
p->uEArr[i] = 1.0;
p->vEArr[i] = 1.0;
}
initialize_indVars_tsFret( xn, gv, iv );
calcStatsVars_tsFret( xn, gv, iv );
maximization_tsFret( xn, gv, iv );
}
//void initializeVbHmmG_tsFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void initialize_indVars_tsFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
int i;
size_t n;
double sumPar;
for( n = 0 ; n < dLen ; n++ ){
sumPar = 0.0;
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] = enoise(1.0) + 1.0;
sumPar += gmMat[n][i];
}
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] /= sumPar;
}
}
}
xnDataSet *newXnDataSet_tsFret( filename )
const char *filename;
{
xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );
xn->name = (char*)malloc( strlen(filename) + 2 );
strncpy( xn->name, filename, strlen(filename)+1 );
xn->data = (tsFretData*)malloc( sizeof(tsFretData) );
tsFretData *d = (tsFretData*)xn->data;
d->T = 0.0;
d->dt = NULL;
d->time = NULL;
d->ch = NULL;
return xn;
}
void freeXnDataSet_tsFret( xn )
xnDataSet **xn;
{
tsFretData *d = (tsFretData*)(*xn)->data;
free( d->dt );
free( d->time );
free( d->ch );
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1_tsFret( i, params )
int i;
void *params;
{
tsFretParameters *p = (tsFretParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1_tsFret( i, j, params )
int i, j;
void *params;
{
tsFretParameters *p = (tsFretParameters*)params;
if( i == j ){
return exp( p->avgLnI[i] - p->avgLnKI[i] );
} else {
return exp( p->avgLnK[i][i] + p->avgLnK[i][j] - p->avgLnKI[i] );
}
}
double pTilde_xn_zn_tsFret( xn, n, i, params )
xnDataSet *xn;
size_t n;
int i;
void *params;
{
tsFretParameters *p = (tsFretParameters*)params;
tsFretData *d = (tsFretData*)xn->data;
return exp( p->avgLnI[i] - (p->avgI[i] * d->dt[n]) + p->avgLnE[i][d->ch[n]] );
}
void calcStatsVars_tsFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsFretData *d = (tsFretData*)xn->data;
tsFretStats *s = (tsFretStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;
double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Ti[i] = 1e-10;
eps[i] = 1e-10;
Nii[i] = 0.0;
Nij[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
Mij[i][j] = 1e-10;
}
}
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){
Ni[i] += gmMat[n][i];
Ti[i] += gmMat[n][i] * d->dt[n];
eps[i] += gmMat[n][i] * d->ch[n];
Nii[i] += xiMat[n][i][i];
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
Mij[i][j] += xiMat[n][i][j];
Nij[i] += xiMat[n][i][j];
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){
Nii[i] = MAX( Nii[i], 1.0 );
Nij[i] = MAX( Nij[i], 1.0 );
}
}
//void calcStatsVarsG_tsFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void maximization_tsFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsFretParameters *p = (tsFretParameters*)gv->params;
tsFretStats *s = (tsFretStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK, **avgLnK = p->avgLnK;
double *avgLnKI = p->avgLnKI, *avgI = p->avgI, *avgLnI = p->avgLnI;
double *avgE = p->avgE, **avgLnE = p->avgLnE;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;
double *uEArr = p->uEArr, *vEArr = p->vEArr;
double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;
double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );
avgK[i][i] = (Ni[i] + aIArr[i]) * Nij[i] / (Nii[i] - 1.0) / (Ti[i] + bIArr[i]);
avgLnK[i][i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nij[i]);
avgLnK[i][i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);
avgI[i] = (Ni[i] + aIArr[i]) / (Ti[i] + bIArr[i]);
avgLnI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) - log(Ti[i] + bIArr[i]);
avgLnKI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nii[i] + Nij[i]);
avgLnKI[i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);
#ifdef INTENSITY_CAP
double meanI = (double)xnWv->N / xnWv->T;
avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );
avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );
#endif
#ifdef TRANSITION_RATE_CAP
avgK[i][i] = MIN( avgK[i][i], avgI[i]/minPhotonNumPerState );
avgLnK[i][i] = MIN( avgLnK[i][i], avgLnI[i] - log(minPhotonNumPerState) );
avgLnKI[i] = MIN( avgLnKI[i], avgLnI[i] + log(1.0 + 1.0/minPhotonNumPerState) );
#endif
for( j = 0 ; j < sNo ; j++ ){
if( i != j ){
avgK[i][j] = ( uKMat[i][j] + Mij[i][j] ) / ( sumUKArr[i] + Nij[i] );
avgLnK[i][j] = gsl_sf_psi( uKMat[i][j] + Mij[i][j] ) - gsl_sf_psi( sumUKArr[i] + Nij[i] );
}
}
avgE[i] = ( uEArr[i] + eps[i] ) / ( uEArr[i] + vEArr[i] + Ni[i] );
avgLnE[i][0] = gsl_sf_psi( vEArr[i] + Ni[i] - eps[i] ); // ln(1-E) for donor
avgLnE[i][0] -= gsl_sf_psi( uEArr[i] + vEArr[i] + Ni[i] );
avgLnE[i][1] = gsl_sf_psi( uEArr[i] + eps[i] ); // ln(E) for acceptor
avgLnE[i][1] -= gsl_sf_psi( uEArr[i] + vEArr[i] + Ni[i] );
}
}
//void maximizationG_tsFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
double varLowerBound_tsFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsFretParameters *p = (tsFretParameters*)gv->params;
tsFretStats *s = (tsFretStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, *cn = iv->cn;
double *avgLnPi = p->avgLnPi, **avgLnK = p->avgLnK, *avgI = p->avgI, *avgLnI = p->avgLnI;
double *avgLnKI = p->avgLnKI, **avgLnE = p->avgLnE;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;
double *uEArr = p->uEArr, *vEArr = p->vEArr;
double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;
double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;
size_t n;
int i, j;
double lnpPi = gsl_sf_lngamma(sumUPi);
double Ck = 1.0, lnpKii = sNo * log(Ck);
double lnpKij = 0.0;
double lnpI = 0.0;
double lnpE = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + 1);
double lnqKiiI = 0.0;
double lnqKij = 0.0;
double lnqE = 0.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpKii -= avgLnK[i][i];
lnpI += aIArr[i] * log(bIArr[i]) - gsl_sf_lngamma(aIArr[i]);
lnpI += (aIArr[i]-1.0)*avgLnI[i] - bIArr[i]*avgI[i];
lnpE += gsl_sf_lngamma(uEArr[i]+vEArr[i]) - gsl_sf_lngamma(uEArr[i]);
lnpE += -gsl_sf_lngamma(vEArr[i]);
lnpE += (uEArr[i]-1.0)*avgLnE[i][1] + (vEArr[i]-1.0)*avgLnE[i][0];
lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);
lnqKiiI += gsl_sf_lngamma(Nii[i] + Nij[i]) + (Ni[i] + aIArr[i]) * log(Ti[i] + bIArr[i]);
lnqKiiI += -gsl_sf_lngamma(Ni[i] + aIArr[i]) -gsl_sf_lngamma(Nii[i]);
lnqKiiI += -gsl_sf_lngamma(Nij[i]) + (Nij[i]-1.0)*avgLnK[i][i];
lnqKiiI += (Ni[i] + Nii[i] + aIArr[i] - 1.0)*avgLnI[i];
lnqKiiI += -(Nii[i] + Nij[i])*avgLnKI[i] - (Ti[i] + bIArr[i])*avgI[i];
lnqE += gsl_sf_lngamma(uEArr[i] + vEArr[i] + Ni[i]);
lnqE -= gsl_sf_lngamma(uEArr[i] + eps[i]);
lnqE -= gsl_sf_lngamma(vEArr[i] + Ni[i] - eps[i]);
lnqE += (uEArr[i] + eps[i] - 1.0)*avgLnE[i][1];
lnqE += (vEArr[i] + Ni[i] - eps[i] - 1.0)*avgLnE[i][0];
lnpKij += gsl_sf_lngamma(sumUKArr[i]);
lnqKij += gsl_sf_lngamma(sumUKArr[i] + Nij[i]);
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
lnpKij += (uKMat[i][j]-1.0)*avgLnK[i][j] - gsl_sf_lngamma(uKMat[i][j]);
lnqKij += (uKMat[i][j]+Mij[i][j]-1)*(gsl_sf_psi(uKMat[i][j]+Mij[i][j])-gsl_sf_psi(sumUKArr[i]+Nij[i]));
lnqKij -= gsl_sf_lngamma( uKMat[i][j] + Mij[i][j] );
}
}
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpKii + lnpKij + lnpI + lnpE;
val -= lnqPi + lnqKiiI + lnqKij + lnqE;
val += lnpX;
return val;
}
//double varLowerBoundG_tsFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void reorderParameters_tsFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsFretParameters *p = (tsFretParameters*)gv->params;
tsFretStats *s = (tsFretStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK;
double **avgLnK = p->avgLnK, *avgLnKI = p->avgLnKI;
double *avgI = p->avgI, *avgLnI = p->avgLnI, *avgE = p->avgE, **avgLnE = p->avgLnE;
double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;
size_t n;
int i, j;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgE values (0=biggest avgE -- sNo=smallest avgE).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgE[i] < avgE[j] ){
index[i]--;
} else if( avgE[i] == avgE[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgI[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnI[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgK[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgK[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnK[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnK[i][j] = s2D[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnKI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnKI[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgE[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgE[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ )
{ s2D[index[i]][0] = avgLnE[i][0];
s2D[index[i]][1] = avgLnE[i][1]; }
for( i = 0 ; i < sNo ; i++ )
{ avgLnE[i][0] = s2D[i][0];
avgLnE[i][1] = s2D[i][1]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ti[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ti[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = eps[i]; }
for( i = 0 ; i < sNo ; i++ ){ eps[i] = store[i]; }
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
//void reorderParametersG_tsFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void outputTsFretResults( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
tsFretParameters *p = (tsFretParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " intensities: ( %g", p->avgI[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgI[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " FRET efficiencies: ( %g", p->avgE[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgE[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " k_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgK[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgK[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "I, E, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", K%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g, %g", p->avgI[i], p->avgE[i], p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgK[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
//void outputTsFretResultsG( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
//}
//
| {
"alphanum_fraction": 0.504381161,
"avg_line_length": 29.0906862745,
"ext": "c",
"hexsha": "2e8dec02c34c872ee02df3f61995a2e54d96f4b5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "okamoto-kenji/varBayes-HMM",
"max_forks_repo_path": "C/vbHmmTsFret.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "okamoto-kenji/varBayes-HMM",
"max_issues_repo_path": "C/vbHmmTsFret.c",
"max_line_length": 119,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "okamoto-kenji/varBayes-HMM",
"max_stars_repo_path": "C/vbHmmTsFret.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z",
"num_tokens": 8899,
"size": 23738
} |
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Sun Nov 7 20:45:16 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-backward 16 */
/*
* This function contains 298 FP additions, 134 FP multiplications,
* (or, 244 additions, 80 multiplications, 54 fused multiply/add),
* 49 stack variables, and 128 memory accesses
*/
static const fftw_real K1_961570560 = FFTW_KONST(+1.961570560806460898252364472268478073947867462);
static const fftw_real K390180644 = FFTW_KONST(+0.390180644032256535696569736954044481855383236);
static const fftw_real K1_111140466 = FFTW_KONST(+1.111140466039204449485661627897065748749874382);
static const fftw_real K1_662939224 = FFTW_KONST(+1.662939224605090474157576755235811513477121624);
static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);
static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);
static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);
static const fftw_real K765366864 = FFTW_KONST(+0.765366864730179543456919968060797733522689125);
static const fftw_real K1_847759065 = FFTW_KONST(+1.847759065022573512256366378793576573644833252);
static const fftw_real K1_414213562 = FFTW_KONST(+1.414213562373095048801688724209698078569671875);
static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_hc2hc_backward_16(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist)
{
int i;
fftw_real *X;
fftw_real *Y;
X = A;
Y = A + (16 * iostride);
{
fftw_real tmp279;
fftw_real tmp324;
fftw_real tmp312;
fftw_real tmp299;
fftw_real tmp276;
fftw_real tmp296;
fftw_real tmp309;
fftw_real tmp323;
fftw_real tmp283;
fftw_real tmp291;
fftw_real tmp286;
fftw_real tmp294;
fftw_real tmp301;
fftw_real tmp319;
fftw_real tmp327;
fftw_real tmp326;
fftw_real tmp316;
fftw_real tmp302;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp277;
fftw_real tmp278;
fftw_real tmp310;
fftw_real tmp297;
fftw_real tmp298;
fftw_real tmp311;
ASSERT_ALIGNED_DOUBLE;
tmp277 = X[2 * iostride];
tmp278 = X[6 * iostride];
tmp310 = tmp277 - tmp278;
tmp297 = Y[-2 * iostride];
tmp298 = Y[-6 * iostride];
tmp311 = tmp298 + tmp297;
tmp279 = K2_000000000 * (tmp277 + tmp278);
tmp324 = K1_414213562 * (tmp310 + tmp311);
tmp312 = K1_414213562 * (tmp310 - tmp311);
tmp299 = K2_000000000 * (tmp297 - tmp298);
}
{
fftw_real tmp275;
fftw_real tmp308;
fftw_real tmp273;
fftw_real tmp306;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp274;
fftw_real tmp307;
fftw_real tmp271;
fftw_real tmp272;
ASSERT_ALIGNED_DOUBLE;
tmp274 = X[4 * iostride];
tmp275 = K2_000000000 * tmp274;
tmp307 = Y[-4 * iostride];
tmp308 = K2_000000000 * tmp307;
tmp271 = X[0];
tmp272 = X[8 * iostride];
tmp273 = tmp271 + tmp272;
tmp306 = tmp271 - tmp272;
}
tmp276 = tmp273 + tmp275;
tmp296 = tmp273 - tmp275;
tmp309 = tmp306 - tmp308;
tmp323 = tmp306 + tmp308;
}
{
fftw_real tmp314;
fftw_real tmp318;
fftw_real tmp317;
fftw_real tmp315;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp281;
fftw_real tmp282;
fftw_real tmp289;
fftw_real tmp290;
ASSERT_ALIGNED_DOUBLE;
tmp281 = X[iostride];
tmp282 = X[7 * iostride];
tmp283 = tmp281 + tmp282;
tmp314 = tmp281 - tmp282;
tmp289 = Y[-iostride];
tmp290 = Y[-7 * iostride];
tmp291 = tmp289 - tmp290;
tmp318 = tmp289 + tmp290;
}
{
fftw_real tmp284;
fftw_real tmp285;
fftw_real tmp292;
fftw_real tmp293;
ASSERT_ALIGNED_DOUBLE;
tmp284 = X[3 * iostride];
tmp285 = X[5 * iostride];
tmp286 = tmp284 + tmp285;
tmp317 = tmp285 - tmp284;
tmp292 = Y[-3 * iostride];
tmp293 = Y[-5 * iostride];
tmp294 = tmp292 - tmp293;
tmp315 = tmp293 + tmp292;
}
tmp301 = tmp283 - tmp286;
tmp319 = tmp317 + tmp318;
tmp327 = tmp318 - tmp317;
tmp326 = tmp314 + tmp315;
tmp316 = tmp314 - tmp315;
tmp302 = tmp294 + tmp291;
}
{
fftw_real tmp280;
fftw_real tmp287;
fftw_real tmp288;
fftw_real tmp295;
ASSERT_ALIGNED_DOUBLE;
tmp280 = tmp276 + tmp279;
tmp287 = K2_000000000 * (tmp283 + tmp286);
X[8 * iostride] = tmp280 - tmp287;
X[0] = tmp280 + tmp287;
tmp288 = tmp276 - tmp279;
tmp295 = K2_000000000 * (tmp291 - tmp294);
X[12 * iostride] = tmp288 + tmp295;
X[4 * iostride] = tmp288 - tmp295;
}
{
fftw_real tmp300;
fftw_real tmp303;
fftw_real tmp304;
fftw_real tmp305;
ASSERT_ALIGNED_DOUBLE;
tmp300 = tmp296 - tmp299;
tmp303 = K1_414213562 * (tmp301 - tmp302);
X[10 * iostride] = tmp300 - tmp303;
X[2 * iostride] = tmp300 + tmp303;
tmp304 = tmp296 + tmp299;
tmp305 = K1_414213562 * (tmp301 + tmp302);
X[6 * iostride] = tmp304 - tmp305;
X[14 * iostride] = tmp304 + tmp305;
}
{
fftw_real tmp313;
fftw_real tmp320;
fftw_real tmp321;
fftw_real tmp322;
ASSERT_ALIGNED_DOUBLE;
tmp313 = tmp309 + tmp312;
tmp320 = (K1_847759065 * tmp316) - (K765366864 * tmp319);
X[9 * iostride] = tmp313 - tmp320;
X[iostride] = tmp313 + tmp320;
tmp321 = tmp309 - tmp312;
tmp322 = (K765366864 * tmp316) + (K1_847759065 * tmp319);
X[5 * iostride] = tmp321 - tmp322;
X[13 * iostride] = tmp321 + tmp322;
}
{
fftw_real tmp325;
fftw_real tmp328;
fftw_real tmp329;
fftw_real tmp330;
ASSERT_ALIGNED_DOUBLE;
tmp325 = tmp323 - tmp324;
tmp328 = (K765366864 * tmp326) - (K1_847759065 * tmp327);
X[11 * iostride] = tmp325 - tmp328;
X[3 * iostride] = tmp325 + tmp328;
tmp329 = tmp323 + tmp324;
tmp330 = (K1_847759065 * tmp326) + (K765366864 * tmp327);
X[7 * iostride] = tmp329 - tmp330;
X[15 * iostride] = tmp329 + tmp330;
}
}
X = X + dist;
Y = Y - dist;
for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 15) {
fftw_real tmp73;
fftw_real tmp98;
fftw_real tmp135;
fftw_real tmp160;
fftw_real tmp182;
fftw_real tmp236;
fftw_real tmp210;
fftw_real tmp248;
fftw_real tmp95;
fftw_real tmp124;
fftw_real tmp138;
fftw_real tmp164;
fftw_real tmp197;
fftw_real tmp216;
fftw_real tmp244;
fftw_real tmp252;
fftw_real tmp80;
fftw_real tmp128;
fftw_real tmp105;
fftw_real tmp161;
fftw_real tmp213;
fftw_real tmp237;
fftw_real tmp189;
fftw_real tmp249;
fftw_real tmp88;
fftw_real tmp115;
fftw_real tmp137;
fftw_real tmp163;
fftw_real tmp204;
fftw_real tmp215;
fftw_real tmp241;
fftw_real tmp251;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp69;
fftw_real tmp180;
fftw_real tmp131;
fftw_real tmp209;
fftw_real tmp72;
fftw_real tmp208;
fftw_real tmp134;
fftw_real tmp181;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp67;
fftw_real tmp68;
fftw_real tmp129;
fftw_real tmp130;
ASSERT_ALIGNED_DOUBLE;
tmp67 = X[0];
tmp68 = Y[-8 * iostride];
tmp69 = tmp67 + tmp68;
tmp180 = tmp67 - tmp68;
tmp129 = Y[0];
tmp130 = X[8 * iostride];
tmp131 = tmp129 - tmp130;
tmp209 = tmp129 + tmp130;
}
{
fftw_real tmp70;
fftw_real tmp71;
fftw_real tmp132;
fftw_real tmp133;
ASSERT_ALIGNED_DOUBLE;
tmp70 = X[4 * iostride];
tmp71 = Y[-12 * iostride];
tmp72 = tmp70 + tmp71;
tmp208 = tmp70 - tmp71;
tmp132 = Y[-4 * iostride];
tmp133 = X[12 * iostride];
tmp134 = tmp132 - tmp133;
tmp181 = tmp132 + tmp133;
}
tmp73 = tmp69 + tmp72;
tmp98 = tmp69 - tmp72;
tmp135 = tmp131 - tmp134;
tmp160 = tmp131 + tmp134;
tmp182 = tmp180 - tmp181;
tmp236 = tmp180 + tmp181;
tmp210 = tmp208 + tmp209;
tmp248 = tmp209 - tmp208;
}
{
fftw_real tmp91;
fftw_real tmp194;
fftw_real tmp119;
fftw_real tmp192;
fftw_real tmp94;
fftw_real tmp191;
fftw_real tmp122;
fftw_real tmp195;
fftw_real tmp116;
fftw_real tmp123;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp89;
fftw_real tmp90;
fftw_real tmp117;
fftw_real tmp118;
ASSERT_ALIGNED_DOUBLE;
tmp89 = Y[-15 * iostride];
tmp90 = X[7 * iostride];
tmp91 = tmp89 + tmp90;
tmp194 = tmp89 - tmp90;
tmp117 = Y[-7 * iostride];
tmp118 = X[15 * iostride];
tmp119 = tmp117 - tmp118;
tmp192 = tmp117 + tmp118;
}
{
fftw_real tmp92;
fftw_real tmp93;
fftw_real tmp120;
fftw_real tmp121;
ASSERT_ALIGNED_DOUBLE;
tmp92 = X[3 * iostride];
tmp93 = Y[-11 * iostride];
tmp94 = tmp92 + tmp93;
tmp191 = tmp92 - tmp93;
tmp120 = Y[-3 * iostride];
tmp121 = X[11 * iostride];
tmp122 = tmp120 - tmp121;
tmp195 = tmp120 + tmp121;
}
tmp95 = tmp91 + tmp94;
tmp116 = tmp91 - tmp94;
tmp123 = tmp119 - tmp122;
tmp124 = tmp116 + tmp123;
tmp138 = tmp123 - tmp116;
tmp164 = tmp119 + tmp122;
{
fftw_real tmp193;
fftw_real tmp196;
fftw_real tmp242;
fftw_real tmp243;
ASSERT_ALIGNED_DOUBLE;
tmp193 = tmp191 - tmp192;
tmp196 = tmp194 - tmp195;
tmp197 = (K923879532 * tmp193) - (K382683432 * tmp196);
tmp216 = (K382683432 * tmp193) + (K923879532 * tmp196);
tmp242 = tmp194 + tmp195;
tmp243 = tmp191 + tmp192;
tmp244 = (K382683432 * tmp242) - (K923879532 * tmp243);
tmp252 = (K382683432 * tmp243) + (K923879532 * tmp242);
}
}
{
fftw_real tmp76;
fftw_real tmp183;
fftw_real tmp104;
fftw_real tmp184;
fftw_real tmp79;
fftw_real tmp186;
fftw_real tmp101;
fftw_real tmp187;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp74;
fftw_real tmp75;
fftw_real tmp102;
fftw_real tmp103;
ASSERT_ALIGNED_DOUBLE;
tmp74 = X[2 * iostride];
tmp75 = Y[-10 * iostride];
tmp76 = tmp74 + tmp75;
tmp183 = tmp74 - tmp75;
tmp102 = Y[-2 * iostride];
tmp103 = X[10 * iostride];
tmp104 = tmp102 - tmp103;
tmp184 = tmp102 + tmp103;
}
{
fftw_real tmp77;
fftw_real tmp78;
fftw_real tmp99;
fftw_real tmp100;
ASSERT_ALIGNED_DOUBLE;
tmp77 = Y[-14 * iostride];
tmp78 = X[6 * iostride];
tmp79 = tmp77 + tmp78;
tmp186 = tmp77 - tmp78;
tmp99 = Y[-6 * iostride];
tmp100 = X[14 * iostride];
tmp101 = tmp99 - tmp100;
tmp187 = tmp99 + tmp100;
}
tmp80 = tmp76 + tmp79;
tmp128 = tmp76 - tmp79;
tmp105 = tmp101 - tmp104;
tmp161 = tmp104 + tmp101;
{
fftw_real tmp211;
fftw_real tmp212;
fftw_real tmp185;
fftw_real tmp188;
ASSERT_ALIGNED_DOUBLE;
tmp211 = tmp183 + tmp184;
tmp212 = tmp186 + tmp187;
tmp213 = K707106781 * (tmp211 - tmp212);
tmp237 = K707106781 * (tmp211 + tmp212);
tmp185 = tmp183 - tmp184;
tmp188 = tmp186 - tmp187;
tmp189 = K707106781 * (tmp185 + tmp188);
tmp249 = K707106781 * (tmp185 - tmp188);
}
}
{
fftw_real tmp84;
fftw_real tmp201;
fftw_real tmp110;
fftw_real tmp199;
fftw_real tmp87;
fftw_real tmp198;
fftw_real tmp113;
fftw_real tmp202;
fftw_real tmp107;
fftw_real tmp114;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp82;
fftw_real tmp83;
fftw_real tmp108;
fftw_real tmp109;
ASSERT_ALIGNED_DOUBLE;
tmp82 = X[iostride];
tmp83 = Y[-9 * iostride];
tmp84 = tmp82 + tmp83;
tmp201 = tmp82 - tmp83;
tmp108 = Y[-iostride];
tmp109 = X[9 * iostride];
tmp110 = tmp108 - tmp109;
tmp199 = tmp108 + tmp109;
}
{
fftw_real tmp85;
fftw_real tmp86;
fftw_real tmp111;
fftw_real tmp112;
ASSERT_ALIGNED_DOUBLE;
tmp85 = X[5 * iostride];
tmp86 = Y[-13 * iostride];
tmp87 = tmp85 + tmp86;
tmp198 = tmp85 - tmp86;
tmp111 = Y[-5 * iostride];
tmp112 = X[13 * iostride];
tmp113 = tmp111 - tmp112;
tmp202 = tmp111 + tmp112;
}
tmp88 = tmp84 + tmp87;
tmp107 = tmp84 - tmp87;
tmp114 = tmp110 - tmp113;
tmp115 = tmp107 - tmp114;
tmp137 = tmp107 + tmp114;
tmp163 = tmp110 + tmp113;
{
fftw_real tmp200;
fftw_real tmp203;
fftw_real tmp239;
fftw_real tmp240;
ASSERT_ALIGNED_DOUBLE;
tmp200 = tmp198 + tmp199;
tmp203 = tmp201 - tmp202;
tmp204 = (K923879532 * tmp200) + (K382683432 * tmp203);
tmp215 = (K923879532 * tmp203) - (K382683432 * tmp200);
tmp239 = tmp201 + tmp202;
tmp240 = tmp199 - tmp198;
tmp241 = (K382683432 * tmp239) - (K923879532 * tmp240);
tmp251 = (K382683432 * tmp240) + (K923879532 * tmp239);
}
}
{
fftw_real tmp81;
fftw_real tmp96;
fftw_real tmp158;
fftw_real tmp162;
fftw_real tmp165;
fftw_real tmp166;
fftw_real tmp157;
fftw_real tmp159;
ASSERT_ALIGNED_DOUBLE;
tmp81 = tmp73 + tmp80;
tmp96 = tmp88 + tmp95;
tmp158 = tmp81 - tmp96;
tmp162 = tmp160 + tmp161;
tmp165 = tmp163 + tmp164;
tmp166 = tmp162 - tmp165;
X[0] = tmp81 + tmp96;
Y[-15 * iostride] = tmp162 + tmp165;
tmp157 = c_re(W[7]);
tmp159 = c_im(W[7]);
X[8 * iostride] = (tmp157 * tmp158) + (tmp159 * tmp166);
Y[-7 * iostride] = (tmp157 * tmp166) - (tmp159 * tmp158);
}
{
fftw_real tmp170;
fftw_real tmp176;
fftw_real tmp174;
fftw_real tmp178;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp168;
fftw_real tmp169;
fftw_real tmp172;
fftw_real tmp173;
ASSERT_ALIGNED_DOUBLE;
tmp168 = tmp160 - tmp161;
tmp169 = tmp88 - tmp95;
tmp170 = tmp168 - tmp169;
tmp176 = tmp169 + tmp168;
tmp172 = tmp73 - tmp80;
tmp173 = tmp164 - tmp163;
tmp174 = tmp172 - tmp173;
tmp178 = tmp172 + tmp173;
}
{
fftw_real tmp167;
fftw_real tmp171;
fftw_real tmp175;
fftw_real tmp177;
ASSERT_ALIGNED_DOUBLE;
tmp167 = c_re(W[11]);
tmp171 = c_im(W[11]);
Y[-3 * iostride] = (tmp167 * tmp170) - (tmp171 * tmp174);
X[12 * iostride] = (tmp171 * tmp170) + (tmp167 * tmp174);
tmp175 = c_re(W[3]);
tmp177 = c_im(W[3]);
Y[-11 * iostride] = (tmp175 * tmp176) - (tmp177 * tmp178);
X[4 * iostride] = (tmp177 * tmp176) + (tmp175 * tmp178);
}
}
{
fftw_real tmp126;
fftw_real tmp142;
fftw_real tmp140;
fftw_real tmp144;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp106;
fftw_real tmp125;
fftw_real tmp136;
fftw_real tmp139;
ASSERT_ALIGNED_DOUBLE;
tmp106 = tmp98 + tmp105;
tmp125 = K707106781 * (tmp115 + tmp124);
tmp126 = tmp106 - tmp125;
tmp142 = tmp106 + tmp125;
tmp136 = tmp128 + tmp135;
tmp139 = K707106781 * (tmp137 + tmp138);
tmp140 = tmp136 - tmp139;
tmp144 = tmp136 + tmp139;
}
{
fftw_real tmp97;
fftw_real tmp127;
fftw_real tmp141;
fftw_real tmp143;
ASSERT_ALIGNED_DOUBLE;
tmp97 = c_re(W[9]);
tmp127 = c_im(W[9]);
X[10 * iostride] = (tmp97 * tmp126) + (tmp127 * tmp140);
Y[-5 * iostride] = (tmp97 * tmp140) - (tmp127 * tmp126);
tmp141 = c_re(W[1]);
tmp143 = c_im(W[1]);
X[2 * iostride] = (tmp141 * tmp142) + (tmp143 * tmp144);
Y[-13 * iostride] = (tmp141 * tmp144) - (tmp143 * tmp142);
}
}
{
fftw_real tmp148;
fftw_real tmp154;
fftw_real tmp152;
fftw_real tmp156;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp146;
fftw_real tmp147;
fftw_real tmp150;
fftw_real tmp151;
ASSERT_ALIGNED_DOUBLE;
tmp146 = tmp135 - tmp128;
tmp147 = K707106781 * (tmp115 - tmp124);
tmp148 = tmp146 - tmp147;
tmp154 = tmp146 + tmp147;
tmp150 = tmp98 - tmp105;
tmp151 = K707106781 * (tmp138 - tmp137);
tmp152 = tmp150 - tmp151;
tmp156 = tmp150 + tmp151;
}
{
fftw_real tmp145;
fftw_real tmp149;
fftw_real tmp153;
fftw_real tmp155;
ASSERT_ALIGNED_DOUBLE;
tmp145 = c_re(W[13]);
tmp149 = c_im(W[13]);
Y[-iostride] = (tmp145 * tmp148) - (tmp149 * tmp152);
X[14 * iostride] = (tmp149 * tmp148) + (tmp145 * tmp152);
tmp153 = c_re(W[5]);
tmp155 = c_im(W[5]);
Y[-9 * iostride] = (tmp153 * tmp154) - (tmp155 * tmp156);
X[6 * iostride] = (tmp155 * tmp154) + (tmp153 * tmp156);
}
}
{
fftw_real tmp206;
fftw_real tmp220;
fftw_real tmp218;
fftw_real tmp222;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp190;
fftw_real tmp205;
fftw_real tmp214;
fftw_real tmp217;
ASSERT_ALIGNED_DOUBLE;
tmp190 = tmp182 - tmp189;
tmp205 = tmp197 - tmp204;
tmp206 = tmp190 - tmp205;
tmp220 = tmp190 + tmp205;
tmp214 = tmp210 - tmp213;
tmp217 = tmp215 - tmp216;
tmp218 = tmp214 - tmp217;
tmp222 = tmp214 + tmp217;
}
{
fftw_real tmp179;
fftw_real tmp207;
fftw_real tmp219;
fftw_real tmp221;
ASSERT_ALIGNED_DOUBLE;
tmp179 = c_re(W[12]);
tmp207 = c_im(W[12]);
X[13 * iostride] = (tmp179 * tmp206) + (tmp207 * tmp218);
Y[-2 * iostride] = (tmp179 * tmp218) - (tmp207 * tmp206);
tmp219 = c_re(W[4]);
tmp221 = c_im(W[4]);
X[5 * iostride] = (tmp219 * tmp220) + (tmp221 * tmp222);
Y[-10 * iostride] = (tmp219 * tmp222) - (tmp221 * tmp220);
}
}
{
fftw_real tmp226;
fftw_real tmp232;
fftw_real tmp230;
fftw_real tmp234;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp224;
fftw_real tmp225;
fftw_real tmp228;
fftw_real tmp229;
ASSERT_ALIGNED_DOUBLE;
tmp224 = tmp210 + tmp213;
tmp225 = tmp204 + tmp197;
tmp226 = tmp224 - tmp225;
tmp232 = tmp224 + tmp225;
tmp228 = tmp182 + tmp189;
tmp229 = tmp215 + tmp216;
tmp230 = tmp228 - tmp229;
tmp234 = tmp228 + tmp229;
}
{
fftw_real tmp223;
fftw_real tmp227;
fftw_real tmp231;
fftw_real tmp233;
ASSERT_ALIGNED_DOUBLE;
tmp223 = c_re(W[8]);
tmp227 = c_im(W[8]);
Y[-6 * iostride] = (tmp223 * tmp226) - (tmp227 * tmp230);
X[9 * iostride] = (tmp227 * tmp226) + (tmp223 * tmp230);
tmp231 = c_re(W[0]);
tmp233 = c_im(W[0]);
Y[-14 * iostride] = (tmp231 * tmp232) - (tmp233 * tmp234);
X[iostride] = (tmp233 * tmp232) + (tmp231 * tmp234);
}
}
{
fftw_real tmp246;
fftw_real tmp256;
fftw_real tmp254;
fftw_real tmp258;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp238;
fftw_real tmp245;
fftw_real tmp250;
fftw_real tmp253;
ASSERT_ALIGNED_DOUBLE;
tmp238 = tmp236 - tmp237;
tmp245 = tmp241 + tmp244;
tmp246 = tmp238 - tmp245;
tmp256 = tmp238 + tmp245;
tmp250 = tmp248 + tmp249;
tmp253 = tmp251 - tmp252;
tmp254 = tmp250 - tmp253;
tmp258 = tmp250 + tmp253;
}
{
fftw_real tmp235;
fftw_real tmp247;
fftw_real tmp255;
fftw_real tmp257;
ASSERT_ALIGNED_DOUBLE;
tmp235 = c_re(W[10]);
tmp247 = c_im(W[10]);
X[11 * iostride] = (tmp235 * tmp246) + (tmp247 * tmp254);
Y[-4 * iostride] = (tmp235 * tmp254) - (tmp247 * tmp246);
tmp255 = c_re(W[2]);
tmp257 = c_im(W[2]);
X[3 * iostride] = (tmp255 * tmp256) + (tmp257 * tmp258);
Y[-12 * iostride] = (tmp255 * tmp258) - (tmp257 * tmp256);
}
}
{
fftw_real tmp262;
fftw_real tmp268;
fftw_real tmp266;
fftw_real tmp270;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp260;
fftw_real tmp261;
fftw_real tmp264;
fftw_real tmp265;
ASSERT_ALIGNED_DOUBLE;
tmp260 = tmp248 - tmp249;
tmp261 = tmp241 - tmp244;
tmp262 = tmp260 + tmp261;
tmp268 = tmp260 - tmp261;
tmp264 = tmp236 + tmp237;
tmp265 = tmp251 + tmp252;
tmp266 = tmp264 - tmp265;
tmp270 = tmp264 + tmp265;
}
{
fftw_real tmp259;
fftw_real tmp263;
fftw_real tmp267;
fftw_real tmp269;
ASSERT_ALIGNED_DOUBLE;
tmp259 = c_re(W[6]);
tmp263 = c_im(W[6]);
Y[-8 * iostride] = (tmp259 * tmp262) - (tmp263 * tmp266);
X[7 * iostride] = (tmp263 * tmp262) + (tmp259 * tmp266);
tmp267 = c_re(W[14]);
tmp269 = c_im(W[14]);
Y[0] = (tmp267 * tmp268) - (tmp269 * tmp270);
X[15 * iostride] = (tmp269 * tmp268) + (tmp267 * tmp270);
}
}
}
if (i == m) {
fftw_real tmp7;
fftw_real tmp51;
fftw_real tmp19;
fftw_real tmp43;
fftw_real tmp39;
fftw_real tmp47;
fftw_real tmp59;
fftw_real tmp64;
fftw_real tmp14;
fftw_real tmp56;
fftw_real tmp24;
fftw_real tmp32;
fftw_real tmp29;
fftw_real tmp33;
fftw_real tmp54;
fftw_real tmp65;
fftw_real tmp63;
fftw_real tmp66;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp3;
fftw_real tmp15;
fftw_real tmp38;
fftw_real tmp57;
fftw_real tmp6;
fftw_real tmp35;
fftw_real tmp18;
fftw_real tmp58;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp1;
fftw_real tmp2;
fftw_real tmp36;
fftw_real tmp37;
ASSERT_ALIGNED_DOUBLE;
tmp1 = X[0];
tmp2 = X[7 * iostride];
tmp3 = tmp1 + tmp2;
tmp15 = tmp1 - tmp2;
tmp36 = Y[0];
tmp37 = Y[-7 * iostride];
tmp38 = tmp36 + tmp37;
tmp57 = tmp36 - tmp37;
}
{
fftw_real tmp4;
fftw_real tmp5;
fftw_real tmp16;
fftw_real tmp17;
ASSERT_ALIGNED_DOUBLE;
tmp4 = X[4 * iostride];
tmp5 = X[3 * iostride];
tmp6 = tmp4 + tmp5;
tmp35 = tmp4 - tmp5;
tmp16 = Y[-4 * iostride];
tmp17 = Y[-3 * iostride];
tmp18 = tmp16 + tmp17;
tmp58 = tmp16 - tmp17;
}
tmp7 = tmp3 + tmp6;
tmp51 = tmp3 - tmp6;
tmp19 = tmp15 - tmp18;
tmp43 = tmp15 + tmp18;
tmp39 = tmp35 + tmp38;
tmp47 = tmp38 - tmp35;
tmp59 = tmp57 - tmp58;
tmp64 = tmp58 + tmp57;
}
{
fftw_real tmp10;
fftw_real tmp20;
fftw_real tmp23;
fftw_real tmp53;
fftw_real tmp13;
fftw_real tmp25;
fftw_real tmp28;
fftw_real tmp52;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp8;
fftw_real tmp9;
fftw_real tmp21;
fftw_real tmp22;
ASSERT_ALIGNED_DOUBLE;
tmp8 = X[2 * iostride];
tmp9 = X[5 * iostride];
tmp10 = tmp8 + tmp9;
tmp20 = tmp8 - tmp9;
tmp21 = Y[-2 * iostride];
tmp22 = Y[-5 * iostride];
tmp23 = tmp21 + tmp22;
tmp53 = tmp21 - tmp22;
}
{
fftw_real tmp11;
fftw_real tmp12;
fftw_real tmp26;
fftw_real tmp27;
ASSERT_ALIGNED_DOUBLE;
tmp11 = X[iostride];
tmp12 = X[6 * iostride];
tmp13 = tmp11 + tmp12;
tmp25 = tmp11 - tmp12;
tmp26 = Y[-iostride];
tmp27 = Y[-6 * iostride];
tmp28 = tmp26 + tmp27;
tmp52 = tmp27 - tmp26;
}
tmp14 = tmp10 + tmp13;
tmp56 = tmp10 - tmp13;
tmp24 = tmp20 - tmp23;
tmp32 = tmp20 + tmp23;
tmp29 = tmp25 - tmp28;
tmp33 = tmp25 + tmp28;
tmp54 = tmp52 - tmp53;
tmp65 = tmp53 + tmp52;
}
X[0] = K2_000000000 * (tmp7 + tmp14);
X[8 * iostride] = -(K2_000000000 * (tmp65 + tmp64));
tmp63 = tmp7 - tmp14;
tmp66 = tmp64 - tmp65;
X[4 * iostride] = K1_414213562 * (tmp63 - tmp66);
X[12 * iostride] = -(K1_414213562 * (tmp63 + tmp66));
{
fftw_real tmp61;
fftw_real tmp62;
fftw_real tmp55;
fftw_real tmp60;
ASSERT_ALIGNED_DOUBLE;
tmp61 = tmp51 - tmp54;
tmp62 = tmp59 - tmp56;
X[6 * iostride] = (K765366864 * tmp61) - (K1_847759065 * tmp62);
X[14 * iostride] = -((K1_847759065 * tmp61) + (K765366864 * tmp62));
tmp55 = tmp51 + tmp54;
tmp60 = tmp56 + tmp59;
X[2 * iostride] = (K1_847759065 * tmp55) - (K765366864 * tmp60);
X[10 * iostride] = -((K765366864 * tmp55) + (K1_847759065 * tmp60));
}
{
fftw_real tmp45;
fftw_real tmp49;
fftw_real tmp48;
fftw_real tmp50;
fftw_real tmp44;
fftw_real tmp46;
ASSERT_ALIGNED_DOUBLE;
tmp44 = K707106781 * (tmp32 + tmp33);
tmp45 = tmp43 - tmp44;
tmp49 = tmp43 + tmp44;
tmp46 = K707106781 * (tmp24 - tmp29);
tmp48 = tmp46 + tmp47;
tmp50 = tmp47 - tmp46;
X[3 * iostride] = (K1_662939224 * tmp45) - (K1_111140466 * tmp48);
X[11 * iostride] = -((K1_111140466 * tmp45) + (K1_662939224 * tmp48));
X[7 * iostride] = (K390180644 * tmp49) - (K1_961570560 * tmp50);
X[15 * iostride] = -((K1_961570560 * tmp49) + (K390180644 * tmp50));
}
{
fftw_real tmp31;
fftw_real tmp41;
fftw_real tmp40;
fftw_real tmp42;
fftw_real tmp30;
fftw_real tmp34;
ASSERT_ALIGNED_DOUBLE;
tmp30 = K707106781 * (tmp24 + tmp29);
tmp31 = tmp19 + tmp30;
tmp41 = tmp19 - tmp30;
tmp34 = K707106781 * (tmp32 - tmp33);
tmp40 = tmp34 + tmp39;
tmp42 = tmp39 - tmp34;
X[iostride] = (K1_961570560 * tmp31) - (K390180644 * tmp40);
X[9 * iostride] = -((K390180644 * tmp31) + (K1_961570560 * tmp40));
X[5 * iostride] = (K1_111140466 * tmp41) - (K1_662939224 * tmp42);
X[13 * iostride] = -((K1_662939224 * tmp41) + (K1_111140466 * tmp42));
}
}
}
static const int twiddle_order[] =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
fftw_codelet_desc fftw_hc2hc_backward_16_desc =
{
"fftw_hc2hc_backward_16",
(void (*)()) fftw_hc2hc_backward_16,
16,
FFTW_BACKWARD,
FFTW_HC2HC,
366,
15,
twiddle_order,
};
| {
"alphanum_fraction": 0.5712578638,
"avg_line_length": 29.1228249744,
"ext": "c",
"hexsha": "9d65fa1e7f5442f7463eff4903cebda6bed53f85",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z",
"max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "albertsgrc/ftdock-opt",
"max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_16.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "albertsgrc/ftdock-opt",
"max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_16.c",
"max_line_length": 126,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "albertsgrc/ftdock-opt",
"max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_16.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z",
"num_tokens": 9029,
"size": 28453
} |
#pragma once
#include <initializer_list>
#include <list>
#include <vector>
#include <gsl/gsl_complex.h>
#include "Expression.h"
class TupleExpression: public Expression {
std::vector<expression> data;
TupleExpression();
TupleExpression(std::vector<expression>&& tuple);
TupleExpression(std::list<expression>& tuple);
TupleExpression(std::initializer_list<expression> tuple);
TupleExpression(std::initializer_list<double> tuple);
TupleExpression(std::initializer_list<gsl_complex> tuple);
public:
static expression construct();
static expression construct(std::vector<expression>&& tuple);
static expression construct(std::list<expression>& tuple);
static expression construct(std::initializer_list<expression> tuple);
static expression construct(std::initializer_list<double> tuple);
static expression construct(std::initializer_list<gsl_complex> tuple);
expression simplify() override;
expression derivative(const std::string& var) override;
expression integrate(const std::string& var) override;
expression at(const int index) override;
size_t size() const override;
expression apply(TransformerFunction f) override;
EXPRESSION_OVERRIDES
};
| {
"alphanum_fraction": 0.7172734314,
"avg_line_length": 30.7380952381,
"ext": "h",
"hexsha": "698312616d74acde6ad4897559c783cb879394fb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoniojkim/CalcPlusPlus",
"max_forks_repo_path": "MathEngine/Expressions/TupleExpression.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "antoniojkim/CalcPlusPlus",
"max_issues_repo_path": "MathEngine/Expressions/TupleExpression.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoniojkim/CalcPlusPlus",
"max_stars_repo_path": "MathEngine/Expressions/TupleExpression.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 246,
"size": 1291
} |
// @Copyright 2007 Kristjan Haule
//
#include <cstdio>
#include <cstdlib>
#include <gsl/gsl_rng.h>
#include <map>
class RanGSL{
const gsl_rng_type *T;
gsl_rng *r;
public:
RanGSL(int idum)
{
gsl_rng_env_setup();
// T = gsl_rng_default;
// T = gsl_rng_taus;
T = gsl_rng_ranlux389;
r = gsl_rng_alloc (T);
gsl_rng_set(r, idum);
}
double operator()()
{ return gsl_rng_uniform (r);}
~RanGSL()
{gsl_rng_free (r);}
};
class dRand48{
public:
dRand48(int idum){srand48(idum);}
double operator()(){
return drand48();
}
};
class Ran0{
long idum;
public:
Ran0(long idum_): idum(idum_){};
double operator()(){
// Minimal random number generator of Park and Miller. Returns a uniform random deviate
// between 0.0 and 1.0. Set or reset idum to any integer value (except the unlikely value MASK)
// to initialize the sequence; idum must not be altered between calls for successive deviates in
// a sequence.
static const int IA=16807;
static const int IM=2147483647;
static const double AM=(1.0/IM);
static const int IQ=127773;
static const int IR=2836;
static const int MASK=123459876;
static long idum;
long k;
float ans;
idum ^= MASK; //XORing with MASK allows use of zero and other simple bit patterns for idum.
k=idum/IQ;
idum = IA*(idum-k*IQ)-IR*k; // Compute idum=(IA*idum) % IM without over
if (idum < 0) idum += IM; // flows by Schrages method.
ans=AM*idum; // Convert idum to a floating result.
idum ^= MASK; // Unmask before return.
return ans;
}
};
| {
"alphanum_fraction": 0.6501877347,
"avg_line_length": 24.96875,
"ext": "h",
"hexsha": "be0edc686d704902cc5f75504cca51c5d22bfc8c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2016-08-02T15:05:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-22T15:46:56.000Z",
"max_forks_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "dmft-wien2k/dmft-wien2k",
"max_forks_repo_path": "src/impurity/ctqmc/random.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487",
"max_issues_repo_issues_event_max_datetime": "2016-07-12T21:42:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-07-12T21:37:53.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "dmft-wien2k/dmft-wien2k-v2",
"max_issues_repo_path": "src/impurity/ctqmc/random.h",
"max_line_length": 100,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "dmft-wien2k/dmft-wien2k-v2",
"max_stars_repo_path": "src/impurity/ctqmc/random.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-18T10:08:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-13T13:04:26.000Z",
"num_tokens": 485,
"size": 1598
} |
#ifndef libceed_solids_examples_setup_dm_h
#define libceed_solids_examples_setup_dm_h
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscfe.h>
#include "../include/structs.h"
// -----------------------------------------------------------------------------
// Setup DM
// -----------------------------------------------------------------------------
PetscErrorCode CreateBCLabel(DM dm, const char name[]);
// Read mesh and distribute DM in parallel
PetscErrorCode CreateDistributedDM(MPI_Comm comm, AppCtx app_ctx, DM *dm);
// Setup DM with FE space of appropriate degree
PetscErrorCode SetupDMByDegree(DM dm, AppCtx app_ctx, PetscInt order,
PetscBool boundary, PetscInt num_comp_u);
#endif // libceed_solids_examples_setup_dm_h
| {
"alphanum_fraction": 0.6037974684,
"avg_line_length": 34.347826087,
"ext": "h",
"hexsha": "afc9589eb9ea5ee9ea131c2d30ff62a9b9b26b76",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wence-/libCEED",
"max_forks_repo_path": "examples/solids/include/setup-dm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "wence-/libCEED",
"max_issues_repo_path": "examples/solids/include/setup-dm.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wence-/libCEED",
"max_stars_repo_path": "examples/solids/include/setup-dm.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 158,
"size": 790
} |
/**
*
* @file dtile.c
*
* PLASMA auxiliary routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Jakub Kurzak
* @author Mathieu Faverge
* @date 2010-11-15
* @generated d Tue Jan 7 11:45:15 2014
*
**/
#include "common.h"
#ifdef USE_MKL
#include <mkl_lapacke.h>
#else
#include <lapacke.h>
#endif
#include "auxiliary.h"
#include "tile.h"
/*#include "quark.h"*/
#define AF77(m, n) &(Af77[ ((int64_t)A.nb*(int64_t)lda*(int64_t)(n)) + (int64_t)(A.mb*(m)) ])
#define ABDL(m, n) BLKADDR(A, double, m, n)
/***************************************************************************//**
* Conversion from LAPACK F77 matrix layout to tile layout - dynamic scheduling
**/
void plasma_pdtile_to_lapack_quark(PLASMA_desc A, double *Af77, int lda)
{
double *f77;
double *bdl;
int X1, Y1;
int X2, Y2;
int n, m, ldt;
for (m = 0; m < A.mt; m++)
{
ldt = BLKLDD(A, m);
for (n = 0; n < A.nt; n++)
{
X1 = n == 0 ? A.j%A.nb : 0;
Y1 = m == 0 ? A.i%A.mb : 0;
X2 = n == A.nt-1 ? (A.j+A.n-1)%A.nb+1 : A.nb;
Y2 = m == A.mt-1 ? (A.i+A.m-1)%A.mb+1 : A.mb;
f77 = AF77(m, n);
bdl = ABDL(m, n);
LAPACKE_dlacpy_work(
LAPACK_COL_MAJOR,
lapack_const(PlasmaUpperLower),
(Y2-Y1), (X2-X1),
&(bdl[X1*lda+Y1]), ldt,
&(f77[X1*lda+Y1]), lda);
}
}
}
| {
"alphanum_fraction": 0.4971246006,
"avg_line_length": 26.0833333333,
"ext": "c",
"hexsha": "01724336f3f26cabd91c02d9fa5f0f4b7a805d55",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z",
"max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "tianyi93/hpxMP_mirror",
"max_forks_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/pdtile.c",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "tianyi93/hpxMP_mirror",
"max_issues_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/pdtile.c",
"max_line_length": 93,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "tianyi93/hpxMP_mirror",
"max_stars_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/pdtile.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z",
"num_tokens": 535,
"size": 1565
} |
#pragma once
#include "Cesium3DTilesReader/Library.h"
#include <Cesium3DTiles/Subtree.h>
#include <CesiumJsonReader/ExtensionReaderContext.h>
#include <gsl/span>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
namespace Cesium3DTilesReader {
/**
* @brief The result of reading a subtree with
* {@link SubtreeReader::readSubtree}.
*/
struct CESIUM3DTILESREADER_API SubtreeReaderResult {
/**
* @brief The read subtree, or std::nullopt if the subtree could not be read.
*/
std::optional<Cesium3DTiles::Subtree> subtree;
/**
* @brief Errors, if any, that occurred during the load process.
*/
std::vector<std::string> errors;
/**
* @brief Warnings, if any, that occurred during the load process.
*/
std::vector<std::string> warnings;
};
/**
* @brief Reads subtrees.
*/
class CESIUM3DTILESREADER_API SubtreeReader {
public:
/**
* @brief Constructs a new instance.
*/
SubtreeReader();
/**
* @brief Gets the context used to control how extensions are loaded from a
* subtree.
*/
CesiumJsonReader::ExtensionReaderContext& getExtensions();
/**
* @brief Gets the context used to control how extensions are loaded from a
* subtree.
*/
const CesiumJsonReader::ExtensionReaderContext& getExtensions() const;
/**
* @brief Reads a subtree.
*
* @param data The buffer from which to read the subtree.
* @param options Options for how to read the subtree.
* @return The result of reading the subtree.
*/
SubtreeReaderResult readSubtree(const gsl::span<const std::byte>& data) const;
private:
CesiumJsonReader::ExtensionReaderContext _context;
};
} // namespace Cesium3DTilesReader
| {
"alphanum_fraction": 0.7075688073,
"avg_line_length": 22.9473684211,
"ext": "h",
"hexsha": "1f1d2f64aea0e4ca0464560e43e9fd5fccedd0bb",
"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": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "yieryi/cesium-native",
"max_forks_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/SubtreeReader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"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": "yieryi/cesium-native",
"max_issues_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/SubtreeReader.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "yieryi/cesium-native",
"max_stars_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/SubtreeReader.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 438,
"size": 1744
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//------------------------------------------------------------------------------
// KeypointSpatialIndex.h
//
// Allows to construction, query, and removal of Keypoint entries based on pixel position.
//------------------------------------------------------------------------------
#pragma once
#include "Utils\thread_memory.h"
#include <memory>
#include <vector>
#include <functional>
#include <opencv2\features2d\features2d.hpp>
#include <gsl/span>
namespace mage
{
class KeypointSpatialIndex
{
struct Impl;
public:
KeypointSpatialIndex(gsl::span<const cv::KeyPoint> keypoints);
void Query(const cv::Point2f& center, int octave, float radius, temp::vector<size_t>& results) const;
void Remove(const cv::KeyPoint& keypoint, size_t value);
~KeypointSpatialIndex();
private:
static constexpr float octaveSpacing = 100;
static constexpr float octaveQueryRange = 1;
std::unique_ptr<Impl> m_impl;
};
} | {
"alphanum_fraction": 0.5885660731,
"avg_line_length": 26.0243902439,
"ext": "h",
"hexsha": "5fb2dede7cf71e201f4ec63c60cb01954058623e",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Core/MAGESLAM/Source/Image/KeypointSpatialIndex.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Core/MAGESLAM/Source/Image/KeypointSpatialIndex.h",
"max_line_length": 109,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Core/MAGESLAM/Source/Image/KeypointSpatialIndex.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 217,
"size": 1067
} |
// Alessandro Casalino
//
// Compile with (Mac with default homebrew gsl 2.6) gcc-9 -O2 quintessence_evolve.c -o quintessence_evolve.exe -L/usr/local/Cellar/gsl/2.6/lib -I/usr/local/Cellar/gsl/2.6/include -lgsl
// Run with ./quintessence_evolve.exe
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
// PHYSICAL PARAMETERS VALUES
// INITIAL CONDITIONS
// Initial value of the scale factor
double a_init = 1e-15;
// Final value of the scale factor
double a_end = 1.1;
// Values of fractional density for the cosmological matter today
double Omega_rad_0 = 8e-5;
double Omega_b_0 = 0.0486;
double Omega_Lambda_0 = 0.;//0.6911;
double Omega_cdm_0 = 0.2589;
// Physical constants for output conversions
double _G_ = 6.67428e-11; /**< Newton constant in m^3/Kg/s^2 */
double _MPc_over_m_ = 3.085677581282e22; // Conversion factor from Mpc to m
double _Gyr_over_Mpc_ = 3.06601394e2; // Conversion factor from Gyr to Mpc
double _c_ = 2.99792458e8; // Speed of light in m/s
double _H0_ = 67.74; // H0 of LCDM in Km/s/Mpc
double fourpiG = 1.;
double T_CONF = 1.;
// COMPUTATION PARAMETERS VALUES
// Number of points used in the computation
int points = (int) 1e6;
// Raise this value to make the csv file smaller, but decreasing resolution
// The value inserted is the ratio between the number of values written in a full resolution file / decreased resolution file
int csv_resolution = 10;
double delta_bisection = 1e-2;
double mg_field_init_min = 1e-20;
double mg_field_init_max = 2e1; //1e16 max for LCDM (model 1)
// QUINTESSENCE PARAMETERS
// Initial value of the quintessence velocity (phi derivated with respect to tau)
double mg_field_p_bk_0 = 0.;
// TEST MODE
// Provides some informations on the terminal and the .csv file during the computation (1: on, others: off)
int TEST_MODE = 1;
// Definition of the POTENTIAL
// For a list of the models see above
double mg_pot(const double mg_field_bk) {
return mg_field_bk * mg_field_bk / 2.;
}
double mg_pot_p(const double mg_field_bk) {
return mg_field_bk;
}
// Definitions of DIFFERENTIAL EQUATION system
// Need to have first order equations to use Runge Kutta
//
double a_p_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
return a_p;
}
double a_pp_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
double a3 = a * a * a;
double rhoa3 = (Omega_cdm_0 + Omega_b_0) + (Omega_Lambda_0 * a3) + (Omega_rad_0 / a);
double Pa3 = - (Omega_Lambda_0 * a3) + 1./3. * (Omega_rad_0 / a );
return fourpiG / 3. * ( (rhoa3 - 3. * Pa3) - a * mg_field_p_bk * mg_field_p_bk + 4. * a3 * mg_pot(mg_field_bk) );
}
double mg_field_bk_p_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
return mg_field_p_bk;
}
double mg_field_bk_pp_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
return - 2. * a_p/a * mg_field_p_bk - mg_pot_p(mg_field_bk) * a * a;
}
double Hconf(const double a, const double mg_field_bk, const double mg_field_p_bk)
{
return sqrt((2. * fourpiG / 3.) * ( ((Omega_cdm_0 + Omega_b_0) / a) + (Omega_Lambda_0 * a * a) + (Omega_rad_0 / a / a) + (mg_field_p_bk * mg_field_p_bk / 2.) + (a * a * mg_pot(mg_field_bk)) ));
}
// Integrand for the particle horizon integral
double particleHorizonIntegrand(double a, double mg_field_bk, double mg_field_p_bk)
{
//return 2. / (sqrt(a) * Hconf(a, mg_field_bk, mg_field_p_bk));
return 1. / ( a * Hconf(a, mg_field_bk, mg_field_p_bk) );
}
// Particle horizon integral step
double particleHorizon(const int i, double * a, double * mg_field_bk, double * mg_field_p_bk) {
double h = a[i]-a[i-1];
double fa = particleHorizonIntegrand(a[i-1],mg_field_bk[i-1],mg_field_p_bk[i-1]);
double fb = particleHorizonIntegrand(a[i],mg_field_bk[i],mg_field_p_bk[i]);
return h*(fa+fb)/2.;
}
// Function used to print results stored in vectors as a csv file
void csv(double * t, double * a, double * a_p, double * mg_field_bk, double * mg_field_p_bk, double * particleHorizonVec, char * filename) {
FILE *fp;
fp = fopen (filename, "w+");
fprintf(fp, "%s, %s, %s, %s, %s, %s, %s, %s", "t", "a(t)", "H(t)/H0", "H_prime(t)/H0^2", "Omega_df", "Omega_r", "Omega_b", "Omega_cdm");
fprintf(fp, ", %s", "omega_df");
fprintf(fp, ", %s", "PH"); // Particle horizon
fprintf(fp, ", %s", "mg_field");
fprintf(fp, ", %s", "mg_field_p");
if(TEST_MODE==1) fprintf(fp, ", %s", "H_check(t)/H0");
fprintf(fp, "\n");
// Time conversion factor
// double tcf = 1./_H0_/(60.*60.*24.*365.*1e9)*_MPc_over_m_/1000.;
int i = 0;
double particleHorizonRes = 0.;
for(i=1;i<points;i++){
particleHorizonRes += particleHorizon(i,a,mg_field_bk,mg_field_p_bk);
particleHorizonVec[i] = particleHorizonRes;
}
i = 0;
double H_test, H_cosmo = 0.;
while( a[i] <= a_end){
double H = Hconf(a[i],mg_field_bk[i],mg_field_p_bk[i]); // this is the Hubble constant with conformal time
double H_cosmo = H / a[i];
double H_prime = 1. / a[i] * a_pp_rk4(a[i], a_p[i], mg_field_bk[i], mg_field_p_bk[i]) - H * H; // this is Hubble prime with conformal time
if(T_CONF==0) H_prime = ( H_prime - H * H )/a[i]/a[i]; // this is Hubble prime with cosmological time
if(T_CONF==0) H = H_cosmo; // this it the Hubble constant with cosmological time
fprintf(fp, "%e, %e, %e, %e, %e, %e, %e, %e", t[i], a[i], H / sqrt(2. * fourpiG / 3.), H_prime / sqrt(2. * fourpiG / 3.) / sqrt(2. * fourpiG / 3.), 2. * fourpiG / 3. * ( (mg_field_p_bk[i] * mg_field_p_bk[i] / 2.) + (a[i] * a[i] * mg_pot(mg_field_bk[i])) ) /H_cosmo /H_cosmo , 2. * fourpiG / 3. * Omega_rad_0 /a[i] /a[i] /a[i] /a[i] /H_cosmo / H_cosmo , 2. * fourpiG / 3. * Omega_b_0 /a[i] /a[i] /a[i] /H_cosmo / H_cosmo , 2. * fourpiG / 3. * Omega_cdm_0 /a[i] /a[i] /a[i] /H_cosmo / H_cosmo );
fprintf(fp, ", %e", (-mg_pot(mg_field_bk[i])+mg_field_p_bk[i]*mg_field_p_bk[i]/2./a[i]/a[i])/(mg_pot(mg_field_bk[i])+mg_field_p_bk[i]*mg_field_p_bk[i]/2./a[i]/a[i]));
fprintf(fp, ", %e", particleHorizonVec[i]);
fprintf(fp, ", %e", mg_field_bk[i]);
fprintf(fp, ", %e", mg_field_p_bk[i]);
if(TEST_MODE==1){
H_test = a_p[i]/a[i];
if(T_CONF==0) H_test = H_test / a[i];
fprintf(fp, ", %e", H_test / sqrt(2. * fourpiG / 3.));
}
fprintf(fp, "\n");
if(a[i+csv_resolution]<= a_end){
i=i+csv_resolution;
}
else{
i++;
}
}
fclose(fp);
}
int scan_for_a0 (double * a) {
int i=0;
for(i=0; a[i] <= a_end; i++);
return i;
}
// This divides an interval in a logarithmic scale of basis 10, and store results in input vector v
void logscale10 (double * v, double A, double B, int points){
int i;
double a = log10(A);
double b = log10(B);
double h = (b - a) / (points-1.0);
for(i=0;i<points;i++){
v[i] = pow(10.0, a + i * h);
}
}
// This function is a temporal step of the Runge-Kutta 4 method:
// evolves the system for a time equal to dtau (h in the program)
void mg_rungekutta4bg(double * f, const double dtau)
{
double k_F[4], k_A[4], k_rhof[4], k_rhor[4], k_rhob[4];
double a = f[1];
double a_p = f[2];
double mg_field_bk = f[3];
double mg_field_p_bk = f[4];
double k1a, k2a, k3a, k4a;
double k1ap, k2ap, k3ap, k4ap;
double k1f, k2f, k3f, k4f;
double k1fp, k2fp, k3fp, k4fp;
k1a = a_p_rk4(a, a_p, mg_field_bk, mg_field_p_bk);
k1ap = a_pp_rk4(a, a_p, mg_field_bk, mg_field_p_bk);
k1f = mg_field_bk_p_rk4(a, a_p, mg_field_bk, mg_field_p_bk);
k1fp = mg_field_bk_pp_rk4(a, a_p, mg_field_bk, mg_field_p_bk);
k2a = a_p_rk4(a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k2ap = a_pp_rk4(a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k2f = mg_field_bk_p_rk4(a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k2fp = mg_field_bk_pp_rk4(a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k3a = a_p_rk4(a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k3ap = a_pp_rk4(a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k3f = mg_field_bk_p_rk4(a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k3fp = mg_field_bk_pp_rk4(a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k4a = a_p_rk4(a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
k4ap = a_pp_rk4(a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
k4f = mg_field_bk_p_rk4(a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
k4fp = mg_field_bk_pp_rk4(a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
f[1] += dtau * (k1a + 2. * k2a + 2. * k3a + k4a) / 6.;
f[2] += dtau * (k1ap + 2. * k2ap + 2. * k3ap + k4ap) / 6.;
f[3] += dtau * (k1f + 2. * k2f + 2. * k3f + k4f) / 6.;
f[4] += dtau * (k1fp + 2. * k2fp + 2. * k3fp + k4fp) / 6.;
}
// This function evolves the system with the Runge-Kutta 4 method until t_stop
double rk4(double * t, double * a, double * a_p, double * mg_field_bk, double * mg_field_p_bk, double Omega_f_0) {
double f[5];
int i = 0;
// Call the function for a logarithmic scale of time
// We don't start from t = 0 to avoid problems with quintessence potentials
logscale10(t,1e-9,20.,points);
while( i < points - 1 ){
f[0] = t[i];
f[1] = a[i];
f[2] = a_p[i];
f[3] = mg_field_bk[i];
f[4] = mg_field_p_bk[i];
mg_rungekutta4bg(f, t[i+1]-t[i]);
a[i+1] = f[1];
a_p[i+1] = f[2];
mg_field_bk[i+1] = f[3];
mg_field_p_bk[i+1] = f[4];
i++;
}
int j = scan_for_a0(a);
double H = Hconf(a[j], mg_field_bk[j], mg_field_p_bk[j]);
double Omega_f = (2. * fourpiG / 3.) * ( (mg_field_p_bk[j] * mg_field_p_bk[j] / 2.) + (a[j] * a[j] * mg_pot(mg_field_bk[j])) ) /H /H;
return Omega_f - Omega_f_0;
}
double bisection (double min, double max, double * t, double * a, double * a_p, double * mg_field_bk, double * mg_field_p_bk, const double Omega_f_0) {
double C = (min+max) / 2.;
while(fabs((max-min)/min)>delta_bisection){
a_p[0] = a_init * Hconf(a[0], mg_field_init_min, mg_field_p_bk[0]);
mg_field_bk[0] = min;
double rk4_min = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
a_p[0] = a_init * Hconf(a[0], C, mg_field_p_bk[0]);
mg_field_bk[0] = C;
double rk4_C = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
if(rk4_min*rk4_C>=0) {
min=C;
}
else {
max=C;
}
C=(max+min)/2.;
if (TEST_MODE == 1) printf("TEST_MODE ON - min: %e , max: %e, C: %e, rk4_min: %e , rk4_C: %e \n", min, max, C, rk4_min, rk4_C);
}
double result = (max+min)/2.;
if(TEST_MODE==1) printf("\n");
printf("\t-> Result of bisection method is mg_field_bk: %e (internal units).\n", result);
//if(TEST_MODE==1) printf("\t--> Confront with LCDM value: %e (internal units).\n", (2. * fourpiG / 3.) * ( Omega_Lambda_0 + 6. * OmegaCDM_0 )/ pow(a_init,3.));
return result;
}
int main() {
double Omega_f_0 = 1. - Omega_Lambda_0 - Omega_rad_0 - Omega_b_0 - Omega_cdm_0;
int i = 0;
printf("\n\t\t----------------------------------------\n\n");
// Definition of the vector needed for the evolution functions
double * t; double * a; double * a_p; double * mg_field_bk; double * mg_field_p_bk; double * particleHorizonVec;
t = (double *) malloc(sizeof(double) * points);
a = (double *) malloc(sizeof(double) * points);
a_p = (double *) malloc(sizeof(double) * points);
mg_field_bk = (double *) malloc(sizeof(double) * points);
mg_field_p_bk = (double *) malloc(sizeof(double) * points);
particleHorizonVec = (double *) malloc(sizeof(double) * points);
if(!t||!a||!a_p||!mg_field_bk||!mg_field_p_bk||!particleHorizonVec){
printf("Error! The memory cannot be allocated. The program will be terminated.\n");
exit(1);
}
// Initial conditions (tau=0)
a[0] = a_init;
mg_field_p_bk[0] = mg_field_p_bk_0;
printf(" Searching for best initial value for the dark fluid ... \n \n");
mg_field_bk[0] = bisection(mg_field_init_min, mg_field_init_max, t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
a_p[0] = a_init * Hconf(a_init, mg_field_bk[0], mg_field_p_bk[0]);
printf("\n\n Evolving the system ...\n");
rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
char filename[50];
sprintf (filename, "mg_bk.csv");
int last_int = scan_for_a0(a);
printf("\n RESULTS:\n");
printf("\t-> H0: %f \n", a_p[last_int]/a[last_int]/sqrt(2. * fourpiG / 3.));
printf("\t-> number of points %d \n", last_int);
//printf("\t-> Age of the Universe: %f Gyr\n", t[last_int] /_H0_/(60.*60.*24.*365.*1e9)*_MPc_over_m_/1000.);
csv(t, a, a_p, mg_field_bk, mg_field_p_bk, particleHorizonVec, filename);
printf("\n The results are saved in '.csv' files. The name is labelled with the value of c, and the model (m).\n");
if(TEST_MODE==1) printf("\n TEST_MODE ON: check the values of H in .csv file. They must be equal!");
printf("\n\t\t----------------------------------------\n");
double * a_int; double * a_p_int; double * mg_field_bk_int; double * mg_field_p_bk_int; double * particleHorizonVec_int;
a_int = (double *) malloc(sizeof(double) * last_int);
a_p_int = (double *) malloc(sizeof(double) * last_int);
mg_field_bk_int = (double *) malloc(sizeof(double) * last_int);
mg_field_p_bk_int = (double *) malloc(sizeof(double) * last_int);
particleHorizonVec_int = (double *) malloc(sizeof(double) * last_int);
if(!a_int||!a_p_int||!mg_field_bk_int||!mg_field_p_bk_int||!particleHorizonVec_int){
printf("Error! The memory cannot be allocated. The program will be terminated.\n");
exit(1);
}
memcpy(a_int, a, last_int * sizeof(double));
memcpy(a_p_int, a_p, last_int * sizeof(double));
memcpy(mg_field_bk_int, mg_field_bk, last_int * sizeof(double));
memcpy(mg_field_p_bk_int, mg_field_p_bk, last_int * sizeof(double));
memcpy(particleHorizonVec_int, particleHorizonVec, last_int * sizeof(double));
free(a);free(a_p);free(mg_field_bk);free(mg_field_p_bk);free(particleHorizonVec);
// Spline interpolation with gsl
gsl_interp_accel *acc_mg_field = gsl_interp_accel_alloc();
gsl_spline * spline_mg_field = gsl_spline_alloc(gsl_interp_cspline,last_int);
gsl_interp_accel *acc_mg_field_p = gsl_interp_accel_alloc();
gsl_spline * spline_mg_field_p = gsl_spline_alloc(gsl_interp_cspline,last_int);
gsl_interp_accel *acc_a_p = gsl_interp_accel_alloc();
gsl_spline * spline_a_p = gsl_spline_alloc(gsl_interp_cspline,last_int);
gsl_interp_accel *acc_particleHorizon = gsl_interp_accel_alloc();
gsl_spline * spline_particleHorizon = gsl_spline_alloc(gsl_interp_cspline,last_int);
gsl_spline_init(spline_mg_field,a_int,mg_field_bk_int,last_int);
gsl_spline_init(spline_mg_field_p,a_int,mg_field_p_bk_int,last_int);
gsl_spline_init(spline_a_p,a_int,a_p_int,last_int);
gsl_spline_init(spline_particleHorizon,a_int,particleHorizonVec_int,last_int);
double a_eval = 1e-2;
printf("spline eval: %e %e \n",a_eval,gsl_spline_eval(spline_mg_field,a_eval,acc_mg_field));
printf("spline eval: %e %e \n",a_eval,gsl_spline_eval(spline_mg_field_p,a_eval,acc_mg_field_p));
printf("spline eval: %e %e \n",a_eval,gsl_spline_eval(spline_a_p,a_eval,acc_a_p));
printf("spline eval: %e %e \n",a_eval,gsl_spline_eval(spline_particleHorizon,a_eval,acc_particleHorizon));
printf("%d %e \n",last_int, particleHorizonVec_int[gsl_interp_bsearch(a_int,a_eval,0,last_int-1)]);
gsl_spline_free(spline_mg_field);gsl_interp_accel_free(acc_mg_field);
gsl_spline_free(spline_mg_field_p);gsl_interp_accel_free(acc_mg_field_p);
gsl_spline_free(spline_a_p);gsl_interp_accel_free(acc_a_p);
gsl_spline_free(spline_particleHorizon);gsl_interp_accel_free(acc_particleHorizon);
free(t);free(a_int);free(a_p_int);free(mg_field_bk_int);free(mg_field_p_bk_int);free(particleHorizonVec_int);
printf("\n");
exit(0);
}
| {
"alphanum_fraction": 0.6480813575,
"avg_line_length": 39.0600461894,
"ext": "c",
"hexsha": "ed6dd0dd26ff4952ed73de96ca5e732d293e3359",
"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": "97dd3f4320f0c61eccae387d5fd945336084e863",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alessandrocasalino/mgevolution",
"max_forks_repo_path": "mg/quintessence_evolve.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "97dd3f4320f0c61eccae387d5fd945336084e863",
"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": "alessandrocasalino/mgevolution",
"max_issues_repo_path": "mg/quintessence_evolve.c",
"max_line_length": 502,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "97dd3f4320f0c61eccae387d5fd945336084e863",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alessandrocasalino/mgevolution",
"max_stars_repo_path": "mg/quintessence_evolve.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5981,
"size": 16913
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <memory>
#include <vector>
#include <gsl/span>
#include <map>
#include <Eigen/Geometry>
namespace mage
{
struct BundlerParameters
{
bool ArePointsFixed{ false }; // True if map points should not be optimized
};
class BundlerLib
{
public:
BundlerLib(const BundlerParameters& bundlerParameters);
~BundlerLib();
void AllocateCameras(size_t count);
void SetCameraPose(size_t idx,
Eigen::Map<const Eigen::Vector3f> position,
Eigen::Map<const Eigen::Matrix3f> orientation,
Eigen::Map<const Eigen::Vector4f> intrinsics, bool isFixed);
void FixCameraPose(size_t idx, bool value);
void AllocateMapPoints(size_t count);
void SetMapPoint(size_t idx, Eigen::Map<const Eigen::Vector3f> point);
void AllocateObservations(size_t count);
void SetObservation(size_t idx, Eigen::Map<const Eigen::Vector2f> position, size_t cameraIndex, size_t mapPointIndex, float informationMatrixScalar);
void AllocateFixedDistanceConstraints(size_t count);
void SetFixedDistanceConstraint(size_t idx, size_t cameraIndex1, size_t cameraIndex2, float distance = 1.0f, float weight = 1.0f);
void AllocateRelativeRotationConstraints(size_t count);
void SetRelativeRotationConstraint(size_t idx, size_t cameraIndex1, size_t cameraIndex2, const Eigen::Quaternionf& deltaRotation, float weight = 1.0f);
void AllocateRelativeTransformConstraints(size_t count);
void SetRelativeTransformConstraint(size_t idx, size_t cameraIndex1, size_t cameraIndex2, Eigen::Map<const Eigen::Vector3f> deltaPosition, const Eigen::Quaternionf& deltaRotation, float weight);
void SetCurrentLambda(float userLambda);
float GetCurrentLambda() const;
// Runs an iteration of the solver for each provided Huber width.
// Return the average square error.
float StepBundleAdjustment(gsl::span<const float> huberWidthPerIteration, float maxErrorSquare, std::vector<unsigned int>& outliers);
void GetPose(size_t idx, Eigen::Map<Eigen::Vector3f> position, Eigen::Map<Eigen::Matrix3f> orientation) const;
void GetPoint(size_t idx, Eigen::Map<Eigen::Vector3f> position) const;
private:
struct Impl;
const std::unique_ptr<Impl> m_impl;
// Description of the problem to optimize from the calling code.
BundlerParameters m_bundlerParameters;
};
}
| {
"alphanum_fraction": 0.7091402014,
"avg_line_length": 37.9705882353,
"ext": "h",
"hexsha": "0dfcc2b51c6399aa2562f675eec1d0695d928764",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Dependencies/BundlerLib/Include/BundlerLib.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Dependencies/BundlerLib/Include/BundlerLib.h",
"max_line_length": 202,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Dependencies/BundlerLib/Include/BundlerLib.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 584,
"size": 2582
} |
/*
MPCOTool:
The Multi-Purposes Calibration and Optimization Tool. A software to perform
calibrations or optimizations of empirical parameters.
AUTHORS: Javier Burguete and Borja Latorre.
Copyright 2012-2019, AUTHORS.
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 AUTHORS ``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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
/**
* \file interface.c
* \brief Source file to define the graphical interface functions.
* \authors Javier Burguete and Borja Latorre.
* \copyright Copyright 2012-2019, all rights reserved.
*/
#define _GNU_SOURCE
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <libxml/parser.h>
#include <libintl.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <json-glib/json-glib.h>
#ifdef G_OS_WIN32
#include <windows.h>
#endif
#if HAVE_MPI
#include <mpi.h>
#endif
#include <gio/gio.h>
#include <gtk/gtk.h>
#include "genetic/genetic.h"
#include "utils.h"
#include "experiment.h"
#include "variable.h"
#include "input.h"
#include "optimize.h"
#include "interface.h"
#define DEBUG_INTERFACE 0 ///< Macro to debug interface functions.
/**
* \def INPUT_FILE
* \brief Macro to define the initial input file.
*/
#ifdef G_OS_WIN32
#define INPUT_FILE "test-ga-win.xml"
#else
#define INPUT_FILE "test-ga.xml"
#endif
Window window[1];
///< Window struct to define the main interface window.
static const char *logo[] = {
"32 32 3 1",
" c None",
". c #0000FF",
"+ c #FF0000",
" ",
" ",
" ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . +++ . ",
" . . +++++ . ",
" . . +++++ . ",
" . . +++++ . ",
" +++ . +++ +++ ",
" +++++ . . +++++ ",
" +++++ . . +++++ ",
" +++++ . . +++++ ",
" +++ . . +++ ",
" . . . . ",
" . +++ . . ",
" . +++++ . . ",
" . +++++ . . ",
" . +++++ . . ",
" . +++ . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" ",
" ",
" "
}; ///< Logo pixmap.
/*
const char * logo[] = {
"32 32 3 1",
" c #FFFFFFFFFFFF",
". c #00000000FFFF",
"X c #FFFF00000000",
" ",
" ",
" ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . XXX . ",
" . . XXXXX . ",
" . . XXXXX . ",
" . . XXXXX . ",
" XXX . XXX XXX ",
" XXXXX . . XXXXX ",
" XXXXX . . XXXXX ",
" XXXXX . . XXXXX ",
" XXX . . XXX ",
" . . . . ",
" . XXX . . ",
" . XXXXX . . ",
" . XXXXX . . ",
" . XXXXX . . ",
" . XXX . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" . . . . ",
" ",
" ",
" "};
*/
static Options options[1];
///< Options struct to define the options dialog.
static Running running[1];
///< Running struct to define the running dialog.
/**
* Function to save the hill climbing method data in a XML node.
*/
static void
input_save_climbing_xml (xmlNode * node) ///< XML node.
{
#if DEBUG_INTERFACE
fprintf (stderr, "input_save_climbing_xml: start\n");
#endif
if (input->nsteps)
{
xml_node_set_uint (node, (const xmlChar *) LABEL_NSTEPS, input->nsteps);
if (input->relaxation != DEFAULT_RELAXATION)
xml_node_set_float (node, (const xmlChar *) LABEL_RELAXATION,
input->relaxation);
switch (input->climbing)
{
case CLIMBING_METHOD_COORDINATES:
xmlSetProp (node, (const xmlChar *) LABEL_CLIMBING,
(const xmlChar *) LABEL_COORDINATES);
break;
default:
xmlSetProp (node, (const xmlChar *) LABEL_CLIMBING,
(const xmlChar *) LABEL_RANDOM);
xml_node_set_uint (node, (const xmlChar *) LABEL_NESTIMATES,
input->nestimates);
}
}
#if DEBUG_INTERFACE
fprintf (stderr, "input_save_climbing_xml: end\n");
#endif
}
/**
* Function to save the hill climbing method data in a JSON node.
*/
static void
input_save_climbing_json (JsonNode * node) ///< JSON node.
{
JsonObject *object;
#if DEBUG_INTERFACE
fprintf (stderr, "input_save_climbing_json: start\n");
#endif
object = json_node_get_object (node);
if (input->nsteps)
{
json_object_set_uint (object, LABEL_NSTEPS, input->nsteps);
if (input->relaxation != DEFAULT_RELAXATION)
json_object_set_float (object, LABEL_RELAXATION, input->relaxation);
switch (input->climbing)
{
case CLIMBING_METHOD_COORDINATES:
json_object_set_string_member (object, LABEL_CLIMBING,
LABEL_COORDINATES);
break;
default:
json_object_set_string_member (object, LABEL_CLIMBING, LABEL_RANDOM);
json_object_set_uint (object, LABEL_NESTIMATES, input->nestimates);
}
}
#if DEBUG_INTERFACE
fprintf (stderr, "input_save_climbing_json: end\n");
#endif
}
/**
* Function to save the input file in XML format.
*/
static inline void
input_save_xml (xmlDoc * doc) ///< xmlDoc struct.
{
unsigned int i, j;
char *buffer;
xmlNode *node, *child;
GFile *file, *file2;
#if DEBUG_INTERFACE
fprintf (stderr, "input_save_xml: start\n");
#endif
// Setting root XML node
node = xmlNewDocNode (doc, 0, (const xmlChar *) LABEL_OPTIMIZE, 0);
xmlDocSetRootElement (doc, node);
// Adding properties to the root XML node
if (xmlStrcmp
((const xmlChar *) input->result, (const xmlChar *) result_name))
xmlSetProp (node, (const xmlChar *) LABEL_RESULT_FILE,
(xmlChar *) input->result);
if (xmlStrcmp
((const xmlChar *) input->variables, (const xmlChar *) variables_name))
xmlSetProp (node, (const xmlChar *) LABEL_VARIABLES_FILE,
(xmlChar *) input->variables);
file = g_file_new_for_path (input->directory);
file2 = g_file_new_for_path (input->simulator);
buffer = g_file_get_relative_path (file, file2);
g_object_unref (file2);
xmlSetProp (node, (const xmlChar *) LABEL_SIMULATOR, (xmlChar *) buffer);
g_free (buffer);
if (input->evaluator)
{
file2 = g_file_new_for_path (input->evaluator);
buffer = g_file_get_relative_path (file, file2);
g_object_unref (file2);
if (xmlStrlen ((xmlChar *) buffer))
xmlSetProp (node, (const xmlChar *) LABEL_EVALUATOR,
(xmlChar *) buffer);
g_free (buffer);
}
if (input->seed != DEFAULT_RANDOM_SEED)
xml_node_set_uint (node, (const xmlChar *) LABEL_SEED, input->seed);
// Setting the algorithm
buffer = (char *) g_slice_alloc (64);
switch (input->algorithm)
{
case ALGORITHM_MONTE_CARLO:
xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,
(const xmlChar *) LABEL_MONTE_CARLO);
snprintf (buffer, 64, "%u", input->nsimulations);
xmlSetProp (node, (const xmlChar *) LABEL_NSIMULATIONS,
(xmlChar *) buffer);
snprintf (buffer, 64, "%u", input->niterations);
xmlSetProp (node, (const xmlChar *) LABEL_NITERATIONS,
(xmlChar *) buffer);
snprintf (buffer, 64, "%.3lg", input->tolerance);
xmlSetProp (node, (const xmlChar *) LABEL_TOLERANCE, (xmlChar *) buffer);
snprintf (buffer, 64, "%u", input->nbest);
xmlSetProp (node, (const xmlChar *) LABEL_NBEST, (xmlChar *) buffer);
input_save_climbing_xml (node);
break;
case ALGORITHM_SWEEP:
xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,
(const xmlChar *) LABEL_SWEEP);
snprintf (buffer, 64, "%u", input->niterations);
xmlSetProp (node, (const xmlChar *) LABEL_NITERATIONS,
(xmlChar *) buffer);
snprintf (buffer, 64, "%.3lg", input->tolerance);
xmlSetProp (node, (const xmlChar *) LABEL_TOLERANCE, (xmlChar *) buffer);
snprintf (buffer, 64, "%u", input->nbest);
xmlSetProp (node, (const xmlChar *) LABEL_NBEST, (xmlChar *) buffer);
input_save_climbing_xml (node);
break;
case ALGORITHM_ORTHOGONAL:
xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,
(const xmlChar *) LABEL_ORTHOGONAL);
snprintf (buffer, 64, "%u", input->niterations);
xmlSetProp (node, (const xmlChar *) LABEL_NITERATIONS,
(xmlChar *) buffer);
snprintf (buffer, 64, "%.3lg", input->tolerance);
xmlSetProp (node, (const xmlChar *) LABEL_TOLERANCE, (xmlChar *) buffer);
snprintf (buffer, 64, "%u", input->nbest);
xmlSetProp (node, (const xmlChar *) LABEL_NBEST, (xmlChar *) buffer);
input_save_climbing_xml (node);
break;
default:
xmlSetProp (node, (const xmlChar *) LABEL_ALGORITHM,
(const xmlChar *) LABEL_GENETIC);
snprintf (buffer, 64, "%u", input->nsimulations);
xmlSetProp (node, (const xmlChar *) LABEL_NPOPULATION,
(xmlChar *) buffer);
snprintf (buffer, 64, "%u", input->niterations);
xmlSetProp (node, (const xmlChar *) LABEL_NGENERATIONS,
(xmlChar *) buffer);
snprintf (buffer, 64, "%.3lg", input->mutation_ratio);
xmlSetProp (node, (const xmlChar *) LABEL_MUTATION, (xmlChar *) buffer);
snprintf (buffer, 64, "%.3lg", input->reproduction_ratio);
xmlSetProp (node, (const xmlChar *) LABEL_REPRODUCTION,
(xmlChar *) buffer);
snprintf (buffer, 64, "%.3lg", input->adaptation_ratio);
xmlSetProp (node, (const xmlChar *) LABEL_ADAPTATION, (xmlChar *) buffer);
break;
}
g_slice_free1 (64, buffer);
if (input->threshold != 0.)
xml_node_set_float (node, (const xmlChar *) LABEL_THRESHOLD,
input->threshold);
// Setting the experimental data
for (i = 0; i < input->nexperiments; ++i)
{
child = xmlNewChild (node, 0, (const xmlChar *) LABEL_EXPERIMENT, 0);
xmlSetProp (child, (const xmlChar *) LABEL_NAME,
(xmlChar *) input->experiment[i].name);
if (input->experiment[i].weight != 1.)
xml_node_set_float (child, (const xmlChar *) LABEL_WEIGHT,
input->experiment[i].weight);
for (j = 0; j < input->experiment->ninputs; ++j)
xmlSetProp (child, (const xmlChar *) stencil[j],
(xmlChar *) input->experiment[i].stencil[j]);
}
// Setting the variables data
for (i = 0; i < input->nvariables; ++i)
{
child = xmlNewChild (node, 0, (const xmlChar *) LABEL_VARIABLE, 0);
xmlSetProp (child, (const xmlChar *) LABEL_NAME,
(xmlChar *) input->variable[i].name);
xml_node_set_float (child, (const xmlChar *) LABEL_MINIMUM,
input->variable[i].rangemin);
if (input->variable[i].rangeminabs != -G_MAXDOUBLE)
xml_node_set_float (child, (const xmlChar *) LABEL_ABSOLUTE_MINIMUM,
input->variable[i].rangeminabs);
xml_node_set_float (child, (const xmlChar *) LABEL_MAXIMUM,
input->variable[i].rangemax);
if (input->variable[i].rangemaxabs != G_MAXDOUBLE)
xml_node_set_float (child, (const xmlChar *) LABEL_ABSOLUTE_MAXIMUM,
input->variable[i].rangemaxabs);
if (input->variable[i].precision != DEFAULT_PRECISION)
xml_node_set_uint (child, (const xmlChar *) LABEL_PRECISION,
input->variable[i].precision);
if (input->algorithm == ALGORITHM_SWEEP
|| input->algorithm == ALGORITHM_ORTHOGONAL)
xml_node_set_uint (child, (const xmlChar *) LABEL_NSWEEPS,
input->variable[i].nsweeps);
else if (input->algorithm == ALGORITHM_GENETIC)
xml_node_set_uint (child, (const xmlChar *) LABEL_NBITS,
input->variable[i].nbits);
if (input->nsteps)
xml_node_set_float (child, (const xmlChar *) LABEL_STEP,
input->variable[i].step);
}
// Saving the error norm
switch (input->norm)
{
case ERROR_NORM_MAXIMUM:
xmlSetProp (node, (const xmlChar *) LABEL_NORM,
(const xmlChar *) LABEL_MAXIMUM);
break;
case ERROR_NORM_P:
xmlSetProp (node, (const xmlChar *) LABEL_NORM,
(const xmlChar *) LABEL_P);
xml_node_set_float (node, (const xmlChar *) LABEL_P, input->p);
break;
case ERROR_NORM_TAXICAB:
xmlSetProp (node, (const xmlChar *) LABEL_NORM,
(const xmlChar *) LABEL_TAXICAB);
}
#if DEBUG_INTERFACE
fprintf (stderr, "input_save: end\n");
#endif
}
/**
* Function to save the input file in JSON format.
*/
static inline void
input_save_json (JsonGenerator * generator) ///< JsonGenerator struct.
{
unsigned int i, j;
char *buffer;
JsonNode *node, *child;
JsonObject *object;
JsonArray *array;
GFile *file, *file2;
#if DEBUG_INTERFACE
fprintf (stderr, "input_save_json: start\n");
#endif
// Setting root JSON node
node = json_node_new (JSON_NODE_OBJECT);
object = json_node_get_object (node);
json_generator_set_root (generator, node);
// Adding properties to the root JSON node
if (strcmp (input->result, result_name))
json_object_set_string_member (object, LABEL_RESULT_FILE, input->result);
if (strcmp (input->variables, variables_name))
json_object_set_string_member (object, LABEL_VARIABLES_FILE,
input->variables);
file = g_file_new_for_path (input->directory);
file2 = g_file_new_for_path (input->simulator);
buffer = g_file_get_relative_path (file, file2);
g_object_unref (file2);
json_object_set_string_member (object, LABEL_SIMULATOR, buffer);
g_free (buffer);
if (input->evaluator)
{
file2 = g_file_new_for_path (input->evaluator);
buffer = g_file_get_relative_path (file, file2);
g_object_unref (file2);
if (strlen (buffer))
json_object_set_string_member (object, LABEL_EVALUATOR, buffer);
g_free (buffer);
}
if (input->seed != DEFAULT_RANDOM_SEED)
json_object_set_uint (object, LABEL_SEED, input->seed);
// Setting the algorithm
buffer = (char *) g_slice_alloc (64);
switch (input->algorithm)
{
case ALGORITHM_MONTE_CARLO:
json_object_set_string_member (object, LABEL_ALGORITHM,
LABEL_MONTE_CARLO);
snprintf (buffer, 64, "%u", input->nsimulations);
json_object_set_string_member (object, LABEL_NSIMULATIONS, buffer);
snprintf (buffer, 64, "%u", input->niterations);
json_object_set_string_member (object, LABEL_NITERATIONS, buffer);
snprintf (buffer, 64, "%.3lg", input->tolerance);
json_object_set_string_member (object, LABEL_TOLERANCE, buffer);
snprintf (buffer, 64, "%u", input->nbest);
json_object_set_string_member (object, LABEL_NBEST, buffer);
input_save_climbing_json (node);
break;
case ALGORITHM_SWEEP:
json_object_set_string_member (object, LABEL_ALGORITHM, LABEL_SWEEP);
snprintf (buffer, 64, "%u", input->niterations);
json_object_set_string_member (object, LABEL_NITERATIONS, buffer);
snprintf (buffer, 64, "%.3lg", input->tolerance);
json_object_set_string_member (object, LABEL_TOLERANCE, buffer);
snprintf (buffer, 64, "%u", input->nbest);
json_object_set_string_member (object, LABEL_NBEST, buffer);
input_save_climbing_json (node);
break;
case ALGORITHM_ORTHOGONAL:
json_object_set_string_member (object, LABEL_ALGORITHM, LABEL_ORTHOGONAL);
snprintf (buffer, 64, "%u", input->niterations);
json_object_set_string_member (object, LABEL_NITERATIONS, buffer);
snprintf (buffer, 64, "%.3lg", input->tolerance);
json_object_set_string_member (object, LABEL_TOLERANCE, buffer);
snprintf (buffer, 64, "%u", input->nbest);
json_object_set_string_member (object, LABEL_NBEST, buffer);
input_save_climbing_json (node);
break;
default:
json_object_set_string_member (object, LABEL_ALGORITHM, LABEL_GENETIC);
snprintf (buffer, 64, "%u", input->nsimulations);
json_object_set_string_member (object, LABEL_NPOPULATION, buffer);
snprintf (buffer, 64, "%u", input->niterations);
json_object_set_string_member (object, LABEL_NGENERATIONS, buffer);
snprintf (buffer, 64, "%.3lg", input->mutation_ratio);
json_object_set_string_member (object, LABEL_MUTATION, buffer);
snprintf (buffer, 64, "%.3lg", input->reproduction_ratio);
json_object_set_string_member (object, LABEL_REPRODUCTION, buffer);
snprintf (buffer, 64, "%.3lg", input->adaptation_ratio);
json_object_set_string_member (object, LABEL_ADAPTATION, buffer);
break;
}
g_slice_free1 (64, buffer);
if (input->threshold != 0.)
json_object_set_float (object, LABEL_THRESHOLD, input->threshold);
// Setting the experimental data
array = json_array_new ();
for (i = 0; i < input->nexperiments; ++i)
{
child = json_node_new (JSON_NODE_OBJECT);
object = json_node_get_object (child);
json_object_set_string_member (object, LABEL_NAME,
input->experiment[i].name);
if (input->experiment[i].weight != 1.)
json_object_set_float (object, LABEL_WEIGHT,
input->experiment[i].weight);
for (j = 0; j < input->experiment->ninputs; ++j)
json_object_set_string_member (object, stencil[j],
input->experiment[i].stencil[j]);
json_array_add_element (array, child);
}
json_object_set_array_member (object, LABEL_EXPERIMENTS, array);
// Setting the variables data
array = json_array_new ();
for (i = 0; i < input->nvariables; ++i)
{
child = json_node_new (JSON_NODE_OBJECT);
object = json_node_get_object (child);
json_object_set_string_member (object, LABEL_NAME,
input->variable[i].name);
json_object_set_float (object, LABEL_MINIMUM,
input->variable[i].rangemin);
if (input->variable[i].rangeminabs != -G_MAXDOUBLE)
json_object_set_float (object, LABEL_ABSOLUTE_MINIMUM,
input->variable[i].rangeminabs);
json_object_set_float (object, LABEL_MAXIMUM,
input->variable[i].rangemax);
if (input->variable[i].rangemaxabs != G_MAXDOUBLE)
json_object_set_float (object, LABEL_ABSOLUTE_MAXIMUM,
input->variable[i].rangemaxabs);
if (input->variable[i].precision != DEFAULT_PRECISION)
json_object_set_uint (object, LABEL_PRECISION,
input->variable[i].precision);
if (input->algorithm == ALGORITHM_SWEEP
|| input->algorithm == ALGORITHM_ORTHOGONAL)
json_object_set_uint (object, LABEL_NSWEEPS,
input->variable[i].nsweeps);
else if (input->algorithm == ALGORITHM_GENETIC)
json_object_set_uint (object, LABEL_NBITS, input->variable[i].nbits);
if (input->nsteps)
json_object_set_float (object, LABEL_STEP, input->variable[i].step);
json_array_add_element (array, child);
}
json_object_set_array_member (object, LABEL_VARIABLES, array);
// Saving the error norm
switch (input->norm)
{
case ERROR_NORM_MAXIMUM:
json_object_set_string_member (object, LABEL_NORM, LABEL_MAXIMUM);
break;
case ERROR_NORM_P:
json_object_set_string_member (object, LABEL_NORM, LABEL_P);
json_object_set_float (object, LABEL_P, input->p);
break;
case ERROR_NORM_TAXICAB:
json_object_set_string_member (object, LABEL_NORM, LABEL_TAXICAB);
}
#if DEBUG_INTERFACE
fprintf (stderr, "input_save_json: end\n");
#endif
}
/**
* Function to save the input file.
*/
static inline void
input_save (char *filename) ///< Input file name.
{
xmlDoc *doc;
JsonGenerator *generator;
#if DEBUG_INTERFACE
fprintf (stderr, "input_save: start\n");
#endif
// Getting the input file directory
input->name = g_path_get_basename (filename);
input->directory = g_path_get_dirname (filename);
if (input->type == INPUT_TYPE_XML)
{
// Opening the input file
doc = xmlNewDoc ((const xmlChar *) "1.0");
input_save_xml (doc);
// Saving the XML file
xmlSaveFormatFile (filename, doc, 1);
// Freeing memory
xmlFreeDoc (doc);
}
else
{
// Opening the input file
generator = json_generator_new ();
json_generator_set_pretty (generator, TRUE);
input_save_json (generator);
// Saving the JSON file
json_generator_to_file (generator, filename, NULL);
// Freeing memory
g_object_unref (generator);
}
#if DEBUG_INTERFACE
fprintf (stderr, "input_save: end\n");
#endif
}
/**
* Function to open the options dialog.
*/
static void
options_new ()
{
#if DEBUG_INTERFACE
fprintf (stderr, "options_new: start\n");
#endif
options->label_seed = (GtkLabel *)
gtk_label_new (_("Pseudo-random numbers generator seed"));
options->spin_seed = (GtkSpinButton *)
gtk_spin_button_new_with_range (0., (gdouble) G_MAXULONG, 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (options->spin_seed),
_("Seed to init the pseudo-random numbers generator"));
gtk_spin_button_set_value (options->spin_seed, (gdouble) input->seed);
options->label_threads = (GtkLabel *)
gtk_label_new (_("Threads number for the stochastic algorithm"));
options->spin_threads
= (GtkSpinButton *) gtk_spin_button_new_with_range (1., 64., 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (options->spin_threads),
_("Number of threads to perform the calibration/optimization for "
"the stochastic algorithm"));
gtk_spin_button_set_value (options->spin_threads, (gdouble) nthreads);
options->label_climbing = (GtkLabel *)
gtk_label_new (_("Threads number for the hill climbing method"));
options->spin_climbing =
(GtkSpinButton *) gtk_spin_button_new_with_range (1., 64., 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (options->spin_climbing),
_("Number of threads to perform the calibration/optimization for the "
"hill climbing method"));
gtk_spin_button_set_value (options->spin_climbing,
(gdouble) nthreads_climbing);
options->grid = (GtkGrid *) gtk_grid_new ();
gtk_grid_attach (options->grid, GTK_WIDGET (options->label_seed), 0, 0, 1, 1);
gtk_grid_attach (options->grid, GTK_WIDGET (options->spin_seed), 1, 0, 1, 1);
gtk_grid_attach (options->grid, GTK_WIDGET (options->label_threads),
0, 1, 1, 1);
gtk_grid_attach (options->grid, GTK_WIDGET (options->spin_threads),
1, 1, 1, 1);
gtk_grid_attach (options->grid, GTK_WIDGET (options->label_climbing), 0, 2, 1,
1);
gtk_grid_attach (options->grid, GTK_WIDGET (options->spin_climbing), 1, 2, 1,
1);
gtk_widget_show_all (GTK_WIDGET (options->grid));
options->dialog = (GtkDialog *)
gtk_dialog_new_with_buttons (_("Options"),
window->window,
GTK_DIALOG_MODAL,
_("_OK"), GTK_RESPONSE_OK,
_("_Cancel"), GTK_RESPONSE_CANCEL, NULL);
gtk_container_add
(GTK_CONTAINER (gtk_dialog_get_content_area (options->dialog)),
GTK_WIDGET (options->grid));
if (gtk_dialog_run (options->dialog) == GTK_RESPONSE_OK)
{
input->seed
= (unsigned long int) gtk_spin_button_get_value (options->spin_seed);
nthreads = gtk_spin_button_get_value_as_int (options->spin_threads);
nthreads_climbing
= gtk_spin_button_get_value_as_int (options->spin_climbing);
}
gtk_widget_destroy (GTK_WIDGET (options->dialog));
#if DEBUG_INTERFACE
fprintf (stderr, "options_new: end\n");
#endif
}
/**
* Function to open the running dialog.
*/
static inline void
running_new ()
{
#if DEBUG_INTERFACE
fprintf (stderr, "running_new: start\n");
#endif
running->label = (GtkLabel *) gtk_label_new (_("Calculating ..."));
running->spinner = (GtkSpinner *) gtk_spinner_new ();
running->grid = (GtkGrid *) gtk_grid_new ();
gtk_grid_attach (running->grid, GTK_WIDGET (running->label), 0, 0, 1, 1);
gtk_grid_attach (running->grid, GTK_WIDGET (running->spinner), 0, 1, 1, 1);
running->dialog = (GtkDialog *)
gtk_dialog_new_with_buttons (_("Calculating"),
window->window, GTK_DIALOG_MODAL, NULL, NULL);
gtk_container_add (GTK_CONTAINER
(gtk_dialog_get_content_area (running->dialog)),
GTK_WIDGET (running->grid));
gtk_spinner_start (running->spinner);
gtk_widget_show_all (GTK_WIDGET (running->dialog));
#if DEBUG_INTERFACE
fprintf (stderr, "running_new: end\n");
#endif
}
/**
* Function to get the stochastic algorithm number.
*
* \return Stochastic algorithm number.
*/
static unsigned int
window_get_algorithm ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_get_algorithm: start\n");
#endif
i = gtk_array_get_active (window->button_algorithm, NALGORITHMS);
#if DEBUG_INTERFACE
fprintf (stderr, "window_get_algorithm: %u\n", i);
fprintf (stderr, "window_get_algorithm: end\n");
#endif
return i;
}
/**
* Function to get the hill climbing method number.
*
* \return Hill climbing method number.
*/
static unsigned int
window_get_climbing ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_get_climbing: start\n");
#endif
i = gtk_array_get_active (window->button_climbing, NCLIMBINGS);
#if DEBUG_INTERFACE
fprintf (stderr, "window_get_climbing: %u\n", i);
fprintf (stderr, "window_get_climbing: end\n");
#endif
return i;
}
/**
* Function to get the norm method number.
*
* \return Norm method number.
*/
static unsigned int
window_get_norm ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_get_norm: start\n");
#endif
i = gtk_array_get_active (window->button_norm, NNORMS);
#if DEBUG_INTERFACE
fprintf (stderr, "window_get_norm: %u\n", i);
fprintf (stderr, "window_get_norm: end\n");
#endif
return i;
}
/**
* Function to save the hill climbing method data in the input file.
*/
static void
window_save_climbing ()
{
#if DEBUG_INTERFACE
fprintf (stderr, "window_save_climbing: start\n");
#endif
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_climbing)))
{
input->nsteps = gtk_spin_button_get_value_as_int (window->spin_steps);
input->relaxation = gtk_spin_button_get_value (window->spin_relaxation);
switch (window_get_climbing ())
{
case CLIMBING_METHOD_COORDINATES:
input->climbing = CLIMBING_METHOD_COORDINATES;
break;
default:
input->climbing = CLIMBING_METHOD_RANDOM;
input->nestimates
= gtk_spin_button_get_value_as_int (window->spin_estimates);
}
}
else
input->nsteps = 0;
#if DEBUG_INTERFACE
fprintf (stderr, "window_save_climbing: end\n");
#endif
}
/**
* Function to save the input file.
*
* \return 1 on OK, 0 on Cancel.
*/
static int
window_save ()
{
GtkFileChooserDialog *dlg;
GtkFileFilter *filter1, *filter2;
char *buffer;
#if DEBUG_INTERFACE
fprintf (stderr, "window_save: start\n");
#endif
// Opening the saving dialog
dlg = (GtkFileChooserDialog *)
gtk_file_chooser_dialog_new (_("Save file"),
window->window,
GTK_FILE_CHOOSER_ACTION_SAVE,
_("_Cancel"), GTK_RESPONSE_CANCEL,
_("_OK"), GTK_RESPONSE_OK, NULL);
gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dlg), TRUE);
buffer = g_build_filename (input->directory, input->name, NULL);
gtk_file_chooser_set_filename (GTK_FILE_CHOOSER (dlg), buffer);
g_free (buffer);
// Adding XML filter
filter1 = (GtkFileFilter *) gtk_file_filter_new ();
gtk_file_filter_set_name (filter1, "XML");
gtk_file_filter_add_pattern (filter1, "*.xml");
gtk_file_filter_add_pattern (filter1, "*.XML");
gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter1);
// Adding JSON filter
filter2 = (GtkFileFilter *) gtk_file_filter_new ();
gtk_file_filter_set_name (filter2, "JSON");
gtk_file_filter_add_pattern (filter2, "*.json");
gtk_file_filter_add_pattern (filter2, "*.JSON");
gtk_file_filter_add_pattern (filter2, "*.js");
gtk_file_filter_add_pattern (filter2, "*.JS");
gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter2);
if (input->type == INPUT_TYPE_XML)
gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dlg), filter1);
else
gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dlg), filter2);
// If OK response then saving
if (gtk_dialog_run (GTK_DIALOG (dlg)) == GTK_RESPONSE_OK)
{
// Setting input file type
filter1 = gtk_file_chooser_get_filter (GTK_FILE_CHOOSER (dlg));
buffer = (char *) gtk_file_filter_get_name (filter1);
if (!strcmp (buffer, "XML"))
input->type = INPUT_TYPE_XML;
else
input->type = INPUT_TYPE_JSON;
// Adding properties to the root XML node
input->simulator = gtk_file_chooser_get_filename
(GTK_FILE_CHOOSER (window->button_simulator));
if (gtk_toggle_button_get_active
(GTK_TOGGLE_BUTTON (window->check_evaluator)))
input->evaluator = gtk_file_chooser_get_filename
(GTK_FILE_CHOOSER (window->button_evaluator));
else
input->evaluator = NULL;
if (input->type == INPUT_TYPE_XML)
{
input->result
= (char *) xmlStrdup ((const xmlChar *)
gtk_entry_get_text (window->entry_result));
input->variables
= (char *) xmlStrdup ((const xmlChar *)
gtk_entry_get_text (window->entry_variables));
}
else
{
input->result = g_strdup (gtk_entry_get_text (window->entry_result));
input->variables =
g_strdup (gtk_entry_get_text (window->entry_variables));
}
// Setting the algorithm
switch (window_get_algorithm ())
{
case ALGORITHM_MONTE_CARLO:
input->algorithm = ALGORITHM_MONTE_CARLO;
input->nsimulations
= gtk_spin_button_get_value_as_int (window->spin_simulations);
input->niterations
= gtk_spin_button_get_value_as_int (window->spin_iterations);
input->tolerance = gtk_spin_button_get_value (window->spin_tolerance);
input->nbest = gtk_spin_button_get_value_as_int (window->spin_bests);
window_save_climbing ();
break;
case ALGORITHM_SWEEP:
input->algorithm = ALGORITHM_SWEEP;
input->niterations
= gtk_spin_button_get_value_as_int (window->spin_iterations);
input->tolerance = gtk_spin_button_get_value (window->spin_tolerance);
input->nbest = gtk_spin_button_get_value_as_int (window->spin_bests);
window_save_climbing ();
break;
case ALGORITHM_ORTHOGONAL:
input->algorithm = ALGORITHM_ORTHOGONAL;
input->niterations
= gtk_spin_button_get_value_as_int (window->spin_iterations);
input->tolerance = gtk_spin_button_get_value (window->spin_tolerance);
input->nbest = gtk_spin_button_get_value_as_int (window->spin_bests);
window_save_climbing ();
break;
default:
input->algorithm = ALGORITHM_GENETIC;
input->nsimulations
= gtk_spin_button_get_value_as_int (window->spin_population);
input->niterations
= gtk_spin_button_get_value_as_int (window->spin_generations);
input->mutation_ratio
= gtk_spin_button_get_value (window->spin_mutation);
input->reproduction_ratio
= gtk_spin_button_get_value (window->spin_reproduction);
input->adaptation_ratio
= gtk_spin_button_get_value (window->spin_adaptation);
break;
}
input->norm = window_get_norm ();
input->p = gtk_spin_button_get_value (window->spin_p);
input->threshold = gtk_spin_button_get_value (window->spin_threshold);
// Saving the XML file
buffer = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dlg));
input_save (buffer);
// Closing and freeing memory
g_free (buffer);
gtk_widget_destroy (GTK_WIDGET (dlg));
#if DEBUG_INTERFACE
fprintf (stderr, "window_save: end\n");
#endif
return 1;
}
// Closing and freeing memory
gtk_widget_destroy (GTK_WIDGET (dlg));
#if DEBUG_INTERFACE
fprintf (stderr, "window_save: end\n");
#endif
return 0;
}
/**
* Function to run a optimization.
*/
static void
window_run ()
{
unsigned int i;
char *msg, *msg2, buffer[64], buffer2[64];
#if DEBUG_INTERFACE
fprintf (stderr, "window_run: start\n");
#endif
if (!window_save ())
{
#if DEBUG_INTERFACE
fprintf (stderr, "window_run: end\n");
#endif
return;
}
running_new ();
while (gtk_events_pending ())
gtk_main_iteration ();
optimize_open ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_run: closing running dialog\n");
#endif
gtk_spinner_stop (running->spinner);
gtk_widget_destroy (GTK_WIDGET (running->dialog));
#if DEBUG_INTERFACE
fprintf (stderr, "window_run: displaying results\n");
#endif
snprintf (buffer, 64, "error = %.15le\n", optimize->error_old[0]);
msg2 = g_strdup (buffer);
for (i = 0; i < optimize->nvariables; ++i, msg2 = msg)
{
snprintf (buffer, 64, "%s = %s\n",
input->variable[i].name, format[input->variable[i].precision]);
snprintf (buffer2, 64, buffer, optimize->value_old[i]);
msg = g_strconcat (msg2, buffer2, NULL);
g_free (msg2);
}
snprintf (buffer, 64, "%s = %.6lg s", _("Calculation time"),
optimize->calculation_time);
msg = g_strconcat (msg2, buffer, NULL);
g_free (msg2);
show_message (_("Best result"), msg, INFO_TYPE);
g_free (msg);
#if DEBUG_INTERFACE
fprintf (stderr, "window_run: freeing memory\n");
#endif
optimize_free ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_run: end\n");
#endif
}
/**
* Function to show a help dialog.
*/
static void
window_help ()
{
char *buffer, *buffer2;
#if DEBUG_INTERFACE
fprintf (stderr, "window_help: start\n");
#endif
buffer2 = g_build_filename (window->application_directory, "..", "manuals",
_("user-manual.pdf"), NULL);
buffer = g_filename_to_uri (buffer2, NULL, NULL);
g_free (buffer2);
#if GTK_MINOR_VERSION >= 22
gtk_show_uri_on_window (window->window, buffer, GDK_CURRENT_TIME, NULL);
#else
gtk_show_uri (NULL, buffer, GDK_CURRENT_TIME, NULL);
#endif
#if DEBUG_INTERFACE
fprintf (stderr, "window_help: uri=%s\n", buffer);
#endif
g_free (buffer);
#if DEBUG_INTERFACE
fprintf (stderr, "window_help: end\n");
#endif
}
/**
* Function to show an about dialog.
*/
static void
window_about ()
{
static const gchar *authors[] = {
"Javier Burguete Tolosa <jburguete@eead.csic.es>",
"Borja Latorre Garcés <borja.latorre@csic.es>",
NULL
};
#if DEBUG_INTERFACE
fprintf (stderr, "window_about: start\n");
#endif
gtk_show_about_dialog
(window->window,
"program_name", "MPCOTool",
"comments",
_("The Multi-Purposes Calibration and Optimization Tool.\n"
"A software to perform calibrations or optimizations of empirical "
"parameters"),
"authors", authors,
"translator-credits",
"Javier Burguete Tolosa <jburguete@eead.csic.es> "
"(english, french and spanish)\n"
"Uğur Çayoğlu (german)",
"version", "4.0.1",
"copyright", "Copyright 2012-2019 Javier Burguete Tolosa",
"logo", window->logo,
"website", "https://github.com/jburguete/mpcotool",
"license-type", GTK_LICENSE_BSD, NULL);
#if DEBUG_INTERFACE
fprintf (stderr, "window_about: end\n");
#endif
}
/**
* Function to update hill climbing method widgets view in the main window.
*/
static void
window_update_climbing ()
{
#if DEBUG_INTERFACE
fprintf (stderr, "window_update_climbing: start\n");
#endif
gtk_widget_show (GTK_WIDGET (window->check_climbing));
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_climbing)))
{
gtk_widget_show (GTK_WIDGET (window->grid_climbing));
gtk_widget_show (GTK_WIDGET (window->label_step));
gtk_widget_show (GTK_WIDGET (window->spin_step));
}
switch (window_get_climbing ())
{
case CLIMBING_METHOD_COORDINATES:
gtk_widget_hide (GTK_WIDGET (window->label_estimates));
gtk_widget_hide (GTK_WIDGET (window->spin_estimates));
break;
default:
gtk_widget_show (GTK_WIDGET (window->label_estimates));
gtk_widget_show (GTK_WIDGET (window->spin_estimates));
}
#if DEBUG_INTERFACE
fprintf (stderr, "window_update_climbing: end\n");
#endif
}
/**
* Function to update the main window view.
*/
static void
window_update ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_update: start\n");
#endif
gtk_widget_set_sensitive
(GTK_WIDGET (window->button_evaluator),
gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON
(window->check_evaluator)));
gtk_widget_hide (GTK_WIDGET (window->label_simulations));
gtk_widget_hide (GTK_WIDGET (window->spin_simulations));
gtk_widget_hide (GTK_WIDGET (window->label_iterations));
gtk_widget_hide (GTK_WIDGET (window->spin_iterations));
gtk_widget_hide (GTK_WIDGET (window->label_tolerance));
gtk_widget_hide (GTK_WIDGET (window->spin_tolerance));
gtk_widget_hide (GTK_WIDGET (window->label_bests));
gtk_widget_hide (GTK_WIDGET (window->spin_bests));
gtk_widget_hide (GTK_WIDGET (window->label_population));
gtk_widget_hide (GTK_WIDGET (window->spin_population));
gtk_widget_hide (GTK_WIDGET (window->label_generations));
gtk_widget_hide (GTK_WIDGET (window->spin_generations));
gtk_widget_hide (GTK_WIDGET (window->label_mutation));
gtk_widget_hide (GTK_WIDGET (window->spin_mutation));
gtk_widget_hide (GTK_WIDGET (window->label_reproduction));
gtk_widget_hide (GTK_WIDGET (window->spin_reproduction));
gtk_widget_hide (GTK_WIDGET (window->label_adaptation));
gtk_widget_hide (GTK_WIDGET (window->spin_adaptation));
gtk_widget_hide (GTK_WIDGET (window->label_sweeps));
gtk_widget_hide (GTK_WIDGET (window->spin_sweeps));
gtk_widget_hide (GTK_WIDGET (window->label_bits));
gtk_widget_hide (GTK_WIDGET (window->spin_bits));
gtk_widget_hide (GTK_WIDGET (window->check_climbing));
gtk_widget_hide (GTK_WIDGET (window->grid_climbing));
gtk_widget_hide (GTK_WIDGET (window->label_step));
gtk_widget_hide (GTK_WIDGET (window->spin_step));
gtk_widget_hide (GTK_WIDGET (window->label_p));
gtk_widget_hide (GTK_WIDGET (window->spin_p));
i = gtk_spin_button_get_value_as_int (window->spin_iterations);
switch (window_get_algorithm ())
{
case ALGORITHM_MONTE_CARLO:
gtk_widget_show (GTK_WIDGET (window->label_simulations));
gtk_widget_show (GTK_WIDGET (window->spin_simulations));
gtk_widget_show (GTK_WIDGET (window->label_iterations));
gtk_widget_show (GTK_WIDGET (window->spin_iterations));
if (i > 1)
{
gtk_widget_show (GTK_WIDGET (window->label_tolerance));
gtk_widget_show (GTK_WIDGET (window->spin_tolerance));
gtk_widget_show (GTK_WIDGET (window->label_bests));
gtk_widget_show (GTK_WIDGET (window->spin_bests));
}
window_update_climbing ();
break;
case ALGORITHM_SWEEP:
case ALGORITHM_ORTHOGONAL:
gtk_widget_show (GTK_WIDGET (window->label_iterations));
gtk_widget_show (GTK_WIDGET (window->spin_iterations));
if (i > 1)
{
gtk_widget_show (GTK_WIDGET (window->label_tolerance));
gtk_widget_show (GTK_WIDGET (window->spin_tolerance));
gtk_widget_show (GTK_WIDGET (window->label_bests));
gtk_widget_show (GTK_WIDGET (window->spin_bests));
}
gtk_widget_show (GTK_WIDGET (window->label_sweeps));
gtk_widget_show (GTK_WIDGET (window->spin_sweeps));
gtk_widget_show (GTK_WIDGET (window->check_climbing));
window_update_climbing ();
break;
default:
gtk_widget_show (GTK_WIDGET (window->label_population));
gtk_widget_show (GTK_WIDGET (window->spin_population));
gtk_widget_show (GTK_WIDGET (window->label_generations));
gtk_widget_show (GTK_WIDGET (window->spin_generations));
gtk_widget_show (GTK_WIDGET (window->label_mutation));
gtk_widget_show (GTK_WIDGET (window->spin_mutation));
gtk_widget_show (GTK_WIDGET (window->label_reproduction));
gtk_widget_show (GTK_WIDGET (window->spin_reproduction));
gtk_widget_show (GTK_WIDGET (window->label_adaptation));
gtk_widget_show (GTK_WIDGET (window->spin_adaptation));
gtk_widget_show (GTK_WIDGET (window->label_bits));
gtk_widget_show (GTK_WIDGET (window->spin_bits));
}
gtk_widget_set_sensitive
(GTK_WIDGET (window->button_remove_experiment), input->nexperiments > 1);
gtk_widget_set_sensitive
(GTK_WIDGET (window->button_remove_variable), input->nvariables > 1);
for (i = 0; i < input->experiment->ninputs; ++i)
{
gtk_widget_show (GTK_WIDGET (window->check_template[i]));
gtk_widget_show (GTK_WIDGET (window->button_template[i]));
gtk_widget_set_sensitive (GTK_WIDGET (window->check_template[i]), 0);
gtk_widget_set_sensitive (GTK_WIDGET (window->button_template[i]), 1);
g_signal_handler_block
(window->check_template[i], window->id_template[i]);
g_signal_handler_block (window->button_template[i], window->id_input[i]);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON
(window->check_template[i]), 1);
g_signal_handler_unblock (window->button_template[i],
window->id_input[i]);
g_signal_handler_unblock (window->check_template[i],
window->id_template[i]);
}
if (i > 0)
{
gtk_widget_set_sensitive (GTK_WIDGET (window->check_template[i - 1]), 1);
gtk_widget_set_sensitive (GTK_WIDGET (window->button_template[i - 1]),
gtk_toggle_button_get_active
GTK_TOGGLE_BUTTON (window->check_template
[i - 1]));
}
if (i < MAX_NINPUTS)
{
gtk_widget_show (GTK_WIDGET (window->check_template[i]));
gtk_widget_show (GTK_WIDGET (window->button_template[i]));
gtk_widget_set_sensitive (GTK_WIDGET (window->check_template[i]), 1);
gtk_widget_set_sensitive
(GTK_WIDGET (window->button_template[i]),
gtk_toggle_button_get_active
GTK_TOGGLE_BUTTON (window->check_template[i]));
g_signal_handler_block
(window->check_template[i], window->id_template[i]);
g_signal_handler_block (window->button_template[i], window->id_input[i]);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON
(window->check_template[i]), 0);
g_signal_handler_unblock (window->button_template[i],
window->id_input[i]);
g_signal_handler_unblock (window->check_template[i],
window->id_template[i]);
}
while (++i < MAX_NINPUTS)
{
gtk_widget_hide (GTK_WIDGET (window->check_template[i]));
gtk_widget_hide (GTK_WIDGET (window->button_template[i]));
}
gtk_widget_set_sensitive
(GTK_WIDGET (window->spin_minabs),
gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_minabs)));
gtk_widget_set_sensitive
(GTK_WIDGET (window->spin_maxabs),
gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (window->check_maxabs)));
if (window_get_norm () == ERROR_NORM_P)
{
gtk_widget_show (GTK_WIDGET (window->label_p));
gtk_widget_show (GTK_WIDGET (window->spin_p));
}
#if DEBUG_INTERFACE
fprintf (stderr, "window_update: end\n");
#endif
}
/**
* Function to avoid memory errors changing the algorithm.
*/
static void
window_set_algorithm ()
{
int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_algorithm: start\n");
#endif
i = window_get_algorithm ();
switch (i)
{
case ALGORITHM_SWEEP:
case ALGORITHM_ORTHOGONAL:
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
if (i < 0)
i = 0;
gtk_spin_button_set_value (window->spin_sweeps,
(gdouble) input->variable[i].nsweeps);
break;
case ALGORITHM_GENETIC:
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
if (i < 0)
i = 0;
gtk_spin_button_set_value (window->spin_bits,
(gdouble) input->variable[i].nbits);
}
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_algorithm: end\n");
#endif
}
/**
* Function to set the experiment data in the main window.
*/
static void
window_set_experiment ()
{
unsigned int i, j;
char *buffer1, *buffer2;
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_experiment: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));
gtk_spin_button_set_value (window->spin_weight, input->experiment[i].weight);
buffer1 = gtk_combo_box_text_get_active_text (window->combo_experiment);
buffer2 = g_build_filename (input->directory, buffer1, NULL);
g_free (buffer1);
g_signal_handler_block
(window->button_experiment, window->id_experiment_name);
gtk_file_chooser_set_filename
(GTK_FILE_CHOOSER (window->button_experiment), buffer2);
g_signal_handler_unblock
(window->button_experiment, window->id_experiment_name);
g_free (buffer2);
for (j = 0; j < input->experiment->ninputs; ++j)
{
g_signal_handler_block (window->button_template[j], window->id_input[j]);
buffer2 =
g_build_filename (input->directory, input->experiment[i].stencil[j],
NULL);
gtk_file_chooser_set_filename (GTK_FILE_CHOOSER
(window->button_template[j]), buffer2);
g_free (buffer2);
g_signal_handler_unblock
(window->button_template[j], window->id_input[j]);
}
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_experiment: end\n");
#endif
}
/**
* Function to remove an experiment in the main window.
*/
static void
window_remove_experiment ()
{
unsigned int i, j;
#if DEBUG_INTERFACE
fprintf (stderr, "window_remove_experiment: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));
g_signal_handler_block (window->combo_experiment, window->id_experiment);
gtk_combo_box_text_remove (window->combo_experiment, i);
g_signal_handler_unblock (window->combo_experiment, window->id_experiment);
experiment_free (input->experiment + i, input->type);
--input->nexperiments;
for (j = i; j < input->nexperiments; ++j)
memcpy (input->experiment + j, input->experiment + j + 1,
sizeof (Experiment));
j = input->nexperiments - 1;
if (i > j)
i = j;
for (j = 0; j < input->experiment->ninputs; ++j)
g_signal_handler_block (window->button_template[j], window->id_input[j]);
g_signal_handler_block
(window->button_experiment, window->id_experiment_name);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), i);
g_signal_handler_unblock
(window->button_experiment, window->id_experiment_name);
for (j = 0; j < input->experiment->ninputs; ++j)
g_signal_handler_unblock (window->button_template[j], window->id_input[j]);
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_remove_experiment: end\n");
#endif
}
/**
* Function to add an experiment in the main window.
*/
static void
window_add_experiment ()
{
unsigned int i, j;
#if DEBUG_INTERFACE
fprintf (stderr, "window_add_experiment: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));
g_signal_handler_block (window->combo_experiment, window->id_experiment);
gtk_combo_box_text_insert_text
(window->combo_experiment, i, input->experiment[i].name);
g_signal_handler_unblock (window->combo_experiment, window->id_experiment);
input->experiment = (Experiment *) g_realloc
(input->experiment, (input->nexperiments + 1) * sizeof (Experiment));
for (j = input->nexperiments - 1; j > i; --j)
memcpy (input->experiment + j + 1, input->experiment + j,
sizeof (Experiment));
input->experiment[j + 1].weight = input->experiment[j].weight;
input->experiment[j + 1].ninputs = input->experiment[j].ninputs;
if (input->type == INPUT_TYPE_XML)
{
input->experiment[j + 1].name
= (char *) xmlStrdup ((xmlChar *) input->experiment[j].name);
for (j = 0; j < input->experiment->ninputs; ++j)
input->experiment[i + 1].stencil[j]
= (char *) xmlStrdup ((xmlChar *) input->experiment[i].stencil[j]);
}
else
{
input->experiment[j + 1].name = g_strdup (input->experiment[j].name);
for (j = 0; j < input->experiment->ninputs; ++j)
input->experiment[i + 1].stencil[j]
= g_strdup (input->experiment[i].stencil[j]);
}
++input->nexperiments;
for (j = 0; j < input->experiment->ninputs; ++j)
g_signal_handler_block (window->button_template[j], window->id_input[j]);
g_signal_handler_block
(window->button_experiment, window->id_experiment_name);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), i + 1);
g_signal_handler_unblock
(window->button_experiment, window->id_experiment_name);
for (j = 0; j < input->experiment->ninputs; ++j)
g_signal_handler_unblock (window->button_template[j], window->id_input[j]);
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_add_experiment: end\n");
#endif
}
/**
* Function to set the experiment name in the main window.
*/
static void
window_name_experiment ()
{
unsigned int i;
char *buffer;
GFile *file1, *file2;
#if DEBUG_INTERFACE
fprintf (stderr, "window_name_experiment: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));
file1
= gtk_file_chooser_get_file (GTK_FILE_CHOOSER (window->button_experiment));
file2 = g_file_new_for_path (input->directory);
buffer = g_file_get_relative_path (file2, file1);
g_signal_handler_block (window->combo_experiment, window->id_experiment);
gtk_combo_box_text_remove (window->combo_experiment, i);
gtk_combo_box_text_insert_text (window->combo_experiment, i, buffer);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), i);
g_signal_handler_unblock (window->combo_experiment, window->id_experiment);
g_free (buffer);
g_object_unref (file2);
g_object_unref (file1);
#if DEBUG_INTERFACE
fprintf (stderr, "window_name_experiment: end\n");
#endif
}
/**
* Function to update the experiment weight in the main window.
*/
static void
window_weight_experiment ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_weight_experiment: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));
input->experiment[i].weight = gtk_spin_button_get_value (window->spin_weight);
#if DEBUG_INTERFACE
fprintf (stderr, "window_weight_experiment: end\n");
#endif
}
/**
* Function to update the experiment input templates number in the main window.
*/
static void
window_inputs_experiment ()
{
unsigned int j;
#if DEBUG_INTERFACE
fprintf (stderr, "window_inputs_experiment: start\n");
#endif
j = input->experiment->ninputs - 1;
if (j
&& !gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON
(window->check_template[j])))
--input->experiment->ninputs;
if (input->experiment->ninputs < MAX_NINPUTS
&& gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON
(window->check_template[j])))
++input->experiment->ninputs;
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_inputs_experiment: end\n");
#endif
}
/**
* Function to update the experiment i-th input template in the main window.
*/
static void
window_template_experiment (void *data)
///< Callback data (i-th input template).
{
unsigned int i, j;
char *buffer;
GFile *file1, *file2;
#if DEBUG_INTERFACE
fprintf (stderr, "window_template_experiment: start\n");
#endif
i = (size_t) data;
j = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_experiment));
file1
= gtk_file_chooser_get_file (GTK_FILE_CHOOSER (window->button_template[i]));
file2 = g_file_new_for_path (input->directory);
buffer = g_file_get_relative_path (file2, file1);
if (input->type == INPUT_TYPE_XML)
input->experiment[j].stencil[i] = (char *) xmlStrdup ((xmlChar *) buffer);
else
input->experiment[j].stencil[i] = g_strdup (buffer);
g_free (buffer);
g_object_unref (file2);
g_object_unref (file1);
#if DEBUG_INTERFACE
fprintf (stderr, "window_template_experiment: end\n");
#endif
}
/**
* Function to set the variable data in the main window.
*/
static void
window_set_variable ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
g_signal_handler_block (window->entry_variable, window->id_variable_label);
gtk_entry_set_text (window->entry_variable, input->variable[i].name);
g_signal_handler_unblock (window->entry_variable, window->id_variable_label);
gtk_spin_button_set_value (window->spin_min, input->variable[i].rangemin);
gtk_spin_button_set_value (window->spin_max, input->variable[i].rangemax);
if (input->variable[i].rangeminabs != -G_MAXDOUBLE)
{
gtk_spin_button_set_value (window->spin_minabs,
input->variable[i].rangeminabs);
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON (window->check_minabs), 1);
}
else
{
gtk_spin_button_set_value (window->spin_minabs, -G_MAXDOUBLE);
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON (window->check_minabs), 0);
}
if (input->variable[i].rangemaxabs != G_MAXDOUBLE)
{
gtk_spin_button_set_value (window->spin_maxabs,
input->variable[i].rangemaxabs);
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON (window->check_maxabs), 1);
}
else
{
gtk_spin_button_set_value (window->spin_maxabs, G_MAXDOUBLE);
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON (window->check_maxabs), 0);
}
gtk_spin_button_set_value (window->spin_precision,
input->variable[i].precision);
gtk_spin_button_set_value (window->spin_steps, (gdouble) input->nsteps);
if (input->nsteps)
gtk_spin_button_set_value (window->spin_step, input->variable[i].step);
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_variable: precision[%u]=%u\n", i,
input->variable[i].precision);
#endif
switch (window_get_algorithm ())
{
case ALGORITHM_SWEEP:
case ALGORITHM_ORTHOGONAL:
gtk_spin_button_set_value (window->spin_sweeps,
(gdouble) input->variable[i].nsweeps);
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_variable: nsweeps[%u]=%u\n", i,
input->variable[i].nsweeps);
#endif
break;
case ALGORITHM_GENETIC:
gtk_spin_button_set_value (window->spin_bits,
(gdouble) input->variable[i].nbits);
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_variable: nbits[%u]=%u\n", i,
input->variable[i].nbits);
#endif
break;
}
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_set_variable: end\n");
#endif
}
/**
* Function to remove a variable in the main window.
*/
static void
window_remove_variable ()
{
unsigned int i, j;
#if DEBUG_INTERFACE
fprintf (stderr, "window_remove_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
g_signal_handler_block (window->combo_variable, window->id_variable);
gtk_combo_box_text_remove (window->combo_variable, i);
g_signal_handler_unblock (window->combo_variable, window->id_variable);
xmlFree (input->variable[i].name);
--input->nvariables;
for (j = i; j < input->nvariables; ++j)
memcpy (input->variable + j, input->variable + j + 1, sizeof (Variable));
j = input->nvariables - 1;
if (i > j)
i = j;
g_signal_handler_block (window->entry_variable, window->id_variable_label);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), i);
g_signal_handler_unblock (window->entry_variable, window->id_variable_label);
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_remove_variable: end\n");
#endif
}
/**
* Function to add a variable in the main window.
*/
static void
window_add_variable ()
{
unsigned int i, j;
#if DEBUG_INTERFACE
fprintf (stderr, "window_add_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
g_signal_handler_block (window->combo_variable, window->id_variable);
gtk_combo_box_text_insert_text (window->combo_variable, i,
input->variable[i].name);
g_signal_handler_unblock (window->combo_variable, window->id_variable);
input->variable = (Variable *) g_realloc
(input->variable, (input->nvariables + 1) * sizeof (Variable));
for (j = input->nvariables - 1; j > i; --j)
memcpy (input->variable + j + 1, input->variable + j, sizeof (Variable));
memcpy (input->variable + j + 1, input->variable + j, sizeof (Variable));
if (input->type == INPUT_TYPE_XML)
input->variable[j + 1].name
= (char *) xmlStrdup ((xmlChar *) input->variable[j].name);
else
input->variable[j + 1].name = g_strdup (input->variable[j].name);
++input->nvariables;
g_signal_handler_block (window->entry_variable, window->id_variable_label);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), i + 1);
g_signal_handler_unblock (window->entry_variable, window->id_variable_label);
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_add_variable: end\n");
#endif
}
/**
* Function to set the variable label in the main window.
*/
static void
window_label_variable ()
{
unsigned int i;
const char *buffer;
#if DEBUG_INTERFACE
fprintf (stderr, "window_label_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
buffer = gtk_entry_get_text (window->entry_variable);
g_signal_handler_block (window->combo_variable, window->id_variable);
gtk_combo_box_text_remove (window->combo_variable, i);
gtk_combo_box_text_insert_text (window->combo_variable, i, buffer);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), i);
g_signal_handler_unblock (window->combo_variable, window->id_variable);
#if DEBUG_INTERFACE
fprintf (stderr, "window_label_variable: end\n");
#endif
}
/**
* Function to update the variable precision in the main window.
*/
static void
window_precision_variable ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_precision_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
input->variable[i].precision
= (unsigned int) gtk_spin_button_get_value_as_int (window->spin_precision);
gtk_spin_button_set_digits (window->spin_min, input->variable[i].precision);
gtk_spin_button_set_digits (window->spin_max, input->variable[i].precision);
gtk_spin_button_set_digits (window->spin_minabs,
input->variable[i].precision);
gtk_spin_button_set_digits (window->spin_maxabs,
input->variable[i].precision);
#if DEBUG_INTERFACE
fprintf (stderr, "window_precision_variable: end\n");
#endif
}
/**
* Function to update the variable rangemin in the main window.
*/
static void
window_rangemin_variable ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangemin_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
input->variable[i].rangemin = gtk_spin_button_get_value (window->spin_min);
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangemin_variable: end\n");
#endif
}
/**
* Function to update the variable rangemax in the main window.
*/
static void
window_rangemax_variable ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangemax_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
input->variable[i].rangemax = gtk_spin_button_get_value (window->spin_max);
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangemax_variable: end\n");
#endif
}
/**
* Function to update the variable rangeminabs in the main window.
*/
static void
window_rangeminabs_variable ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangeminabs_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
input->variable[i].rangeminabs
= gtk_spin_button_get_value (window->spin_minabs);
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangeminabs_variable: end\n");
#endif
}
/**
* Function to update the variable rangemaxabs in the main window.
*/
static void
window_rangemaxabs_variable ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangemaxabs_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
input->variable[i].rangemaxabs
= gtk_spin_button_get_value (window->spin_maxabs);
#if DEBUG_INTERFACE
fprintf (stderr, "window_rangemaxabs_variable: end\n");
#endif
}
/**
* Function to update the variable step in the main window.
*/
static void
window_step_variable ()
{
unsigned int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_step_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
input->variable[i].step = gtk_spin_button_get_value (window->spin_step);
#if DEBUG_INTERFACE
fprintf (stderr, "window_step_variable: end\n");
#endif
}
/**
* Function to update the variable data in the main window.
*/
static void
window_update_variable ()
{
int i;
#if DEBUG_INTERFACE
fprintf (stderr, "window_update_variable: start\n");
#endif
i = gtk_combo_box_get_active (GTK_COMBO_BOX (window->combo_variable));
if (i < 0)
i = 0;
switch (window_get_algorithm ())
{
case ALGORITHM_SWEEP:
case ALGORITHM_ORTHOGONAL:
input->variable[i].nsweeps
= gtk_spin_button_get_value_as_int (window->spin_sweeps);
#if DEBUG_INTERFACE
fprintf (stderr, "window_update_variable: nsweeps[%d]=%u\n", i,
input->variable[i].nsweeps);
#endif
break;
case ALGORITHM_GENETIC:
input->variable[i].nbits
= gtk_spin_button_get_value_as_int (window->spin_bits);
#if DEBUG_INTERFACE
fprintf (stderr, "window_update_variable: nbits[%d]=%u\n", i,
input->variable[i].nbits);
#endif
}
#if DEBUG_INTERFACE
fprintf (stderr, "window_update_variable: end\n");
#endif
}
/**
* Function to read the input data of a file.
*
* \return 1 on succes, 0 on error.
*/
static int
window_read (char *filename) ///< File name.
{
unsigned int i;
char *buffer;
#if DEBUG_INTERFACE
fprintf (stderr, "window_read: start\n");
#endif
// Reading new input file
input_free ();
input->result = input->variables = NULL;
if (!input_open (filename))
{
#if DEBUG_INTERFACE
fprintf (stderr, "window_read: end\n");
#endif
return 0;
}
// Setting GTK+ widgets data
gtk_entry_set_text (window->entry_result, input->result);
gtk_entry_set_text (window->entry_variables, input->variables);
buffer = g_build_filename (input->directory, input->simulator, NULL);
gtk_file_chooser_set_filename (GTK_FILE_CHOOSER
(window->button_simulator), buffer);
g_free (buffer);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (window->check_evaluator),
(size_t) input->evaluator);
if (input->evaluator)
{
buffer = g_build_filename (input->directory, input->evaluator, NULL);
gtk_file_chooser_set_filename (GTK_FILE_CHOOSER
(window->button_evaluator), buffer);
g_free (buffer);
}
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON (window->button_algorithm[input->algorithm]), TRUE);
switch (input->algorithm)
{
case ALGORITHM_MONTE_CARLO:
gtk_spin_button_set_value (window->spin_simulations,
(gdouble) input->nsimulations);
// fallthrough
case ALGORITHM_SWEEP:
case ALGORITHM_ORTHOGONAL:
gtk_spin_button_set_value (window->spin_iterations,
(gdouble) input->niterations);
gtk_spin_button_set_value (window->spin_bests, (gdouble) input->nbest);
gtk_spin_button_set_value (window->spin_tolerance, input->tolerance);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON
(window->check_climbing), input->nsteps);
if (input->nsteps)
{
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON (window->button_climbing[input->climbing]),
TRUE);
gtk_spin_button_set_value (window->spin_steps,
(gdouble) input->nsteps);
gtk_spin_button_set_value (window->spin_relaxation,
(gdouble) input->relaxation);
switch (input->climbing)
{
case CLIMBING_METHOD_RANDOM:
gtk_spin_button_set_value (window->spin_estimates,
(gdouble) input->nestimates);
}
}
break;
default:
gtk_spin_button_set_value (window->spin_population,
(gdouble) input->nsimulations);
gtk_spin_button_set_value (window->spin_generations,
(gdouble) input->niterations);
gtk_spin_button_set_value (window->spin_mutation, input->mutation_ratio);
gtk_spin_button_set_value (window->spin_reproduction,
input->reproduction_ratio);
gtk_spin_button_set_value (window->spin_adaptation,
input->adaptation_ratio);
}
gtk_toggle_button_set_active
(GTK_TOGGLE_BUTTON (window->button_norm[input->norm]), TRUE);
gtk_spin_button_set_value (window->spin_p, input->p);
gtk_spin_button_set_value (window->spin_threshold, input->threshold);
g_signal_handler_block (window->combo_experiment, window->id_experiment);
g_signal_handler_block (window->button_experiment,
window->id_experiment_name);
gtk_combo_box_text_remove_all (window->combo_experiment);
for (i = 0; i < input->nexperiments; ++i)
gtk_combo_box_text_append_text (window->combo_experiment,
input->experiment[i].name);
g_signal_handler_unblock
(window->button_experiment, window->id_experiment_name);
g_signal_handler_unblock (window->combo_experiment, window->id_experiment);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_experiment), 0);
g_signal_handler_block (window->combo_variable, window->id_variable);
g_signal_handler_block (window->entry_variable, window->id_variable_label);
gtk_combo_box_text_remove_all (window->combo_variable);
for (i = 0; i < input->nvariables; ++i)
gtk_combo_box_text_append_text (window->combo_variable,
input->variable[i].name);
g_signal_handler_unblock (window->entry_variable, window->id_variable_label);
g_signal_handler_unblock (window->combo_variable, window->id_variable);
gtk_combo_box_set_active (GTK_COMBO_BOX (window->combo_variable), 0);
window_set_variable ();
window_update ();
#if DEBUG_INTERFACE
fprintf (stderr, "window_read: end\n");
#endif
return 1;
}
/**
* Function to open the input data.
*/
static void
window_open ()
{
GtkFileChooserDialog *dlg;
GtkFileFilter *filter;
char *buffer, *directory, *name;
#if DEBUG_INTERFACE
fprintf (stderr, "window_open: start\n");
#endif
// Saving a backup of the current input file
directory = g_strdup (input->directory);
name = g_strdup (input->name);
// Opening dialog
dlg = (GtkFileChooserDialog *)
gtk_file_chooser_dialog_new (_("Open input file"),
window->window,
GTK_FILE_CHOOSER_ACTION_OPEN,
_("_Cancel"), GTK_RESPONSE_CANCEL,
_("_OK"), GTK_RESPONSE_OK, NULL);
// Adding XML filter
filter = (GtkFileFilter *) gtk_file_filter_new ();
gtk_file_filter_set_name (filter, "XML");
gtk_file_filter_add_pattern (filter, "*.xml");
gtk_file_filter_add_pattern (filter, "*.XML");
gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter);
// Adding JSON filter
filter = (GtkFileFilter *) gtk_file_filter_new ();
gtk_file_filter_set_name (filter, "JSON");
gtk_file_filter_add_pattern (filter, "*.json");
gtk_file_filter_add_pattern (filter, "*.JSON");
gtk_file_filter_add_pattern (filter, "*.js");
gtk_file_filter_add_pattern (filter, "*.JS");
gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dlg), filter);
// If OK saving
while (gtk_dialog_run (GTK_DIALOG (dlg)) == GTK_RESPONSE_OK)
{
// Traying to open the input file
buffer = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dlg));
if (!window_read (buffer))
{
#if DEBUG_INTERFACE
fprintf (stderr, "window_open: error reading input file\n");
#endif
g_free (buffer);
// Reading backup file on error
buffer = g_build_filename (directory, name, NULL);
input->result = input->variables = NULL;
if (!input_open (buffer))
{
// Closing on backup file reading error
#if DEBUG_INTERFACE
fprintf (stderr, "window_read: error reading backup file\n");
#endif
g_free (buffer);
break;
}
g_free (buffer);
}
else
{
g_free (buffer);
break;
}
}
// Freeing and closing
g_free (name);
g_free (directory);
gtk_widget_destroy (GTK_WIDGET (dlg));
#if DEBUG_INTERFACE
fprintf (stderr, "window_open: end\n");
#endif
}
/**
* Function to open the main window.
*/
void
window_new (GtkApplication * application) ///< GtkApplication struct.
{
unsigned int i;
char *buffer, *buffer2, buffer3[64];
char *label_algorithm[NALGORITHMS] = {
"_Monte-Carlo", _("_Sweep"), _("_Genetic"), _("_Orthogonal")
};
char *tip_algorithm[NALGORITHMS] = {
_("Monte-Carlo brute force algorithm"),
_("Sweep brute force algorithm"),
_("Genetic algorithm"),
_("Orthogonal sampling brute force algorithm"),
};
char *label_climbing[NCLIMBINGS] = {
_("_Coordinates climbing"), _("_Random climbing")
};
char *tip_climbing[NCLIMBINGS] = {
_("Coordinates climbing estimate method"),
_("Random climbing estimate method")
};
char *label_norm[NNORMS] = { "L2", "L∞", "Lp", "L1" };
char *tip_norm[NNORMS] = {
_("Euclidean error norm (L2)"),
_("Maximum error norm (L∞)"),
_("P error norm (Lp)"),
_("Taxicab error norm (L1)")
};
#if DEBUG_INTERFACE
fprintf (stderr, "window_new: start\n");
#endif
// Creating the window
window->window = main_window
= (GtkWindow *) gtk_application_window_new (application);
// Finish when closing the window
g_signal_connect_swapped (window->window, "delete-event",
G_CALLBACK (g_application_quit),
G_APPLICATION (application));
// Setting the window title
gtk_window_set_title (window->window, "MPCOTool");
// Creating the open button
window->button_open = (GtkToolButton *) gtk_tool_button_new
(gtk_image_new_from_icon_name ("document-open",
GTK_ICON_SIZE_LARGE_TOOLBAR), _("Open"));
g_signal_connect (window->button_open, "clicked", window_open, NULL);
// Creating the save button
window->button_save = (GtkToolButton *) gtk_tool_button_new
(gtk_image_new_from_icon_name ("document-save",
GTK_ICON_SIZE_LARGE_TOOLBAR), _("Save"));
g_signal_connect (window->button_save, "clicked", (GCallback) window_save,
NULL);
// Creating the run button
window->button_run = (GtkToolButton *) gtk_tool_button_new
(gtk_image_new_from_icon_name ("system-run",
GTK_ICON_SIZE_LARGE_TOOLBAR), _("Run"));
g_signal_connect (window->button_run, "clicked", window_run, NULL);
// Creating the options button
window->button_options = (GtkToolButton *) gtk_tool_button_new
(gtk_image_new_from_icon_name ("preferences-system",
GTK_ICON_SIZE_LARGE_TOOLBAR), _("Options"));
g_signal_connect (window->button_options, "clicked", options_new, NULL);
// Creating the help button
window->button_help = (GtkToolButton *) gtk_tool_button_new
(gtk_image_new_from_icon_name ("help-browser",
GTK_ICON_SIZE_LARGE_TOOLBAR), _("Help"));
g_signal_connect (window->button_help, "clicked", window_help, NULL);
// Creating the about button
window->button_about = (GtkToolButton *) gtk_tool_button_new
(gtk_image_new_from_icon_name ("help-about",
GTK_ICON_SIZE_LARGE_TOOLBAR), _("About"));
g_signal_connect (window->button_about, "clicked", window_about, NULL);
// Creating the exit button
window->button_exit = (GtkToolButton *) gtk_tool_button_new
(gtk_image_new_from_icon_name ("application-exit",
GTK_ICON_SIZE_LARGE_TOOLBAR), _("Exit"));
g_signal_connect_swapped (window->button_exit, "clicked",
G_CALLBACK (g_application_quit),
G_APPLICATION (application));
// Creating the buttons bar
window->bar_buttons = (GtkToolbar *) gtk_toolbar_new ();
gtk_toolbar_insert
(window->bar_buttons, GTK_TOOL_ITEM (window->button_open), 0);
gtk_toolbar_insert
(window->bar_buttons, GTK_TOOL_ITEM (window->button_save), 1);
gtk_toolbar_insert
(window->bar_buttons, GTK_TOOL_ITEM (window->button_run), 2);
gtk_toolbar_insert
(window->bar_buttons, GTK_TOOL_ITEM (window->button_options), 3);
gtk_toolbar_insert
(window->bar_buttons, GTK_TOOL_ITEM (window->button_help), 4);
gtk_toolbar_insert
(window->bar_buttons, GTK_TOOL_ITEM (window->button_about), 5);
gtk_toolbar_insert
(window->bar_buttons, GTK_TOOL_ITEM (window->button_exit), 6);
gtk_toolbar_set_style (window->bar_buttons, GTK_TOOLBAR_BOTH);
// Creating the simulator program label and entry
window->label_simulator = (GtkLabel *) gtk_label_new (_("Simulator program"));
window->button_simulator = (GtkFileChooserButton *)
gtk_file_chooser_button_new (_("Simulator program"),
GTK_FILE_CHOOSER_ACTION_OPEN);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_simulator),
_("Simulator program executable file"));
gtk_widget_set_hexpand (GTK_WIDGET (window->button_simulator), TRUE);
// Creating the evaluator program label and entry
window->check_evaluator = (GtkCheckButton *)
gtk_check_button_new_with_mnemonic (_("_Evaluator program"));
g_signal_connect (window->check_evaluator, "toggled", window_update, NULL);
window->button_evaluator = (GtkFileChooserButton *)
gtk_file_chooser_button_new (_("Evaluator program"),
GTK_FILE_CHOOSER_ACTION_OPEN);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->button_evaluator),
_("Optional evaluator program executable file"));
// Creating the results files labels and entries
window->label_result = (GtkLabel *) gtk_label_new (_("Result file"));
window->entry_result = (GtkEntry *) gtk_entry_new ();
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->entry_result), _("Best results file"));
window->label_variables = (GtkLabel *) gtk_label_new (_("Variables file"));
window->entry_variables = (GtkEntry *) gtk_entry_new ();
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->entry_variables), _("All simulated results file"));
// Creating the files grid and attaching widgets
window->grid_files = (GtkGrid *) gtk_grid_new ();
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->label_simulator),
0, 0, 1, 1);
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->button_simulator),
1, 0, 1, 1);
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->check_evaluator),
0, 1, 1, 1);
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->button_evaluator),
1, 1, 1, 1);
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->label_result),
0, 2, 1, 1);
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->entry_result),
1, 2, 1, 1);
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->label_variables),
0, 3, 1, 1);
gtk_grid_attach (window->grid_files, GTK_WIDGET (window->entry_variables),
1, 3, 1, 1);
// Creating the algorithm properties
window->label_simulations = (GtkLabel *) gtk_label_new
(_("Simulations number"));
window->spin_simulations
= (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e12, 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_simulations),
_("Number of simulations to perform for each iteration"));
gtk_widget_set_hexpand (GTK_WIDGET (window->spin_simulations), TRUE);
window->label_iterations = (GtkLabel *)
gtk_label_new (_("Iterations number"));
window->spin_iterations
= (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e6, 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_iterations), _("Number of iterations"));
g_signal_connect
(window->spin_iterations, "value-changed", window_update, NULL);
gtk_widget_set_hexpand (GTK_WIDGET (window->spin_iterations), TRUE);
window->label_tolerance = (GtkLabel *) gtk_label_new (_("Tolerance"));
window->spin_tolerance =
(GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_tolerance),
_("Tolerance to set the variable interval on the next iteration"));
window->label_bests = (GtkLabel *) gtk_label_new (_("Bests number"));
window->spin_bests
= (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e6, 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_bests),
_("Number of best simulations used to set the variable interval "
"on the next iteration"));
window->label_population
= (GtkLabel *) gtk_label_new (_("Population number"));
window->spin_population
= (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e12, 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_population),
_("Number of population for the genetic algorithm"));
gtk_widget_set_hexpand (GTK_WIDGET (window->spin_population), TRUE);
window->label_generations
= (GtkLabel *) gtk_label_new (_("Generations number"));
window->spin_generations
= (GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e6, 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_generations),
_("Number of generations for the genetic algorithm"));
window->label_mutation = (GtkLabel *) gtk_label_new (_("Mutation ratio"));
window->spin_mutation
= (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_mutation),
_("Ratio of mutation for the genetic algorithm"));
window->label_reproduction
= (GtkLabel *) gtk_label_new (_("Reproduction ratio"));
window->spin_reproduction
= (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_reproduction),
_("Ratio of reproduction for the genetic algorithm"));
window->label_adaptation = (GtkLabel *) gtk_label_new (_("Adaptation ratio"));
window->spin_adaptation
= (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_adaptation),
_("Ratio of adaptation for the genetic algorithm"));
window->label_threshold = (GtkLabel *) gtk_label_new (_("Threshold"));
window->spin_threshold = (GtkSpinButton *)
gtk_spin_button_new_with_range (-G_MAXDOUBLE, G_MAXDOUBLE,
precision[DEFAULT_PRECISION]);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_threshold),
_("Threshold in the objective function to finish the simulations"));
window->scrolled_threshold =
(GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (window->scrolled_threshold),
GTK_WIDGET (window->spin_threshold));
// gtk_widget_set_hexpand (GTK_WIDGET (window->scrolled_threshold), TRUE);
// gtk_widget_set_halign (GTK_WIDGET (window->scrolled_threshold),
// GTK_ALIGN_FILL);
// Creating the hill climbing method properties
window->check_climbing = (GtkCheckButton *)
gtk_check_button_new_with_mnemonic (_("_Hill climbing method"));
g_signal_connect (window->check_climbing, "clicked", window_update, NULL);
window->grid_climbing = (GtkGrid *) gtk_grid_new ();
window->button_climbing[0] = (GtkRadioButton *)
gtk_radio_button_new_with_mnemonic (NULL, label_climbing[0]);
gtk_grid_attach (window->grid_climbing,
GTK_WIDGET (window->button_climbing[0]), 0, 0, 1, 1);
g_signal_connect (window->button_climbing[0], "clicked", window_update, NULL);
for (i = 0; ++i < NCLIMBINGS;)
{
window->button_climbing[i] = (GtkRadioButton *)
gtk_radio_button_new_with_mnemonic
(gtk_radio_button_get_group (window->button_climbing[0]),
label_climbing[i]);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_climbing[i]),
tip_climbing[i]);
gtk_grid_attach (window->grid_climbing,
GTK_WIDGET (window->button_climbing[i]), 0, i, 1, 1);
g_signal_connect (window->button_climbing[i], "clicked", window_update,
NULL);
}
window->label_steps = (GtkLabel *) gtk_label_new (_("Steps number"));
window->spin_steps = (GtkSpinButton *)
gtk_spin_button_new_with_range (1., 1.e12, 1.);
gtk_widget_set_hexpand (GTK_WIDGET (window->spin_steps), TRUE);
window->label_estimates
= (GtkLabel *) gtk_label_new (_("Climbing estimates number"));
window->spin_estimates = (GtkSpinButton *)
gtk_spin_button_new_with_range (1., 1.e3, 1.);
window->label_relaxation
= (GtkLabel *) gtk_label_new (_("Relaxation parameter"));
window->spin_relaxation = (GtkSpinButton *)
gtk_spin_button_new_with_range (0., 2., 0.001);
gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->label_steps),
0, NCLIMBINGS, 1, 1);
gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->spin_steps),
1, NCLIMBINGS, 1, 1);
gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->label_estimates),
0, NCLIMBINGS + 1, 1, 1);
gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->spin_estimates),
1, NCLIMBINGS + 1, 1, 1);
gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->label_relaxation),
0, NCLIMBINGS + 2, 1, 1);
gtk_grid_attach (window->grid_climbing, GTK_WIDGET (window->spin_relaxation),
1, NCLIMBINGS + 2, 1, 1);
// Creating the array of algorithms
window->grid_algorithm = (GtkGrid *) gtk_grid_new ();
window->button_algorithm[0] = (GtkRadioButton *)
gtk_radio_button_new_with_mnemonic (NULL, label_algorithm[0]);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_algorithm[0]),
tip_algorithm[0]);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->button_algorithm[0]), 0, 0, 1, 1);
g_signal_connect (window->button_algorithm[0], "clicked",
window_set_algorithm, NULL);
for (i = 0; ++i < NALGORITHMS;)
{
window->button_algorithm[i] = (GtkRadioButton *)
gtk_radio_button_new_with_mnemonic
(gtk_radio_button_get_group (window->button_algorithm[0]),
label_algorithm[i]);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_algorithm[i]),
tip_algorithm[i]);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->button_algorithm[i]), 0, i, 1, 1);
g_signal_connect (window->button_algorithm[i], "clicked",
window_set_algorithm, NULL);
}
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->label_simulations),
0, NALGORITHMS, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->spin_simulations), 1, NALGORITHMS, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->label_iterations),
0, NALGORITHMS + 1, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_iterations),
1, NALGORITHMS + 1, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_tolerance),
0, NALGORITHMS + 2, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_tolerance),
1, NALGORITHMS + 2, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_bests),
0, NALGORITHMS + 3, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_bests),
1, NALGORITHMS + 3, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->label_population),
0, NALGORITHMS + 4, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_population),
1, NALGORITHMS + 4, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->label_generations),
0, NALGORITHMS + 5, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->spin_generations),
1, NALGORITHMS + 5, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_mutation),
0, NALGORITHMS + 6, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_mutation),
1, NALGORITHMS + 6, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->label_reproduction),
0, NALGORITHMS + 7, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->spin_reproduction),
1, NALGORITHMS + 7, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->label_adaptation),
0, NALGORITHMS + 8, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->spin_adaptation),
1, NALGORITHMS + 8, 1, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->check_climbing),
0, NALGORITHMS + 9, 2, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->grid_climbing),
0, NALGORITHMS + 10, 2, 1);
gtk_grid_attach (window->grid_algorithm, GTK_WIDGET (window->label_threshold),
0, NALGORITHMS + 11, 1, 1);
gtk_grid_attach (window->grid_algorithm,
GTK_WIDGET (window->scrolled_threshold),
1, NALGORITHMS + 11, 1, 1);
window->frame_algorithm = (GtkFrame *) gtk_frame_new (_("Algorithm"));
gtk_container_add (GTK_CONTAINER (window->frame_algorithm),
GTK_WIDGET (window->grid_algorithm));
// Creating the variable widgets
window->combo_variable = (GtkComboBoxText *) gtk_combo_box_text_new ();
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->combo_variable), _("Variables selector"));
window->id_variable = g_signal_connect
(window->combo_variable, "changed", window_set_variable, NULL);
window->button_add_variable = (GtkButton *)
gtk_button_new_from_icon_name ("list-add", GTK_ICON_SIZE_BUTTON);
g_signal_connect (window->button_add_variable, "clicked", window_add_variable,
NULL);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_add_variable),
_("Add variable"));
window->button_remove_variable = (GtkButton *)
gtk_button_new_from_icon_name ("list-remove", GTK_ICON_SIZE_BUTTON);
g_signal_connect (window->button_remove_variable, "clicked",
window_remove_variable, NULL);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_remove_variable),
_("Remove variable"));
window->label_variable = (GtkLabel *) gtk_label_new (_("Name"));
window->entry_variable = (GtkEntry *) gtk_entry_new ();
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->entry_variable), _("Variable name"));
gtk_widget_set_hexpand (GTK_WIDGET (window->entry_variable), TRUE);
window->id_variable_label = g_signal_connect
(window->entry_variable, "changed", window_label_variable, NULL);
window->label_min = (GtkLabel *) gtk_label_new (_("Minimum"));
window->spin_min = (GtkSpinButton *) gtk_spin_button_new_with_range
(-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_min), _("Minimum initial value of the variable"));
window->scrolled_min
= (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (window->scrolled_min),
GTK_WIDGET (window->spin_min));
g_signal_connect (window->spin_min, "value-changed",
window_rangemin_variable, NULL);
window->label_max = (GtkLabel *) gtk_label_new (_("Maximum"));
window->spin_max = (GtkSpinButton *) gtk_spin_button_new_with_range
(-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_max), _("Maximum initial value of the variable"));
window->scrolled_max
= (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (window->scrolled_max),
GTK_WIDGET (window->spin_max));
g_signal_connect (window->spin_max, "value-changed",
window_rangemax_variable, NULL);
window->check_minabs = (GtkCheckButton *)
gtk_check_button_new_with_mnemonic (_("_Absolute minimum"));
g_signal_connect (window->check_minabs, "toggled", window_update, NULL);
window->spin_minabs = (GtkSpinButton *) gtk_spin_button_new_with_range
(-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_minabs),
_("Minimum allowed value of the variable"));
window->scrolled_minabs
= (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (window->scrolled_minabs),
GTK_WIDGET (window->spin_minabs));
g_signal_connect (window->spin_minabs, "value-changed",
window_rangeminabs_variable, NULL);
window->check_maxabs = (GtkCheckButton *)
gtk_check_button_new_with_mnemonic (_("_Absolute maximum"));
g_signal_connect (window->check_maxabs, "toggled", window_update, NULL);
window->spin_maxabs = (GtkSpinButton *) gtk_spin_button_new_with_range
(-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_maxabs),
_("Maximum allowed value of the variable"));
window->scrolled_maxabs
= (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (window->scrolled_maxabs),
GTK_WIDGET (window->spin_maxabs));
g_signal_connect (window->spin_maxabs, "value-changed",
window_rangemaxabs_variable, NULL);
window->label_precision = (GtkLabel *) gtk_label_new (_("Precision digits"));
window->spin_precision = (GtkSpinButton *)
gtk_spin_button_new_with_range (0., (gdouble) DEFAULT_PRECISION, 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_precision),
_("Number of precision floating point digits\n"
"0 is for integer numbers"));
g_signal_connect (window->spin_precision, "value-changed",
window_precision_variable, NULL);
window->label_sweeps = (GtkLabel *) gtk_label_new (_("Sweeps number"));
window->spin_sweeps =
(GtkSpinButton *) gtk_spin_button_new_with_range (1., 1.e12, 1.);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->spin_sweeps),
_("Number of steps sweeping the variable"));
g_signal_connect (window->spin_sweeps, "value-changed",
window_update_variable, NULL);
window->label_bits = (GtkLabel *) gtk_label_new (_("Bits number"));
window->spin_bits
= (GtkSpinButton *) gtk_spin_button_new_with_range (1., 64., 1.);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_bits),
_("Number of bits to encode the variable"));
g_signal_connect
(window->spin_bits, "value-changed", window_update_variable, NULL);
window->label_step = (GtkLabel *) gtk_label_new (_("Step size"));
window->spin_step = (GtkSpinButton *) gtk_spin_button_new_with_range
(-G_MAXDOUBLE, G_MAXDOUBLE, precision[DEFAULT_PRECISION]);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_step),
_("Initial step size for the hill climbing method"));
window->scrolled_step
= (GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (window->scrolled_step),
GTK_WIDGET (window->spin_step));
g_signal_connect
(window->spin_step, "value-changed", window_step_variable, NULL);
window->grid_variable = (GtkGrid *) gtk_grid_new ();
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->combo_variable), 0, 0, 2, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->button_add_variable), 2, 0, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->button_remove_variable), 3, 0, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->label_variable), 0, 1, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->entry_variable), 1, 1, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->label_min), 0, 2, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->scrolled_min), 1, 2, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->label_max), 0, 3, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->scrolled_max), 1, 3, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->check_minabs), 0, 4, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->scrolled_minabs), 1, 4, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->check_maxabs), 0, 5, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->scrolled_maxabs), 1, 5, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->label_precision), 0, 6, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->spin_precision), 1, 6, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->label_sweeps), 0, 7, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->spin_sweeps), 1, 7, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->label_bits), 0, 8, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->spin_bits), 1, 8, 3, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->label_step), 0, 9, 1, 1);
gtk_grid_attach (window->grid_variable,
GTK_WIDGET (window->scrolled_step), 1, 9, 3, 1);
window->frame_variable = (GtkFrame *) gtk_frame_new (_("Variable"));
gtk_container_add (GTK_CONTAINER (window->frame_variable),
GTK_WIDGET (window->grid_variable));
// Creating the experiment widgets
window->combo_experiment = (GtkComboBoxText *) gtk_combo_box_text_new ();
gtk_widget_set_tooltip_text (GTK_WIDGET (window->combo_experiment),
_("Experiment selector"));
window->id_experiment = g_signal_connect
(window->combo_experiment, "changed", window_set_experiment, NULL);
window->button_add_experiment = (GtkButton *)
gtk_button_new_from_icon_name ("list-add", GTK_ICON_SIZE_BUTTON);
g_signal_connect
(window->button_add_experiment, "clicked", window_add_experiment, NULL);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_add_experiment),
_("Add experiment"));
window->button_remove_experiment = (GtkButton *)
gtk_button_new_from_icon_name ("list-remove", GTK_ICON_SIZE_BUTTON);
g_signal_connect (window->button_remove_experiment, "clicked",
window_remove_experiment, NULL);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_remove_experiment),
_("Remove experiment"));
window->label_experiment
= (GtkLabel *) gtk_label_new (_("Experimental data file"));
window->button_experiment = (GtkFileChooserButton *)
gtk_file_chooser_button_new (_("Experimental data file"),
GTK_FILE_CHOOSER_ACTION_OPEN);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_experiment),
_("Experimental data file"));
window->id_experiment_name
= g_signal_connect (window->button_experiment, "selection-changed",
window_name_experiment, NULL);
gtk_widget_set_hexpand (GTK_WIDGET (window->button_experiment), TRUE);
window->label_weight = (GtkLabel *) gtk_label_new (_("Weight"));
window->spin_weight
= (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1., 0.001);
gtk_widget_set_tooltip_text
(GTK_WIDGET (window->spin_weight),
_("Weight factor to build the objective function"));
g_signal_connect
(window->spin_weight, "value-changed", window_weight_experiment, NULL);
window->grid_experiment = (GtkGrid *) gtk_grid_new ();
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->combo_experiment), 0, 0, 2, 1);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->button_add_experiment), 2, 0, 1, 1);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->button_remove_experiment), 3, 0, 1, 1);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->label_experiment), 0, 1, 1, 1);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->button_experiment), 1, 1, 3, 1);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->label_weight), 0, 2, 1, 1);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->spin_weight), 1, 2, 3, 1);
for (i = 0; i < MAX_NINPUTS; ++i)
{
snprintf (buffer3, 64, "%s %u", _("Input template"), i + 1);
window->check_template[i] = (GtkCheckButton *)
gtk_check_button_new_with_label (buffer3);
window->id_template[i]
= g_signal_connect (window->check_template[i], "toggled",
window_inputs_experiment, NULL);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->check_template[i]), 0, 3 + i, 1, 1);
window->button_template[i] = (GtkFileChooserButton *)
gtk_file_chooser_button_new (_("Input template"),
GTK_FILE_CHOOSER_ACTION_OPEN);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_template[i]),
_("Experimental input template file"));
window->id_input[i] =
g_signal_connect_swapped (window->button_template[i],
"selection-changed",
(GCallback) window_template_experiment,
(void *) (size_t) i);
gtk_grid_attach (window->grid_experiment,
GTK_WIDGET (window->button_template[i]), 1, 3 + i, 3, 1);
}
window->frame_experiment = (GtkFrame *) gtk_frame_new (_("Experiment"));
gtk_container_add (GTK_CONTAINER (window->frame_experiment),
GTK_WIDGET (window->grid_experiment));
// Creating the error norm widgets
window->frame_norm = (GtkFrame *) gtk_frame_new (_("Error norm"));
window->grid_norm = (GtkGrid *) gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window->frame_norm),
GTK_WIDGET (window->grid_norm));
window->button_norm[0] = (GtkRadioButton *)
gtk_radio_button_new_with_mnemonic (NULL, label_norm[0]);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_norm[0]),
tip_norm[0]);
gtk_grid_attach (window->grid_norm,
GTK_WIDGET (window->button_norm[0]), 0, 0, 1, 1);
g_signal_connect (window->button_norm[0], "clicked", window_update, NULL);
for (i = 0; ++i < NNORMS;)
{
window->button_norm[i] = (GtkRadioButton *)
gtk_radio_button_new_with_mnemonic
(gtk_radio_button_get_group (window->button_norm[0]), label_norm[i]);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->button_norm[i]),
tip_norm[i]);
gtk_grid_attach (window->grid_norm,
GTK_WIDGET (window->button_norm[i]), 0, i, 1, 1);
g_signal_connect (window->button_norm[i], "clicked", window_update, NULL);
}
window->label_p = (GtkLabel *) gtk_label_new (_("P parameter"));
gtk_grid_attach (window->grid_norm, GTK_WIDGET (window->label_p), 1, 1, 1, 1);
window->spin_p = (GtkSpinButton *)
gtk_spin_button_new_with_range (-G_MAXDOUBLE, G_MAXDOUBLE, 0.01);
gtk_widget_set_tooltip_text (GTK_WIDGET (window->spin_p),
_("P parameter for the P error norm"));
window->scrolled_p =
(GtkScrolledWindow *) gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (window->scrolled_p),
GTK_WIDGET (window->spin_p));
gtk_widget_set_hexpand (GTK_WIDGET (window->scrolled_p), TRUE);
gtk_widget_set_halign (GTK_WIDGET (window->scrolled_p), GTK_ALIGN_FILL);
gtk_grid_attach (window->grid_norm, GTK_WIDGET (window->scrolled_p),
1, 2, 1, 2);
// Creating the grid and attaching the widgets to the grid
window->grid = (GtkGrid *) gtk_grid_new ();
gtk_grid_attach (window->grid, GTK_WIDGET (window->bar_buttons), 0, 0, 3, 1);
gtk_grid_attach (window->grid, GTK_WIDGET (window->grid_files), 0, 1, 1, 1);
gtk_grid_attach (window->grid,
GTK_WIDGET (window->frame_algorithm), 0, 2, 1, 1);
gtk_grid_attach (window->grid,
GTK_WIDGET (window->frame_variable), 1, 2, 1, 1);
gtk_grid_attach (window->grid,
GTK_WIDGET (window->frame_experiment), 2, 2, 1, 1);
gtk_grid_attach (window->grid, GTK_WIDGET (window->frame_norm), 1, 1, 2, 1);
gtk_container_add (GTK_CONTAINER (window->window), GTK_WIDGET (window->grid));
// Setting the window logo
window->logo = gdk_pixbuf_new_from_xpm_data (logo);
gtk_window_set_icon (window->window, window->logo);
// Showing the window
gtk_widget_show_all (GTK_WIDGET (window->window));
// In GTK+ 3.16 and 3.18 the default scrolled size is wrong
#if GTK_MINOR_VERSION >= 16
gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_min), -1, 40);
gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_max), -1, 40);
gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_minabs), -1, 40);
gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_maxabs), -1, 40);
gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_step), -1, 40);
gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_p), -1, 40);
gtk_widget_set_size_request (GTK_WIDGET (window->scrolled_threshold), -1, 40);
#endif
// Reading initial example
input_new ();
buffer2 = g_get_current_dir ();
buffer = g_build_filename (buffer2, "..", "tests", "test1", INPUT_FILE, NULL);
g_free (buffer2);
window_read (buffer);
g_free (buffer);
#if DEBUG_INTERFACE
fprintf (stderr, "window_new: start\n");
#endif
}
| {
"alphanum_fraction": 0.6590936388,
"avg_line_length": 39.3868267831,
"ext": "c",
"hexsha": "95aba2601cddfdd31c0fb7e8d65d8aeebfa8f8f2",
"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": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/mpcotool",
"max_forks_repo_path": "4.0.5/interface.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/mpcotool",
"max_issues_repo_path": "4.0.5/interface.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/mpcotool",
"max_stars_repo_path": "4.0.5/interface.c",
"max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z",
"num_tokens": 26679,
"size": 108235
} |
#ifndef EV3PLOTTER_MESSAGEQUEUE_H
#define EV3PLOTTER_MESSAGEQUEUE_H
#include <gsl/span>
#include <memory>
#include <string_view>
#include <type_safe/flag_set.hpp>
namespace ev3plotter {
class message_queue {
public:
enum class option { read, write, non_blocking, remove_on_destruction, _flag_set_size };
enum class send_result { success, failure_queue_full, failure };
enum class receive_result { success, failure_no_messages, failure };
message_queue(std::string_view name, std::size_t max_message_size, type_safe::flag_set<option> options);
~message_queue();
send_result send(std::string_view msg);
receive_result receive(gsl::span<char>& buffer);
std::size_t message_size() const noexcept;
private:
class impl;
std::unique_ptr<impl> impl_;
};
} // namespace ev3plotter
#endif // EV3PLOTTER_MESSAGEQUEUE_H | {
"alphanum_fraction": 0.7494199536,
"avg_line_length": 25.3529411765,
"ext": "h",
"hexsha": "b2d821e6ba9491162f25f2ca93515e1d2021ff63",
"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": "5c3aae6c2bc4cee2b5798fb26f35dfe81e2e503c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "biocomp/ev3dev-lang-cpp2",
"max_forks_repo_path": "mqueue/mqueue/message_queue.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c3aae6c2bc4cee2b5798fb26f35dfe81e2e503c",
"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": "biocomp/ev3dev-lang-cpp2",
"max_issues_repo_path": "mqueue/mqueue/message_queue.h",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5c3aae6c2bc4cee2b5798fb26f35dfe81e2e503c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "biocomp/ev3dev-lang-cpp2",
"max_stars_repo_path": "mqueue/mqueue/message_queue.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 207,
"size": 862
} |
#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_nrm2 (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int N = 1;
float X[] = { 0.317f };
int incX = -1;
float expected = 0.0f;
float f;
f = cblas_snrm2(N, X, incX);
gsl_test_rel(f, expected, flteps, "snrm2(case 28)");
};
{
int N = 1;
double X[] = { 0.071 };
int incX = -1;
double expected = 0;
double f;
f = cblas_dnrm2(N, X, incX);
gsl_test_rel(f, expected, dbleps, "dnrm2(case 29)");
};
{
int N = 1;
float X[] = { 0.776f, 0.983f };
int incX = -1;
float expected = 0.0f;
float f;
f = cblas_scnrm2(N, X, incX);
gsl_test_rel(f, expected, flteps, "scnrm2(case 30)");
};
{
int N = 1;
double X[] = { 0.549, -0.354 };
int incX = -1;
double expected = 0;
double f;
f = cblas_dznrm2(N, X, incX);
gsl_test_rel(f, expected, dbleps, "dznrm2(case 31)");
};
{
int N = 2;
float X[] = { 0.14f, -0.632f };
int incX = 1;
float expected = 0.647320631527f;
float f;
f = cblas_snrm2(N, X, incX);
gsl_test_rel(f, expected, flteps, "snrm2(case 32)");
};
{
int N = 2;
double X[] = { 0.696, -0.804 };
int incX = 1;
double expected = 1.06340584915;
double f;
f = cblas_dnrm2(N, X, incX);
gsl_test_rel(f, expected, dbleps, "dnrm2(case 33)");
};
{
int N = 2;
float X[] = { 0.281f, -0.063f, 0.367f, 0.232f };
int incX = 1;
float expected = 0.521001919382f;
float f;
f = cblas_scnrm2(N, X, incX);
gsl_test_rel(f, expected, flteps, "scnrm2(case 34)");
};
{
int N = 2;
double X[] = { -0.359, -0.76, -0.906, -0.108 };
int incX = 1;
double expected = 1.24055672986;
double f;
f = cblas_dznrm2(N, X, incX);
gsl_test_rel(f, expected, dbleps, "dznrm2(case 35)");
};
{
int N = 2;
float X[] = { 0.918f, -0.126f };
int incX = -1;
float expected = 0.0f;
float f;
f = cblas_snrm2(N, X, incX);
gsl_test_rel(f, expected, flteps, "snrm2(case 36)");
};
{
int N = 2;
double X[] = { 0.217, -0.588 };
int incX = -1;
double expected = 0;
double f;
f = cblas_dnrm2(N, X, incX);
gsl_test_rel(f, expected, dbleps, "dnrm2(case 37)");
};
{
int N = 2;
float X[] = { 0.31f, 0.059f, -0.442f, 0.987f };
int incX = -1;
float expected = 0.0f;
float f;
f = cblas_scnrm2(N, X, incX);
gsl_test_rel(f, expected, flteps, "scnrm2(case 38)");
};
{
int N = 2;
double X[] = { 0.609, 0.615, -0.143, -0.957 };
int incX = -1;
double expected = 0;
double f;
f = cblas_dznrm2(N, X, incX);
gsl_test_rel(f, expected, dbleps, "dznrm2(case 39)");
};
}
| {
"alphanum_fraction": 0.54595186,
"avg_line_length": 19.0416666667,
"ext": "c",
"hexsha": "020cde02e50d4d3cad55c928972c7687df523962",
"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_nrm2.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_nrm2.c",
"max_line_length": 56,
"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_nrm2.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": 1138,
"size": 2742
} |
#if MKL_FOUND
#include <mkl.h>
#else
#if BLAS_FOUND
#include <cblas.h>
#endif
#endif
inline void sgemm(bool transA,
bool transB,
int rows_a,
int rows_b,
int width,
float alpha,
float* a,
int lda,
float* b,
int ldb,
float beta,
float* c,
int ldc) {
#if BLAS_FOUND
cblas_sgemm(CblasRowMajor,
transA ? CblasTrans : CblasNoTrans,
transB ? CblasTrans : CblasNoTrans,
rows_a,
rows_b,
width,
alpha,
a,
lda,
b,
ldb,
beta,
c,
ldc);
#else
transA; transB; rows_a; rows_b; width; alpha; a; lda; b; ldb; beta; c; ldc; // make compiler happy
ABORT("Marian must be compiled with a BLAS library");
#endif
}
| {
"alphanum_fraction": 0.424,
"avg_line_length": 23.8095238095,
"ext": "h",
"hexsha": "a591fdd26a9b22d793fa14c3674b9324dcc75c93",
"lang": "C",
"max_forks_count": 192,
"max_forks_repo_forks_event_max_datetime": "2022-03-28T05:33:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-06-27T10:17:26.000Z",
"max_forks_repo_head_hexsha": "2ef018e829e08a688eb02d3a56f29d23b284b901",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "delong-coder/marian-dev",
"max_forks_repo_path": "src/tensors/cpu/prod_blas.h",
"max_issues_count": 732,
"max_issues_repo_head_hexsha": "2ef018e829e08a688eb02d3a56f29d23b284b901",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T10:26:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-21T15:32:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "delong-coder/marian-dev",
"max_issues_repo_path": "src/tensors/cpu/prod_blas.h",
"max_line_length": 102,
"max_stars_count": 829,
"max_stars_repo_head_hexsha": "2ef018e829e08a688eb02d3a56f29d23b284b901",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "delong-coder/marian-dev",
"max_stars_repo_path": "src/tensors/cpu/prod_blas.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T17:24:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-05T12:14:34.000Z",
"num_tokens": 224,
"size": 1000
} |
#include<stdio.h>
#include<sys/time.h>
#include <stdlib.h>
#include <cblas.h>
#include <omp.h>
void SGEMM_NT_MP(float *C, float *A, float *B, long M, long N, long K,
long LN, long LK, float *SB, long k_tag)
{
asm volatile(
".macro PACK_KERNEL5x4_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldr q5, [x16], #16 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" prfm PLDL1KEEP, [x17, #128] \n"
" fmul v12.4s, v0.4s, v5.4s \n"
" ldr q2, [x13], #16 \n"
" fmul v13.4s, v1.4s, v5.4s \n"
" ldr q3, [x14], #16 \n"
" fmul v14.4s, v2.4s, v5.4s \n"
" ldr q4, [x15], #16 \n"
" fmul v15.4s, v3.4s, v5.4s \n"
" ldr q6, [x17], #16 \n"
" fmul v16.4s, v4.4s, v5.4s \n"
" ldr q7, [x18], #16 \n"
" fmul v17.4s, v0.4s, v6.4s \n"
" ldr q8, [x19], #16 \n"
" ldr q9, [x11], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[0], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmul v18.4s, v1.4s, v6.4s \n"
" fmul v19.4s, v2.4s, v6.4s \n"
" fmul v20.4s, v3.4s, v6.4s \n"
" fmul v21.4s, v4.4s, v6.4s \n"
" ldr q10, [x12], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[1], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmul v22.4s, v0.4s, v7.4s \n"
" fmul v23.4s, v1.4s, v7.4s \n"
" fmul v24.4s, v2.4s, v7.4s \n"
" fmul v25.4s, v3.4s, v7.4s \n"
" fmul v26.4s, v4.4s, v7.4s \n"
" ldr q11, [x13], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[2], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmul v27.4s, v0.4s, v8.4s \n"
" ldr q0, [x14], #16 \n"
" fmul v28.4s, v1.4s, v8.4s \n"
" ldr q1, [x15], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[3], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" ldr q5, [x16], #16 \n"
" fmul v29.4s, v2.4s, v8.4s \n"
" fmul v30.4s, v3.4s, v8.4s \n"
" fmul v31.4s, v4.4s, v8.4s \n"
".endm \n"
".macro PACK_KERNEL5x4_K0 \n"
" prfm PLDL1KEEP, [x16, #128] \n"
" ldr q6, [x17], #16 \n"
" fmla v12.4s, v0.4s, v5.4s \n"
" fmla v13.4s, v1.4s, v5.4s \n"
" prfm PLDL1KEEP, [x17, #128] \n"
" ldr q7, [x18], #16 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v14.4s, v2.4s, v5.4s \n"
" fmla v15.4s, v3.4s, v5.4s \n"
" fmla v16.4s, v4.4s, v5.4s \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" ldr q8, [x19], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[0], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v17.4s, v0.4s, v6.4s \n"
" fmla v18.4s, v1.4s, v6.4s \n"
" fmla v19.4s, v2.4s, v6.4s \n"
" fmla v20.4s, v3.4s, v6.4s \n"
" fmla v21.4s, v4.4s, v6.4s \n"
" ldr q9, [x11], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[1], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v22.4s, v0.4s, v7.4s \n"
" fmla v23.4s, v1.4s, v7.4s \n"
" ldr q10, [x12], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[2], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v24.4s, v2.4s, v7.4s \n"
" fmla v25.4s, v3.4s, v7.4s \n"
" fmla v26.4s, v4.4s, v7.4s \n"
" ldr q11, [x13], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[3], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v27.4s, v0.4s, v8.4s \n"
" ldr q5, [x16], #16 \n"
" ldr q0, [x14], #16 \n"
" fmla v28.4s, v1.4s, v8.4s \n"
" ldr q1, [x15], #16 \n"
" fmla v29.4s, v2.4s, v8.4s \n"
" fmla v30.4s, v3.4s, v8.4s \n"
" fmla v31.4s, v4.4s, v8.4s \n"
".endm \n"
".macro PACK_KERNEL5x4_K1 \n"
" prfm PLDL1KEEP, [x18, #128] \n"
" ldr q6, [x17], #16 \n"
" fmla v12.4s, v9.4s, v5.4s \n"
" fmla v13.4s, v10.4s, v5.4s \n"
" prfm PLDL1KEEP, [x19, #128] \n"
" ldr q7, [x18], #16 \n"
" fmla v14.4s, v11.4s, v5.4s \n"
" fmla v15.4s, v0.4s, v5.4s \n"
" fmla v16.4s, v1.4s, v5.4s \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" ldr q8, [x19], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[0], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v17.4s, v9.4s, v6.4s \n"
" fmla v18.4s, v10.4s, v6.4s \n"
" ldr q2, [x13], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[1], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmla v19.4s, v11.4s, v6.4s \n"
" fmla v20.4s, v0.4s, v6.4s \n"
" fmla v21.4s, v1.4s, v6.4s \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" ldr q3, [x14], #16 \n"
" fmla v25.4s, v0.4s, v7.4s \n"
" fmla v26.4s, v1.4s, v7.4s \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[2], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v30.4s, v0.4s, v8.4s \n"
" ldr q0, [x11], #16 \n"
" fmla v31.4s, v1.4s, v8.4s \n"
" ldr q1, [x12], #16 \n"
" fmla v22.4s, v9.4s, v7.4s \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[3], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" ldr q5, [x16], #16 \n"
" fmla v23.4s, v10.4s, v7.4s \n"
" fmla v24.4s, v11.4s, v7.4s \n"
" ldr q4, [x15], #16 \n"
" fmla v27.4s, v9.4s, v8.4s \n"
" fmla v28.4s, v10.4s, v8.4s \n"
" fmla v29.4s, v11.4s, v8.4s \n"
".endm \n"
".macro PACK_KERNEL5x4_END_K \n"
" ldr q6, [x17], #16 \n"
" fmla v12.4s, v9.4s, v5.4s \n"
" fmla v13.4s, v10.4s, v5.4s \n"
" ldr q7, [x18], #16 \n"
" fmla v14.4s, v11.4s, v5.4s \n"
" fmla v15.4s, v0.4s, v5.4s \n"
" fmla v16.4s, v1.4s, v5.4s \n"
" ldr q8, [x19], #16 \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[0], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v17.4s, v9.4s, v6.4s \n"
" faddp v12.4s, v12.4s, v17.4s \n"
" fmla v18.4s, v10.4s, v6.4s \n"
" faddp v13.4s, v13.4s, v18.4s \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[1], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v19.4s, v11.4s, v6.4s \n"
" faddp v14.4s, v14.4s, v19.4s \n"
" fmla v20.4s, v0.4s, v6.4s \n"
" faddp v15.4s, v15.4s, v20.4s \n"
" fmla v21.4s, v1.4s, v6.4s \n"
" faddp v16.4s, v16.4s, v21.4s \n"
" fmla v25.4s, v0.4s, v7.4s \n"
" fmla v26.4s, v1.4s, v7.4s \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[2], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v30.4s, v0.4s, v8.4s \n"
" faddp v25.4s, v25.4s, v30.4s \n"
" fmla v31.4s, v1.4s, v8.4s \n"
" faddp v26.4s, v26.4s, v31.4s \n"
" fmla v22.4s, v9.4s, v7.4s \n"
" st4 {v5.s, v6.s, v7.s, v8.s}[3], [x24] \n"
" add x24, x24, x8, lsl #2 \n"
" fmla v23.4s, v10.4s, v7.4s \n"
" fmla v24.4s, v11.4s, v7.4s \n"
" faddp v15.4s, v15.4s, v25.4s \n"
" faddp v16.4s, v16.4s, v26.4s \n"
" fmla v27.4s, v9.4s, v8.4s \n"
" faddp v22.4s, v22.4s, v27.4s \n"
" fmla v28.4s, v10.4s, v8.4s \n"
" faddp v23.4s, v23.4s, v28.4s \n"
" fmla v29.4s, v11.4s, v8.4s \n"
" faddp v24.4s, v24.4s, v29.4s \n"
" faddp v12.4s, v12.4s, v22.4s \n"
" faddp v13.4s, v13.4s, v23.4s \n"
" faddp v14.4s, v14.4s, v24.4s \n"
".endm \n"
".macro PACKB_ADD_C \n"
" ldr q0, [x25] \n"
" ldr q1, [x26] \n"
" fadd v12.4s, v12.4s, v0.4s \n"
" ldr q2, [x27] \n"
" fadd v13.4s, v13.4s, v1.4s \n"
" ldr q3, [x28] \n"
" fadd v14.4s, v14.4s, v2.4s \n"
" ldr q4, [x29] \n"
" fadd v15.4s, v15.4s, v3.4s \n"
" fadd v16.4s, v16.4s, v4.4s \n"
".endm \n"
".macro SAVE5x4 \n"
" subs x7, x7, #1 \n"
" str q12, [x25], #16 \n"
" str q13, [x26], #16 \n"
" str q14, [x27], #16 \n"
" str q15, [x28], #16 \n"
" str q16, [x29], #16 \n"
".endm \n"
".macro ADD_C \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" prfm PLDL1KEEP, [x29, #64] \n"
" ldp q0, q1, [x25] \n"
" fadd v12.4s, v12.4s, v0.4s \n"
" ldp q2, q3, [x25, #32] \n"
" fadd v13.4s, v13.4s, v1.4s \n"
" fadd v22.4s, v2.4s, v22.4s \n"
" ldp q4, q5, [x26] \n"
" fadd v23.4s, v3.4s, v23.4s \n"
" fadd v14.4s, v4.4s, v14.4s \n"
" ldp q6, q7, [x26, #32] \n"
" fadd v15.4s, v5.4s, v15.4s \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" prfm PLDL1KEEP, [x29, #64] \n"
" fadd v24.4s, v6.4s, v24.4s \n"
" ldp q8, q9, [x27] \n"
" fadd v25.4s, v7.4s, v25.4s \n"
" fadd v16.4s, v8.4s, v16.4s \n"
" ldp q10, q11, [x27, #32] \n"
" fadd v17.4s, v9.4s, v17.4s \n"
" fadd v26.4s, v10.4s, v26.4s \n"
" ldp q0, q1, [x28] \n"
" fadd v27.4s, v11.4s, v27.4s \n"
" fadd v18.4s, v0.4s, v18.4s \n"
" ldp q2, q3, [x28, #32] \n"
" fadd v19.4s, v1.4s, v19.4s \n"
" fadd v28.4s, v2.4s, v28.4s \n"
" ldp q4, q5, [x29] \n"
" fadd v29.4s, v3.4s, v29.4s \n"
" fadd v20.4s, v4.4s, v20.4s \n"
" ldp q6, q7, [x29, #32] \n"
" fadd v21.4s, v5.4s, v21.4s \n"
" fadd v30.4s, v30.4s, v6.4s \n"
" fadd v31.4s, v31.4s, v7.4s \n"
".endm \n"
".macro SAVE5x16 \n"
" subs x21, x21, #1 \n"
" stp q12, q13, [x25] \n"
" stp q14, q15, [x26] \n"
" stp q16, q17, [x27] \n"
" stp q18, q19, [x28] \n"
" stp q20, q21, [x29] \n"
// " add x10, x10, x9 \n"
" add x10, x10, x6, lsl #4 \n"
" add x10, x10, x6, lsl #2 \n"
" stp q22, q23, [x25, #32] \n"
" add x25, x29, x9, lsl #2 \n"
" stp q24, q25, [x26, #32] \n"
" add x26, x29, x9, lsl #3 \n"
" stp q26, q27, [x27, #32] \n"
" add x27, x25, x9, lsl #3 \n"
" stp q28, q29, [x28, #32] \n"
" add x28, x26, x9, lsl #3 \n"
" stp q30, q31, [x29, #32] \n"
" add x29, x27, x9, lsl #3 \n"
".endm \n"
".macro KERNEL5x16_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" ldr q2, [x13], #16 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
" ldr q3, [x14], #16 \n"
" fmul v16.4s, v8.4s, v2.s[0] \n"
" fmul v17.4s, v9.4s, v2.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldr q4, [x15], #16 \n"
" fmul v18.4s, v8.4s, v3.s[0] \n"
" fmul v19.4s, v9.4s, v3.s[0] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v20.4s, v8.4s, v4.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmul v21.4s, v9.4s, v4.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmul v22.4s, v10.4s, v0.s[0] \n"
" fmul v23.4s, v11.4s, v0.s[0] \n"
" fmul v24.4s, v10.4s, v1.s[0] \n"
" fmul v25.4s, v11.4s, v1.s[0] \n"
" fmul v26.4s, v10.4s, v2.s[0] \n"
" fmul v27.4s, v11.4s, v2.s[0] \n"
" ldr q5, [x11], #16 \n"
" fmul v28.4s, v10.4s, v3.s[0] \n"
" fmul v29.4s, v11.4s, v3.s[0] \n"
" fmul v30.4s, v10.4s, v4.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmul v31.4s, v11.4s, v4.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
" fmla v16.4s, v8.4s, v2.s[0] \n"
" fmla v17.4s, v9.4s, v2.s[0] \n"
" fmla v18.4s, v8.4s, v3.s[0] \n"
" fmla v19.4s, v9.4s, v3.s[0] \n"
" fmla v20.4s, v8.4s, v4.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v4.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[0] \n"
" fmla v23.4s, v11.4s, v0.s[0] \n"
" fmla v24.4s, v10.4s, v1.s[0] \n"
" fmla v25.4s, v11.4s, v1.s[0] \n"
" fmla v26.4s, v10.4s, v2.s[0] \n"
" fmla v27.4s, v11.4s, v2.s[0] \n"
" ldr q5, [x11], #16 \n" //
" fmla v28.4s, v10.4s, v3.s[0] \n"
" fmla v29.4s, v11.4s, v3.s[0] \n"
" fmla v30.4s, v10.4s, v4.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmla v31.4s, v11.4s, v4.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v8.4s, v0.s[1] \n"
" fmla v13.4s, v9.4s, v0.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[1] \n"
" fmla v15.4s, v9.4s, v1.s[1] \n"
" fmla v16.4s, v8.4s, v2.s[1] \n"
" fmla v17.4s, v9.4s, v2.s[1] \n"
" fmla v18.4s, v8.4s, v3.s[1] \n"
" fmla v19.4s, v9.4s, v3.s[1] \n"
" fmla v20.4s, v8.4s, v4.s[1] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v4.s[1] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[1] \n"
" fmla v23.4s, v11.4s, v0.s[1] \n"
" fmla v24.4s, v10.4s, v1.s[1] \n"
" fmla v25.4s, v11.4s, v1.s[1] \n"
" fmla v26.4s, v10.4s, v2.s[1] \n"
" fmla v27.4s, v11.4s, v2.s[1] \n"
" ldr q6, [x12], #16 \n"
" fmla v28.4s, v10.4s, v3.s[1] \n"
" fmla v29.4s, v11.4s, v3.s[1] \n"
" fmla v30.4s, v10.4s, v4.s[1] \n"
" ldr q10, [x24], #16 \n"
" fmla v31.4s, v11.4s, v4.s[1] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K2 \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
" fmla v16.4s, v8.4s, v2.s[2] \n"
" fmla v17.4s, v9.4s, v2.s[2] \n"
" fmla v18.4s, v8.4s, v3.s[2] \n"
" fmla v19.4s, v9.4s, v3.s[2] \n"
" fmla v20.4s, v8.4s, v4.s[2] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v4.s[2] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[2] \n"
" fmla v23.4s, v11.4s, v0.s[2] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmla v24.4s, v10.4s, v1.s[2] \n"
" fmla v25.4s, v11.4s, v1.s[2] \n"
" fmla v26.4s, v10.4s, v2.s[2] \n"
" fmla v27.4s, v11.4s, v2.s[2] \n"
" ldr q7, [x13], #16 \n" //
" fmla v28.4s, v10.4s, v3.s[2] \n"
" fmla v29.4s, v11.4s, v3.s[2] \n"
" fmla v30.4s, v10.4s, v4.s[2] \n"
" ldr q10, [x24], #16 \n"
" fmla v31.4s, v11.4s, v4.s[2] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K3 \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[3] \n"
" fmla v15.4s, v9.4s, v1.s[3] \n"
" fmla v16.4s, v8.4s, v2.s[3] \n"
" fmla v17.4s, v9.4s, v2.s[3] \n"
" fmla v18.4s, v8.4s, v3.s[3] \n"
" fmla v19.4s, v9.4s, v3.s[3] \n"
" fmla v20.4s, v8.4s, v4.s[3] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v4.s[3] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x14], #16 \n"
" fmla v24.4s, v10.4s, v1.s[3] \n"
" fmla v25.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x15], #16 \n"
" fmla v26.4s, v10.4s, v2.s[3] \n"
" fmla v27.4s, v11.4s, v2.s[3] \n"
" fmla v28.4s, v10.4s, v3.s[3] \n"
" fmla v29.4s, v11.4s, v3.s[3] \n"
" fmla v30.4s, v10.4s, v4.s[3] \n"
" ldr q10, [x24], #16 \n"
" fmla v31.4s, v11.4s, v4.s[3] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K4 \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmla v12.4s, v8.4s, v5.s[0] \n"
" fmla v13.4s, v9.4s, v5.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v6.s[0] \n"
" fmla v15.4s, v9.4s, v6.s[0] \n"
" fmla v16.4s, v8.4s, v7.s[0] \n"
" fmla v17.4s, v9.4s, v7.s[0] \n"
" fmla v18.4s, v8.4s, v0.s[0] \n"
" fmla v19.4s, v9.4s, v0.s[0] \n"
" fmla v20.4s, v8.4s, v1.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v1.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v5.s[0] \n"
" fmla v23.4s, v11.4s, v5.s[0] \n"
" fmla v24.4s, v10.4s, v6.s[0] \n"
" fmla v25.4s, v11.4s, v6.s[0] \n"
" fmla v26.4s, v10.4s, v7.s[0] \n"
" fmla v27.4s, v11.4s, v7.s[0] \n"
" ldr q2, [x13], #16 \n" //
" fmla v28.4s, v10.4s, v0.s[0] \n"
" fmla v29.4s, v11.4s, v0.s[0] \n"
" fmla v30.4s, v10.4s, v1.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmla v31.4s, v11.4s, v1.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K5 \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmla v12.4s, v8.4s, v5.s[1] \n"
" fmla v13.4s, v9.4s, v5.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v6.s[1] \n"
" fmla v15.4s, v9.4s, v6.s[1] \n"
" fmla v16.4s, v8.4s, v7.s[1] \n"
" fmla v17.4s, v9.4s, v7.s[1] \n"
" fmla v18.4s, v8.4s, v0.s[1] \n"
" fmla v19.4s, v9.4s, v0.s[1] \n"
" fmla v20.4s, v8.4s, v1.s[1] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v1.s[1] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v5.s[1] \n"
" fmla v23.4s, v11.4s, v5.s[1] \n"
" fmla v24.4s, v10.4s, v6.s[1] \n"
" fmla v25.4s, v11.4s, v6.s[1] \n"
" fmla v26.4s, v10.4s, v7.s[1] \n"
" fmla v27.4s, v11.4s, v7.s[1] \n"
" ldr q3, [x14], #16 \n"
" fmla v28.4s, v10.4s, v0.s[1] \n"
" fmla v29.4s, v11.4s, v0.s[1] \n"
" fmla v30.4s, v10.4s, v1.s[1] \n"
" ldr q10, [x24], #16 \n"
" fmla v31.4s, v11.4s, v1.s[1] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K6 \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" fmla v12.4s, v8.4s, v5.s[2] \n"
" fmla v13.4s, v9.4s, v5.s[2] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v6.s[2] \n"
" fmla v15.4s, v9.4s, v6.s[2] \n"
" fmla v16.4s, v8.4s, v7.s[2] \n"
" fmla v17.4s, v9.4s, v7.s[2] \n"
" fmla v18.4s, v8.4s, v0.s[2] \n"
" fmla v19.4s, v9.4s, v0.s[2] \n"
" fmla v20.4s, v8.4s, v1.s[2] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v1.s[2] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v5.s[2] \n"
" fmla v23.4s, v11.4s, v5.s[2] \n"
" fmla v24.4s, v10.4s, v6.s[2] \n"
" fmla v25.4s, v11.4s, v6.s[2] \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v26.4s, v10.4s, v7.s[2] \n"
" fmla v27.4s, v11.4s, v7.s[2] \n"
" ldr q4, [x15], #16 \n" //
" fmla v28.4s, v10.4s, v0.s[2] \n"
" fmla v29.4s, v11.4s, v0.s[2] \n"
" fmla v30.4s, v10.4s, v1.s[2] \n"
" ldr q10, [x24], #16 \n"
" fmla v31.4s, v11.4s, v1.s[2] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_K7 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v8.4s, v5.s[3] \n"
" fmla v13.4s, v9.4s, v5.s[3] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v6.s[3] \n"
" fmla v15.4s, v9.4s, v6.s[3] \n"
" fmla v16.4s, v8.4s, v7.s[3] \n"
" fmla v17.4s, v9.4s, v7.s[3] \n"
" fmla v18.4s, v8.4s, v0.s[3] \n"
" fmla v19.4s, v9.4s, v0.s[3] \n"
" fmla v20.4s, v8.4s, v1.s[3] \n"
" ldr q8, [x24], #16 \n"
" fmla v21.4s, v9.4s, v1.s[3] \n"
" ldr q9, [x24], #16 \n"
" fmla v28.4s, v10.4s, v0.s[3] \n"
" fmla v29.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" fmla v30.4s, v10.4s, v1.s[3] \n"
" fmla v31.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x12], #16 \n"
" fmla v22.4s, v10.4s, v5.s[3] \n"
" fmla v23.4s, v11.4s, v5.s[3] \n"
" fmla v24.4s, v10.4s, v6.s[3] \n"
" fmla v25.4s, v11.4s, v6.s[3] \n"
" fmla v26.4s, v10.4s, v7.s[3] \n"
" ldr q10, [x24], #16 \n"
" fmla v27.4s, v11.4s, v7.s[3] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL5x16_END_K \n"
" fmla v12.4s, v8.4s, v5.s[3] \n"
" fmla v13.4s, v9.4s, v5.s[3] \n"
" fmla v14.4s, v8.4s, v6.s[3] \n"
" fmla v15.4s, v9.4s, v6.s[3] \n"
" fmla v16.4s, v8.4s, v7.s[3] \n"
" fmla v17.4s, v9.4s, v7.s[3] \n"
" fmla v18.4s, v8.4s, v0.s[3] \n"
" fmla v19.4s, v9.4s, v0.s[3] \n"
" fmla v20.4s, v8.4s, v1.s[3] \n"
" fmla v21.4s, v9.4s, v1.s[3] \n"
" fmla v28.4s, v10.4s, v0.s[3] \n"
" fmla v29.4s, v11.4s, v0.s[3] \n"
" fmla v30.4s, v10.4s, v1.s[3] \n"
" fmla v31.4s, v11.4s, v1.s[3] \n"
" fmla v22.4s, v10.4s, v5.s[3] \n"
" fmla v23.4s, v11.4s, v5.s[3] \n"
" fmla v24.4s, v10.4s, v6.s[3] \n"
" fmla v25.4s, v11.4s, v6.s[3] \n"
" fmla v26.4s, v10.4s, v7.s[3] \n"
" fmla v27.4s, v11.4s, v7.s[3] \n"
".endm \n"
".macro KERNEL4x16_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" ldr q2, [x13], #16 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
" ldr q3, [x14], #16 \n"
" fmul v16.4s, v8.4s, v2.s[0] \n"
" fmul v17.4s, v9.4s, v2.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v18.4s, v8.4s, v3.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmul v19.4s, v9.4s, v3.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmul v22.4s, v10.4s, v0.s[0] \n"
" fmul v23.4s, v11.4s, v0.s[0] \n"
" fmul v24.4s, v10.4s, v1.s[0] \n"
" fmul v25.4s, v11.4s, v1.s[0] \n"
" fmul v26.4s, v10.4s, v2.s[0] \n"
" fmul v27.4s, v11.4s, v2.s[0] \n"
// " ldr q5, [x11], #16 \n"
" fmul v28.4s, v10.4s, v3.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmul v29.4s, v11.4s, v3.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL4x16_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
" fmla v16.4s, v8.4s, v2.s[0] \n"
" fmla v17.4s, v9.4s, v2.s[0] \n"
" fmla v18.4s, v8.4s, v3.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmla v19.4s, v9.4s, v3.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[0] \n"
" fmla v23.4s, v11.4s, v0.s[0] \n"
" fmla v24.4s, v10.4s, v1.s[0] \n"
" fmla v25.4s, v11.4s, v1.s[0] \n"
" fmla v26.4s, v10.4s, v2.s[0] \n"
" fmla v27.4s, v11.4s, v2.s[0] \n"
// " ldr q5, [x11], #16 \n" //
" fmla v28.4s, v10.4s, v3.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmla v29.4s, v11.4s, v3.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL4x16_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v8.4s, v0.s[1] \n"
" fmla v13.4s, v9.4s, v0.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[1] \n"
" fmla v15.4s, v9.4s, v1.s[1] \n"
" fmla v16.4s, v8.4s, v2.s[1] \n"
" fmla v17.4s, v9.4s, v2.s[1] \n"
" fmla v18.4s, v8.4s, v3.s[1] \n"
" ldr q8, [x24], #16 \n"
" fmla v19.4s, v9.4s, v3.s[1] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[1] \n"
" fmla v23.4s, v11.4s, v0.s[1] \n"
" fmla v24.4s, v10.4s, v1.s[1] \n"
" fmla v25.4s, v11.4s, v1.s[1] \n"
" fmla v26.4s, v10.4s, v2.s[1] \n"
" fmla v27.4s, v11.4s, v2.s[1] \n"
// " ldr q6, [x12], #16 \n"
" fmla v28.4s, v10.4s, v3.s[1] \n"
" ldr q10, [x24], #16 \n"
" fmla v29.4s, v11.4s, v3.s[1] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL4x16_K2 \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
" fmla v16.4s, v8.4s, v2.s[2] \n"
" fmla v17.4s, v9.4s, v2.s[2] \n"
" fmla v18.4s, v8.4s, v3.s[2] \n"
" ldr q8, [x24], #16 \n"
" fmla v19.4s, v9.4s, v3.s[2] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[2] \n"
" fmla v23.4s, v11.4s, v0.s[2] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmla v24.4s, v10.4s, v1.s[2] \n"
" fmla v25.4s, v11.4s, v1.s[2] \n"
" fmla v26.4s, v10.4s, v2.s[2] \n"
" fmla v27.4s, v11.4s, v2.s[2] \n"
// " ldr q7, [x13], #16 \n" //
" fmla v28.4s, v10.4s, v3.s[2] \n"
" ldr q10, [x24], #16 \n"
" fmla v29.4s, v11.4s, v3.s[2] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL4x16_K3 \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[3] \n"
" fmla v15.4s, v9.4s, v1.s[3] \n"
" fmla v16.4s, v8.4s, v2.s[3] \n"
" fmla v17.4s, v9.4s, v2.s[3] \n"
" fmla v18.4s, v8.4s, v3.s[3] \n"
" ldr q8, [x24], #16 \n"
" fmla v19.4s, v9.4s, v3.s[3] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" fmla v24.4s, v10.4s, v1.s[3] \n"
" fmla v25.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x12], #16 \n"
" fmla v26.4s, v10.4s, v2.s[3] \n"
" fmla v27.4s, v11.4s, v2.s[3] \n"
" ldr q2, [x13], #16 \n"
" fmla v28.4s, v10.4s, v3.s[3] \n"
" ldr q10, [x24], #16 \n"
" fmla v29.4s, v11.4s, v3.s[3] \n"
" ldr q11, [x24], #16 \n"
" ldr q3, [x14], #16 \n"
".endm \n"
".macro KERNEL4x16_END_K \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" fmla v14.4s, v8.4s, v1.s[3] \n"
" fmla v15.4s, v9.4s, v1.s[3] \n"
" fmla v16.4s, v8.4s, v2.s[3] \n"
" fmla v17.4s, v9.4s, v2.s[3] \n"
" fmla v18.4s, v8.4s, v3.s[3] \n"
" fmla v19.4s, v9.4s, v3.s[3] \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" fmla v24.4s, v10.4s, v1.s[3] \n"
" fmla v25.4s, v11.4s, v1.s[3] \n"
" fmla v26.4s, v10.4s, v2.s[3] \n"
" fmla v27.4s, v11.4s, v2.s[3] \n"
" fmla v28.4s, v10.4s, v3.s[3] \n"
" fmla v29.4s, v11.4s, v3.s[3] \n"
".endm \n"
".macro M4_ADD_C \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" ldp q0, q1, [x25] \n"
" fadd v12.4s, v12.4s, v0.4s \n"
" ldp q2, q3, [x25, #32] \n"
" fadd v13.4s, v13.4s, v1.4s \n"
" fadd v22.4s, v2.4s, v22.4s \n"
" ldp q4, q5, [x26] \n"
" fadd v23.4s, v3.4s, v23.4s \n"
" fadd v14.4s, v4.4s, v14.4s \n"
" ldp q6, q7, [x26, #32] \n"
" fadd v15.4s, v5.4s, v15.4s \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" fadd v24.4s, v6.4s, v24.4s \n"
" ldp q8, q9, [x27] \n"
" fadd v25.4s, v7.4s, v25.4s \n"
" fadd v16.4s, v8.4s, v16.4s \n"
" ldp q10, q11, [x27, #32] \n"
" fadd v17.4s, v9.4s, v17.4s \n"
" fadd v26.4s, v10.4s, v26.4s \n"
" ldp q0, q1, [x28] \n"
" fadd v27.4s, v11.4s, v27.4s \n"
" fadd v18.4s, v0.4s, v18.4s \n"
" ldp q2, q3, [x28, #32] \n"
" fadd v19.4s, v1.4s, v19.4s \n"
" fadd v28.4s, v2.4s, v28.4s \n"
" fadd v29.4s, v3.4s, v29.4s \n"
".endm \n"
".macro SAVE4x16 \n"
" stp q12, q13, [x25] \n"
" stp q14, q15, [x26] \n"
" stp q16, q17, [x27] \n"
" stp q18, q19, [x28] \n"
" stp q22, q23, [x25, #32] \n"
" stp q24, q25, [x26, #32] \n"
" stp q26, q27, [x27, #32] \n"
" stp q28, q29, [x28, #32] \n"
".endm \n"
".macro KERNEL3x16_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" ldr q2, [x13], #16 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v16.4s, v8.4s, v2.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmul v17.4s, v9.4s, v2.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmul v22.4s, v10.4s, v0.s[0] \n"
" fmul v23.4s, v11.4s, v0.s[0] \n"
" fmul v24.4s, v10.4s, v1.s[0] \n"
" fmul v25.4s, v11.4s, v1.s[0] \n"
" fmul v26.4s, v10.4s, v2.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmul v27.4s, v11.4s, v2.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL3x16_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
" fmla v16.4s, v8.4s, v2.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmla v17.4s, v9.4s, v2.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[0] \n"
" fmla v23.4s, v11.4s, v0.s[0] \n"
" fmla v24.4s, v10.4s, v1.s[0] \n"
" fmla v25.4s, v11.4s, v1.s[0] \n"
" fmla v26.4s, v10.4s, v2.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmla v27.4s, v11.4s, v2.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL3x16_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v8.4s, v0.s[1] \n"
" fmla v13.4s, v9.4s, v0.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[1] \n"
" fmla v15.4s, v9.4s, v1.s[1] \n"
" fmla v16.4s, v8.4s, v2.s[1] \n"
" ldr q8, [x24], #16 \n"
" fmla v17.4s, v9.4s, v2.s[1] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[1] \n"
" fmla v23.4s, v11.4s, v0.s[1] \n"
" fmla v24.4s, v10.4s, v1.s[1] \n"
" fmla v25.4s, v11.4s, v1.s[1] \n"
" fmla v26.4s, v10.4s, v2.s[1] \n"
" ldr q10, [x24], #16 \n"
" fmla v27.4s, v11.4s, v2.s[1] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL3x16_K2 \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
" fmla v16.4s, v8.4s, v2.s[2] \n"
" ldr q8, [x24], #16 \n"
" fmla v17.4s, v9.4s, v2.s[2] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[2] \n"
" fmla v23.4s, v11.4s, v0.s[2] \n"
" fmla v24.4s, v10.4s, v1.s[2] \n"
" fmla v25.4s, v11.4s, v1.s[2] \n"
" fmla v26.4s, v10.4s, v2.s[2] \n"
" ldr q10, [x24], #16 \n"
" fmla v27.4s, v11.4s, v2.s[2] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL3x16_K3 \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[3] \n"
" fmla v15.4s, v9.4s, v1.s[3] \n"
" fmla v16.4s, v8.4s, v2.s[3] \n"
" ldr q8, [x24], #16 \n"
" fmla v17.4s, v9.4s, v2.s[3] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" fmla v24.4s, v10.4s, v1.s[3] \n"
" fmla v25.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x12], #16 \n"
" fmla v26.4s, v10.4s, v2.s[3] \n"
" ldr q10, [x24], #16 \n"
" fmla v27.4s, v11.4s, v2.s[3] \n"
" ldr q11, [x24], #16 \n"
" ldr q2, [x13], #16 \n"
".endm \n"
".macro KERNEL3x16_END_K \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" fmla v14.4s, v8.4s, v1.s[3] \n"
" fmla v15.4s, v9.4s, v1.s[3] \n"
" fmla v16.4s, v8.4s, v2.s[3] \n"
" fmla v17.4s, v9.4s, v2.s[3] \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" fmla v24.4s, v10.4s, v1.s[3] \n"
" fmla v25.4s, v11.4s, v1.s[3] \n"
" fmla v26.4s, v10.4s, v2.s[3] \n"
" fmla v27.4s, v11.4s, v2.s[3] \n"
".endm \n"
".macro M3_ADD_C \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" ldp q0, q1, [x25] \n"
" fadd v12.4s, v12.4s, v0.4s \n"
" ldp q2, q3, [x25, #32] \n"
" fadd v13.4s, v13.4s, v1.4s \n"
" fadd v22.4s, v2.4s, v22.4s \n"
" ldp q4, q5, [x26] \n"
" fadd v23.4s, v3.4s, v23.4s \n"
" fadd v14.4s, v4.4s, v14.4s \n"
" ldp q6, q7, [x26, #32] \n"
" fadd v15.4s, v5.4s, v15.4s \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" fadd v24.4s, v6.4s, v24.4s \n"
" ldp q8, q9, [x27] \n"
" fadd v25.4s, v7.4s, v25.4s \n"
" fadd v16.4s, v8.4s, v16.4s \n"
" ldp q10, q11, [x27, #32] \n"
" fadd v17.4s, v9.4s, v17.4s \n"
" fadd v26.4s, v10.4s, v26.4s \n"
" fadd v27.4s, v11.4s, v27.4s \n"
".endm \n"
".macro SAVE3x16 \n"
" stp q12, q13, [x25] \n"
" stp q14, q15, [x26] \n"
" stp q16, q17, [x27] \n"
" stp q22, q23, [x25, #32] \n"
" stp q24, q25, [x26, #32] \n"
" stp q26, q27, [x27, #32] \n"
".endm \n"
".macro KERNEL2x16_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmul v22.4s, v10.4s, v0.s[0] \n"
" fmul v23.4s, v11.4s, v0.s[0] \n"
" fmul v24.4s, v10.4s, v1.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmul v25.4s, v11.4s, v1.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL2x16_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[0] \n"
" fmla v23.4s, v11.4s, v0.s[0] \n"
" fmla v24.4s, v10.4s, v1.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmla v25.4s, v11.4s, v1.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL2x16_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v8.4s, v0.s[1] \n"
" fmla v13.4s, v9.4s, v0.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[1] \n"
" ldr q8, [x24], #16 \n"
" fmla v15.4s, v9.4s, v1.s[1] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[1] \n"
" fmla v23.4s, v11.4s, v0.s[1] \n"
" fmla v24.4s, v10.4s, v1.s[1] \n"
" ldr q10, [x24], #16 \n"
" fmla v25.4s, v11.4s, v1.s[1] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL2x16_K2 \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" ldr q8, [x24], #16 \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[2] \n"
" fmla v23.4s, v11.4s, v0.s[2] \n"
" fmla v24.4s, v10.4s, v1.s[2] \n"
" ldr q10, [x24], #16 \n"
" fmla v25.4s, v11.4s, v1.s[2] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL2x16_K3 \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v14.4s, v8.4s, v1.s[3] \n"
" ldr q8, [x24], #16 \n"
" fmla v15.4s, v9.4s, v1.s[3] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" fmla v24.4s, v10.4s, v1.s[3] \n"
" ldr q10, [x24], #16 \n"
" fmla v25.4s, v11.4s, v1.s[3] \n"
" ldr q11, [x24], #16 \n"
" ldr q1, [x12], #16 \n"
".endm \n"
".macro KERNEL2x16_END_K \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" fmla v14.4s, v8.4s, v1.s[3] \n"
" fmla v15.4s, v9.4s, v1.s[3] \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" fmla v24.4s, v10.4s, v1.s[3] \n"
" fmla v25.4s, v11.4s, v1.s[3] \n"
".endm \n"
".macro M2_ADD_C \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" ldp q0, q1, [x25] \n"
" fadd v12.4s, v12.4s, v0.4s \n"
" ldp q2, q3, [x25, #32] \n"
" fadd v13.4s, v13.4s, v1.4s \n"
" fadd v22.4s, v2.4s, v22.4s \n"
" ldp q4, q5, [x26] \n"
" fadd v23.4s, v3.4s, v23.4s \n"
" fadd v14.4s, v4.4s, v14.4s \n"
" ldp q6, q7, [x26, #32] \n"
" fadd v15.4s, v5.4s, v15.4s \n"
" fadd v24.4s, v6.4s, v24.4s \n"
" fadd v25.4s, v7.4s, v25.4s \n"
".endm \n"
".macro SAVE2x16 \n"
" stp q12, q13, [x25] \n"
" stp q14, q15, [x26] \n"
" stp q22, q23, [x25, #32] \n"
" stp q24, q25, [x26, #32] \n"
".endm \n"
".macro KERNEL1x16_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" ldr q9, [x24], #16 \n"
" fmul v22.4s, v10.4s, v0.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmul v23.4s, v11.4s, v0.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL1x16_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" ldr q8, [x24], #16 \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" ldr q9, [x24], #16 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v22.4s, v10.4s, v0.s[0] \n"
" ldr q10, [x24], #16 \n"
" fmla v23.4s, v11.4s, v0.s[0] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL1x16_K1 \n"
" fmla v12.4s, v8.4s, v0.s[1] \n"
" ldr q8, [x24], #16 \n"
" fmla v13.4s, v9.4s, v0.s[1] \n"
" ldr q9, [x24], #16 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v22.4s, v10.4s, v0.s[1] \n"
" ldr q10, [x24], #16 \n"
" fmla v23.4s, v11.4s, v0.s[1] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL1x16_K2 \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" ldr q8, [x24], #16 \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" ldr q9, [x24], #16 \n"
" fmla v22.4s, v10.4s, v0.s[2] \n"
" ldr q10, [x24], #16 \n"
" fmla v23.4s, v11.4s, v0.s[2] \n"
" ldr q11, [x24], #16 \n"
".endm \n"
".macro KERNEL1x16_K3 \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" ldr q8, [x24], #16 \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" ldr q9, [x24], #16 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" ldr q10, [x24], #16 \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
" ldr q11, [x24], #16 \n"
" ldr q0, [x11], #16 \n"
".endm \n"
".macro M1_ADD_C \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" ldp q0, q1, [x25] \n"
" fadd v12.4s, v12.4s, v0.4s \n"
" ldp q2, q3, [x25, #32] \n"
" fadd v13.4s, v13.4s, v1.4s \n"
" fadd v22.4s, v2.4s, v22.4s \n"
" fadd v23.4s, v3.4s, v23.4s \n"
".endm \n"
".macro KERNEL1x16_END_K \n"
" fmla v12.4s, v8.4s, v0.s[3] \n"
" fmla v13.4s, v9.4s, v0.s[3] \n"
" fmla v22.4s, v10.4s, v0.s[3] \n"
" fmla v23.4s, v11.4s, v0.s[3] \n"
".endm \n"
".macro SAVE1x16 \n"
" stp q12, q13, [x25] \n"
" stp q22, q23, [x25, #32] \n"
".endm \n"
".macro N8_SAVE5x8 \n"
" subs x21, x21, #1 \n"
" add x10, x10, x5, lsl #4 \n"
" add x10, x10, x5, lsl #2 \n"
" stp q12, q13, [x25] \n"
" add x25, x29, x6 \n"
" stp q14, q15, [x26] \n"
" add x26, x25, x6 \n"
" stp q16, q17, [x27] \n"
" add x27, x26, x6 \n"
" stp q18, q19, [x28] \n"
" add x28, x27, x6 \n"
" stp q20, q21, [x29] \n"
" add x29, x28, x6 \n"
".endm \n"
".macro N8_KERNEL5x8_BEGIN_K \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" ldr q2, [x13], #16 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
" ldr q3, [x14], #16 \n"
" fmul v16.4s, v8.4s, v2.s[0] \n"
" fmul v17.4s, v9.4s, v2.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldr q4, [x15], #16 \n"
" fmul v18.4s, v8.4s, v3.s[0] \n"
" fmul v19.4s, v9.4s, v3.s[0] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v20.4s, v8.4s, v4.s[0] \n"
" fmul v21.4s, v9.4s, v4.s[0] \n"
".endm \n"
".macro N8_KERNEL5x8_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
" fmla v16.4s, v8.4s, v2.s[0] \n"
" fmla v17.4s, v9.4s, v2.s[0] \n"
" fmla v18.4s, v8.4s, v3.s[0] \n"
" fmla v19.4s, v9.4s, v3.s[0] \n"
" fmla v20.4s, v8.4s, v4.s[0] \n"
" fmla v21.4s, v9.4s, v4.s[0] \n"
".endm \n"
".macro N8_KERNEL5x8_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v10.4s, v0.s[1] \n"
" fmla v13.4s, v11.4s, v0.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v14.4s, v10.4s, v1.s[1] \n"
" fmla v15.4s, v11.4s, v1.s[1] \n"
" fmla v16.4s, v10.4s, v2.s[1] \n"
" fmla v17.4s, v11.4s, v2.s[1] \n"
" fmla v18.4s, v10.4s, v3.s[1] \n"
" fmla v19.4s, v11.4s, v3.s[1] \n"
" fmla v20.4s, v10.4s, v4.s[1] \n"
" fmla v21.4s, v11.4s, v4.s[1] \n"
".endm \n"
".macro N8_KERNEL5x8_K2 \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
" fmla v16.4s, v8.4s, v2.s[2] \n"
" fmla v17.4s, v9.4s, v2.s[2] \n"
" fmla v18.4s, v8.4s, v3.s[2] \n"
" fmla v19.4s, v9.4s, v3.s[2] \n"
" fmla v20.4s, v8.4s, v4.s[2] \n"
" fmla v21.4s, v9.4s, v4.s[2] \n"
".endm \n"
".macro N8_KERNEL5x8_K3 \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x12], #16 \n"
" fmla v16.4s, v10.4s, v2.s[3] \n"
" fmla v17.4s, v11.4s, v2.s[3] \n"
" ldr q2, [x13], #16 \n"
" fmla v18.4s, v10.4s, v3.s[3] \n"
" fmla v19.4s, v11.4s, v3.s[3] \n"
" ldr q3, [x14], #16 \n"
" fmla v20.4s, v10.4s, v4.s[3] \n"
" fmla v21.4s, v11.4s, v4.s[3] \n"
" ldr q4, [x15], #16 \n"
".endm \n"
".macro N8_KERNEL5x8_END_K \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
" fmla v16.4s, v10.4s, v2.s[3] \n"
" fmla v17.4s, v11.4s, v2.s[3] \n"
" fmla v18.4s, v10.4s, v3.s[3] \n"
" fmla v19.4s, v11.4s, v3.s[3] \n"
" fmla v20.4s, v10.4s, v4.s[3] \n"
" fmla v21.4s, v11.4s, v4.s[3] \n"
".endm \n"
".macro N8_KERNEL4x8_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" ldr q2, [x13], #16 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
" ldr q3, [x14], #16 \n"
" fmul v16.4s, v8.4s, v2.s[0] \n"
" fmul v17.4s, v9.4s, v2.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v18.4s, v8.4s, v3.s[0] \n"
" fmul v19.4s, v9.4s, v3.s[0] \n"
".endm \n"
".macro N8_KERNEL4x8_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
" fmla v16.4s, v8.4s, v2.s[0] \n"
" fmla v17.4s, v9.4s, v2.s[0] \n"
" fmla v18.4s, v8.4s, v3.s[0] \n"
" fmla v19.4s, v9.4s, v3.s[0] \n"
".endm \n"
".macro N8_KERNEL4x8_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v10.4s, v0.s[1] \n"
" fmla v13.4s, v11.4s, v0.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v14.4s, v10.4s, v1.s[1] \n"
" fmla v15.4s, v11.4s, v1.s[1] \n"
" fmla v16.4s, v10.4s, v2.s[1] \n"
" fmla v17.4s, v11.4s, v2.s[1] \n"
" fmla v18.4s, v10.4s, v3.s[1] \n"
" fmla v19.4s, v11.4s, v3.s[1] \n"
".endm \n"
".macro N8_KERNEL4x8_K2 \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
" fmla v16.4s, v8.4s, v2.s[2] \n"
" fmla v17.4s, v9.4s, v2.s[2] \n"
" fmla v18.4s, v8.4s, v3.s[2] \n"
" fmla v19.4s, v9.4s, v3.s[2] \n"
".endm \n"
".macro N8_KERNEL4x8_K3 \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x12], #16 \n"
" fmla v16.4s, v10.4s, v2.s[3] \n"
" fmla v17.4s, v11.4s, v2.s[3] \n"
" ldr q2, [x13], #16 \n"
" fmla v18.4s, v10.4s, v3.s[3] \n"
" fmla v19.4s, v11.4s, v3.s[3] \n"
" ldr q3, [x14], #16 \n"
".endm \n"
".macro N8_KERNEL4x8_END_K \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
" fmla v16.4s, v10.4s, v2.s[3] \n"
" fmla v17.4s, v11.4s, v2.s[3] \n"
" fmla v18.4s, v10.4s, v3.s[3] \n"
" fmla v19.4s, v11.4s, v3.s[3] \n"
".endm \n"
".macro N8_SAVE4x8 \n"
" stp q12, q13, [x25] \n"
" stp q14, q15, [x26] \n"
" stp q16, q17, [x27] \n"
" stp q18, q19, [x28] \n"
".endm \n"
".macro N8_KERNEL3x8_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" ldr q2, [x13], #16 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v16.4s, v8.4s, v2.s[0] \n"
" fmul v17.4s, v9.4s, v2.s[0] \n"
".endm \n"
".macro N8_KERNEL3x8_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
" fmla v16.4s, v8.4s, v2.s[0] \n"
" fmla v17.4s, v9.4s, v2.s[0] \n"
".endm \n"
".macro N8_KERNEL3x8_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmla v12.4s, v10.4s, v0.s[1] \n"
" fmla v13.4s, v11.4s, v0.s[1] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v14.4s, v10.4s, v1.s[1] \n"
" fmla v15.4s, v11.4s, v1.s[1] \n"
" fmla v16.4s, v10.4s, v2.s[1] \n"
" fmla v17.4s, v11.4s, v2.s[1] \n"
".endm \n"
".macro N8_KERNEL3x8_K2 \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
" fmla v16.4s, v8.4s, v2.s[2] \n"
" fmla v17.4s, v9.4s, v2.s[2] \n"
".endm \n"
".macro N8_KERNEL3x8_K3 \n"
" prfm PLDL1KEEP, [x15, #64] \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x12], #16 \n"
" fmla v16.4s, v10.4s, v2.s[3] \n"
" fmla v17.4s, v11.4s, v2.s[3] \n"
" ldr q2, [x13], #16 \n"
".endm \n"
".macro N8_KERNEL3x8_END_K \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
" fmla v16.4s, v10.4s, v2.s[3] \n"
" fmla v17.4s, v11.4s, v2.s[3] \n"
".endm \n"
".macro N8_SAVE3x8 \n"
" stp q12, q13, [x25] \n"
" stp q14, q15, [x26] \n"
" stp q16, q17, [x27] \n"
".endm \n"
".macro N8_KERNEL2x8_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldr q1, [x12], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v14.4s, v8.4s, v1.s[0] \n"
" fmul v15.4s, v9.4s, v1.s[0] \n"
".endm \n"
".macro N8_KERNEL2x8_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
" fmla v14.4s, v8.4s, v1.s[0] \n"
" fmla v15.4s, v9.4s, v1.s[0] \n"
".endm \n"
".macro N8_KERNEL2x8_K1 \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v12.4s, v10.4s, v0.s[1] \n"
" fmla v13.4s, v11.4s, v0.s[1] \n"
" fmla v14.4s, v10.4s, v1.s[1] \n"
" fmla v15.4s, v11.4s, v1.s[1] \n"
".endm \n"
".macro N8_KERNEL2x8_K2 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
" fmla v14.4s, v8.4s, v1.s[2] \n"
" fmla v15.4s, v9.4s, v1.s[2] \n"
".endm \n"
".macro N8_KERNEL2x8_K3 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
" ldr q1, [x12], #16 \n"
".endm \n"
".macro N8_KERNEL2x8_END_K \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" fmla v14.4s, v10.4s, v1.s[3] \n"
" fmla v15.4s, v11.4s, v1.s[3] \n"
".endm \n"
".macro N8_SAVE2x8 \n"
" stp q12, q13, [x25] \n"
" stp q14, q15, [x26] \n"
".endm \n"
".macro N8_KERNEL1x8_BEGIN_K \n"
" \n"
" ldr q0, [x11], #16 \n"
" ldp q8, q9, [x24], #32 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmul v12.4s, v8.4s, v0.s[0] \n"
" fmul v13.4s, v9.4s, v0.s[0] \n"
".endm \n"
".macro N8_KERNEL1x8_K0 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v12.4s, v8.4s, v0.s[0] \n"
" fmla v13.4s, v9.4s, v0.s[0] \n"
".endm \n"
".macro N8_KERNEL1x8_K1 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v12.4s, v10.4s, v0.s[1] \n"
" fmla v13.4s, v11.4s, v0.s[1] \n"
".endm \n"
".macro N8_KERNEL1x8_K2 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q10, q11, [x24], #32 \n"
" fmla v12.4s, v8.4s, v0.s[2] \n"
" fmla v13.4s, v9.4s, v0.s[2] \n"
".endm \n"
".macro N8_KERNEL1x8_K3 \n"
" prfm PLDL1KEEP, [x24, #128] \n"
" ldp q8, q9, [x24], #32 \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
" ldr q0, [x11], #16 \n"
".endm \n"
".macro N8_KERNEL1x8_END_K \n"
" fmla v12.4s, v10.4s, v0.s[3] \n"
" fmla v13.4s, v11.4s, v0.s[3] \n"
".endm \n"
".macro N8_SAVE1x8 \n"
" stp q12, q13, [x25] \n"
".endm \n"
//----------------------------------------------------
"SMM: \n"
" ldr x0, %[C] \n"
" ldr x1, %[A] \n"
" ldr x2, %[B] \n"
" ldr x3, %[M] \n"
" ldr x4, %[N] \n"
" ldr x5, %[K] \n"
// " ldr x7, %[temp] \n"
" ldr x9, %[LN] \n"
" ldr x6, %[LK] \n"
" ldr x19, %[SB] \n"
" ldr x8, %[k_tag] \n"
// " lsl x6, x4, #2 \n" //sizeof(N)
" add sp, sp, #-32 \n"
" mov x23, #5 \n"
// " lsl x8, x5, #2 \n" //sizeof(K)
" prfm PLDL1KEEP, [x1] \n"
" prfm PLDL1KEEP, [x2] \n"
" udiv x30, x3, x23 \n" // M / 5
" lsr x20, x4, #4 \n" // N / 16
" msub x23, x30, x23, x3 \n" // M % 5
" str x23, [sp] \n"
" mov x23, x19 \n" //SB
" str x8, [sp, #16] \n"
// " cmp x20, #0 \n"
// " beq BEGIN_N8 \n"
//-----------------------------------------------N16
"BEGIN_N16: \n"
" mov x25, x0 \n" //C1*
" add x26, x25, x9, lsl #2 \n" //C2*
" add x27, x25, x9, lsl #3 \n" //C3*
" add x28, x26, x9, lsl #3 \n" //C4*
" add x29, x27, x9, lsl #3 \n" //C5*
" mov x10, x1 \n"
" mov x21, x30 \n"
" mov x24, x23 \n" //还原SB的地址
" mov x7, #4 \n" //4次B的循环
" mov x8, #16 \n"
"BEGIN_PACKB: \n"
" mov x16, x2 \n" //B0*
" add x17, x16, x6, lsl #2 \n"
" add x18, x17, x6, lsl #2 \n"
" add x19, x18, x6, lsl #2 \n"
" mov x11, x10 \n" //A0*
" add x12, x11, x6, lsl #2 \n" //A1*
" add x13, x12, x6, lsl #2 \n" //A2*
" add x14, x13, x6, lsl #2 \n" //A3*
" add x15, x14, x6, lsl #2 \n" //A4*
" prfm PLDL1KEEP, [x16, #64] \n"
" prfm PLDL1KEEP, [x17, #64] \n"
" prfm PLDL1KEEP, [x18, #64] \n"
" prfm PLDL1KEEP, [x19, #64] \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" prfm PLDL1KEEP, [x15, #64] \n"
"PACK_Body_K: \n"
" lsr x22, x5, #3 \n" // K / 8
" PACK_KERNEL5x4_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b PACK_K1_7 \n"
"PACK_K: \n"
" PACK_KERNEL5x4_K0 \n"
"PACK_K1_7: \n"
" beq PACK_Edge_K \n"
" PACK_KERNEL5x4_K1 \n"
" subs x22, x22, #1 \n"
" b PACK_K \n"
"PACK_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" prfm PLDL1KEEP, [x29, #64] \n"
" PACK_KERNEL5x4_END_K \n"
" ldr x8, [sp, #16] \n"
" cmp x8, #0 \n"
" beq PACKB_SAVE1 \n"
" PACKB_ADD_C \n"
"PACKB_SAVE1: \n"
" SAVE5x4 \n"
" mov x8, #16 \n"
// " beq END_PACKB \n"
" add x23, x23, #16 \n"
" mov x24, x23 \n"
" add x2, x2, x6, lsl #4 \n"
" bgt BEGIN_PACKB \n"
"END_PACKB: \n"
" sub x23, x23, x8, lsl #2 \n" //还原SB的索引
" sub x29, x29, x8, lsl #2 \n" //C矩阵的偏移量还原
" add x25, x29, x9, lsl #2 \n"
" add x26, x25, x9, lsl #2 \n"
" add x27, x26, x9, lsl #2 \n"
" add x28, x27, x9, lsl #2 \n"
" add x29, x28, x9, lsl #2 \n"
" add x10, x10, x6, lsl #4 \n"
" add x10, x10, x6, lsl #2 \n" // A + 5行
" cmp x8, #16 \n"
" bne N8_END_PACKB \n"
" subs x21, x21, #1 \n"
" beq END_M5 \n"
//---------------------------------------------------
"BEGIN_M5: \n"
" mov x24, x23 \n"
" mov x11, x10 \n"
" add x12, x11, x6, lsl #2 \n"
" add x13, x12, x6, lsl #2 \n"
" add x14, x13, x6, lsl #2 \n"
" add x15, x14, x6, lsl #2 \n"
" prfm PLDL1KEEP, [x24, #512] \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" prfm PLDL1KEEP, [x15, #64] \n"
"Body_K: \n"
" lsr x22, x5, #3 \n" // K / 8
" KERNEL5x16_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b K1_7 \n"
"Main_K: \n"
" KERNEL5x16_K0 \n"
"K1_7: \n"
" KERNEL5x16_K1 \n"
" KERNEL5x16_K2 \n"
" KERNEL5x16_K3 \n"
" KERNEL5x16_K4 \n"
" KERNEL5x16_K5 \n"
" KERNEL5x16_K6 \n"
" beq Edge_K \n"
" KERNEL5x16_K7 \n"
" subs x22, x22, #1 \n"
" b Main_K \n"
"Edge_K: \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" prfm PLDL1KEEP, [x29, #64] \n"
" KERNEL5x16_END_K \n"
" ldr x8, [sp, #16] \n"
" cmp x8, #0 \n"
" beq M5_SAVE1 \n"
" ADD_C \n"
"M5_SAVE1: \n"
" SAVE5x16 \n"
// " SAVE5x16 \n"
" bgt BEGIN_M5 \n"
"END_M5: \n"
" mov x24, x23 \n" //B0*
" ldr x21, [sp] \n"
" cmp x21, #4 \n"
" bne BEGIN_M3 \n"
//--------------------------------------------------------
"BEGIN_M4: \n"
" mov x11, x10 \n"
" add x12, x11, x6, lsl #2 \n"
" add x13, x12, x6, lsl #2 \n"
" add x14, x13, x6, lsl #2 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
"M4_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" KERNEL4x16_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b M4_K1_3 \n"
"M4_Main_K: \n"
" KERNEL4x16_K0 \n"
"M4_K1_3: \n"
" KERNEL4x16_K1 \n"
" KERNEL4x16_K2 \n"
" beq M4_Edge_K \n"
" KERNEL4x16_K3 \n"
" subs x22, x22, #1 \n"
" b M4_Main_K \n"
"M4_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" KERNEL4x16_END_K \n"
" ldr x8, [sp, #16] \n"
" cmp x8, #0 \n"
" beq M4_SAVE1 \n"
" M4_ADD_C \n"
"M4_SAVE1: \n"
" SAVE4x16 \n"
" b END_M \n"
//--------------------------------------------------------
"BEGIN_M3: \n"
" cmp x21, #3 \n"
" bne BEGIN_M2 \n"
" mov x11, x10 \n"
" add x12, x11, x6, lsl #2 \n"
" add x13, x12, x6, lsl #2 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
"M3_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" KERNEL3x16_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b M3_K1_3 \n"
"M3_Main_K: \n"
" KERNEL3x16_K0 \n"
"M3_K1_3: \n"
" KERNEL3x16_K1 \n"
" KERNEL3x16_K2 \n"
" beq M3_Edge_K \n"
" KERNEL3x16_K3 \n"
" subs x22, x22, #1 \n"
" b M3_Main_K \n"
"M3_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" KERNEL3x16_END_K \n"
" ldr x8, [sp, #16] \n"
" cmp x8, #0 \n"
" beq M3_SAVE1 \n"
" M3_ADD_C \n"
"M3_SAVE1: \n"
" SAVE3x16 \n"
" b END_M \n"
//----------------------------------------------------------
"BEGIN_M2: \n"
" cmp x21, #2 \n"
" bne BEGIN_M1 \n"
" mov x11, x10 \n"
" add x12, x11, x6, lsl #2 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
"M2_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" KERNEL2x16_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b M2_K1_3 \n"
"M2_Main_K: \n"
" KERNEL2x16_K0 \n"
"M2_K1_3: \n"
" KERNEL2x16_K1 \n"
" KERNEL2x16_K2 \n"
" beq M2_Edge_K \n"
" KERNEL2x16_K3 \n"
" subs x22, x22, #1 \n"
" b M2_Main_K \n"
"M2_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" KERNEL2x16_END_K \n"
" ldr x8, [sp, #16] \n"
" cmp x8, #0 \n"
" beq M2_SAVE1 \n"
" M2_ADD_C \n"
"M2_SAVE1: \n"
" SAVE2x16 \n"
" b END_M \n"
//---------------------------------------------------------
"BEGIN_M1: \n"
" cmp x21, #1 \n"
" bne END_M \n"
" mov x11, x10 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
"M1_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" KERNEL1x16_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b M1_K1_3 \n"
"M1_Main_K: \n"
" KERNEL1x16_K0 \n"
"M1_K1_3: \n"
" KERNEL1x16_K1 \n"
" KERNEL1x16_K2 \n"
" beq M1_Edge_K \n"
" KERNEL1x16_K3 \n"
" subs x22, x22, #1 \n"
" b M1_Main_K \n"
"M1_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" KERNEL1x16_END_K \n"
" ldr x8, [sp, #16] \n"
" cmp x8, #0 \n"
" beq M1_SAVE1 \n"
" M1_ADD_C \n"
"M1_SAVE1: \n"
" SAVE1x16 \n"
"END_M: \n"
" subs x20, x20, #1 \n"
" add x16, x16, #64 \n"
" add x0, x0, #64 \n"
" bgt BEGIN_N16 \n"
"END_N16: \n"
" ands x20, x4, #15 \n"
" beq END_N \n"
"N8_END_PACKB: \n"
/*
"BEGIN_N8: \n"
//----------------------------------------------------------N8
"N8_BEGIN_PACKB: \n"
" mov x25, x0 \n" //C1*
" add x26, x25, x6 \n" //C2*
" add x27, x25, x6, lsl #1 \n" //C3*
" add x28, x26, x6, lsl #1 \n" //C4*
" add x29, x27, x6, lsl #1 \n" //C5*
" mov x10, x1 \n" //A0*
" mov x21, x30 \n" // M / 5
" mov x7, #2 \n"
" mov x24, x23 \n"
" mov x8, #8 \n"
" b BEGIN_PACKB \n"
"N8_END_PACKB: \n"
" subs x21, x21, #1 \n"
" beq N8_END_M5 \n"
//--------------------------------------------------N8M5
"N8_BEGIN_M5: \n"
" mov x24, x23 \n"
" mov x11, x10 \n"
" add x12, x11, x5, lsl #2 \n"
" add x13, x12, x5, lsl #2 \n"
" add x14, x13, x5, lsl #2 \n"
" add x15, x14, x5, lsl #2 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
" prfm PLDL1KEEP, [x15, #64] \n"
"N8_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" N8_KERNEL5x8_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b N8_K1_3 \n"
"N8_Main_K: \n"
" N8_KERNEL5x8_K0 \n"
"N8_K1_3: \n"
" N8_KERNEL5x8_K1 \n"
" N8_KERNEL5x8_K2 \n"
" beq N8_Edge_K \n"
" N8_KERNEL5x8_K3 \n"
" subs x22, x22, #1 \n"
" b N8_Main_K \n"
"N8_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #64] \n"
" prfm PLDL1KEEP, [x26, #64] \n"
" prfm PLDL1KEEP, [x27, #64] \n"
" prfm PLDL1KEEP, [x28, #64] \n"
" prfm PLDL1KEEP, [x29, #64] \n"
" N8_KERNEL5x8_END_K \n"
" N8_SAVE5x8 \n"
" bgt N8_BEGIN_M5 \n"
//---------------------------------------------------------
"N8_END_M5: \n"
" mov x24, x23 \n" //B0*
" ldr x21, [sp] \n"
" cmp x21, #4 \n"
" bne N8_BEGIN_M3 \n"
//--------------------------------------------------------
"N8_BEGIN_M4: \n"
" mov x11, x10 \n"
" add x12, x11, x5, lsl #2 \n"
" add x13, x12, x5, lsl #2 \n"
" add x14, x13, x5, lsl #2 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
" prfm PLDL1KEEP, [x14, #64] \n"
"N8_M4_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" N8_KERNEL4x8_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b N8_M4_K1_3 \n"
"N8_M4_Main_K: \n"
" N8_KERNEL4x8_K0 \n"
"N8_M4_K1_3: \n"
" N8_KERNEL4x8_K1 \n"
" N8_KERNEL4x8_K2 \n"
" beq N8_M4_Edge_K \n"
" N8_KERNEL4x8_K3 \n"
" subs x22, x22, #1 \n"
" b N8_M4_Main_K \n"
"N8_M4_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #32] \n"
" prfm PLDL1KEEP, [x26, #32] \n"
" prfm PLDL1KEEP, [x27, #32] \n"
" prfm PLDL1KEEP, [x28, #32] \n"
" N8_KERNEL4x8_END_K \n"
" N8_SAVE4x8 \n"
" b N8_END_M \n"
//------------------------------------------------------------------
"N8_BEGIN_M3: \n"
" cmp x21, #3 \n"
" bne N8_BEGIN_M2 \n"
" mov x11, x10 \n"
" add x12, x11, x5, lsl #2 \n"
" add x13, x12, x5, lsl #2 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
" prfm PLDL1KEEP, [x13, #64] \n"
"N8_M3_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" N8_KERNEL3x8_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b N8_M3_K1_3 \n"
"N8_M3_Main_K: \n"
" N8_KERNEL3x8_K0 \n"
"N8_M3_K1_3: \n"
" N8_KERNEL3x8_K1 \n"
" N8_KERNEL3x8_K2 \n"
" beq N8_M3_Edge_K \n"
" N8_KERNEL3x8_K3 \n"
" subs x22, x22, #1 \n"
" b N8_M3_Main_K \n"
"N8_M3_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #32] \n"
" prfm PLDL1KEEP, [x26, #32] \n"
" prfm PLDL1KEEP, [x27, #32] \n"
" N8_KERNEL3x8_END_K \n"
" N8_SAVE3x8 \n"
" b N8_END_M \n"
//--------------------------------------------------------
"N8_BEGIN_M2: \n"
" cmp x21, #2 \n"
" bne N8_BEGIN_M1 \n"
" mov x11, x10 \n"
" add x12, x11, x5, lsl #2 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
" prfm PLDL1KEEP, [x12, #64] \n"
"N8_M2_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" N8_KERNEL2x8_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b N8_M2_K1_3 \n"
"N8_M2_Main_K: \n"
" N8_KERNEL2x8_K0 \n"
"N8_M2_K1_3: \n"
" N8_KERNEL2x8_K1 \n"
" N8_KERNEL2x8_K2 \n"
" beq N8_M2_Edge_K \n"
" N8_KERNEL2x8_K3 \n"
" subs x22, x22, #1 \n"
" b N8_M2_Main_K \n"
"N8_M2_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #32] \n"
" prfm PLDL1KEEP, [x26, #32] \n"
" N8_KERNEL2x8_END_K \n"
" N8_SAVE2x8 \n"
" b N8_END_M \n"
//-----------------------------------------------------
"N8_BEGIN_M1: \n"
" cmp x21, #1 \n"
" bne N8_END_M \n"
" mov x11, x10 \n"
" prfm PLDL1KEEP, [x11, #64] \n"
"N8_M1_Body_K: \n"
" lsr x22, x5, #2 \n" // K / 8
" N8_KERNEL1x8_BEGIN_K \n"
" subs x22, x22, #1 \n"
" b N8_M1_K1_3 \n"
"N8_M1_Main_K: \n"
" N8_KERNEL1x8_K0 \n"
"N8_M1_K1_3: \n"
" N8_KERNEL1x8_K1 \n"
" N8_KERNEL1x8_K2 \n"
" beq N8_M1_Edge_K \n"
" N8_KERNEL1x8_K3 \n"
" subs x22, x22, #1 \n"
" b N8_M1_Main_K \n"
"N8_M1_Edge_K: \n"
" prfm PLDL1KEEP, [x25, #32] \n"
" N8_KERNEL1x8_END_K \n"
" N8_SAVE1x8 \n"
"N8_END_M: \n"
*/
"END_N: \n"
" add sp, sp, #32 \n"
:
:
[C] "m" (C),
[A] "m" (A),
[B] "m" (B),
[M] "m" (M),
[N] "m" (N),
[K] "m" (K),
[LN] "m" (LN),
[LK] "m" (LK),
[SB] "m" (SB),
[k_tag] "m" (k_tag)
: "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8",
"x9", "x10", "x11", "x12", "x13","x14", "x15", "x16",
"x17", "x18", "x19", "x20", "x21", "x22", "x23", "x24","x25",
"x26", "x27", "x28", "x29", "x30",
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
"v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
"v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
void Small_SGEMM(float *C, float *A, float *B, long M, long N,
long K, long *temp, long LD)
{
omp_set_num_threads(num);
long i, k, kc;
long LK = K;
long GEMM_K = 328;
void *ptr;
posix_memalign(&ptr, 64, num * GEMM_K * 16 *sizeof( float ));
float *SSB = (float *)ptr;
# pragma omp parallel for private(k,kc)
for(i=0; i< LD; i= i + N)
{
float *CC = C + i ;
for(k = 0; k < LK; k = k + kc)
{
kc = GEMM_K;
if(LK - k < GEMM_K)
kc = LK - k;
float * AA = A + k;
float *BB = B + i * LK + k ;
SMM(CC, AA, BB, M, N, kc, temp, LD, LK,
&SSB[i/N * GEMM_K * 16], k);
}
}
free(SSB);
}
int main()
{
openblas_set_num_threads(num);
int i,j,k;
int loop=5;
long M, N, K;
double start, cost;
int flag =0 ;
void *ptr, *ptr1;
long temp =-1;
int pc;
FILE *fp;
if( (fp=fopen("NSMM_P_FT.txt","w")) == NULL )
{
puts("Fail to open file!");
exit(0);
}
K = 576;
for(j = 5; j < 6;j++)
{
M = 262;
N = 50176;
// K = 4992 + 8 * j;
double ops = M *N *K * 1.0e-09 * 2;
fprintf(fp, "%d %d %d", M,N,K);
for(pc =0; pc < 5; pc++)
{
posix_memalign(&ptr1, 4096, M* K * sizeof( float ));
posix_memalign(&ptr, 4096, K* N * sizeof( float ));
float *A = (float *)ptr1;
float *B = (float *)ptr;
float *C = ( float * ) malloc( M* N * sizeof( float ) );
random_matrix(M,K,A);
random_matrix(K,N,B);
// transpose(K, N, B);
for( i =0 ;i< 2; i++)
Small_SGEMM(C, A, B, M, N/num, K, &temp, N);
start = dclock();
for( i= 0; i< loop ;i++)
Small_SGEMM(C, A, B, M, N/num, K, &temp, N);
cost =(dclock()-start)/loop;
ops = M * N * K * 1.0e-09 * 2;
printf("\nN_SMM: M= %d N=%d K=%d flops = %lf effic= %.3lf %\n",
M, N, K, ops/cost, ops/cost/17.6 * 100/num);
fprintf(fp, " %.3f", ops/cost);
free(A);
free(B);
free(C);
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
| {
"alphanum_fraction": 0.4114525247,
"avg_line_length": 23.9071406681,
"ext": "c",
"hexsha": "50cfb13b65775787f1862d2395f70ad35967249e",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T02:32:05.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-17T15:31:02.000Z",
"max_forks_repo_head_hexsha": "63a36c010d5a307d98e8470a75313a777dba0514",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "AnonymousYWL/LibShalom",
"max_forks_repo_path": "NN_LIB/test_SMM_m5n16_thread.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "63a36c010d5a307d98e8470a75313a777dba0514",
"max_issues_repo_issues_event_max_datetime": "2021-12-29T07:03:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-10-18T11:26:20.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "AnonymousYWL/LibShalom",
"max_issues_repo_path": "NN_LIB/test_SMM_m5n16_thread.c",
"max_line_length": 71,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AnonymousYWL/MYLIB",
"max_stars_repo_path": "NN_LIB/test_SMM_m5n16_thread.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T10:45:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-04T14:39:37.000Z",
"num_tokens": 44798,
"size": 78009
} |
#include <stdlib.h>
#if !defined(__APPLE__)
#include <malloc.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <fftw3.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include "../cosmolike_core/theory/basics.c"
#include "../cosmolike_core/theory/structs.c"
#include "../cosmolike_core/theory/parameters.c"
#include "../cosmolike_core/emu17/P_cb/emu.c"
#include "../cosmolike_core/theory/recompute.c"
#include "../cosmolike_core/theory/cosmo3D.c"
#include "../cosmolike_core/theory/redshift_spline.c"
#include "../cosmolike_core/theory/halo.c"
#include "../cosmolike_core/theory/HOD.c"
#include "../cosmolike_core/theory/pt.c"
#include "../cosmolike_core/theory/cosmo2D_fourier.c"
#include "../cosmolike_core/theory/IA.c"
#include "../cosmolike_core/theory/cluster.c"
#include "../cosmolike_core/theory/BAO.c"
#include "../cosmolike_core/theory/external_prior.c"
#include "../cosmolike_core/theory/GRS.c"
#include "like_grs.c"
double log_like_wrapper(input_cosmo_params ic, input_nuisance_params_grs in);
double log_like_wrapper(input_cosmo_params ic, input_nuisance_params_grs in)
{
// printf("%le %le %le %le %le %le %le\n",ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0);
// printf("%le %le %le %le %le %le %le\n",in.grsbias[0], in.grsbias[1], in.grsbias[2], in.grsbias[3],in.grsbias[4], in.grsbias[5], in.grsbias[6]);
//printf("%le %le %le %le %le %le %le %le %le %le\n",in.grssigmap[0], in.grssigmap[1], in.grssigmap[2], in.grssigmap[3], in.grssigmap[4], in.grssigmap[5], in.grssigmap[6],in.grssigmaz, in.grspshot, in.grskstar);
double like = log_like_GRS(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,in.grsbias[0], in.grsbias[1], in.grsbias[2], in.grsbias[3],in.grsbias[4], in.grsbias[5], in.grsbias[6], in.grssigmap[0], in.grssigmap[1], in.grssigmap[2], in.grssigmap[3], in.grssigmap[4], in.grssigmap[5], in.grssigmap[6],in.grssigmaz, in.grspshot, in.grskstar);
return like;
}
int main(void){
double res;
init_GRS();
res=log_like_GRS(0.3156,0.831,0.9645,-1.0,0.0,0.0491685,0.6727,0.0,0.0,1.538026692020565,1.862707210288686,2.213131761595241,2.617023657038295,2.975011712138650,3.376705680190931,3.725882076395691,290.,290.,290.,290.,290.,290.,290.,0.001,0.0,0.24);
printf("loglike=%le\n",res);
res=log_like_GRS(0.2325384451023471,1.0310887691615935,0.8595022066924793, -1.137588053600136, 0.14993639190238117, 0.05165678142188447, 0.8247432633482439,0.0,0.0,1.538026692020565,1.862707210288686,2.213131761595241,2.617023657038295,2.975011712138650,3.376705680190931,3.725882076395691,290.,290.,290.,290.,290.,290.,290.,0.001,0.0,0.24);
printf("loglike=%le\n",res);
return 0;
}
// double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0,
// double B1, double B2, double B3, double B4, double B5, double B6, double B7,
// double SIGMAP1, double SIGMAP2, double SIGMAP3, double SIGMAP4, double SIGMAP5, double SIGMAP6, double SIGMAP7,
// double SIGMAZ, double PSHOT, double KSTAR)
// log_multi_like(0.315,0.831,0.965,-1.0,0.0,0.049,0.673,1.19,1.30,1.44,1.57,1.70,1.82,1.93,290.,290.,290.,290.,290.,290.,290.,0.001,0.0,0.094);
// double dk, dmu, *k, *mu, *data, *variance;
// int i;
// k = create_double_vector(0,GRS.N_k-1);
// mu = create_double_vector(0,GRS.N_mu-1);
// data = create_double_vector(0,GRS.N_z*GRS.N_k*GRS.N_mu-1);
// variance = create_double_vector(0,GRS.N_z*GRS.N_k*GRS.N_mu-1);
// dk = (GRS.k_max-GRS.k_min)/GRS.N_k;
// dmu= 1./GRS.N_mu;
// for (i =0; i < GRS.N_k; i++){
// // use linear spacing in k!
// k[i] = GRS.k_min +(i+0.5)*dk;
// }
// for (i =0; i < GRS.N_mu; i++){
// // use linear spacing in mu!
// mu[i] = (i+0.5)*dmu;
// }
// set_data_GRS(k,mu,data);
// set_variance_GRS(k,mu, dk, dmu, variance);
// return 0;
// }
/*int main(void){
set_cosmological_parameters_to_Planck_WP();
init_GRS_single_zbin(0.16,0.4);
double z;
GRS_gal.b_g[0] = 1.0;
for (z = 0.1; z < 2.5; z+=0.05){
GRS.z[0] = z;
printf("%.3f %e %e %e\n", z, 1./P_obs(0.14,0.6,0), 1./P_obs(0.5,0.6,0),1./P_obs(1.0,0.6,0));
}
return 0;
}
*/ | {
"alphanum_fraction": 0.6981382979,
"avg_line_length": 42.5660377358,
"ext": "c",
"hexsha": "b86062c013fe3cca64eca84f4604c1e09cb08144",
"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": "aa65774dc1870450723b0a13449681e37d0f979c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CosmoLike/WFIRST_forecasts",
"max_forks_repo_path": "like_grs_only.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "aa65774dc1870450723b0a13449681e37d0f979c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "CosmoLike/WFIRST_forecasts",
"max_issues_repo_path": "like_grs_only.c",
"max_line_length": 376,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "aa65774dc1870450723b0a13449681e37d0f979c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CosmoLike/WFIRST_forecasts",
"max_stars_repo_path": "like_grs_only.c",
"max_stars_repo_stars_event_max_datetime": "2019-08-21T00:36:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-21T00:36:40.000Z",
"num_tokens": 1802,
"size": 4512
} |
#pragma once
#include <gsl/gsl>
#include <type_traits>
#include "Exponentials.h"
#include "HyperionUtils/Concepts.h"
#include "HyperionUtils/Macros.h"
#include "HyperionUtils/OptionAndResult.h"
namespace hyperion::math {
using utils::None;
using utils::Option;
using utils::Some;
using utils::concepts::FloatingPoint;
/// @brief The possible kinds of value interpolation possible by `Interpolator`
enum class InterpolationType
{
Linear = 0,
Logarithmic,
Exponential
};
IGNORE_PADDING_START
/// @brief Interpolates from a starting value to a final value in the way prescribed by `Type`
/// @note `T` must be a floating point type
/// @note The start value must be in [0, target value] and the target value must be > 0
///
/// @tparam T - The floating point type to perform operations in
/// @tparam Type - The type of interpolation
template<FloatingPoint T, InterpolationType Type = InterpolationType::Linear>
class Interpolator {
public:
static constexpr T DEFAULT_TARGET_VALUE = gsl::narrow_cast<T>(1.0);
static constexpr T DEFAULT_INITIAL_VALUE = gsl::narrow_cast<T>(0.0);
static constexpr T DEFAULT_TRANSITION_LENGTH = gsl::narrow_cast<T>(0.1);
static constexpr size_t DEFAULT_SAMPLE_RATE = 44100ULL;
/// @brief Creates a default `Interpolator`
constexpr Interpolator() noexcept = default;
/// @brief Creates an `Interpolator` with the given target value
///
/// @param targetValue - The target final value to interpolate to
constexpr explicit Interpolator(T targetValue) noexcept
: m_target_value(targetValue),
mLinearTransitionStep(
(m_target_value - m_initial_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)),
m_samples_to_transition(get_samples_to_transition()) {
}
/// @brief Creates an `Interpolator` with the given target value and sample rate
///
/// @param targetValue - The target final value to interpolate to
/// @param sampleRate - The sample rate to process at
constexpr explicit Interpolator(T targetValue, size_t sampleRate) noexcept
: m_sample_rate(sampleRate), m_target_value(targetValue),
mLinearTransitionStep(
(m_target_value - m_initial_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)),
m_samples_to_transition(get_samples_to_transition()) {
}
/// @brief Creates an `Interpolator` with the given target and initial values, and sample
/// rate
///
/// @param targetValue - The target final value to interpolate to
/// @param initial_value - The initial value to start interpolation from
/// @param sampleRate - The sample rate to process at
constexpr Interpolator(T targetValue, T initial_value, size_t sampleRate) noexcept
: m_sample_rate(sampleRate), m_target_value(targetValue),
m_current_value(initial_value), m_initial_value(m_current_value),
mLinearTransitionStep(
(m_target_value - m_initial_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)),
m_samples_to_transition(get_samples_to_transition()) {
}
/// @brief Creates an `Interpolator` with the given target and initial values, time to
/// interpolate over, and sample rate
///
/// @param targetValue - The target final value to interpolate to
/// @param initial_value - The initial value to start interpolation from
/// @param transitionLengthSeconds - The transition time to interpolate over
/// @param sampleRate - The sample rate to process at
constexpr Interpolator(T targetValue,
T initial_value,
T transitionLengthSeconds,
size_t sampleRate) noexcept
: m_sample_rate(sampleRate), m_target_value(targetValue),
m_current_value(initial_value), m_initial_value(m_current_value),
m_transition_lengthSeconds(transitionLengthSeconds),
mLinearTransitionStep(
(m_target_value - m_initial_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)),
m_samples_to_transition(get_samples_to_transition()) {
}
constexpr Interpolator(const Interpolator& interpolator) noexcept = default;
constexpr Interpolator(Interpolator&& interpolator) noexcept = default;
~Interpolator() noexcept = default;
/// @brief Gets the next value in the interpolation sequence
/// If `currentSample` is given, gets the value in the sequence for the given sample index
/// @note This is only available for `Interpolator`s of type
/// `InterpolationType::Logarithmic` or `InterpolationType::Exponential`
/// @param currentSample - The (optional) sample in the sequence to get the value for
///
/// @return - The interpolation value
inline auto get_next_value(Option<size_t> currentSample = None()) noexcept -> T {
if(currentSample.is_some()) {
m_current_transition_sample = currentSample.unwrap();
}
if(m_current_transition_sample <= m_samples_to_transition) {
m_current_value = interpolate(m_current_transition_sample);
m_current_transition_sample++;
}
return m_current_value;
}
/// @brief Resets the `Interpolator`.
/// - If `initial_value` is given, the `Interpolator` will start at the given one instead of
/// `DEFAULT_INITIAL_VALUE`
/// - If `transitionLengthSeconds` is also given, the `Interpolator` will interpolate over
/// that length of time instead of the current one
///
/// @param initial_value - The initial value to start interpolation from
/// @param transitionLengthSeconds - The transition time to interpolate over
inline auto
reset(Option<T> initial_value, Option<T> transitionLengthSeconds) noexcept -> void {
if(initial_value.is_some()) {
m_current_value = initial_value.unwrap();
m_initial_value = m_current_value;
}
else {
m_current_value = DEFAULT_INITIAL_VALUE;
m_initial_value = m_current_value;
}
if(transitionLengthSeconds.is_some()) {
m_transition_lengthSeconds = transitionLengthSeconds.unwrap();
}
mLinearTransitionStep
= (m_target_value - m_current_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds);
m_samples_to_transition = get_samples_to_transition();
m_current_transition_sample = 0ULL;
}
/// @brief Sets the target value to interpolate to, to the given one
///
/// @param targetValue - The value to interpolate to
constexpr inline auto set_target(T targetValue) noexcept -> void {
m_target_value = targetValue;
m_initial_value = m_current_value;
mLinearTransitionStep
= (m_target_value - m_initial_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds);
m_samples_to_transition = get_samples_to_transition();
}
/// @brief Sets the sample rate to use for interpolation
///
/// @param sampleRate - The sample rate to use for interpolation
inline auto set_sample_rate(size_t sampleRate) noexcept -> void {
m_sample_rate = sampleRate;
mLinearTransitionStep
= (m_target_value - m_initial_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds);
m_samples_to_transition = get_samples_to_transition();
m_current_transition_sample = 0ULL;
}
constexpr auto
operator=(const Interpolator& interpolator) noexcept -> Interpolator& = default;
constexpr auto operator=(Interpolator&& interpolator) noexcept -> Interpolator& = default;
private:
static constexpr T LOG_TIME_FACTOR = gsl::narrow_cast<T>(5.0);
static constexpr T EXP_TIME_FACTOR = gsl::narrow_cast<T>(0.693);
size_t m_sample_rate = DEFAULT_SAMPLE_RATE;
T m_target_value = DEFAULT_TARGET_VALUE;
T m_current_value = DEFAULT_INITIAL_VALUE;
T m_initial_value = DEFAULT_INITIAL_VALUE;
T m_transition_lengthSeconds = DEFAULT_TRANSITION_LENGTH;
T mLinearTransitionStep
= (m_target_value - m_initial_value)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds);
size_t m_samples_to_transition = get_samples_to_transition();
size_t m_current_transition_sample = 0;
/// @brief Gets the interpolated value for the given sample
///
/// @param sample - The sample to get the interpolated value for
///
/// @return The interpolated value
inline auto interpolate(size_t sample) noexcept -> T {
if constexpr(Type == InterpolationType::Linear) {
return linear_interpolation(sample);
}
else if constexpr(Type == InterpolationType::Logarithmic) {
return log_interpolation(sample);
}
else {
return exp_interpolation(sample);
}
}
inline auto linear_interpolation(size_t sample) noexcept -> T {
return m_initial_value + (mLinearTransitionStep * gsl::narrow_cast<T>(sample));
}
/// @brief Performs "logarithmic" interpolation.
/// In reality, this is a pseudo logarithmic shape:
///
/// y = transition_factor *
/// [1 + (peak_factor - 1) * (-e^{1 - t / (transtionLength / time_factor) } ) ]
///
/// where t = sample / sampleRate
///
/// which has a horizontal asymptote at ~ the target value and more pronouced slope
///
/// @param sample - The sample to get the interpolation value for
///
/// @return - The interpolated value
inline auto log_interpolation(size_t sample) noexcept -> T {
return (m_initial_value - m_target_value)
* math::Exponentials::exp(-gsl::narrow_cast<T>(sample)
/ (gsl::narrow_cast<T>(m_sample_rate)
* m_transition_lengthSeconds / LOG_TIME_FACTOR))
+ m_target_value;
}
/// @brief Performs exponential interpolation:
///
/// y = e^{t / (transitionLength / time_factor) } - 1
///
/// where t = sample / sampleRate
///
/// @param sample The sample to get the interpolation value for
///
/// @return - The interpolated value
inline auto exp_interpolation(size_t sample) noexcept -> T {
return (m_target_value - m_initial_value)
* (math::Exponentials::exp(
gsl::narrow_cast<T>(sample)
/ (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds
/ EXP_TIME_FACTOR))
- gsl::narrow_cast<T>(1.0))
+ m_initial_value;
}
/// @brief Gets the number of samples necessary to fully complete the interpolation sequence
///
/// @return The number of samples in the interpolation sequence
inline auto get_samples_to_transition() noexcept -> size_t {
return gsl::narrow_cast<size_t>(gsl::narrow_cast<T>(m_sample_rate)
* m_transition_lengthSeconds);
}
};
IGNORE_PADDING_STOP
} // namespace hyperion::math
| {
"alphanum_fraction": 0.7076750491,
"avg_line_length": 39.9141791045,
"ext": "h",
"hexsha": "7725a7a290b181b156ba15d541fcd2fad8699428",
"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": "77093e282b29747741fd4164b4e165fcef267471",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "braxtons12/Hyperion-Math",
"max_forks_repo_path": "include/HyperionMath/Interpolator.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471",
"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": "braxtons12/Hyperion-Math",
"max_issues_repo_path": "include/HyperionMath/Interpolator.h",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "braxtons12/Hyperion-Math",
"max_stars_repo_path": "include/HyperionMath/Interpolator.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2562,
"size": 10697
} |
/* sys/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
int
main (void)
{
double y, y_expected;
int e, e_expected;
gsl_ieee_env_setup ();
/* Test for expm1 */
y = gsl_expm1 (0.0);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_expm1(0.0)");
y = gsl_expm1 (1e-10);
y_expected = 1.000000000050000000002e-10;
gsl_test_rel (y, y_expected, 1e-15, "gsl_expm1(1e-10)");
y = gsl_expm1 (-1e-10);
y_expected = -9.999999999500000000017e-11;
gsl_test_rel (y, y_expected, 1e-15, "gsl_expm1(-1e-10)");
y = gsl_expm1 (0.1);
y_expected = 0.1051709180756476248117078264902;
gsl_test_rel (y, y_expected, 1e-15, "gsl_expm1(0.1)");
y = gsl_expm1 (-0.1);
y_expected = -0.09516258196404042683575094055356;
gsl_test_rel (y, y_expected, 1e-15, "gsl_expm1(-0.1)");
y = gsl_expm1 (10.0);
y_expected = 22025.465794806716516957900645284;
gsl_test_rel (y, y_expected, 1e-15, "gsl_expm1(10.0)");
y = gsl_expm1 (-10.0);
y_expected = -0.99995460007023751514846440848444;
gsl_test_rel (y, y_expected, 1e-15, "gsl_expm1(-10.0)");
/* Test for log1p */
y = gsl_log1p (0.0);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_log1p(0.0)");
y = gsl_log1p (1e-10);
y_expected = 9.9999999995000000000333333333308e-11;
gsl_test_rel (y, y_expected, 1e-15, "gsl_log1p(1e-10)");
y = gsl_log1p (0.1);
y_expected = 0.095310179804324860043952123280765;
gsl_test_rel (y, y_expected, 1e-15, "gsl_log1p(0.1)");
y = gsl_log1p (10.0);
y_expected = 2.3978952727983705440619435779651;
gsl_test_rel (y, y_expected, 1e-15, "gsl_log1p(10.0)");
/* Test for gsl_hypot */
y = gsl_hypot (0.0, 0.0);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(0.0, 0.0)");
y = gsl_hypot (1e-10, 1e-10);
y_expected = 1.414213562373095048801688e-10;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1e-10, 1e-10)");
y = gsl_hypot (1e-38, 1e-38);
y_expected = 1.414213562373095048801688e-38;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1e-38, 1e-38)");
y = gsl_hypot (1e-10, -1.0);
y_expected = 1.000000000000000000005;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1e-10, -1)");
y = gsl_hypot (-1.0, 1e-10);
y_expected = 1.000000000000000000005;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(-1, 1e-10)");
y = gsl_hypot (1e307, 1e301);
y_expected = 1.000000000000499999999999e307;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1e307, 1e301)");
y = gsl_hypot (1e301, 1e307);
y_expected = 1.000000000000499999999999e307;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1e301, 1e307)");
y = gsl_hypot (1e307, 1e307);
y_expected = 1.414213562373095048801688e307;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1e307, 1e307)");
/* Test +-Inf, finite */
y = gsl_hypot (GSL_POSINF, 1.2);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_POSINF, 1.2)");
y = gsl_hypot (GSL_NEGINF, 1.2);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_NEGINF, 1.2)");
y = gsl_hypot (1.2, GSL_POSINF);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1.2, GSL_POSINF)");
y = gsl_hypot (1.2, GSL_NEGINF);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1.2, GSL_NEGINF)");
/* Test NaN, finite */
y = gsl_hypot (GSL_NAN, 1.2);
y_expected = GSL_NAN;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_NAN, 1.2)");
y = gsl_hypot (1.2, GSL_NAN);
y_expected = GSL_NAN;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(1.2, GSL_NAN)");
/* Test NaN, NaN */
y = gsl_hypot (GSL_NAN, GSL_NAN);
y_expected = GSL_NAN;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_NAN, GSL_NAN)");
/* Test +Inf, NaN */
y = gsl_hypot (GSL_POSINF, GSL_NAN);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_POSINF, GSL_NAN)");
/* Test -Inf, NaN */
y = gsl_hypot (GSL_NEGINF, GSL_NAN);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_NEGINF, GSL_NAN)");
/* Test NaN, +Inf */
y = gsl_hypot (GSL_NAN, GSL_POSINF);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_NAN, GSL_POSINF)");
/* Test NaN, -Inf */
y = gsl_hypot (GSL_NAN, GSL_NEGINF);
y_expected = GSL_POSINF;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot(GSL_NAN, GSL_NEGINF)");
/* Test for gsl_hypot3 */
y = gsl_hypot3 (0.0, 0.0, 0.0);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(0.0, 0.0, 0.0)");
y = gsl_hypot3 (1e-10, 1e-10, 1e-10);
y_expected = 1.732050807568877293527446e-10;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(1e-10, 1e-10, 1e-10)");
y = gsl_hypot3 (1e-38, 1e-38, 1e-38);
y_expected = 1.732050807568877293527446e-38;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(1e-38, 1e-38, 1e-38)");
y = gsl_hypot3 (1e-10, 1e-10, -1.0);
y_expected = 1.000000000000000000099;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(1e-10, 1e-10, -1)");
y = gsl_hypot3 (1e-10, -1.0, 1e-10);
y_expected = 1.000000000000000000099;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(1e-10, -1, 1e-10)");
y = gsl_hypot3 (-1.0, 1e-10, 1e-10);
y_expected = 1.000000000000000000099;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(-1, 1e-10, 1e-10)");
y = gsl_hypot3 (1e307, 1e301, 1e301);
y_expected = 1.0000000000009999999999995e307;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(1e307, 1e301, 1e301)");
y = gsl_hypot3 (1e307, 1e307, 1e307);
y_expected = 1.732050807568877293527446e307;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(1e307, 1e307, 1e307)");
y = gsl_hypot3 (1e307, 1e-307, 1e-307);
y_expected = 1.0e307;
gsl_test_rel (y, y_expected, 1e-15, "gsl_hypot3(1e307, 1e-307, 1e-307)");
/* Test for acosh */
y = gsl_acosh (1.0);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_acosh(1.0)");
y = gsl_acosh (1.1);
y_expected = 4.435682543851151891329110663525e-1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_acosh(1.1)");
y = gsl_acosh (10.0);
y_expected = 2.9932228461263808979126677137742e0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_acosh(10.0)");
y = gsl_acosh (1e10);
y_expected = 2.3718998110500402149594646668302e1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_acosh(1e10)");
/* Test for asinh */
y = gsl_asinh (0.0);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(0.0)");
y = gsl_asinh (1e-10);
y_expected = 9.9999999999999999999833333333346e-11;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(1e-10)");
y = gsl_asinh (-1e-10);
y_expected = -9.9999999999999999999833333333346e-11;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(1e-10)");
y = gsl_asinh (0.1);
y_expected = 9.983407889920756332730312470477e-2;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(0.1)");
y = gsl_asinh (-0.1);
y_expected = -9.983407889920756332730312470477e-2;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(-0.1)");
y = gsl_asinh (1.0);
y_expected = 8.8137358701954302523260932497979e-1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(1.0)");
y = gsl_asinh (-1.0);
y_expected = -8.8137358701954302523260932497979e-1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(-1.0)");
y = gsl_asinh (10.0);
y_expected = 2.9982229502979697388465955375965e0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(10)");
y = gsl_asinh (-10.0);
y_expected = -2.9982229502979697388465955375965e0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(-10)");
y = gsl_asinh (1e10);
y_expected = 2.3718998110500402149599646668302e1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(1e10)");
y = gsl_asinh (-1e10);
y_expected = -2.3718998110500402149599646668302e1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_asinh(-1e10)");
/* Test for atanh */
y = gsl_atanh (0.0);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_atanh(0.0)");
y = gsl_atanh (1e-20);
y_expected = 1e-20;
gsl_test_rel (y, y_expected, 1e-15, "gsl_atanh(1e-20)");
y = gsl_atanh (-1e-20);
y_expected = -1e-20;
gsl_test_rel (y, y_expected, 1e-15, "gsl_atanh(-1e-20)");
y = gsl_atanh (0.1);
y_expected = 1.0033534773107558063572655206004e-1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_atanh(0.1)");
y = gsl_atanh (-0.1);
y_expected = -1.0033534773107558063572655206004e-1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_atanh(-0.1)");
y = gsl_atanh (0.9);
y_expected = 1.4722194895832202300045137159439e0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_atanh(0.9)");
y = gsl_atanh (-0.9);
y_expected = -1.4722194895832202300045137159439e0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_atanh(0.9)");
/* Test for pow_int */
y = gsl_pow_2 (-3.14);
y_expected = pow (-3.14, 2.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_2(-3.14)");
y = gsl_pow_3 (-3.14);
y_expected = pow (-3.14, 3.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_3(-3.14)");
y = gsl_pow_4 (-3.14);
y_expected = pow (-3.14, 4.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_4(-3.14)");
y = gsl_pow_5 (-3.14);
y_expected = pow (-3.14, 5.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_5(-3.14)");
y = gsl_pow_6 (-3.14);
y_expected = pow (-3.14, 6.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_6(-3.14)");
y = gsl_pow_7 (-3.14);
y_expected = pow (-3.14, 7.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_7(-3.14)");
y = gsl_pow_8 (-3.14);
y_expected = pow (-3.14, 8.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_8(-3.14)");
y = gsl_pow_9 (-3.14);
y_expected = pow (-3.14, 9.0);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_9(-3.14)");
{
int n;
for (n = -9; n < 10; n++)
{
y = gsl_pow_int (-3.14, n);
y_expected = pow (-3.14, n);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_int(-3.14,%d)", n);
}
}
{
unsigned int n;
for (n = 0; n < 10; n++)
{
y = gsl_pow_uint (-3.14, n);
y_expected = pow (-3.14, n);
gsl_test_rel (y, y_expected, 1e-15, "gsl_pow_uint(-3.14,%d)", n);
}
}
/* Test case for n at INT_MAX, INT_MIN */
{
double u = 1.0000001;
int n = INT_MAX;
y = gsl_pow_int (u, n);
y_expected = pow (u, n);
gsl_test_rel (y, y_expected, 1e-6, "gsl_pow_int(%.7f,%d)", u, n);
n = INT_MIN;
y = gsl_pow_int (u, n);
y_expected = pow (u, n);
gsl_test_rel (y, y_expected, 1e-6, "gsl_pow_int(%.7f,%d)", u, n);
}
/* Test for ldexp */
y = gsl_ldexp (M_PI, -2);
y_expected = M_PI_4;
gsl_test_rel (y, y_expected, 1e-15, "gsl_ldexp(pi,-2)");
y = gsl_ldexp (1.0, 2);
y_expected = 4.000000;
gsl_test_rel (y, y_expected, 1e-15, "gsl_ldexp(1.0,2)");
y = gsl_ldexp (0.0, 2);
y_expected = 0.0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_ldexp(0.0,2)");
y = gsl_ldexp (9.999999999999998890e-01, 1024);
y_expected = GSL_DBL_MAX;
gsl_test_rel (y, y_expected, 1e-15, "gsl_ldexp DBL_MAX");
y = gsl_ldexp (1e308, -2000);
y_expected = 8.7098098162172166755761e-295;
gsl_test_rel (y, y_expected, 1e-15, "gsl_ldexp(1e308,-2000)");
y = gsl_ldexp (GSL_DBL_MIN, 2000);
y_expected = 2.554675596204441378334779940e294;
gsl_test_rel (y, y_expected, 1e-15, "gsl_ldexp(DBL_MIN,2000)");
/* Test subnormals */
{
int i = 0;
volatile double x = GSL_DBL_MIN;
y_expected = 2.554675596204441378334779940e294;
x /= 2;
while (x > 0)
{
i++ ;
y = gsl_ldexp (x, 2000 + i);
gsl_test_rel (y, y_expected, 1e-15, "gsl_ldexp(DBL_MIN/2**%d,%d)",i,2000+i);
x /= 2;
}
}
/* Test for frexp */
y = gsl_frexp (0.0, &e);
y_expected = 0;
e_expected = 0;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(0) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(0) exponent");
y = gsl_frexp (M_PI, &e);
y_expected = M_PI_4;
e_expected = 2;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(pi) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(pi) exponent");
y = gsl_frexp (2.0, &e);
y_expected = 0.5;
e_expected = 2;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(2.0) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(2.0) exponent");
y = gsl_frexp (1.0 / 4.0, &e);
y_expected = 0.5;
e_expected = -1;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(0.25) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(0.25) exponent");
y = gsl_frexp (1.0 / 4.0 - 4.0 * GSL_DBL_EPSILON, &e);
y_expected = 0.999999999999996447;
e_expected = -2;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(0.25-eps) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(0.25-eps) exponent");
y = gsl_frexp (GSL_DBL_MAX, &e);
y_expected = 9.999999999999998890e-01;
e_expected = 1024;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(DBL_MAX) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(DBL_MAX) exponent");
y = gsl_frexp (-GSL_DBL_MAX, &e);
y_expected = -9.999999999999998890e-01;
e_expected = 1024;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(-DBL_MAX) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(-DBL_MAX) exponent");
y = gsl_frexp (GSL_DBL_MIN, &e);
y_expected = 0.5;
e_expected = -1021;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(DBL_MIN) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(DBL_MIN) exponent");
y = gsl_frexp (-GSL_DBL_MIN, &e);
y_expected = -0.5;
e_expected = -1021;
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(-DBL_MIN) fraction");
gsl_test_int (e, e_expected, "gsl_frexp(-DBL_MIN) exponent");
/* Test subnormals */
{
int i = 0;
volatile double x = GSL_DBL_MIN;
y_expected = 0.5;
e_expected = -1021;
x /= 2;
while (x > 0)
{
e_expected--;
i++ ;
y = gsl_frexp (x, &e);
gsl_test_rel (y, y_expected, 1e-15, "gsl_frexp(DBL_MIN/2**%d) fraction",i);
gsl_test_int (e, e_expected, "gsl_frexp(DBL_MIN/2**%d) exponent", i);
x /= 2;
}
}
/* Test for approximate floating point comparison */
{
double x, y;
int i;
x = M_PI;
y = 22.0 / 7.0;
/* test the basic function */
for (i = 0; i < 10; i++)
{
double tol = pow (10, -i);
int res = gsl_fcmp (x, y, tol);
gsl_test_int (res, -(i >= 4), "gsl_fcmp(%.5f,%.5f,%g)", x, y, tol);
}
for (i = 0; i < 10; i++)
{
double tol = pow (10, -i);
int res = gsl_fcmp (y, x, tol);
gsl_test_int (res, (i >= 4), "gsl_fcmp(%.5f,%.5f,%g)", y, x, tol);
}
}
#if HAVE_IEEE_COMPARISONS
/* Test for isinf, isnan, finite */
{
double zero, one, inf, nan;
int s;
zero = 0.0;
one = 1.0;
inf = exp (1.0e10);
nan = inf / inf;
s = gsl_isinf (zero);
gsl_test_int (s, 0, "gsl_isinf(0)");
s = gsl_isinf (one);
gsl_test_int (s, 0, "gsl_isinf(1)");
s = gsl_isinf (inf);
gsl_test_int (s, 1, "gsl_isinf(inf)");
s = gsl_isinf (-inf);
gsl_test_int (s, -1, "gsl_isinf(-inf)");
s = gsl_isinf (nan);
gsl_test_int (s, 0, "gsl_isinf(nan)");
s = gsl_isnan (zero);
gsl_test_int (s, 0, "gsl_isnan(0)");
s = gsl_isnan (one);
gsl_test_int (s, 0, "gsl_isnan(1)");
s = gsl_isnan (inf);
gsl_test_int (s, 0, "gsl_isnan(inf)");
s = gsl_isnan (-inf);
gsl_test_int (s, 0, "gsl_isnan(-inf)");
s = gsl_isnan (nan);
gsl_test_int (s, 1, "gsl_isnan(nan)");
s = gsl_finite (zero);
gsl_test_int (s, 1, "gsl_finite(0)");
s = gsl_finite (one);
gsl_test_int (s, 1, "gsl_finite(1)");
s = gsl_finite (inf);
gsl_test_int (s, 0, "gsl_finite(inf)");
s = gsl_finite (-inf);
gsl_test_int (s, 0, "gsl_finite(-inf)");
s = gsl_finite (nan);
gsl_test_int (s, 0, "gsl_finite(nan)");
}
#endif
{
double x = gsl_fdiv (2.0, 3.0);
gsl_test_rel (x, 2.0 / 3.0, 4 * GSL_DBL_EPSILON, "gsl_fdiv(2,3)");
}
/* Test constants in gsl_math.h */
{
double x = log(M_E);
gsl_test_rel (x, 1.0, 4 * GSL_DBL_EPSILON, "ln(M_E)");
}
{
double x=pow(2.0,M_LOG2E);
gsl_test_rel (x, exp(1.0), 4 * GSL_DBL_EPSILON, "2^M_LOG2E");
}
{
double x=pow(10.0,M_LOG10E);
gsl_test_rel (x, exp(1.0), 4 * GSL_DBL_EPSILON, "10^M_LOG10E");
}
{
double x=pow(M_SQRT2, 2.0);
gsl_test_rel (x, 2.0, 4 * GSL_DBL_EPSILON, "M_SQRT2^2");
}
{
double x=pow(M_SQRT1_2, 2.0);
gsl_test_rel (x, 1.0/2.0, 4 * GSL_DBL_EPSILON, "M_SQRT1_2");
}
{
double x=pow(M_SQRT3, 2.0);
gsl_test_rel (x, 3.0, 4 * GSL_DBL_EPSILON, "M_SQRT3^2");
}
{
double x = M_PI;
gsl_test_rel (x, 3.1415926535897932384626433832795, 4 * GSL_DBL_EPSILON, "M_PI");
}
{
double x = 2 * M_PI_2;
gsl_test_rel (x, M_PI, 4 * GSL_DBL_EPSILON, "2*M_PI_2");
}
{
double x = 4 * M_PI_4;
gsl_test_rel (x, M_PI, 4 * GSL_DBL_EPSILON, "4*M_PI_4");
}
{
double x = pow(M_SQRTPI, 2.0);
gsl_test_rel (x, M_PI, 4 * GSL_DBL_EPSILON, "M_SQRTPI^2");
}
{
double x = pow(M_2_SQRTPI, 2.0);
gsl_test_rel (x, 4/M_PI, 4 * GSL_DBL_EPSILON, "M_SQRTPI^2");
}
{
double x = M_1_PI;
gsl_test_rel (x, 1/M_PI, 4 * GSL_DBL_EPSILON, "M_1_SQRTPI");
}
{
double x = M_2_PI;
gsl_test_rel (x, 2.0/M_PI, 4 * GSL_DBL_EPSILON, "M_2_PI");
}
{
double x = exp(M_LN10);
gsl_test_rel (x, 10, 4 * GSL_DBL_EPSILON, "exp(M_LN10)");
}
{
double x = exp(M_LN2);
gsl_test_rel (x, 2, 4 * GSL_DBL_EPSILON, "exp(M_LN2)");
}
{
double x = exp(M_LNPI);
gsl_test_rel (x, M_PI, 4 * GSL_DBL_EPSILON, "exp(M_LNPI)");
}
{
double x = M_EULER;
gsl_test_rel (x, 0.5772156649015328606065120900824, 4 * GSL_DBL_EPSILON, "M_EULER");
}
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.6302566026,
"avg_line_length": 27.3308931186,
"ext": "c",
"hexsha": "7685d3edc258e2fcbd7db2febc1274932be4dbf9",
"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": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/sys/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/sys/test.c",
"max_line_length": 88,
"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/sys/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": 7808,
"size": 18667
} |
/* coupled_oscillators.c Kuramoto model of coupled phase oscillators */
/*
* Dynamique Populations Cellulaires
* Université Lyon 1, 2014
*
* Fichiers:
* coupled_oscillators.c
* makefile
*
* Ce code utilise la librairie gsl (GNU Scientific Library)
*
* Pour compiler sur mac ou linux:
*
* ouvrir un terminal
* >> make
* >> ./coupled_oscillators
*
* Deux fichiers sont générés en sortie:
* osc.txt : series temporelles
* order.txt: paramètre d'ordre
*
* Le fichier osc.txt contient est structuré en colonnes::
* 0 w1 w2 ... wNOSC
* t1 1 2 3 ... NOSC
*
* La premiere ligne est composee des frequences des oscillateurs. Les
* oscillateurs sont places en ordre croissant de frequence.
* t est le temps, r le module du paramètre d'ordre, psi l'argument du paramètre
* d'ordre, 1...NOSC les phases des oscillateur.
* Les phases des oscillateurs sont dans R (pas dans [0, 2*pi]).
*
* Pour visualiser les résultats, on peut utiliser gnuplot ou Matlab
*
* GNUPLOT:
* plot 'osc.txt' u 1:2:(sin($3)) nonuniform matrix with image
*
* Pour tracer le paramètre d'ordre
*
* pour r:
* plot 'order.txt' using 1:2 w lines
*
* pour psi:
* plot 'order.txt' using 1:3 w lines
*
* Pour Matlab, utiliser le script coupled_oscillators.m
*
*/
/* ================================================================= */
/* Libraries */
/* ================================================================= */
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_odeiv2.h>
struct par {
uint32_t NOSC;
double K;
double *w;
};
int ode_rhs(double t, const double y[], double f[], void *params);
int compare(const void *, const void *);
int main ( int argc, char *argv[] )
{
uint32_t NOSC=50; /* nbr oscillators */
double K=.5; /* coupling stength */
double sigma=0.5; /* std w distribution */
double *y; /* phase of oscillators */
struct par mu; /* parameters */
FILE *file_order,*file_out;
uint32_t i;
double t,tfinal;
double h,hmin;
double w_mean;
double r,psi, rx, ry;
/* get command line input parameters */
if (argc == 4)
{
NOSC = strtoul(argv[1],NULL,10);
K = strtod(argv[2],NULL);
tfinal = strtod(argv[3],NULL);
}
else
{
fprintf(stderr, "Error: call to coupled_oscillators must have the following three mandatory arguments: unsigned long NOSC, double K, and double tfinal\n");
exit(EXIT_FAILURE);
}
/* init random number generator */
const gsl_rng_type * rngT;
gsl_rng * rand_nbr_gen;
gsl_rng_env_setup();
rngT = gsl_rng_default;
rand_nbr_gen = gsl_rng_alloc(rngT);
/* gsl ode */
const gsl_odeiv2_step_type * odeT;
gsl_odeiv2_step * s;
gsl_odeiv2_control * c;
gsl_odeiv2_evolve * e;
gsl_odeiv2_system sys;
int status;
mu.NOSC = NOSC;
mu.K = K;
mu.w = malloc(NOSC*sizeof(double));
y = malloc(NOSC*sizeof(double));
w_mean = 0.0;
for (i = 0; i < NOSC; i++)
{
y[i] = 2*M_PI*gsl_rng_uniform(rand_nbr_gen)-M_PI;
mu.w[i] = gsl_ran_gaussian(rand_nbr_gen,sigma*sigma);
w_mean += mu.w[i];
}
w_mean /= NOSC;
/* sort the frequencies from slowest to fastest */
qsort(mu.w, NOSC, sizeof(double), compare);
/* remove the mean to mu.w */
file_out = fopen("osc.txt","w");
fprintf(file_out,"%.5e ",0.0);
for ( i = 0; i < NOSC; i++)
{
mu.w[i] -= w_mean;
fprintf(file_out,"%.5e ",mu.w[i]);
}
fprintf(file_out,"\n");
/* DO NOT TOUCH mu.w BELOW */
/* initialise the ode solver */
/* the solver used is a Runge-Kutta-Fehlberg (4, 5) method */
odeT = gsl_odeiv2_step_rkf45;
s = gsl_odeiv2_step_alloc(odeT,NOSC);
c = gsl_odeiv2_control_y_new(1e-6,0.0);
e = gsl_odeiv2_evolve_alloc(NOSC);
h = 1e-2;
hmin = 1e-5;
t = 0.0;
file_order = fopen("order.txt","w");
while (t < tfinal )
{
/* apply one step of the ode solver */
sys = (gsl_odeiv2_system) {ode_rhs, NULL, NOSC, &mu};
status = gsl_odeiv2_evolve_apply(e,c,s,&sys,&t,tfinal,&h,y);
if (status != GSL_SUCCESS)
break;
rx = 0;
ry = 0;
for ( i = 0; i < NOSC; i++)
{
rx += cos(y[i]);
ry += sin(y[i]);
}
rx /= NOSC;
ry /= NOSC;
r = hypot(rx,ry);
psi = atan2(ry,rx);
if (h < hmin) h = hmin;
printf(".\n");
fprintf(file_order,"%.5e %.5e %.5e\n",t,r,psi);
fprintf(file_out,"%.5e ",t);
for (i = 0; i < NOSC; i++)
{
fprintf (file_out,"%.5e ",y[i]);
}
fprintf(file_out,"\n");
}
gsl_odeiv2_evolve_free(e);
gsl_odeiv2_control_free(c);
gsl_odeiv2_step_free(s);
fclose(file_out);
fclose(file_order);
free(y);
free(mu.w);
return 0;
}
int ode_rhs(double t, const double y[], double f[], void *params)
{
struct par mu = *(struct par*)params;
uint32_t NOSC = mu.NOSC;
double K = mu.K;
double *w = mu.w;
uint32_t i,j;
double *c;
/* printf("call to ode_rhs, NOSC=%d\n",NOSC); */
c = malloc(NOSC*sizeof(double));
/* compute coupling */
for ( i = 0; i < NOSC; i++)
{
c[i] = 0.0;
for ( j = 0; j < NOSC; j++)
{
c[i] += sin(y[j]-y[i]);
}
f[i] = w[i] + K/NOSC*c[i];
/* printf("f[%d]=%f\n",i,f[i]); */
}
free(c);
return GSL_SUCCESS;
}
int compare(const void *a, const void *b)
{
const double *da = (const double *) a;
const double *db = (const double *) b;
return (*da > *db) - (*da < *db);
}
| {
"alphanum_fraction": 0.5515534312,
"avg_line_length": 24.4083333333,
"ext": "c",
"hexsha": "67651775e5d6cd050a35d95b3ae53ef8000c5f4b",
"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": "aed21ddb6b45db5d526b6003495972773131e9d2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "samubernard/popdyn",
"max_forks_repo_path": "coupled_oscillators/coupled_oscillators.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "aed21ddb6b45db5d526b6003495972773131e9d2",
"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": "samubernard/popdyn",
"max_issues_repo_path": "coupled_oscillators/coupled_oscillators.c",
"max_line_length": 160,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aed21ddb6b45db5d526b6003495972773131e9d2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "samubernard/popdyn",
"max_stars_repo_path": "coupled_oscillators/coupled_oscillators.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1763,
"size": 5858
} |
/* fft/gsl_fft_complex_float.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_FFT_COMPLEX_FLOAT_H__
#define __GSL_FFT_COMPLEX_FLOAT_H__
#include <stddef.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_fft.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
/* Power of 2 routines */
int gsl_fft_complex_float_radix2_forward (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n);
int gsl_fft_complex_float_radix2_backward (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n);
int gsl_fft_complex_float_radix2_inverse (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n);
int gsl_fft_complex_float_radix2_transform (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n,
const gsl_fft_direction sign);
int gsl_fft_complex_float_radix2_dif_forward (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n);
int gsl_fft_complex_float_radix2_dif_backward (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n);
int gsl_fft_complex_float_radix2_dif_inverse (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n);
int gsl_fft_complex_float_radix2_dif_transform (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n,
const gsl_fft_direction sign);
/* Mixed Radix general-N routines */
typedef struct
{
size_t n;
size_t nf;
size_t factor[64];
gsl_complex_float *twiddle[64];
gsl_complex_float *trig;
}
gsl_fft_complex_wavetable_float;
typedef struct
{
size_t n;
float *scratch;
}
gsl_fft_complex_workspace_float;
gsl_fft_complex_wavetable_float *gsl_fft_complex_wavetable_float_alloc (size_t n);
void gsl_fft_complex_wavetable_float_free (gsl_fft_complex_wavetable_float * wavetable);
gsl_fft_complex_workspace_float *gsl_fft_complex_workspace_float_alloc (size_t n);
void gsl_fft_complex_workspace_float_free (gsl_fft_complex_workspace_float * workspace);
int gsl_fft_complex_float_memcpy (gsl_fft_complex_wavetable_float * dest,
gsl_fft_complex_wavetable_float * src);
int gsl_fft_complex_float_forward (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n,
const gsl_fft_complex_wavetable_float * wavetable,
gsl_fft_complex_workspace_float * work);
int gsl_fft_complex_float_backward (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n,
const gsl_fft_complex_wavetable_float * wavetable,
gsl_fft_complex_workspace_float * work);
int gsl_fft_complex_float_inverse (gsl_complex_packed_array_float data,
const size_t stride,
const size_t n,
const gsl_fft_complex_wavetable_float * wavetable,
gsl_fft_complex_workspace_float * work);
int gsl_fft_complex_float_transform (gsl_complex_packed_array_float data,
const size_t stride, const size_t n,
const gsl_fft_complex_wavetable_float * wavetable,
gsl_fft_complex_workspace_float * work,
const gsl_fft_direction sign);
__END_DECLS
#endif /* __GSL_FFT_COMPLEX_FLOAT_H__ */
| {
"alphanum_fraction": 0.5999252197,
"avg_line_length": 38.2071428571,
"ext": "h",
"hexsha": "d3ff395f976eb924d1363748f0de1d7180191bf3",
"lang": "C",
"max_forks_count": 30,
"max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.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/gsl/gsl_fft_complex_float.h",
"max_issues_count": 11,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.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/gsl/gsl_fft_complex_float.h",
"max_line_length": 88,
"max_stars_count": 77,
"max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "shi-bash-cmd/qtTest",
"max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_fft_complex_float.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z",
"num_tokens": 1010,
"size": 5349
} |
#pragma once
#include <cstddef>
#include <gsl/gsl.h>
namespace util{
template<typename T>
using span_dyn = gsl::span<T>;
template<typename T, int64_t M>
using span_1d = gsl::span<T,M>;
template<typename T, int64_t M, int64_t N>
using span_2d = gsl::span<T,M,N>;
template<typename T, int64_t L, int64_t M, int64_t N>
using span_3d = gsl::span<T,L,M,N>;
//Not works and param.cpp directly uses gsl.h
template<typename... Args>
auto as_span(Args&&... args){
return gsl::as_span(std::forward<Args>(args)...);
}
template<int64_t T>
using dim = gsl::dim<T>;
template<std::ptrdiff_t Extent = gsl::dynamic_range>
using cstring_span = gsl::basic_string_span<const char, Extent>;
}//namespace util
| {
"alphanum_fraction": 0.7122507123,
"avg_line_length": 23.4,
"ext": "h",
"hexsha": "8535a886269555224ab6077d4140d224802c32ba",
"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": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "uphere-co/nlp-prototype",
"max_forks_repo_path": "rnn++/utils/span.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3",
"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": "uphere-co/nlp-prototype",
"max_issues_repo_path": "rnn++/utils/span.h",
"max_line_length": 64,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "uphere-co/nlp-prototype",
"max_stars_repo_path": "rnn++/utils/span.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 204,
"size": 702
} |
#pragma once
#include "Cesium3DTiles/Library.h"
#include "CesiumGltf/Model.h"
#include <functional>
#include <glm/mat4x4.hpp>
#include <gsl/span>
#include <optional>
namespace Cesium3DTiles {
/**
* @brief Functions for loading and processing glTF models.
*
* This class offers basic functions for loading glTF models as
* `CesiumGltf::Model` instances, and for processing the mesh primitives that
* appear in the resulting models.
*/
class CESIUM3DTILES_API Gltf final {
public:
/** @brief This class cannot be instantiated */
Gltf() = delete;
/**
* @brief A callback function for {@link Gltf::forEachPrimitiveInScene}.
*/
typedef void ForEachPrimitiveInSceneCallback(
CesiumGltf::Model& gltf,
CesiumGltf::Node& node,
CesiumGltf::Mesh& mesh,
CesiumGltf::MeshPrimitive& primitive,
const glm::dmat4& transform);
/**
* @brief Apply the given callback to all relevant primitives.
*
* If the given `sceneID` is non-negative and exists in the given glTF,
* then the given callback will be applied to all meshes of this scene.
*
* If the given `sceneId` is negative, then the meshes that the callback
* will be applied to depends on the structure of the glTF model:
*
* * If the glTF model has a default scene, then it will
* be applied to all meshes of the default scene.
* * Otherwise, it will be applied to all meshes of the the first scene.
* * Otherwise (if the glTF model does not contain any scenes), it will
* be applied to all meshes that can be found by starting a traversal
* at the root node.
* * Otherwise (if there are no scenes and no nodes), then all meshes
* will be traversed.
*
* @param gltf The glTF model.
* @param sceneID The scene ID (index)
* @param callback The callback to apply
*/
static void forEachPrimitiveInScene(
CesiumGltf::Model& gltf,
int sceneID,
std::function<ForEachPrimitiveInSceneCallback>&& callback);
/**
* @brief A callback function for {@link Gltf::forEachPrimitiveInScene}.
*/
typedef void ForEachPrimitiveInSceneConstCallback(
const CesiumGltf::Model& gltf,
const CesiumGltf::Node& node,
const CesiumGltf::Mesh& mesh,
const CesiumGltf::MeshPrimitive& primitive,
const glm::dmat4& transform);
/** @copydoc Gltf::forEachPrimitiveInScene() */
static void forEachPrimitiveInScene(
const CesiumGltf::Model& gltf,
int sceneID,
std::function<ForEachPrimitiveInSceneConstCallback>&& callback);
};
} // namespace Cesium3DTiles
| {
"alphanum_fraction": 0.6993387787,
"avg_line_length": 32.1375,
"ext": "h",
"hexsha": "648931f8ea345d6dc5e8e7eabde7c3bf574a85d0",
"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": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "zy6p/cesium-native",
"max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Gltf.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b",
"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": "zy6p/cesium-native",
"max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Gltf.h",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "zy6p/cesium-native",
"max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Gltf.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-27T04:47:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-27T04:47:23.000Z",
"num_tokens": 677,
"size": 2571
} |
#ifndef PDCD_SMSVM_H
#define PDCD_SMSVM_H
#include <string>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <stdio.h> /* printf */
#include <time.h>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <math.h>
//This class implements the method SMART_CD.
/*
The optimization problem to solve is of the form f(x)+g(x)+h(Mx) ;
where f(x)=sum_{j=1}^m lambda_f[j] phi_j(<A_j,x>) and g(x)=sum_{i=1}^n g_i(x_i), h(x)= |x|_1. We all assume that each phi_j is 1-smooth.
*/
template<typename L, typename D>
class PDCD_SMSVM
{
private:
std::vector<D> Au;
std::vector<D> Az;
std::vector<D> Mu;
std::vector<D> Mz;
std::vector<D> Mx;
std::vector<D> Ax;
std::vector<D> lambda_f;
protected:
// parameters
D mu_f;
D mu_psi;
D mu_g;
L n; // x\in \R^n
L tau; //number of threads on each node/computer
D sumofLi;
// variables
std::vector<D> u;
std::vector<D> z;
std::vector<D> x;
std::vector<D> v;
std::vector<D> L_M;
std::vector<D> L_f;
std::vector<D> t;
D gamma;
D theta;
D theta0;
L m_1;
L m_2;
// sampling variables
std::vector<D> proba_vector;
std::vector<D> S;
std::vector<D> all_n;
std::vector<D> sampled;
D max_p;
D min_p;
// auxiliary variables
L max_nb_loops;
L evaluation;
ofstream samp;
L nb_iters;
L nb_of_iters_per_loop;
L print_every_N;
D running_time;
Matrix<L,D> data_A;
Matrix<L, D> data_M;
std::vector<D> lambda;
std::vector<D> M_tlambda;
D beta_s;
D function_value;
D residual1;
D residual2;
public:
gsl_rng * rng;
virtual inline D gradient_of_phi_j(D, L){return D(NULL);}
virtual inline D value_of_g_i(D, L){return D(NULL);}
virtual inline D value_of_phi_j(D, L){return D(NULL);}
virtual inline D prox_of_g_i(D,D,D, L){return D(NULL);}
virtual inline D value_of_phistar_i(D,L) {return D(NULL);}
virtual inline void set_matrix_M(){}
virtual inline void set_matrix_A(){}
PDCD_SMSVM()
{
}
void set_rng()
{
gsl_rng_env_setup();
const gsl_rng_type * T;
T = gsl_rng_default;
rng = gsl_rng_alloc(T);
gsl_rng_set(rng,time(NULL));
//gsl_rng_set(rng, 27432042);
}
// sample i with probability pi=proba_vector[i]
L sampling()
{
//L i=(floor)(gsl_rng_uniform(rng)*n);
L i=gsl_rng_uniform_int(rng, n);
if(tau==1)
{
D y=gsl_rng_uniform(rng);
while(y*max_p>proba_vector[i])
{
i=(floor)(gsl_rng_uniform(rng)*n);
y=gsl_rng_uniform(rng);
}
}
return i;
}
// sample S
void batch_sampling()
{
if(tau<n)
{
L i=sampling();
for(L k=0;k<tau;k++)
{
while(sampled[i]==1)
{
i=sampling();
}
sampled[i]=1;
S[k]=i;
}
for(L k=0;k<tau;k++)
{
sampled[S[k]]=0;
}
}
else {
S=all_n;
//cout<<"s=all_n"<<endl;
}
}
void compute_x()
{
for(L i=0;i<n;i++){
x[i]=gamma*u[i]+z[i];
}
for(L j=0;j<m_2;j++){
Mx[j]=gamma*Mu[j]+Mz[j];
}
for(L j=0;j<m_1;j++){
Ax[j]=gamma*Au[j]+Az[j];
}
}
inline void compute_function_value() {
D res=0;
D res2= 0;
D tmp1= 0;
for(L i=0;i<this->n;i++){
res+=value_of_g_i(x[i],i);
}
for(L j=0;j<m_1;j++){
res+=lambda_f[j]*value_of_phi_j(Ax[j],j);
}
for(L j=0;j<m_2;j++){
if (1- Mx[j]> tmp1){
tmp1= 1- Mx[j];
}
res2+=max(0.0,1- Mx[j]);
}
residual1= tmp1;
residual2= res2/m_2;
function_value=res+ m_2*residual2;;
}
void initialize(D beta_0, vector<D> & x0, vector<D> & y0, L val_tau, D p_N, D val_lambda_f)
{
set_matrix_M();
set_matrix_A();
this->tau=val_tau;
m_1=data_A.get_n();
m_2=data_M.get_n();
cout<<"m_1="<<m_1<<endl;
cout<<"m_2="<<m_2<<endl;
lambda_f.resize(m_1,val_lambda_f);
n=data_A.nfeatures;
tau=val_tau;
all_n.resize(n,0);
for(L i=0;i<n;i++)
all_n[i]=i;
print_every_N= p_N;
nb_of_iters_per_loop=floor(max(1.,n/(tau+0.0)));
lambda.resize(m_2,0);
for(L j=0;j<m_2;j++)
lambda[j]=y0[j];
u.clear();
u.resize(n,0);
z.clear();
z.resize(n,0);
x.clear();
x.resize(n,0);
for(L i=0;i<n;i++)
{
z[i]=x0[i];
x[i]=x0[i];
}
sampled.clear();
sampled.resize(n,0);
S.clear();
S.resize(tau,0);
t.clear();
t.resize(n,0);
M_tlambda.resize(n,0);
compute_Mty();
Au.clear();
Au.resize(m_1,0);
Az.clear();
Az.resize(m_1,0);
Ax.clear();
Ax.resize(m_1,0);
Mu.clear();
Mu.resize(m_2,0);
Mz.clear();
Mz.resize(m_2,0);
Mx.clear();
Mx.resize(m_2,0);
compute_Az(x0);
compute_Mz(x0);
compute_Ax(x0);
compute_Mx(x0);
beta_s= beta_0;
set_v();
set_p();
set_rng();
theta0= min_p;
theta= theta0;
cout<< "theta0= "<< theta0<< endl;
gamma= 1- theta0;
cout<<"finished SMART_CD initializing"<<endl;
}
inline void compute_and_record_res(){
if (nb_iters%print_every_N== 0){
cout<< "gamma= "<< gamma<< " theta= "<< theta<< " beta_s= "<< beta_s<< endl;
//compute_KKT_residual();
compute_function_value();
cout<<setprecision(9)<<"Iteration: "<<nb_iters<<"; time="<<running_time<<"; infeasibility= "<< residual1<<" "<< residual2<<"; function value="<<function_value<< endl;
samp<<setprecision(9)<< nb_iters<<" "<<running_time<<" "<<residual1<< " "<< residual2<< " "<< function_value<<" "<<endl;
}
}
inline D partial_i_of_f(L i)
{
D res=0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
D tmp=lambda_f[j]*gradient_of_phi_j(gamma*Au[j]+Az[j], j);
res+=data_A.A_t[k]*tmp;
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
D tmp=(gamma*Mu[j]+Mz[j]- 1)/beta_s+lambda[j];
if (tmp> 0){
tmp= 0;
}
else if( tmp< -1){
tmp= -1;
}
res+=data_M.A_t[k]*tmp;
}
return res;
}
inline void set_v()
{
v.resize(n,0);
L_f.resize(n,0);
L_M.resize(n,0);
D maxv=0;
D minv=std::numeric_limits<double>::max();
D sumv=0;
D sumvi1=0;
L sumw=0;
L maxw=0;
L minw=n;
sumofLi=0;
for(L j=0;j<m_1;j++)
{
sumw+=data_A.w_t[j];
maxw=max(maxw,data_A.w_t[j]);
minw=min(minw,data_A.w_t[j]);
}
cout<<"sumw="<<sumw<<"; maxw="<<maxw<<"; minw="<<minw<<endl;
for(L i=0;i<n;i++)
{
D lfi=0;
D lmi=0;
D lfi1= 0;
D lmi1= 0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
lfi+=(1.+(data_A.w_t[j]-1.)*(tau-1.)/max(n-1.,1.))*data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];
lfi1+=data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
lmi+=(1.+(data_M.w_t[j]-1.)*(tau-1.)/max(n-1.,1.))*data_M.A_t[k]*data_M.A_t[k];
lmi1+=data_M.A_t[k]*data_M.A_t[k];
}
L_f[i]=lfi;
L_M[i]= lmi;
sumv+=lfi;
sumvi1+=lfi1;
if(maxv<lfi) maxv=lfi;
if(minv>lfi) minv=lfi;
}
if(tau==n){
for(L i=0;i<n;i++)
L_f[i]=sumvi1;
}
sumofLi=sumvi1;
cout<<" max of v: "<<maxv<<" ; min of v: "<<minv<<" ; sumofv: "<<sumv<<" sumofLi="<<sumofLi<<endl;
}
inline void set_p(){
proba_vector.resize(n,0.0);
D res= 0;
D tmp= 1;
D tmp2= 0;
for (L i=0; i< n; i++){
res+= sqrt(L_f[i]+ L_M[i]/beta_s);
}
for (L i= 0; i< n; i++){
proba_vector[i]= sqrt(L_f[i]+ L_M[i]/beta_s)/res;
if (proba_vector[i]< tmp){
tmp= proba_vector[i];
}
if (proba_vector[i]> tmp2){
tmp2= proba_vector[i];
}
}
if (tmp== 0){
for (L i= 0; i< n; i++){
proba_vector[i]= 1.0/n;
}
min_p= 1.0/n;
max_p= 1.0/n;
}
else{
min_p= tmp;
max_p= tmp2;
}
cout<< "max_p= "<< max_p<< "; min_p= "<< min_p<< endl;
}
inline void update_z_coordinate( L i, D dz){
z[i]+=dz;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
Az[j]+=dz*data_A.A_t[k];
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
Mz[j]+=dz*data_M.A_t[k];
//if(j==2869) cout<<"gamma="<<gamma<<"; "<<dz<<"; "<<Mz[j]<<endl;
}
}
inline void update_x_coordinate( L i, D dx){
x[i]+=dx;
x[i]=x[i];
L j;
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
j=data_M.col_idx[k];
Mx[j]+=dx*data_M.A_t[k];
}
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
j=data_A.col_idx[k];
Ax[j]+=dx*data_A.A_t[k];
}
}
inline void update_u_coordinate( L i, D du){
u[i]+=du;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
Au[j]+=du*data_A.A_t[k];
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
Mu[j]+=du*data_M.A_t[k];
}
}
void compute_Au(){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Au[j]+=u[kj]*data_A.A[k];
}
}
void compute_Mu(){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mu[j]+=u[kj]*data_M.A[k];
}
}
void compute_Az(){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Az[j]+=z[kj]*data_A.A[k];
}
}
void compute_Mz(){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mz[j]+=z[kj]*data_M.A[k];
}
}
void compute_Au(vector<D> & x0){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Au[j]+=x0[kj]*data_A.A[k];
}
}
void compute_Az(vector<D> & x0){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Az[j]+=x0[kj]*data_A.A[k];
}
}
void compute_Mu(vector<D> & x0){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mu[j]+=x0[kj]*data_M.A[k];
}
}
void compute_Mz(vector<D> & x0){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mz[j]+=x0[kj]*data_M.A[k];
}
}
void compute_Mx(vector<D> & x0){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mx[j]+=x0[kj]*data_M.A[k];
}
}
void compute_Ax(vector<D> & x0){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Ax[j]+=x0[kj]*data_A.A[k];
}
}
void compute_Mty(){
M_tlambda.clear();
M_tlambda.resize(this->n,0);
for(L i=0;i<this->n;i++)
{
for(L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++){
L j=data_M.col_idx[k];
M_tlambda[i]+=lambda[j]*data_M.A_t[k];
}
}
}
void update_theta()
{
theta= (sqrt(theta*theta*theta*theta+ 4*theta*theta)- theta*theta)/2;
}
void reset(){
beta_s= beta_s/(1+ theta);
}
void PDCD_SMSVM_solver(D beta_0, vector<D> & x0,vector<D> & y0, L val_tau, L max_nb_epoch, L p_N, D val_lambda_f,string filename1, D time2)
{
initialize(beta_0, x0, y0, val_tau, p_N, val_lambda_f);
cout<<"running SMART_CD"<<" ; "<<filename1<<" max_nb_epoch "<<max_nb_epoch<<endl;
nb_iters=0;
filename1="results/PDCD_SMSVM_"+filename1;
samp.open(filename1.c_str());
//srand48(27432042);
srand(time(NULL));
running_time= 0;
print_every_N=p_N;
compute_and_record_res();
D start;
start = std::clock();
while(nb_iters<max_nb_epoch)
{
start = std::clock();
D ti=0;
//D si=0;
D gi=0;
D Li=0;
L i=0;
for(L it=0;it<nb_of_iters_per_loop;it++)
{
gamma*=(1-theta);
if(theta==1) gamma=1;
batch_sampling();
for(L it_S=0;it_S<tau;it_S++)
{
i=S[it_S];
gi=partial_i_of_f(i);
Li=(L_f[i]+ L_M[i]/beta_s)*theta/theta0;
t[i]=prox_of_g_i(gi, Li, z[i],i);
}
for(L it_S=0;it_S<tau;it_S++)
{
i=S[it_S];
ti=t[i];
update_z_coordinate(i, ti);
update_u_coordinate(i, -(1- theta/theta0)/gamma*ti);
}
update_theta();
reset();
}
running_time+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;
nb_iters++;
compute_x();
compute_and_record_res();
if (running_time> time2){
break;
}
}
}
};
#endif
| {
"alphanum_fraction": 0.4874562219,
"avg_line_length": 21.3603053435,
"ext": "h",
"hexsha": "65e2edf03ba1a78009523641bc882f907b26cc6d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "lifei16/supplementary_code",
"max_forks_repo_path": "IPALM_OPENMP/PDCD_SMSVM.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-Source-Code"
],
"max_issues_repo_name": "lifei16/supplementary_code",
"max_issues_repo_path": "IPALM_OPENMP/PDCD_SMSVM.h",
"max_line_length": 175,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "lifei16/supplementary_code",
"max_stars_repo_path": "IPALM_OPENMP/PDCD_SMSVM.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4548,
"size": 13991
} |
/*Python3 includes*/
#include <Python.h>
/*System includes*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <sys/stat.h>
#include <float.h>
#include <sys/time.h>
/*GSL includes*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_cblas.h>
#include <pthread.h>
/*User includes*/
#include "vbgmmmodule.h"
char szMLInputFile[BUFSIZ]; // mustlink file path
// Module method definition
static PyObject *get_wrapper_version(PyObject *self, PyObject *args)
{
(void)self;
(void)args;
return Py_BuildValue("s", "0.3");
}
static PyObject *vbgmm_get_n_jobs(PyObject *self, PyObject *args)
{
(void)self;
(void)args;
return PyLong_FromLong(N_RTHREADS);
}
static PyObject *vbgmm_testfit(PyObject *self, PyObject *args)
{
(void)self;
const char *szFileStub = "/home/kgravouil/THESE/data/FENNEC/fennec/c-concoct/tests";
int nKStart = 60, nLMin = 1000, nMaxIter = 30;
unsigned long lSeed = 666;
double dEpsilon = 1e-1;
int bCout = 0;
int sts;
sts = driver(szFileStub, nKStart, nLMin, lSeed, nMaxIter, dEpsilon, bCout);
return Py_BuildValue("i", sts);
}
static PyObject *vbgmm_fit(PyObject *self, PyObject *args)
{
(void)self;
const char *szFileStub = NULL;
int nKStart = 0, nLMin = 0, nMaxIter;
unsigned long lSeed;
double dEpsilon;
int bCout = 0;
int sts;
if (!PyArg_ParseTuple(args, "siikidi", &szFileStub, &nKStart, &nLMin, &lSeed, &nMaxIter,
&dEpsilon, &bCout))
return NULL;
//TODO: return the np.array of clustering result
sts = driver(szFileStub, nKStart, nLMin, lSeed, nMaxIter, dEpsilon, bCout);
return Py_BuildValue("i", sts);
}
//Method definition object for this extension, these argumens mean:
//ml_name: The name of the method
//ml_meth: Function pointer to the method implementation
//ml_flags: Flags indicating special features of this method, such as
// accepting arguments, accepting keyword arguments, being a
// class method, or being a static method of a class.
//ml_doc: Contents of this method's docstring
static PyMethodDef vbgmm_methods[] = {
{"get_wrapper_version",
get_wrapper_version,
METH_NOARGS,
"Return the python wrapper version"},
{"get_n_jobs",
vbgmm_get_n_jobs,
METH_NOARGS,
"Return number of jobs to run."},
{"fit",
vbgmm_fit,
METH_VARARGS,
"Fit a variational Bayesian Gaussian mixture."},
{"test_fit",
vbgmm_testfit,
METH_VARARGS,
"Quick test of fit function."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
//Module definition
//The arguments of this structure tell Python what to call your extension,
//what its methods are and where to look for its method definitions
static struct PyModuleDef vbgmm_definition = {
PyModuleDef_HEAD_INIT,
"vbgmm",
"A Python module that compute VBGMM",
-1,
vbgmm_methods};
//Module initialization
//Python calls this function when importing your extension. It is important
//that this function is named PyInit_[[your_module_name]] exactly, and matches
//the name keyword argument in setup.py's setup() call.
PyMODINIT_FUNC PyInit_vbgmm(void)
{
Py_Initialize();
return PyModule_Create(&vbgmm_definition);
}
/*** core functions ***/
int driver(const char *szFileStub, int nKStart, int nLMin, unsigned long lSeed,
int nMaxIter, double dEpsilon, int bCOut)
{
t_Params tParams;
t_Data tData;
gsl_rng *ptGSLRNG = NULL;
const gsl_rng_type *ptGSLRNGType = NULL;
int nD = 0, nN = 0;
char szOFile[MAX_LINE_LENGTH];
t_VBParams tVBParams;
t_Cluster *ptBestCluster = NULL;
gsl_matrix *ptTemp = NULL;
gsl_matrix *ptTVar = NULL;
sprintf(szMLInputFile, "%s%s%d.dat", szFileStub, MLINPUT_FILE, nLMin);
/*initialise GSL RNG */
gsl_rng_env_setup();
gsl_set_error_handler_off();
ptGSLRNGType = gsl_rng_default;
ptGSLRNG = gsl_rng_alloc(ptGSLRNGType);
/*get command line params */
tParams.nKStart = nKStart;
tParams.nLMin = nLMin;
tParams.nMaxIter = nMaxIter;
tParams.dEpsilon = dEpsilon;
tParams.lSeed = lSeed;
setParams(&tParams, szFileStub);
/*read in input data */
readInputData(tParams.szInputFile, &tData);
readPInputData(tParams.szPInputFile, &tData);
nD = tData.nD;
nN = tData.nN;
ptTemp = gsl_matrix_alloc(tData.nT, nD);
ptTVar = gsl_matrix_alloc(tData.nT, tData.nT);
setVBParams(&tVBParams, &tData);
ptBestCluster = (t_Cluster *)malloc(sizeof(t_Cluster));
ptBestCluster->nN = nN;
ptBestCluster->nK = tParams.nKStart;
ptBestCluster->nD = nD;
ptBestCluster->ptData = &tData;
ptBestCluster->ptVBParams = &tVBParams;
ptBestCluster->lSeed = tParams.lSeed;
ptBestCluster->nMaxIter = tParams.nMaxIter;
ptBestCluster->dEpsilon = tParams.dEpsilon;
if (bCOut > 0)
ptBestCluster->szCOutFile = (char *)szFileStub;
else
ptBestCluster->szCOutFile = NULL;
runRThreads((void *)&ptBestCluster);
compressCluster(ptBestCluster);
calcCovarMatrices(ptBestCluster, &tData);
// printing clustering results
printf("[DEBUG] Printing clustering\n");
sprintf(szOFile, "%sclustering_gt%d.csv", tParams.szOutFileStub,
tParams.nLMin);
writeClusters(szOFile, ptBestCluster, &tData);
/*free up memory in data object */
printf("[DEBUG] Cleaning memory\n");
destroyData(&tData);
/*free up best BIC clusters */
destroyCluster(ptBestCluster);
free(ptBestCluster);
destroyParams(&tParams);
gsl_rng_free(ptGSLRNG);
gsl_matrix_free(tVBParams.ptInvW0);
gsl_matrix_free(ptTemp);
gsl_matrix_free(ptTVar);
printf("[INFO] done\n");
return EXIT_SUCCESS;
}
void setParams(t_Params *ptParams, const char *szFileStub)
{
ptParams->szInputFile = (char *)malloc(MAX_LINE_LENGTH * sizeof(char));
if (!ptParams->szInputFile)
goto memoryError;
ptParams->szPInputFile = (char *)malloc(MAX_LINE_LENGTH * sizeof(char));
if (!ptParams->szPInputFile)
goto memoryError;
sprintf(ptParams->szInputFile, "%s%s%d.csv", szFileStub, INPUT_FILE,
ptParams->nLMin);
sprintf(ptParams->szPInputFile, "%s%s%d.csv", szFileStub, PINPUT_FILE,
ptParams->nLMin);
ptParams->szOutFileStub = szFileStub;
return;
memoryError:
fprintf(stderr, "Failed allocating memory in setParams\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void destroyParams(t_Params *ptParams)
{
free(ptParams->szInputFile);
free(ptParams->szPInputFile);
}
void setVBParams(t_VBParams *ptVBParams, t_Data *ptData)
{
int i = 0, nD = ptData->nD;
double adVar[nD], adMu[nD];
ptVBParams->dBeta0 = DEF_BETA0;
ptVBParams->dNu0 = (double)nD;
ptVBParams->ptInvW0 = gsl_matrix_alloc(nD, nD);
calcSampleVar(ptData, adVar, adMu);
gsl_matrix_set_zero(ptVBParams->ptInvW0);
for (i = 0; i < nD; i++)
{
double dRD = adVar[i] * ((double)nD);
gsl_matrix_set(ptVBParams->ptInvW0, i, i, dRD);
}
ptVBParams->dLogWishartB =
dLogWishartB(ptVBParams->ptInvW0, nD, ptVBParams->dNu0, TRUE);
}
void readInputData(const char *szFile, t_Data *ptData)
{
double **aadX = NULL;
int i = 0, j = 0, nD = 0, nN = 0;
char szLine[MAX_LINE_LENGTH];
FILE *ifp = NULL;
ifp = fopen(szFile, "r");
if (ifp)
{
char *szTok = NULL;
char *pcError = NULL;
if (fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)
goto formatError;
szTok = strtok(szLine, DELIM);
/*count dimensions */
while (strtok(NULL, DELIM) != NULL)
{
nD++;
}
/*count data points */
while (fgets(szLine, MAX_LINE_LENGTH, ifp) != NULL)
{
nN++;
}
fclose(ifp);
/*reopen input file */
ifp = fopen(szFile, "r");
if (fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)
goto formatError;
/*allocate memory for dimension names */
ptData->aszDimNames = (char **)malloc(nD * sizeof(char *));
if (!ptData->aszDimNames)
goto memoryError;
szTok = strtok(szLine, DELIM);
/*read in dim names */
for (i = 0; i < nD; i++)
{
szTok = strtok(NULL, DELIM);
ptData->aszDimNames[i] = strdup(szTok);
}
/*allocate memory for data matrix */
aadX = (double **)malloc(nN * sizeof(double *));
if (!aadX)
goto memoryError;
for (i = 0; i < nN; i++)
{
aadX[i] = (double *)malloc(nD * sizeof(double));
if (!aadX[i])
goto memoryError;
}
/*read in input data */
ptData->aszSampleNames = (char **)malloc(nN * sizeof(char *));
if (!ptData->aszSampleNames)
goto memoryError;
for (i = 0; i < nN; i++)
{
if (fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)
goto formatError;
szTok = strtok(szLine, DELIM);
ptData->aszSampleNames[i] = strdup(szTok);
for (j = 0; j < nD; j++)
{
szTok = strtok(NULL, DELIM);
aadX[i][j] = strtod(szTok, &pcError);
if (*pcError != '\0')
{
goto formatError;
}
}
}
fclose(ifp);
}
else
{
fprintf(stderr,
"Failed to open abundance data file %s aborting\n",
szFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
ptData->nD = nD;
ptData->nN = nN;
ptData->aadX = aadX;
return;
memoryError:
fprintf(stderr, "Failed allocating memory in readInputData\n");
fflush(stderr);
exit(EXIT_FAILURE);
formatError:
fprintf(stderr, "Incorrectly formatted abundance data file\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void readPInputData(const char *szFile, t_Data *ptData)
{
int i = 0, j = 0, nD = ptData->nD, nT = 0;
char szLine[MAX_LINE_LENGTH];
FILE *ifp = NULL;
ifp = fopen(szFile, "r");
if (ifp)
{
char *szTok = NULL;
char *pcError = NULL;
nT = 1;
if (fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)
goto memoryError;
szTok = strtok(szLine, DELIM);
/*count dimensions */
while (strtok(NULL, DELIM) != NULL)
{
nT++;
}
ptData->ptTMatrix = gsl_matrix_alloc(nT, nD);
fclose(ifp);
/*reopen input file */
ifp = fopen(szFile, "r");
for (i = 0; i < nD; i++)
{
double dTemp = 0.0;
if (fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL)
goto formatError;
szTok = strtok(szLine, DELIM);
dTemp = strtod(szTok, &pcError);
if (*pcError != '\0')
{
goto formatError;
}
gsl_matrix_set(ptData->ptTMatrix, 0, i, dTemp);
for (j = 1; j < nT; j++)
{
szTok = strtok(NULL, DELIM);
dTemp = strtod(szTok, &pcError);
if (*pcError != '\0')
{
goto formatError;
}
gsl_matrix_set(ptData->ptTMatrix, j, i, dTemp);
}
}
fclose(ifp);
}
else
{
fprintf(stderr,
"Failed to open abundance data file %s aborting\n",
szFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
ptData->nT = nT;
return;
formatError:
fprintf(stderr, "Incorrectly formatted abundance data file\n");
fflush(stderr);
exit(EXIT_FAILURE);
memoryError:
fprintf(stderr, "Failed allocating memory in readPInputFile\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void destroyData(t_Data *ptData)
{
int nN = ptData->nN, nD = ptData->nD;
int i = 0;
gsl_matrix_free(ptData->ptTMatrix);
for (i = 0; i < nD; i++)
{
free(ptData->aszDimNames[i]);
}
free(ptData->aszDimNames);
for (i = 0; i < nN; i++)
{
free(ptData->aadX[i]);
}
free(ptData->aadX);
for (i = 0; i < nN; i++)
{
free(ptData->aszSampleNames[i]);
}
free(ptData->aszSampleNames);
return;
}
void destroyCluster(t_Cluster *ptCluster)
{
int i = 0, nN = ptCluster->nN, nKSize = ptCluster->nKSize;
if (ptCluster->szCOutFile != NULL)
{
free(ptCluster->szCOutFile);
}
free(ptCluster->anMaxZ);
free(ptCluster->anW);
for (i = 0; i < nN; i++)
{
free(ptCluster->aadZ[i]);
}
free(ptCluster->aadZ);
free(ptCluster->adLDet);
free(ptCluster->adPi);
free(ptCluster->adBeta);
free(ptCluster->adNu);
for (i = 0; i < nKSize; i++)
{
free(ptCluster->aadMu[i]);
free(ptCluster->aadM[i]);
}
free(ptCluster->aadMu);
free(ptCluster->aadM);
for (i = 0; i < nKSize; i++)
{
gsl_matrix_free(ptCluster->aptSigma[i]);
gsl_matrix_free(ptCluster->aptCovar[i]);
}
free(ptCluster->aptSigma);
free(ptCluster->aptCovar);
return;
}
void allocateCluster(t_Cluster *ptCluster, int nN, int nK, int nD,
t_Data *ptData, long lSeed, int nMaxIter, double dEpsilon,
char *szCOutFile)
{
int i = 0, j = 0, k = 0;
ptCluster->szCOutFile = szCOutFile;
ptCluster->ptVBParams = NULL;
ptCluster->lSeed = lSeed;
ptCluster->nMaxIter = nMaxIter;
ptCluster->dEpsilon = dEpsilon;
ptCluster->ptData = ptData;
ptCluster->nN = nN;
ptCluster->nK = nK;
ptCluster->nKSize = nK;
ptCluster->nD = nD;
ptCluster->dVBL = 0.0;
ptCluster->anMaxZ = (int *)malloc(nN * sizeof(int)); /*destroyed */
if (!ptCluster->anMaxZ)
goto memoryError;
ptCluster->anW = (int *)malloc(nK * sizeof(int)); /*destroyed */
if (!ptCluster->anW)
goto memoryError;
for (i = 0; i < nN; i++)
{
ptCluster->anMaxZ[i] = NOT_SET;
}
for (i = 0; i < nK; i++)
{
ptCluster->anW[i] = 0;
}
ptCluster->aadZ = (double **)malloc(nN * sizeof(double *)); /*destroyed */
if (!ptCluster->aadZ)
goto memoryError;
for (i = 0; i < nN; i++)
{
ptCluster->aadZ[i] = (double *)malloc(nK * sizeof(double)); /*destroyed */
if (!ptCluster->aadZ[i])
goto memoryError;
for (j = 0; j < nK; j++)
{
ptCluster->aadZ[i][j] = 0.0;
}
}
ptCluster->adLDet = (double *)malloc(nK * sizeof(double)); /*all */
ptCluster->adPi = (double *)malloc(nK * sizeof(double));
ptCluster->adBeta = (double *)malloc(nK * sizeof(double));
ptCluster->adNu = (double *)malloc(nK * sizeof(double)); /*destroyed */
if (!ptCluster->adLDet || !ptCluster->adPi)
goto memoryError;
if (!ptCluster->adBeta || !ptCluster->adNu)
goto memoryError;
for (k = 0; k < nK; k++)
{
ptCluster->adLDet[k] = 0.0;
ptCluster->adPi[k] = 0.0;
ptCluster->adBeta[k] = 0.0;
ptCluster->adNu[k] = 0.0;
}
ptCluster->aadMu = (double **)malloc(nK * sizeof(double *));
if (!ptCluster->aadMu)
goto memoryError;
ptCluster->aadM = (double **)malloc(nK * sizeof(double *));
if (!ptCluster->aadM)
goto memoryError;
for (i = 0; i < nK; i++)
{
ptCluster->aadM[i] = (double *)malloc(nD * sizeof(double));
if (!ptCluster->aadM[i])
goto memoryError;
ptCluster->aadMu[i] = (double *)malloc(nD * sizeof(double));
if (!ptCluster->aadMu[i])
goto memoryError;
}
ptCluster->aptSigma = (gsl_matrix **)malloc(nK * sizeof(gsl_matrix *));
if (!ptCluster->aptSigma)
goto memoryError;
for (i = 0; i < nK; i++)
{
ptCluster->aptSigma[i] =
(gsl_matrix *)gsl_matrix_alloc(nD, nD);
}
ptCluster->aptCovar = (gsl_matrix **)malloc(nK * sizeof(gsl_matrix *));
if (!ptCluster->aptCovar)
goto memoryError;
for (i = 0; i < nK; i++)
{
ptCluster->aptCovar[i] =
(gsl_matrix *)gsl_matrix_alloc(nD, nD);
}
return;
memoryError:
fprintf(stderr, "Failed allocating memory in allocateCluster\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void writeSquareMatrix(char *szFile, gsl_matrix *ptMatrix, int nD)
{
int i = 0, j = 0;
FILE *ofp = fopen(szFile, "w");
if (ofp)
{
for (i = 0; i < nD; i++)
{
for (j = 0; j < nD - 1; j++)
{
fprintf(ofp, "%f,",
gsl_matrix_get(ptMatrix, i, j));
}
fprintf(ofp, "%f\n", gsl_matrix_get(ptMatrix, i, j));
}
}
else
{
fprintf(stderr,
"Failed to open %s for writing in writeSquareMatrix\n",
szFile);
fflush(stderr);
}
}
double decomposeMatrix(gsl_matrix *ptSigmaMatrix, int nD)
{
double dDet = 0.0;
int status;
int l = 0;
status = gsl_linalg_cholesky_decomp(ptSigmaMatrix);
if (status == GSL_EDOM)
{
fprintf(stderr,
"Failed Cholesky decomposition in decomposeMatrix\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
else
{
for (l = 0; l < nD; l++)
{
double dT = gsl_matrix_get(ptSigmaMatrix, l, l);
dDet += 2.0 * log(dT);
}
gsl_linalg_cholesky_invert(ptSigmaMatrix);
return dDet;
}
}
void performMStep(t_Cluster *ptCluster, t_Data *ptData)
{
int i = 0, j = 0, k = 0, l = 0, m = 0;
int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;
double **aadZ = ptCluster->aadZ, **aadX = ptData->aadX;
double *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi;
double **aadCovar = NULL, **aadInvWK = NULL;
t_VBParams *ptVBParams = ptCluster->ptVBParams;
// gsl_matrix *ptSigmaMatrix = gsl_matrix_alloc(nD, nD);
aadCovar = (double **)malloc(nD * sizeof(double *));
if (!aadCovar)
goto memoryError;
for (i = 0; i < nD; i++)
{
aadCovar[i] = (double *)malloc(nD * sizeof(double));
if (!aadCovar[i])
goto memoryError;
}
aadInvWK = (double **)malloc(nD * sizeof(double *));
if (!aadInvWK)
goto memoryError;
for (i = 0; i < nD; i++)
{
aadInvWK[i] = (double *)malloc(nD * sizeof(double));
if (!aadInvWK[i])
goto memoryError;
}
/*perform M step */
for (k = 0; k < nK; k++)
{ /*loop components */
double *adMu = ptCluster->aadMu[k];
gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k];
double dF = 0.0;
/*recompute mixture weights and means */
for (j = 0; j < nD; j++)
{
adMu[j] = 0.0;
for (l = 0; l < nD; l++)
{
aadCovar[j][l] = 0.0;
}
}
/* compute weight associated with component k */
adPi[k] = 0.0;
for (i = 0; i < nN; i++)
{
if (aadZ[i][k] > MIN_Z)
{
adPi[k] += aadZ[i][k];
for (j = 0; j < nD; j++)
{
adMu[j] += aadZ[i][k] * aadX[i][j];
}
}
}
/*normalise means */
if (adPi[k] > MIN_PI)
{
/*Equation 10.60 */
ptCluster->adBeta[k] = ptVBParams->dBeta0 + adPi[k];
for (j = 0; j < nD; j++)
{
/*Equation 10.61 */
ptCluster->aadM[k][j] =
adMu[j] / ptCluster->adBeta[k];
adMu[j] /= adPi[k];
}
ptCluster->adNu[k] = ptVBParams->dNu0 + adPi[k];
/*calculate covariance matrices */
for (i = 0; i < nN; i++)
{
if (aadZ[i][k] > MIN_Z)
{
double adDiff[nD];
for (j = 0; j < nD; j++)
{
adDiff[j] =
aadX[i][j] - adMu[j];
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadCovar[l][m] +=
aadZ[i][k] *
adDiff[l] *
adDiff[m];
}
}
}
}
for (l = 0; l < nD; l++)
{
for (m = l + 1; m < nD; m++)
{
aadCovar[l][m] = aadCovar[m][l];
}
}
/*save sample covariances for later use */
for (l = 0; l < nD; l++)
{
for (m = 0; m < nD; m++)
{
double dC = aadCovar[l][m] / adPi[k];
gsl_matrix_set(ptCluster->aptCovar[k],
l, m, dC);
}
}
/*Now perform equation 10.62 */
dF = (ptVBParams->dBeta0 * adPi[k]) /
ptCluster->adBeta[k];
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadInvWK[l][m] =
gsl_matrix_get(ptVBParams->ptInvW0,
l,
m) +
aadCovar[l][m] +
dF * adMu[l] * adMu[m];
}
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadCovar[l][m] /= adPi[k];
gsl_matrix_set(ptSigmaMatrix, l, m,
aadInvWK[l][m]);
gsl_matrix_set(ptSigmaMatrix, m, l,
aadInvWK[l][m]);
}
}
/*Implement Equation 10.65 */
adLDet[k] = ((double)nD) * log(2.0);
for (l = 0; l < nD; l++)
{
double dX =
0.5 * (ptCluster->adNu[k] - (double)l);
adLDet[k] += gsl_sf_psi(dX);
}
adLDet[k] -= decomposeMatrix(ptSigmaMatrix, nD);
}
else
{
/*Equation 10.60 */
adPi[k] = 0.0;
ptCluster->adBeta[k] = ptVBParams->dBeta0;
for (j = 0; j < nD; j++)
{
/*Equation 10.61 */
ptCluster->aadM[k][j] = 0.0;
adMu[j] = 0.0;
}
ptCluster->adNu[k] = ptVBParams->dNu0;
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadInvWK[l][m] =
gsl_matrix_get(ptVBParams->ptInvW0,
l, m);
}
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadInvWK[l][m] =
gsl_matrix_get(ptVBParams->ptInvW0,
l, m);
}
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
gsl_matrix_set(ptSigmaMatrix, l, m,
aadInvWK[l][m]);
gsl_matrix_set(ptSigmaMatrix, m, l,
aadInvWK[l][m]);
}
}
/*Implement Equation 10.65 */
adLDet[k] = ((double)nD) * log(2.0);
for (l = 0; l < nD; l++)
{
double dX =
0.5 * (ptCluster->adNu[k] - (double)l);
adLDet[k] += gsl_sf_psi(dX);
}
adLDet[k] -= decomposeMatrix(ptSigmaMatrix, nD);
}
}
/*Normalise pi */
if (1)
{
double dNP = 0.0;
for (k = 0; k < nK; k++)
{
dNP += adPi[k];
}
for (k = 0; k < nK; k++)
{
adPi[k] /= dNP;
}
}
/*free up memory */
for (i = 0; i < nD; i++)
{
free(aadCovar[i]);
free(aadInvWK[i]);
}
free(aadCovar);
free(aadInvWK);
return;
memoryError:
fprintf(stderr, "Failed allocating memory in performMStep\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void calcCovarMatrices(t_Cluster *ptCluster, t_Data *ptData)
{
int i = 0, j = 0, k = 0, l = 0, m = 0;
int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;
double **aadZ = ptCluster->aadZ, **aadX = ptData->aadX;
double *adPi = ptCluster->adPi, **aadCovar = NULL;
double dN = (double)nN;
aadCovar = (double **)malloc(nD * sizeof(double *));
if (!aadCovar)
goto memoryError;
for (i = 0; i < nD; i++)
{
aadCovar[i] = (double *)malloc(nD * sizeof(double));
if (!aadCovar[i])
goto memoryError;
}
for (k = 0; k < nK; k++)
{ /*loop components */
double *adMu = ptCluster->aadMu[k];
gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k];
/*recompute mixture weights and means */
for (j = 0; j < nD; j++)
{
adMu[j] = 0.0;
for (l = 0; l < nD; l++)
{
aadCovar[j][l] = 0.0;
}
/*prevents singularities */
aadCovar[j][j] = MIN_COVAR;
}
/* compute weight associated with component k */
adPi[k] = 0.0;
for (i = 0; i < nN; i++)
{
adPi[k] += aadZ[i][k];
for (j = 0; j < nD; j++)
{
adMu[j] += aadZ[i][k] * aadX[i][j];
}
}
/*normalise means */
for (j = 0; j < nD; j++)
{
adMu[j] /= adPi[k];
}
/*calculate covariance matrices */
for (i = 0; i < nN; i++)
{
double adDiff[nD];
for (j = 0; j < nD; j++)
{
adDiff[j] = aadX[i][j] - adMu[j];
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadCovar[l][m] +=
aadZ[i][k] * adDiff[l] * adDiff[m];
}
}
}
for (l = 0; l < nD; l++)
{
for (m = l + 1; m < nD; m++)
{
aadCovar[l][m] = aadCovar[m][l];
}
}
for (l = 0; l < nD; l++)
{
for (m = 0; m < nD; m++)
{
aadCovar[l][m] /= adPi[k];
gsl_matrix_set(ptSigmaMatrix, l, m,
aadCovar[l][m]);
}
}
adPi[k] /= dN; /*normalise weights */
}
/*free up memory */
for (i = 0; i < nD; i++)
{
free(aadCovar[i]);
}
//gsl_matrix_free(ptSigmaMatrix);
free(aadCovar);
return;
memoryError:
fprintf(stderr, "Failed allocating memory in performMStep\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void calcCovarMatricesVB(t_Cluster *ptCluster, t_Data *ptData)
{
int i = 0, j = 0, k = 0, l = 0, m = 0;
int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;
double **aadZ = ptCluster->aadZ, **aadX = ptData->aadX;
double *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi;
double **aadCovar = NULL, **aadInvWK = NULL;
t_VBParams *ptVBParams = ptCluster->ptVBParams;
aadCovar = (double **)malloc(nD * sizeof(double *));
if (!aadCovar)
goto memoryError;
for (i = 0; i < nD; i++)
{
aadCovar[i] = (double *)malloc(nD * sizeof(double));
if (!aadCovar[i])
goto memoryError;
}
aadInvWK = (double **)malloc(nD * sizeof(double *));
if (!aadInvWK)
goto memoryError;
for (i = 0; i < nD; i++)
{
aadInvWK[i] = (double *)malloc(nD * sizeof(double));
if (!aadInvWK[i])
goto memoryError;
}
/*perform M step */
for (k = 0; k < nK; k++)
{ /*loop components */
double *adMu = ptCluster->aadMu[k];
gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k];
double dF = 0.0;
/*recompute mixture weights and means */
for (j = 0; j < nD; j++)
{
adMu[j] = 0.0;
for (l = 0; l < nD; l++)
{
aadCovar[j][l] = 0.0;
}
}
/* compute weight associated with component k */
adPi[k] = 0.0;
for (i = 0; i < nN; i++)
{
adPi[k] += aadZ[i][k];
for (j = 0; j < nD; j++)
{
adMu[j] += aadZ[i][k] * aadX[i][j];
}
}
/*normalise means */
if (adPi[k] > MIN_PI)
{
/*Equation 10.60 */
ptCluster->adBeta[k] = ptVBParams->dBeta0 + adPi[k];
for (j = 0; j < nD; j++)
{
/*Equation 10.61 */
ptCluster->aadM[k][j] =
adMu[j] / ptCluster->adBeta[k];
adMu[j] /= adPi[k];
}
ptCluster->adNu[k] = ptVBParams->dNu0 + adPi[k];
/*calculate covariance matrices */
for (i = 0; i < nN; i++)
{
double adDiff[nD];
for (j = 0; j < nD; j++)
{
adDiff[j] = aadX[i][j] - adMu[j];
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadCovar[l][m] +=
aadZ[i][k] * adDiff[l] *
adDiff[m];
}
}
}
for (l = 0; l < nD; l++)
{
for (m = l + 1; m < nD; m++)
{
aadCovar[l][m] = aadCovar[m][l];
}
}
/*save sample covariances for later use */
for (l = 0; l < nD; l++)
{
for (m = 0; m < nD; m++)
{
double dC = aadCovar[l][m] / adPi[k];
gsl_matrix_set(ptCluster->aptCovar[k],
l, m, dC);
}
}
/*Now perform equation 10.62 */
dF = (ptVBParams->dBeta0 * adPi[k]) /
ptCluster->adBeta[k];
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadInvWK[l][m] =
gsl_matrix_get(ptVBParams->ptInvW0,
l,
m) +
aadCovar[l][m] +
dF * adMu[l] * adMu[m];
}
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
//aadCovar[l][m] /= adPi[k];
gsl_matrix_set(ptSigmaMatrix, l, m,
aadInvWK[l][m]);
gsl_matrix_set(ptSigmaMatrix, m, l,
aadInvWK[l][m]);
}
}
}
else
{
/*Equation 10.60 */
adPi[k] = 0.0;
ptCluster->adBeta[k] = ptVBParams->dBeta0;
for (j = 0; j < nD; j++)
{
/*Equation 10.61 */
ptCluster->aadM[k][j] = 0.0;
adMu[j] = 0.0;
}
ptCluster->adNu[k] = ptVBParams->dNu0;
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
aadInvWK[l][m] =
gsl_matrix_get(ptVBParams->ptInvW0,
l, m);
}
}
for (l = 0; l < nD; l++)
{
for (m = 0; m <= l; m++)
{
//aadCovar[l][m] /= adPi[k];
gsl_matrix_set(ptSigmaMatrix, l, m,
aadInvWK[l][m]);
gsl_matrix_set(ptSigmaMatrix, m, l,
aadInvWK[l][m]);
}
}
/*Implement Equation 10.65 */
adLDet[k] = ((double)nD) * log(2.0);
for (l = 0; l < nD; l++)
{
double dX =
0.5 * (ptCluster->adNu[k] - (double)l);
adLDet[k] += gsl_sf_psi(dX);
}
adLDet[k] -= decomposeMatrix(ptSigmaMatrix, nD);
}
}
/*Normalise pi */
if (1)
{
double dNP = 0.0;
for (k = 0; k < nK; k++)
{
dNP += adPi[k];
}
for (k = 0; k < nK; k++)
{
adPi[k] /= dNP;
}
}
/*free up memory */
for (i = 0; i < nD; i++)
{
free(aadCovar[i]);
free(aadInvWK[i]);
}
//gsl_matrix_free(ptSigmaMatrix);
free(aadCovar);
free(aadInvWK);
return;
memoryError:
fprintf(stderr, "Failed allocating memory in performMStep\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void updateMeans(t_Cluster *ptCluster, t_Data *ptData)
{
int i = 0, j = 0, k = 0;
int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;
int *anMaxZ = ptCluster->anMaxZ;
int *anW = ptCluster->anW;
double **aadX = ptData->aadX, **aadMu = ptCluster->aadMu;
for (k = 0; k < nK; k++)
{
for (j = 0; j < nD; j++)
{
aadMu[k][j] = 0.0;
}
}
for (i = 0; i < nN; i++)
{
int nZ = anMaxZ[i];
for (j = 0; j < nD; j++)
{
aadMu[nZ][j] += aadX[i][j];
}
}
for (k = 0; k < nK; k++)
{ /*loop components */
/*normalise means */
if (anW[k] > 0)
{
for (j = 0; j < nD; j++)
{
aadMu[k][j] /= (double)anW[k];
}
}
else
{
for (j = 0; j < nD; j++)
{
aadMu[k][j] = 0.0;
}
}
}
return;
}
void initRandom(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData)
{
/*very simple initialisation assign each data point to random cluster */
int i = 0, k = 0;
for (i = 0; i < ptData->nN; i++)
{
int nIK = -1;
for (k = 0; k < ptCluster->nK; k++)
{
ptCluster->aadZ[i][k] = 0.0;
}
nIK = gsl_rng_uniform_int(ptGSLRNG, ptCluster->nK);
ptCluster->aadZ[i][nIK] = 1.0;
}
performMStep(ptCluster, ptData);
return;
}
void initMustlink(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData)
{
/* initialiation which assign set of individuals which must link to random cluster */
int i = 0, k = 0;
char buffer[MAX_LINE_LENGTH];
FILE *f;
for (i = 0; i < ptData->nN; i++)
for (k = 0; k < ptCluster->nK; k++)
ptCluster->aadZ[i][k] = 0.0;
f = fopen(szMLInputFile, "r");
if (f == NULL)
return;
while (fgets(buffer, MAX_LINE_LENGTH, f))
{
int nIK = gsl_rng_uniform_int(ptGSLRNG, ptCluster->nK);
char *tok = buffer, *pos;
while ((pos = strchr(tok, ',')))
{
*pos = 0;
i = atoi(tok);
tok = pos + 1;
ptCluster->aadZ[i][nIK] = 1.0;
}
i = atoi(tok);
ptCluster->aadZ[i][nIK] = 1.0;
}
fclose(f);
performMStep(ptCluster, ptData);
}
double calcDist(double *adX, double *adMu, int nD)
{
double dDist = 0.0;
int i = 0;
for (i = 0; i < nD; i++)
{
double dV = adX[i] - adMu[i];
dDist += dV * dV;
}
return sqrt(dDist);
}
void initKMeans(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData)
{
/*very simple initialisation assign each data point to random cluster */
int i = 0, k = 0, nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;
double **aadMu = ptCluster->aadMu, **aadX = ptData->aadX;
int *anMaxZ = ptCluster->anMaxZ, *anW = ptCluster->anW, nChange = nN;
int nIter = 0, nMaxIter = ptCluster->nMaxIter;
for (i = 0; i < nN; i++)
{
int nIK = gsl_rng_uniform_int(ptGSLRNG, nK);
ptCluster->anMaxZ[i] = nIK;
anW[nIK]++;
}
updateMeans(ptCluster, ptData);
while (nChange > 0 && nIter < nMaxIter)
{
nChange = 0;
/*reassign vectors */
for (i = 0; i < nN; i++)
{
double dMinDist = DBL_MAX;
int nMinK = NOT_SET;
for (k = 0; k < nK; k++)
{
double dDist = calcDist(aadX[i], aadMu[k], nD);
if (dDist < dMinDist)
{
nMinK = k;
dMinDist = dDist;
}
}
if (nMinK != anMaxZ[i])
{
int nCurr = anMaxZ[i];
nChange++;
anW[nCurr]--;
anW[nMinK]++;
anMaxZ[i] = nMinK;
/*check for empty clusters */
if (anW[nCurr] == 0)
{
int nRandI =
gsl_rng_uniform_int(ptGSLRNG, nN);
int nKI = 0;
/*select at random from non empty clusters */
while (anW[anMaxZ[nRandI]] == 1)
{
nRandI =
gsl_rng_uniform_int(ptGSLRNG, nN);
}
nKI = anMaxZ[nRandI];
anW[nKI]--;
anW[nCurr] = 1;
anMaxZ[nRandI] = nCurr;
}
}
}
//printf("%d %d\n",nIter,nChange);
nIter++;
updateMeans(ptCluster, ptData);
}
for (i = 0; i < nN; i++)
{
for (k = 0; k < nK; k++)
{
ptCluster->aadZ[i][k] = 0.0;
}
ptCluster->aadZ[i][anMaxZ[i]] = 1.0;
}
performMStep(ptCluster, ptData);
return;
}
/*note assuming you are using inverse W matrix*/
double dLogWishartB(gsl_matrix *ptInvW, int nD, double dNu, int bInv)
{
int i = 0;
double dRet = 0.0, dT = 0.0;
double dLogDet = 0.0, dD = (double)nD;
gsl_matrix *ptTemp = gsl_matrix_alloc(nD, nD);
gsl_matrix_memcpy(ptTemp, ptInvW);
dLogDet = decomposeMatrix(ptTemp, nD);
if (bInv == TRUE)
{
dRet = 0.5 * dNu * dLogDet;
}
else
{
dRet = -0.5 * dNu * dLogDet;
}
dT = 0.5 * dNu * dD * log(2.0);
dT += 0.25 * dD * (dD - 1.0) * log(M_PI);
for (i = 0; i < nD; i++)
{
dT += gsl_sf_lngamma(0.5 * (dNu - (double)i));
}
gsl_matrix_free(ptTemp);
return dRet - dT;
}
double dWishartExpectLogDet(gsl_matrix *ptW, double dNu, int nD)
{
int i = 0;
double dRet = 0.0, dLogDet = 0.0, dD = (double)nD;
gsl_matrix *ptTemp = gsl_matrix_alloc(nD, nD);
gsl_matrix_memcpy(ptTemp, ptW);
dLogDet = decomposeMatrix(ptW, nD);
dRet = dD * log(2.0) + dLogDet;
for (i = 0; i < nD; i++)
{
dRet += gsl_sf_psi(0.5 * (dNu - (double)i));
}
gsl_matrix_free(ptTemp);
return dRet;
}
double dWishartEntropy(gsl_matrix *ptW, double dNu, int nD)
{
double dRet = -dLogWishartB(ptW, nD, dNu, FALSE);
double dExpLogDet = dWishartExpectLogDet(ptW, dNu, nD);
double dD = (double)nD;
dRet -= 0.5 * (dNu - dD - 1.0) * dExpLogDet;
dRet += 0.5 * dNu * dD;
return dRet;
}
double calcVBL(t_Cluster *ptCluster)
{
int i = 0, k = 0, l = 0, nN = ptCluster->nN;
int nK = ptCluster->nK, nD = ptCluster->nD;
double dBishop1 = 0.0, dBishop2 = 0.0, dBishop3 = 0.0, dBishop4 = 0.0, dBishop5 = 0.0; /*Bishop equations 10.71... */
gsl_matrix *ptRes = gsl_matrix_alloc(nD, nD);
gsl_vector *ptDiff = gsl_vector_alloc(nD);
gsl_vector *ptR = gsl_vector_alloc(nD);
double dD = (double)nD;
double **aadMu = ptCluster->aadMu, **aadM = ptCluster->aadM, **aadZ = ptCluster->aadZ;
double *adBeta = ptCluster->adBeta, *adNu = ptCluster->adNu, *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi;
double adNK[nK];
double d2Pi = 2.0 * M_PI, dBeta0 = ptCluster->ptVBParams->dBeta0, dNu0 = ptCluster->ptVBParams->dNu0, dRet = 0.0;
double dK = 0.0;
for (k = 0; k < nK; k++)
{
adNK[k] = 0.0;
}
/*Equation 10.72 */
for (i = 0; i < nN; i++)
{
for (k = 0; k < nK; k++)
{
adNK[k] += aadZ[i][k];
if (adPi[k] > 0.0)
{
dBishop2 += aadZ[i][k] * log(adPi[k]);
}
}
}
for (k = 0; k < nK; k++)
{
if (adNK[k] > 0.0)
{
dK++;
}
}
/*Equation 10.71 */
for (k = 0; k < nK; k++)
{
if (adNK[k] > 0.0)
{
double dT1 = 0.0, dT2 = 0.0, dF = 0.0;
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0,
ptCluster->aptCovar[k],
ptCluster->aptSigma[k], 0.0, ptRes);
for (l = 0; l < nD; l++)
{
dT1 += gsl_matrix_get(ptRes, l, l);
}
for (l = 0; l < nD; l++)
{
gsl_vector_set(ptDiff, l,
aadMu[k][l] - aadM[k][l]);
}
gsl_blas_dsymv(CblasLower, 1.0, ptCluster->aptSigma[k],
ptDiff, 0.0, ptR);
gsl_blas_ddot(ptDiff, ptR, &dT2);
dF = adLDet[k] - adNu[k] * (dT1 + dT2) -
dD * (log(d2Pi) + (1.0 / adBeta[k]));
dBishop1 += 0.5 * adNK[k] * dF;
}
}
/*Equation 10.74 */
for (k = 0; k < nK; k++)
{
if (adNK[k] > 0.0)
{
double dT1 = 0.0, dT2 = 0.0, dF = 0.0;
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0,
ptCluster->ptVBParams->ptInvW0,
ptCluster->aptSigma[k], 0.0, ptRes);
for (l = 0; l < nD; l++)
{
dT1 += gsl_matrix_get(ptRes, l, l);
}
for (l = 0; l < nD; l++)
{
gsl_vector_set(ptDiff, l, aadM[k][l]);
}
gsl_blas_dsymv(CblasLower, 1.0, ptCluster->aptSigma[k],
ptDiff, 0.0, ptR);
gsl_blas_ddot(ptDiff, ptR, &dT2);
dF = dD * log(dBeta0 / d2Pi) + adLDet[k] -
((dD * dBeta0) / adBeta[k]) -
dBeta0 * adNu[k] * dT2 - adNu[k] * dT1;
dBishop3 += 0.5 * (dF + (dNu0 - dD - 1.0) * adLDet[k]);
}
}
dBishop3 += dK * ptCluster->ptVBParams->dLogWishartB;
/*Equation 10.75 */
for (i = 0; i < nN; i++)
{
for (k = 0; k < nK; k++)
{
if (aadZ[i][k] > 0.0)
{
dBishop4 += aadZ[i][k] * log(aadZ[i][k]);
}
}
}
/*Equation 10.77 */
for (k = 0; k < nK; k++)
{
if (adNK[k] > 0.0)
{
dBishop5 +=
0.5 * adLDet[k] + 0.5 * dD * log(adBeta[k] / d2Pi) -
0.5 * dD -
dWishartExpectLogDet(ptCluster->aptSigma[k],
adNu[k], nD);
}
}
gsl_matrix_free(ptRes);
gsl_vector_free(ptDiff);
gsl_vector_free(ptR);
dRet = dBishop1 + dBishop2 + dBishop3 - dBishop4 - dBishop5;
return dRet;
}
void calcZ(t_Cluster *ptCluster, t_Data *ptData)
{
double **aadX = ptData->aadX, **aadZ = ptCluster->aadZ;
int i = 0, k = 0, l = 0;
int nK = ptCluster->nK, nD = ptCluster->nD, nN = ptData->nN;
gsl_vector *ptDiff = gsl_vector_alloc(nD);
gsl_vector *ptRes = gsl_vector_alloc(nD);
double adDist[nK], dD = (double)nD;
double **aadM = ptCluster->aadM, *adPi = ptCluster->adPi;
for (i = 0; i < nN; i++)
{
double dMinDist = DBL_MAX;
double dTotalZ = 0.0;
double dNTotalZ = 0.0;
for (k = 0; k < nK; k++)
{
if (adPi[k] > 0.)
{
/*set vector to data point */
for (l = 0; l < nD; l++)
{
gsl_vector_set(ptDiff, l,
aadX[i][l] - aadM[k][l]);
}
gsl_blas_dsymv(CblasLower, 1.0,
ptCluster->aptSigma[k], ptDiff,
0.0, ptRes);
gsl_blas_ddot(ptDiff, ptRes, &adDist[k]);
adDist[k] *= ptCluster->adNu[k];
adDist[k] -= ptCluster->adLDet[k];
adDist[k] += dD / ptCluster->adBeta[k];
if (adDist[k] < dMinDist)
{
dMinDist = adDist[k];
}
}
}
for (k = 0; k < nK; k++)
{
if (adPi[k] > 0.)
{
aadZ[i][k] =
adPi[k] * exp(-0.5 *
(adDist[k] - dMinDist));
dTotalZ += aadZ[i][k];
}
else
{
aadZ[i][k] = 0.0;
}
}
for (k = 0; k < nK; k++)
{
double dF = aadZ[i][k] / dTotalZ;
if (dF < MIN_Z)
{
aadZ[i][k] = 0.0;
}
dNTotalZ += aadZ[i][k];
}
if (dNTotalZ > 0.)
{
for (k = 0; k < nK; k++)
{
aadZ[i][k] /= dNTotalZ;
}
}
}
gsl_vector_free(ptRes);
gsl_vector_free(ptDiff);
return;
}
void gmmTrainVB(t_Cluster *ptCluster, t_Data *ptData)
{
int i = 0, k = 0, nIter = 0;
int nN = ptData->nN, nK = ptCluster->nK;
/*change in log-likelihood */
double dLastVBL = 0.0, dDelta = DBL_MAX;
double **aadZ = ptCluster->aadZ;
int nMaxIter = ptCluster->nMaxIter;
double dEpsilon = ptCluster->dEpsilon;
/*calculate data likelihood */
calcZ(ptCluster, ptData);
ptCluster->dVBL = calcVBL(ptCluster);
while (nIter < nMaxIter && dDelta > dEpsilon)
{
/*update parameter estimates */
performMStep(ptCluster, ptData);
/*calculate responsibilities */
calcZ(ptCluster, ptData);
dLastVBL = ptCluster->dVBL;
ptCluster->dVBL = calcVBL(ptCluster);
dDelta = fabs(ptCluster->dVBL - dLastVBL);
printf("[DEBUG-%d] nIter=%d ; maxIter=%d ; dVBL=%.4f ; delta=%.4e ; epsilon=%.4e\n",
ptCluster->nThread, nIter, nMaxIter, ptCluster->dVBL, dDelta, dEpsilon);
nIter++;
}
/*assign to best clusters */
for (i = 0; i < nN; i++)
{
double dMaxZ = aadZ[i][0];
int nMaxK = 0;
for (k = 1; k < nK; k++)
{
if (aadZ[i][k] > dMaxZ)
{
nMaxK = k;
dMaxZ = aadZ[i][k];
}
}
ptCluster->anMaxZ[i] = nMaxK;
}
return;
}
void writeClusters(char *szOutFile, t_Cluster *ptCluster, t_Data *ptData)
{
int nN = ptCluster->nN, i = 0;
FILE *ofp = fopen(szOutFile, "w");
if (ofp)
{
for (i = 0; i < nN; i++)
{
fprintf(ofp, "%s,%d\n", ptData->aszSampleNames[i],
ptCluster->anMaxZ[i]);
}
fclose(ofp);
printf("[DEBUG] file '%s' closed\n", szOutFile);
}
else
{
fprintf(stderr,
"Failed to open %s for writing in writeClusters\n",
szOutFile);
fflush(stderr);
}
}
void writeMeans(char *szOutFile, t_Cluster *ptCluster)
{
int nK = ptCluster->nK, nD = ptCluster->nD, i = 0, j = 0;
FILE *ofp = fopen(szOutFile, "w");
if (ofp)
{
for (i = 0; i < nK; i++)
{
for (j = 0; j < nD - 1; j++)
{
fprintf(ofp, "%f,", ptCluster->aadMu[i][j]);
}
fprintf(ofp, "%f\n", ptCluster->aadMu[i][nD - 1]);
}
fclose(ofp);
}
else
{
fprintf(stderr,
"Failed to open %s for writing in writeMeanss\n",
szOutFile);
fflush(stderr);
}
}
void writeTMeans(char *szOutFile, t_Cluster *ptCluster, t_Data *ptData)
{
int nK = ptCluster->nK, nD = ptCluster->nD, nT = ptData->nT, i = 0, j = 0;
FILE *ofp = fopen(szOutFile, "w");
gsl_vector *ptVector = gsl_vector_alloc(nD);
gsl_vector *ptTVector = gsl_vector_alloc(nT);
if (ofp)
{
for (i = 0; i < nK; i++)
{
for (j = 0; j < nD; j++)
{
gsl_vector_set(ptVector, j,
ptCluster->aadMu[i][j]);
}
gsl_blas_dgemv(CblasNoTrans, 1.0, ptData->ptTMatrix,
ptVector, 0.0, ptTVector);
for (j = 0; j < nT - 1; j++)
{
fprintf(ofp, "%f,",
gsl_vector_get(ptTVector, j));
}
fprintf(ofp, "%f\n", gsl_vector_get(ptTVector, nD - 1));
}
fclose(ofp);
}
else
{
fprintf(stderr,
"Failed to open %s for writing in writeMeanss\n",
szOutFile);
fflush(stderr);
}
gsl_vector_free(ptVector);
gsl_vector_free(ptTVector);
}
void *fitEM(void *pvCluster)
{
t_Cluster *ptCluster = (t_Cluster *)pvCluster;
gsl_rng *ptGSLRNG = NULL;
const gsl_rng_type *ptGSLRNGType = NULL;
time_t start_t, end_t;
time(&start_t);
/*initialise GSL RNG*/
ptGSLRNGType = gsl_rng_default;
ptGSLRNG = gsl_rng_alloc(ptGSLRNGType);
gsl_rng_set(ptGSLRNG, ptCluster->lSeed);
if (ptCluster->szCOutFile == NULL)
{
printf("[DEBUG-%d] init KMeans...\n", ptCluster->nThread);
initKMeans(ptGSLRNG, ptCluster, ptCluster->ptData);
}
else
{
printf("[DEBUG-%d] init using must-link...\n", ptCluster->nThread);
initMustlink(ptGSLRNG, ptCluster, ptCluster->ptData);
}
printf("[DEBUG-%d] train VBGMM...\n", ptCluster->nThread);
gmmTrainVB(ptCluster, ptCluster->ptData);
gsl_rng_free(ptGSLRNG);
time(&end_t);
printf("[DEBUG-%d] Lower bound=%.2f ; Execution time fitEM=%.2f sec\n",
ptCluster->nThread, ptCluster->dVBL, difftime(end_t, start_t));
return NULL;
}
void *runRThreads(void *pvpDCluster)
{
t_Cluster **pptDCluster = (t_Cluster **)pvpDCluster;
t_Cluster *ptDCluster = (t_Cluster *)*pptDCluster;
double dBestVBL = -DBL_MAX;
t_Cluster **aptCluster = NULL;
pthread_t atRestarts[N_RTHREADS]; /*run each restart on a separate thread */
int r = 0, nBestR = -1;
char *szCOutFile = NULL;
aptCluster = (t_Cluster **)malloc(N_RTHREADS * sizeof(t_Cluster *));
if (!aptCluster)
goto memoryError;
for (r = 0; r < N_RTHREADS; r++)
{
if (ptDCluster->szCOutFile != NULL)
{
szCOutFile =
(char *)malloc(sizeof(char) * MAX_LINE_LENGTH);
sprintf(szCOutFile, "%sr%d.csv", ptDCluster->szCOutFile,
r);
}
aptCluster[r] = (t_Cluster *)malloc(sizeof(t_Cluster));
allocateCluster(aptCluster[r], ptDCluster->nN, ptDCluster->nK,
ptDCluster->nD, ptDCluster->ptData,
ptDCluster->lSeed + r * R_PRIME,
ptDCluster->nMaxIter, ptDCluster->dEpsilon,
szCOutFile);
aptCluster[r]->ptVBParams = ptDCluster->ptVBParams;
aptCluster[r]->nThread = r;
pthread_create(&atRestarts[r], NULL, fitEM, (void *)aptCluster[r]);
}
//TODO: use pthread_tryjoin_np to join pthreads or display some info
for (r = 0; r < N_RTHREADS; r++)
{
pthread_join(atRestarts[r], NULL);
}
/*free up memory associated with input cluster */
free(ptDCluster);
for (r = 0; r < N_RTHREADS; r++)
{
if (aptCluster[r]->dVBL > dBestVBL)
{
nBestR = r;
dBestVBL = aptCluster[r]->dVBL;
}
}
printf("[DEBUG] best clustering result dVBL = %.4f\n", dBestVBL);
*pptDCluster = aptCluster[nBestR];
for (r = 0; r < N_RTHREADS; r++)
{
if (r != nBestR)
{
destroyCluster(aptCluster[r]);
free(aptCluster[r]);
}
}
free(aptCluster);
return NULL;
memoryError:
fprintf(stderr, "Failed allocating memory in runRThreads\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
void calcSampleVar(t_Data *ptData, double *adVar, double *adMu)
{
double **aadX = ptData->aadX;
int i = 0, n = 0;
int nD = ptData->nD, nN = ptData->nN;
/*sample means */
double dN = (double)nN;
for (i = 0; i < nD; i++)
{
adMu[i] = 0.0;
adVar[i] = 0.0;
}
for (i = 0; i < nD; i++)
{
for (n = 0; n < nN; n++)
{
adMu[i] += aadX[n][i];
adVar[i] += aadX[n][i] * aadX[n][i];
}
adMu[i] /= dN;
adVar[i] = (adVar[i] - dN * adMu[i] * adMu[i]) / (dN - 1.0);
}
return;
}
void compressCluster(t_Cluster *ptCluster)
{
int i = 0, k = 0, nNewK = 0, nN = ptCluster->nN;
double **aadNewZ = NULL, dN = (double)nN;
for (i = 0; i < ptCluster->nK; i++)
{
if (ptCluster->adPi[i] > 0.0)
{
nNewK++;
}
}
aadNewZ = (double **)malloc(nN * sizeof(double *));
if (!aadNewZ)
goto memoryError;
for (i = 0; i < nN; i++)
{
aadNewZ[i] = (double *)malloc(nNewK * sizeof(double));
if (!aadNewZ[i])
goto memoryError;
}
for (i = 0; i < nN; i++)
{
int nC = 0;
for (k = 0; k < ptCluster->nK; k++)
{
if (ptCluster->adPi[k] > 0.0)
{
aadNewZ[i][nC] = ptCluster->aadZ[i][k];
nC++;
}
}
}
for (i = 0; i < nN; i++)
{
free(ptCluster->aadZ[i]);
}
free(ptCluster->aadZ);
/*reset Z and K */
ptCluster->aadZ = aadNewZ;
ptCluster->nK = nNewK;
/*recalculate Pi */
for (k = 0; k < ptCluster->nK; k++)
{
ptCluster->adPi[k] = 0.0;
for (i = 0; i < nN; i++)
{
ptCluster->adPi[k] += ptCluster->aadZ[i][k];
}
ptCluster->adPi[k] /= dN;
}
/*assign to best clusters */
for (i = 0; i < nN; i++)
{
double dMaxZ = ptCluster->aadZ[i][0];
int nMaxK = 0;
for (k = 1; k < ptCluster->nK; k++)
{
if (ptCluster->aadZ[i][k] > dMaxZ)
{
nMaxK = k;
dMaxZ = ptCluster->aadZ[i][k];
}
}
ptCluster->anMaxZ[i] = nMaxK;
}
for (k = 0; k < ptCluster->nK; k++)
{
ptCluster->anW[k] = 0;
}
for (i = 0; i < nN; i++)
{
ptCluster->anW[ptCluster->anMaxZ[i]]++;
}
return;
memoryError:
fprintf(stderr, "Failed allocating memory in main\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
| {
"alphanum_fraction": 0.5885042602,
"avg_line_length": 20.4348222425,
"ext": "c",
"hexsha": "1e2508e83ffa1416f5eb9f21bd96b0448c3856af",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-08-16T17:25:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-16T17:25:06.000Z",
"max_forks_repo_head_hexsha": "12683f9f5b382955c9028b87b8ecf6c22a029191",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "keuv-grvl/fennec",
"max_forks_repo_path": "c-concoct/vbgmmmodule.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "12683f9f5b382955c9028b87b8ecf6c22a029191",
"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": "keuv-grvl/fennec",
"max_issues_repo_path": "c-concoct/vbgmmmodule.c",
"max_line_length": 118,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "12683f9f5b382955c9028b87b8ecf6c22a029191",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "keuv-grvl/fennec",
"max_stars_repo_path": "c-concoct/vbgmmmodule.c",
"max_stars_repo_stars_event_max_datetime": "2018-12-13T14:54:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-01T21:10:40.000Z",
"num_tokens": 16895,
"size": 44834
} |
/* specfunc/gsl_sf_lambert.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_LAMBERT_H__
#define __GSL_SF_LAMBERT_H__
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Lambert's Function W_0(x)
*
* W_0(x) is the principal branch of the
* implicit function defined by W e^W = x.
*
* -1/E < x < \infty
*
* exceptions: GSL_EMAXITER;
*/
int gsl_sf_lambert_W0_e(double x, gsl_sf_result * result);
double gsl_sf_lambert_W0(double x);
/* Lambert's Function W_{-1}(x)
*
* W_{-1}(x) is the second real branch of the
* implicit function defined by W e^W = x.
* It agrees with W_0(x) when x >= 0.
*
* -1/E < x < \infty
*
* exceptions: GSL_MAXITER;
*/
int gsl_sf_lambert_Wm1_e(double x, gsl_sf_result * result);
double gsl_sf_lambert_Wm1(double x);
__END_DECLS
#endif /* __GSL_SF_LAMBERT_H__ */
| {
"alphanum_fraction": 0.7148372863,
"avg_line_length": 25.9,
"ext": "h",
"hexsha": "53b70a3a3f7296e9016865d8b73585404fbb2257",
"lang": "C",
"max_forks_count": 30,
"max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/gsl_sf_lambert.h",
"max_issues_count": 11,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/gsl_sf_lambert.h",
"max_line_length": 81,
"max_stars_count": 77,
"max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "shi-bash-cmd/qtTest",
"max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_sf_lambert.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z",
"num_tokens": 518,
"size": 1813
} |
/* spcompress.c
*
* Copyright (C) 2012-2014, 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spmatrix.h>
/*
gsl_spmatrix_ccs()
Create a sparse matrix in compressed column format
Inputs: T - sparse matrix in triplet format
Return: pointer to new matrix (should be freed when finished with it)
*/
gsl_spmatrix *
gsl_spmatrix_ccs(const gsl_spmatrix *T)
{
if (!GSL_SPMATRIX_ISTRIPLET(T))
{
GSL_ERROR_NULL("matrix must be in triplet format", GSL_EINVAL);
}
else
{
const size_t *Tj; /* column indices of triplet matrix */
size_t *Cp; /* column pointers of compressed column matrix */
size_t *w; /* copy of column pointers */
gsl_spmatrix *m;
size_t n;
m = gsl_spmatrix_alloc_nzmax(T->size1, T->size2, T->nz,
GSL_SPMATRIX_CCS);
if (!m)
return NULL;
Tj = T->p;
Cp = m->p;
/* initialize column pointers to 0 */
for (n = 0; n < m->size2 + 1; ++n)
Cp[n] = 0;
/*
* compute the number of elements in each column:
* Cp[j] = # non-zero elements in column j
*/
for (n = 0; n < T->nz; ++n)
Cp[Tj[n]]++;
/* compute column pointers: p[j] = p[j-1] + nnz[j-1] */
gsl_spmatrix_cumsum(m->size2, Cp);
/* make a copy of the column pointers */
w = (size_t *) m->work;
for (n = 0; n < m->size2; ++n)
w[n] = Cp[n];
/* transfer data from triplet format to CCS */
for (n = 0; n < T->nz; ++n)
{
size_t k = w[Tj[n]]++;
m->i[k] = T->i[n];
m->data[k] = T->data[n];
}
m->nz = T->nz;
return m;
}
}
gsl_spmatrix *
gsl_spmatrix_compcol(const gsl_spmatrix *T)
{
return gsl_spmatrix_ccs(T);
}
/*
gsl_spmatrix_crs()
Create a sparse matrix in compressed row format
Inputs: T - sparse matrix in triplet format
Return: pointer to new matrix (should be freed when finished with it)
*/
gsl_spmatrix *
gsl_spmatrix_crs(const gsl_spmatrix *T)
{
if (!GSL_SPMATRIX_ISTRIPLET(T))
{
GSL_ERROR_NULL("matrix must be in triplet format", GSL_EINVAL);
}
else
{
const size_t *Ti; /* row indices of triplet matrix */
size_t *Cp; /* row pointers of compressed row matrix */
size_t *w; /* copy of column pointers */
gsl_spmatrix *m;
size_t n;
m = gsl_spmatrix_alloc_nzmax(T->size1, T->size2, T->nz,
GSL_SPMATRIX_CRS);
if (!m)
return NULL;
Ti = T->i;
Cp = m->p;
/* initialize row pointers to 0 */
for (n = 0; n < m->size1 + 1; ++n)
Cp[n] = 0;
/*
* compute the number of elements in each row:
* Cp[i] = # non-zero elements in row i
*/
for (n = 0; n < T->nz; ++n)
Cp[Ti[n]]++;
/* compute row pointers: p[i] = p[i-1] + nnz[i-1] */
gsl_spmatrix_cumsum(m->size1, Cp);
/* make a copy of the row pointers */
w = (size_t *) m->work;
for (n = 0; n < m->size1; ++n)
w[n] = Cp[n];
/* transfer data from triplet format to CRS */
for (n = 0; n < T->nz; ++n)
{
size_t k = w[Ti[n]]++;
m->i[k] = T->p[n];
m->data[k] = T->data[n];
}
m->nz = T->nz;
return m;
}
}
/*
gsl_spmatrix_cumsum()
Compute the cumulative sum:
p[j] = Sum_{k=0...j-1} c[k]
0 <= j < n + 1
Alternatively,
p[0] = 0
p[j] = p[j - 1] + c[j - 1]
Inputs: n - length of input array
c - (input/output) array of size n + 1
on input, contains the n values c[k]
on output, contains the n + 1 values p[j]
Return: success or error
*/
void
gsl_spmatrix_cumsum(const size_t n, size_t *c)
{
size_t sum = 0;
size_t k;
for (k = 0; k < n; ++k)
{
size_t ck = c[k];
c[k] = sum;
sum += ck;
}
c[n] = sum;
} /* gsl_spmatrix_cumsum() */
| {
"alphanum_fraction": 0.5637626263,
"avg_line_length": 23.8793969849,
"ext": "c",
"hexsha": "d680fa550b80e4fc1f290dbbc1ab670bcf337923",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcompress.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spcompress.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/spmatrix/spcompress.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 1434,
"size": 4752
} |
#ifndef MITRO_GRAPH_SHORTEST_PATH_DIJKSTRA_H
#define MITRO_GRAPH_SHORTEST_PATH_DIJKSTRA_H
#include "Graph.h"
#include <gsl.h>
/////////////////////////////////////////////////////
// DIJKSTRA'S SHORTEST PATH
/////////////////////////////////////////////////////
std::vector<std::pair<double, const GraphEdge*>> nodeWeightDijkstra(Graph &g, int startNode, int endNode);
std::vector<std::pair<double, const GraphEdge*>> edgeWeightDijkstra(Graph &g, int startNode, int endNode);
namespace graph_algorithm_capture
{
struct ShortestPathEdgeWeightDijkstraState
{
std::vector<std::pair<double, const GraphEdge*>> path;
std::set<std::pair<double, int>> openNodes; // discovered but not fully processed
std::set<std::pair<double, int>> closedNodes; // fully processed
std::vector<gsl::not_null<const GraphEdge*>> processedEdges; // processed, not part of any of the minimal paths
int inspectedNode;
const GraphEdge * inspectedEdge;
std::string description;
ShortestPathEdgeWeightDijkstraState(const std::vector<std::pair<double, const GraphEdge*>> &path,
const std::set<std::pair<double, int>> &openNodes,
const std::set<std::pair<double, int>> &closedNodes,
const std::vector<gsl::not_null<const GraphEdge*>> &processedEdges,
int inspectedNode,
const GraphEdge* inspectedEdge,
const std::string &description) :
path(path),
openNodes(openNodes),
closedNodes(closedNodes),
processedEdges(processedEdges),
inspectedNode(inspectedNode),
inspectedEdge(inspectedEdge),
description(description)
{}
};
std::vector<ShortestPathEdgeWeightDijkstraState>
edgeWeightDijkstraCaptureStates(Graph &g, int startNode, int endNode);
} // namespace graph_algorithm_capture
#endif // MITRO_GRAPH_SHORTEST_PATH_DIJKSTRA_H
| {
"alphanum_fraction": 0.6485377116,
"avg_line_length": 40.6041666667,
"ext": "h",
"hexsha": "f6a9bb0e7c96f4702e40c0a5407d5f59bdcbfcee",
"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": "f30b93fb5c1f61f5abc6c239b351e923e9168ff3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mitro42/Graph",
"max_forks_repo_path": "include/shortestPathDijkstra.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f30b93fb5c1f61f5abc6c239b351e923e9168ff3",
"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": "mitro42/Graph",
"max_issues_repo_path": "include/shortestPathDijkstra.h",
"max_line_length": 119,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "f30b93fb5c1f61f5abc6c239b351e923e9168ff3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mitro42/Graph",
"max_stars_repo_path": "include/shortestPathDijkstra.h",
"max_stars_repo_stars_event_max_datetime": "2016-07-02T07:29:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-14T15:38:07.000Z",
"num_tokens": 436,
"size": 1949
} |
//Gets line spectral frequencies (LSFs).
//from the autoregressive (AR) coefficients along cols or rows of X.
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include "cmp_ascend.c"
#ifdef __cplusplus
namespace ov {
extern "C" {
#endif
int ar2lsf_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim);
int ar2lsf_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim);
int ar2lsf_c (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim);
int ar2lsf_z (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim);
int ar2lsf_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim)
{
const float z = 0.0f, o = 1.0f;
const int P = (dim==0) ? R : C;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P+1, n = P+1, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
float *poly, *prev, *omegas, *compan, *wr, *wi, zz[1];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in ar2lsf_s: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in ar2lsf_s: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in ar2lsf_s: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(wr=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(wi=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(float *)malloc((size_t)(n*n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_scopy(n,&X[c*R],1,poly,1); }
else { cblas_scopy(n,&X[c],C,poly,1); }
poly[P] = z; prev[P] = -o;
for (r=0; r<P; r++) { prev[r] = poly[P-r-1]; }
for (r=0; r<n; r++) { poly[r] -= prev[r]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(P,&o,0,&compan[1],n+1); cblas_scopy(n,poly,1,compan,n);
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_s: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = (wi[r]>10.0f*FLT_EPSILON) ? atan2f(wi[r],wr[r]) : 0.0f; poly[r] += prev[r] + prev[r]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(P,&o,0,&compan[1],n+1); cblas_scopy(n,poly,1,compan,n);
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_s: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = (wi[r]>10.0f*FLT_EPSILON) ? atan2f(wi[r],wr[r]) : 0.0f; }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(P,&omegas[n+1],1,&Y[c*P],1); }
else { cblas_scopy(P,&omegas[n+1],1,&Y[c],C); }
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_scopy(n,&X[r],R,poly,1); }
else { cblas_scopy(n,&X[r*C],1,poly,1); }
poly[P] = z; prev[P] = -o;
for (c=0; c<P; c++) { prev[c] = poly[P-c-1]; }
for (c=0; c<n; c++) { poly[c] -= prev[c]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(P,&o,0,&compan[1],n+1); cblas_scopy(n,poly,1,compan,n);
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_s: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = (wi[c]>10.0f*FLT_EPSILON) ? atan2f(wi[c],wr[c]) : 0.0f; poly[c] += prev[c] + prev[c]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(P,&o,0,&compan[1],n+1); cblas_scopy(n,poly,1,compan,n);
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_s: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = (wi[c]>10.0f*FLT_EPSILON) ? atan2f(wi[c],wr[c]) : 0.0f; }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(P,&omegas[n+1],1,&Y[r],R); }
else { cblas_scopy(P,&omegas[n+1],1,&Y[r*P],1); }
}
}
else
{
fprintf(stderr,"error in ar2lsf_s: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wr); free(wi); free(poly); free(prev); free(omegas);
return 0;
}
int ar2lsf_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim)
{
const double z = 0.0, o = 1.0;
const int P = (dim==0) ? R : C;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P+1, n = P+1, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
double *poly, *prev, *omegas, *compan, *wr, *wi, zz[1];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in ar2lsf_d: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in ar2lsf_d: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in ar2lsf_d: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(wr=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(wi=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(double *)malloc((size_t)(n*n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_dcopy(n,&X[c*R],1,poly,1); }
else { cblas_dcopy(n,&X[c],C,poly,1); }
poly[P] = z; prev[P] = -o;
for (r=0; r<P; r++) { prev[r] = poly[n-r]; }
for (r=0; r<n; r++) { poly[r] -= prev[r]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(P,&o,0,&compan[1],n+1); cblas_dcopy(n,poly,1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_d: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = (wi[r]>10.0*DBL_EPSILON) ? atan2(wi[r],wr[r]) : 0.0; poly[r] += prev[r] + prev[r]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(P,&o,0,&compan[1],n+1); cblas_dcopy(n,poly,1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_d: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = (wi[r]>10.0*DBL_EPSILON) ? atan2(wi[r],wr[r]) : 0.0; }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(P,&omegas[n+1],1,&Y[c*P],1); }
else { cblas_dcopy(P,&omegas[n+1],1,&Y[c],C); }
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_dcopy(n,&X[r],R,poly,1); }
else { cblas_dcopy(n,&X[r*C],1,poly,1); }
poly[P] = z; prev[P] = -o;
for (c=0; c<P; c++) { prev[c] = poly[n-c]; }
for (c=0; c<n; c++) { poly[c] -= prev[c]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(P,&o,0,&compan[1],n+1); cblas_dcopy(n,poly,1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_d: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = (wi[c]>10.0*DBL_EPSILON) ? atan2(wi[c],wr[c]) : 0.0; poly[c] += prev[c] + prev[c]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(P,&o,0,&compan[1],n+1); cblas_dcopy(n,poly,1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in ar2lsf_d: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = (wi[c]>10.0*DBL_EPSILON) ? atan2(wi[c],wr[c]) : 0.0; }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(P,&omegas[n+1],1,&Y[r],R); }
else { cblas_dcopy(P,&omegas[n+1],1,&Y[r*P],1); }
}
}
else
{
fprintf(stderr,"error in ar2lsf_d: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wr); free(wi); free(poly); free(prev); free(omegas);
return 0;
}
int ar2lsf_c (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim)
{
const float z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f};
const int P = (dim==0) ? R : C;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P, n = P, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
float *poly, *prev, *omegas, *compan, *wc, zz[2];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in ar2lsf_c: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in ar2lsf_c: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in ar2lsf_c: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(wc=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(float *)malloc((size_t)(4*n*n)*sizeof(float)))) { fprintf(stderr,"error in ar2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_ccopy(n,&X[2*c*R],1,poly,1); }
else { cblas_ccopy(n,&X[2*c],C,poly,1); }
poly[2*P] = poly[2*P+1] = prev[2*P+1] = 0.0f; prev[2*P] = -1.0f;
for (r=0; r<P; r++) { prev[2*r] = poly[2*(P-r-1)]; prev[2*r+1] = poly[2*(P-r-1)+1]; }
for (r=0; r<n; r++) { poly[2*r] -= prev[2*r]; poly[2*r+1] -= prev[2*r+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(P,o,0,&compan[2],n+1); cblas_ccopy(n,poly,1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_c: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = atan2f(wc[2*r+1],wc[2*r]); poly[2*r] += prev[2*r] + prev[2*r]; poly[2*r+1] += prev[2*r+1] + prev[2*r+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(P,o,0,&compan[2],n+1); cblas_ccopy(n,poly,1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_c: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = atan2f(wc[2*r+1],wc[2*r]); }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(2*n,omegas,1,&Y[2*c*n],1); }
else { cblas_scopy(2*n,omegas,1,&Y[c],C); }
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_ccopy(n,&X[2*r],R,poly,1); }
else { cblas_ccopy(n,&X[2*r*C],1,poly,1); }
poly[2*P] = poly[2*P+1] = prev[2*P+1] = 0.0f; prev[2*P] = -1.0f;
for (c=0; c<P; c++) { prev[2*c] = poly[2*(P-c-1)]; prev[2*c+1] = poly[2*(P-c-1)+1]; }
for (c=0; c<n; c++) { poly[2*c] -= prev[2*c]; poly[2*c+1] -= prev[2*c+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(P,o,0,&compan[2],n+1); cblas_ccopy(n,poly,1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_c: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = atan2f(wc[2*c+1],wc[2*c]); poly[2*c] += prev[2*c] + prev[2*c]; poly[2*c+1] += prev[2*c+1] + prev[2*c+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(P,o,0,&compan[2],n+1); cblas_ccopy(n,poly,1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_c: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = atan2f(wc[2*c+1],wc[2*c]); }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(2*n,omegas,1,&Y[r],R); }
else { cblas_scopy(2*n,omegas,1,&Y[2*r*n],1); }
}
}
else
{
fprintf(stderr,"error in ar2lsf_c: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wc); free(poly); free(prev); free(omegas);
return 0;
}
int ar2lsf_z (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim)
{
const double z[2] = {0.0,0.0}, o[2] = {1.0,0.0};
const int P = (dim==0) ? R : C;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P, n = P, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
double *poly, *prev, *omegas, *compan, *wc, zz[2];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in ar2lsf_z: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in ar2lsf_z: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in ar2lsf_z: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(wc=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(double *)malloc((size_t)(4*n*n)*sizeof(double)))) { fprintf(stderr,"error in ar2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_zcopy(n,&X[2*c*R],1,poly,1); }
else { cblas_zcopy(n,&X[2*c],C,poly,1); }
poly[2*P] = poly[2*P+1] = prev[2*P+1] = 0.0; prev[2*P] = -1.0;
for (r=0; r<P; r++) { prev[2*r] = poly[2*(P-r-1)]; prev[2*r+1] = poly[2*(P-r-1)+1]; }
for (r=0; r<n; r++) { poly[2*r] -= prev[2*r]; poly[2*r+1] -= prev[2*r+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(P,o,0,&compan[2],n+1); cblas_zcopy(n,poly,1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_z: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = atan2(wc[2*r+1],wc[2*r]); poly[2*r] += prev[2*r] + prev[2*r]; poly[2*r+1] += prev[2*r+1] + prev[2*r+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(P,o,0,&compan[2],n+1); cblas_zcopy(n,poly,1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_z: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = atan2(wc[2*r+1],wc[2*r]); }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(2*n,omegas,1,&Y[2*c*n],1); }
else { cblas_dcopy(2*n,omegas,1,&Y[c],C); }
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_zcopy(n,&X[2*r],R,poly,1); }
else { cblas_zcopy(n,&X[2*r*C],1,poly,1); }
poly[2*P] = poly[2*P+1] = prev[2*P+1] = 0.0; prev[2*P] = -1.0;
for (c=0; c<P; c++) { prev[2*c] = poly[2*(P-c-1)]; prev[2*c+1] = poly[2*(P-c-1)+1]; }
for (c=0; c<n; c++) { poly[2*c] -= prev[2*c]; poly[2*c+1] -= prev[2*c+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(P,o,0,&compan[2],n+1); cblas_zcopy(n,poly,1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_z: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = atan2(wc[2*c+1],wc[2*c]); poly[2*c] += prev[2*c] + prev[2*c]; poly[2*c+1] += prev[2*c+1] + prev[2*c+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(P,o,0,&compan[2],n+1); cblas_zcopy(n,poly,1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in ar2lsf_z: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = atan2(wc[2*c+1],wc[2*c]); }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(2*n,omegas,1,&Y[r],R); }
else { cblas_dcopy(2*n,omegas,1,&Y[2*r*n],1); }
}
}
else
{
fprintf(stderr,"error in ar2lsf_z: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wc); free(poly); free(prev); free(omegas);
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.576836545,
"avg_line_length": 59.783625731,
"ext": "c",
"hexsha": "0be89577def0e13f2dd07014bbc8c64250774b5a",
"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/ar2lsf.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/ar2lsf.c",
"max_line_length": 168,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/aud",
"max_stars_repo_path": "c/ar2lsf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7398,
"size": 20446
} |
/* integration/qawo.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include "initialise.c"
#include "set_initial.c"
#include "reset.c"
#include "qpsrt.c"
#include "util.c"
#include "qpsrt2.c"
#include "qelg.c"
#include "positivity.c"
#include "qc25f.c"
int
gsl_integration_qawo (gsl_function * f,
const double a,
const double epsabs, const double epsrel,
const size_t limit,
gsl_integration_workspace * workspace,
gsl_integration_qawo_table * wf,
double *result, double *abserr)
{
double area, errsum;
double res_ext, err_ext;
double result0, abserr0, resabs0, resasc0;
double tolerance;
double ertest = 0;
double error_over_large_intervals = 0;
double reseps = 0, abseps = 0, correc = 0;
size_t ktmin = 0;
int roundoff_type1 = 0, roundoff_type2 = 0, roundoff_type3 = 0;
int error_type = 0, error_type2 = 0;
size_t iteration = 0;
int positive_integrand = 0;
int extrapolate = 0;
int extall = 0;
int disallow_extrapolation = 0;
struct extrapolation_table table;
double b = a + wf->L ;
double abs_omega = fabs (wf->omega) ;
/* Initialize results */
initialise (workspace, a, b);
*result = 0;
*abserr = 0;
if (limit > workspace->limit)
{
GSL_ERROR ("iteration limit exceeds available workspace", GSL_EINVAL) ;
}
/* Test on accuracy */
if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))
{
GSL_ERROR ("tolerance cannot be achieved with given epsabs and epsrel",
GSL_EBADTOL);
}
/* Perform the first integration */
qc25f (f, a, b, wf, 0, &result0, &abserr0, &resabs0, &resasc0);
set_initial_result (workspace, result0, abserr0);
tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));
if (abserr0 <= 100 * GSL_DBL_EPSILON * resabs0 && abserr0 > tolerance)
{
*result = result0;
*abserr = abserr0;
GSL_ERROR ("cannot reach tolerance because of roundoff error "
"on first attempt", GSL_EROUND);
}
else if ((abserr0 <= tolerance && abserr0 != resasc0) || abserr0 == 0.0)
{
*result = result0;
*abserr = abserr0;
return GSL_SUCCESS;
}
else if (limit == 1)
{
*result = result0;
*abserr = abserr0;
GSL_ERROR ("a maximum of one iteration was insufficient", GSL_EMAXITER);
}
/* Initialization */
initialise_table (&table);
if (0.5 * abs_omega * fabs(b - a) <= 2)
{
append_table (&table, result0);
extall = 1;
}
area = result0;
errsum = abserr0;
res_ext = result0;
err_ext = GSL_DBL_MAX;
positive_integrand = test_positivity (result0, resabs0);
iteration = 1;
do
{
size_t current_level;
double a1, b1, a2, b2;
double a_i, b_i, r_i, e_i;
double area1 = 0, area2 = 0, area12 = 0;
double error1 = 0, error2 = 0, error12 = 0;
double resasc1, resasc2;
double resabs1, resabs2;
double last_e_i;
/* Bisect the subinterval with the largest error estimate */
retrieve (workspace, &a_i, &b_i, &r_i, &e_i);
current_level = workspace->level[workspace->i] + 1;
if (current_level >= wf->n)
{
error_type = -1 ; /* exceeded limit of table */
break ;
}
a1 = a_i;
b1 = 0.5 * (a_i + b_i);
a2 = b1;
b2 = b_i;
iteration++;
qc25f (f, a1, b1, wf, current_level, &area1, &error1, &resabs1, &resasc1);
qc25f (f, a2, b2, wf, current_level, &area2, &error2, &resabs2, &resasc2);
area12 = area1 + area2;
error12 = error1 + error2;
last_e_i = e_i;
/* Improve previous approximations to the integral and test for
accuracy.
We write these expressions in the same way as the original
QUADPACK code so that the rounding errors are the same, which
makes testing easier. */
errsum = errsum + error12 - e_i;
area = area + area12 - r_i;
tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));
if (resasc1 != error1 && resasc2 != error2)
{
double delta = r_i - area12;
if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)
{
if (!extrapolate)
{
roundoff_type1++;
}
else
{
roundoff_type2++;
}
}
if (iteration > 10 && error12 > e_i)
{
roundoff_type3++;
}
}
/* Test for roundoff and eventually set error flag */
if (roundoff_type1 + roundoff_type2 >= 10 || roundoff_type3 >= 20)
{
error_type = 2; /* round off error */
}
if (roundoff_type2 >= 5)
{
error_type2 = 1;
}
/* set error flag in the case of bad integrand behaviour at
a point of the integration range */
if (subinterval_too_small (a1, a2, b2))
{
error_type = 4;
}
/* append the newly-created intervals to the list */
update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);
if (errsum <= tolerance)
{
goto compute_result;
}
if (error_type)
{
break;
}
if (iteration >= limit - 1)
{
error_type = 1;
break;
}
/* set up variables on first iteration */
if (iteration == 2 && extall)
{
error_over_large_intervals = errsum;
ertest = tolerance;
append_table (&table, area);
continue;
}
if (disallow_extrapolation)
{
continue;
}
if (extall)
{
error_over_large_intervals += -last_e_i;
if (current_level < workspace->maximum_level)
{
error_over_large_intervals += error12;
}
if (extrapolate)
goto label70;
}
if (large_interval(workspace))
{
continue;
}
if (extall)
{
extrapolate = 1;
workspace->nrmax = 1;
}
else
{
/* test whether the interval to be bisected next is the
smallest interval. */
size_t i = workspace->i;
double width = workspace->blist[i] - workspace->alist[i];
if (0.25 * fabs(width) * abs_omega > 2)
continue;
extall = 1;
error_over_large_intervals = errsum;
ertest = tolerance;
continue;
}
label70:
if (!error_type2 && error_over_large_intervals > ertest)
{
if (increase_nrmax (workspace))
continue;
}
/* Perform extrapolation */
append_table (&table, area);
if (table.n < 3)
{
reset_nrmax(workspace);
extrapolate = 0;
error_over_large_intervals = errsum;
continue;
}
qelg (&table, &reseps, &abseps);
ktmin++;
if (ktmin > 5 && err_ext < 0.001 * errsum)
{
error_type = 5;
}
if (abseps < err_ext)
{
ktmin = 0;
err_ext = abseps;
res_ext = reseps;
correc = error_over_large_intervals;
ertest = GSL_MAX_DBL (epsabs, epsrel * fabs (reseps));
if (err_ext <= ertest)
break;
}
/* Prepare bisection of the smallest interval. */
if (table.n == 1)
{
disallow_extrapolation = 1;
}
if (error_type == 5)
{
break;
}
/* work on interval with largest error */
reset_nrmax (workspace);
extrapolate = 0;
error_over_large_intervals = errsum;
}
while (iteration < limit);
*result = res_ext;
*abserr = err_ext;
if (err_ext == GSL_DBL_MAX)
goto compute_result;
if (error_type || error_type2)
{
if (error_type2)
{
err_ext += correc;
}
if (error_type == 0)
error_type = 3;
if (result != 0 && area != 0)
{
if (err_ext / fabs (res_ext) > errsum / fabs (area))
goto compute_result;
}
else if (err_ext > errsum)
{
goto compute_result;
}
else if (area == 0.0)
{
goto return_error;
}
}
/* Test on divergence. */
{
double max_area = GSL_MAX_DBL (fabs (res_ext), fabs (area));
if (!positive_integrand && max_area < 0.01 * resabs0)
goto return_error;
}
{
double ratio = res_ext / area;
if (ratio < 0.01 || ratio > 100 || errsum > fabs (area))
error_type = 6;
}
goto return_error;
compute_result:
*result = sum_results (workspace);
*abserr = errsum;
return_error:
if (error_type > 2)
error_type--;
if (error_type == 0)
{
return GSL_SUCCESS;
}
else if (error_type == 1)
{
GSL_ERROR ("number of iterations was insufficient", GSL_EMAXITER);
}
else if (error_type == 2)
{
GSL_ERROR ("cannot reach tolerance because of roundoff error",
GSL_EROUND);
}
else if (error_type == 3)
{
GSL_ERROR ("bad integrand behavior found in the integration interval",
GSL_ESING);
}
else if (error_type == 4)
{
GSL_ERROR ("roundoff error detected in extrapolation table", GSL_EROUND);
}
else if (error_type == 5)
{
GSL_ERROR ("integral is divergent, or slowly convergent", GSL_EDIVERGE);
}
else if (error_type == -1)
{
GSL_ERROR ("exceeded limit of trigonometric table", GSL_ETABLE);
}
else
{
GSL_ERROR ("could not integrate function", GSL_EFAILED);
}
}
| {
"alphanum_fraction": 0.5526194216,
"avg_line_length": 23.4772234273,
"ext": "c",
"hexsha": "03b9dce7fdd52349578131b6097fb4cbc5e623f0",
"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/integration/qawo.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/integration/qawo.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/integration/qawo.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": 2910,
"size": 10823
} |
/* Generalization Error with Resampling method.
*/
//gcc -Wall -g -lm -lgsl -lgslcblas rsm4ge.c -o rsm4ge
//make rsm4ge
//Usage:rsm4ge data/11train1e3.dat 10 1 data/11test101x101.dat
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <dirent.h>
//#define nNmax 100
#define square(x) ((x)*(x))
#define buffsize 1024
#define linesize 10000
#define nRSmax 2
#define NORS2 -1
#define DIRECT -1
#define LEAVEMANYOUT 0
#define MULTIFOLD 1
#define BOOTSTRAP 2
char *methodname1[4]={"Direct","LeaveManyOut","MultiFold","BootStrap"};
//int *NN;
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix_double.h>
#include "my_misc.c"
void usage(int argc,char **argv){
// fprintf(stderr,"Usage: %s <fn_given> <fn_valid> N:<N>:<nD>:<nN> m:<m>:<d>:<nm> [<options>]\n",argv[0]);
fprintf(stderr,"Usage: %s <fn_given> <fn_valid> <N:<N1>:<NN>:<Nd> | N:<N1>-<N2>:<NStep>> <m:<m1>:<nm>:<md>|m:<m1>-<m2>:<md>> [<options>]\n",argv[0]);
fprintf(stderr,
"fn_given : file name of given data\n"
"<fn_valid> : the file name of validation data if exist (default /dev/null).\n"
"N:<N1>[:<NN>[:<ND>]] : number of cells N=N1+ND*i for i=0,1,..,NN-1 .\n"
"N:<N1>-<N2>[:<ND>]] : number of cells N=N1+ND*i for i=0,1,... until N<=N2.\n"
"m:<m1>:<md>:<nm> : number of ensenble m=m1+nd*i for i=0,1,2,...,nm-1.\n"
"m:<m1>-<m2>:<md> : number of ensenble m=m1+nd*i for i=0,1,2,... until m<=nd.\n"
"k:<k> : dimension of the input vector (defalut:2).\n"
"rs:<rsprog> : executable program for resampling method(defalut:rs4irem).\n"
"<other options> : see ensrs.c\n"
);
}
static char pr[buffsize];
int main(int argc,char **argv)
{
char cmd[30000];
char rdir[buffsize];
char fngiven[1024];
char fnvalid[1024];
char fnplt[1033];
char fnloss[1033];
FILE *fp,*fploss;
char *rdir0="./result-ensrs";
// char *rdir1="./result-ensrs/rsresults";
int i,j,jj,ij;
int K=2; //dimension
int *rsmo;
char ensrsprog[256];
int _N,_DN=1,_nN,*NN,_N1,_N2;
int Ngs1=0,Ngs2=0;
int _m,_dm,_nm,*mm=NULL,_m1,_m2;
// int _e,_de,_ne,*ee,_e1,_e2;
double *LD,*Ltst,*Lvar,*Lvarval,*Lvar0;
double *Lib,Libmin5,*Lemp,*H0,*L0,*L0v,*Ltr;
int ij_LDmin=0;
int ij_Ltstmin=0;
int ij_Lvarmin=0;
int ij_Lvarvalmin=0;
DIR *pdir;
// int _N1,_N2,_m1,_m2;
int intmode,bayesmode;
double bayesopt1=0,bayesopt2=0,bayesopt3=0,bayesopt4=0;
int m_LD=0;
// char bagalpha[10]={0,};
int BAGGING=0,rs_method=-1,rs_seed=10,rs_ens=1;
// double rs_alpha=0,kc=2;//kc=2:coverage factor for 95% extended uncertainty
double rs_alpha=0;//kc=2:coverage factor for 95% extended uncertainty
double rs_beta=0;
double *rs_Alpha=NULL;
char *rsa;
// sprintf(ensrsprog,"rs4irem");
int t_boost=-1;
// double rethresh_boost=12.0;
int dsp=1;
int DISP=1;
#define NoBoost 0
#define EmBoost 1
#define GbBoost 2
int Boost=NoBoost;
sprintf(ensrsprog,"ensrs");
if(argc<5){
usage(argc,argv);
return(-1);
}
sprintf(fngiven,"%s",argv[1]);
sprintf(fnvalid,"%s",argv[2]);
rsmo=(int *)malloc(sizeof(int)*argc);
for(i=3;i<argc;i++) rsmo[i]=1;
for(i=3;i<argc;i++){
if(strncmp(argv[i],"ib:",3)==0){
sscanf(&(argv[i][3]),"%d:%d:%lf:%lf:%lf:%lf",&intmode,&bayesmode,&bayesopt1,&bayesopt2,&bayesopt3,&bayesopt4);
rsmo[i]=1;
m_LD=bayesopt2;
}
}
for(i=3;i<argc;i++){
if(strncmp(argv[i],"N:",2)==0){
char *p;
int ptn=0;
for(p=&argv[i][2];;){
if(*p==0) break;
if(ptn==0){//unknown pattern
if(*p==':') {ptn=1;break;}
if(*p=='-') {ptn=2;break;}
}
p++;
}
if(ptn==1) {sscanf(&argv[i][2],"%d:%d:%d",&_N1,&_DN,&_nN);_N2=_N1+(_nN-1)*_DN;}
else if(ptn==2) sscanf(&argv[i][2],"%d-%d:%d",&_N1,&_N2,&_DN);
else _N1=_N2=_DN=1;
if(_DN<=0) _DN=1;
for(_nN=0,_N=_N1;_N<=_N2;_N+=_DN) _nN++;
if(_nN<1) _nN=1;
NN=(int *)malloc(sizeof(int)*(_nN+1));
for(jj=0;jj<_nN;jj++) NN[jj]=_N1+_DN*jj;
NN[_nN]=0;
rsmo[i]=0;
}
else if(strncmp(argv[i],"NN:",3)==0){
char *p;
_nN=0;
for(p=&argv[i][3];;){
if(*p==0) break;
if(*p==':') _nN++;
p++;
}
_nN++;
NN=(int *)malloc(sizeof(int)*(_nN+1));
for(p=&argv[i][3],_nN=0;;){
sscanf(p,"%d",&NN[_nN++]);
for(;;) if(*p==':'|| *p=='-' || *p==0) break; else p++;
if(*p==0) break;
if(*p=='-'){
int _n,j;
sscanf(++p,"%d",&_n);
for(j=NN[_nN-1]+1;j<=_n;j++) NN[_nN++]=j;
for(;;) if(*p==':'|| *p=='-' || *p==0) break; else p++;
if(*p==0) break;
}
p++;
}
NN[_nN]=0;
rsmo[i]=0;
}
else if(strncmp(argv[i],"Ngs:",4)==0){
sscanf(&argv[i][4],"%d-%d",&Ngs1,&Ngs2);
_nN=Ngs2-Ngs1;
NN=(int *)malloc(sizeof(int)*(_nN+1));
NN[0]=Ngs1;
NN[1]=Ngs2;
rsmo[i]=0;
}
else if(strncmp(argv[i],"m:",2)==0){
char *p;
int ptn=0;
for(p=&argv[i][2];;){
if(*p==0) break;
if(ptn==0){//unknown pattern
if(*p==':') {ptn=1;break;}
if(*p=='-') {ptn=2;break;}
}
p++;
}
if(ptn==1) {sscanf(&argv[i][2],"%d:%d:%d",&_m1,&_dm,&_nm);_m2=_m1+(_nm-1)*_dm;}
else if(ptn==2) sscanf(&argv[i][2],"%d-%d:%d",&_m1,&_m2,&_dm);
else _m1=_m2=_nm=1;
// sscanf(&argv[i][2],"%d:%d:%d",&_m1,&_m2,&_dm);
//if(_m1<3) _m1=3;
if(_dm<1) _dm=1;
if(_m1<m_LD*2+1) _m1=m_LD*2+1;
for(_nm=0,_m=_m1;_m<=_m2;_m++) _nm++;
mm=(int *)malloc(sizeof(int)*(_nm+1));
for(jj=0;jj<_nm;jj++) mm[jj]=_m1+_dm*jj;
mm[_nm]=0;
rsmo[i]=0;
}
else if(strncmp(argv[i],"M:",2)==0){
char *p;
int ptn=0;
for(p=&argv[i][2];;){
if(*p==0) break;
if(ptn==0){//unknown pattern
if(*p==':') {ptn=1;break;}
if(*p=='-') {ptn=2;break;}
}
p++;
}
if(ptn==1) {sscanf(&argv[i][2],"%d:%d:%d",&_m1,&_dm,&_nm);_m2=_m1+(_nm-1)*_dm;}
else if(ptn==2) sscanf(&argv[i][2],"%d-%d:%d",&_m1,&_m2,&_dm);
else _m1=_m2=_nm=1;
if(_m1<1) _m1=1;
if(_dm<1) _dm=1;
for(_nm=0,_m=_m1;_m<=_m2;_m+=_dm) _nm++;
mm=(int *)malloc(sizeof(int)*(_nm+1));
for(jj=0;jj<_nm;jj++) mm[jj]=_m1+_dm*jj;
mm[_nm]=0;
rsmo[i]=0;
}
else if(strncmp(argv[i],"k:",2)==0) sscanf(&argv[i][2],"%d",&K);
else if(strncmp(argv[i],"rs:",3)==0) {sprintf(ensrsprog,"%s",&argv[i][3]);rsmo[i]=0;}
else if(strncmp(argv[i],"bga:",4)==0){
// sprintf(bagalpha,"%s",&argv[i][4]);rsmo[i]=0;
sscanf(&argv[i][4],"%lf",&rs_alpha);
rs_method=2;
rsmo[i]=0;
rs_seed=10;
rs_ens=1;
}//bootstrap aggregation
else if(strncmp(argv[i],"rsa:",4)==0){
// sscanf(&argv[i][4],"%d:%lf:%d",&rs_method,&rs_alpha,&rs_seed);
int ncol=0;
char *p=&argv[i][4];
for(;*p!=0;p++) if(*p==':') ncol++;
rsa=&argv[i][4];
if(ncol==2) {sscanf(rsa,"%d:%lf:%d",&rs_method,&rs_alpha,&rs_seed);rs_ens=1;}
else if(ncol==3) sscanf(rsa,"%d:%lf:%d:%d",&rs_method,&rs_alpha,&rs_seed,&rs_ens);
else if(ncol==4) sscanf(rsa,"%d:%lf:%d:%d:%lf",&rs_method,&rs_alpha,&rs_seed,&rs_ens,&rs_beta);
BAGGING=1;//bagging with validfile
rsmo[i]=0;
}//resampling aggregation
else if(strncmp(argv[i],"dsp:",4)==0){
sscanf(&argv[i][4],"%d",&dsp);
rsmo[i]=0;
}
else if(strncmp(argv[i],"DISP:",5)==0){
sscanf(&argv[i][5],"%d",&DISP);
// rsmo[i]=0;
}
else if(strncmp(argv[i],"bst:",4)==0){
char *p;
p=&argv[i][4];
for(j=0;;p++) {
if(*p==0) break;
if(*p==':') if(++j>=1) break;
}
// if(j>=1) {sscanf(&argv[i][4],"%d:%lf",&t_boost,&rethresh_boost);}
if(j>=1) {sscanf(&argv[i][4],"%d:%d",&t_boost,&Boost);}
else {sscanf(&argv[i][4],"%d",&t_boost);}
// sscanf(&argv[i][4],"%d",&t_boost);
rsmo[i]=0;
}
}
if(rs_method>=0 && strncmp(fnvalid,"/dev/null",9)==0) BAGGING=2;//bagging without validfile
if(mm==NULL){mm=(int *)malloc(sizeof(int)*(2)); mm[0]=1; mm[1]=0; _nm=1;}//??
LD =(double *)malloc(sizeof(double)*_nN*_nm);
Ltst =(double *)malloc(sizeof(double)*_nN*_nm);
Lvar =(double *)malloc(sizeof(double)*_nN*_nm);
Lvar0 =(double *)malloc(sizeof(double)*_nN*_nm);
Lvarval=(double *)malloc(sizeof(double)*_nN*_nm);
Lib =(double *)malloc(sizeof(double)*_nN*_nm);
Lemp=(double *)malloc(sizeof(double)*_nN*_nm);
H0 =(double *)malloc(sizeof(double)*_nN*_nm);//Entropy
int *s_Ltstmin=(int*)malloc(sizeof(int)*_nN*_nm);
int smax_Ltstmin=_nN*_nm;
// if(smax_Ltstmin>50) smax_Ltstmin=50;
if(smax_Ltstmin>5) smax_Ltstmin=5;
L0 =(double *)malloc(sizeof(double)*_nN*_nm);//OriginalLoss
L0v =(double *)malloc(sizeof(double)*_nN*_nm);//OriginalLoss - Lob
Ltr =(double *)malloc(sizeof(double)*_nN*_nm);//OriginalLoss - Ltr
int *s_L0vmin=(int*)malloc(sizeof(int)*_nN*_nm);
int smax_L0vmin=1;
sprintf(rdir,"%s",rdir0);
if((pdir=opendir(rdir))==NULL) {sprintf(cmd,"mkdir %s",rdir);system(cmd);} else closedir(pdir);
sprintf(rdir,"%s/tmp",rdir0);
if((pdir=opendir(rdir))==NULL) {sprintf(cmd,"mkdir %s",rdir);system(cmd);} else closedir(pdir);
{ //dir to store the result
sprintf(rdir,"%s",rdir0);
if((pdir=opendir(rdir))==NULL) {sprintf(cmd,"mkdir %s",rdir);system(cmd);} else closedir(pdir);
sprintf(&rdir[strlen(rdir)],"/%s",fnbody(fngiven,pr));//
sprintf(&rdir[strlen(rdir)],"+%s",fnbody(fnvalid,pr));//
for(i=2;i<argc;i++){
sprintf(&rdir[strlen(rdir)],"%s",argv[i]);
}
for(i=strlen(rdir0)+1;rdir[i]!=0;i++) if(rdir[i]=='/') rdir[i]='@';
rdir[240]=0;
if((pdir=opendir(rdir))==NULL) {sprintf(cmd,"mkdir %s",rdir);system(cmd);}
else closedir(pdir);
}
sprintf(fnloss,"%s/loss.dat",rdir);
sprintf(fnplt ,"%s/loss.plt",rdir);
int nGivenData;
///////////For Golden Section Method
const double r = 2. / (3. + sqrt(5.));//0.381966
double c, d, fc, fd, t,*pfcd;
double a, b, fa, fb;
char *fn_predall="predict+all.dat";
int n_predall=0;
// if((fploss=fopen(fnloss,"r"))==NULL){
if(1==1 || (fploss=fopen(fnloss,"r"))==NULL){
for(i=0;i<_nN;i++){
for(j=0;j<_nm;j++){
ij=i*_nm+j;
if(rs_method<0){//for specified valid-file
sprintf(cmd,"%s %s -1:%s %d-%d:%d ",ensrsprog,fngiven,fnvalid,NN[i]-m_LD*_DN,NN[i]+(mm[j]-1+m_LD)*_DN,_DN);
}
else{//for bagging or unspecified valid-file
if(rs_beta>1){
if(rs_Alpha==NULL){
rs_Alpha=(double *)malloc(sizeof(double)*(_nN+1));
FILE *fp=fopen(fngiven,"r");
char line[10240];
for(nGivenData=0;;nGivenData++){
fgets(line,10240,fp);
if(feof(fp)) break;
}
fclose(fp);
}
rs_Alpha[i]=-log(NN[i]*(K+1)*rs_beta/nGivenData);
if(rs_Alpha[i]>2.3) rs_Alpha[i]=2.3;
rs_alpha=rs_Alpha[i];
}
if(t_boost==-1 || Boost==NoBoost){//default for resampling = Bagging-Only
// sprintf(cmd,"%s %s %d:%d:%.2f:%d %d-%d:%d bg:%s ",ensrsprog,fngiven,rs_method,rs_ens,rs_Alpha[i],rs_seed,NN[i],NN[i]+(mm[j]-1)*_DN,1,fnvalid);//for ensrs060609.c
sprintf(cmd,"%s %s %d:%d:%g:%d %d-%d:%d bg:%s ",ensrsprog,fngiven,rs_method,rs_ens,rs_alpha,rs_seed,NN[i],NN[i]+(mm[j]-1)*_DN,1,fnvalid);//for ensrs060609.c
//sprintf(cmd,"%s %s %d:%d:%.2f:%d %d-%d:%d bg:%s ",ensrsprog,fngiven,rs_method,rs_ens,rs_alpha,rs_seed,NN[i]-m_LD*_DN,NN[i]+(mm[j]-1+m_LD)*_DN,1,fnvalid);
//sprintf(cmd,"%s %s %d:%d:%.2f:%d %d-%d:%d bg:%s ",ensrsprog,fngiven,rs_method,mm[j],rs_alpha,rs_seed,NN[i],NN[i],1,fnvalid);//for ensrs060608.c
}
else if(Boost==GbBoost){//Gradient-based boosting
int t;
for(t=1;t<=t_boost;t++){
// sprintf(cmd,"%s %s %d:%d:%.2f:%d %d-%d:%d bg:%s bst:%d:%d ",ensrsprog,fngiven,rs_method,rs_ens,rs_Alpha[i],rs_seed,NN[i],NN[i]+(mm[j]-1)*_DN,1,fnvalid,t,Boost);//for ensrs060907.c
sprintf(cmd,"%s %s %d:%d:%g:%d %d-%d:%d bg:%s bst:%d:%d ",ensrsprog,fngiven,rs_method,rs_ens,rs_alpha,rs_seed,NN[i],NN[i]+(mm[j]-1)*_DN,1,fnvalid,t,Boost);//for ensrs060907.c
if(t==t_boost) break;
for(jj=3;jj<argc;jj++) if(rsmo[jj]) sprintf(&cmd[strlen(cmd)],"%s ",argv[jj]);
sprintf(&cmd[strlen(cmd)],"> /dev/null");
fprintf(stderr,"! Executing '%s'.\n",cmd);
system(cmd);
}
}
else if(Boost==EmBoost){
// sprintf(cmd,"%s %s %d:%d:%.2f:%d %d-%d:%d bg:%s bst:%d:%d ",ensrsprog,fngiven,rs_method,rs_ens,rs_Alpha[i],rs_seed,NN[i],NN[i]+(mm[j]-1)*_DN,1,fnvalid,t_boost,Boost);//for ensrs060907.c
sprintf(cmd,"%s %s %d:%d:%g:%d %d-%d:%d bg:%s bst:%d:%d ",ensrsprog,fngiven,rs_method,rs_ens,rs_alpha,rs_seed,NN[i],NN[i]+(mm[j]-1)*_DN,1,fnvalid,t_boost,Boost);//for ensrs060907.c
}
}//elsee{//for bagging or unspecified valid-file
// sprintf(cmd,"%s %s -1:%s %d-%d:%d ",ensrsprog,fngiven,fnvalid,NN[i]-mm[j],NN[i]+mm[j],_d);
// sprintf(cmd,"%s %s -1:%s %d-%d:%d ",ensrsprog,fngiven,fnvalid,NN[i],NN[i]+mm[j]+2*m_LD,_dm);
// sprintf(cmd,"%s %s -1:%s %d-%d:%d ",ensrsprog,fngiven,fnvalid,NN[i],NN[i]+mm[j]*_DN,_DN);
// sprintf(cmd,"%s %s -1:%s %d-%d:%d ",ensrsprog,fngiven,fnvalid,NN[i],NN[i]+mm[j],_dm);
// sprintf(cmd,"%s %s -1:%s %d:%d:%d ",ensrsprog,fngiven,fnvalid,NN[i],mm[j],_dm);
// sprintf(cmd,"%s %s -1:%s %d-%d ",ensrsprog,fngiven,fnvalid,NN[i],NN[i]+mm[j]-1);
for(jj=3;jj<argc;jj++) if(rsmo[jj]) sprintf(&cmd[strlen(cmd)],"%s ",argv[jj]);
sprintf(&cmd[strlen(cmd)],"> /dev/null");
fprintf(stderr,"Executing '%s'.\n",cmd);
if(system(cmd)==-1){
fprintf(stderr,"Error when executing '%s'.\n",cmd);
return(-1);
}
#ifdef PREDALL
{
if(n_predall==0){
sprintf(cmd,"cat predict+.dat|awk '{print $2,$3,$1;}'> %s",fn_predall);
fprintf(stderr,"#executing %s\n",cmd);
system(cmd);
}
else{
sprintf(cmd,"cp %s p1.dat;cat predict+.dat |awk '{print $1}'| paste p1.dat - > %s",fn_predall,fn_predall);
fprintf(stderr,"#executing %s\n",cmd);
system(cmd);
}
n_predall++;
}
#endif//#ifdef PREDALL
double *func=Ltst;
//double *func=LD;//check LD/N for estimating bias
{
int _nfiles,_num;
fp=fopen("./loss+.dat","r");
fscanf(fp,"%lf %lf %lf %lf %lf %d %d %lf %lf %lf %lf %lf",&LD[ij],&Ltst[ij],&Lvar[ij],&Lvarval[ij],&Lvar0[ij],&_nfiles,&_num,&Lib[ij],&Lemp[ij],&H0[ij],&L0[ij],&Ltr[ij]);
L0v[ij]=L0[ij]-Lvar[ij];
//double tmp=Ltst[ij]; Ltst[ij]=LD[ij];LD[ij]=tmp;//check LD/N for estimating bias
//double tmp=Ltst[ij]; Ltst[ij]=LD[ij]/(NN[i]);LD[ij]=tmp;//check LD/N for estimating bias
// double tmp=Ltst[ij]; Ltst[ij]=LD[ij]/(NN[i]*NN[i]);LD[ij]=tmp;//check LD/N for estimating bias
// LD[ij]/=(NN[i]*NN[i]);//checkLD/N//check LD/N for estimating bias
// LD[ij]/=NN[i];//checkLD/N//check LD/N for estimating bias
// double tmp=Ltst[ij]; Ltst[ij]=LD[ij]/NN[i];LD[ij]=tmp;//check LD/N for estimating bias
// double tmp=Ltst[ij]; Ltst[ij]=-LD[ij]/NN[i];LD[ij]=tmp;//check LD/N for estimating bias
fclose(fp);
}
if(Ngs1!=0){//golden section method searches Ltst
if(i==0){a=NN[i];fa=func[ij];} // if(i==0){a=NN[i];fa=Ltst[ij];}
else if(i==1){
b=NN[i];
fb=func[ij]; // fb=Ltst[ij];
t = r * (b - a);
c=a+t;
d=b-t;
NN[i+1]=(int)(c+.5);
NN[i+2]=(int)(d+.5);
}
else if(i==2){
fc=func[ij];// fc=Ltst[ij];
pfcd=&fd;
if((fa>=fc && fc>=fb) || (fa<=fc && fc<=fb)){
fprintf(stderr,"#(i%d)Ltst(%d)%g,Ltst(%d)%g,Ltst(%d)%g\n",i,(int)(a+.5),fa,(int)(c+.5),fc,(int)(b+.5),fb);
fprintf(stderr,"# Minimum of L may not be in the range Ngs:%d:%d !!!\n",Ngs1,Ngs2);
// exit(-1);
}
}
else if(i>=3){
*pfcd=func[ij];// *pfcd=Ltst[ij];
fprintf(stderr,"#(i%d)Ltst(%d)%g,Ltst(%d)%g,Ltst(%d)%g,Ltst(%d)%g \n",i,(int)(a+.5),fa,(int)(c+.5),fc,(int)(d+.5),fd,(int)(b+.5),fb);
if(i>=10 && (fc>func[1] &&(fd>func[1]))){ // if(i>=10 && (fc> Ltst[1]) &&(fd>Ltst[1])){
fprintf(stderr,"#(i%d)Ltst(%d)%g,Ltst(%d)%g,Ltst(%d)%g\n",i,(int)(c+.5),fc,(int)(b+.5),fb,NN[1],Ltst[1]);
fprintf(stderr,"# Minimum of L may not be in the range Ngs:%d:%d !!!\n",Ngs1,Ngs2);
// exit(-1);
}
if(fc>fd){
a = c; c = d; fc = fd; d = b - r * (b - a);
if (d - c < 0.5) {
_nN=i+1;
break;
}
NN[i+1]=(int)(d+.5);
pfcd=&fd;
// fd = f(d,par);
} else {
b = d; d = c; fd = fc; c = a + r * (b - a);
if (d - c < 0.5) {
_nN=i+1;
break;
}
NN[i+1]=(int)(c+.5);
pfcd=&fc;
// fc = f(c,par);
}
}
}
// {//060517
// double _msemean,_msestdp,_msestdm;
// fp=fopen("./tmp/rsresult.dat","r");
// fscanf(fp,"%lf %lf %lf %lf",&_msemean,&_msestdp,&_msestdm,&Lib[ij]);
// fclose(fp);
// }
}
}
fploss=fopen(fnloss,"w");
for(i=0;i<_nN;i++){
for(j=0;j<_nm;j++){
ij=i*_nm+j;
fprintf(fploss,"%d %d %13.7e %13.7e %13.7e %13.7e %13.7e %13.7e %.7e %.7e %.7e#N m LD Ltst Lvar Lvarval Lvar0\n",
NN[i],mm[j],LD[ij],Ltst[ij],Lvar[ij],Lvarval[ij],Lvar0[ij],Lib[ij],Lemp[ij],H0[ij],L0[ij]);
}
fprintf(fploss,"\n");
}
fclose(fploss);
if(Ngs1!=0){
sprintf(cmd,"sort -g %s >tmploss.dat; mv tmploss.dat %s",fnloss,fnloss);
system(cmd);
}
fploss=fopen(fnloss,"r");
}//closing if((fploss=fopen(fnloss,"r"))==NULL){
#define FINISH
#ifdef FINISH
#ifdef PREDALL
if((DISP&0x02)==0x02){
sprintf(fnplt ,"dispypall.plt");
fp=fopen(fnplt,"w");
fprintf(fp,"set style data lines\n");
fprintf(fp,"plot \"%s\" using 1:2 w lp t \"y\"",fn_predall);
int m;
for(m=0;m<n_predall;m++) fprintf(fp,", \"\" using 1:%d t \"y^N%d\"",3+m,NN[m/_nm]);
fprintf(fp,"\npause -1 \"hit return to quit.\"\n");
fclose(fp);
sprintf(cmd,"xterm -geometry 50x5+0-0 -e gnuplot -geometry 320x180+0+0 %s",fnplt);
fprintf(stderr,"Execute '%s'.\n",cmd);
sprintf(&cmd[strlen(cmd)],"&");
system(cmd);
}
#endif//#ifdef PREDALL
return(0);
}
#else
{
char buff[buffsize];
// int _NN,_mm;
int _mm;
ij_LDmin=ij_Ltstmin=ij_Lvarmin=ij_Lvarvalmin=0;
for(i=0;i<_nN;i++){
for(j=0;j<_nm;j++){
ij=i*_nm+j;
for(;;){
fgets(buff,buffsize,fploss);
if(feof(fploss)) break;
if(strlen(buff)>1) break;
}
sscanf(buff,"%d %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&NN[i],&_mm,&LD[ij],&Ltst[ij],&Lvar[ij],&Lvarval[ij],&Lvar0[ij],&Lib[ij],&Lemp[ij],&H0[ij],&L0[ij],&Ltr[ij]);
L0v[ij]=L0[ij]-Lvar[ij];
// &_NN,&_mm,&LD[ij],&Ltst[ij],&Lvar[ij],&Lvarval[ij],&Lvar0[ij],&Lib[ij],&Lemp[ij],&H0[ij]);
// Lvar[ij]*=(mm[j]/(mm[j]-1+1e-3));
// Lvar0[ij]*=(mm[j]/(mm[j]-1+1e-3));
// &NN[i],&mm[j],&LD[ij],&Ltst[ij],&Lvar[ij],&Lvarval[ij]);
// if(_mm!=mm[j]){
// fprintf(stderr,"m=%d,%dhen\n",mm[j],_mm);
// }
// if(_NN!=NN[i]){
// fprintf(stderr,"N=%d,%dhen\n",NN[i],_NN);
// }
{
// if(LD[ij]<1e-20){ fprintf(stderr,"hen\n"); }
if(LD[ij]<LD[ij_LDmin]) ij_LDmin=ij;
if(Ltst[ij]<Ltst[ij_Ltstmin]) ij_Ltstmin=ij;
if(Lvar[ij]<Lvar[ij_Lvarmin]) ij_Lvarmin=ij;
if(Lvarval[ij]<Lvarval[ij_Lvarmin]) ij_Lvarvalmin=ij;
// if(LD[ij]>1e-20 && LD[ij]<LD[ij_LDmin]) ij_LDmin=ij;
// if(Ltst[ij]>1e-20 && Ltst[ij]<Ltst[ij_Ltstmin]) ij_Ltstmin=ij;
// if(Lvar[ij]>1e-20 && Lvar[ij]<Lvar[ij_Lvarmin]) ij_Lvarmin=ij;
// if(Lvarval[ij]>1e-20 && Lvarval[ij]<Lvarval[ij_Lvarmin]) ij_Lvarvalmin=ij;
}
}
}
fclose(fploss);
}
double Libr=2.0;
Libmin5=1e30;
for(i=0;i<_nN*_nm;i++) {
s_Ltstmin[i]=i;
// if(Libmin5>Lib[i]) Libmin5=Lib[i];
}
{
// Libmin5*=2.;
for(i=0;i<smax_Ltstmin;i++){
for(j=i+1;j<_nN*_nm;j++){
if(Ltst[s_Ltstmin[j]]<Ltst[s_Ltstmin[i]]){
int itmp=s_Ltstmin[i];
s_Ltstmin[i]=s_Ltstmin[j];
s_Ltstmin[j]=itmp;
}
}
}
}
{
// Libmin5*=2.;
for(i=0;i<smax_L0vmin;i++){
for(j=i+1;j<_nN*_nm;j++){
if(L0v[s_L0vmin[j]]<L0v[s_L0vmin[i]]){
int itmp=s_L0vmin[i];
s_L0vmin[i]=s_L0vmin[j];
s_L0vmin[j]=itmp;
}
}
}
}
{
//for local min
int *ss,itmp,n=_nN*_nm,ns=10,is;
int n0,m0,n1,n2,i0,j0,ii,jj;
int localmin;
ss=(int *)malloc(sizeof(int)*n);
//Local min of LD
{
fprintf(stderr,"##Increasing Lib (Check Overfitting)\n");
ns=3;
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(Lib[ss[i]]>Lib[ss[j]]){//Increasing
// if(LD[ss[i]]<LD[ss[j]]){//Decreasing
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
// if(Lib[ss[i]]>Libmin5) continue;
// if(Lvar[ss[i]]<1e-20) continue;
// i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
// for(ii=i0-1;ii<=i0+1;ii++){
// for(jj=j0-1;jj<=j0+1;jj++){
// if(ii<0) continue;
// if(ii>_nN-1) continue;
// if(jj<0) continue;
// if(jj>_nm-1) continue;
// if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
// }
// }
if(localmin==1){
is++;
if(is<=ns){
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"%3d:%3d(N:%3d-%3d)LD=%.3e Lvar=%.3e Lvar0=%.3e Ltst=%.3e Lib%d=%.3e",n0,m0,n1,n2,LD[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],i,Lib[ss[i]]);
// // fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// // fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n0+m0-1-_DN*m_LD));
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD=%.3e Lvar=%.3e Lvar0=%.3e Lib%d=%.3e Ltst=%.3e N:%d-:%d M:%d\n",LD[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],i,Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d)LD=%.3e Lvar=%.3e Lvar0=%.3e Ltst=%.3e Lib%d=%.3e\n",n0,m0,n1,n2,LD[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],i,Lib[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n0+m0-1-_DN*m_LD));
}
}
// if(is>=ns) break;
}
}
if(!BAGGING){
Libmin5=Lib[ss[0]];
fprintf(stderr,"#Below, ignore Lib>(Libmin=%.3e)*%.2f=",Libmin5,Libr);
Libmin5*=Libr;fprintf(stderr,"%e\n",Libmin5);
{
fprintf(stderr,"##Increasing LD with local min of LD\n");
// fprintf(stderr,"##Decreasing LD with local min of LD\n");
ns=3;
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(LD[ss[i]]>LD[ss[j]]){//Increasing
// if(LD[ss[i]]<LD[ss[j]]){//Decreasing
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
for(ii=i0-1;ii<=i0+1;ii++){
for(jj=j0-1;jj<=j0+1;jj++){
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
// if(ii<NN[0]) continue;
// if(ii>NN[_nN-1]) continue;
// if(jj<mm[0]) continue;
// if(jj>mm[_nm-1]) continue;
//
if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
}
}
if(localmin==1){
is++;
if(is<=ns){
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LDmin%3d=%.3e Lvar=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",i,LD[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d)LDmin%3d=%.3e Lvar=%.3e Lvar0=%.3e Ltst=%.3e Lib=%.3e\n",n0,m0,n1,n2,i,LD[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LDmin%3d=%e Lvar=%e Ltst=%e\n",n0,m0,n1,n2,i,LD[ss[i]],Lvar[ss[i]],Ltst[ss[i]]);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LDmin%3d=%e Lvar=%e Ltst=%e LD*Lvar=%e\n",n0,m0,n1,n2,i,LD[ss[i]],Lvar[ss[i]],Ltst[ss[i]],LD[ss[i]]*Lvar[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
}
}
// if(is>=ns) break;
}
fprintf(stderr,"#TotalLocalmins of LD=%d(<%d)\n",is,n);
}
{
double *_L =(double *)malloc(sizeof(double)*_nN*_nm);
fprintf(stderr,"##Increasing _L=(Lvar/Lvar0) with local min of LD\n");
ns=3;
for(i=0;i<n;i++){
// _L[i]=Lemp[i]-Lvar0[i];
//_L[i]=Lib[i]-Lvar0[i];
// _L[i]=Lib[i]+Lvar0[i];//bad
// _L[i]=Lvar0[i];//bad
// _L[i]=Lvar[i];//good
_L[i]=Lvar[i]/Lvar0[i];//NG for 2e3
// _L[i]=Lvar[i]-Lvar0[i];//Good
}
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
// if(_L[ss[i]]<_L[ss[j]]){
if(_L[ss[i]]>_L[ss[j]]){
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
for(ii=i0-1;ii<=i0+1;ii++){
for(jj=j0-1;jj<=j0+1;jj++){
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
}
}
// localmin=1;
if(localmin==1){
is++;
if(is<=ns){
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"_L%3d=%.3e Lvar=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",i,_L[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d)_L%3d=%.3e Lvar=%.3e Lvar0=%.3e Ltst=%.3e Lib=%.3e",n0,m0,n1,n2,i,_L[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
}
}
}
free(_L);
}
{
double *_LD2 =(double *)malloc(sizeof(double)*_nN*_nm);
// fprintf(stderr,"##Increasing LD with local min of LD\n");
fprintf(stderr,"##Decreasing LD2 with local min of LD\n");
ns=3;
for(i=0;i<n;i++){
i0=i/_nm;j0=i%_nm;
ii=i0-1;if(ii<0) ii=0;
// _LD2[i]=Lib[ii*_nm+j0]-Lib[i];//060529
//_LD2[i]=-Lib[ii*_nm+j0];//060529
//_LD2[i]=LD[i]-LD[ii*_nm+j0];//060529
// _LD2[i]=LD[ii*_nm+j0]-LD[i];ii=i0+1;if(ii>=_nN) ii=_nN-1;_LD2[i] = (LD[ii*_nm+j0]-LD[i])/_LD2[i];//060529
_LD2[i]=LD[ii*_nm+j0]-LD[i];_LD2[i] = 1./_LD2[i];//060529
}
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(_LD2[ss[i]]<_LD2[ss[j]]){
// if(_LD2[ss[i]]>_LD2[ss[j]]){
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
for(ii=i0-1;ii<=i0+1;ii++){
for(jj=j0-1;jj<=j0+1;jj++){
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
// if(ii<NN[0]) continue;
// if(ii>NN[_nN-1]) continue;
// if(jj<mm[0]) continue;
// if(jj>mm[_nm-1]) continue;
//
if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
}
}
if(localmin==1){
is++;
if(is<=ns){
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD2max%3d=%.3e Lvar=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",i,_LD2[ss[i]],Lvar[ss[i]],Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD2:%3d=%e Lvar=%e Ltst=%e\n",n0,m0,n1,n2,i,LD[ss[i]],Lvar[ss[i]],Ltst[ss[i]]);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD2:%3d=%e Lvar=%e Ltst=%e LD*Lvar=%e\n",n0,m0,n1,n2,i,LD[ss[i]],Lvar[ss[i]],Ltst[ss[i]],LD[ss[i]]*Lvar[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
}
if(is>=ns) break;
}
}
// fprintf(stderr,"#TotalLocalmins of LD=%d(<%d)\n",is,n);
free(_LD2);
}
//local min of Lvar
{
fprintf(stderr,"##Increasing Lvar with local min of Lvar\n");
ns=3;
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(Lvar[ss[i]]>Lvar[ss[j]]){
// if(Lvar[ss[i]]<Lvar[ss[j]]){
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
for(ii=i0-1;ii<=i0+1;ii++){
for(jj=j0-1;jj<=j0+1;jj++){
// fprintf(stderr,"ii,jj=%d:%d\n",ii,jj);
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
if(Lvar[ii*_nm+jj]<Lvar[ss[i]]) {localmin=0;break;}
}
}
if(localmin==1){
is++;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD=%.3e Lvarmin%3d=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%.3e Lvarmin%3d=%.3e Lvar0=%.3e Ltst=%.3e Lib=%.3e",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%e Lvarmin%3d=%e Ltst=%e\n",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Ltst[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
if(is>=ns) break;
}
}
}
{
// fprintf(stderr,"##global Lvar max with local min\n");
fprintf(stderr,"##Decreasing Lvar with local min of LD\n");
ns=3;
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
// if(Lvar[ss[i]]>Lvar[ss[j]]){
if(Lvar[ss[i]]<Lvar[ss[j]]){
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
if(Lib[ss[i]]>Libmin5) continue;
for(ii=i0-1;ii<=i0+1;ii++){
for(jj=j0-1;jj<=j0+1;jj++){
// fprintf(stderr,"ii,jj=%d:%d\n",ii,jj);
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
if(Lvar[ii*_nm+jj]<Lvar[ss[i]]) {localmin=0;break;}
}
}
if(localmin==1){
is++;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD=%.3e Lvarmax%3d=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%.3e Lvarmax%3d=%.3e Lvar0=%.3e Ltst=%.3e Lib=%.3e",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%e Lvarmin%3d=%e Ltst=%e\n",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Ltst[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
if(is>=ns) break;
}
}
}
//global Lvar min and local LDmin
{
fprintf(stderr,"##Increasing Lvar with local min of LD (9neighbour of (l1,ld) **Use this or the next)** \n");
// fprintf(stderr,"##global min of Lvar with local min of LD\n");
ns=3;
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(Lvar[ss[i]]>Lvar[ss[j]]){
//if(Lvar[ss[i]]<Lvar[ss[j]]){//060517
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
for(ii=i0-1;ii<=i0+1;ii++){
for(jj=j0-1;jj<=j0+1;jj++){
// fprintf(stderr,"ii,jj=%d:%d\n",ii,jj);
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
}
}
if(localmin==1){
is++;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD=%.3e Lvarmin%2d=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"#%2d:%2d(N:%2d-%2d) LD=%.3e Lvarmin%2d=%.3e Lvar0=%.3e Ltst=%.3e Lib=%.3e",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%e Lvarmin%3d=%e Ltst=%e\n",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Ltst[ss[i]]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
if(is>=ns) break;
}
}
}
{
fprintf(stderr,"##Increasing Lvar with local min of LD (9neighbour of (l1,l2)**Use this or the above)**) \n");
ns=3;
for(i=0;i<n;i++) ss[i]=i;
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(Lvar[ss[i]]>Lvar[ss[j]]){
// if(Lvar[ss[i]]<Lvar[ss[j]]){//060517
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
{
int iii;
for(iii=0;iii<9;iii++){
if(iii==0){ii=i0-1;jj=j0 ;}//l1-1,l2-1
if(iii==1){ii=i0-1;jj=j0+1;}//l1-1,l2
if(iii==2){ii=i0-1;jj=j0+2;}//l1-1,l2+1
if(iii==3){ii=i0 ;jj=j0-1;}//l1-1,l2-1
if(iii==4){ii=i0 ;jj=j0 ;}//l1-1,l2
if(iii==5){ii=i0 ;jj=j0+1;}//l1-1,l2+1
if(iii==6){ii=i0+1;jj=j0-2;}//l1-1,l2-1
if(iii==7){ii=i0+1;jj=j0-1;}//l1-1,l2
if(iii==8){ii=i0+1;jj=j0 ;}//l1-1,l2+1
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
}
}
if(localmin==1){
is++;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD=%.3e Lvarmin%3d=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d D:%d m:%d\n",LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// // fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%e Lvarmin%3d=%e Ltst=%e\n",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Ltst[ss[i]]);
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%.3e Lvarmin%3d=%.3e Lvar0=%.3e Ltst=%.3e Lib=%.3e",n0,m0,n1,n2,LD[ss[i]],i,Lvar[ss[i]],Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// // fprintf(stderr,"**N:%d-%d\n",n0+_DN,n2=n0+m0-2);
// // fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
if(is>=ns) break;
}
}
}
{
double *_Lvar =(double *)malloc(sizeof(double)*_nN*_nm);
fprintf(stderr,"##Increasing |Lvar-Lvar0|\n");
ns=3;
for(i=0;i<n;i++){
ss[i]=i;
_Lvar[i]=Lvar[i]-Lvar0[i];//060529
// _Lvar[i]=fabs(Lvar[i]/Lvar0[i]-1.2);//060529
// _Lvar[i]=fabs((Lvar[i]-Lvar0[i])/Lib[i]);//060518??
// _Lvar[i]=Lvar[i]/Lvar0[i];
// _Lvar[i]=fabs(Lvar[i]-Lvar0[i]);//good one
// _Lvar[i]=fabs((Lvar[i]-Lvar0[i])/Lvar0[i]);//060518??
// _Lvar[i]=fabs((Lvar[i]-Lvar0[i])/sqrt(Lib[i]));//060518??
// _Lvar[i]=fabs(Lvar[i]-Lvar0[i])/Lvar[i];
// _Lvar[i]=fabs(Lvar[i]-Lvar0[i])/Lvar0[i];
}
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(_Lvar[ss[i]]>_Lvar[ss[j]]){
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
// for(ii=i0-1;ii<=i0+1;ii++){
// for(jj=j0-1;jj<=j0+1;jj++){
// // fprintf(stderr,"ii,jj=%d:%d\n",ii,jj);
// if(ii<0) continue;
// if(ii>_nN-1) continue;
// if(jj<0) continue;
// if(jj>_nm-1) continue;
// if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
// }
// }
if(localmin==1){
is++;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD=%.3e Lvar=%.3e Lvar0min%3d=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",LD[ss[i]],Lvar[ss[i]],i,Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%.3e Lvar=%.3e Lvar0min%3d=%.3e Ltst=%.3e Lib=%.3e",n0,m0,n1,n2,LD[ss[i]],Lvar[ss[i]],i,Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// // fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
if(is>=ns) break;
}
}
}
{
double *_Lvar =(double *)malloc(sizeof(double)*_nN*_nm);
fprintf(stderr,"##Increasing |Lvar-Lvar0| with local min of LD(9neighbour of (l1,ld)\n");
ns=3;
for(i=0;i<n;i++){
ss[i]=i;
_Lvar[i]=Lvar[i]-Lvar0[i];//060529
// _Lvar[i]=fabs(Lvar[i]/Lvar0[i]-1.2);//060529??
// _Lvar[i]=fabs((Lvar[i]-Lvar0[i])/Lib[i]);//060518??
// _Lvar[i]=Lvar[i]/Lvar0[i];
// _Lvar[i]=fabs(Lvar[i]-Lvar0[i]);//good one
// _Lvar[i]=fabs((Lvar[i]-Lvar0[i])/Lvar0[i]);//060518??
// _Lvar[i]=fabs((Lvar[i]-Lvar0[i])/sqrt(Lib[i]));//060518??
// _Lvar[i]=fabs(Lvar[i]-Lvar0[i])/Lvar[i];
// _Lvar[i]=fabs(Lvar[i]-Lvar0[i])/Lvar0[i];
}
is=0;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(_Lvar[ss[i]]>_Lvar[ss[j]]){
itmp=ss[i];
ss[i]=ss[j];
ss[j]=itmp;
}
}
if(Lib[ss[i]]>Libmin5) continue;
if(Lvar[ss[i]]<1e-20) continue;
if(Lvar[ss[i]]<Lvar0[ss[i]]) continue;
i0=ss[i]/_nm;j0=ss[i]%_nm;
localmin=1;
for(ii=i0-1;ii<=i0+1;ii++){
for(jj=j0-1;jj<=j0+1;jj++){
// fprintf(stderr,"ii,jj=%d:%d\n",ii,jj);
if(ii<0) continue;
if(ii>_nN-1) continue;
if(jj<0) continue;
if(jj>_nm-1) continue;
if(LD[ii*_nm+jj]<LD[ss[i]]) {localmin=0;break;}
}
}
if(localmin==1){
is++;
n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;
fprintf(stderr,"LD=%.3e Lvar=%.3e Lvar0min%3d=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",LD[ss[i]],Lvar[ss[i]],i,Lvar0[ss[i]],Lib[ss[i]],Ltst[ss[i]],n1,_DN,m0);
// n0=NN[ss[i]/_nm];m0=mm[ss[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"%3d:%3d(N:%3d-%3d) LD=%.3e Lvar=%.3e Lvar0min%3d=%.3e Ltst=%.3e Lib=%.3e",n0,m0,n1,n2,LD[ss[i]],Lvar[ss[i]],i,Lvar0[ss[i]],Ltst[ss[i]],Lib[ss[i]]);
// // fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
if(is>=ns) break;
}
}
}
}
static char pr1[buffsize];
fp=fopen(fnplt,"w+");
for(i=0;i<smax_Ltstmin;i++){
n0=NN[s_Ltstmin[i]/_nm];m0=mm[s_Ltstmin[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"t:%s v:%s LD%.2eLvar%.2eLvar0%.2eLib%.3eLtst%d=%.3eOvf%.3eLb'%.3eN:%d-:%dM:%drsa:%s\n",
// fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[s_Ltstmin[i]],Lvar[s_Ltstmin[i]],Lvar0[s_Ltstmin[i]],Lib[s_Ltstmin[i]],i,Ltst[s_Ltstmin[i]],
// // Ltst[s_Ltstmin[i]]-Lib[s_Ltstmin[i]],//overfit
// Ltst[s_Ltstmin[i]]+Lvar0[s_Ltstmin[i]]-Lib[s_Ltstmin[i]],//overfit
// (Lib[s_Ltstmin[i]]-Lvar0[s_Ltstmin[i]])/Ltst[s_Ltstmin[i]],//Lbias-Ovrfit
// n1,_DN,m0,rsa);
if(BAGGING==2){
// fprintf(stderr,"t:%s v:%s Ltst%d=%.3e(LvarPop%.3e)LbiasPop%.3e,LbiasPopB%.3eLib%.3eN:%d-:%dM:%drsa:%sbst:%d:%d\n",
fprintf(stderr,"t:%s v:%s Lob%d=%.3e(uc%.3e)Lbias%.3e,LbiasPopB%.3eLib%.3eLemp%.3eH%.4fN:%d-:%dM:%drsa:%sbst:%d:%d\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),
i,Ltst[s_Ltstmin[i]],
LD[s_Ltstmin[i]],
Ltst[s_Ltstmin[i]]-LD[s_Ltstmin[i]],//Ltst-Lvar=Lbias+Lnoise
Ltst[s_Ltstmin[i]]+(1.-rs_alpha)*LD[s_Ltstmin[i]],//kc=2:coverage factor for 95% extended uncertainty
// Ltst[s_Ltstmin[i]]-(rs_alpha-1.)*LD[s_Ltstmin[i]],//kc=2:coverage factor for 95% extended uncertainty
//Ltst[s_Ltstmin[i]]-5.*LD[s_Ltstmin[i]]-4.*sqrt((LD[s_Ltstmin[i]])*(Ltst[s_Ltstmin[i]]-LD[s_Ltstmin[i]])),//kc=2:coverage factor for 95% extended uncertainty
//Ltst[s_Ltstmin[i]]+3.*LD[s_Ltstmin[i]]+4.*sqrt((LD[s_Ltstmin[i]])*(Ltst[s_Ltstmin[i]]-LD[s_Ltstmin[i]])),
// Ltst[s_Ltstmin[i]]-5.*LD[s_Ltstmin[i]],//kc=2:coverage factor for 95% extended uncertainty
// Ltst[s_Ltstmin[i]]+3.*LD[s_Ltstmin[i]],
Lib[s_Ltstmin[i]],
Lemp[s_Ltstmin[i]],
H0[s_Ltstmin[i]],
n1,_DN,m0,rsa,t_boost,Boost);
}
else{
fprintf(stderr,"t:%s v:%s LD%.2eLvar%.2eLvar0%.2eLib%.3eH%.4fLtst%d=%.3eN:%d-:%dM:%drsa:%sbst:%d:%d\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[s_Ltstmin[i]],Lvar[s_Ltstmin[i]],Lvar0[s_Ltstmin[i]],Lib[s_Ltstmin[i]],
// fprintf(stderr,"t:%s v:%s LD%.2eLvar%.2eLvar0%.2eLemp%.3eH%.4fLtst%d=%.3eN:%d-:%dM:%drsa:%sbst:%d:%d\n",
// fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[s_Ltstmin[i]],Lvar[s_Ltstmin[i]],Lvar0[s_Ltstmin[i]],Lemp[s_Ltstmin[i]],
//fprintf(stderr,"t:%s v:%s LD%.2eLvar%.2eLvar0%.2eLib%.3eH%.4fLtst%d=%.3eN:%d-:%dM:%drsa:%sbst:%d:%d\n",
//fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[s_Ltstmin[i]],Lvar[s_Ltstmin[i]],Lvar0[s_Ltstmin[i]],Lib[s_Ltstmin[i]],
H0[s_Ltstmin[i]],
i,Ltst[s_Ltstmin[i]],
n1,_DN,m0,rsa,t_boost,Boost);
// fprintf(stderr,"t:%s v:%s LD%.2eLvar%.2eLvar0%.2eLib%.3eLtst%d=%.3eLtr+Lvl%.3eN:%d-:%dM:%drsa:%sbst:%d\n",
// fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[s_Ltstmin[i]],Lvar[s_Ltstmin[i]],Lvar0[s_Ltstmin[i]],Lib[s_Ltstmin[i]],i,Ltst[s_Ltstmin[i]],
// Ltst[s_Ltstmin[i]]+Lib[s_Ltstmin[i]],n1,_DN,m0,rsa,t_boost);
}
//// fprintf(stderr,"t:%s v:%s LD%.2eLvar%.2eLvar0%.2eLib%.3eLtst%d=%.3eLtr/Lvl%.3fN:%d-:%dM:%drsa:%s\n",
//// fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[s_Ltstmin[i]],Lvar[s_Ltstmin[i]],Lvar0[s_Ltstmin[i]],Lib[s_Ltstmin[i]],i,Ltst[s_Ltstmin[i]],Lib[s_Ltstmin[i]]/Ltst[s_Ltstmin[i]],n1,_DN,m0,rsa);
// n0=NN[s_Ltstmin[i]/_nm];m0=mm[s_Ltstmin[i]%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"t:%s v:%s %d:%d(N:%d-%d) LD =%.3e Ltst%d=%.3e Lvar=%.3e Lvar0=%.3e Lib=%.3e",
// fnbody(fngiven,pr),fnbody(fnvalid,pr1),n0,m0,n1,n2,LD[s_Ltstmin[i]],i,Ltst[s_Ltstmin[i]],Lvar[s_Ltstmin[i]],Lvar0[s_Ltstmin[i]],Lib[s_Ltstmin[i]]);
// // fprintf(stderr,"**N:%d-%d\n",(int)(n0+_DN*m_LD),(int)(n2=n0+m0-1-_DN*m_LD));
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
}
for(i=0;i<smax_L0vmin;i++){
n0=NN[s_Ltstmin[i]/_nm];m0=mm[s_Ltstmin[i]%_nm];n1=n0;n2=n0+(m0-1)*_DN;//n1=n0+1;n2=n0+m0-2;
// if(BAGGING==2){
fprintf(stderr,"t:%s v:%s L0v%d=%.3e=%.3e-%.3eLtst(Lob)%.3eLib%.3eLtr%.3eN:%d-:%dM:%drsa:%sbst:%d:%d\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),
i,
L0v[s_L0vmin[i]],
L0[s_L0vmin[i]],
Lvar[s_L0vmin[i]],
Ltst[s_L0vmin[i]],
Lib[s_L0vmin[i]],
Ltr[s_L0vmin[i]],
n1,_DN,m0,rsa,t_boost,Boost);
// }
}
n0=NN[ij_LDmin/_nm];m0=mm[ij_LDmin%_nm];n1=n0;n2=n0+(m0-1)*_DN;//n1=n0+1;n2=n0+m0-2;
fprintf(stderr,"t:%s v:%s LDmin=%.3e Lvar=%.3e Lvar0=%.3e Lib=%.3e Ltst=%.3e N:%d-:%d M:%d\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[ij_LDmin],Lvar[ij_LDmin],Lvar0[ij_LDmin],Lib[ij_LDmin],Ltst[ij_LDmin],n1,_DN,m0);
// n0=NN[ij_LDmin/_nm];m0=mm[ij_LDmin%_nm];n1=n0;n2=n0+m0-1;//n1=n0+1;n2=n0+m0-2;
// fprintf(stderr,"t:%s v:%s %d:%d(N:%d-%d) LDmin=%.3e Ltst=%.3e Lvar=%.3e Lvar0=%.3e Lib=%.3e",
// fnbody(fngiven,pr),fnbody(fnvalid,pr1),n0,m0,n1,n2,LD[ij_LDmin],Ltst[ij_LDmin],Lvar[ij_LDmin],Lvar0[ij_LDmin],Lib[ij_LDmin]);
// fprintf(stderr,"**N:%d-%d\n",(int)(n0+_dm*m_LD),(int)(n2=n0+m0-1-_dm*m_LD));
// fprintf(stderr,"test=%d %d %d\n", 1/10,8/10,11/10);
// fprintf(stderr,"t:%s v:%s ij%d(i%d,j%d) N:%d:%d LDmin=%e Ltst=%e\n",
// fnbody(fngiven,pr),fnbody(fnvalid,pr1),NN[ij_LDmin/_nm],mm[ij_LDmin%_nm],LD[ij_LDmin],Ltst[ij_LDmin]);
fprintf(fp,"set style data linespoints\n");
fprintf(fp,"set logscale z\n");
fprintf(fp,"set title \"%s %s N:%d-:%d M:%d LDmin=%e Ltst=%e rsa:%s\"\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),n1,_DN,m0,LD[ij_LDmin],Ltst[ij_LDmin],rsa);
fprintf(fp,"set xlabel \"l1\";set ylabel \"ld\";set zlabel \"LD\"\n");
if(BAGGING==2){
fprintf(fp,"splot \"%s.dat\" using 1:2:4, \"%s.dat\" using 1:2:($4-5*$3), \"%s.dat\" using 1:2:($4+3*$3)\n",fnbody(fnloss,pr),fnbody(fnloss,pr),fnbody(fnloss,pr));
}
else{
// fprintf(fp,"splot \"%s.dat\" using 1:2:3\n",fnbody(fnloss,pr));
fprintf(fp,"splot \"%s.dat\" using 1:2:4\n",fnbody(fnloss,pr));
}
fprintf(fp,"pause -1 \"hit return for save!\"\n");
fprintf(fp,"set terminal tgif\n");
fprintf(fp,"set output \"./lhat.obj\"\n");
fprintf(fp,"replot\n");
//
n0=NN[ij_Ltstmin/_nm];m0=mm[ij_Ltstmin%_nm];n1=n0;n2=n0+(m0-1)*_DN;//n1=n0+1;n2=n0+m0-2;
fprintf(fp,"set terminal x11\n");
fprintf(fp,"set title \"%s %s Ltst=%e Ltstmin=%e Lib=%e N:%d-:%d M:%d\"\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),LD[ij_Ltstmin],Ltst[ij_Ltstmin],Lib[ij_Ltstmin],n1,_DN,m0);
// fprintf(fp,"splot \"%s.dat\" using 1:2:4\n",fnbody(fnloss,pr));
fprintf(fp,"set xlabel \"l1\";set ylabel \"ld\";set zlabel \"4Ltst,8Lib\"\n");
fprintf(fp,"splot \"%s.dat\" using 1:2:4, \"%s.dat\" using 1:2:8\n",fnbody(fnloss,pr),fnbody(fnloss,pr));
fprintf(fp,"pause -1 \"hit return for save !\"\n");
fprintf(fp,"set terminal tgif\n");
fprintf(fp,"set output \"./lhat.obj\"\n");
fprintf(fp,"replot\n");
//
n0=NN[ij_Lvarmin/_nm];m0=mm[ij_Lvarmin%_nm];n1=n0;n2=n0+(m0-1)*_DN;//n1=n0+1;n2=n0+m0-2;
fprintf(fp,"set terminal x11\n");
fprintf(stderr,"t:%s v:%s Lvarmin=%e Lvarval=%e N:%d-:%d M:%d\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),Lvar[ij_Lvarmin],Lvarval[ij_Lvarmin],n1,_DN,m0);
fprintf(fp,"set title \"Lvar %s %s Lvarmin=%e Lvarval=%e N:%d-:%d M:%d\"\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),Lvar[ij_Lvarmin],Lvarval[ij_Lvarmin],n1,_DN,m0);
fprintf(fp,"set xlabel \"l1\";set ylabel \"ld\";set zlabel \"5Lvar,7Lvar0\"\n");
// fprintf(fp,"splot \"%s.dat\" using 1:2:5\n",fnbody(fnloss,pr));
fprintf(fp,"splot \"%s.dat\" using 1:2:5, \"%s.dat\" using 1:2:7\n",fnbody(fnloss,pr),fnbody(fnloss,pr));
fprintf(fp,"pause -1 \"hit return for save !\"\n");
fprintf(fp,"set terminal tgif\n");
fprintf(fp,"set output \"./lhat.obj\"\n");
fprintf(fp,"replot\n");
//
n0=NN[ij_Lvarvalmin/_nm];m0=mm[ij_Lvarvalmin%_nm];n1=n0;n2=n0+(m0-1)*_DN;//n1=n0+1;n2=n0+m0-2;
fprintf(fp,"set terminal x11\n");
fprintf(stderr,"t:%s v:%s Lvar=%e Lvarvalmin=%e N:%d-:%d M:%d\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),Lvar[ij_Lvarvalmin],Lvarval[ij_Lvarvalmin],n1,_DN,m0);
fprintf(fp,"set title \"%s %s Lvar=%e Lvarvalmin=%e N:%d-:%d M:%d\"\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),Lvar[ij_Lvarvalmin],Lvarval[ij_Lvarvalmin],n1,_DN,m0);
fprintf(fp,"set xlabel \"l1\";set ylabel \"ld\";set zlabel \"6Lvarval\"\n");
fprintf(fp,"splot \"%s.dat\" using 1:2:6\n",fnbody(fnloss,pr));//Lvarval
fprintf(fp,"pause -1 \"hit return for save !\"\n");
fprintf(fp,"set terminal tgif\n");
fprintf(fp,"set output \"./lhat.obj\"\n");
fprintf(fp,"replot\n");
//
fprintf(fp,"set terminal x11\n");
fprintf(stderr,"t:%s v:%s Lvar=%e Lvarvalmin=%e N:%d-:%d M:%d\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),Lvar[ij_Lvarvalmin],Lvarval[ij_Lvarvalmin],n1,_DN,m0);
fprintf(fp,"set title \"Lvar-Lvar0 %s %s Lvar=%e Lvarvalmin=%e N:%d-:%d M:%d\"\n",
fnbody(fngiven,pr),fnbody(fnvalid,pr1),Lvar[ij_Lvarvalmin],Lvarval[ij_Lvarvalmin],n1,_DN,m0);
// fprintf(fp,"splot \"%s.dat\" using 1:2:7\n",fnbody(fnloss,pr));//Lvar-Lvar0
fprintf(fp,"set xlabel \"l1\";set ylabel \"ld\";set zlabel \"5Lvar-7Lvar0\"\n");
fprintf(fp,"splot [][][0.00001:1] \"%s.dat\" using 1:2:($5-$7)\n",fnbody(fnloss,pr));//Lvar-Lvar0
// fprintf(fp,"splot \"%s.dat\" using 1:2:($5/$7)\n",fnbody(fnloss,pr));//Lvar-Lvar0
// fprintf(fp,"splot [2:][2:][0.0001:1] \"%s.dat\" using 1:2:5, \"%s.dat\" using 1:2:7 \n",fnbody(fnloss,pr),fnbody(fnloss,pr));//Lvar-Lvar0
fprintf(fp,"pause -1 \"hit return for save !\"\n");
fprintf(fp,"set terminal tgif\n");
fprintf(fp,"set output \"./lhat.obj\"\n");
fprintf(fp,"replot\n");
//
fprintf(fp,"quit\n");
fclose(fp);
if(dsp==1 && DISP==1){
sprintf(cmd,"cd %s;xterm -geometry 40x5-0+0 -e gnuplot %s.plt",rdir,fnbody(fnplt,pr));
fprintf(stderr,"#Executing '%s'.\n",cmd);
sprintf(&cmd[strlen(cmd)],"&");
system(cmd);
}
}
return(0);
}
#endif
| {
"alphanum_fraction": 0.5462629127,
"avg_line_length": 40.0405515004,
"ext": "c",
"hexsha": "88beeab5a6bd5b50cb9a74539f0e68074e0d8fb2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z",
"max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_forks_repo_licenses": [
"CECILL-B"
],
"max_forks_repo_name": "Kurogi-Lab/CAN2",
"max_forks_repo_path": "0522/tsp/ens2ge.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CECILL-B"
],
"max_issues_repo_name": "Kurogi-Lab/CAN2",
"max_issues_repo_path": "0522/tsp/ens2ge.c",
"max_line_length": 203,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_stars_repo_licenses": [
"CECILL-B"
],
"max_stars_repo_name": "Kurogi-Lab/CAN2",
"max_stars_repo_path": "0522/tsp/ens2ge.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 21051,
"size": 49370
} |
//This involves multiplication of two vectors.
#include <stdio.h>
#include <gsl/gsl_vector.h>
void vector_mul(double* a, double *b, double *c, size_t size)
{
int i;
gsl_vector * a_vec = gsl_vector_alloc (size);
gsl_vector * b_vec = gsl_vector_alloc (size);
gsl_vector * c_vec = gsl_vector_alloc (size);
for (i = 0; i < size; i++)
{
gsl_vector_set (a_vec, i, a[i]);
gsl_vector_set (b_vec, i, b[i]);
}
gsl_vector_mul(a_vec,b_vec);
gsl_vector_memcpy(c_vec, a_vec);
for (i = 0; i < size; i++) /* OUT OF RANGE ERROR */
{
c[i] = gsl_vector_get (c_vec, i);
printf ("v_%d = %g\n", i, gsl_vector_get (c_vec, i));
}
gsl_vector_free (a_vec);
gsl_vector_free (b_vec);
gsl_vector_free (c_vec);
}
/*
//The main function has been provided solely for the sake of testing the function. It will be removed when the problem set is formally passed on.
int main (void)
{
double a[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
double b[5] = {0.1, 0.2, 0.3, 0.4, 0.5};
double *c;
vector_mul(a, b, c, 5);
return 0;
}*/
| {
"alphanum_fraction": 0.6332378223,
"avg_line_length": 25.5365853659,
"ext": "c",
"hexsha": "96cd57c10c58d765a04399ca70667391c73670cf",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RITUait/OpenModelica",
"max_forks_repo_path": "TestSample/Resources/Include/p4.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "RITUait/OpenModelica",
"max_issues_repo_path": "TestSample/Resources/Include/p4.c",
"max_line_length": 145,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RITUait/OpenModelica",
"max_stars_repo_path": "Resources/Include/p4.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-03T04:23:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-03T04:23:39.000Z",
"num_tokens": 356,
"size": 1047
} |
#ifndef SN3D_H
#define SN3D_H
#include <cassert>
#ifndef __CUDA_ARCH__
// host code
#define __artis_assert(e) if (!(e)) { if (output_file != NULL) {(void)fprintf(output_file, "[rank %d] %s:%d: failed assertion `%s' in function %s\n", globals::rank_global, __FILE__, __LINE__, #e, __PRETTY_FUNCTION__);} (void)fprintf(stderr, "[rank %d] %s:%d: failed assertion `%s' in function %s\n", globals::rank_global, __FILE__, __LINE__, #e, __PRETTY_FUNCTION__); abort();}
//
#define assert_always(e) __artis_assert(e)
#if defined TESTMODE && TESTMODE
#define assert_testmodeonly(e) __artis_assert(e)
#else
#define assert_testmodeonly(e) ((void)0)
#endif
#define printout(...) fprintf(output_file, __VA_ARGS__)
#ifdef _OPENMP
#ifndef __CUDACC__
#define safeadd(var, val) _Pragma("omp atomic update") \
var += val
#else
#define safeadd(var, val) var += val
#endif
#else
#define safeadd(var, val) var += val
#endif
#else
// device code
#define printout(...) printf (__VA_ARGS__)
#define assert_always(e) assert(e)
#if defined TESTMODE && TESTMODE
#define assert_testmodeonly(e) assert(e)
#else
#define assert_testmodeonly(e) ((void)0)
#endif
#define safeadd(var, val) atomicAdd(&var, val)
#endif
#define safeincrement(var) safeadd(var, 1)
#include "cuda.h"
#include <stdarg.h> /// MK: needed for printout()
#include <gsl/gsl_integration.h>
#define DEBUG_ON
// #define DO_TITER
// #define FORCE_LTE
#include "globals.h"
#include "types.h"
#include "vectors.h"
#if (DETAILED_BF_ESTIMATORS_ON && !NO_LUT_PHOTOION)
#error Must use NO_LUT_PHOTOION with DETAILED_BF_ESTIMATORS_ON
#endif
#if !defined MPI_ON
// #define MPI_ON //only needed for debugging MPI, the makefile will switch this on
#endif
#ifdef MPI_ON
#include "mpi.h"
#endif
//#define _OPENMP
#ifdef _OPENMP
#include "omp.h"
#endif
#define COOLING_UNDEFINED -99
#define RPKT_EVENTTYPE_BB 550
#define RPKT_EVENTTYPE_CONT 551
extern int tid;
extern __managed__ bool use_cellhist;
extern __managed__ bool neutral_flag;
#ifndef __CUDA_ARCH__
extern gsl_rng *rng; // pointer for random number generator
#else
extern __device__ void *rng;
#endif
extern gsl_integration_workspace *gslworkspace;
extern FILE *output_file;
extern __managed__ int myGpuId;
#ifdef _OPENMP
#pragma omp threadprivate(tid, myGpuId, use_cellhist, neutral_flag, rng, gslworkspace, output_file)
#endif
inline void gsl_error_handler_printout(const char *reason, const char *file, int line, int gsl_errno)
{
if (gsl_errno != 18) // roundoff error
{
printout("WARNING: gsl (%s:%d): %s (Error code %d)\n", file, line, reason, gsl_errno);
// abort();
}
}
inline FILE *fopen_required(const char *filename, const char *mode)
{
FILE *file = fopen(filename, mode);
if (file == NULL)
{
printout("ERROR: Could not open file '%s' for mode '%s'.\n", filename, mode);
abort();
}
return file;
}
inline int get_timestep(const double time)
{
assert_always(time >= globals::tmin);
assert_always(time < globals::tmax);
for (int nts = 0; nts < globals::ntstep; nts++)
{
const double tsend = (nts < (globals::ntstep - 1)) ? globals::time_step[nts + 1].start : globals::tmax;
if (time >= globals::time_step[nts].start && time < tsend)
{
return nts;
}
}
assert_always(false); // could not find matching timestep
return -1;
}
inline double get_arrive_time(const PKT *pkt_ptr)
/// We know that a packet escaped at "escape_time". However, we have
/// to allow for travel time. Use the formula in Leon's paper. The extra
/// distance to be travelled beyond the reference surface is ds = r_ref (1 - mu).
{
return pkt_ptr->escape_time - (dot(pkt_ptr->pos, pkt_ptr->dir) / globals::CLIGHT_PROP);
}
inline double get_arrive_time_cmf(const PKT *pkt_ptr)
{
return pkt_ptr->escape_time * sqrt(1. - (globals::vmax * globals::vmax / CLIGHTSQUARED));
}
__host__ __device__
inline int get_max_threads(void)
{
#ifdef __CUDA_ARCH__
return MCUDATHREADS;
#elif defined _OPENMP
return omp_get_max_threads();
#else
return 1;
#endif
}
__host__ __device__
inline int get_num_threads(void)
{
#ifdef __CUDA_ARCH__
return blockDim.x * blockDim.y * blockDim.z;
#elif defined _OPENMP
return omp_get_num_threads();
#else
return 1;
#endif
}
__host__ __device__
inline int get_thread_num(void)
{
#ifdef __CUDA_ARCH__
return threadIdx.x + blockDim.x * blockIdx.x;
#elif defined _OPENMP
return omp_get_thread_num();
#else
return 0;
#endif
}
#endif // SN3D_H
| {
"alphanum_fraction": 0.70720423,
"avg_line_length": 22.5820895522,
"ext": "h",
"hexsha": "0eb47f63b2dff8dbcc78aa75b7ce129b010f1a6d",
"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": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "artis-mcrt/artis",
"max_forks_repo_path": "sn3d.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "artis-mcrt/artis",
"max_issues_repo_path": "sn3d.h",
"max_line_length": 379,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "artis-mcrt/artis",
"max_stars_repo_path": "sn3d.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z",
"num_tokens": 1304,
"size": 4539
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
void
cblas_ssyr (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,
const int N, const float alpha, const float *X, const int incX,
float *A, const int lda)
{
#define BASE float
#include "source_syr.h"
#undef BASE
}
| {
"alphanum_fraction": 0.7185430464,
"avg_line_length": 21.5714285714,
"ext": "c",
"hexsha": "c837bae79726c2d951ecc84be7e36ad67b0ea562",
"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/ssyr.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/ssyr.c",
"max_line_length": 69,
"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/ssyr.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": 92,
"size": 302
} |
#ifndef MSNHINFERENCECFG_H
#define MSNHINFERENCECFG_H
#include <stdint.h>
#include <float.h>
#include <string>
#include <vector>
#include <chrono>
#include "Msnhnet/utils/MsnhException.h"
#include "Msnhnet/config/MsnhnetMacro.h"
#include <math.h>
#include <string.h>
#ifdef USE_OMP
#include <omp.h>
#endif
#ifdef USE_NEON
#include <arm_neon.h>
#endif
#ifdef USE_OPEN_BLAS
#include <cblas.h>
#endif
#ifdef USE_NNPACK
#include <nnpack.h>
#endif
#ifndef OMP_THREAD
#define OMP_THREAD omp_get_max_threads()
#endif
enum ActivationType
{
LOGISTIC,
RELU,
RELU6,
RELIE,
RAMP,
TANH,
PLSE,
LEAKY,
ELU,
LOGGY,
STAIR,
HARDTAN,
LHTAN,
SOFT_PLUS,
SELU,
SWISH,
MISH,
NORM_CHAN,
NORM_CHAN_SOFTMAX,
NORM_CHAN_SOFTMAX_MAXVAL,
NONE
};
enum LayerType
{
CONVOLUTIONAL,
DECONVOLUTIONAL,
CONNECTED,
MAXPOOL,
LOCAL_AVGPOOL,
GLOBAL_AVGPOOL,
SOFTMAX,
CROP,
ROUTE,
NORMALIZATION,
AVGPOOL,
ACTIVE,
BATCHNORM,
NETWORK,
YOLOV3,
YOLOV3_OUT,
GAUSSIAN_YOLO,
UPSAMPLE,
L2NORM,
EMPTY,
BLANK,
CONFIG,
RES_BLOCK,
RES_2_BLOCK,
CONCAT_BLOCK,
ADD_BLOCK,
PADDING
};
enum WeightsType
{
NO_WEIGHTS,
PER_FEATURE,
PER_CHANNEL
};
enum WeightsNorm
{
NO_NORM,
RELU_NORM,
SOFTMAX_NORM
};
#endif
| {
"alphanum_fraction": 0.6058147397,
"avg_line_length": 14.0857142857,
"ext": "h",
"hexsha": "698c999df146690f57977992e0bfadddbe37edb7",
"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": "95522102b57e3cee679875ddf7766c032fde5655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cloud-mxd/Msnhnet",
"max_forks_repo_path": "include/Msnhnet/config/MsnhnetCfg.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "95522102b57e3cee679875ddf7766c032fde5655",
"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": "cloud-mxd/Msnhnet",
"max_issues_repo_path": "include/Msnhnet/config/MsnhnetCfg.h",
"max_line_length": 41,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "95522102b57e3cee679875ddf7766c032fde5655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cloud-mxd/Msnhnet",
"max_stars_repo_path": "include/Msnhnet/config/MsnhnetCfg.h",
"max_stars_repo_stars_event_max_datetime": "2020-08-10T03:31:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-10T03:31:00.000Z",
"num_tokens": 434,
"size": 1479
} |
/* linalg/test_cod.c
*
* Copyright (C) 2017 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
static int test_COD_decomp_eps(const gsl_matrix * m, const double eps, const char *desc);
static int test_COD_decomp(gsl_rng *r);
static int test_COD_lssolve_eps(const gsl_matrix * m, const double * actual, const double eps, const char *desc);
static int test_COD_lssolve(void);
static int test_COD_lssolve2_eps(const double lambda, const gsl_matrix * A, const gsl_vector * b, const double eps, const char *desc);
static int test_COD_lssolve2(gsl_rng * r);
/* create a matrix of a given rank */
static int
create_rank_matrix(const size_t rank, gsl_matrix * m, gsl_rng * r)
{
const size_t M = m->size1;
const size_t N = m->size2;
size_t i;
gsl_vector *u = gsl_vector_alloc(M);
gsl_vector *v = gsl_vector_alloc(N);
gsl_matrix_set_zero(m);
/* add several rank-1 matrices together */
for (i = 0; i < rank; ++i)
{
create_random_vector(u, r);
create_random_vector(v, r);
gsl_blas_dger(1.0, u, v, m);
}
gsl_vector_free(u);
gsl_vector_free(v);
return GSL_SUCCESS;
}
static int
test_COD_decomp_eps(const gsl_matrix * m, const double eps, const char *desc)
{
int s = 0;
size_t i, j, M = m->size1, N = m->size2;
size_t rank;
gsl_matrix * QRZT = gsl_matrix_alloc(M, N);
gsl_matrix * Q = gsl_matrix_alloc(M, M);
gsl_matrix * R = gsl_matrix_alloc(M, N);
gsl_matrix * QR = gsl_matrix_alloc(M, N);
gsl_matrix * Z = gsl_matrix_alloc(N, N);
gsl_vector * tau_Q = gsl_vector_alloc(GSL_MIN(M, N));
gsl_vector * tau_Z = gsl_vector_alloc(GSL_MIN(M, N));
gsl_vector * work = gsl_vector_alloc(N);
gsl_matrix * lhs = gsl_matrix_alloc(M, N);
gsl_matrix * rhs = gsl_matrix_alloc(M, N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_matrix_memcpy(QRZT, m);
s += gsl_linalg_COD_decomp(QRZT, tau_Q, tau_Z, perm, &rank, work);
s += gsl_linalg_COD_unpack(QRZT, tau_Q, tau_Z, rank, Q, R, Z);
/* compute lhs = m P */
gsl_matrix_memcpy(lhs, m);
gsl_permute_matrix(perm, lhs);
/* compute rhs = Q R Z^T */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, Q, R, 0.0, QR);
gsl_blas_dgemm (CblasNoTrans, CblasTrans, 1.0, QR, Z, 0.0, rhs);
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
double aij = gsl_matrix_get(rhs, i, j);
double bij = gsl_matrix_get(lhs, i, j);
gsl_test_rel(aij, bij, eps, "%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i, j, aij, bij);
}
}
gsl_permutation_free (perm);
gsl_vector_free(work);
gsl_vector_free(tau_Q);
gsl_vector_free(tau_Z);
gsl_matrix_free(QRZT);
gsl_matrix_free(lhs);
gsl_matrix_free(rhs);
gsl_matrix_free(QR);
gsl_matrix_free(Q);
gsl_matrix_free(R);
gsl_matrix_free(Z);
return s;
}
static int
test_COD_decomp(gsl_rng *r)
{
int s = 0;
size_t N;
gsl_matrix *m;
/* test COD decomposition on Hilbert matrices */
for (N = 1; N <= 12; ++N)
{
m = gsl_matrix_alloc(N, N);
create_hilbert_matrix2(m);
test_COD_decomp_eps(m, 256.0 * N * GSL_DBL_EPSILON, "COD_decomp hilbert");
gsl_matrix_free(m);
}
/* build some matrices of a given rank and test */
m = gsl_matrix_alloc(100, 50);
create_rank_matrix(26, m, r);
test_COD_decomp_eps(m, 1.0e2 * GSL_DBL_EPSILON, "COD_decomp rank 26");
gsl_matrix_free(m);
m = gsl_matrix_alloc(550, 200);
create_rank_matrix(176, m, r);
test_COD_decomp_eps(m, 1.0e3 * GSL_DBL_EPSILON, "COD_decomp rank 176");
gsl_matrix_free(m);
test_COD_decomp_eps(m35, 1.0e1 * GSL_DBL_EPSILON, "COD_decomp m(3,5)");
test_COD_decomp_eps(m53, 1.0e1 * GSL_DBL_EPSILON, "COD_decomp m(5,3)");
test_COD_decomp_eps(s35, 1.0e1 * GSL_DBL_EPSILON, "COD_decomp s(3,5)");
test_COD_decomp_eps(s53, 1.0e1 * GSL_DBL_EPSILON, "COD_decomp s(5,3)");
test_COD_decomp_eps(vander2, 1.0e1 * GSL_DBL_EPSILON, "COD_decomp vander(2)");
test_COD_decomp_eps(vander3, 1.0e1 * GSL_DBL_EPSILON, "COD_decomp vander(3)");
test_COD_decomp_eps(vander4, 1.0e1 * GSL_DBL_EPSILON, "COD_decomp vander(4)");
test_COD_decomp_eps(vander12, 1e-3, "COD_decomp vander(12)"); /* FIXME: large tolerance needed */
return s;
}
static int
test_COD_lssolve_eps(const gsl_matrix * m, const double * actual, const double eps, const char *desc)
{
int s = 0;
size_t i, M = m->size1, N = m->size2;
gsl_vector * lhs = gsl_vector_alloc(M);
gsl_vector * rhs = gsl_vector_alloc(M);
gsl_matrix * QRZT = gsl_matrix_alloc(M, N);
gsl_vector * tau_Q = gsl_vector_alloc(GSL_MIN(M, N));
gsl_vector * tau_Z = gsl_vector_alloc(GSL_MIN(M, N));
gsl_vector * work = gsl_vector_alloc(N);
gsl_vector * x = gsl_vector_alloc(N);
gsl_vector * r = gsl_vector_alloc(M);
gsl_vector * res = gsl_vector_alloc(M);
gsl_permutation * perm = gsl_permutation_alloc(N);
size_t rank;
gsl_matrix_memcpy(QRZT, m);
for (i = 0; i < M; i++)
gsl_vector_set(rhs, i, i + 1.0);
s += gsl_linalg_COD_decomp(QRZT, tau_Q, tau_Z, perm, &rank, work);
s += gsl_linalg_COD_lssolve(QRZT, tau_Q, tau_Z, perm, rank, rhs, x, res);
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
gsl_test_rel(xi, actual[i], eps,
"%s (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, xi, actual[i]);
}
/* compute residual r = b - m x */
if (M == N)
{
gsl_vector_set_zero(r);
}
else
{
gsl_vector_memcpy(r, rhs);
gsl_blas_dgemv(CblasNoTrans, -1.0, m, x, 1.0, r);
}
for (i = 0; i < N; i++)
{
double r1 = gsl_vector_get(res, i);
double r2 = gsl_vector_get(r, i);
if (fabs(r2) < 1.0e3 * GSL_DBL_EPSILON)
{
gsl_test_abs(r1, r2, 10.0 * eps,
"%s res (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, r1, r2);
}
else
{
gsl_test_rel(r1, r2, eps,
"%s res (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, r1, r2);
}
}
gsl_vector_free(r);
gsl_vector_free(res);
gsl_vector_free(x);
gsl_vector_free(tau_Q);
gsl_vector_free(tau_Z);
gsl_matrix_free(QRZT);
gsl_vector_free(rhs);
gsl_vector_free(lhs);
gsl_vector_free(work);
gsl_permutation_free(perm);
return s;
}
static int
test_COD_lssolve(void)
{
int s = 0;
test_COD_lssolve_eps(m53, m53_lssolution, 1.0e4 * GSL_DBL_EPSILON, "COD_lssolve m(5,3)");
test_COD_lssolve_eps(hilb2, hilb2_solution, 1.0e2 * GSL_DBL_EPSILON, "COD_lssolve hilbert(2)");
test_COD_lssolve_eps(hilb3, hilb3_solution, 1.0e2 * GSL_DBL_EPSILON, "COD_lssolve hilbert(3)");
test_COD_lssolve_eps(hilb4, hilb4_solution, 1.0e4 * GSL_DBL_EPSILON, "COD_lssolve hilbert(4)");
test_COD_lssolve_eps(vander2, vander2_solution, 1.0e1 * GSL_DBL_EPSILON, "COD_lssolve vander(2)");
test_COD_lssolve_eps(vander3, vander3_solution, 1.0e1 * GSL_DBL_EPSILON, "COD_lssolve vander(3)");
test_COD_lssolve_eps(vander4, vander4_solution, 1.0e2 * GSL_DBL_EPSILON, "COD_lssolve vander(4)");
/* rank-1 least squares problem from the 'lin2' test dataset for multifit_nlinear */
{
const size_t M = 20;
const size_t N = 5;
/* unique minimum norm solution from "Factorize" matlab package */
const double x_ls[] = { 1.818181818181817e-02, 3.636363636363636e-02, 5.454545454545454e-02,
7.272727272727272e-02, 9.090909090909088e-02 };
gsl_matrix *m = gsl_matrix_alloc(M, N);
size_t i, j;
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
gsl_matrix_set(m, i, j, (i + 1.0) * (j + 1.0));
}
}
test_COD_lssolve_eps(m, x_ls, 1.0e2 * GSL_DBL_EPSILON, "COD_lssolve lin2");
gsl_matrix_free(m);
}
return s;
}
/* solve: min ||b - A x||^2 + lambda^2 ||x||^2 */
static int
test_COD_lssolve2_eps(const double lambda, const gsl_matrix * A, const gsl_vector * b, const double eps, const char *desc)
{
int s = 0;
size_t i, M = A->size1, N = A->size2;
gsl_vector * lhs = gsl_vector_alloc(M);
gsl_matrix * QRZT = gsl_matrix_alloc(M, N);
gsl_vector * tau_Q = gsl_vector_alloc(GSL_MIN(M, N));
gsl_vector * tau_Z = gsl_vector_alloc(GSL_MIN(M, N));
gsl_vector * work = gsl_vector_alloc(N);
gsl_vector * x = gsl_vector_alloc(N);
gsl_vector * x_aug = gsl_vector_alloc(N);
gsl_vector * r = gsl_vector_alloc(M);
gsl_vector * res = gsl_vector_alloc(M);
gsl_permutation * perm = gsl_permutation_alloc(N);
size_t rank;
/* form full rank augmented system B = [ A ; lambda*I_N ], f = [ rhs ; 0 ] and solve with QRPT */
{
gsl_vector_view v;
gsl_matrix_view m;
gsl_permutation *p = gsl_permutation_alloc(N);
gsl_matrix * B = gsl_matrix_calloc(M + N, N);
gsl_vector * f = gsl_vector_calloc(M + N);
gsl_vector * tau = gsl_vector_alloc(N);
gsl_vector * residual = gsl_vector_alloc(M + N);
int signum;
m = gsl_matrix_submatrix(B, 0, 0, M, N);
gsl_matrix_memcpy(&m.matrix, A);
m = gsl_matrix_submatrix(B, M, 0, N, N);
v = gsl_matrix_diagonal(&m.matrix);
gsl_vector_set_all(&v.vector, lambda);
v = gsl_vector_subvector(f, 0, M);
gsl_vector_memcpy(&v.vector, b);
/* solve: [ A ; lambda*I ] x_aug = [ b ; 0 ] */
gsl_linalg_QRPT_decomp(B, tau, p, &signum, work);
gsl_linalg_QRPT_lssolve(B, tau, p, f, x_aug, residual);
gsl_permutation_free(p);
gsl_matrix_free(B);
gsl_vector_free(f);
gsl_vector_free(tau);
gsl_vector_free(residual);
}
gsl_matrix_memcpy(QRZT, A);
s += gsl_linalg_COD_decomp(QRZT, tau_Q, tau_Z, perm, &rank, work);
{
gsl_matrix *S = gsl_matrix_alloc(rank, rank);
gsl_vector *workr = gsl_vector_alloc(rank);
s += gsl_linalg_COD_lssolve2(lambda, QRZT, tau_Q, tau_Z, perm, rank, b, x, res, S, workr);
gsl_matrix_free(S);
gsl_vector_free(workr);
}
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(x_aug, i);
gsl_test_rel(xi, yi, eps,
"%s (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, xi, yi);
}
/* compute residual r = b - A x */
if (M == N)
{
gsl_vector_set_zero(r);
}
else
{
gsl_vector_memcpy(r, b);
gsl_blas_dgemv(CblasNoTrans, -1.0, A, x, 1.0, r);
}
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(res, i);
double yi = gsl_vector_get(r, i);
gsl_test_rel(xi, yi, sqrt(eps),
"%s res (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, xi, yi);
}
gsl_vector_free(r);
gsl_vector_free(res);
gsl_vector_free(x);
gsl_vector_free(x_aug);
gsl_vector_free(tau_Q);
gsl_vector_free(tau_Z);
gsl_matrix_free(QRZT);
gsl_vector_free(lhs);
gsl_vector_free(work);
gsl_permutation_free(perm);
return s;
}
static int
test_COD_lssolve2(gsl_rng * r)
{
int s = 0;
gsl_matrix *m;
gsl_vector *b;
size_t M, N;
const double lambda = 2.3;
M = 100;
N = 50;
m = gsl_matrix_alloc(M, N);
b = gsl_vector_alloc(M);
create_rank_matrix(26, m, r);
create_random_vector(b, r);
test_COD_lssolve2_eps(lambda, m, b, 1.0e4 * M * GSL_DBL_EPSILON, "COD_lssolve2 rank 26");
gsl_matrix_free(m);
gsl_vector_free(b);
M = 500;
N = 450;
m = gsl_matrix_alloc(M, N);
b = gsl_vector_alloc(M);
create_rank_matrix(278, m, r);
create_random_vector(b, r);
test_COD_lssolve2_eps(lambda, m, b, 1.0e6 * M * GSL_DBL_EPSILON, "COD_lssolve2 rank 278");
gsl_matrix_free(m);
gsl_vector_free(b);
return s;
}
| {
"alphanum_fraction": 0.6453872483,
"avg_line_length": 29.2843822844,
"ext": "c",
"hexsha": "d69883bec4d18969454535477158ed149abb8f2a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_cod.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_cod.c",
"max_line_length": 134,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_cod.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": 4126,
"size": 12563
} |
#pragma once
#include <string>
#include <gsl/gsl_complex.h>
#include "Expression.h"
struct NumericalExpression: public Expression {
NumericalExpression(Scanner::Type kind);
expression derivative(const std::string& var) override;
expression integrate(const std::string& var) override;
};
class NumExpression: public NumericalExpression {
double real, imag;
NumExpression(double real, double imag);
NumExpression(const std::string&);
public:
static expression construct(double real, double imag = 0);
static expression construct(const gsl_complex& z);
static expression construct(const std::string&);
bool isNumber() const override { return true; }
gsl_complex complex(const Variables& vars = emptyVars) const override;
EXPRESSION_OVERRIDES
};
class HexExpression: public NumericalExpression {
unsigned long long num;
HexExpression(unsigned long long num);
HexExpression(const std::string&);
public:
static expression construct(unsigned long long num);
static expression construct(const std::string&);
bool isNumber() const override { return true; }
EXPRESSION_OVERRIDES
};
class BinExpression: public NumericalExpression {
unsigned long long num;
BinExpression(unsigned long long num);
BinExpression(const std::string&);
public:
static expression construct(unsigned long long num);
static expression construct(const std::string&);
bool isNumber() const override { return true; }
EXPRESSION_OVERRIDES
};
| {
"alphanum_fraction": 0.7004377736,
"avg_line_length": 23.8656716418,
"ext": "h",
"hexsha": "ab0123d8363ec77977bab3222668b230cb862d0e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoniojkim/CalcPlusPlus",
"max_forks_repo_path": "MathEngine/Expressions/NumericalExpression.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "antoniojkim/CalcPlusPlus",
"max_issues_repo_path": "MathEngine/Expressions/NumericalExpression.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoniojkim/CalcPlusPlus",
"max_stars_repo_path": "MathEngine/Expressions/NumericalExpression.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 310,
"size": 1599
} |
#include "AsynchronousUpdate.h"
#include <stdio.h>
#include <stdlib.h>
#include "constants.h"
#include <gsl/gsl_rng.h>
#include <omp.h>
int getBool(gsl_rng* r)
{
return gsl_rng_uniform_int(r,2);
}
void singleStateUpdate(int n, int* state, int** topology, int seed, int* fixed_nodes)
{
//Perform Asynchronous Updates
gsl_rng* asyncer = gsl_rng_alloc(gsl_rng_ranlxs2);
gsl_rng_set(asyncer,seed);
for (int i = 0; i < ITER_ASYNCHRONOUS; ++i)
{
int node_to_update = gsl_rng_uniform_int(asyncer,n);
if(fixed_nodes[node_to_update] == NORMAL_FLAG)
{
int val_temp = 0;
for (int j = 0; j < n; ++j)
{
val_temp+= state[j]*topology[node_to_update][j];
}
if(val_temp > 0)
{
state[node_to_update] = 1;
}
else if(val_temp<0)
{
state[node_to_update] = LOWER_EXPRESSION;
}
}
}
//Free the rng
gsl_rng_free(asyncer);
}
void getFinalState(int n, int state[n], gsl_rng* rangen, int** topology, int* fixed_nodes, int i)
{
#pragma omp parallel for
for (int j = 0; j < n; ++j)
{
if(fixed_nodes[j]==NORMAL_FLAG)
{
#pragma omp critical(rand)
{
state[j] = getBool(rangen);
}
if(state[j]==0)
{
state[j] = LOWER_EXPRESSION;
}
}
else{
state[j] = fixed_nodes[j];
}
}
singleStateUpdate(n,state,topology,i+1,fixed_nodes);
}
asynclist* updateAsyncList(int n, int** topology, int* fixed_nodes, int height, int seed_init)
{
if(height)
{
if(height%2)
{
gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2);
gsl_rng_set(rangen,seed_init);
asynclist* to_merge[2];
int seed[2] = {gsl_rng_get(rangen),gsl_rng_get(rangen)};
int i;
#pragma omp parallel for shared(n,topology,fixed_nodes,seed,height) private(i)
for (i = 0; i < 2; ++i)
{
to_merge[i] = updateAsyncList(n,topology,fixed_nodes,height-1,seed[i]);
}
return merge_asynclist(to_merge[0],to_merge[1],n);
}
else
{
gsl_rng* rangen = gsl_rng_alloc(gsl_rng_taus2);
gsl_rng_set(rangen,seed_init);
asynclist* to_merge[2];
int seed[2] = {gsl_rng_get(rangen),gsl_rng_get(rangen)};
int i;
#pragma omp parallel for shared(n,topology,fixed_nodes,seed,height) private(i)
for (i = 0; i < 2; ++i)
{
to_merge[i] = updateAsyncList(n,topology,fixed_nodes,height-1,seed[i]);
}
return merge_asynclist(to_merge[0],to_merge[1],n);
}
}
else{
asynclist* list = (asynclist*)malloc(sizeof(asynclist));
init_asynclist(list);
int state[n];
gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2);
gsl_rng_set(rangen,seed_init);
for (int i = 0; i < n; ++i)
{
if(fixed_nodes[i] == NORMAL_FLAG)
{
state[i] = gsl_rng_uniform_int(rangen,2);
if(state[i]==0)
{
state[i] = LOWER_EXPRESSION;
}
}
else
{
state[i] = fixed_nodes[i];
}
}
singleStateUpdate(n,state,topology,gsl_rng_get(rangen),fixed_nodes);
list->n_elements = 1;
asynclistnode* node = (asynclistnode*)malloc(sizeof(asynclistnode));
if(!node)
{
exit(10);
}
node->n_occurances = 1;
node->state = (int*)malloc(n*sizeof(int));
if(!(node->state))
{
exit(11);
}
for (int i = 0; i < n; ++i)
{
node->state[i] = state[i];
}
node->next = NULL;
node->prev = NULL;
list->next = node;
return list;
}
}
void updateAsyncTree(int n, int** topology, int* fixed_nodes, base* stable)
{
int iter = (1<<N_SAMPLES);
gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2);
gsl_rng_set(rangen,0);
#pragma omp parallel for
for (int i = 0; i < iter; ++i)
{
/*
gsl_rng* rangen = gsl_rng_alloc(gsl_rng_ranlxs2);
gsl_rng_set(rangen,i);
*/
//int* state=(int*)malloc(n*sizeof(int));
int state[n];
getFinalState(n,state,rangen,topology,fixed_nodes,i);
#pragma omp critical(addToTree)
{
add_node(stable,n,state);
}
//free(state);
}
gsl_rng_free(rangen);
} | {
"alphanum_fraction": 0.6453564851,
"avg_line_length": 21.4745762712,
"ext": "c",
"hexsha": "c405a5e7163a85af45b972d87785b1edf97ce6ce",
"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": "40d62e8e233e958f8ac5455197963dd20c4b645c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SamarthH/CBool",
"max_forks_repo_path": "src/AsynchronousUpdate.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "40d62e8e233e958f8ac5455197963dd20c4b645c",
"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": "SamarthH/CBool",
"max_issues_repo_path": "src/AsynchronousUpdate.c",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "40d62e8e233e958f8ac5455197963dd20c4b645c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SamarthH/CBool",
"max_stars_repo_path": "src/AsynchronousUpdate.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1296,
"size": 3801
} |
/* matrix/gsl_matrix_uchar.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_UCHAR_H__
#define __GSL_MATRIX_UCHAR_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_uchar.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
unsigned char * data;
gsl_block_uchar * block;
int owner;
} gsl_matrix_uchar;
typedef struct
{
gsl_matrix_uchar matrix;
} _gsl_matrix_uchar_view;
typedef _gsl_matrix_uchar_view gsl_matrix_uchar_view;
typedef struct
{
gsl_matrix_uchar matrix;
} _gsl_matrix_uchar_const_view;
typedef const _gsl_matrix_uchar_const_view gsl_matrix_uchar_const_view;
/* Allocation */
gsl_matrix_uchar *
gsl_matrix_uchar_alloc (const size_t n1, const size_t n2);
gsl_matrix_uchar *
gsl_matrix_uchar_calloc (const size_t n1, const size_t n2);
gsl_matrix_uchar *
gsl_matrix_uchar_alloc_from_block (gsl_block_uchar * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
gsl_matrix_uchar *
gsl_matrix_uchar_alloc_from_matrix (gsl_matrix_uchar * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
gsl_vector_uchar *
gsl_vector_uchar_alloc_row_from_matrix (gsl_matrix_uchar * m,
const size_t i);
gsl_vector_uchar *
gsl_vector_uchar_alloc_col_from_matrix (gsl_matrix_uchar * m,
const size_t j);
void gsl_matrix_uchar_free (gsl_matrix_uchar * m);
/* Views */
_gsl_matrix_uchar_view
gsl_matrix_uchar_submatrix (gsl_matrix_uchar * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_uchar_view
gsl_matrix_uchar_row (gsl_matrix_uchar * m, const size_t i);
_gsl_vector_uchar_view
gsl_matrix_uchar_column (gsl_matrix_uchar * m, const size_t j);
_gsl_vector_uchar_view
gsl_matrix_uchar_diagonal (gsl_matrix_uchar * m);
_gsl_vector_uchar_view
gsl_matrix_uchar_subdiagonal (gsl_matrix_uchar * m, const size_t k);
_gsl_vector_uchar_view
gsl_matrix_uchar_superdiagonal (gsl_matrix_uchar * m, const size_t k);
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_array (unsigned char * base,
const size_t n1,
const size_t n2);
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_array_with_tda (unsigned char * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_vector (gsl_vector_uchar * v,
const size_t n1,
const size_t n2);
_gsl_matrix_uchar_view
gsl_matrix_uchar_view_vector_with_tda (gsl_vector_uchar * v,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_submatrix (const gsl_matrix_uchar * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_row (const gsl_matrix_uchar * m,
const size_t i);
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_column (const gsl_matrix_uchar * m,
const size_t j);
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_diagonal (const gsl_matrix_uchar * m);
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_subdiagonal (const gsl_matrix_uchar * m,
const size_t k);
_gsl_vector_uchar_const_view
gsl_matrix_uchar_const_superdiagonal (const gsl_matrix_uchar * m,
const size_t k);
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_array (const unsigned char * base,
const size_t n1,
const size_t n2);
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_array_with_tda (const unsigned char * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_vector (const gsl_vector_uchar * v,
const size_t n1,
const size_t n2);
_gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_vector_with_tda (const gsl_vector_uchar * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
unsigned char gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j);
void gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x);
unsigned char * gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j);
const unsigned char * gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j);
void gsl_matrix_uchar_set_zero (gsl_matrix_uchar * m);
void gsl_matrix_uchar_set_identity (gsl_matrix_uchar * m);
void gsl_matrix_uchar_set_all (gsl_matrix_uchar * m, unsigned char x);
int gsl_matrix_uchar_fread (FILE * stream, gsl_matrix_uchar * m) ;
int gsl_matrix_uchar_fwrite (FILE * stream, const gsl_matrix_uchar * m) ;
int gsl_matrix_uchar_fscanf (FILE * stream, gsl_matrix_uchar * m);
int gsl_matrix_uchar_fprintf (FILE * stream, const gsl_matrix_uchar * m, const char * format);
int gsl_matrix_uchar_memcpy(gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);
int gsl_matrix_uchar_swap(gsl_matrix_uchar * m1, gsl_matrix_uchar * m2);
int gsl_matrix_uchar_swap_rows(gsl_matrix_uchar * m, const size_t i, const size_t j);
int gsl_matrix_uchar_swap_columns(gsl_matrix_uchar * m, const size_t i, const size_t j);
int gsl_matrix_uchar_swap_rowcol(gsl_matrix_uchar * m, const size_t i, const size_t j);
int gsl_matrix_uchar_transpose (gsl_matrix_uchar * m);
int gsl_matrix_uchar_transpose_memcpy (gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);
unsigned char gsl_matrix_uchar_max (const gsl_matrix_uchar * m);
unsigned char gsl_matrix_uchar_min (const gsl_matrix_uchar * m);
void gsl_matrix_uchar_minmax (const gsl_matrix_uchar * m, unsigned char * min_out, unsigned char * max_out);
void gsl_matrix_uchar_max_index (const gsl_matrix_uchar * m, size_t * imax, size_t *jmax);
void gsl_matrix_uchar_min_index (const gsl_matrix_uchar * m, size_t * imin, size_t *jmin);
void gsl_matrix_uchar_minmax_index (const gsl_matrix_uchar * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
int gsl_matrix_uchar_isnull (const gsl_matrix_uchar * m);
int gsl_matrix_uchar_ispos (const gsl_matrix_uchar * m);
int gsl_matrix_uchar_isneg (const gsl_matrix_uchar * m);
int gsl_matrix_uchar_add (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
int gsl_matrix_uchar_sub (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
int gsl_matrix_uchar_mul_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
int gsl_matrix_uchar_div_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
int gsl_matrix_uchar_scale (gsl_matrix_uchar * a, const double x);
int gsl_matrix_uchar_add_constant (gsl_matrix_uchar * a, const double x);
int gsl_matrix_uchar_add_diagonal (gsl_matrix_uchar * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
int gsl_matrix_uchar_get_row(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t i);
int gsl_matrix_uchar_get_col(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t j);
int gsl_matrix_uchar_set_row(gsl_matrix_uchar * m, const size_t i, const gsl_vector_uchar * v);
int gsl_matrix_uchar_set_col(gsl_matrix_uchar * m, const size_t j, const gsl_vector_uchar * v);
/* inline functions if you are using GCC */
#ifdef HAVE_INLINE
extern inline
unsigned char
gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
#endif
return m->data[i * m->tda + j] ;
}
extern inline
void
gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
#endif
m->data[i * m->tda + j] = x ;
}
extern inline
unsigned char *
gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (unsigned char *) (m->data + (i * m->tda + j)) ;
}
extern inline
const unsigned char *
gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (const unsigned char *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_UCHAR_H__ */
| {
"alphanum_fraction": 0.6667855233,
"avg_line_length": 35.1661442006,
"ext": "h",
"hexsha": "c85c01223be8487ee57067cf4ee4ee05bb1c4201",
"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/matrix/gsl_matrix_uchar.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/matrix/gsl_matrix_uchar.h",
"max_line_length": 124,
"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/matrix/gsl_matrix_uchar.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 2838,
"size": 11218
} |
/* spmatrix/gsl_spmatrix_float.h
*
* Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017, 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_SPMATRIX_COMPLEX_FLOAT_H__
#define __GSL_SPMATRIX_COMPLEX_FLOAT_H__
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_bst.h>
#include <gsl/gsl_vector_complex_float.h>
#include <gsl/gsl_matrix_complex_float.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/*
* COO format:
*
* If data[n] = A_{ij}, then:
* i = A->i[n]
* j = A->p[n]
*
* Compressed column format (CSC):
*
* If data[n] = A_{ij}, then:
* i = A->i[n]
* A->p[j] <= n < A->p[j+1]
* so that column j is stored in
* [ data[p[j]], data[p[j] + 1], ..., data[p[j+1] - 1] ]
*
* Compressed row format (CSR):
*
* If data[n] = A_{ij}, then:
* j = A->i[n]
* A->p[i] <= n < A->p[i+1]
* so that row i is stored in
* [ data[p[i]], data[p[i] + 1], ..., data[p[i+1] - 1] ]
*/
typedef struct
{
size_t size1; /* number of rows */
size_t size2; /* number of columns */
/* i (size nzmax) contains:
*
* COO/CSC: row indices
* CSR: column indices
*/
int *i;
float *data; /* matrix elements of size nzmax */
/*
* COO: p[n] = column number of element data[n]
* CSC: p[j] = index in data of first non-zero element in column j
* CSR: p[i] = index in data of first non-zero element in row i
*/
int *p;
size_t nzmax; /* maximum number of matrix elements */
size_t nz; /* number of non-zero values in matrix */
gsl_bst_workspace *tree; /* binary tree structure */
gsl_spmatrix_pool *pool; /* memory pool for binary tree nodes */
size_t node_size; /* size of individual tree node in bytes */
/*
* workspace of size 2*MAX(size1,size2)*MAX(sizeof(float),sizeof(int))
* used in various routines
*/
union
{
void *work_void;
int *work_int;
float *work_atomic;
} work;
int sptype; /* sparse storage type */
size_t spflags; /* GSL_SPMATRIX_FLG_xxx */
} gsl_spmatrix_complex_float;
/*
* Prototypes
*/
/* allocation / initialization */
gsl_spmatrix_complex_float * gsl_spmatrix_complex_float_alloc (const size_t n1, const size_t n2);
gsl_spmatrix_complex_float * gsl_spmatrix_complex_float_alloc_nzmax (const size_t n1, const size_t n2,
const size_t nzmax, const int sptype);
void gsl_spmatrix_complex_float_free (gsl_spmatrix_complex_float * m);
int gsl_spmatrix_complex_float_realloc (const size_t nzmax, gsl_spmatrix_complex_float * m);
size_t gsl_spmatrix_complex_float_nnz (const gsl_spmatrix_complex_float * m);
const char * gsl_spmatrix_complex_float_type (const gsl_spmatrix_complex_float * m);
int gsl_spmatrix_complex_float_set_zero (gsl_spmatrix_complex_float * m);
int gsl_spmatrix_complex_float_tree_rebuild (gsl_spmatrix_complex_float * m);
/* compress */
int gsl_spmatrix_complex_float_csc (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);
int gsl_spmatrix_complex_float_csr (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);
gsl_spmatrix_complex_float * gsl_spmatrix_complex_float_compress (const gsl_spmatrix_complex_float * src, const int sptype);
gsl_spmatrix_complex_float * gsl_spmatrix_complex_float_compcol (const gsl_spmatrix_complex_float * src);
gsl_spmatrix_complex_float * gsl_spmatrix_complex_float_ccs (const gsl_spmatrix_complex_float * src);
gsl_spmatrix_complex_float * gsl_spmatrix_complex_float_crs (const gsl_spmatrix_complex_float * src);
/* copy */
int gsl_spmatrix_complex_float_memcpy (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);
/* file I/O */
int gsl_spmatrix_complex_float_fprintf (FILE * stream, const gsl_spmatrix_complex_float * m, const char * format);
gsl_spmatrix_complex_float * gsl_spmatrix_complex_float_fscanf (FILE * stream);
int gsl_spmatrix_complex_float_fwrite (FILE * stream, const gsl_spmatrix_complex_float * m);
int gsl_spmatrix_complex_float_fread (FILE * stream, gsl_spmatrix_complex_float * m);
/* get/set */
gsl_complex_float gsl_spmatrix_complex_float_get (const gsl_spmatrix_complex_float * m, const size_t i, const size_t j);
int gsl_spmatrix_complex_float_set (gsl_spmatrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x);
gsl_complex_float * gsl_spmatrix_complex_float_ptr (const gsl_spmatrix_complex_float * m, const size_t i, const size_t j);
/* operations */
int gsl_spmatrix_complex_float_scale (gsl_spmatrix_complex_float * m, const gsl_complex_float x);
int gsl_spmatrix_complex_float_scale_columns (gsl_spmatrix_complex_float * m, const gsl_vector_complex_float * x);
int gsl_spmatrix_complex_float_scale_rows (gsl_spmatrix_complex_float * m, const gsl_vector_complex_float * x);
int gsl_spmatrix_complex_float_add (gsl_spmatrix_complex_float * c, const gsl_spmatrix_complex_float * a, const gsl_spmatrix_complex_float * b);
int gsl_spmatrix_complex_float_d2sp (gsl_spmatrix_complex_float * T, const gsl_matrix_complex_float * A);
int gsl_spmatrix_complex_float_sp2d (gsl_matrix_complex_float * A, const gsl_spmatrix_complex_float * S);
/* properties */
int gsl_spmatrix_complex_float_equal (const gsl_spmatrix_complex_float * a, const gsl_spmatrix_complex_float * b);
/* swap */
int gsl_spmatrix_complex_float_transpose (gsl_spmatrix_complex_float * m);
int gsl_spmatrix_complex_float_transpose2 (gsl_spmatrix_complex_float * m);
int gsl_spmatrix_complex_float_transpose_memcpy (gsl_spmatrix_complex_float * dest, const gsl_spmatrix_complex_float * src);
__END_DECLS
#endif /* __GSL_SPMATRIX_COMPLEX_FLOAT_H__ */
| {
"alphanum_fraction": 0.7387414708,
"avg_line_length": 38.3430232558,
"ext": "h",
"hexsha": "fa216c7ab328eac3bf9a4c66f3e8c04142ace1ac",
"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_spmatrix_complex_float.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_spmatrix_complex_float.h",
"max_line_length": 144,
"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_spmatrix_complex_float.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1785,
"size": 6595
} |
//
// Created by ZL on 2019-06-13.
//
#ifndef ZQCNNDEMO_ZQCNN_MTCNN_NCHWC4_H
#define ZQCNNDEMO_ZQCNN_MTCNN_NCHWC4_H
#include "ZQ_CNN_Net_NCHWC.h"
#include "ZQ_CNN_MTCNN_NCHWC.h"
#include <vector>
#include <iostream>
#include "opencv2/opencv.hpp"
#include "ZQ_CNN_CompileConfig.h"
#include <cblas.h>
class MTCNNNCHWC {
public:
MTCNNNCHWC(const std::string &model_path);
std::vector<ZQ::ZQ_CNN_BBox> detect(const std::string &img_path);
std::vector<ZQ::ZQ_CNN_BBox> detectMat(cv::Mat &image0);
private:
ZQ::ZQ_CNN_MTCNN_NCHWC *mtcnn;
int thread_num = 1;
};
#endif //ZQCNNDEMO_ZQCNN_MTCNN_NCHWC4_H
| {
"alphanum_fraction": 0.7431781701,
"avg_line_length": 20.0967741935,
"ext": "h",
"hexsha": "a06ebf088dc9bbf85755e1c91039a91ab47d53b1",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-04-17T02:21:50.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-27T00:49:48.000Z",
"max_forks_repo_head_hexsha": "337fab2b58f14d118b59072d9469646cdba43d57",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "zhu260824/ZQCNN_Android",
"max_forks_repo_path": "app/src/main/cpp/zqcnn_mtcnn_nchwc4.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "337fab2b58f14d118b59072d9469646cdba43d57",
"max_issues_repo_issues_event_max_datetime": "2019-06-26T09:10:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-06-26T09:10:21.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "zhu260824/ZQCNN_Android",
"max_issues_repo_path": "app/src/main/cpp/zqcnn_mtcnn_nchwc4.h",
"max_line_length": 69,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "337fab2b58f14d118b59072d9469646cdba43d57",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "zhu260824/ZQCNN_Android",
"max_stars_repo_path": "app/src/main/cpp/zqcnn_mtcnn_nchwc4.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-14T07:23:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-18T14:38:56.000Z",
"num_tokens": 234,
"size": 623
} |
#pragma once
#include <gsl\gsl>
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <map>
#include "DrawableGameComponent.h"
#include "FullScreenRenderTarget.h"
#include "FullScreenQuad.h"
#include "MatrixHelper.h"
namespace Library
{
class Texture2D;
class TexturedModelMaterial;
}
namespace Rendering
{
class DistortionMaskingDemo final : public Library::DrawableGameComponent
{
public:
DistortionMaskingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
DistortionMaskingDemo(const DistortionMaskingDemo&) = delete;
DistortionMaskingDemo(DistortionMaskingDemo&&) = default;
DistortionMaskingDemo& operator=(const DistortionMaskingDemo&) = default;
DistortionMaskingDemo& operator=(DistortionMaskingDemo&&) = default;
~DistortionMaskingDemo();
bool DrawCutoutModeEnabled() const;
void SetDrawCutoutModeEnabled(bool enabled);
void ToggledDrawCutoutModeEnabled();
float DisplacementScale() const;
void SetDisplacementScale(float displacementScale);
virtual void Initialize() override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
struct PixelCBufferPerObject
{
float DisplacementScale{ 1.0f };
DirectX::XMFLOAT3 Padding;
};
enum class DistortionShaderClass
{
Cutout = 0,
Composite,
NoDistortion
};
inline static const DirectX::XMVECTORF32 CutoutZeroColor{ DirectX::Colors::Black };
DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };
std::shared_ptr<Library::TexturedModelMaterial> mTexturedModelMaterial;
Library::FullScreenRenderTarget mSceneRenderTarget;
Library::FullScreenRenderTarget mCutoutRenderTarget;
Library::FullScreenQuad mFullScreenQuad;
winrt::com_ptr<ID3D11Buffer> mPixelCBufferPerObject;
PixelCBufferPerObject mPixelCBufferPerObjectData;
std::shared_ptr<Library::Texture2D> mDistortionMap;
std::map<DistortionShaderClass, winrt::com_ptr<ID3D11ClassInstance>> mShaderClassInstances;
winrt::com_ptr<ID3D11Buffer> mVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mIndexBuffer;
std::uint32_t mIndexCount{ 0 };
bool mDrawCutoutModeEnabled{ false };
bool mUpdateMaterial{ true };
};
} | {
"alphanum_fraction": 0.7865013774,
"avg_line_length": 30.676056338,
"ext": "h",
"hexsha": "0a0707f7e5b5ea75ade69a1fbc5584922d8413f0",
"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/7.5_Distortion_Masking/DistortionMaskingDemo.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/7.5_Distortion_Masking/DistortionMaskingDemo.h",
"max_line_length": 93,
"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/7.5_Distortion_Masking/DistortionMaskingDemo.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 585,
"size": 2178
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \defgroup ioda_cxx_types Type System
* \brief The data type system
* \ingroup ioda_cxx_api
*
* @{
* \file Type.h
* \brief Interfaces for ioda::Type and related classes. Implements the type system.
*/
#include <array>
#include <cstring>
#include <functional>
#include <gsl/gsl-lite.hpp>
#include <memory>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <vector>
#include "ioda/Types/Type_Provider.h"
#include "ioda/Exception.h"
#include "ioda/defs.h"
namespace ioda {
class Type;
/// Basic pre-defined types (Python convenience wrappers)
/// \see py_ioda.cpp
/// \note Names here do not match the python equivalents. The
/// Python names match numpy's definitions.
enum class BasicTypes {
undefined_, ///< Internal use only
float_,
double_,
ldouble_,
char_,
short_,
ushort_,
int_,
uint_,
lint_,
ulint_,
llint_,
ullint_,
int32_,
uint32_,
int16_,
uint16_,
int64_,
uint64_,
bool_,
str_
};
namespace detail {
IODA_DL size_t COMPAT_strncpy_s(char* dest, size_t destSz, const char* src, size_t srcSz);
class Type_Backend;
template <class Type_Implementation = Type>
class Type_Base {
friend class ::ioda::Type;
std::shared_ptr<Type_Backend> backend_;
protected:
::ioda::detail::Type_Provider* provider_;
/// @name General Functions
/// @{
Type_Base(std::shared_ptr<Type_Backend> b, ::ioda::detail::Type_Provider* p)
: backend_(b), provider_(p) {}
/// Get the type provider.
inline detail::Type_Provider* getTypeProvider() const { return provider_; }
/*
/// \brief Convenience function to check a type.
/// \param DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \returns True if the type matches
/// \returns False (0) if the type does not match
/// \throws if an error occurred.
template <class DataType>
bool isA() const {
Type templateType = Types::GetType_Wrapper<DataType>::GetType(getTypeProvider());
return isA(templateType);
}
/// Hand-off to the backend to check equivalence
virtual bool isA(Type lhs) const;
/// Python compatability function
inline bool isA(BasicTypes dataType) const { return isA(Type(dataType, getTypeProvider())); }
*/
public:
virtual ~Type_Base() {}
std::shared_ptr<Type_Backend> getBackend() const { return backend_; }
bool isValid() const { return (backend_.use_count() > 0); }
/// \brief Get the size of a single element of a type, in bytes.
/// \details This function is paired with the read and write functions to allow you to
/// read and write data in a type-agnostic manner.
/// This size report is a bit complicated when variable-length strings are encountered.
/// In these cases, the size of the string pointer is returned.
virtual size_t getSize() const;
/// @}
};
} // namespace detail
/// \brief Represents the "type" (i.e. integer, string, float) of a piece of data.
/// \ingroup ioda_cxx_types
///
/// Generally, you do not have to use this class directly. Attributes and Variables have
/// templated functions that convert your type into the type used internally by ioda.
/// \see Types::GetType and Types::GetType_Wrapper for functions that produce these types.
class IODA_DL Type : public detail::Type_Base<> {
public:
Type();
Type(std::shared_ptr<detail::Type_Backend> b, std::type_index t);
Type(BasicTypes, gsl::not_null<::ioda::detail::Type_Provider*> t);
virtual ~Type();
/// @name Type-querying functions
/// @{
/// @deprecated This function is problematic since we cannot query a type properly
/// when loading from a file.
std::type_index getType() const { return as_type_index_; }
inline std::type_index operator()() const { return getType(); }
inline std::type_index get() const { return getType(); }
/// @}
private:
std::type_index as_type_index_;
};
namespace detail {
/// Backends inherit from this and they provide their own functions.
/// Lots of std::dynamic_cast, unfortunately.
class IODA_DL Type_Backend : public Type_Base<> {
public:
virtual ~Type_Backend();
size_t getSize() const override;
protected:
Type_Backend();
};
} // namespace detail
/// \brief Defines the type system used for manipulating IODA objects.
namespace Types {
// using namespace ioda::Handles;
/// \brief Convenience struct to determine if a type can represent a string.
/// \ingroup ioda_cxx_types
/// \todo extend to UTF-8 strings, as HDF5 supports these. No support for UTF-16, but conversion
/// functions may be applied.
/// \todo Fix for "const std::string".
template <typename T>
struct is_string : public std::integral_constant<
bool, std::is_same<char*, typename std::decay<T>::type>::value
|| std::is_same<const char*, typename std::decay<T>::type>::value> {};
/// \brief Convenience struct to determine if a type can represent a string.
/// \ingroup ioda_cxx_types
template <>
struct is_string<std::string> : std::true_type {};
/// Useful compile-time definitions.
namespace constants {
/// \note Different than ObsSpace variable-length dimension. This is for a Type.
constexpr size_t _Variable_Length = 0;
// constexpr int _Not_An_Array_type = -3;
} // namespace constants
/// \brief For fundamental, non-string types.
/// \ingroup ioda_cxx_types
template <class DataType, int Array_Type_Dimensionality = 0>
Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t> Adims = {},
typename std::enable_if<!is_string<DataType>::value>::type* = 0) {
if (Array_Type_Dimensionality <= 0)
throw Exception(
"Bad assertion / unsupported fundamental type at the frontend side "
"of the ioda type system.", ioda_Here());
else
return t->makeArrayType(Adims, typeid(DataType[]), typeid(DataType));
}
/// \brief For fundamental string types. These are either constant or variable length arrays.
/// Separate handling elsewhere.
/// \ingroup ioda_cxx_types
template <class DataType, int String_Type_Length = constants::_Variable_Length>
Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t> = {},
typename std::enable_if<is_string<DataType>::value>::type* = 0) {
return t->makeStringType(String_Type_Length, typeid(DataType));
}
// This macro just repeats a long definition
/// @def IODA_ADD_FUNDAMENTAL_TYPE
/// Macro that defines a "fundamental type" that needs to be supported
/// by the backend. These match C++11.
/// \ingroup ioda_cxx_types
/// \see https://en.cppreference.com/w/cpp/language/types
/// \since C++11: we use bool, short int, unsigned short int,
/// int, unsigned int, long int, unsigned long int,
/// long long int, unsigned long long int,
/// signed char, unsigned char, char,
/// wchar_t, char16_t, char32_t,
/// float, double, long double.
/// \since C++20: we also add char8_t.
#define IODA_ADD_FUNDAMENTAL_TYPE(x) \
template <> \
inline Type GetType<x, 0>(gsl::not_null<const ::ioda::detail::Type_Provider*> t, \
std::initializer_list<Dimensions_t>, void*) { \
return t->makeFundamentalType(typeid(x)); \
}
IODA_ADD_FUNDAMENTAL_TYPE(bool);
IODA_ADD_FUNDAMENTAL_TYPE(short int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned short int);
IODA_ADD_FUNDAMENTAL_TYPE(int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned int);
IODA_ADD_FUNDAMENTAL_TYPE(long int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned long int);
IODA_ADD_FUNDAMENTAL_TYPE(long long int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned long long int);
IODA_ADD_FUNDAMENTAL_TYPE(signed char);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned char);
IODA_ADD_FUNDAMENTAL_TYPE(char);
IODA_ADD_FUNDAMENTAL_TYPE(wchar_t);
IODA_ADD_FUNDAMENTAL_TYPE(char16_t);
IODA_ADD_FUNDAMENTAL_TYPE(char32_t);
// IODA_ADD_FUNDAMENTAL_TYPE(char8_t); // C++20
IODA_ADD_FUNDAMENTAL_TYPE(float);
IODA_ADD_FUNDAMENTAL_TYPE(double);
IODA_ADD_FUNDAMENTAL_TYPE(long double);
#undef IODA_ADD_FUNDAMENTAL_TYPE
/*
/// Used in an example. Incomplete.
/// \todo Pop off std::array as a 1-D object
template<> inline Type GetType<std::array<int,2>, 0>
(gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t>, void*) {
return t->makeArrayType({2}, typeid(std::array<int,2>), typeid(int)); }
*/
/*
template <class DataType, int Array_Type_Dimensionality = 0>
Type GetType(
gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t> Adims = {},
typename std::enable_if<!is_string<DataType>::value>::type* = 0);
template <class DataType, int String_Type_Length = constants::_Variable_Length>
Type GetType(
gsl::not_null<const ::ioda::detail::Type_Provider*> t,
typename std::enable_if<is_string<DataType>::value>::type* = 0);
*/
/// \brief Wrapper struct to call GetType. Needed because of C++ template rules.
/// \ingroup ioda_cxx_types
/// \see ioda::Attribute, ioda::Has_Attributes, ioda::Variable, ioda::Has_Variables
template <class DataType,
int Length = 0> //, typename = std::enable_if_t<!is_string<DataType>::value>>
struct GetType_Wrapper {
static Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) {
/// \note Currently breaks array types, but these are not yet used.
return ::ioda::Types::GetType<DataType, Length>(t, {Length});
}
};
/// \ingroup ioda_cxx_types
typedef std::function<Type(gsl::not_null<const ::ioda::detail::Type_Provider*>)>
TypeWrapper_function;
/*
template <class DataType, int Length = 0, typename = std::enable_if_t<is_string<DataType>::value>>
struct GetType_Wrapper {
Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) const {
// string split
return ::ioda::Types::GetType<DataType, Length>(t);
}
};
*/
// inline Encapsulated_Handle GetTypeFixedString(Dimensions_t sz);
} // namespace Types
} // namespace ioda
/// @}
| {
"alphanum_fraction": 0.6891904807,
"avg_line_length": 34.5313531353,
"ext": "h",
"hexsha": "0fd39a6df3673a6eab59e208982c3969e84c1931",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z",
"max_forks_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Gibies/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Types/Type.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Gibies/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Types/Type.h",
"max_line_length": 100,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Gibies/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Types/Type.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z",
"num_tokens": 2614,
"size": 10463
} |
#ifndef THREADEDNESS_INCLUDE
#define THREADEDNESS_INCLUDE
#include <string>
#include <gsl/string_span>
#include "config/commandLineOptions.h"
#include "config/fleetingOptionsInterface.h"
#include "config/variablesMap.h"
#include "core/task.h"
namespace execHelper::plugins {
using Jobs = config::Jobs_t;
const gsl::czstring<> JOBS_KEY = "jobs";
/**
* \brief Extends the functionality to include the _jobs_ config parameter and processes this parameter, using the --jobs flag
*/
struct JobsLong {
/**
* Adds the variables for this functionality to the given variables map
*
* @param[in] options The fleeting options to take into account
* @param[out] variables The variables map to add the variables to
*/
static void
getVariables(config::VariablesMap& variables,
const config::FleetingOptionsInterface& options) noexcept;
/**
* Applies the given variables to the task
*
* @param[in] variables The variables map to use
* @param[out] task The task with the given variables map applied to it
*/
inline static void apply(core::Task& task,
const config::VariablesMap& variables) noexcept {
task.append(
{"--jobs", std::to_string(*(variables.get<Jobs>(JOBS_KEY)))});
}
};
/**
* \brief Extends the functionality to include the _jobs_ config parameter and processes this parameter, using the -j flag
*/
struct JobsShort {
/*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)
*/
inline static void
getVariables(config::VariablesMap& variables,
const config::FleetingOptionsInterface& options) noexcept {
JobsLong::getVariables(variables, options);
}
/*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)
*/
inline static void apply(core::Task& task,
const config::VariablesMap& variables) noexcept {
task.append({"-j", std::to_string(*(variables.get<Jobs>(JOBS_KEY)))});
}
};
} // namespace execHelper::plugins
#endif /* THREADEDNESS_INCLUDE */
| {
"alphanum_fraction": 0.6695933457,
"avg_line_length": 31.8235294118,
"ext": "h",
"hexsha": "959118c6e9a9d8f16d62220a1f0978b7008958bb",
"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/plugins/include/plugins/threadedness.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/plugins/include/plugins/threadedness.h",
"max_line_length": 126,
"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/plugins/include/plugins/threadedness.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": 477,
"size": 2164
} |
#pragma once
#include <gsl.h>
#include <boost/optional.hpp>
#include <mitkPythonService.h>
#include <QObject>
#include <QSet>
#include <QString>
#include <QVariant>
#include <QVariantList>
#include <QVector>
#include <SolidData.h>
#include <FaceIdentifier.h>
#include <ISolverStudyData.h>
#include <MeshData.h>
#include <VesselForestData.h>
#include <PCMRIData.h>
#include "PythonSolverSetupServiceActivator.h"
#include <PythonSolverSetupManager.h>
#include "PythonSolverSetupServiceExports.h"
namespace crimson
{
class FaceTypeQtWrapper : public QObject
{
Q_OBJECT
public:
Q_ENUMS(FaceType);
enum FaceType {
ftCapInflow = FaceIdentifier::ftCapInflow,
ftCapOutflow = FaceIdentifier::ftCapOutflow,
ftWall = FaceIdentifier::ftWall,
ftUndefined = FaceIdentifier::ftUndefined
};
};
class ArrayDataTypeQtWrapper : public QObject
{
Q_OBJECT
public:
Q_ENUMS(ArrayDataType);
enum class ArrayDataType {
Int = 0,
Double = 1,
};
};
class PyFaceIdentifier
{
public:
static PythonQtObjectPtr cppToPy(const FaceIdentifier& cppFaceId)
{
auto pythonService = PythonSolverSetupServiceActivator::getPythonService();
pythonService->Execute("import CRIMSONCore");
QVariantList parentSolidIndices;
for (const auto& parentSolidIndex : cppFaceId.parentSolidIndices) {
parentSolidIndices << QString::fromStdString(parentSolidIndex);
}
auto result = PythonQtObjectPtr{pythonService->GetPythonManager()->mainContext().call(
"CRIMSONCore.FaceIdentifier.FaceIdentifier",
QVariantList{static_cast<FaceTypeQtWrapper::FaceType>(cppFaceId.faceType), parentSolidIndices})};
Ensures(!result.isNull());
return result;
}
static boost::optional<FaceIdentifier> pyToCpp(PythonQtObjectPtr pyFaceId)
{
FaceIdentifier cppFaceId;
QVariant faceIdVariant = pyFaceId.getVariable("faceType");
if (!faceIdVariant.canConvert<int>()) {
MITK_ERROR << "Face identifier not recognized - wrong faceType (expected int)";
return boost::none;
}
cppFaceId.faceType = static_cast<FaceIdentifier::FaceType>(faceIdVariant.toInt());
QVariant parentSolidIndicesVariant = pyFaceId.getVariable("parentSolidIndices");
if (!parentSolidIndicesVariant.canConvert<QVariantList>()) {
MITK_ERROR << "Face identifier not recognized - wrong parentSolidIndices (expected list of strings)";
return boost::none;
}
for (const auto& parentSolidIndexVariant : parentSolidIndicesVariant.toList()) {
if (!parentSolidIndexVariant.canConvert<QString>()) {
MITK_ERROR << "Face identifier not recognized - wrong item in parentSolidIndices (expected string)";
return boost::none;
}
cppFaceId.parentSolidIndices.insert(parentSolidIndexVariant.toString().toStdString());
}
return cppFaceId;
}
};
class Utils : public QObject
{
Q_OBJECT
public slots:
void static_Utils_reloadAll() { crimson::PythonSolverSetupServiceActivator::reloadPythonSolverSetups(true); }
void static_Utils_logError(QString message) { MITK_ERROR << message.toStdString(); }
void static_Utils_logWarning(QString message) { MITK_WARN << message.toStdString(); }
void static_Utils_logInformation(QString message) { MITK_INFO << message.toStdString(); }
};
class SolidDataQtWrapper : public QObject
{
Q_OBJECT
public:
SolidDataQtWrapper()
: _brep(nullptr)
{
}
SolidDataQtWrapper(gsl::not_null<const SolidData*> brep)
: _brep(brep)
{
}
SolidDataQtWrapper(const SolidDataQtWrapper& other)
: _brep(other._brep)
{
}
public slots:
QVector<double> getFaceNormal(PythonQtObjectPtr pyFaceIdentifier) const
{
Expects(_brep != nullptr);
auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);
if (!cppFaceIdOptional) {
return {};
}
auto normal = _brep->getFaceNormal(cppFaceIdOptional.get());
return QVector<double>{normal[0], normal[1], normal[2]};
}
double getDistanceToFaceEdge(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const
{
Expects(_brep != nullptr);
auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);
if (!cppFaceIdOptional) {
return 0;
}
auto pos = mitk::Point3D{};
pos[0] = x;
pos[1] = y;
pos[2] = z;
return _brep->getDistanceToFaceEdge(cppFaceIdOptional.get(), pos);
}
PythonQtObjectPtr getFaceIdentifierForModelFace(int faceIndex) const
{
Expects(_brep != nullptr);
auto identifierOpt = _brep->getFaceIdentifierMap().getFaceIdentifierForModelFace(faceIndex);
return identifierOpt ? PyFaceIdentifier::cppToPy(identifierOpt.get()) : nullptr;
}
int getNumberOfModelFaces() const
{
Expects(_brep != nullptr);
return _brep->getFaceIdentifierMap().getNumberOfModelFaces();
}
int getNumberOfFaceIdentifiers() const
{
Expects(_brep != nullptr);
return _brep->getFaceIdentifierMap().getNumberOfFaceIdentifiers();
}
int faceIdentifierIndex(PythonQtObjectPtr pyFaceIdentifier) const
{
Expects(_brep != nullptr);
auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);
if (!cppFaceIdOptional) {
return 0;
}
return _brep->getFaceIdentifierMap().faceIdentifierIndex(cppFaceIdOptional.get());
}
PythonQtObjectPtr getFaceIdentifier(int uniqueFaceId) const
{
Expects(_brep != nullptr);
return PyFaceIdentifier::cppToPy(_brep->getFaceIdentifierMap().getFaceIdentifier(uniqueFaceId));
}
QVector<int> getModelFacesForFaceIdentifier(PythonQtObjectPtr pyFaceIdentifier) const
{
Expects(_brep != nullptr);
auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);
if (!cppFaceIdOptional) {
return {};
}
return QVector<int>::fromStdVector(_brep->getFaceIdentifierMap().getModelFacesForFaceIdentifier(cppFaceIdOptional.get()));
}
private:
const SolidData* _brep;
};
class MeshDataQtWrapper : public QObject
{
Q_OBJECT
public:
MeshDataQtWrapper()
: _mesh(nullptr)
{
}
MeshDataQtWrapper(gsl::not_null<const MeshData*> mesh)
: _mesh(mesh)
{
}
MeshDataQtWrapper(const MeshDataQtWrapper& other)
: _mesh(other._mesh)
{
}
public slots:
int getNNodes() const
{
Expects(_mesh != nullptr);
return _mesh->getNNodes();
}
int getNEdges() const
{
Expects(_mesh != nullptr);
return _mesh->getNEdges();
}
int getNFaces() const
{
Expects(_mesh != nullptr);
return _mesh->getNFaces();
}
int getNElements() const
{
Expects(_mesh != nullptr);
return _mesh->getNElements();
}
QVector<double> getNodeCoordinates(int nodeIndex) const
{
Expects(_mesh != nullptr);
auto coords = _mesh->getNodeCoordinates(nodeIndex);
return QVector<double>{coords[0], coords[1], coords[2]};
}
QVector<int> getElementNodeIds(int elementIndex) const
{
Expects(_mesh != nullptr);
return QVector<int>::fromStdVector(_mesh->getElementNodeIds(elementIndex));
}
QVector<int> getAdjacentElements(int elementIndex) const
{
Expects(_mesh != nullptr);
return QVector<int>::fromStdVector(_mesh->getAdjacentElements(elementIndex));
}
QVector<int> getNodeIdsForFace(PythonQtObjectPtr pyFaceIdentifier) const
{
Expects(_mesh != nullptr);
auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);
if (!cppFaceIdOptional) {
return {};
}
return QVector<int>::fromStdVector(_mesh->getNodeIdsForFace(cppFaceIdOptional.get()));
}
QVariantList getMeshFaceInfoForFace(PythonQtObjectPtr pyFaceIdentifier) const // TODO: QVector<QVector<int>>
{
Expects(_mesh != nullptr);
auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);
if (!cppFaceIdOptional) {
return {};
}
auto faceInfos = _mesh->getMeshFaceInfoForFace(cppFaceIdOptional.get());
auto out = QVariantList{};
out.reserve(faceInfos.size());
std::transform(
faceInfos.begin(), faceInfos.end(), std::back_inserter(out),
[](const crimson::MeshData::MeshFaceInfo& info) {
return QVariant::fromValue(QVector<int>{info.elementId, info.globalFaceId, info.nodeIds[0], info.nodeIds[1], info.nodeIds[2]});
});
return out;
}
private:
const MeshData* _mesh;
};
class VesselForestDataQtWrapper : public QObject
{
Q_OBJECT
public:
using UIDToVesselPathDataMap = std::unordered_map<std::string, const VesselPathAbstractData*>;
VesselForestDataQtWrapper()
: _vesselForest(nullptr)
{
}
VesselForestDataQtWrapper(gsl::not_null<const VesselForestData*> data, UIDToVesselPathDataMap uidToVesselPathDataMap)
: _vesselForest(data)
, _uidToVesselPathDataMap(std::move(uidToVesselPathDataMap))
{
}
VesselForestDataQtWrapper(const VesselForestDataQtWrapper& other)
: _vesselForest(other._vesselForest)
, _uidToVesselPathDataMap(other._uidToVesselPathDataMap)
{
}
// VesselForestDataQtWrapper(const VesselForestDataQtWrapper&) = default;
const UIDToVesselPathDataMap& getUIDToVesselPathDataMap() const { return _uidToVesselPathDataMap; }
public slots:
QVariantMap getActiveConnectedComponentsMap() const
{
Expects(_vesselForest != nullptr);
auto result = QVariantMap{};
for (const auto& uidComponentIndexPair : _vesselForest->computeActiveConnectedComponents()) {
result[QString::fromStdString(uidComponentIndexPair.first)] = uidComponentIndexPair.second;
}
return result;
}
QVariantList getClosestPoint(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const
{
Expects(_vesselForest != nullptr);
auto closestPathInfo = _getClosestVesselPath(pyFaceIdentifier, x, y, z);
if (!closestPathInfo.vesselPath) {
return {};
}
return QVariantList{closestPathInfo.distance, closestPathInfo.t};
}
QVector<double> getVesselPathCoordinateFrame(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const
{
auto closestPathInfo = _getClosestVesselPath(pyFaceIdentifier, x, y, z);
if (!closestPathInfo.vesselPath) {
return{};
}
auto pt = closestPathInfo.vesselPath->getPosition(closestPathInfo.t);
auto tangent = closestPathInfo.vesselPath->getTangentVector(closestPathInfo.t);
auto normal = closestPathInfo.vesselPath->getNormalVector(closestPathInfo.t);
return QVector<double>{pt[0], pt[1], pt[2], tangent[0], tangent[1], tangent[2], normal[0], normal[1], normal[2]};
}
private:
struct ClosestVesselPathInfo {
const VesselPathAbstractData* vesselPath = nullptr;
double distance = 0;
double t = 0;
};
ClosestVesselPathInfo _getClosestVesselPath(PythonQtObjectPtr pyFaceIdentifier, double x, double y, double z) const
{
auto cppFaceIdOptional = PyFaceIdentifier::pyToCpp(pyFaceIdentifier);
if (!cppFaceIdOptional) {
return {};
}
auto&& parentSolidIndices = cppFaceIdOptional->parentSolidIndices;
auto result = ClosestVesselPathInfo{};
auto pos = mitk::Point3D{};
mitk::FillVector3D(pos, x, y, z);
for (const auto& vesselUID : parentSolidIndices) {
auto closestPointRequestResult = _uidToVesselPathDataMap.at(vesselUID)->getClosestPoint(pos);
auto d = closestPointRequestResult.closestPoint.EuclideanDistanceTo(pos);
if (result.vesselPath == nullptr || d < result.distance) {
result.vesselPath = _uidToVesselPathDataMap.at(vesselUID);
result.t = closestPointRequestResult.t;
result.distance = d;
}
}
return result;
}
const VesselForestData* _vesselForest;
UIDToVesselPathDataMap _uidToVesselPathDataMap;
};
class PCMRIDataQtWrapper : public QObject
{
Q_OBJECT
public:
PCMRIDataQtWrapper()
: _pcmriData(nullptr)
{
}
PCMRIDataQtWrapper(gsl::not_null<const PCMRIData*> pcmriData)
: _pcmriData(pcmriData)
{
}
PCMRIDataQtWrapper(const PCMRIDataQtWrapper& other)
: _pcmriData(other._pcmriData)
{
}
public slots:
QVector<double> getTimepoints() const
{
Expects(_pcmriData != nullptr);
return QVector<double>::fromStdVector(_pcmriData->getTimepoints());
}
QVector<double> getFlowWaveform() const
{
Expects(_pcmriData != nullptr);
return QVector<double>::fromStdVector(_pcmriData->getFlowWaveform());
}
QVector<double> getSingleMappedPCMRIvector(int pointIndex, int timepointIndex) const
{
Expects(_pcmriData != nullptr);
auto coords = _pcmriData->getSingleMappedPCMRIvector(pointIndex, timepointIndex);
return QVector<double>{coords[0], coords[1], coords[2]};
}
private:
const PCMRIData* _pcmriData;
};
}
Q_DECLARE_METATYPE(crimson::SolidDataQtWrapper)
Q_DECLARE_METATYPE(crimson::MeshDataQtWrapper)
Q_DECLARE_METATYPE(crimson::VesselForestDataQtWrapper)
Q_DECLARE_METATYPE(crimson::PCMRIDataQtWrapper)
| {
"alphanum_fraction": 0.6761744966,
"avg_line_length": 28.9809725159,
"ext": "h",
"hexsha": "fbfcf15b77ac0ab3d0e6b4ac9260367f3d52cd47",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z",
"max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "carthurs/CRIMSONGUI",
"max_forks_repo_path": "Modules/PythonSolverSetupService/src/PythonQtWrappers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "carthurs/CRIMSONGUI",
"max_issues_repo_path": "Modules/PythonSolverSetupService/src/PythonQtWrappers.h",
"max_line_length": 143,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "carthurs/CRIMSONGUI",
"max_stars_repo_path": "Modules/PythonSolverSetupService/src/PythonQtWrappers.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": 3334,
"size": 13708
} |
/******************************************************************************
* *
* ELECTRONS.C *
* *
* ELECTRON THERMODYNAMICS *
* *
******************************************************************************/
#include "decs.h"
#include <gsl/gsl_sf_bessel.h>
/* TODO: Encapsulate electron equation of state in EOS framework.
* For now, I'v ebroken encapsulation but made the code
* complain/break if EOS_TYPE is not EOS_TYPE_GAMMA
* when ELECTRONS are active.
*
* The best strategy is probably to make a two-temperature
* electron EOS one of the available EOS's.
*
* Until then, I'm worried that we might hit a maintainability
* problem becasue if the implementation in ELECTRONS changes
* the implementation in EOS_TYPE_GAMMA needs to change too.
* ~JMM
*/
#if ELECTRONS
#if EOS == EOS_TYPE_GAMMA
void heat_electrons_zone(int i, int j, int k, double Pi[NVAR], double Ps[NVAR],
double Pf[NVAR], double Dt);
void fixup_electrons_1zone(double P[NVAR]);
void init_electrons() {
double uel;
ZSLOOP(-NG, N1 + NG - 1, -NG, NG + N2 - 1, -NG, NG + N3 - 1) {
// Set electron internal energy to constant fraction of internal energy
uel = fel0 * P[i][j][k][UU];
// Initialize entropies
P[i][j][k][KTOT] = (gam - 1.) * P[i][j][k][UU] * pow(P[i][j][k][RHO], -gam);
P[i][j][k][KEL] = (game - 1.) * uel * pow(P[i][j][k][RHO], -game);
}
bound_prim(P);
}
void heat_electrons(
grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt) {
timer_start(TIMER_ELECTRON);
#pragma omp parallel for collapse(3) schedule(dynamic)
ZLOOP {
heat_electrons_zone(i, j, k, Pi[i][j][k], Ps[i][j][k], Pf[i][j][k], Dt);
}
timer_stop(TIMER_ELECTRON);
}
void heat_electrons_zone(int i, int j, int k, double Pi[NVAR], double Ps[NVAR],
double Pf[NVAR], double Dt) {
double ktotharm, ktotadv, fel;
// Calculated and advected entropy at final time
ktotharm = (gam - 1.) * Pf[UU] / pow(Pf[RHO], gam);
ktotadv = Pf[KTOT];
// Electron heating fraction
fel = get_fel(i, j, k, Ps);
// Update final electron entropy according to Ressler+ 2015 Eqn. 27:
Pf[KEL] += (game - 1.) / (gam - 1.) * pow(Ps[RHO], gam - game) * fel *
(ktotharm - ktotadv);
// Diagnostics
struct of_geom *geom = &ggeom[i][j][CENT];
struct of_state q;
get_state(Ps, geom, &q);
double uadv = ktotadv / (gam - 1.) * pow(Pf[RHO], gam);
double Qud = q.ucon[0] * q.ucov[0] * (Pf[UU] - uadv) *
pow(Ps[RHO] / Pf[RHO], gam) / Dt;
Qvisc[i][j][k] = fel * Qud;
// Reset total entropy
Pf[KTOT] = ktotharm;
}
double get_fel(int i, int j, int k, double P[NVAR]) {
#if BETA_HEAT == 0
return fel0;
#endif
struct of_geom geom;
double beta, fel, c1, Trat, Tpr, mbeta, qrat;
double pres, bsq;
double c2, c3, c22, c32;
c1 = 0.92;
Tpr = (gam - 1.) * P[UU] / P[RHO];
double uel = 1. / (game - 1.) * P[KEL] * pow(P[RHO], game);
double Tel = (game - 1.) * uel / P[RHO];
if (Tel <= 0.)
Tel = SMALL;
if (Tpr <= 0.)
Tpr = SMALL;
Trat = fabs(Tpr / Tel);
pres = P[RHO] * Tpr; // Proton pressure
geom = *get_geometry(i, j, k, CENT);
bsq = bsq_calc(P, &geom);
beta = pres / bsq * 2.;
if (beta > 1.e20)
beta = 1.e20;
mbeta = 2. - 0.2 * log10(Trat);
if (Trat <= 1.) {
c2 = 1.6 / Trat;
c3 = 18. + 5. * log10(Trat);
} else {
c2 = 1.2 / Trat;
c3 = 18.;
}
c22 = pow(c2, 2.);
c32 = pow(c3, 2.);
qrat = c1 * (c22 + pow(beta, mbeta)) / (c32 + pow(beta, mbeta)) *
exp(-1. / beta) * pow(MP / ME * Trat, .5);
fel = 1. / (1. + qrat);
return fel;
}
// Modified Bessel function of second kind with safe inputs
double safe_Kn(int n, double x) {
if (x > 100.) {
return exp(-x) * sqrt(M_PI / (2. * x));
} else {
return gsl_sf_bessel_Kn(n, x);
}
}
#if RADIATION
void coulomb(
grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt) {
timer_start(TIMER_ELECTRON);
#pragma omp parallel for collapse(3)
ZLOOP {
double rho = Ps[i][j][k][RHO];
double thetae = MP / ME * Ps[i][j][k][KEL] * pow(rho, game - 1.);
double ue = Ps[i][j][k][KEL] * pow(rho, game) / (game - 1.);
double up = Ps[i][j][k][UU] - ue;
double n = rho * Ne_unit;
double Ti = up * U_unit * (gamp - 1.) / (n * KBOL);
double thetai = KBOL * Ti / (MP * CL * CL);
double thetam = 1. / (1. / thetae + 1. / thetai);
double logCoul = COULOMB_LOG;
double Te = thetae * ME * CL * CL / KBOL;
struct of_geom *geom;
struct of_state q;
// Sanity checks, although electron fixup routine should catch these
if (!isnan(Te) && !isnan(Ti) && Te > 0. && Ti > 0.) {
double Qc, term1, term2;
// Get Coulomb heating rate.
// Need to handle cases where Thetai < 1e-2, Thetae < 1e-2, and both
// Thetae and Thetai < 1e-2 separately due to Bessel functions exploding
double prefac =
3. / 2. * ME / MP * n * n * logCoul * CL * KBOL * THOMSON * (Ti - Te);
double thetaCrit = 1.e-2;
if (thetae < thetaCrit && thetai < thetaCrit) {
term1 = sqrt(thetam / (M_PI * thetae * thetai / 2.));
term2 = sqrt(thetam / (M_PI * thetae * thetai / 2.));
} else if (thetae < thetaCrit) {
term1 =
exp(-1. / thetai) / safe_Kn(2, 1. / thetai) * sqrt(thetam / thetae);
term2 =
exp(-1. / thetai) / safe_Kn(2, 1. / thetai) * sqrt(thetam / thetae);
} else if (thetai < thetaCrit) {
term1 =
exp(-1. / thetae) / safe_Kn(2, 1. / thetae) * sqrt(thetam / thetai);
term2 =
exp(-1. / thetae) / safe_Kn(2, 1. / thetae) * sqrt(thetam / thetai);
} else {
term1 = safe_Kn(1, 1. / thetam) /
(safe_Kn(2, 1. / thetae) * safe_Kn(2, 1. / thetai));
term2 = safe_Kn(0, 1. / thetam) /
(safe_Kn(2, 1. / thetae) * safe_Kn(2, 1. / thetai));
}
term1 *= (2. * pow(thetae + thetai, 2) + 1.) / (thetae + thetai);
term2 *= 2.;
Qc = prefac * (term1 + term2);
// Convert to code units
Qc *= T_unit / U_unit;
// Update electron internal energy
geom = &ggeom[i][j][CENT];
get_state(Ps[i][j][k], geom, &q);
double ue_f =
Pf[i][j][k][KEL] * pow(Pf[i][j][k][RHO], game) / (game - 1.);
ue_f += Qc * Dt / q.ucon[0];
// Record diagnostic
Qcoul[i][j][k] = q.ucov[0] * Qc;
// Update electron entropy
Pf[i][j][k][KEL] = (game - 1.) * ue_f * pow(Pf[i][j][k][RHO], -game);
}
} // ZLOOP
timer_stop(TIMER_ELECTRON);
}
void apply_rad_force_e(grid_prim_type Prh, grid_prim_type Pr,
grid_fourvector_type radG, double Dt) {
// Apply only to active zones for this proc -- ghost zone four-force
// depositions already communicated over MPI
#pragma omp parallel for collapse(3) schedule(dynamic)
ZLOOP {
struct of_geom *geom = &ggeom[i][j][CENT];
struct of_state q;
double Uel, Urho;
double C = 0.;
// Get fluid state at n + 1/2 where radiation four-force is centered
get_state(Prh[i][j][k], geom, &q);
for (int mu = 0; mu < NDIM; mu++) {
C += -q.ucon[mu] * radG[i][j][k][mu];
}
// Get fluid state at n+1 for full update
get_state(Pr[i][j][k], geom, &q);
// Remove \sqrt{-g} from radG
C = C / geom->g;
Urho = Pr[i][j][k][RHO] * q.ucon[0];
Uel = Pr[i][j][k][KEL] * Urho;
Uel += Dt * (C * (game - 1.) * pow(Prh[i][j][k][RHO], 1. - game));
// Supercooling diagnostics
if (Uel < 0.) {
double U_1[NVAR], prim_2[NVAR], U_2[NVAR];
struct of_state q_1, q_2;
Nsuper[i][j][k]++;
// (1) Record total energy density after cooling
get_state(Pr[i][j][k], &ggeom[i][j][CENT], &q_1);
primtoflux(Pr[i][j][k], &q_1, 0, 0, &ggeom[i][j][CENT], U_1);
// (2) Calculate total energy density with zero electron energy density
PLOOP prim_2[ip] = psupersave[i][j][k][ip];
double ue = prim_2[KEL] * pow(prim_2[RHO], game) / (game - 1.);
prim_2[UU] -= ue;
get_state(prim_2, &ggeom[i][j][CENT], &q_2);
primtoflux(prim_2, &q_2, 0, 0, &ggeom[i][j][CENT], U_2);
// Subtract (2) from (1); integrated over volume, this is fake energy
Esuper[i][j][k] += fabs((U_1[UU] - U_2[UU]) * dx[1] * dx[2] * dx[3]);
} // Uel < 0
Pr[i][j][k][KEL] = Uel / Urho;
// Reset total entropy
Pr[i][j][k][KTOT] =
(gam - 1.) * Pr[i][j][k][UU] * pow(Pr[i][j][k][RHO], -gam);
} // ZSLOOP
}
#endif // RADIATION
void fixup_electrons(grid_prim_type P) {
timer_start(TIMER_ELECTRON);
#pragma omp parallel for collapse(3) schedule(dynamic)
ZLOOP { fixup_electrons_1zone(P[i][j][k]); }
timer_stop(TIMER_ELECTRON);
}
void fixup_electrons_1zone(double P[NVAR]) {
double kelmax =
P[KTOT] * pow(P[RHO], gam - game) / (tptemin + (gam - 1.) / (game - 1.));
double kelmin =
P[KTOT] * pow(P[RHO], gam - game) / (tptemax + (gam - 1.) / (game - 1.));
// Replace NANs with cold electrons
if (isnan(P[KEL]))
P[KEL] = kelmin;
// Enforce maximum Tp/Te
P[KEL] = MY_MAX(P[KEL], kelmin);
// Enforce minimum Tp/Te
P[KEL] = MY_MIN(P[KEL], kelmax);
}
#endif // EOS == EOS_TYPE_GAMMA
#endif // ELECTRONS
| {
"alphanum_fraction": 0.5265423242,
"avg_line_length": 32.4186046512,
"ext": "c",
"hexsha": "6b37ceeabce08661c16a0ed44710dc9fdefc46d9",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-12-10T21:42:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-21T04:59:44.000Z",
"max_forks_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "soumide1102/nubhlight",
"max_forks_repo_path": "core/electrons.c",
"max_issues_count": 13,
"max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772",
"max_issues_repo_issues_event_max_datetime": "2021-06-15T20:00:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T02:10:48.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "soumide1102/nubhlight",
"max_issues_repo_path": "core/electrons.c",
"max_line_length": 80,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "soumide1102/nubhlight",
"max_stars_repo_path": "core/electrons.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T11:05:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-05T22:59:21.000Z",
"num_tokens": 3348,
"size": 9758
} |
#include <math.h>
#include <stdio.h>
//#include "gsl_headers.h"
#include <iostream>
//#include "laplaceEP.h"
//#include "matrix.h"
#include <time.h>
//#include <dai/alldai.h>
//#include <dai/bp.h>
// #include <map>
// #include <boost/shared_ptr.hpp>
// #include <string>
//
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include "gsl/gsl_cdf.h"
#include "gsl/gsl_randist.h"
//Transformations
double fre_1(double x, double func, double mu, double w);
double f_1(double x, double func, double mu, double w);
// double f(double x, double w);
// General functions
double compute_vector_mean(int N, double missing, gsl_vector *v);
double compute_vector_var(int N, double missing, gsl_vector *v);
double compute_vector_max(int N, double missing, gsl_vector *v);
double compute_vector_min(int N, double missing, gsl_vector *v);
int factorial (int N);
int poissrnd(double lambda);
//gsl_matrix *double2gsl(double *Amat, int nRows, int nCols);
void matrix_multiply(gsl_matrix *A,gsl_matrix *B,gsl_matrix *C,double alpha,double beta,CBLAS_TRANSPOSE_t TransA,CBLAS_TRANSPOSE_t TransB);
double *column_to_row_major_order(double *A,int nRows,int nCols);
//double *row_to_column_major_order(double *A,int nRows,int nCols);
double det_get(gsl_matrix *Amat, int Arows, int Acols, int inPlace);
double lndet_get(gsl_matrix *Amat, int Arows, int Acols, int inPlace);
// gsl_matrix *inverse(gsl_matrix *Amat, int Asize);
void inverse(gsl_matrix *Amat, int Asize);
double trace(gsl_matrix *Amat, int Asize);
double logFun(double x);
double expFun(double x);
//Sampling functions
int mnrnd(double *p, int nK);
void mvnrnd(gsl_vector *X, gsl_matrix *Sigma,gsl_vector *Mu, int K, const gsl_rng *seed);
double truncnormrnd(double mu, double sigma, double xlo, double xhi);
| {
"alphanum_fraction": 0.7511811024,
"avg_line_length": 32.8448275862,
"ext": "h",
"hexsha": "260626c8dd0244c06ad8f743b3b25923aa3ce862",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-02-18T07:18:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-04T01:53:41.000Z",
"max_forks_repo_head_hexsha": "b219c650d0429ea71b953743730ae53cc122a61b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ferjorosa/test-glfm",
"max_forks_repo_path": "src/Ccode/core/GeneralFunctions.h",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "b219c650d0429ea71b953743730ae53cc122a61b",
"max_issues_repo_issues_event_max_datetime": "2019-10-11T01:54:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-18T13:22:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ferjorosa/test-glfm",
"max_issues_repo_path": "src/Ccode/core/GeneralFunctions.h",
"max_line_length": 139,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "b219c650d0429ea71b953743730ae53cc122a61b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ferjorosa/test-glfm",
"max_stars_repo_path": "src/Ccode/core/GeneralFunctions.h",
"max_stars_repo_stars_event_max_datetime": "2021-10-18T20:01:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-07T03:43:25.000Z",
"num_tokens": 551,
"size": 1905
} |
/*
Copyright [2017-2021] [IBM Corporation]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _MCAS_HSTORE_NUPM_H
#define _MCAS_HSTORE_NUPM_H
#include "pool_manager.h"
#include "alloc_key.h" /* AK_FORMAL */
#include "hstore_nupm_types.h"
#include "hstore_open_pool.h"
#include "persister_nupm.h"
#include <common/string_view.h>
#include <gsl/pointers>
#include <cstring> /* strerror */
#include <cinttypes> /* PRIx64 */
#include <cstdlib> /* getenv */
struct dax_manager;
template <typename PersistData, typename Heap>
struct region;
#pragma GCC diagnostic push
/* Note: making enable_shared_from_this private avoids the non-virtual-dtor error but
* generates a different error with no error text (G++ 5.4.0)
*/
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
/* Region is region<persist_data_t, heap_rc>, Table is hstore::table_t Allocator is table_t::allocator_type, LockType is hstore::locK_type_t */
template <typename Region, typename Table, typename Allocator, typename LockType>
struct hstore_nupm
: public pool_manager<::open_pool<non_owner<Region>>>
{
using region_type = Region;
private:
using table_t = Table;
using allocator_t = Allocator;
using lock_type_t = LockType;
using string_view = common::string_view;
public:
using open_pool_handle = ::open_pool<non_owner<region_type>>;
using base = pool_manager<open_pool_handle>;
private:
std::unique_ptr<dax_manager> _dax_manager;
unsigned _numa_node;
static unsigned name_to_numa_node(const string_view name);
public:
hstore_nupm(unsigned debug_level_, const string_view, const string_view name_, std::unique_ptr<dax_manager> mgr_);
virtual ~hstore_nupm();
const std::unique_ptr<dax_manager> & get_dax_manager() const override { return _dax_manager; }
void pool_create_check(std::size_t) override;
auto pool_create_1(
const pool_path &path_
, std::size_t size_
) -> nupm::region_descriptor override;
auto pool_create_2(
AK_FORMAL
const nupm::region_descriptor &rac
, component::IKVStore::flags_t flags
, std::size_t expected_obj_count
) -> std::unique_ptr<open_pool_handle> override;
nupm::region_descriptor pool_open_1(
const pool_path &path_
) override;
auto pool_open_2(
AK_FORMAL
const nupm::region_descriptor & v_
, component::IKVStore::flags_t flags_
) -> std::unique_ptr<open_pool_handle> override;
void pool_close_check(const string_view) override;
void pool_delete(const pool_path &path_) override;
/* ERROR: want get_pool_regions(<proper type>, std::vector<::iovec>&) */
nupm::region_descriptor pool_get_regions(const open_pool_handle &) const override;
};
#pragma GCC diagnostic pop
#include "hstore_nupm.tcc"
#endif
| {
"alphanum_fraction": 0.7343797163,
"avg_line_length": 31.5523809524,
"ext": "h",
"hexsha": "456e92b13b32370cc1b2e4b8c8544c8ab30adf51",
"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": "efaf438eb20cffa18b13f176c74a2b3153f89c07",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "fQuinzan/mcas",
"max_forks_repo_path": "src/components/store/hstore/src/hstore_nupm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07",
"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": "fQuinzan/mcas",
"max_issues_repo_path": "src/components/store/hstore/src/hstore_nupm.h",
"max_line_length": 143,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "fQuinzan/mcas",
"max_stars_repo_path": "src/components/store/hstore/src/hstore_nupm.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 823,
"size": 3313
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C code for the initialization of the instrumental noise for LIGO/VIRGO detectors.
*
*/
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#include "LLVnoise.h"
/******************************************************************************/
/****** Global variables storing interpolating splines for the noise PSD ******/
gsl_spline* __LLVSimFD_LHONoiseSpline_init = NULL; /* for initialization only */
gsl_spline** const __LLVSimFD_LHONoiseSpline = &__LLVSimFD_LHONoiseSpline_init;
gsl_spline* __LLVSimFD_LLONoiseSpline_init = NULL; /* for initialization only */
gsl_spline** const __LLVSimFD_LLONoiseSpline = &__LLVSimFD_LLONoiseSpline_init;
gsl_spline* __LLVSimFD_VIRGONoiseSpline_init = NULL; /* for initialization only */
gsl_spline** const __LLVSimFD_VIRGONoiseSpline = &__LLVSimFD_VIRGONoiseSpline_init;
gsl_interp_accel* __LLVSimFD_LHONoiseAccel_init = NULL; /* for initialization only */
gsl_interp_accel** const __LLVSimFD_LHONoiseAccel = &__LLVSimFD_LHONoiseAccel_init;
gsl_interp_accel* __LLVSimFD_LLONoiseAccel_init = NULL; /* for initialization only */
gsl_interp_accel** const __LLVSimFD_LLONoiseAccel = &__LLVSimFD_LLONoiseAccel_init;
gsl_interp_accel* __LLVSimFD_VIRGONoiseAccel_init = NULL; /* for initialization only */
gsl_interp_accel** const __LLVSimFD_VIRGONoiseAccel = &__LLVSimFD_VIRGONoiseAccel_init;
double __LLVSimFD_LHONoise_fLow = 0;
double __LLVSimFD_LHONoise_fHigh = 0;
double __LLVSimFD_LLONoise_fLow = 0;
double __LLVSimFD_LLONoise_fHigh = 0;
double __LLVSimFD_VIRGONoise_fLow = 0;
double __LLVSimFD_VIRGONoise_fHigh = 0;
int __LLVSimFD_Noise_setup = FAILURE;
/* The number of points in the noise data files - required as the Read_Vector function needs a gsl vector already initialized to the right length */
//#define noisedata_pts 3000
#define noisedata_pts 16365
/**************************************************************/
/****** Functions loading and evaluating the noise PSD *******/
/* Function parsing the environment variable $LLV_NOISE_DATA_PATH and trying to run LLVSimFD_Noise_Init in each */
int LLVSimFD_Noise_Init_ParsePath(void)
{
if (!__LLVSimFD_Noise_setup) return(SUCCESS);
int ret = FAILURE;
char *envpath = NULL;
char path[32768];
char *brkt, *word;
envpath = getenv("LLV_NOISE_DATA_PATH");
if(!envpath) {
printf("Error: the environment variable LLV_NOISE_DATA_PATH, giving the path to the noise data, seems undefined\n");
exit(1);
}
strncpy(path, envpath, sizeof(path));
for(word=strtok_r(path,":",&brkt); word; word=strtok_r(NULL,":",&brkt))
{
//printf("%s\n", word);
ret = LLVSimFD_Noise_Init(word);
if(ret == SUCCESS) break;
}
if(ret!=SUCCESS) {
printf("Error: unable to find LLVSimFD noise data files in $LLV_NOISE_DATA_PATH\n");
exit(FAILURE);
}
__LLVSimFD_Noise_setup = ret;
return(ret);
}
/* Function loading the noise data from a directory */
int LLVSimFD_Noise_Init(const char dir[]) {
if(!__LLVSimFD_Noise_setup) {
printf("Error: LLVSimFD noise was already set up!");
exit(1);
}
/* Loading noise data in gsl_vectors */
int ret = SUCCESS;
gsl_matrix* noise_LHO = gsl_matrix_alloc(noisedata_pts, 2);
gsl_matrix* noise_LLO = gsl_matrix_alloc(noisedata_pts, 2);
gsl_matrix* noise_VIRGO = gsl_matrix_alloc(noisedata_pts, 2);
char* file_LIGO = malloc(strlen(dir)+64);
char* file_VIRGO = malloc(strlen(dir)+64);
//sprintf(file_LIGO, "%s", "LIGO-P1200087-v18-aLIGO_DESIGN.txt");
//sprintf(file_VIRGO, "%s", "LIGO-P1200087-v18-AdV_DESIGN.txt");
sprintf(file_LIGO, "%s", "aLIGO_sensitivity.dat");
sprintf(file_VIRGO, "%s", "aVirgo_sensitivity.dat");
ret |= Read_Text_Matrix(dir, file_LIGO, noise_LHO);
ret |= Read_Text_Matrix(dir, file_LIGO, noise_LLO);
ret |= Read_Text_Matrix(dir, file_VIRGO, noise_VIRGO);
if(ret==FAILURE) {
printf("Error: problem reading LLV noise data.");
exit(1);
}
/* Linear interpolation of the data, after setting the gsl_spline structures */
else if(ret==SUCCESS) {
/* Extracting te vectors for the frequencies and data */
gsl_vector* noise_LHO_freq = gsl_vector_alloc(noisedata_pts);
gsl_vector* noise_LLO_freq = gsl_vector_alloc(noisedata_pts);
gsl_vector* noise_VIRGO_freq = gsl_vector_alloc(noisedata_pts);
gsl_vector* noise_LHO_data = gsl_vector_alloc(noisedata_pts);
gsl_vector* noise_LLO_data = gsl_vector_alloc(noisedata_pts);
gsl_vector* noise_VIRGO_data = gsl_vector_alloc(noisedata_pts);
gsl_matrix_get_col(noise_LHO_freq, noise_LHO, 0);
gsl_matrix_get_col(noise_LLO_freq, noise_LLO, 0);
gsl_matrix_get_col(noise_VIRGO_freq, noise_VIRGO, 0);
gsl_matrix_get_col(noise_LHO_data, noise_LHO, 1);
gsl_matrix_get_col(noise_LLO_data, noise_LLO, 1);
gsl_matrix_get_col(noise_VIRGO_data, noise_VIRGO, 1);
/* Setting the global variables that indicate the range in frequency of these splines */
__LLVSimFD_LHONoise_fLow = gsl_vector_get(noise_LHO_freq, 0);
__LLVSimFD_LHONoise_fHigh = gsl_vector_get(noise_LHO_freq, noise_LHO_freq->size - 1);
__LLVSimFD_LLONoise_fLow = gsl_vector_get(noise_LLO_freq, 0);
__LLVSimFD_LLONoise_fHigh = gsl_vector_get(noise_LLO_freq, noise_LLO_freq->size - 1);
__LLVSimFD_VIRGONoise_fLow = gsl_vector_get(noise_VIRGO_freq, 0);
__LLVSimFD_VIRGONoise_fHigh = gsl_vector_get(noise_VIRGO_freq, noise_VIRGO_freq->size - 1);
/* Initializing the splines and accelerators */
*__LLVSimFD_LHONoiseSpline = gsl_spline_alloc(gsl_interp_linear, noisedata_pts);
*__LLVSimFD_LLONoiseSpline = gsl_spline_alloc(gsl_interp_linear, noisedata_pts);
*__LLVSimFD_VIRGONoiseSpline = gsl_spline_alloc(gsl_interp_linear, noisedata_pts);
*__LLVSimFD_LHONoiseAccel = gsl_interp_accel_alloc();
*__LLVSimFD_LLONoiseAccel = gsl_interp_accel_alloc();
*__LLVSimFD_VIRGONoiseAccel = gsl_interp_accel_alloc();
gsl_spline_init(*__LLVSimFD_LHONoiseSpline, gsl_vector_const_ptr(noise_LHO_freq, 0), gsl_vector_const_ptr(noise_LHO_data, 0), noisedata_pts);
gsl_spline_init(*__LLVSimFD_LLONoiseSpline, gsl_vector_const_ptr(noise_LLO_freq, 0), gsl_vector_const_ptr(noise_LLO_data, 0), noisedata_pts);
gsl_spline_init(*__LLVSimFD_VIRGONoiseSpline, gsl_vector_const_ptr(noise_VIRGO_freq, 0), gsl_vector_const_ptr(noise_VIRGO_data, 0), noisedata_pts);
/* Setting the global tag to success and clean up */
gsl_matrix_free(noise_LHO);
gsl_matrix_free(noise_LLO);
gsl_matrix_free(noise_VIRGO);
gsl_vector_free(noise_LHO_freq);
gsl_vector_free(noise_LLO_freq);
gsl_vector_free(noise_VIRGO_freq);
gsl_vector_free(noise_LHO_data);
gsl_vector_free(noise_LLO_data);
gsl_vector_free(noise_VIRGO_data);
__LLVSimFD_Noise_setup = SUCCESS;
}
/* Cleaning and output */
free(file_LIGO);
free(file_VIRGO);
return(ret);
}
/* The noise functions themselves */
double NoiseSnLHO(const double f) {
if(__LLVSimFD_Noise_setup==FAILURE) {
printf("Error: noise interpolation has not been set up\n");
exit(1);
}
if ((f < __LLVSimFD_LHONoise_fLow) || (f > __LLVSimFD_LHONoise_fHigh)) {
return INFINITY;
}
else {
double sqrtSn = gsl_spline_eval(*__LLVSimFD_LHONoiseSpline, f, *__LLVSimFD_LHONoiseAccel);
return sqrtSn * sqrtSn;
}
}
double NoiseSnLLO(const double f) {
if(__LLVSimFD_Noise_setup==FAILURE) {
printf("Error: noise interpolation has not been set up\n");
exit(1);
}
if ((f < __LLVSimFD_LLONoise_fLow) || (f > __LLVSimFD_LLONoise_fHigh)) {
return INFINITY;
}
else {
double sqrtSn = gsl_spline_eval(*__LLVSimFD_LLONoiseSpline, f, *__LLVSimFD_LLONoiseAccel);
return sqrtSn * sqrtSn;
}
}
double NoiseSnVIRGO(const double f) {
if(__LLVSimFD_Noise_setup==FAILURE) {
printf("Error: noise interpolation has not been set up\n");
exit(1);
}
if ((f < __LLVSimFD_VIRGONoise_fLow) || (f > __LLVSimFD_VIRGONoise_fHigh)) {
return INFINITY;
}
else {
double sqrtSn = gsl_spline_eval(*__LLVSimFD_VIRGONoiseSpline, f, *__LLVSimFD_VIRGONoiseAccel);
return sqrtSn * sqrtSn;
}
}
| {
"alphanum_fraction": 0.7424862589,
"avg_line_length": 39.587962963,
"ext": "c",
"hexsha": "22e2f15877cc01a90bf83b142946a36e56618140",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "LLVsim/LLVnoise.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "LLVsim/LLVnoise.c",
"max_line_length": 151,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "LLVsim/LLVnoise.c",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 2597,
"size": 8551
} |
#include "sly/defines.h"
#include <gsl/gsl>
#include <memory.h>
#include <optional>
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include "sly/debug/logger.h"
#include "sly/enum.h"
#include "sly/errors.h"
#include "sly/macros.h"
#include "sly/retval.h"
#include "sly/types.h"
| {
"alphanum_fraction": 0.6910299003,
"avg_line_length": 15.05,
"ext": "h",
"hexsha": "bc735191cbcc3edff39d7af3b7a3729842ee9119",
"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": "9216cf04a78f1d41af01186489ba6680b9641229",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Gibbeon/sly",
"max_forks_repo_path": "slycore/include/sly/global.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229",
"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": "Gibbeon/sly",
"max_issues_repo_path": "slycore/include/sly/global.h",
"max_line_length": 29,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Gibbeon/sly",
"max_stars_repo_path": "slycore/include/sly/global.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 89,
"size": 301
} |
#include <math.h>
#include <gsl/gsl_math.h>
#include <options/options.h>
#include "../csm/csm_all.h"
int main(int argc, const char * argv[]) {
sm_set_program_name(argv[0]);
const char*input_filename;
const char*output_filename;
double diff[3] = {0, 0, 0};
double laser[3] ={0,0,0};
double omega[2] ={0,0};
double omega_vel = 0;
double vel[2] ={0,0};
double vel_omega = 0;
struct option* ops = options_allocate(15);
options_string(ops, "in", &input_filename, "stdin", "input file");
options_string(ops, "out", &output_filename, "stdout", "output file");
options_double(ops, "l_x", &(laser[0]), 0.0, "laser x (m)");
options_double(ops, "l_y", &(laser[1]), 0.0, "laser y (m)");
options_double(ops, "l_theta", &(laser[2]), 0.0, "laser theta (rad)");
options_double(ops, "omega0", &(omega[0]), 0.0, "omega (rad)");
options_double(ops, "omega1", &(omega[1]), 0.0, "omega (linear)");
options_double(ops, "omega_vel", &(omega_vel), 0.0, "omega x vel");
options_double(ops, "vel0", &(vel[0]), 0.0, "vel (m)");
options_double(ops, "vel1", &(vel[1]), 0.0, "vel (linear)");
options_double(ops, "vel_omega", &(vel_omega), 0.0, "vel x omega");
if(!options_parse_args(ops, argc, argv)) {
fprintf(stderr, " Corrects bias in odometry.\n");
options_print_help(ops, stderr);
return -1;
}
FILE * input_stream = open_file_for_reading(input_filename);
FILE *output_stream = open_file_for_writing(output_filename);
if(!input_stream || !output_stream) return -1;
LDP laser_ref = ld_read_smart(input_stream);
if(!laser_ref) {
sm_error("Cannot read first scan.\n");
return -2;
}
copy_d(laser_ref->odometry, 3, laser_ref->estimate);
double old_odometry[3];
copy_d(laser_ref->odometry, 3, old_odometry);
LDP laser_sens;
ld_write_as_json(laser_ref, output_stream);
while((laser_sens = ld_read_smart(input_stream))) {
double guess[3], old_guess[3];
pose_diff_d(laser_sens->odometry, old_odometry, guess);
pose_diff_d(laser_sens->odometry, old_odometry, old_guess);
copy_d(laser_sens->odometry, 3, old_odometry);
if(fabs(guess[2]) > 1e-7)
guess[2] = old_guess[2] * omega[1] + omega_vel * guess[0] + omega[0];
if(fabs(guess[0]) > 1e-7)
guess[0] = old_guess[0] * vel[1] + vel_omega * guess[2] + vel[0];
fprintf(stderr, "odo: %f %f %f Corr: %f rad \t%f m \n", guess[0], guess[1], guess[2], guess[2]-old_guess[2], guess[0]-old_guess[0]);
oplus_d(laser_ref->odometry, guess, laser_sens->odometry);
oplus_d(laser_sens->odometry, laser, laser_sens->estimate);
fprintf(stderr, "ref odo: %s ref est: %s \n",
friendly_pose(laser_ref->odometry),
friendly_pose(laser_ref->estimate));
fprintf(stderr, "sens odo: %s sens est: %s \n",
friendly_pose(laser_sens->odometry),
friendly_pose(laser_sens->estimate));
ld_write_as_json(laser_sens, output_stream);
ld_free(laser_ref);
laser_ref = laser_sens;
}
return 0;
}
| {
"alphanum_fraction": 0.6688333904,
"avg_line_length": 29.8265306122,
"ext": "c",
"hexsha": "5b4e74f96f4a6ee41e26cdca76226f735c790e13",
"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": "509223ef116f307d443e9a058923ad42f0c507e9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ozaslan/basics",
"max_forks_repo_path": "csm/sm/apps/ld_correct.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9",
"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": "ozaslan/basics",
"max_issues_repo_path": "csm/sm/apps/ld_correct.c",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ozaslan/basics",
"max_stars_repo_path": "csm/sm/apps/ld_correct.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 979,
"size": 2923
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#ifndef __DRIVERS_common_utils_h__
#define __DRIVERS_common_utils_h__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
#include <petscpc.h>
#include <petscksp.h>
#include <petscsnes.h>
#include <petscversion.h>
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )
#if (PETSC_VERSION_MINOR >=6)
#include "petsc/private/vecimpl.h"
#include "petsc/private/matimpl.h"
#include "petsc/private/pcimpl.h"
#include "petsc/private/kspimpl.h"
#include "petsc/private/snesimpl.h"
#else
#include "petsc-private/vecimpl.h"
#include "petsc-private/matimpl.h"
#include "petsc-private/pcimpl.h"
#include "petsc-private/kspimpl.h"
#include "petsc-private/snesimpl.h"
#endif
#else
#include "private/vecimpl.h"
#include "private/matimpl.h"
#include "private/pcimpl.h"
#include "private/kspimpl.h"
#include "private/snesimpl.h"
#endif
#include "../../../../StgDomain/Utils/src/PETScCompatibility.h"
#include "pc_GtKG.h"
#include "pc_ScaledGtKG.h"
#include "stokes_block_scaling.h"
#include "stokes_mvblock_scaling.h"
#include "ksp_scale.h"
/* BSSCR_create_execute_script.c */
int BSSCR_create_execute_script( void );
/* create_petsc_header.c */
PetscErrorCode BSSCR_GeneratePetscHeader_for_file( FILE *fd, MPI_Comm comm );
PetscErrorCode BSSCR_GeneratePetscHeader_for_viewer( PetscViewer viewer );
/* MatIdentityOperator.c */
//PetscErrorCode MatCreateIdentityOperator( Mat A, Mat *_I );
/* read_matrices.c */
//PetscErrorCode StokesReadOperators( MPI_Comm comm, Mat *K, Mat *G, Mat *D, Mat *C, Vec *f, Vec *h );
/* stokes_residual.c */
double BSSCR_StokesMomentumResidual( Mat K, Mat G, Vec F, Vec u, Vec p );
double BSSCR_StokesContinuityResidual( Mat G, Mat C, Vec H, Vec u, Vec p );
/* preconditioner.c */
PetscErrorCode BSSCR_StokesReadPCSchurMat( MPI_Comm comm, Mat *S );
PetscErrorCode BSSCR_StokesCreatePCSchur( Mat K, Mat G, PC pc_S );
/* nullspace */
/*
PetscErrorCode BSSCR_MatGtKinvG_ContainsConstantNullSpace(
Mat K, Mat G, Mat M,Vec t1, Vec ustar, Vec r, Vec l,
KSP ksp, PetscTruth *has_cnst_nullsp );
PetscErrorCode BSSCR_VecRemoveConstNullspace(Vec v, Vec nsp_vec);
*/
/* PetscErrorCode BSSCR_MatContainsConstantNullSpace( Mat A, PetscTruth *has_cnst_nullsp ); */
//PetscErrorCode BSSCR_MatContainsConstNullSpace(Mat A, Vec nsp_vec, PetscTruth *has);
/* timed residuals */
//PetscErrorCode KSPLogDestroyMonitor(KSP ksp);
PetscErrorCode BSSCR_KSPLogSetMonitor(KSP ksp,PetscInt len,PetscInt *monitor_index);
PetscErrorCode BSSCR_KSPLogGetTimeHistory(KSP ksp,PetscInt monitor_index,PetscInt *na,PetscLogDouble **log);
PetscErrorCode BSSCR_KSPLogGetResidualHistory(KSP ksp,PetscInt monitor_index,PetscInt *na,PetscReal **rlog);
PetscErrorCode BSSCR_KSPLogGetResidualTimeHistory(KSP ksp,PetscInt monitor_index,PetscInt *na,PetscReal **rlog,PetscLogDouble **tlog);
PetscErrorCode BSSCR_KSPLogSolve(PetscViewer v,PetscInt monitor_index,KSP ksp);
PetscErrorCode BSSCR_BSSCR_KSPLogSolveSummary(PetscViewer v,PetscInt monitor_index,KSP ksp);
/* operator summary */
PetscErrorCode BSSCR_MatInfoLog(PetscViewer v,Mat A,const char name[]);
PetscErrorCode BSSCR_VecInfoLog(PetscViewer v,Vec x,const char name[]);
PetscErrorCode BSSCR_StokesCreateOperatorSummary( Mat K, Mat G, Mat C, Vec f, Vec h, const char filename[] );
/* standard output */
PetscErrorCode BSSCR_solver_output( KSP ksp, PetscInt monitor_index, const char res_file[], const char solver_conf[] );
PetscErrorCode BSSCR_KSPLogConvergenceRate(PetscViewer v,PetscInt monitor_index, KSP ksp);
/* list available operations */
PetscErrorCode BSSCR_MatListOperations( Mat A, PetscViewer v );
PetscErrorCode BSSCR_VecListOperations( Vec x, PetscViewer v );
PetscErrorCode BSSCR_KSPListOperations( KSP ksp, PetscViewer v );
PetscErrorCode BSSCR_PCListOperations( PC pc, PetscViewer v );
PetscErrorCode BSSCR_SNESListOperations( SNES snes, PetscViewer v );
/* Register any petsc objects defined in drivers */
PetscErrorCode BSSCR_PetscExtStokesSolversInitialize( void );
PetscErrorCode BSSCR_PetscExtStokesSolversFinalize( void );
/* stokes block */
/*
PetscErrorCode BSSCR_CreateStokesBlockOperators( MPI_Comm comm,
Mat K, Mat G, Mat D, Mat C,
Vec u, Vec p, Vec f, Vec h,
Mat *A, Vec *x, Vec *b );
*/
/* stokes output */
PetscErrorCode BSSCR_stokes_output( PetscViewer v, Mat stokes_A, Vec stokes_b, Vec stokes_x, KSP ksp, PetscInt monitor_index );
//PetscErrorCode BSSCR_NSPRemoveAll(Vec v, void *_data);
//PetscErrorCode BSSCR_CheckNullspace(KSP ksp_S, Mat S, Vec h_hat, MatStokesBlockScaling BA, Vec * _nsp_vec);
#endif
| {
"alphanum_fraction": 0.7016381373,
"avg_line_length": 38.5319148936,
"ext": "h",
"hexsha": "76a9784e7167998eea664caf494c34db6e5067fb",
"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/common-driver-utils.h",
"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/common-driver-utils.h",
"max_line_length": 134,
"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/common-driver-utils.h",
"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": 1646,
"size": 5433
} |
#ifndef CTETRA_SUBMESH_H
#define CTETRA_SUBMESH_H
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include "ecache.h"
void submesh_ijk_to_k(int na, int nb, int nc, int i, int j, int k, double k_opt[3]);
int submesh_ijk_index(int na, int nb, int nc, int i, int j, int k);
int **subcells_around_ijk(int na, int nb, int nc, int i, int j, int k, int *subcell_num);
void get_k_orig(double k_opt[3], int G_order[3], int G_neg[3], double k_orig[3]);
void MinMaxVals(EnergyCache *Ecache, double *emin, double *emax);
void OptimizeGs(gsl_matrix *R, int G_order[3], int G_neg[3]);
#endif // CTETRA_SUBMESH_H
| {
"alphanum_fraction": 0.7223042836,
"avg_line_length": 28.2083333333,
"ext": "h",
"hexsha": "df3087e6b0b9cac3d93f00fa298d2137b96379d1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/ctetra",
"max_forks_repo_path": "submesh.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/ctetra",
"max_issues_repo_path": "submesh.h",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/ctetra",
"max_stars_repo_path": "submesh.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 228,
"size": 677
} |
/* vector/gsl_vector_uint.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_UINT_H__
#define __GSL_VECTOR_UINT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_uint.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
unsigned int *data;
gsl_block_uint *block;
int owner;
}
gsl_vector_uint;
typedef struct
{
gsl_vector_uint vector;
} _gsl_vector_uint_view;
typedef _gsl_vector_uint_view gsl_vector_uint_view;
typedef struct
{
gsl_vector_uint vector;
} _gsl_vector_uint_const_view;
typedef const _gsl_vector_uint_const_view gsl_vector_uint_const_view;
/* Allocation */
GSL_FUN gsl_vector_uint *gsl_vector_uint_alloc (const size_t n);
GSL_FUN gsl_vector_uint *gsl_vector_uint_calloc (const size_t n);
GSL_FUN gsl_vector_uint *gsl_vector_uint_alloc_from_block (gsl_block_uint * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_uint *gsl_vector_uint_alloc_from_vector (gsl_vector_uint * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_uint_free (gsl_vector_uint * v);
/* Views */
GSL_FUN _gsl_vector_uint_view
gsl_vector_uint_view_array (unsigned int *v, size_t n);
GSL_FUN _gsl_vector_uint_view
gsl_vector_uint_view_array_with_stride (unsigned int *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_uint_const_view
gsl_vector_uint_const_view_array (const unsigned int *v, size_t n);
GSL_FUN _gsl_vector_uint_const_view
gsl_vector_uint_const_view_array_with_stride (const unsigned int *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_uint_view
gsl_vector_uint_subvector (gsl_vector_uint *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_uint_view
gsl_vector_uint_subvector_with_stride (gsl_vector_uint *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_uint_const_view
gsl_vector_uint_const_subvector (const gsl_vector_uint *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_uint_const_view
gsl_vector_uint_const_subvector_with_stride (const gsl_vector_uint *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_FUN void gsl_vector_uint_set_zero (gsl_vector_uint * v);
GSL_FUN void gsl_vector_uint_set_all (gsl_vector_uint * v, unsigned int x);
GSL_FUN int gsl_vector_uint_set_basis (gsl_vector_uint * v, size_t i);
GSL_FUN int gsl_vector_uint_fread (FILE * stream, gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_fwrite (FILE * stream, const gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_fscanf (FILE * stream, gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_fprintf (FILE * stream, const gsl_vector_uint * v,
const char *format);
GSL_FUN int gsl_vector_uint_memcpy (gsl_vector_uint * dest, const gsl_vector_uint * src);
GSL_FUN int gsl_vector_uint_reverse (gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_swap (gsl_vector_uint * v, gsl_vector_uint * w);
GSL_FUN int gsl_vector_uint_swap_elements (gsl_vector_uint * v, const size_t i, const size_t j);
GSL_FUN unsigned int gsl_vector_uint_max (const gsl_vector_uint * v);
GSL_FUN unsigned int gsl_vector_uint_min (const gsl_vector_uint * v);
GSL_FUN void gsl_vector_uint_minmax (const gsl_vector_uint * v, unsigned int * min_out, unsigned int * max_out);
GSL_FUN size_t gsl_vector_uint_max_index (const gsl_vector_uint * v);
GSL_FUN size_t gsl_vector_uint_min_index (const gsl_vector_uint * v);
GSL_FUN void gsl_vector_uint_minmax_index (const gsl_vector_uint * v, size_t * imin, size_t * imax);
GSL_FUN int gsl_vector_uint_add (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_FUN int gsl_vector_uint_sub (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_FUN int gsl_vector_uint_mul (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_FUN int gsl_vector_uint_div (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_FUN int gsl_vector_uint_scale (gsl_vector_uint * a, const unsigned int x);
GSL_FUN int gsl_vector_uint_add_constant (gsl_vector_uint * a, const double x);
GSL_FUN int gsl_vector_uint_axpby (const unsigned int alpha, const gsl_vector_uint * x, const unsigned int beta, gsl_vector_uint * y);
GSL_FUN unsigned int gsl_vector_uint_sum (const gsl_vector_uint * a);
GSL_FUN int gsl_vector_uint_equal (const gsl_vector_uint * u,
const gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_isnull (const gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_ispos (const gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_isneg (const gsl_vector_uint * v);
GSL_FUN int gsl_vector_uint_isnonneg (const gsl_vector_uint * v);
GSL_FUN INLINE_DECL unsigned int gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x);
GSL_FUN INLINE_DECL unsigned int * gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i);
GSL_FUN INLINE_DECL const unsigned int * gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
unsigned int
gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
INLINE_FUN
void
gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
INLINE_FUN
unsigned int *
gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (unsigned int *) (v->data + i * v->stride);
}
INLINE_FUN
const unsigned int *
gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const unsigned int *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_UINT_H__ */
| {
"alphanum_fraction": 0.6891696751,
"avg_line_length": 34.1975308642,
"ext": "h",
"hexsha": "816129051705621ee9b192c23c05638f9df7bc61",
"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_vector_uint.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_vector_uint.h",
"max_line_length": 134,
"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_vector_uint.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": 2027,
"size": 8310
} |
/* This file is necessary otherwise clang instantiate the bindgen tools
* multiple time concurrently which produce non-deterministic results. */
#include <cblas.h>
#include <lapacke.h>
| {
"alphanum_fraction": 0.7807486631,
"avg_line_length": 31.1666666667,
"ext": "h",
"hexsha": "ba490e1a69bd0d0d9e804a7e076a8adafeddf8cc",
"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": "2fec4031f085ccb4f32a020c9f817e3f919bfa65",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "florv/scala-offheap",
"max_forks_repo_path": "lapack-jni/src/include.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2fec4031f085ccb4f32a020c9f817e3f919bfa65",
"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": "florv/scala-offheap",
"max_issues_repo_path": "lapack-jni/src/include.h",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2fec4031f085ccb4f32a020c9f817e3f919bfa65",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "florv/scala-offheap",
"max_stars_repo_path": "lapack-jni/src/include.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 39,
"size": 187
} |
/* ===============================================================================*/
/* Version 1.0. Cullan Howlett */
/* Copyright (c) 2017 International Centre for Radio Astronomy Research, */
/* The MIT License (MIT) University of Western Australia */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in */
/* all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN */
/* THE SOFTWARE. */
/* ===============================================================================*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_integration.h>
// Fisher matrix calculation for surveys with velocity and density field measurements.
// ASSUMPTIONS:
// - Uncorrelated shot-noise between the density and velocity fields
// - I use the trapezium rule to integrate over r. There will be some error due to this, but this makes the most sense as
// we are binning the number density anyway, and it makes hella difference in the speed of the code.
// - The redshift dependence of the non-linear matter and velocity divergence power spectra is captured using linear interpolation.
// - The PV error scales as a fixed pecentage of H0*r.
// - Flat LCDM cosmology (but not necessarily GR as gammaval can be changed).
// - The damping of the velocity and density fields due to non-linear RSD is redshift independent
// The parameters necessary for the calculation
static int nparams = 4; // The number of free parameters (we can use any of beta, fsigma8, r_g, sigma_g, sigma_u)
static int Data[4] = {0,1,3,4}; // A vector of flags for the parameters we are interested in (0=beta, 1=fsigma8, 2=r_g, 3=sigma_g, 4=sigma_u). MAKE SURE THE LENGTH OF THIS VECTOR, NPARAMS AND THE ENTRIES AGREE/MAKE SENSE, OR YOU MIGHT GET NONSENSE RESULTS!!
static int nziter = 1; // Now many bins in redshift between zmin and zmax we are considering
static double zmin = 0.0; // The minimum redshift to consider (You must have power spectra that are within this range or GSL spline will error out)
static double zmax = 0.1; // The maximum redshift to consider (You must have power spectra that are within this range or GSL spline will error out)
static double Om = 0.3121; // The matter density at z=0
static double c = 299792.458; // The speed of light in km/s
static double gammaval = 0.55; // The value of gammaval to use in the forecasts (where f(z) = Om(z)^gammaval)
static double r_g = 1.0; // The cross correlation coefficient between the velocity and density fields
static double beta0 = 0.393; // The value of beta (at z=0, we'll modify this by the redshift dependent value of bias and f as required)
static double sigma80 = 0.8150; // The value of sigma8 at z=0
static double sigma_u = 13.00; // The value of the velocity damping parameter in Mpc/h. I use the values from Jun Koda's paper
static double sigma_g = 4.24; // The value of the density damping parameter in Mpc/h. I use the values from Jun Koda's paper
static double kmax = 0.2; // The maximum k to evaluate for dd, dv and vv correlations (Typical values are 0.1 - 0.2, on smaller scales the models are likely to break down).
static double survey_area[3] = {0.0, 0.0, 1.745}; // We need to know the survey area for each survey and the overlap area between the surveys (redshift survey only first, then PV survey only, then overlap.
// For fully overlapping we would have {0, 0, size_overlap}. For redshift larger than PV, we would have {size_red-size_overlap, 0, size_overlap}). Units are pi steradians, such that full sky is 4.0, half sky is 2.0 etc.
static double error_rand = 300.0; // The observational error due to random non-linear velocities (I normally use 300km/s as in Jun Koda's paper)
static double error_dist = 0.05; // The percentage error on the distance indicator (Typically 0.05 - 0.10 for SNe IA, 0.2 or more for Tully-Fisher or Fundamental Plane)
static double verbosity = 0; // How much output to give: 0 = only percentage errors on fsigma8, 1 = other useful info and nuisance parameters, 2 = full fisher and covariance matrices
// The number of redshifts and the redshifts themselves of the input matter and velocity divergence power spectra.
// These numbers are multiplied by 100, converted to ints and written in the form _z0p%02d which is then appended to the filename Pvel_file. See routine read_power.
static double nzin = 11;
static double zin[11] = {0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50};
char * Pvel_file = "./example_files/example_pk"; // The file containing the velocity divergence power spectrum. Don't include .dat as we'll append the redshifts on read in
// The files containing the number density of the surveys. First is the PV survey, then the redshift survey. These files MUST have the same binning and redshift range,
// so that the sum over redshift bins works (would be fine if we used splines), i.e., if one survey is shallower then that file must contain rows with n(z)=0.
// I also typically save nbar x 10^6 in the input file to make sure I don't lose precision when outputting small nbar values to files. This is corrected when the nbar file
// is read in, so see the read_nz() routine!
char * nbar_file[300] = {"./example_files/example_nbar_vel.dat",
"./example_files/example_nbar_red.dat"};
// Other global parameters and arrays
int NK, * NRED;
double pkkmin; // The minimum kmin to integrate over, based on the input power spectrum file
double pkkmax; // The maximum k in the input power spectrum. The maximum k to integrate over is the smallest of this or kmax
double * zarray;
double * rarray;
double * deltararray;
double * growtharray;
double ** nbararray;
double * karray, * deltakarray;
double ** pmmarray, ** pmtarray, ** pttarray;
gsl_spline * growth_spline, * r_spline;
gsl_interp_accel * growth_acc, * r_acc;
// Prototypes
double zeff_integrand(double mu, void * pin);
double mu_integrand(double mu, void * pin);
double ezinv(double x, void *p);
double rz(double red);
double growthfunc(double x, void *p);
double growthz(double red);
void read_nz();
void read_power();
// Calculates the fished matrix for a velocity survey.
int main(int argc, char **argv) {
FILE * fout;
int i, j;
// Read in the velocity divergence power spectrum output from the COPTER code (Carlson 2009)
read_power();
// Read in the number densities of the surveys
read_nz();
// Run some checks
if (!((survey_area[0] > 0.0) || (survey_area[2] > 0.0))) {
for (i=0; i<nparams; i++) {
if (Data[i] == 2) {
printf("ERROR: r_g is a free parameter, but there is no information in the density field (Fisher matrix will be singular)\n");
exit(0);
}
if (Data[i] == 3) {
printf("ERROR: sigma_g is a free parameter, but there is no information in the density field (Fisher matrix will be singular)\n");
exit(0);
}
}
}
if (!((survey_area[1] > 0.0) || (survey_area[2] > 0.0))) {
for (i=0; i<nparams; i++) {
if (Data[i] == 4) {
printf("ERROR: sigma_u is a free parameter, but there is no information in the velocity field (Fisher matrix will be singular)\n");
exit(0);
}
}
}
if ((sizeof(Data)/sizeof(*Data)) != nparams) {
printf("ERROR: Size of Data vector for parameters of interest must be equal to nparams\n");
exit(0);
}
// Calculate the Fisher matrices for all bins.
gsl_matrix * Fisher_Tot = gsl_matrix_alloc(nparams, nparams);
for (i=0; i<nparams; i++) {
for (j=0; j<nparams; j++) gsl_matrix_set(Fisher_Tot, i, j, 0.0);
}
printf("Evaluating the Fisher Matrix for %d bins between [z_min = %lf, z_max = %lf]\n", nziter, zmin, zmax);
if (verbosity == 0) printf("# zmin zmax zeff fsigma8(z_eff) percentage error(z_eff)\n");
int ziter;
for (ziter = 0; ziter<nziter; ziter++) {
double zbinwidth = (zmax-zmin)/(nziter);
double zmin_iter = ziter*zbinwidth + zmin;
double zmax_iter = (ziter+1.0)*zbinwidth + zmin;
double rzmax = gsl_spline_eval(r_spline, zmax_iter, r_acc);
double kmin = M_PI/rzmax;
if (verbosity > 0) printf("Evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\n", kmin, kmax, zmin_iter, zmax_iter);
// Calculate the effective redshift (which I base on the sum of the S/N for the density and velocity fields)
int numk;
double k_sum1 = 0.0, k_sum2 = 0.0;
for (numk=0; numk<NK; numk++) {
double k = karray[numk]+0.5*deltakarray[numk];
double deltak = deltakarray[numk];
if (k < kmin) continue;
if (k > kmax) continue;
double result, error;
double params[4] = {numk, k, zmin_iter, zmax_iter};
size_t nevals = 1000;
gsl_function F;
F.function = &zeff_integrand;
F.params = ¶ms;
gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);
gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);
gsl_integration_workspace_free(w);
k_sum1 += k*k*deltak*result;
k_sum2 += k*k*deltak;
}
double z_eff = k_sum1/k_sum2;
if (verbosity > 0) printf("Effective redshift z_eff = %lf\n", z_eff);
double growth_eff = gsl_spline_eval(growth_spline, z_eff, growth_acc);
// Calculate the fisher matrix, integrating over k, then mu, then r (r is last as it means we are effectively integrating over effective volume).
// As the input spectra are tabulated we'll just use the trapezium rule to integrate over k
gsl_matrix * Fisher = gsl_matrix_alloc(nparams, nparams);
for (i=0; i<nparams; i++) {
for (j=i; j<nparams; j++) {
double k_sum = 0.0;
for (numk=0; numk<NK; numk++) {
double k = karray[numk]+0.5*deltakarray[numk];
double deltak = deltakarray[numk];
if (k < kmin) continue;
if (k > kmax) continue;
double result, error;
double params[6] = {numk, k, Data[i], Data[j], zmin_iter, zmax_iter};
size_t nevals = 1000;
gsl_function F;
F.function = &mu_integrand;
F.params = ¶ms;
gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);
gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);
gsl_integration_workspace_free(w);
k_sum += k*k*deltak*result;
}
//printf("%d, %d, %lf\n", i, j, k_sum/(4.0*M_PI));
gsl_matrix_set(Fisher, i, j, k_sum/(4.0*M_PI));
gsl_matrix_set(Fisher, j, i, k_sum/(4.0*M_PI));
}
}
for (i=0; i<nparams; i++) {
for (j=0; j<nparams; j++) {
double val = gsl_matrix_get(Fisher_Tot, i, j) + gsl_matrix_get(Fisher, i, j);
gsl_matrix_set(Fisher_Tot, i, j, val);
}
}
if (verbosity == 2) {
printf("Fisher Matrix\n======================\n");
for (i=0; i<nparams; i++) {
printf("[");
for (j=0; j<nparams; j++) printf("%15.6lf,\t", gsl_matrix_get(Fisher, i, j));
printf("],\n");
}
}
// Now invert the Fisher matrix
int s;
gsl_permutation * p;
gsl_matrix * Covariance = gsl_matrix_alloc(nparams, nparams);
p = gsl_permutation_alloc(nparams);
gsl_linalg_LU_decomp(Fisher, p, &s);
gsl_linalg_LU_invert(Fisher, p, Covariance);
gsl_permutation_free(p);
double sigma8 = sigma80 * growth_eff;
double Omz = Om*ezinv(z_eff,NULL)*ezinv(z_eff,NULL)*(1.0+z_eff)*(1.0+z_eff)*(1.0+z_eff);
double f = pow(Omz, gammaval);
double beta = f*beta0*growth_eff/pow(Om,0.55);
if (verbosity == 0) {
for (i=0; i<nparams; i++) {
if (Data[i] == 1) printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\n", zmin_iter, zmax_iter, z_eff, f*sigma8, 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));
}
}
if (verbosity > 0) {
for (i=0; i<nparams; i++) {
if (Data[i] == 0) {
printf("beta = %12.6lf +/- %12.6lf\n", beta, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on beta\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/beta);
}
if (Data[i] == 1) {
printf("fsigma8 = %12.6lf +/- %12.6lf\n", f*sigma8, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on fsigma8\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));
}
if (Data[i] == 2) {
printf("r_g = %12.6lf +/- %12.6lf\n", r_g, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on r_g\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/r_g);
}
if (Data[i] == 3) {
printf("sigma_g = %12.6lf +/- %12.6lf\n", sigma_g, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on sigma_g\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_g);
}
if (Data[i] == 4) {
printf("sigma_u = %12.6lf +/- %12.6lf\n", sigma_u, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on sigma_u\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_u);
}
}
}
if (verbosity == 2) {
printf("Covariance Matrix\n======================\n");
for (i=0; i<nparams; i++) {
printf("[");
for (j=0; j<nparams; j++) printf("%15.6lf,\t", gsl_matrix_get(Covariance, i, j));
printf("],\n");
}
}
gsl_matrix_free(Fisher);
gsl_matrix_free(Covariance);
}
// Now the full Fisher matrix over all redshifts if we had more than 1 redshift bin
if (nziter > 1) {
double rzmax = gsl_spline_eval(r_spline, zmax, r_acc);
double kmin = M_PI/rzmax;
if (verbosity > 0) printf("Finally, evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\n", kmin, kmax, zmin, zmax);
// Calculate the effective redshift
int numk;
double k_sum1 = 0.0, k_sum2 = 0.0;
for (numk=0; numk<NK; numk++) {
double k = karray[numk]+0.5*deltakarray[numk];
double deltak = deltakarray[numk];
if (k < kmin) continue;
if (k > kmax) continue;
double result, error;
double params[4] = {numk, k, zmin, zmax};
size_t nevals = 1000;
gsl_function F;
F.function = &zeff_integrand;
F.params = ¶ms;
gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);
gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);
gsl_integration_workspace_free(w);
k_sum1 += k*k*deltak*result;
k_sum2 += k*k*deltak;
}
double z_eff = k_sum1/k_sum2;
if (verbosity > 0) printf("Effective redshift z_eff = %lf\n", z_eff);
double growth_eff = gsl_spline_eval(growth_spline, z_eff, growth_acc);
if (verbosity == 2) {
printf("Fisher Matrix\n======================\n");
for (i=0; i<nparams; i++) {
printf("[");
for (j=0; j<nparams; j++) printf("%15.6lf,\t", gsl_matrix_get(Fisher_Tot, i, j));
printf("],\n");
}
}
// Now invert the Fisher matrix
int s;
gsl_permutation * p;
gsl_matrix * Covariance = gsl_matrix_alloc(nparams, nparams);
p = gsl_permutation_alloc(nparams);
gsl_linalg_LU_decomp(Fisher_Tot, p, &s);
gsl_linalg_LU_invert(Fisher_Tot, p, Covariance);
gsl_permutation_free(p);
double sigma8 = sigma80 * growth_eff;
double Omz = Om*ezinv(z_eff,NULL)*ezinv(z_eff,NULL)*(1.0+z_eff)*(1.0+z_eff)*(1.0+z_eff);
double f = pow(Omz, gammaval);
double beta = f*beta0*growth_eff/pow(Om,0.55);
if (verbosity == 0) {
printf("# Full redshift range:\n");
for (i=0; i<nparams; i++) {
if (Data[i] == 1) printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\n", zmin, zmax, z_eff, f*sigma8, 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));
}
}
if (verbosity > 0) {
for (i=0; i<nparams; i++) {
if (Data[i] == 0) {
printf("beta = %12.6lf +/- %12.6lf\n", beta, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on beta\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/beta);
}
if (Data[i] == 1) {
printf("fsigma8 = %12.6lf +/- %12.6lf\n", f*sigma8, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on fsigma8\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));
}
if (Data[i] == 2) {
printf("r_g = %12.6lf +/- %12.6lf\n", r_g, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on r_g\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/r_g);
}
if (Data[i] == 3) {
printf("sigma_g = %12.6lf +/- %12.6lf\n", sigma_g, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on sigma_g\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_g);
}
if (Data[i] == 4) {
printf("sigma_u = %12.6lf +/- %12.6lf\n", sigma_u, sqrt(gsl_matrix_get(Covariance, i, i)));
printf("%4.2lf percent error on sigma_u\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_u);
}
}
}
if (verbosity == 2) {
printf("Covariance Matrix\n======================\n");
for (i=0; i<nparams; i++) {
printf("[");
for (j=0; j<nparams; j++) printf("%15.6lf,\t", gsl_matrix_get(Covariance, i, j));
printf("],\n");
}
}
}
gsl_matrix_free(Fisher_Tot);
gsl_spline_free(growth_spline);
gsl_interp_accel_free(growth_acc);
return 0;
}
// The integrand to calculate the effective redshift. I'm not actually sure how this is done in the case of
// density and velocity field measurements, but it seems logical to base it on the sum of the integral of the density spectra and the velocity power spectra
// weighted by their effective signal to noise. In this way the effective redshift is calculated in the same way as a redshift survey, but there is some dependence
// on the S/N in the velocity power spectrum too. In any case, the S/N of the density field measurement is always much higher (because there are
// no errors and the number density is higher) and so this dominates the effective redshift calculation.
double zeff_integrand(double mu, void * pin) {
int i, j, m, q, u, surv;
double * p = (double *)pin;
int numk = (int)p[0];
double k = p[1];
double zminval = p[2];
double zmaxval = p[3];
gsl_interp_accel * Pmm_acc, * Pmt_acc, * Ptt_acc;
gsl_spline * Pmm_spline, * Pmt_spline, * Ptt_spline;
if (nzin > 1) {
double * Pmm_array = (double *)malloc(nzin*sizeof(double));
double * Pmt_array = (double *)malloc(nzin*sizeof(double));
double * Ptt_array = (double *)malloc(nzin*sizeof(double));
for (j=0; j<nzin; j++) {
Pmm_array[j] = pmmarray[j][numk];
Pmt_array[j] = pmtarray[j][numk];
Ptt_array[j] = pttarray[j][numk];
}
Pmm_acc = gsl_interp_accel_alloc();
Pmm_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);
gsl_spline_init(Pmm_spline, zin, Pmm_array, nzin);
free(Pmm_array);
Pmt_acc = gsl_interp_accel_alloc();
Pmt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);
gsl_spline_init(Pmt_spline, zin, Pmt_array, nzin);
free(Pmt_array);
Ptt_acc = gsl_interp_accel_alloc();
Ptt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);
gsl_spline_init(Ptt_spline, zin, Ptt_array, nzin);
free(Ptt_array);
}
double dendamp = sqrt(1.0/(1.0+0.5*(k*k*mu*mu*sigma_g*sigma_g))); // This is unitless
double veldamp = sin(k*sigma_u)/(k*sigma_u); // This is unitless
double dVeff = 0.0, zdVeff = 0.0;
for (i=0; i<NRED[0]; i++) {
double zval = zarray[i];
if (zval < zminval) continue;
if (zval > zmaxval) break;
double r_sum = 0.0;
double r = rarray[i];
double deltar = deltararray[i];
double dd_prefac=0.0, vv_prefac=0.0;
double P_gg=0.0, P_uu=0.0;
double sigma8 = sigma80 * growtharray[i];
// First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift
double Pmm, Pmt, Ptt;
Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc);
Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc);
Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc);
double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval);
double f = pow(Omz, gammaval);
double beta = f*beta0*growtharray[i]/pow(Om,0.55);
vv_prefac = 1.0e2*f*mu*veldamp/k;
dd_prefac = (1.0/(beta*beta) + 2.0*r_g*mu*mu/beta + mu*mu*mu*mu)*f*f*dendamp*dendamp;
P_gg = dd_prefac*Pmm;
P_uu = vv_prefac*vv_prefac*Ptt;
// We need to do the overlapping and non-overlapping parts of the redshifts and PV surveys separately
for (surv=0; surv<3; surv++) {
double surv_sum = 0.0;
if (survey_area[surv] > 0.0) {
double error_obs, error_noise, n_g = 0.0, n_u = 0.0;
// Set the nbar for each section.
if (surv == 0) {
n_g = nbararray[1][i];
} else if (surv == 1) {
error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)
error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2}
n_u = nbararray[0][i]/error_noise;
} else {
error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)
error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2}
n_u = nbararray[0][i]/error_noise;
n_g = nbararray[1][i];
}
double value1 = n_g/(1.0 + n_g*P_gg);
double value2 = n_u/(1.0 + n_u*P_uu);
surv_sum += value1*value1 + value2*value2;
surv_sum *= survey_area[surv];
r_sum += surv_sum;
}
}
dVeff += r*r*deltar*r_sum;
zdVeff += zval*r*r*deltar*r_sum;
}
gsl_spline_free(Pmm_spline);
gsl_spline_free(Pmt_spline);
gsl_spline_free(Ptt_spline);
gsl_interp_accel_free(Pmm_acc);
gsl_interp_accel_free(Pmt_acc);
gsl_interp_accel_free(Ptt_acc);
return zdVeff/dVeff;
}
// The integrand for the integral over mu in the Fisher matrix calculation.
// For each mu we need to create a 4x4 matrix of the relevant power spectra derivatives and the inverse of the power spectrum matrix.
// Because there are some regions where the number density goes to zero we have to work directly with the inverse as it is difficult to invert numerically
// but if we deal with the inverse only then we can just set the relevant parts to zero when the number density is zero.
double mu_integrand(double mu, void * pin) {
int i, j, m, q, u, surv;
double * p = (double *)pin;
double result, error;
int numk = (int)p[0];
double k = p[1];
double zminval = p[4];
double zmaxval = p[5];
gsl_interp_accel * Pmm_acc, * Pmt_acc, * Ptt_acc;
gsl_spline * Pmm_spline, * Pmt_spline, * Ptt_spline;
double * Pmm_array = (double *)malloc(nzin*sizeof(double));
double * Pmt_array = (double *)malloc(nzin*sizeof(double));
double * Ptt_array = (double *)malloc(nzin*sizeof(double));
for (j=0; j<nzin; j++) {
Pmm_array[j] = pmmarray[j][numk];
Pmt_array[j] = pmtarray[j][numk];
Ptt_array[j] = pttarray[j][numk];
}
Pmm_acc = gsl_interp_accel_alloc();
Pmm_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);
gsl_spline_init(Pmm_spline, zin, Pmm_array, nzin);
free(Pmm_array);
Pmt_acc = gsl_interp_accel_alloc();
Pmt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);
gsl_spline_init(Pmt_spline, zin, Pmt_array, nzin);
free(Pmt_array);
Ptt_acc = gsl_interp_accel_alloc();
Ptt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);
gsl_spline_init(Ptt_spline, zin, Ptt_array, nzin);
free(Ptt_array);
double dendamp = sqrt(1.0/(1.0+0.5*(k*k*mu*mu*sigma_g*sigma_g))); // This is unitless
double veldamp = sin(k*sigma_u)/(k*sigma_u); // This is unitless
double result_sum = 0.0;
for (i=0; i<NRED[0]; i++) {
double zval = zarray[i];
double r_sum = 0.0;
double r = rarray[i];
double deltar = deltararray[i];
if (zval < zminval) continue;
if (zval > zmaxval) break;
double dd_prefac=0.0, dv_prefac=0.0, vv_prefac=0.0;
double P_gg=0.0, P_ug=0.0, P_uu=0.0;
double sigma8 = sigma80 * growtharray[i];
// First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift
double Pmm, Pmt, Ptt;
Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc);
Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc);
Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc);
double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval);
double f = pow(Omz, gammaval);
double beta = f*beta0*growtharray[i]/pow(Om,0.55);
vv_prefac = 1.0e2*f*mu*veldamp/k;
dd_prefac = (1.0/(beta*beta) + 2.0*r_g*mu*mu/beta + mu*mu*mu*mu)*f*f*dendamp*dendamp;
dv_prefac = (r_g/beta + mu*mu)*f*dendamp;
P_gg = dd_prefac*Pmm;
P_ug = vv_prefac*dv_prefac*Pmt;
P_uu = vv_prefac*vv_prefac*Ptt;
// And now the derivatives. Need to create a matrix of derivatives for each of the two parameters of interest
gsl_matrix * dPdt1 = gsl_matrix_calloc(2, 2);
gsl_matrix * dPdt2 = gsl_matrix_calloc(2, 2);
double value;
switch((int)p[2]) {
// Differential w.r.t betaA
case 0:
value = -2.0*(1.0/beta + r_g*mu*mu)*f*f*dendamp*dendamp*Pmm/(beta*beta);
gsl_matrix_set(dPdt1, 0, 0, value);
value = -(vv_prefac*f*r_g*dendamp*Pmt)/(beta*beta);
gsl_matrix_set(dPdt1, 0, 1, value);
gsl_matrix_set(dPdt1, 1, 0, value);
break;
// Differential w.r.t fsigma8
case 1:
value = 2.0*(f/(beta*beta) + 2.0*f*r_g*mu*mu/beta + f*mu*mu*mu*mu)*dendamp*dendamp*Pmm/sigma8;
gsl_matrix_set(dPdt1, 0, 0, value);
value = 2.0*vv_prefac*(r_g/beta + mu*mu)*dendamp*Pmt/sigma8;
gsl_matrix_set(dPdt1, 0, 1, value);
gsl_matrix_set(dPdt1, 1, 0, value);
value = (2.0*P_uu)/(f*sigma8);
gsl_matrix_set(dPdt1, 1, 1, value);
break;
// Differential w.r.t r_g
case 2:
value = 2.0*(1.0/beta)*mu*mu*f*f*dendamp*dendamp*Pmm;
gsl_matrix_set(dPdt1, 0, 0, value);
value = vv_prefac*(1.0/beta)*f*dendamp*Pmt;
gsl_matrix_set(dPdt1, 0, 1, value);
gsl_matrix_set(dPdt1, 1, 0, value);
break;
// Differential w.r.t sigma_g
case 3:
value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg;
gsl_matrix_set(dPdt1, 0, 0, value);
value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug;
gsl_matrix_set(dPdt1, 0, 1, value);
gsl_matrix_set(dPdt1, 1, 0, value);
break;
// Differential w.r.t sigma_u
case 4:
value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);
gsl_matrix_set(dPdt1, 0, 1, value);
gsl_matrix_set(dPdt1, 1, 0, value);
value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);
gsl_matrix_set(dPdt1, 1, 1, value);
break;
default:
break;
}
switch((int)p[3]) {
// Differential w.r.t betaA
case 0:
value = -2.0*(1.0/beta + r_g*mu*mu)*f*f*dendamp*dendamp*Pmm/(beta*beta);
gsl_matrix_set(dPdt2, 0, 0, value);
value = -(vv_prefac*f*r_g*dendamp*Pmt)/(beta*beta);
gsl_matrix_set(dPdt2, 0, 1, value);
gsl_matrix_set(dPdt2, 1, 0, value);
break;
// Differential w.r.t fsigma8
case 1:
value = 2.0*(f/(beta*beta) + 2.0*f*r_g*mu*mu/beta + f*mu*mu*mu*mu)*dendamp*dendamp*Pmm/sigma8;
gsl_matrix_set(dPdt2, 0, 0, value);
value = 2.0*vv_prefac*(r_g/beta + mu*mu)*dendamp*Pmt/sigma8;
gsl_matrix_set(dPdt2, 0, 1, value);
gsl_matrix_set(dPdt2, 1, 0, value);
value = (2.0*P_uu)/(f*sigma8);
gsl_matrix_set(dPdt2, 1, 1, value);
break;
// Differential w.r.t r_g
case 2:
value = 2.0*(1.0/beta)*mu*mu*f*f*dendamp*dendamp*Pmm;
gsl_matrix_set(dPdt2, 0, 0, value);
value = vv_prefac*(1.0/beta)*f*dendamp*Pmt;
gsl_matrix_set(dPdt2, 0, 1, value);
gsl_matrix_set(dPdt2, 1, 0, value);
break;
// Differential w.r.t sigma_g
case 3:
value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg;
gsl_matrix_set(dPdt2, 0, 0, value);
value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug;
gsl_matrix_set(dPdt2, 0, 1, value);
gsl_matrix_set(dPdt2, 1, 0, value);
break;
// Differential w.r.t sigma_u
case 4:
value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);
gsl_matrix_set(dPdt2, 0, 1, value);
gsl_matrix_set(dPdt2, 1, 0, value);
value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);
gsl_matrix_set(dPdt2, 1, 1, value);
break;
default:
break;
}
// We need to do the overlapping and non-overlapping parts of the surveys separately
for (surv=0; surv<3; surv++) {
double surv_sum = 0.0;
if (survey_area[surv] > 0.0) {
double error_obs, error_noise, n_g = 0.0, n_u = 0.0;
// Set the nbar for each section.
if (surv == 0) {
n_g = nbararray[1][i];
} else if (surv == 1) {
error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)
error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2}
n_u = nbararray[0][i]/error_noise;
} else {
error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)
error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2}
n_u = nbararray[0][i]/error_noise;
n_g = nbararray[1][i];
}
//printf("%lf, %lf, %lf\n", r, n_g, 1.0e6*n_u);
if (!((n_u > 0.0) || (n_g > 0.0))) continue;
// First we need the determinant.
double det = 1.0 + n_u*n_g*(P_gg*P_uu - P_ug*P_ug) + n_u*P_uu + n_g*P_gg;
// Now the inverse matrix.
gsl_matrix * iP = gsl_matrix_calloc(2, 2);
value = n_u*n_g*P_uu + n_g;
gsl_matrix_set(iP, 0, 0, value);
value = n_g*n_u*P_gg + n_u;
gsl_matrix_set(iP, 1, 1, value);
value = - n_g*n_u*P_ug;
gsl_matrix_set(iP, 0, 1, value);
gsl_matrix_set(iP, 1, 0, value);
// Finally we need to compute the Fisher integrand by summing over the inverse and differential matrices
for (j=0; j<2; j++) {
for (m=0; m<2; m++) {
for (u=0; u<2; u++) {
for (q=0; q<2; q++) {
value = gsl_matrix_get(dPdt1, j, q)*gsl_matrix_get(iP, q, u)*gsl_matrix_get(dPdt2, u, m)*gsl_matrix_get(iP, m, j);
surv_sum += value;
}
}
}
}
surv_sum /= det*det;
surv_sum *= survey_area[surv];
r_sum += surv_sum;
gsl_matrix_free(iP);
//printf("%d, %lf, %lf, %lf, %lf\n", surv, k, mu, r, r_sum);
}
}
//printf("%lf, %lf, %lf, %lf\n", k, mu, r, r_sum);
result_sum += r*r*deltar*r_sum;
gsl_matrix_free(dPdt1);
gsl_matrix_free(dPdt2);
}
gsl_spline_free(Pmm_spline);
gsl_spline_free(Pmt_spline);
gsl_spline_free(Ptt_spline);
gsl_interp_accel_free(Pmm_acc);
gsl_interp_accel_free(Pmt_acc);
gsl_interp_accel_free(Ptt_acc);
return result_sum;
}
// Routine to read in the number density as a function of redshift. We need a file containing the left-most edge of each redshift bin and teh number density in that bin.
// From this we create arrays to store the bin centre, the bin width, the comoving distance and growth factor at the bin centre and the number density.
// The last bin width and bin centre is constructed from the last row of the input and the value of zmax at the top of the code.
// ITS VERY IMPORTANT THAT THE NUMBER OF ROWS AND THE REDSHIFTS OF BOTH THE DENSITY AND PV NUMBER DENSITIES MATCH AS THE INTEGRATION OVER Z IS DONE USING THE TRAPEZIUM RULE.
// ALSO MAKE NOTE OF THE FACTOR OF 1.0e-6 ON LINE 827. THIS IS BECAUSE I TYPICALLY SAVE THE VALUE OF NBAR x 10^6 IN THE INPUT FILES< SO THAT I DON'T LOSE PRECISION
// WHEN SMALL VALUES OF THE NUMBER DENSITY ARE WRITTEN TO A FILE!
void read_nz() {
FILE * fp;
char buf[500];
int i, nsamp;
NRED = (int *)calloc(2, sizeof(int));
nbararray = (double **)calloc(2, sizeof(double*));
double * zinarray;
for (nsamp = 0; nsamp < 2; nsamp++) {
if(!(fp = fopen(nbar_file[nsamp], "r"))) {
printf("\nERROR: Can't open nbar file '%s'.\n\n", nbar_file[nsamp]);
exit(0);
}
NRED[nsamp] = 0;
while(fgets(buf,500,fp)) {
if(strncmp(buf,"#",1)!=0) {
double tz, tnbar;
if(sscanf(buf, "%lf %lf\n", &tz, &tnbar) != 2) {printf("nbar read error\n"); exit(0);};
if (tz > zmax) break;
NRED[nsamp]++;
}
}
fclose(fp);
if (nsamp == 0) zinarray = (double *)calloc(NRED[nsamp], sizeof(double));
nbararray[nsamp] = (double *)calloc(NRED[nsamp], sizeof(double));
NRED[nsamp] = 0;
fp = fopen(nbar_file[nsamp], "r");
while(fgets(buf,500,fp)) {
if(strncmp(buf,"#",1)!=0) {
double tz, tnbar;
if(sscanf(buf, "%lf %lf\n", &tz, &tnbar) != 2) {printf("nbar read error\n"); exit(0);};
if (tz > zmax) break;
if (nsamp == 0) zinarray[NRED[nsamp]] = tz;
nbararray[nsamp][NRED[nsamp]] = 1.0e-6*tnbar;
NRED[nsamp]++;
}
}
fclose(fp);
}
if (NRED[1] != NRED[0]) {
printf("ERROR: The number of redshift bins for each sample must match\n");
exit(0);
}
zarray = (double *)calloc(NRED[0], sizeof(double));
rarray = (double *)calloc(NRED[0], sizeof(double));
deltararray = (double *)calloc(NRED[0], sizeof(double));
growtharray = (double *)calloc(NRED[0], sizeof(double));
for (i=0; i<NRED[0]-1; i++) {
zarray[i] = (zinarray[i+1]+zinarray[i])/2.0;
rarray[i] = rz(zarray[i]);
deltararray[i] = rz(zinarray[i+1]) - rz(zinarray[i]);
growtharray[i] = growthz(zarray[i])/growthz(0.0);
//printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\n", zarray[i], rarray[i], deltararray[i], growtharray[i], nbararray[0][i], nbararray[1][i]);
}
zarray[NRED[0]-1] = (zmax+zinarray[NRED[0]-1])/2.0;
rarray[NRED[0]-1] = rz(zarray[NRED[0]-1]);
deltararray[NRED[0]-1] = rz(zmax) - rz(zinarray[NRED[0]-1]);
growtharray[NRED[0]-1] = growthz(zarray[NRED[0]-1])/growthz(0.0);
//printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\n", zarray[NRED[0]-1], rarray[NRED[0]-1], deltararray[NRED[0]-1], growtharray[NRED[0]-1], nbararray[0][NRED[0]-1], nbararray[1][NRED[0]-1]);
growth_acc = gsl_interp_accel_alloc();
growth_spline = gsl_spline_alloc(gsl_interp_cspline, NRED[0]);
gsl_spline_init(growth_spline, zarray, growtharray, NRED[0]);
free(zinarray);
// Also create a simple redshift-distance spline
int nbins = 400;
double REDMIN = 0.0;
double REDMAX = 2.0;
double redbinwidth = (REDMAX-REDMIN)/(double)(nbins-1);
double RMIN = rz(REDMIN);
double RMAX = rz(REDMAX);
double * ztemp = (double *)malloc(nbins*sizeof(double));
double * rtemp = (double *)malloc(nbins*sizeof(double));
for (i=0;i<nbins;i++) {
ztemp[i] = i*redbinwidth+REDMIN;
rtemp[i] = rz(ztemp[i]);
}
r_acc = gsl_interp_accel_alloc();
r_spline = gsl_spline_alloc(gsl_interp_cspline, nbins);
gsl_spline_init(r_spline, ztemp, rtemp, nbins);
free(ztemp);
free(rtemp);
return;
}
// Routine to read in the velocity power spectrum.
void read_power() {
FILE * fp;
char buf[500];
int i, j;
pmmarray = (double**)malloc(nzin*sizeof(double*));
pmtarray = (double**)malloc(nzin*sizeof(double*));
pttarray = (double**)malloc(nzin*sizeof(double*));
for (i = 0; i<nzin; i++) {
char Pvel_file_in[500];
sprintf(Pvel_file_in, "%s_z0p%02d.dat", Pvel_file, (int)(100.0*zin[i]));
if(!(fp = fopen(Pvel_file_in, "r"))) {
printf("\nERROR: Can't open power file '%s'.\n\n", Pvel_file_in);
exit(0);
}
NK = 0;
while(fgets(buf,500,fp)) {
if(strncmp(buf,"#",1)!=0) {
double tk, pkdelta, pkdeltavel, pkvel;
if(sscanf(buf, "%lf %lf %lf %lf\n", &tk, &pkdelta, &pkdeltavel, &pkvel) != 4) {printf("Pvel read error\n"); exit(0);};
NK++;
}
}
fclose(fp);
if (i == 0) {
karray = (double *)calloc(NK, sizeof(double));
deltakarray = (double *)calloc(NK-1, sizeof(double));
}
pmmarray[i] = (double *)calloc(NK, sizeof(double));
pmtarray[i] = (double *)calloc(NK, sizeof(double));
pttarray[i] = (double *)calloc(NK, sizeof(double));
NK = 0;
fp = fopen(Pvel_file_in, "r");
while(fgets(buf,500,fp)) {
if(strncmp(buf,"#",1)!=0) {
double tk, pkdelta, pkdeltavel, pkvel;
if(sscanf(buf, "%lf %lf %lf %lf\n", &tk, &pkdelta, &pkdeltavel, &pkvel) != 4) {printf("Pvel read error\n"); exit(0);};
if (i == 0) karray[NK] = tk;
pttarray[i][NK] = pkvel;
pmmarray[i][NK] = pkdelta;
pmtarray[i][NK] = pkdeltavel;
NK++;
}
}
fclose(fp);
}
for (i=0; i<NK-1; i++) deltakarray[i] = karray[i+1]-karray[i];
pkkmin = karray[0];
pkkmax = karray[NK-1];
if (pkkmax < kmax) {
printf("ERROR: The maximum k in the input power spectra id less than k_max\n");
exit(0);
}
return;
}
// Integrand for the comoving distance
double ezinv(double x, void *p) {
return 1.0/sqrt(Om*(1.0+x)*(1.0+x)*(1.0+x)+(1.0-Om));
}
// Calculates the comoving distance from the redshift
double rz(double red) {
double result, error;
gsl_function F;
gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);
F.function = &ezinv;
gsl_integration_qags(&F, 0.0, red, 0, 1e-7, 1000, w, &result, &error);
gsl_integration_workspace_free(w);
return c*result/100.0;
}
// The integrand for the normalised growth factor
double growthfunc(double x, void *p) {
double red = 1.0/x - 1.0;
double Omz = Om*ezinv(red,NULL)*ezinv(red,NULL)/(x*x*x);
double f = pow(Omz, gammaval);
return f/x;
}
// Calculates the normalised growth factor as a function of redshift given a value of gammaval
double growthz(double red) {
double result, error;
gsl_function F;
gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);
F.function = &growthfunc;
double a = 1.0/(1.0+red);
gsl_integration_qags(&F, a, 1.0, 0, 1e-7, 1000, w, &result, &error);
gsl_integration_workspace_free(w);
return exp(-result);
}
| {
"alphanum_fraction": 0.5630368958,
"avg_line_length": 44.9445564516,
"ext": "c",
"hexsha": "b8a6c4ff530a6603181965c09b58f198d3e99134",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-09-20T11:31:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-09-20T11:31:54.000Z",
"max_forks_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LBJ-Wade/PV_fisher",
"max_forks_repo_path": "PV_fisher.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15",
"max_issues_repo_issues_event_max_datetime": "2019-02-05T08:34:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-08-30T17:39:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LBJ-Wade/PV_fisher",
"max_issues_repo_path": "PV_fisher.c",
"max_line_length": 271,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LBJ-Wade/PV_fisher",
"max_stars_repo_path": "PV_fisher.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-04T11:39:16.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-01T15:07:11.000Z",
"num_tokens": 12833,
"size": 44585
} |
/**
@file
Copyright John Reid 2006
*/
#include "biopsy/defs.h"
#include <gsl/gsl_rng.h>
namespace biopsy {
gsl_rng *
get_gsl_rng();
} //namespace biopsy
| {
"alphanum_fraction": 0.6687116564,
"avg_line_length": 7.7619047619,
"ext": "h",
"hexsha": "314ba6dff7cd3c3afb32e62d607116c11f8d1d45",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JohnReid/biopsy",
"max_forks_repo_path": "C++/include/biopsy/gsl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "JohnReid/biopsy",
"max_issues_repo_path": "C++/include/biopsy/gsl.h",
"max_line_length": 24,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JohnReid/biopsy",
"max_stars_repo_path": "C++/include/biopsy/gsl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 46,
"size": 163
} |
/*
MIT License
Copyright (c) 2021 Shunji Uno <shunji_uno@iscpc.jp>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <stdint.h>
#include <math.h>
#include <float.h>
#ifdef MKL
#include <mkl.h>
#ifdef MKL_SBLAS
#include <mkl_spblas.h>
#endif /* MKL_SBLAS */
#else
#include <cblas.h>
#endif /* MKL */
#ifdef SXAT
#include <sblas.h>
#endif
#define DNRM2(N,X) cblas_dnrm2(N,X,1)
#define DDOT(N,X,Y) cblas_ddot(N,X,1,Y,1)
#define MATRIX_TYPE_INDEX0 (0)
#define MATRIX_TYPE_INDEX1 (1)
#define MATRIX_TYPE_ASYMMETRIC (0<<4)
#define MATRIX_TYPE_SYMMETRIC (1<<4)
#define MATRIX_TYPE_LOWER (1<<5)
#define MATRIX_TYPE_UPPER (0)
#define MATRIX_TYPE_UNIT (1<<6)
#define MATRIX_TYPE_NON_UNIT (0)
#define MATRIX_TYPE_CSC (0<<8)
#define MATRIX_TYPE_CSR (1<<8)
#define MATRIX_TYPE_ELLPACK (2<<8)
#define MATRIX_TYPE_JAD (3<<8)
#define MATRIX_TYPE_DCSC (8<<8)
#define MATRIX_TYPE_DCSR (9<<8)
#define MATRIX_TYPE_MASK (0xf<<8)
#define MATRIX_INDEX_TYPE(A) (((A)->flags)&0xf)
#define MATRIX_IS_SYMMETRIC(A) (((A)->flags)&MATRIX_TYPE_SYMMETRIC)
#define MATRIX_IS_LOWER(A) (((A)->flags)&MATRIX_TYPE_LOWER)
#define MATRIX_IS_UNIT(A) (((A)->flags)&MATRIX_TYPE_UNIT)
#define MATRIX_IS_CSC(A) ((((A)->flags)&MATRIX_TYPE_MASK) == MATRIX_TYPE_CSC)
#define MATRIX_IS_CSR(A) ((((A)->flags)&MATRIX_TYPE_MASK) == MATRIX_TYPE_CSR)
#ifdef __cplusplus
extern "C" {
#endif
typedef struct ellpack_info {
int32_t nw;
double* COEF;
int32_t* ICOL;
} ellpack_info_t;
typedef struct jad_info {
int32_t* perm;
int32_t* ptr;
int32_t* index;
double* value;
int32_t maxnzr;
} jad_info_t;
typedef struct Matrix {
int NROWS;
int NNZ;
uint32_t flags;
int* pointers;
int* indice;
double* values;
ellpack_info_t _ellpack;
jad_info_t _jad;
void* info;
#ifdef MKL
sparse_matrix_t hdl;
#endif
#ifdef SXAT
sblas_handle_t hdl;
#endif
#ifdef SSL2
double *w;
int *iw;
#endif
int optimized;
} Matrix_t;
/*
* Generic Matrix operations
*/
void Matrix_init_generic(Matrix_t *A);
void Matrix_free_generic(Matrix_t *A);
int Matrix_optimize_generic(Matrix_t *A);
int Matrix_MV_generic(const Matrix_t *A, const double alpha, const double* x, const double beta, const double* y, double* z);
/*
* Architecture dependent Matrix operations (prototype for override)
*/
void Matrix_init(Matrix_t *A);
void Matrix_free(Matrix_t *A);
int Matrix_optimize(Matrix_t *A);
int Matrix_MV(const Matrix_t *A, const double alpha, const double* x, const double beta, const double* y, double* z);
/*
* Architecture independent functions
*/
void Matrix_setMatrixCSR(Matrix_t *A, const int nrows, const int nnz, const int *aptr,
const int *aind, const double *aval, const uint32_t flags);
Matrix_t* Matrix_duplicate(const Matrix_t* A);
int Matrix_convert_index(Matrix_t* A, int base);
int Matrix_transpose(Matrix_t* A);
int Matrix_extract_symmetric(Matrix_t* A);
int Matrix_create_ellpack(Matrix_t* A);
int Matrix_create_jad(Matrix_t* A);
#ifdef __cplusplus
}
#endif
| {
"alphanum_fraction": 0.7300733496,
"avg_line_length": 29.0070921986,
"ext": "h",
"hexsha": "558a06721bfc626aa6b1dea75c21d0d139b3081f",
"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": "b7792f8922d8610c5e15ce99cfa7380835ce1692",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ISCPC/vesolver",
"max_forks_repo_path": "openmp/libsolver/src/common/Matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b7792f8922d8610c5e15ce99cfa7380835ce1692",
"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": "ISCPC/vesolver",
"max_issues_repo_path": "openmp/libsolver/src/common/Matrix.h",
"max_line_length": 125,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b7792f8922d8610c5e15ce99cfa7380835ce1692",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ISCPC/vesolver",
"max_stars_repo_path": "openmp/libsolver/src/common/Matrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1070,
"size": 4090
} |
#ifndef CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H
#define CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H
#include "imageoperationactioncontroller.h"
#include "s3d/cv/image_operation/image_operation.h"
#include <QAction>
#include <gsl/gsl>
class ImageOperationTriggerController : public ImageOperationActionController {
Q_OBJECT
public:
ImageOperationTriggerController(gsl::not_null<QAction*> action,
gsl::not_null<s3d::image_operation::ImageOperation*> imageOperation);
void onActionTriggered() override;
};
#endif //CONTROLLERS_UPDATERECTIFICATIONCONTROLLER_H
| {
"alphanum_fraction": 0.7937293729,
"avg_line_length": 26.347826087,
"ext": "h",
"hexsha": "dae6082e477e814d29bff59565694197d1682014",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z",
"max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hugbed/OpenS3D",
"max_forks_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtriggercontroller.h",
"max_issues_count": 40,
"max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "hugbed/OpenS3D",
"max_issues_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtriggercontroller.h",
"max_line_length": 103,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hugbed/OpenS3D",
"max_stars_repo_path": "src/apps/S3DAnalyzer/controllers/imageoperationtriggercontroller.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z",
"num_tokens": 133,
"size": 606
} |
#if !defined(compressibleFlow_h)
#define compressibleFlow_h
#include <petsc.h>
#include "fluxDifferencer.h"
typedef enum {RHO, RHOE, RHOU, RHOV, RHOW, TOTAL_COMPRESSIBLE_FLOW_COMPONENTS} CompressibleFlowComponents;
typedef enum {T, VEL, TOTAL_COMPRESSIBLE_AUX_COMPONENTS} CompressibleAuxComponents;
struct _FlowData_CompressibleFlow{
/*Courant Friedrichs Lewy*/
PetscReal cfl;
/* thermal conductivity*/
PetscReal k;
/* dynamic viscosity*/
PetscReal mu;
/* store method used for flux differencer */
FluxDifferencerFunction fluxDifferencer;
// EOS function calls
PetscErrorCode (*decodeStateFunction)(const PetscReal* yi, PetscInt dim, PetscReal density, PetscReal totalEnergy, const PetscReal* velocity, PetscReal* internalEnergy, PetscReal* a, PetscReal* p, void* ctx);
void* decodeStateFunctionContext;
PetscErrorCode (*computeTemperatureFunction)(const PetscReal* yi, PetscInt dim, PetscReal density, PetscReal totalEnergy, const PetscReal* massFlux, PetscReal* T, void* ctx);
void* computeTemperatureContext;
PetscBool automaticTimeStepCalculator;
} ;
typedef struct _FlowData_CompressibleFlow* FlowData_CompressibleFlow;
typedef PetscErrorCode (*FVAuxFieldUpdateFunction)(FlowData_CompressibleFlow flowData, PetscReal time, PetscInt dim, const PetscFVCellGeom *cellGeom, const PetscScalar* conservedValues, PetscScalar* auxField);
PETSC_EXTERN PetscErrorCode FVFlowUpdateAuxFieldsFV(DM dm, DM auxDM, PetscReal time, Vec locXVec, Vec locAuxField, PetscInt numberUpdateFunctions, FVAuxFieldUpdateFunction* updateFunctions, FlowData_CompressibleFlow data);
PETSC_EXTERN PetscErrorCode CompressibleFlowDiffusionSourceRHSFunctionLocal(DM dm, DM auxDM, PetscReal time, Vec locXVec, Vec locAuxVec, Vec globFVec, FlowData_CompressibleFlow flowParameters);
PETSC_EXTERN void CompressibleFlowComputeEulerFlux(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *area, const PetscReal *xL, const PetscReal *xR, PetscInt numConstants, const PetscScalar constants[], PetscReal *flux, void* ctx);
PETSC_EXTERN PetscErrorCode CompressibleFlowComputeStressTensor(PetscInt dim, PetscReal mu, const PetscReal* gradVelL, const PetscReal * gradVelR, PetscReal* tau);
#endif | {
"alphanum_fraction": 0.811996419,
"avg_line_length": 58.7894736842,
"ext": "h",
"hexsha": "bfca823fc9648d8c3e438f212ca63dabc4eb3ec3",
"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": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pakserep/ablate",
"max_forks_repo_path": "ablateCore/flow/compressibleFlow.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"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": "pakserep/ablate",
"max_issues_repo_path": "ablateCore/flow/compressibleFlow.h",
"max_line_length": 246,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pakserep/ablate",
"max_stars_repo_path": "ablateCore/flow/compressibleFlow.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 572,
"size": 2234
} |
#include <stdlib.h>
#include <utility>
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_sf.h>
#include <string>
#include <random>
#include <array>
using namespace std;
struct mass_eff_scalar_density_params
{
vector<double> scalar_coeff;
vector<double> scalar_exp;
double number_density;
double nucleon_mass;
double degeneracy;
double temperature;
vector<double> vec_coeff;
vector<double> vec_exp;
};
//struct for the parameters for root solving for the coupling constants
struct coeff_params
{
double saturation_densitiy;
double nucleon_mass;
double binding_energy;
double degeneracy;
vector<double> scalar_exp;
vector<double> vec_exp;
unsigned int* terms;
};
//struct for the parameters for finding the critical point
struct crit_params
{
vector<double> scalar_coeff;
vector<double> scalar_exp;
vector<double> vec_coeff;
vector<double> vec_exp;
double nucleon_mass;
double degeneracy;
};
//struct for the parameters for finding the interaction terms for 1 CP
struct interaction_params
{
double nucleon_mass;
double degeneracy;
double saturation_density;
double binding_energy;
double critical_temperature;
double critical_density;
unsigned int* terms;
};
//struct for the parameters for finding the interaction terms for 2 CPs
struct interaction_params_2crit
{
double nucleon_mass;
double degeneracy;
double saturation_density;
double binding_energy;
double critical_temperature_lg;
double critical_density_lg;
double critical_temperature_qgp;
double critical_density_qgp;
double spinodial_l_density;
double spinodial_r_density;
unsigned int* terms;
};
int mass_eff_scalar_density_root(const gsl_vector * x, void *params, gsl_vector * f);
int print_state_mass_eff_scalar_density (size_t iter, gsl_multiroot_fsolver * s);
pair<double, double> get_mass_eff_scalar_density(double degeneracy, double nucleon_mass,vector<double> scalar_coeff ,vector<double> scalar_exp,double number_density,bool print);
int T_mass_eff_mu_eff_scalar_density_root(const gsl_vector * x, void *params, gsl_vector * f);
int print_state_T_mass_eff_mu_eff_scalar_density (size_t iter, gsl_multiroot_fsolver * s);
tuple<double, double,double,bool> get_T_mass_eff_mu_eff_scalar_density(vector<double> scalar_coeff, vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double nucleon_mass,double number_density, double temperature, double degeneracy, bool print);
int coeff_root(const gsl_vector * x, void *params, gsl_vector * f);
int print_state_coeff (size_t iter, gsl_multiroot_fsolver * s);
pair<double, double> get_coeff(double nucleon_mass, double saturation_density, double binding_energy, double degeneracy, vector<double> scalar_exp, vector<double> vec_exp, bool print, unsigned int terms[2], bool * success=NULL);
int crit_root(const gsl_vector * x, void *params, gsl_vector * f);
pair<double, double> get_crit(double nucleon_mass,double saturation_density, double binding_energy, double degeneracy, vector<double> scalar_exp, vector<double> vec_exp, bool print, double crit_T=19.09, double crit_density=540000, vector<double> scalar_coeff={0.0}, vector<double> vec_coeff={0.0});
int interaction_root(const gsl_vector * x, void *params, gsl_vector * f);
int print_state_interaction (size_t iter, gsl_multiroot_fsolver * s);
tuple<double, double,double,double, double, bool> get_interaction_4D(void * p, bool print,vector<double> init_exp={2.05,2.05},vector<double> init_coeff={10*4*M_PI/pow(550,2.0),10*4*M_PI/pow(783,2.0)});
int interaction_root_2crit(const gsl_vector * x, void *params, gsl_vector * f);
int print_state_interaction_2crit (size_t iter, gsl_multiroot_fsolver * s);
tuple<double, vector<double>, vector<double>, bool> get_interaction_2crit(void * p, bool print,vector<double> init_exp={2.05,2.05,3,3},vector<double> init_coeff={10*4*M_PI/pow(550,2.0),10*4*M_PI/pow(783,2.0),0,0});
double energy_pp_minus_mass_solv(double degeneracy, double nucleon_mass,double number_density, vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);
double energy_pp_minus_mass_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);
double press_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);
double press_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);
double incsolv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp,double delta=1);
double T_press_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature);
double T_press_dmu_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1.);
double T_press_dT_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1e-2);
double T_press_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1e3);
double T_press_dn2_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp,double temperature, double delta=1e3);
pair<double, double> T_press_dn12_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1e3);
double T_eps_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature);
void gsl_handler (const char * reason, const char * file, int line, int gsl_errno);
bool validate_interaction(double error, vector<double> coeff_guess, vector<double> exp_guess,vector<double> coeff, vector<double> exp, string filename, int timestamp, void* params);
void interaction_4D_grid(double nucleon_mass,double critical_temperature, double critical_density, double binding_energy, double saturation_density, double degeneracy, double boundaries [4][3], unsigned int terms [2], string filename, bool print, int num_sol=0);
void interaction_4D_crit_grid(double nucleon_mass, double binding_energy, double saturation_density, double degeneracy, double boundaries_model [4][3], double boundaries_crit [2][3], unsigned int terms [2], string filename, bool print, int num_sol);
double round_to_n_digits(double x, int n);
| {
"alphanum_fraction": 0.8029187125,
"avg_line_length": 71.8823529412,
"ext": "h",
"hexsha": "5aef5306dae9f9e01710e6804799b3c1ea147efb",
"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": "44c03dee180ab10dc83ea6eb4e5be4911dc20445",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "NGoetz/CWalecka",
"max_forks_repo_path": "src/wsolvers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "44c03dee180ab10dc83ea6eb4e5be4911dc20445",
"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": "NGoetz/CWalecka",
"max_issues_repo_path": "src/wsolvers.h",
"max_line_length": 298,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "44c03dee180ab10dc83ea6eb4e5be4911dc20445",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "NGoetz/CWalecka",
"max_stars_repo_path": "src/wsolvers.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1705,
"size": 7332
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.