Search is not available for this dataset
text string | meta dict |
|---|---|
// This matrix class is a C++ wrapper for the GNU Scientific Library
// Copyright (C) ULP-IPB Strasbourg
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#ifndef _vector_#type#_h
#define _vector_#type#_h
#ifdef __HP_aCC
#include <iostream.h>
#else
#include <iostream>
#endif
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector#typeext#.h>
#include <gsl/gsl_blas.h>
#include <gslwrap/vector_double.h>
//#define NDEBUG 0
#include <assert.h>
namespace gsl
{
#ifndef __HP_aCC
using std::ostream;
//using std::string;
//using std::runtime_error;
#endif
class vector#typeext#_view;
class vector#typeext#
{
protected:
gsl_vector#typeext# *gsldata;
void free(){if(gsldata) gsl_vector#typeext#_free(gsldata);gsldata=NULL;}
void alloc(size_t n) {gsldata=gsl_vector#typeext#_alloc(n);}
void calloc(size_t n){gsldata=gsl_vector#typeext#_calloc(n);}
public:
typedef #type# value_type;
vector#typeext#() : gsldata(NULL) {;}
vector#typeext#( const vector#typeext# &other ):gsldata(NULL) {copy(other);}
template<class oclass>
vector#typeext#( const oclass &other ):gsldata(NULL) {copy(other);}
~vector#typeext#(){free();}
vector#typeext#(const size_t& n,bool clear=true)
{
if(clear){this->calloc(n);}
else {this->alloc(n);}
}
vector#typeext#(const int& n,bool clear=true)
{
if(clear){this->calloc(n);}
else {this->alloc(n);}
}
void resize(size_t n);
template <class oclass>
void copy(const oclass &other)
{
if ( static_cast<const void *>( this ) == static_cast<const void *>( &other ) )
return;
if (!other.is_set())
{
gsldata=NULL;
return;
}
resize(other.size());
for (size_t i=0;i<size();i++)
{
gsl_vector#typeext#_set(gsldata, i, (#type#)other[i]);
}
}
void copy(const vector#typeext#& other);
bool is_set() const{if (gsldata) return true; else return false;}
// void clone(vector#typeext#& other);
// size_t size() const {if (!gsldata) {cout << "vector#typeext#::size vector not initialized" << endl; exit(-1);}return gsldata->size;}
size_t size() const {assert (gsldata); return gsldata->size;}
/** for interfacing with gsl c */
/* gsl_vector#typeext# *gslobj() {if (!gsldata){cout << "vector#typeext#::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return gsldata;} */
/* const gsl_vector#typeext# *gslobj() const {if (!gsldata){cout << "vector#typeext#::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return gsldata;} */
gsl_vector#typeext# *gslobj() {assert(gsldata);return gsldata;}
const gsl_vector#typeext# *gslobj() const {assert(gsldata);return gsldata;}
static vector#typeext#_view create_vector_view( const gsl_vector#typeext#_view &other );
// ********Accessing vector elements
// Unlike FORTRAN compilers, C compilers do not usually provide support for range checking of vectors and matrices (2). However, the functions gsl_vector#typeext#_get and gsl_vector#typeext#_set can perform range checking for you and report an error if you attempt to access elements outside the allowed range.
// The functions for accessing the elements of a vector or matrix are defined in `gsl_vector#typeext#.h' and declared extern inline to eliminate function-call overhead. If necessary you can turn off range checking completely without modifying any source files by recompiling your program with the preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler supports inline functions the effect of turning off range checking is to replace calls to gsl_vector#typeext#_get(v,i) by v->data[i*v->stride] and and calls to gsl_vector#typeext#_set(v,i,x) by v->data[i*v->stride]=x. Thus there should be no performance penalty for using the range checking functions when range checking is turned off.
// This function returns the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked and 0 is returned.
#type# get(size_t i) const {return gsl_vector#typeext#_get(gsldata,i);}
// This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked.
void set(size_t i,#type# x){gsl_vector#typeext#_set(gsldata,i,x);}
// These functions return a pointer to the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked
#type# &operator[](size_t i) { return *gsl_vector#typeext#_ptr(gsldata,i);}
const #type# &operator[](size_t i) const { return *gsl_vector#typeext#_ptr(gsldata,i);}
#type# &operator()(size_t i) { return *gsl_vector#typeext#_ptr(gsldata,i);}
const #type# &operator()(size_t i) const { return *gsl_vector#typeext#_ptr(gsldata,i);}
// ***** Initializing vector elements
// This function sets all the elements of the vector v to the value x.
void set_all(#type# x){gsl_vector#typeext#_set_all (gsldata,x);}
// This function sets all the elements of the vector v to zero.
void set_zero(){gsl_vector#typeext#_set_zero (gsldata);}
// This function makes a basis vector by setting all the elements of the vector v to zero except for the i-th element which is set to one.
int set_basis (size_t i) {return gsl_vector#typeext#_set_basis (gsldata,i);}
// **** Reading and writing vectors
// The library provides functions for reading and writing vectors to a file as binary data or formatted text.
// This function writes the elements of the vector v to the stream stream in binary format. The return value is 0 for success and GSL_EFAILED if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures.
int fwrite (FILE * stream) const {return gsl_vector#typeext#_fwrite (stream, gsldata);}
// This function reads into the vector v from the open stream stream in binary format. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many bytes to read. The return value is 0 for success and GSL_EFAILED if there was a problem reading from the file. The data is assumed to have been written in the native binary format on the same architecture.
int fread (FILE * stream) {return gsl_vector#typeext#_fread (stream, gsldata);}
void load( const char *filename );
///
void save( const char *filename ) const;
// This function writes the elements of the vector v line-by-line to the stream stream using the format specifier format, which should be one of the %g, %e or %f formats for floating point numbers and %d for integers. The function returns 0 for success and GSL_EFAILED if there was a problem writing to the file.
int fprintf (FILE * stream, const char * format) const {return gsl_vector#typeext#_fprintf (stream, gsldata,format) ;}
// This function reads formatted data from the stream stream into the vector v. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many numbers to read. The function returns 0 for success and GSL_EFAILED if there was a problem reading from the file.
int fscanf (FILE * stream) {return gsl_vector#typeext#_fscanf (stream, gsldata); }
// ******* Vector views
// In addition to creating vectors from slices of blocks it is also possible to slice vectors and create vector views. For example, a subvector of another vector can be described with a view, or two views can be made which provide access to the even and odd elements of a vector.
// A vector view is a temporary object, stored on the stack, which can be used to operate on a subset of vector elements. Vector views can be defined for both constant and non-constant vectors, using separate types that preserve constness. A vector view has the type gsl_vector#typeext#_view and a constant vector view has the type gsl_vector#typeext#_const_view. In both cases the elements of the view can be accessed as a gsl_vector#typeext# using the vector component of the view object. A pointer to a vector of type gsl_vector#typeext# * or const gsl_vector#typeext# * can be obtained by taking the address of this component with the & operator.
// These functions return a vector view of a subvector of another vector v. The start of the new vector is offset by offset elements from the start of the original
// vector. The new vector has n elements. Mathematically, the i-th element of the new vector v' is given by,
// v'(i) = v->data[(offset + i)*v->stride]
// where the index i runs from 0 to n-1.
// The data pointer of the returned vector struct is set to null if the combined parameters (offset,n) overrun the end of the original vector.
// The new vector is only a view of the block underlying the original vector, v. The block containing the elements of v is not owned by the new vector. When the
// new vector goes out of scope the original vector v and its block will continue to exist. The original memory can only be deallocated by freeing the original vector.
// Of course, the original vector should not be deallocated while the new vector is still in use.
// The function gsl_vector#typeext#_const_subvector is equivalent to gsl_vector#typeext#_subvector but can be used for vectors which are declared const.
vector#typeext#_view subvector (size_t offset, size_t n);
const vector#typeext#_view subvector (size_t offset, size_t n) const;
// vector#typeext#_const_view subvector (size_t offset, size_t n) const;
// class view
// {
// gsl_vector#typeext#_view *gsldata;
// public:
// view();
// };
// view subvector(size_t offset, size_t n)
// {
// return view(gsl_vector#typeext#_subvector(gsldata,offset,n);
// }
// const view subvector(size_t offset, size_t n) const
// {
// return view(gsl_vector#typeext#_const_subvector(gsldata,offset,n);
// }
// Function: gsl_vector#typeext# gsl_vector#typeext#_subvector_with_stride (gsl_vector#typeext# *v, size_t offset, size_t stride, size_t n)
// Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_const_subvector_with_stride (const gsl_vector#typeext# * v, size_t offset, size_t stride, size_t n)
// These functions return a vector view of a subvector of another vector v with an additional stride argument. The subvector is formed in the same way as for
// gsl_vector#typeext#_subvector but the new vector has n elements with a step-size of stride from one element to the next in the original vector. Mathematically,
// the i-th element of the new vector v' is given by,
// v'(i) = v->data[(offset + i*stride)*v->stride]
// where the index i runs from 0 to n-1.
// Note that subvector views give direct access to the underlying elements of the original vector. For example, the following code will zero the even elements of the
// vector v of length n, while leaving the odd elements untouched,
// gsl_vector#typeext#_view v_even = gsl_vector#typeext#_subvector_with_stride (v, 0, 2, n/2);
// gsl_vector#typeext#_set_zero (&v_even.vector);
// A vector view can be passed to any subroutine which takes a vector argument just as a directly allocated vector would be, using &view.vector. For example, the
// following code computes the norm of odd elements of v using the BLAS routine DNRM2,
// gsl_vector#typeext#_view v_odd = gsl_vector#typeext#_subvector_with_stride (v, 1, 2, n/2);
// double r = gsl_blas_dnrm2 (&v_odd.vector);
// The function gsl_vector#typeext#_const_subvector_with_stride is equivalent to gsl_vector#typeext#_subvector_with_stride but can be used for
// vectors which are declared const.
// Function: gsl_vector#typeext#_view gsl_vector#typeext#_complex_real (gsl_vector#typeext#_complex *v)
// Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_complex_const_real (const gsl_vector#typeext#_complex *v)
// These functions return a vector view of the real parts of the complex vector v.
// The function gsl_vector#typeext#_complex_const_real is equivalent to gsl_vector#typeext#_complex_real but can be used for vectors which are declared
// const.
// Function: gsl_vector#typeext#_view gsl_vector#typeext#_complex_imag (gsl_vector#typeext#_complex *v)
// Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_complex_const_imag (const gsl_vector#typeext#_complex *v)
// These functions return a vector view of the imaginary parts of the complex vector v.
// The function gsl_vector#typeext#_complex_const_imag is equivalent to gsl_vector#typeext#_complex_imag but can be used for vectors which are declared
// const.
// Function: gsl_vector#typeext#_view gsl_vector#typeext#_view_array (double *base, size_t n)
// Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_const_view_array (const double *base, size_t n)
// These functions return a vector view of an array. The start of the new vector is given by base and has n elements. Mathematically, the i-th element of the new
// vector v' is given by,
// v'(i) = base[i]
// where the index i runs from 0 to n-1.
// The array containing the elements of v is not owned by the new vector view. When the view goes out of scope the original array will continue to exist. The
// original memory can only be deallocated by freeing the original pointer base. Of course, the original array should not be deallocated while the view is still in use.
// The function gsl_vector#typeext#_const_view_array is equivalent to gsl_vector#typeext#_view_array but can be used for vectors which are declared const.
// Function: gsl_vector#typeext#_view gsl_vector#typeext#_view_array_with_stride (double * base, size_t stride, size_t n)
// Function: gsl_vector#typeext#_const_view gsl_vector#typeext#_const_view_array_with_stride (const double * base, size_t stride, size_t n)
// These functions return a vector view of an array base with an additional stride argument. The subvector is formed in the same way as for
// gsl_vector#typeext#_view_array but the new vector has n elements with a step-size of stride from one element to the next in the original array. Mathematically,
// the i-th element of the new vector v' is given by,
// v'(i) = base[i*stride]
// where the index i runs from 0 to n-1.
// Note that the view gives direct access to the underlying elements of the original array. A vector view can be passed to any subroutine which takes a vector
// argument just as a directly allocated vector would be, using &view.vector.
// The function gsl_vector#typeext#_const_view_array_with_stride is equivalent to gsl_vector#typeext#_view_array_with_stride but can be used for
// arrays which are declared const.
// ************* Copying vectors
// Common operations on vectors such as addition and multiplication are available in the BLAS part of the library (see section BLAS Support). However, it is useful to have a small number of utility functions which do not require the full BLAS code. The following functions fall into this category.
// This function copies the elements of the vector src into the vector dest.
vector#typeext#& operator=(const vector#typeext#& other){copy(other);return (*this);}
// Function: int gsl_vector#typeext#_swap (gsl_vector#typeext# * v, gsl_vector#typeext# * w)
// This function exchanges the elements of the vectors v and w by copying. The two vectors must have the same length.
// ***** Exchanging elements
// The following function can be used to exchange, or permute, the elements of a vector.
// Function: int gsl_vector#typeext#_swap_elements (gsl_vector#typeext# * v, size_t i, size_t j)
// This function exchanges the i-th and j-th elements of the vector v in-place.
int swap_elements (size_t i, size_t j) {return gsl_vector#typeext#_swap_elements (gsldata, i,j);}
// Function: int gsl_vector#typeext#_reverse (gsl_vector#typeext# * v)
// This function reverses the order of the elements of the vector v.
int reverse () {return gsl_vector#typeext#_reverse (gsldata) ;}
// ******* Vector operations
// The following operations are only defined for real vectors.
// This function adds the elements of vector b to the elements of vector a, a'_i = a_i + b_i. The two vectors must have the same length.
int operator+=(const vector#typeext# &other) {return gsl_vector#typeext#_add (gsldata, other.gsldata);}
// This function subtracts the elements of vector b from the elements of vector a, a'_i = a_i - b_i. The two vectors must have the same length.
int operator-=(const vector#typeext# &other) {return gsl_vector#typeext#_sub (gsldata, other.gsldata);}
// Function: int gsl_vector#typeext#_mul (gsl_vector#typeext# * a, const gsl_vector#typeext# * b)
// This function multiplies the elements of vector a by the elements of vector b, a'_i = a_i * b_i. The two vectors must have the same length.
int operator*=(const vector#typeext# &other) {return gsl_vector#typeext#_mul (gsldata, other.gsldata);}
// This function divides the elements of vector a by the elements of vector b, a'_i = a_i / b_i. The two vectors must have the same length.
int operator/=(const vector#typeext# &other) {return gsl_vector#typeext#_div (gsldata, other.gsldata);}
// This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i.
int operator*=(#type# x) {return gsl_vector#typeext#_scale (gsldata, x);}
// Function: int gsl_vector#typeext#_add_constant (gsl_vector#typeext# * a, const double x)
// This function adds the constant value x to the elements of the vector a, a'_i = a_i + x.
int operator+=(#type# x) {return gsl_vector#typeext#_add_constant (gsldata,x);}
// This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i.
int operator/=(#type# x) {return gsl_vector#typeext#_scale (gsldata, 1/x);}
// bool operators:
bool operator==(const vector#typeext#& other) const;
bool operator!=(const vector#typeext#& other) const { return (!((*this)==other));}
// stream output:
// friend ostream& operator<< ( ostream& os, const vector#typeext#& vect );
/** returns sum of all the vector elements. */
#type# sum() const;
// returns sqrt(v.t*v);
double norm2() const;
// **** Finding maximum and minimum elements of vectors
// This function returns the maximum value in the vector v.
double max() const{return gsl_vector#typeext#_max (gsldata) ;}
// Function: double gsl_vector#typeext#_min (const gsl_vector#typeext# * v)
// This function returns the minimum value in the vector v.
double min() const{return gsl_vector#typeext#_min (gsldata) ;}
// Function: void gsl_vector#typeext#_minmax (const gsl_vector#typeext# * v, double * min_out, double * max_out)
// This function returns the minimum and maximum values in the vector v, storing them in min_out and max_out.
// This function returns the index of the maximum value in the vector v. When there are several equal maximum elements then the lowest index is returned.
size_t max_index(){return gsl_vector#typeext#_max_index (gsldata);}
// Function: size_t gsl_vector#typeext#_min_index (const gsl_vector#typeext# * v)
// This function returns the index of the minimum value in the vector v. When there are several equal minimum elements then the lowest index is returned.
size_t min_index(){return gsl_vector#typeext#_min_index (gsldata);}
// Function: void gsl_vector#typeext#_minmax_index (const gsl_vector#typeext# * v, size_t * imin, size_t * imax)
// This function returns the indices of the minimum and maximum values in the vector v, storing them in imin and imax. When there are several equal minimum
// or maximum elements then the lowest indices are returned.
// Vector properties
// Function: int gsl_vector#typeext#_isnull (const gsl_vector#typeext# * v)
// This function returns 1 if all the elements of the vector v are zero, and 0 otherwise. };
bool isnull(){return gsl_vector#typeext#_isnull (gsldata);}
};
// When you add create a view it will stick to its with the view until you call change_view
// ex:
// matrix_float m(5,5);
// vector_float v(5);
// // ...
// m.column(3) = v; //the 3rd column of the matrix m will equal v.
class vector#typeext#_view : public vector#typeext#
{
public:
vector#typeext#_view(const vector#typeext#& other) :vector#typeext#(){init(other);}
vector#typeext#_view(const vector#typeext#_view& other):vector#typeext#(){init(other);}
vector#typeext#_view(const gsl_vector#typeext#& gsl_other) : vector#typeext#() {init_with_gsl_vector(gsl_other);}
void init(const vector#typeext#& other);
void init_with_gsl_vector(const gsl_vector#typeext#& gsl_other);
void change_view(const vector#typeext#& other){init(other);}
private:
};
ostream& operator<< ( ostream& os, const vector#typeext# & vect );
// vector_type<>::type is a template interface to vector_?
// it is usefull for in templated situations for getting the correct vector type
#define tmp_type_is#typeext#
#ifdef tmp_type_is
typedef vector vector_double;
template<class T>
struct vector_type {typedef vector_double type;};
template<class T>
struct value_type {typedef double type;};
#else
template<> struct vector_type<#type#> {typedef vector#typeext# type;};
#endif
#undef tmp_type_is#typeext#
}
#endif// _vector_#type#_h
| {
"alphanum_fraction": 0.7351524157,
"avg_line_length": 55.2462686567,
"ext": "h",
"hexsha": "f421ee0b7eb1b986147496102a95e3b1a0eeac78",
"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": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_forks_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_forks_repo_name": "entn-at/GlottDNN",
"max_forks_repo_path": "src/gslwrap/vector_source.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_issues_repo_name": "entn-at/GlottDNN",
"max_issues_repo_path": "src/gslwrap/vector_source.h",
"max_line_length": 702,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_stars_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_stars_repo_name": "entn-at/GlottDNN",
"max_stars_repo_path": "src/gslwrap/vector_source.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5758,
"size": 22209
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
#if (defined(SMOOTH_PHI) || defined(SMOOTH_ROTB) || defined(BSMOOTH))
/*! Structure for communication during the density computation. Holds data that is sent to other processors.
*/
static struct smoothdata_in
{
MyDouble Pos[3];
MyFloat Hsml;
int NodeList[NODELISTLENGTH];
}
*SmoothDataIn, *SmoothDataGet;
static struct smoothdata_out
{
#ifdef SMOOTH_PHI
MyFloat SmoothPhi;
MyFloat SmoothDivB;
#endif
#ifdef SMOOTH_ROTB
MyFloat SmoothRotB[3];
#endif
#ifdef BSMOOTH
MyFloat BSmooth[3];
#endif
#if defined(BLACK_HOLES)
MyLongDouble SmoothedEntr;
#endif
MyFloat DensityNorm;
}
*SmoothDataResult, *SmoothDataOut;
void smoothed_values(void)
{
int ngrp, sendTask, recvTask, place, nexport, nimport;
int i, j, ndone, ndone_flag, dummy;
double timeall = 0, timecomp1 = 0, timecomp2 = 0, timecommsumm1 = 0, timecommsumm2 = 0, timewait1 =
0, timewait2 = 0;
double timecomp, timecomm, timewait;
double tstart, tend, t0, t1;
#ifdef BSMOOTH
int Smooth_Flag = 0;
double dB[3];
#endif
/* Display information message that this step is executed on Task 0 ... */
if(ThisTask == 0)
{
printf("Updating SPH interpolants for:"
#ifdef SMOOTH_PHI
" (divB and Phi(Dedner)"
#endif /* SMOOTH_PHI */
#ifdef SMOOTH_ROTB
" (rotB)"
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
" (B)"
#endif /* BSMOOTH */
"\n");
#ifdef BSMOOTH
printf("Flag_FullStep = %d, Main TimestepCounts = %d\n", Flag_FullStep, All.MainTimestepCounts);
#endif
}
#ifdef BSMOOTH
if(Flag_FullStep == 1)
{
if((All.MainTimestepCounts % All.BSmoothInt == 0) && (All.BSmoothInt >= 0))
{
Smooth_Flag = 1;
if(ThisTask == 0)
printf("Smoothing B %d, %f\n", All.BSmoothInt, All.BSmoothFrac);
}
All.MainTimestepCounts++;
}
#endif
Ngblist = (int *) mymalloc(NumPart * sizeof(int));
All.BunchSize =
(int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +
sizeof(struct smoothdata_in) + sizeof(struct smoothdata_out) +
sizemax(sizeof(struct smoothdata_in),
sizeof(struct smoothdata_out))));
DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));
DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));
CPU_Step[CPU_SMTHMISC] += measure_time();
t0 = second();
i = FirstActiveParticle; /* begin with this index */
do
{
for(j = 0; j < NTask; j++)
{
Send_count[j] = 0;
Exportflag[j] = -1;
}
/* do local particles and prepare export list */
tstart = second();
for(nexport = 0; i >= 0; i = NextActiveParticle[i])
{
if(density_isactive(i))
{
if(smoothed_evaluate(i, 0, &nexport, Send_count) < 0)
break;
}
}
tend = second();
timecomp1 += timediff(tstart, tend);
#ifdef MYSORT
mysort_dataindex(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);
#else
qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);
#endif
tstart = second();
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
tend = second();
timewait1 += timediff(tstart, tend);
for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)
{
Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];
nimport += Recv_count[j];
if(j > 0)
{
Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];
Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];
}
}
SmoothDataGet = (struct smoothdata_in *) mymalloc(nimport * sizeof(struct smoothdata_in));
SmoothDataIn = (struct smoothdata_in *) mymalloc(nexport * sizeof(struct smoothdata_in));
/* prepare particle data for export */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
SmoothDataIn[j].Pos[0] = P[place].Pos[0];
SmoothDataIn[j].Pos[1] = P[place].Pos[1];
SmoothDataIn[j].Pos[2] = P[place].Pos[2];
SmoothDataIn[j].Hsml = PPP[place].Hsml;
memcpy(SmoothDataIn[j].NodeList,
DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));
}
/* exchange particle data */
tstart = second();
for(ngrp = 1; ngrp < (1 << PTask); ngrp++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)
{
/* get the particles */
MPI_Sendrecv(&SmoothDataIn[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct smoothdata_in), MPI_BYTE,
recvTask, TAG_SMOOTH_A,
&SmoothDataGet[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct smoothdata_in), MPI_BYTE,
recvTask, TAG_SMOOTH_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
tend = second();
timecommsumm1 += timediff(tstart, tend);
myfree(SmoothDataIn);
SmoothDataResult = (struct smoothdata_out *) mymalloc(nimport * sizeof(struct smoothdata_out));
SmoothDataOut = (struct smoothdata_out *) mymalloc(nexport * sizeof(struct smoothdata_out));
/* now do the particles that were sent to us */
tstart = second();
for(j = 0; j < nimport; j++)
smoothed_evaluate(j, 1, &dummy, &dummy);
tend = second();
timecomp2 += timediff(tstart, tend);
if(i < 0)
ndone_flag = 1;
else
ndone_flag = 0;
tstart = second();
MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
tend = second();
timewait2 += timediff(tstart, tend);
/* get the result */
tstart = second();
for(ngrp = 1; ngrp < (1 << PTask); ngrp++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)
{
/* send the results */
MPI_Sendrecv(&SmoothDataResult[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct smoothdata_out),
MPI_BYTE, recvTask, TAG_SMOOTH_B,
&SmoothDataOut[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct smoothdata_out),
MPI_BYTE, recvTask, TAG_SMOOTH_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
tend = second();
timecommsumm2 += timediff(tstart, tend);
/* add the result to the local particles */
tstart = second();
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
if(P[place].Type == 0)
{
#ifdef SMOOTH_PHI
SphP[place].SmoothPhi += SmoothDataOut[j].SmoothPhi;
SphP[place].SmoothDivB += SmoothDataOut[j].SmoothDivB;
#endif /* SMOOTH_PHI */
#ifdef SMOOTH_ROTB
SphP[place].SmoothedRotB[0] += SmoothDataOut[j].SmoothRotB[0];
SphP[place].SmoothedRotB[1] += SmoothDataOut[j].SmoothRotB[1];
SphP[place].SmoothedRotB[2] += SmoothDataOut[j].SmoothRotB[2];
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
SphP[place].BSmooth[0] += SmoothDataOut[j].BSmooth[0];
SphP[place].BSmooth[1] += SmoothDataOut[j].BSmooth[1];
SphP[place].BSmooth[2] += SmoothDataOut[j].BSmooth[2];
#endif /* BSMOOTH */
SphP[place].DensityNorm += SmoothDataOut[j].DensityNorm;
}
}
tend = second();
timecomp1 += timediff(tstart, tend);
myfree(SmoothDataOut);
myfree(SmoothDataResult);
myfree(SmoothDataGet);
}
while(ndone < NTask);
myfree(DataNodeList);
myfree(DataIndexTable);
myfree(Ngblist);
/* do final operations on results */
tstart = second();
for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i])
{
if(density_isactive(i))
if(P[i].Type == 0)
{
#ifdef SMOOTH_PHI
SphP[i].SmoothPhi /= SphP[i].DensityNorm;
SphP[i].SmoothDivB /= SphP[i].DensityNorm;
#endif /* SMOOTH_PHI */
#ifdef SMOOTH_ROTB
SphP[i].SmoothedRotB[0] /= SphP[i].DensityNorm;
SphP[i].SmoothedRotB[1] /= SphP[i].DensityNorm;
SphP[i].SmoothedRotB[2] /= SphP[i].DensityNorm;
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
SphP[i].BSmooth[0] /= SphP[i].DensityNorm;
SphP[i].BSmooth[1] /= SphP[i].DensityNorm;
SphP[i].BSmooth[2] /= SphP[i].DensityNorm;
if(Smooth_Flag == 1)
{
dB[0] = All.BSmoothFrac * (SphP[i].BSmooth[0] - SphP[i].BPred[0]);
dB[1] = All.BSmoothFrac * (SphP[i].BSmooth[1] - SphP[i].BPred[1]);
dB[2] = All.BSmoothFrac * (SphP[i].BSmooth[2] - SphP[i].BPred[2]);
SphP[i].BPred[0] += dB[0];
SphP[i].BPred[1] += dB[1];
SphP[i].BPred[2] += dB[2];
#ifndef EULERPOTENTIALS
SphP[i].B[0] += dB[0];
SphP[i].B[1] += dB[1];
SphP[i].B[2] += dB[2];
#endif
}
#endif /* BSMOOTH */
}
}
tend = second();
timecomp1 += timediff(tstart, tend);
/* collect some timing information */
t1 = WallclockTime = second();
timeall += timediff(t0, t1);
timecomp = timecomp1 + timecomp2;
timewait = timewait1 + timewait2;
timecomm = timecommsumm1 + timecommsumm2;
CPU_Step[CPU_SMTHCOMPUTE] += timecomp;
CPU_Step[CPU_SMTHWAIT] += timewait;
CPU_Step[CPU_SMTHCOMM] += timecomm;
CPU_Step[CPU_SMTHMISC] += timeall - (timecomp + timewait + timecomm);
}
/*! This function represents the core of the SPH density computation. The
* target particle may either be local, or reside in the communication
* buffer.
*/
int smoothed_evaluate(int target, int mode, int *nexport, int *nsend_local)
{
int j, n, listindex = 0;
int startnode, numngb_inbox;
double h, h2, hinv, hinv3, hinv4;
double wk, dwk;
double dx, dy, dz, r, r2, u, mass_j;
MyFloat *pos;
double DensityNorm = 0;
#ifdef SMOOTH_PHI
double SmoothPhi = 0.0;
double SmoothDivB = 0.0;
#endif /* SMOOTH_PHI */
#ifdef SMOOTH_ROTB
double smoothrotb[3];
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
double BSmooth[3];
#endif /* BSMOOTH */
#ifdef SMOOTH_ROTB
smoothrotb[0] = smoothrotb[1] = smoothrotb[2] = 0;
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
BSmooth[0] = BSmooth[1] = BSmooth[2] = 0;
#endif /* BSMOOTH */
if(mode == 0)
{
pos = P[target].Pos;
h = PPP[target].Hsml;
}
else
{
pos = SmoothDataGet[target].Pos;
h = SmoothDataGet[target].Hsml;
}
h2 = h * h;
hinv = 1.0 / h;
#ifndef TWODIMS
hinv3 = hinv * hinv * hinv;
#else
hinv3 = hinv * hinv / boxSize_Z;
#endif
hinv4 = hinv3 * hinv;
if(mode == 0)
{
startnode = All.MaxPart; /* root node */
}
else
{
startnode = SmoothDataGet[target].NodeList[0];
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
while(startnode >= 0)
{
while(startnode >= 0)
{
numngb_inbox = ngb_treefind_variable(&pos[0], h, target, &startnode, mode, nexport, nsend_local);
if(numngb_inbox < 0)
return -1;
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
dx = pos[0] - P[j].Pos[0];
dy = pos[1] - P[j].Pos[1];
dz = pos[2] - P[j].Pos[2];
#ifdef PERIODIC /* now find the closest image in the given box size */
if(dx > boxHalf_X)
dx -= boxSize_X;
if(dx < -boxHalf_X)
dx += boxSize_X;
if(dy > boxHalf_Y)
dy -= boxSize_Y;
if(dy < -boxHalf_Y)
dy += boxSize_Y;
if(dz > boxHalf_Z)
dz -= boxSize_Z;
if(dz < -boxHalf_Z)
dz += boxSize_Z;
#endif
r2 = dx * dx + dy * dy + dz * dz;
if(r2 < h2)
{
r = sqrt(r2);
u = r * hinv;
if(u < 0.5)
{
wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);
dwk = hinv4 * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);
}
else
{
wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);
dwk = hinv4 * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);
}
mass_j = P[j].Mass;
wk /= SphP[j].d.Density;
#ifdef SMOOTH_PHI
SmoothPhi += mass_j * wk * SphP[j].PhiPred;
SmoothDivB += mass_j * wk * SphP[j].divB;
#endif /* SMOOTH_PHI */
#ifdef SMOOTH_ROTB
smoothrotb[0] += mass_j * wk * SphP[j].RotB[0];
smoothrotb[1] += mass_j * wk * SphP[j].RotB[1];
smoothrotb[2] += mass_j * wk * SphP[j].RotB[2];
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
BSmooth[0] += mass_j * wk * SphP[j].BPred[0];
BSmooth[1] += mass_j * wk * SphP[j].BPred[1];
BSmooth[2] += mass_j * wk * SphP[j].BPred[2];
#endif /* BSMOOTH */
DensityNorm += mass_j * wk;
}
}
}
if(mode == 1)
{
listindex++;
if(listindex < NODELISTLENGTH)
{
startnode = SmoothDataGet[target].NodeList[listindex];
if(startnode >= 0)
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
}
}
if(mode == 0)
{
#ifdef SMOOTH_PHI
SphP[target].SmoothPhi = SmoothPhi;
SphP[target].SmoothDivB = SmoothDivB;
#endif /* SMOOTH_PHI */
#ifdef SMOOTH_ROTB
SphP[target].SmoothedRotB[0] = smoothrotb[0];
SphP[target].SmoothedRotB[1] = smoothrotb[1];
SphP[target].SmoothedRotB[2] = smoothrotb[2];
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
SphP[target].BSmooth[0] = BSmooth[0];
SphP[target].BSmooth[1] = BSmooth[1];
SphP[target].BSmooth[2] = BSmooth[2];
#endif /* BSMOOTH */
SphP[target].DensityNorm = DensityNorm;
}
else
{
#ifdef SMOOTH_PHI
SmoothDataResult[target].SmoothPhi = SmoothPhi;
SmoothDataResult[target].SmoothDivB = SmoothDivB;
#endif /* SMOOTH_PHI */
#ifdef SMOOTH_ROTB
SmoothDataResult[target].SmoothRotB[0] = smoothrotb[0];
SmoothDataResult[target].SmoothRotB[1] = smoothrotb[1];
SmoothDataResult[target].SmoothRotB[2] = smoothrotb[2];
#endif /* SMOOTH_ROTB */
#ifdef BSMOOTH
SmoothDataResult[target].BSmooth[0] = BSmooth[0];
SmoothDataResult[target].BSmooth[1] = BSmooth[1];
SmoothDataResult[target].BSmooth[2] = BSmooth[2];
#endif /* BSMOOTH */
SmoothDataResult[target].DensityNorm = DensityNorm;
}
return 0;
}
#endif
| {
"alphanum_fraction": 0.6215463697,
"avg_line_length": 25.5602189781,
"ext": "c",
"hexsha": "cc606fa734470c2cc5dfc836a24e5dc3f446dfe7",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/smooth_simple.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/smooth_simple.c",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/smooth_simple.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4612,
"size": 14007
} |
/**
* This file is part of the "libterminal" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <terminal/GraphicsAttributes.h>
#include <terminal/Line.h>
#include <terminal/primitives.h>
#include <crispy/algorithm.h>
#include <crispy/assert.h>
#include <crispy/ring.h>
#include <unicode/convert.h>
#include <range/v3/algorithm/copy.hpp>
#include <range/v3/iterator/insert_iterators.hpp>
#include <range/v3/view/iota.hpp>
#include <gsl/span>
#include <gsl/span_ext>
#include <algorithm>
#include <array>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
namespace terminal
{
// {{{ Margin
struct Margin
{
struct Horizontal
{
ColumnOffset from;
ColumnOffset
to; // TODO: call it begin and end and have end point to to+1 to avoid unnecessary +1's later
[[nodiscard]] constexpr ColumnCount length() const noexcept
{
return unbox<ColumnCount>(to - from) + ColumnCount(1);
}
[[nodiscard]] constexpr bool contains(ColumnOffset _value) const noexcept
{
return from <= _value && _value <= to;
}
[[nodiscard]] constexpr bool operator==(Horizontal rhs) const noexcept
{
return from == rhs.from && to == rhs.to;
}
[[nodiscard]] constexpr bool operator!=(Horizontal rhs) const noexcept { return !(*this == rhs); }
};
struct Vertical
{
LineOffset from;
// TODO: call it begin and end and have end point to to+1 to avoid unnecessary +1's later
LineOffset to;
[[nodiscard]] constexpr LineCount length() const noexcept
{
return unbox<LineCount>(to - from) + LineCount(1);
}
[[nodiscard]] constexpr bool contains(LineOffset _value) const noexcept
{
return from <= _value && _value <= to;
}
[[nodiscard]] constexpr bool operator==(Vertical const& rhs) const noexcept
{
return from == rhs.from && to == rhs.to;
}
[[nodiscard]] constexpr bool operator!=(Vertical const& rhs) const noexcept
{
return !(*this == rhs);
}
};
Vertical vertical {}; // top-bottom
Horizontal horizontal {}; // left-right
};
constexpr bool operator==(Margin const& a, PageSize b) noexcept
{
return a.horizontal.from.value == 0 && a.horizontal.to.value + 1 == b.columns.value
&& a.vertical.from.value == 0 && a.vertical.to.value + 1 == b.lines.value;
}
constexpr bool operator!=(Margin const& a, PageSize b) noexcept
{
return !(a == b);
}
// }}}
template <typename Cell>
using Lines = crispy::ring<Line<Cell>>;
/**
* Represents a logical grid line, i.e. a sequence lines that were written without
* an explicit linefeed, triggering an auto-wrap.
*/
template <typename Cell>
struct LogicalLine
{
LineOffset top {};
LineOffset bottom {};
std::vector<std::reference_wrapper<Line<Cell>>> lines {};
[[nodiscard]] Line<Cell> joinWithRightTrimmed() const
{
// TODO: determine final line's column count and pass it to ctor.
typename Line<Cell>::Buffer output;
auto lineFlags = lines.front().get().flags();
for (Line<Cell> const& line: lines)
for (Cell const& cell: line.cells())
output.emplace_back(cell);
while (!output.empty() && output.back().empty())
output.pop_back();
return Line<Cell>(output, lineFlags);
}
[[nodiscard]] std::string text() const
{
std::string output;
for (auto const& line: lines)
output += line.get().toUtf8();
return output;
}
};
template <typename Cell>
bool operator==(LogicalLine<Cell> const& a, LogicalLine<Cell> const& b) noexcept
{
return a.top == b.top && a.bottom == b.bottom;
}
template <typename Cell>
bool operator!=(LogicalLine<Cell> const& a, LogicalLine<Cell> const& b) noexcept
{
return !(a == b);
}
template <typename Cell>
struct LogicalLines
{
LineOffset topMostLine;
LineOffset bottomMostLine;
std::reference_wrapper<Lines<Cell>> lines;
struct iterator // {{{
{
std::reference_wrapper<Lines<Cell>> lines;
LineOffset top;
LineOffset next; // index to next logical line's beginning
LineOffset bottom;
LogicalLine<Cell> current;
iterator(std::reference_wrapper<Lines<Cell>> _lines,
LineOffset _top,
LineOffset _next,
LineOffset _bottom):
lines { _lines }, top { _top }, next { _next }, bottom { _bottom }
{
Require(_top <= next);
Require(next <= _bottom + 1);
++*this;
}
LogicalLine<Cell> const& operator*() const noexcept { return current; }
LogicalLine<Cell> const* operator->() const noexcept { return ¤t; }
iterator& operator++()
{
if (next == bottom + 1)
{
current.top = next;
current.bottom = next;
return *this;
}
Require(!lines.get()[unbox<int>(next)].wrapped());
current.top = LineOffset::cast_from(next);
current.lines.clear();
do
current.lines.emplace_back(lines.get()[unbox<int>(next++)]);
while (next <= bottom && lines.get()[unbox<int>(next)].wrapped());
current.bottom = LineOffset::cast_from(next - 1);
return *this;
}
iterator& operator--()
{
if (next == top - 1)
{
current.top = top - 1;
current.bottom = top - 1;
return *this;
}
auto const bottomMost = next - 1;
do
--next;
while (lines.get()[unbox<int>(next)].wrapped());
auto const topMost = next;
current.top = topMost;
current.bottom = bottomMost;
current.lines.clear();
for (auto i = topMost; i <= bottomMost; ++i)
current.lines.emplace_back(lines.get()[unbox<int>(i)]);
return *this;
}
iterator& operator++(int)
{
auto c = *this;
++*this;
return c;
}
iterator& operator--(int)
{
auto c = *this;
--*this;
return c;
}
bool operator==(iterator const& other) const noexcept { return current == other.current; }
bool operator!=(iterator const& other) const noexcept { return current != other.current; }
}; // }}}
iterator begin() const { return iterator(lines, topMostLine, topMostLine, bottomMostLine); }
iterator end() const { return iterator(lines, topMostLine, bottomMostLine + 1, bottomMostLine); }
};
template <typename Cell>
struct ReverseLogicalLines
{
LineOffset topMostLine;
LineOffset bottomMostLine;
std::reference_wrapper<Lines<Cell>> lines;
struct iterator // {{{
{
std::reference_wrapper<Lines<Cell>> lines;
LineOffset top;
LineOffset next; // index to next logical line's beginning
LineOffset bottom;
LogicalLine<Cell> current;
iterator(std::reference_wrapper<Lines<Cell>> _lines,
LineOffset _top,
LineOffset _next,
LineOffset _bottom):
lines { _lines }, top { _top }, next { _next }, bottom { _bottom }
{
Require(_top - 1 <= next);
Require(next <= _bottom);
++*this;
}
LogicalLine<Cell> const& operator*() const noexcept { return current; }
iterator& operator--()
{
if (next == bottom + 1)
{
current.top = bottom + 1;
current.bottom = bottom + 1;
return *this;
}
Require(!lines.get()[unbox<int>(next)].wrapped());
current.top = LineOffset::cast_from(next);
current.lines.clear();
do
current.lines.emplace_back(lines.get()[unbox<int>(next++)]);
while (next <= bottom && lines.get()[unbox<int>(next)].wrapped());
current.bottom = LineOffset::cast_from(next - 1);
return *this;
}
iterator& operator++()
{
if (next == top - 1)
{
current.top = next;
current.bottom = next;
return *this;
}
auto const bottomMost = next;
while (lines.get()[unbox<int>(next)].wrapped())
--next;
auto const topMost = next;
--next; // jump to next logical line's bottom line above the current logical one
current.top = topMost;
current.bottom = bottomMost;
current.lines.clear();
for (auto i = topMost; i <= bottomMost; ++i)
current.lines.emplace_back(lines.get()[unbox<int>(i)]);
return *this;
}
iterator& operator++(int)
{
auto c = *this;
++*this;
return c;
}
iterator& operator--(int)
{
auto c = *this;
--*this;
return c;
}
bool operator==(iterator const& other) const noexcept { return current == other.current; }
bool operator!=(iterator const& other) const noexcept { return current != other.current; }
}; // }}}
iterator begin() const { return iterator(lines, topMostLine, bottomMostLine, bottomMostLine); }
iterator end() const { return iterator(lines, topMostLine, topMostLine - 1, bottomMostLine); }
};
/**
* Manages the screen grid buffer (main screen + scrollback history).
*
* <h3>Future motivations</h3>
*
* <ul>
* <li>manages text reflow upon resize
* <li>manages underlying disk storage for very old scrollback history lines.
* </ul>
*
* <h3>Layout</h3>
*
* <pre>
* +0========================-3+ <-- scrollback top
* |1 -2|
* |2 Scrollback history -1|
* |3 0| <-- scrollback bottom
* +4-------------------------1+ <-- main page top
* |5 2|
* |6 main page area 3|
* |7 4| <-- main page bottom
* +---------------------------+
* ^ ^
* 1 pageSize.columns
* </pre>
*/
template <typename Cell>
class Grid
{
// TODO: Rename all "History" to "Scrollback"?
public:
Grid(PageSize _pageSize, bool _reflowOnResize, LineCount _maxHistoryLineCount);
Grid(): Grid(PageSize { LineCount(25), ColumnCount(80) }, false, LineCount(0)) {}
void reset();
// {{{ grid global properties
[[nodiscard]] LineCount maxHistoryLineCount() const noexcept { return maxHistoryLineCount_; }
void setMaxHistoryLineCount(LineCount _maxHistoryLineCount);
[[nodiscard]] LineCount totalLineCount() const noexcept { return maxHistoryLineCount_ + pageSize_.lines; }
[[nodiscard]] LineCount historyLineCount() const noexcept
{
return std::min(maxHistoryLineCount_, linesUsed_ - pageSize_.lines);
}
[[nodiscard]] bool reflowOnResize() const noexcept { return reflowOnResize_; }
void setReflowOnResize(bool _enabled) { reflowOnResize_ = _enabled; }
[[nodiscard]] PageSize pageSize() const noexcept { return pageSize_; }
/// Resizes the main page area of the grid and adapts the scrollback area's width accordingly.
///
/// @param _pageSize new size of the main page area
/// @param _currentCursorPos current cursor position
/// @param _wrapPending AutoWrap is on and a wrap is pending
///
/// @returns updated cursor position.
[[nodiscard]] CellLocation resize(PageSize _pageSize, CellLocation _currentCursorPos, bool _wrapPending);
// }}}
// {{{ Line API
/// @returns reference to Line at given relative offset @p _line.
Line<Cell>& lineAt(LineOffset _line) noexcept;
Line<Cell> const& lineAt(LineOffset _line) const noexcept;
gsl::span<Cell const> lineBuffer(LineOffset _line) const noexcept { return lineAt(_line).cells(); }
gsl::span<Cell const> lineBufferRightTrimmed(LineOffset _line) const noexcept;
[[nodiscard]] std::string lineText(LineOffset _line) const;
[[nodiscard]] std::string lineTextTrimmed(LineOffset _line) const;
[[nodiscard]] std::string lineText(Line<Cell> const& _line) const;
void setLineText(LineOffset _line, std::string_view _text);
// void resetLine(LineOffset _line, GraphicsAttributes _attribs) noexcept
// { lineAt(_line).reset(_attribs); }
[[nodiscard]] ColumnCount lineLength(LineOffset _line) const noexcept { return lineAt(_line).size(); }
[[nodiscard]] bool isLineBlank(LineOffset _line) const noexcept;
[[nodiscard]] bool isLineWrapped(LineOffset _line) const noexcept;
[[nodiscard]] int computeLogicalLineNumberFromBottom(LineCount _n) const noexcept;
[[nodiscard]] size_t zero_index() const noexcept { return lines_.zero_index(); }
// }}}
/// Gets a reference to the cell relative to screen origin (top left, 0:0).
[[nodiscard]] Cell& useCellAt(LineOffset _line, ColumnOffset _column) noexcept;
[[nodiscard]] Cell& at(LineOffset _line, ColumnOffset _column) noexcept;
[[nodiscard]] Cell const& at(LineOffset _line, ColumnOffset _column) const noexcept;
// page view API
gsl::span<Line<Cell>> pageAtScrollOffset(ScrollOffset _scrollOffset);
gsl::span<Line<Cell> const> pageAtScrollOffset(ScrollOffset _scrollOffset) const;
gsl::span<Line<Cell>> mainPage();
gsl::span<Line<Cell> const> mainPage() const;
LogicalLines<Cell> logicalLines()
{
return LogicalLines<Cell> { boxed_cast<LineOffset>(-historyLineCount()),
boxed_cast<LineOffset>(pageSize_.lines - 1),
lines_ };
}
ReverseLogicalLines<Cell> logicalLinesReverse()
{
return ReverseLogicalLines<Cell> { boxed_cast<LineOffset>(-historyLineCount()),
boxed_cast<LineOffset>(pageSize_.lines - 1),
lines_ };
}
// {{{ buffer manipulation
/// Completely deletes all scrollback lines.
void clearHistory();
/// Scrolls up by @p _n lines within the given margin.
///
/// @param _n number of lines to scroll up within the given margin.
/// @param _defaultAttributes SGR attributes the newly created grid cells will be initialized with.
/// @param _margin the margin coordinates to perform the scrolling action into.
LineCount scrollUp(LineCount _n, GraphicsAttributes _defaultAttributes, Margin _margin) noexcept;
/// Scrolls up main page by @p _n lines and re-initializes grid cells with @p _defaultAttributes.
LineCount scrollUp(LineCount _n, GraphicsAttributes _defaultAttributes = {}) noexcept;
/// Scrolls down by @p _n lines within the given margin.
///
/// @param _n number of lines to scroll down within the given margin.
/// @param _defaultAttributes SGR attributes the newly created grid cells will be initialized with.
/// @param _margin the margin coordinates to perform the scrolling action into.
void scrollDown(LineCount _n, GraphicsAttributes const& _defaultAttributes, Margin const& _margin);
// Scrolls the data within the margins to the left filling the new space on the right with empty cells.
void scrollLeft(GraphicsAttributes _defaultAttributes, Margin _margin) noexcept;
// }}}
// {{{ Rendering API
/// Renders the full screen by passing every grid cell to the callback.
template <typename RendererT>
void render(RendererT&& _render, ScrollOffset _scrollOffset = {}) const;
/// Takes text-screenshot of the main page.
[[nodiscard]] std::string renderMainPageText() const;
/// Renders the full grid's text characters.
///
/// Empty cells are represented as strings and lines split by LF.
[[nodiscard]] std::string renderAllText() const;
// }}}
[[nodiscard]] constexpr LineFlags defaultLineFlags() const noexcept;
[[nodiscard]] constexpr LineCount linesUsed() const noexcept;
void verifyState() const;
private:
CellLocation growLines(LineCount _newHeight, CellLocation _cursor);
void appendNewLines(LineCount _count, GraphicsAttributes _attr);
void clampHistory();
// {{{ buffer helpers
void resizeBuffers(PageSize _newSize)
{
auto const newTotalLineCount = historyLineCount() + _newSize.lines;
lines_.resize(unbox<size_t>(newTotalLineCount));
pageSize_ = _newSize;
}
void rezeroBuffers() noexcept { lines_.rezero(); }
void rotateBuffers(int offset) noexcept { lines_.rotate(offset); }
void rotateBuffersLeft(LineCount count) noexcept { lines_.rotate_left(unbox<size_t>(count)); }
void rotateBuffersRight(LineCount count) noexcept { lines_.rotate_right(unbox<size_t>(count)); }
// }}}
// private fields
//
PageSize pageSize_;
bool reflowOnResize_ = false;
LineCount maxHistoryLineCount_;
// Number of lines is at least the sum of maxHistoryLineCount_ + pageSize_.lines,
// because shrinking the page height does not necessarily
// have to resize the array (as optimization).
Lines<Cell> lines_;
// Number of lines used in the Lines buffer.
LineCount linesUsed_;
};
template <typename Cell>
std::ostream& dumpGrid(std::ostream& os, Grid<Cell> const& grid);
template <typename Cell>
std::string dumpGrid(Grid<Cell> const& grid);
// {{{ impl
template <typename Cell>
constexpr LineFlags Grid<Cell>::defaultLineFlags() const noexcept
{
return reflowOnResize_ ? LineFlags::Wrappable : LineFlags::None;
}
template <typename Cell>
constexpr LineCount Grid<Cell>::linesUsed() const noexcept
{
return linesUsed_;
}
template <typename Cell>
bool Grid<Cell>::isLineWrapped(LineOffset _line) const noexcept
{
return _line >= -boxed_cast<LineOffset>(historyLineCount())
&& boxed_cast<LineCount>(_line) < pageSize_.lines && lineAt(_line).wrapped();
}
template <typename Cell>
template <typename RendererT>
void Grid<Cell>::render(RendererT&& _render, ScrollOffset _scrollOffset) const
{
assert(!_scrollOffset || unbox<LineCount>(_scrollOffset) <= historyLineCount());
auto y = LineOffset(0);
for (int i = -*_scrollOffset, e = i + *pageSize_.lines; i != e; ++i, ++y)
{
auto x = ColumnOffset(0);
Line<Cell> const& line = lines_[i];
if (line.isTrivialBuffer())
_render.renderTrivialLine(line.trivialBuffer(), y);
else
{
_render.startLine(y);
for (Cell const& cell: line.cells())
_render.renderCell(cell, y, x++);
_render.endLine();
}
}
_render.finish();
}
// }}}
} // namespace terminal
// {{{ fmt formatter
namespace fmt
{
template <>
struct formatter<terminal::Margin::Horizontal>
{
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const terminal::Margin::Horizontal range, FormatContext& ctx)
{
return fmt::format_to(ctx.out(), "{}..{}", range.from, range.to);
}
};
template <>
struct formatter<terminal::Margin::Vertical>
{
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const terminal::Margin::Vertical range, FormatContext& ctx)
{
return fmt::format_to(ctx.out(), "{}..{}", range.from, range.to);
}
};
} // namespace fmt
// }}}
| {
"alphanum_fraction": 0.6102959099,
"avg_line_length": 32.2531446541,
"ext": "h",
"hexsha": "4fed5a55a0ec588e181f75fe7ee06edeb4973cfa",
"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": "0e6d75a2042437084c9f9880a5c8b5661a02da07",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "christianparpart/libterminal",
"max_forks_repo_path": "src/terminal/Grid.h",
"max_issues_count": 69,
"max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07",
"max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "christianparpart/libterminal",
"max_issues_repo_path": "src/terminal/Grid.h",
"max_line_length": 110,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "christianparpart/libterminal",
"max_stars_repo_path": "src/terminal/Grid.h",
"max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z",
"num_tokens": 4612,
"size": 20513
} |
/* matrix/gsl_matrix_uchar.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_UCHAR_H__
#define __GSL_MATRIX_UCHAR_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_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_FUN gsl_matrix_uchar *
gsl_matrix_uchar_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_uchar *
gsl_matrix_uchar_calloc (const size_t n1, const size_t n2);
GSL_FUN 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_FUN 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_FUN gsl_vector_uchar *
gsl_vector_uchar_alloc_row_from_matrix (gsl_matrix_uchar * m,
const size_t i);
GSL_FUN gsl_vector_uchar *
gsl_vector_uchar_alloc_col_from_matrix (gsl_matrix_uchar * m,
const size_t j);
GSL_FUN void gsl_matrix_uchar_free (gsl_matrix_uchar * m);
/* Views */
GSL_FUN _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_FUN _gsl_vector_uchar_view
gsl_matrix_uchar_row (gsl_matrix_uchar * m, const size_t i);
GSL_FUN _gsl_vector_uchar_view
gsl_matrix_uchar_column (gsl_matrix_uchar * m, const size_t j);
GSL_FUN _gsl_vector_uchar_view
gsl_matrix_uchar_diagonal (gsl_matrix_uchar * m);
GSL_FUN _gsl_vector_uchar_view
gsl_matrix_uchar_subdiagonal (gsl_matrix_uchar * m, const size_t k);
GSL_FUN _gsl_vector_uchar_view
gsl_matrix_uchar_superdiagonal (gsl_matrix_uchar * m, const size_t k);
GSL_FUN _gsl_vector_uchar_view
gsl_matrix_uchar_subrow (gsl_matrix_uchar * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_uchar_view
gsl_matrix_uchar_subcolumn (gsl_matrix_uchar * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_uchar_view
gsl_matrix_uchar_view_array (unsigned char * base,
const size_t n1,
const size_t n2);
GSL_FUN _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_FUN _gsl_matrix_uchar_view
gsl_matrix_uchar_view_vector (gsl_vector_uchar * v,
const size_t n1,
const size_t n2);
GSL_FUN _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_FUN _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_FUN _gsl_vector_uchar_const_view
gsl_matrix_uchar_const_row (const gsl_matrix_uchar * m,
const size_t i);
GSL_FUN _gsl_vector_uchar_const_view
gsl_matrix_uchar_const_column (const gsl_matrix_uchar * m,
const size_t j);
GSL_FUN _gsl_vector_uchar_const_view
gsl_matrix_uchar_const_diagonal (const gsl_matrix_uchar * m);
GSL_FUN _gsl_vector_uchar_const_view
gsl_matrix_uchar_const_subdiagonal (const gsl_matrix_uchar * m,
const size_t k);
GSL_FUN _gsl_vector_uchar_const_view
gsl_matrix_uchar_const_superdiagonal (const gsl_matrix_uchar * m,
const size_t k);
GSL_FUN _gsl_vector_uchar_const_view
gsl_matrix_uchar_const_subrow (const gsl_matrix_uchar * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_uchar_const_view
gsl_matrix_uchar_const_subcolumn (const gsl_matrix_uchar * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_uchar_const_view
gsl_matrix_uchar_const_view_array (const unsigned char * base,
const size_t n1,
const size_t n2);
GSL_FUN _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_FUN _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_FUN _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 */
GSL_FUN void gsl_matrix_uchar_set_zero (gsl_matrix_uchar * m);
GSL_FUN void gsl_matrix_uchar_set_identity (gsl_matrix_uchar * m);
GSL_FUN void gsl_matrix_uchar_set_all (gsl_matrix_uchar * m, unsigned char x);
GSL_FUN int gsl_matrix_uchar_fread (FILE * stream, gsl_matrix_uchar * m) ;
GSL_FUN int gsl_matrix_uchar_fwrite (FILE * stream, const gsl_matrix_uchar * m) ;
GSL_FUN int gsl_matrix_uchar_fscanf (FILE * stream, gsl_matrix_uchar * m);
GSL_FUN int gsl_matrix_uchar_fprintf (FILE * stream, const gsl_matrix_uchar * m, const char * format);
GSL_FUN int gsl_matrix_uchar_memcpy(gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);
GSL_FUN int gsl_matrix_uchar_swap(gsl_matrix_uchar * m1, gsl_matrix_uchar * m2);
GSL_FUN int gsl_matrix_uchar_swap_rows(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_uchar_swap_columns(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_uchar_swap_rowcol(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_uchar_transpose (gsl_matrix_uchar * m);
GSL_FUN int gsl_matrix_uchar_transpose_memcpy (gsl_matrix_uchar * dest, const gsl_matrix_uchar * src);
GSL_FUN unsigned char gsl_matrix_uchar_max (const gsl_matrix_uchar * m);
GSL_FUN unsigned char gsl_matrix_uchar_min (const gsl_matrix_uchar * m);
GSL_FUN void gsl_matrix_uchar_minmax (const gsl_matrix_uchar * m, unsigned char * min_out, unsigned char * max_out);
GSL_FUN void gsl_matrix_uchar_max_index (const gsl_matrix_uchar * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_uchar_min_index (const gsl_matrix_uchar * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_uchar_minmax_index (const gsl_matrix_uchar * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_uchar_isnull (const gsl_matrix_uchar * m);
GSL_FUN int gsl_matrix_uchar_ispos (const gsl_matrix_uchar * m);
GSL_FUN int gsl_matrix_uchar_isneg (const gsl_matrix_uchar * m);
GSL_FUN int gsl_matrix_uchar_isnonneg (const gsl_matrix_uchar * m);
GSL_FUN int gsl_matrix_uchar_add (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_FUN int gsl_matrix_uchar_sub (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_FUN int gsl_matrix_uchar_mul_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_FUN int gsl_matrix_uchar_div_elements (gsl_matrix_uchar * a, const gsl_matrix_uchar * b);
GSL_FUN int gsl_matrix_uchar_scale (gsl_matrix_uchar * a, const double x);
GSL_FUN int gsl_matrix_uchar_add_constant (gsl_matrix_uchar * a, const double x);
GSL_FUN int gsl_matrix_uchar_add_diagonal (gsl_matrix_uchar * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_uchar_get_row(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t i);
GSL_FUN int gsl_matrix_uchar_get_col(gsl_vector_uchar * v, const gsl_matrix_uchar * m, const size_t j);
GSL_FUN int gsl_matrix_uchar_set_row(gsl_matrix_uchar * m, const size_t i, const gsl_vector_uchar * v);
GSL_FUN 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 */
GSL_FUN INLINE_DECL unsigned char gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x);
GSL_FUN INLINE_DECL unsigned char * gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const unsigned char * gsl_matrix_uchar_const_ptr(const gsl_matrix_uchar * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
unsigned char
gsl_matrix_uchar_get(const gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
}
#endif
return m->data[i * m->tda + j] ;
}
INLINE_FUN
void
gsl_matrix_uchar_set(gsl_matrix_uchar * m, const size_t i, const size_t j, const unsigned char x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
m->data[i * m->tda + j] = x ;
}
INLINE_FUN
unsigned char *
gsl_matrix_uchar_ptr(gsl_matrix_uchar * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (unsigned char *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
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 (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (const unsigned char *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_UCHAR_H__ */
| {
"alphanum_fraction": 0.6487566607,
"avg_line_length": 37.6378830084,
"ext": "h",
"hexsha": "8183f1b13354d74700382f48f58943a3b603cfee",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_matrix_uchar.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_matrix_uchar.h",
"max_line_length": 133,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_matrix_uchar.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3395,
"size": 13512
} |
static char help[] =
"Solves a 1D advection plus diffusion problem using FD discretization\n"
"and a structured-grid (DMDA). Option prefix -b1_. Equation is\n"
" - eps u'' + (a(x) u)' = 0\n"
"with a(x)=1, on domain [-1,1], and with Dirichlet boundary conditions\n"
"u(-1) = 1, u(1) = 0. Default eps=0.01. The diffusion discretized by\n"
"centered, as usual, but advection is by first-order upwinding, centered,\n"
"or van Leer limiter scheme. An analytic Jacobian is implemented, except\n"
"for the van Leer limiter. The limiters in the residual and Jacobian\n"
"evaluations are separately controllable.\n\n";
#include <petsc.h>
typedef enum {NONE, CENTERED, VANLEER} LimiterType;
static const char *LimiterTypes[] = {"none","centered","vanleer",
"LimiterType", "", NULL};
static PetscReal centered(PetscReal theta) {
return 0.5;
}
static PetscReal vanleer(PetscReal theta) {
const PetscReal abstheta = PetscAbsReal(theta);
return 0.5 * (theta + abstheta) / (1.0 + abstheta);
}
static void* limiterptr[] = {NULL, ¢ered, &vanleer};
typedef struct {
PetscReal eps; // amount of diffusion; require: eps > 0
PetscReal (*limiter_fcn)(PetscReal),
(*jac_limiter_fcn)(PetscReal);
} AdCtx;
static PetscReal u_exact(PetscReal x, AdCtx *usr) {
return (1.0 - exp((x-1) / usr->eps)) / (1.0 - exp(- 2.0 / usr->eps));
}
static PetscReal wind_a(PetscReal x) {
return 1.0;
}
extern PetscErrorCode FormUExact(DMDALocalInfo*, AdCtx*, Vec);
extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal*,PetscReal*, AdCtx*);
extern PetscErrorCode FormJacobianLocal(DMDALocalInfo*, PetscReal*, Mat, Mat, AdCtx*);
int main(int argc,char **argv) {
PetscErrorCode ierr;
DM da, da_after;
SNES snes;
Vec u_initial, u, u_exact;
PetscReal hx, err2, errinf;
DMDALocalInfo info;
LimiterType limiter = NONE, jac_limiter;
PetscBool snesfdset, snesfdcolorset;
AdCtx user;
PetscInitialize(&argc,&argv,(char*)0,help);
user.eps = 0.01;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"b1_",
"both1d (1D advection-diffusion solver) options",""); CHKERRQ(ierr);
ierr = PetscOptionsReal("-eps","positive diffusion coefficient",
"both1d.c",user.eps,&(user.eps),NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnum("-limiter","flux-limiter type",
"both1d.c",LimiterTypes,
(PetscEnum)limiter,(PetscEnum*)&limiter,NULL); CHKERRQ(ierr);
jac_limiter = limiter;
ierr = PetscOptionsEnum("-jac_limiter","flux-limiter type used in Jacobian evaluation",
"both1d.c",LimiterTypes,
(PetscEnum)jac_limiter,(PetscEnum*)&jac_limiter,NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
if (user.eps <= 0.0) {
SETERRQ1(PETSC_COMM_SELF,2,"eps=%.3f invalid ... eps > 0 required",user.eps);
}
user.limiter_fcn = limiterptr[limiter];
ierr = PetscOptionsHasName(NULL,NULL,"-snes_fd",&snesfdset); CHKERRQ(ierr);
ierr = PetscOptionsHasName(NULL,NULL,"-snes_fd_color",&snesfdcolorset); CHKERRQ(ierr);
if (snesfdset || snesfdcolorset) {
user.jac_limiter_fcn = NULL;
jac_limiter = 4; // corresponds to empty string
} else
user.jac_limiter_fcn = limiterptr[jac_limiter];
ierr = DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,
3, // default to hx=1 grid
1,2, // d.o.f., stencil width
NULL,&da); CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMDASetUniformCoordinates(da,-1.0,1.0,-1.0,1.0,-1.0,1.0); CHKERRQ(ierr);
ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr);
ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr);
ierr = SNESSetDM(snes,da);CHKERRQ(ierr);
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)FormFunctionLocal,&user);CHKERRQ(ierr);
ierr = DMDASNESSetJacobianLocal(da,
(DMDASNESJacobian)FormJacobianLocal,&user); CHKERRQ(ierr);
ierr = SNESSetApplicationContext(snes,&user); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);
ierr = DMGetGlobalVector(da,&u_initial); CHKERRQ(ierr);
ierr = VecSet(u_initial,0.0); CHKERRQ(ierr);
ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr);
ierr = DMRestoreGlobalVector(da,&u_initial); CHKERRQ(ierr);
ierr = DMDestroy(&da); CHKERRQ(ierr);
ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr);
ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"done on %d point grid (eps = %g, limiter = %s, jac_limiter = %s)\n",
info.mx,user.eps,LimiterTypes[limiter],LimiterTypes[jac_limiter]); CHKERRQ(ierr);
ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);
ierr = FormUExact(&info,&user,u_exact); CHKERRQ(ierr);
ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) u_exact
ierr = VecNorm(u,NORM_INFINITY,&errinf); CHKERRQ(ierr);
ierr = VecNorm(u,NORM_2,&err2); CHKERRQ(ierr);
hx = 2.0 / (info.mx - 1);
err2 *= PetscSqrtReal(hx);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"numerical error: |u-uexact|_inf = %.4e, |u-uexact|_2 = %.4e\n",
errinf,err2); CHKERRQ(ierr);
VecDestroy(&u_exact); SNESDestroy(&snes);
return PetscFinalize();
}
PetscErrorCode FormUExact(DMDALocalInfo *info, AdCtx *usr, Vec uex) {
PetscErrorCode ierr;
PetscInt i;
PetscReal hx, x, *auex;
hx = 2.0 / (info->mx - 1);
ierr = DMDAVecGetArray(info->da, uex, &auex);CHKERRQ(ierr);
for (i=info->xs; i<info->xs+info->xm; i++) {
x = -1.0 + i * hx;
auex[i] = u_exact(x,usr);
}
ierr = DMDAVecRestoreArray(info->da, uex, &auex);CHKERRQ(ierr);
return 0;
}
/* compute residuals:
F_i = (- eps u'' + (a(x) u)') * hx at interior points
F_i = c (u - (b.c.)) at boundary points */
PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal *au,
PetscReal *aF, AdCtx *usr) {
const PetscReal eps = usr->eps,
hx = 2.0 / (info->mx - 1),
halfx = hx / 2.0,
hx2 = hx * hx,
scdiag = (2.0 * eps) / hx + 1.0;
PetscReal x, uE, uW, uxx, a, u_up, flux, u_dn, u_far, theta;
PetscInt i;
// for each owned cell, non-advective part of residual at cell center
for (i=info->xs; i<info->xs+info->xm; i++) {
if (i == 0) {
aF[i] = scdiag * (au[i] - 1.0);
} else if (i == info->mx-1) {
aF[i] = scdiag * (au[i] - 0.0);
} else {
uW = (i == 1) ? 1.0 : au[i-1];
uE = (i == info->mx-2) ? 0.0 : au[i+1];
uxx = (uW - 2.0 * au[i] + uE) / hx2;
aF[i] = - eps * uxx * hx;
}
}
// for each E face of an owned cell, compute flux at the face center
// and then add that to the correct residual
// note -1 start to get W faces of owned cells living on ownership
// boundaries
for (i=info->xs-1; i<info->xs+info->xm; i++) {
// if cell center is outside [-1,1], or on x=1 boundary, then no need
// to compute a flux
if (i < 0 || i == info->mx-1)
continue;
// traverse E cell face center points x_{i+1/2} for flux contributions
// get pth component of wind and first-order upwind flux
x = -1.0 + i * hx;
a = wind_a(x + halfx);
if (a >= 0.0) {
if (i == 0) {
u_up = 1.0;
} else {
u_up = au[i];
}
} else {
if (i+1 == info->mx-1) {
u_up = 0.0;
} else {
u_up = au[i+1];
}
}
flux = a * u_up;
if (usr->limiter_fcn != NULL) {
// flux correction from high-order formula with psi(theta)
if (a >= 0)
u_dn = (i+1 < info->mx-1) ? au[i+1] : 0.0;
else
u_dn = au[i];
if (u_dn != u_up) {
if (a >= 0)
u_far = (i-1 > 0) ? au[i-1] : 1.0;
else
u_far = (i+2 < info->mx-1) ? au[i+2] : 0.0;
theta = (u_up - u_far) / (u_dn - u_up);
flux += a * (*(usr->limiter_fcn))(theta) * (u_dn - u_up);
}
}
// update non-boundary and owned F_i on both sides of computed flux
// note aF[] does not have stencil width
if (i > 0 && i >= info->xs)
aF[i] += flux; // flux out of i at E
if (i+1 < info->mx-1 && i+1 < info->xs + info->xm)
aF[i+1] -= flux; // flux into i+1 at W
}
return 0;
}
PetscErrorCode FormJacobianLocal(DMDALocalInfo *info, PetscReal *u,
Mat J, Mat P, AdCtx *usr) {
PetscErrorCode ierr;
const PetscReal eps = usr->eps,
hx = 2.0 / (info->mx - 1),
halfx = hx / 2.0,
scdiag = (2.0 * eps) / hx + 1.0;
PetscInt i, col[3];
PetscReal x, aE, aW, v[3];
if (usr->jac_limiter_fcn == &vanleer) {
SETERRQ(PETSC_COMM_SELF,1,"Jacobian for vanleer limiter is not implemented");
}
ierr = MatZeroEntries(P); CHKERRQ(ierr);
for (i=info->xs; i<info->xs+info->xm; i++) {
if (i == 0 || i == info->mx-1) {
v[0] = scdiag;
ierr = MatSetValues(P,1,&i,1,&i,v,ADD_VALUES); CHKERRQ(ierr);
} else {
// diffusive part
col[0] = i;
v[0] = (2.0 * eps) / hx;
col[1] = i-1;
v[1] = (i-1 > 0) ? - eps / hx : 0.0;
col[2] = i+1;
v[2] = (i+1 < info->mx-1) ? - eps / hx : 0.0;
ierr = MatSetValues(P,1,&i,3,col,v,ADD_VALUES); CHKERRQ(ierr);
// advective part: from each adjacent face
x = -1.0 + i * hx;
aE = wind_a(x + halfx);
aW = wind_a(x - halfx);
if (aE >= 0.0) {
col[0] = i;
v[0] = aE;
} else {
col[0] = i+1;
v[0] = (i+1 < info->mx-1) ? aE : 0.0; // check if i+1 is boundary
}
if (aW >= 0.0) {
col[1] = i-1;
v[1] = (i-1 > 0) ? - aW : 0.0; // check if i-1 is boundary
} else {
col[1] = i;
v[1] = - aW;
}
ierr = MatSetValues(P,1,&i,2,col,v,ADD_VALUES); CHKERRQ(ierr);
if (usr->jac_limiter_fcn == ¢ered) {
col[0] = i+1;
col[1] = i;
if (aE >= 0.0) {
v[0] = (i+1 < info->mx-1) ? aE/2.0 : 0.0; // check if i+1 is boundary
v[1] = - aE/2.0;
} else {
v[0] = (i+1 < info->mx-1) ? - aE/2.0 : 0.0; // check if i+1 is boundary
v[1] = aE/2.0;
}
ierr = MatSetValues(P,1,&i,2,col,v,ADD_VALUES); CHKERRQ(ierr);
col[0] = i;
col[1] = i-1;
if (aW >= 0.0) {
v[0] = - aW/2.0;
v[1] = (i-1 > 0) ? aW/2.0 : 0.0; // check if i-1 is boundary
} else {
v[0] = aW/2.0;
v[1] = (i-1 > 0) ? - aW/2.0 : 0.0; // check if i-1 is boundary
}
ierr = MatSetValues(P,1,&i,2,col,v,ADD_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;
}
| {
"alphanum_fraction": 0.5271613117,
"avg_line_length": 39.4640522876,
"ext": "c",
"hexsha": "8f1fc8dc8643381857654576acbda7f3c6845643",
"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/ch11/solns/both1d.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/ch11/solns/both1d.c",
"max_line_length": 92,
"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/ch11/solns/both1d.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": 3800,
"size": 12076
} |
/*
* 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 type_3f1a28e2_0da6_44b6_84db_29542f5a65c0_h
#define type_3f1a28e2_0da6_44b6_84db_29542f5a65c0_h
#include <utility>
#include <gslib/basetype.h>
#include <gslib/math.h>
__gslib_begin__
template<class _ty, class _protopt>
struct point_t:
public _protopt
{
typedef _ty type;
typedef _protopt proto;
typedef point_t<_ty, _protopt> myref;
public:
point_t() { this->x = 0; this->y = 0; }
point_t(const proto& p): proto(p) {}
point_t(type a, type b) { this->x = a; this->y = b; }
void offset(type u, type v) { this->x += u; this->y += v; }
void offset(const proto& p) { this->x += p.x; this->y += p.y; }
void set_point(type a, type b) { this->x = a; this->y = b; }
bool operator == (const myref& that) const { return this->x == that.x && this->y == that.y; }
bool operator != (const myref& that) const { return this->x != that.x || this->y != that.y; }
};
struct vec2i { int x, y; };
typedef point_t<int, vec2i> point;
typedef point_t<float, vec2> pointf;
template<class _ty, class _ptcls>
struct rect_t
{
typedef _ty type;
typedef rect_t<_ty, _ptcls> myref;
typedef _ptcls point;
public:
type left, top, right, bottom;
public:
rect_t()
{
left = 0;
top = 0;
right = 0;
bottom = 0;
}
rect_t(type l, type t, type w, type h) { set_rect(l, t, w, h); }
type width() const { return right - left; }
type height() const { return bottom - top; }
void set_rect(type l, type t, type w, type h)
{
left = l;
top = t;
right = l + w;
bottom = t + h;
}
void set_ltrb(type l, type t, type r, type b)
{
left = l;
top = t;
right = r;
bottom = b;
}
void set_by_pts(const point& p1, const point& p2)
{
left = gs_min(p1.x, p2.x);
top = gs_min(p1.y, p2.y);
right = gs_max(p1.x, p2.x);
bottom = gs_max(p1.y, p2.y);
}
bool in_rect(const point& pt) const { return pt.x >= left && pt.x < right && pt.y >= top && pt.y < bottom; }
void offset(type x, type y) { left += x; right += x; top += y; bottom += y; }
void deflate(type u, type v);
void move_to(const point& pt) { move_to(pt.x, pt.y); }
void move_to(type x, type y);
bool operator == (const myref& that) const { return left == that.left && right == that.right && top == that.top && bottom == that.bottom; }
bool operator != (const myref& that) const { return left != that.left || right != that.right || top != that.top || bottom != that.bottom; }
type area() const { return width() * height(); }
point center() const
{
point c;
c.x = (left + right) / 2;
c.y = (top + bottom) / 2;
return c;
}
point top_left() const { return point(left, top); }
point top_right() const { return point(right, top); }
point bottom_left() const { return point(left, bottom); }
point bottom_right() const { return point(right, bottom); }
};
typedef rect_t<int, point> rect;
typedef rect_t<float, pointf> rectf;
inline rectf to_rectf(const rect& rc)
{
return std::move(rectf((float)rc.left, (float)rc.top, (float)rc.width(), (float)rc.height()));
}
inline rect to_aligned_rect(const rectf& rc)
{
return std::move(rect(round(rc.left), round(rc.top), round(rc.width()), round(rc.height())));
}
gs_export extern bool intersect_rect(rect& rc, const rect& rc1, const rect& rc2);
gs_export extern bool is_rect_intersected(const rect& rc1, const rect& rc2);
gs_export extern void union_rect(rect& rc, const rect& rc1, const rect& rc2);
gs_export extern bool substract_rect(rect& rc, const rect& rc1, const rect& rc2);
gs_export extern bool intersect_rect(rectf& rc, const rectf& rc1, const rectf& rc2);
gs_export extern bool is_rect_intersected(const rectf& rc1, const rectf& rc2);
gs_export extern bool is_rect_contained(const rect& rc1, const rect& rc2);
gs_export extern bool is_rect_contained(const rectf& rc1, const rectf& rc2);
gs_export extern void union_rect(rectf& rc, const rectf& rc1, const rectf& rc2);
gs_export extern bool substract_rect(rectf& rc, const rectf& rc1, const rectf& rc2);
gs_export extern bool is_line_rect_overlapped(const point& p1, const point& p2, const rect& rc);
gs_export extern bool is_line_rect_overlapped(const pointf& p1, const pointf& p2, const rectf& rc);
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6429932444,
"avg_line_length": 37.9802631579,
"ext": "h",
"hexsha": "46174f5fa068275d52a85c8ffc77be91f6045a3c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/gslib/type.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/gslib/type.h",
"max_line_length": 144,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/type.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": 1601,
"size": 5773
} |
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <gsl/gsl_rng.h>
#include <fastpm/libfastpm.h>
#include <fastpm/logging.h>
#include "pmpfft.h"
/* The following functions fill the gaussian field*/
static void
pmic_fill_gaussian_gadget(PM * pm, FastPMFloat * delta_k, int seed);
static void
pmic_fill_gaussian_fast(PM * pm, FastPMFloat * delta_k, int seed);
static void
pmic_fill_gaussian_slow(PM * pm, FastPMFloat * delta_k, int seed);
void
fastpm_ic_fill_gaussiank(PM * pm, FastPMFloat * delta_k, int seed, enum FastPMFillDeltaKScheme scheme)
{
/* clear the memory to avoid any modes that we forget to set. */
memset(delta_k, 0, pm_allocsize(pm) * sizeof(delta_k[0]));
switch(scheme) {
case FASTPM_DELTAK_GADGET:
pmic_fill_gaussian_gadget(pm, delta_k, seed);
break;
case FASTPM_DELTAK_FAST:
pmic_fill_gaussian_fast(pm, delta_k, seed);
break;
case FASTPM_DELTAK_SLOW:
pmic_fill_gaussian_slow(pm, delta_k, seed);
break;
default:
pmic_fill_gaussian_gadget(pm, delta_k, seed);
break;
}
}
struct PofK {
fastpm_fkfunc func;
void * data;
double Volume;
} ;
static double _powerspec_to_transfer(double k, struct PofK * pk)
{
double f = sqrt(pk->func(k, pk->data));
f *= sqrt(1.0 / pk->Volume);
return f;
}
void
fastpm_ic_induce_correlation(PM * pm, FastPMFloat * delta_k, fastpm_fkfunc pkfunc, void * data)
{
struct PofK pk;
pk.func = pkfunc;
pk.data = data;
pk.Volume = pm->Volume;
fastpm_apply_any_transfer(pm, delta_k, delta_k, (fastpm_fkfunc) _powerspec_to_transfer, &pk);
}
void
fastpm_ic_remove_variance(PM * pm, FastPMFloat * delta_k)
{
#pragma omp parallel
{
PMKIter kiter;
for(pm_kiter_init(pm, &kiter);
!pm_kiter_stop(&kiter);
pm_kiter_next(&kiter)) {
double k2 = 0;
int d;
for(d = 0; d < 3; d++) {
k2 += kiter.kk[d][kiter.iabs[d]];
}
/* https://en.wikipedia.org/wiki/Atan2 */
double a = delta_k[kiter.ind];
double b = delta_k[kiter.ind + 1];
if(a == 0 && b == 0) {
delta_k[kiter.ind + 0] = 0;
delta_k[kiter.ind + 1] = 0;
} else {
double phase = atan2(b, a);
delta_k[kiter.ind + 0] = cos(phase);
delta_k[kiter.ind + 1] = sin(phase);
}
}
}
}
static inline void
SETSEED(PM * pm, unsigned int * table[2][2], int i, int j, gsl_rng * rng)
{
unsigned int seed = 0x7fffffff * gsl_rng_uniform(rng);
int ii[2] = {i, (pm->Nmesh[0] - i) % pm->Nmesh[0]};
int jj[2] = {j, (pm->Nmesh[1] - j) % pm->Nmesh[1]};
int d1, d2;
for(d1 = 0; d1 < 2; d1++) {
ii[d1] -= pm->ORegion.start[0];
jj[d1] -= pm->ORegion.start[1];
}
for(d1 = 0; d1 < 2; d1++)
for(d2 = 0; d2 < 2; d2++) {
if( ii[d1] >= 0 &&
ii[d1] < pm->ORegion.size[0] &&
jj[d2] >= 0 &&
jj[d2] < pm->ORegion.size[1]
) {
table[d1][d2][ii[d1] * pm->ORegion.size[1] + jj[d2]] = seed;
}
}
}
static inline unsigned int
GETSEED(PM * pm, unsigned int * table[2][2], int i, int j, int d1, int d2)
{
i -= pm->ORegion.start[0];
j -= pm->ORegion.start[1];
if(i < 0) abort();
if(j < 0) abort();
if(i >= pm->ORegion.size[0]) abort();
if(j >= pm->ORegion.size[1]) abort();
return table[d1][d2][i * pm->ORegion.size[1] + j];
}
static void
SAMPLE(gsl_rng * rng, double * ampl, double * phase)
{
*phase = gsl_rng_uniform(rng) * 2 * M_PI;
*ampl = 0;
do *ampl = gsl_rng_uniform(rng); while(*ampl == 0);
}
static void
pmic_fill_gaussian_gadget(PM * pm, FastPMFloat * delta_k, int seed)
{
/* Fill delta_k with gadget scheme */
int d;
int i, j, k;
memset(delta_k, 0, sizeof(delta_k[0]) * pm->allocsize);
gsl_rng * rng = gsl_rng_alloc(gsl_rng_ranlxd1);
gsl_rng_set(rng, seed);
unsigned int * seedtable[2][2];
for(i = 0; i < 2; i ++)
for(j = 0; j < 2; j ++) {
seedtable[i][j] = calloc(pm->ORegion.size[0] * pm->ORegion.size[1], sizeof(int));
}
for(i = 0; i < pm->Nmesh[0] / 2; i++) {
for(j = 0; j < i; j++) SETSEED(pm, seedtable, i, j, rng);
for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, j, i, rng);
for(j = 0; j < i; j++) SETSEED(pm, seedtable, pm->Nmesh[0] - 1 - i, j, rng);
for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, pm->Nmesh[1] - 1 - j, i, rng);
for(j = 0; j < i; j++) SETSEED(pm, seedtable, i, pm->Nmesh[1] - 1 - j, rng);
for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, j, pm->Nmesh[0] - 1 - i, rng);
for(j = 0; j < i; j++) SETSEED(pm, seedtable, pm->Nmesh[0] - 1 - i, pm->Nmesh[1] - 1 - j, rng);
for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, pm->Nmesh[1] - 1 - j, pm->Nmesh[0] - 1 - i, rng);
}
gsl_rng_free(rng);
ptrdiff_t irel[3];
for(i = pm->ORegion.start[0];
i < pm->ORegion.start[0] + pm->ORegion.size[0];
i ++) {
gsl_rng * lower_rng = gsl_rng_alloc(gsl_rng_ranlxd1);
gsl_rng * this_rng = gsl_rng_alloc(gsl_rng_ranlxd1);
int ci = pm->Nmesh[0] - i;
if(ci >= pm->Nmesh[0]) ci -= pm->Nmesh[0];
for(j = pm->ORegion.start[1];
j < pm->ORegion.start[1] + pm->ORegion.size[1];
j ++) {
/* always pull the gaussian from the lower quadrant plane for k = 0
* plane*/
/* always pull the whitenoise from the lower quadrant plane for k = 0
* plane and k == Nmesh / 2 plane*/
int d1 = 0, d2 = 0;
int cj = pm->Nmesh[1] - j;
if(cj >= pm->Nmesh[1]) cj -= pm->Nmesh[1];
/* d1, d2 points to the conjugate quandrant */
if( (ci == i && cj < j)
|| (ci < i && cj != j)
|| (ci < i && cj == j)) {
d1 = 1;
d2 = 1;
}
unsigned int seed_conj, seed_this;
/* the lower quadrant generator */
seed_conj = GETSEED(pm, seedtable, i, j, d1, d2);
gsl_rng_set(lower_rng, seed_conj);
seed_this = GETSEED(pm, seedtable, i, j, 0, 0);
gsl_rng_set(this_rng, seed_this);
for(k = 0; k <= pm->Nmesh[2] / 2; k ++) {
int use_conj = (d1 != 0 || d2 != 0) && (k == 0 || k == pm->Nmesh[2] / 2);
double ampl, phase;
if(use_conj) {
/* on k = 0 and Nmesh/2 plane, we use the lower quadrant generator,
* then hermit transform the result if it is nessessary */
SAMPLE(this_rng, &l, &phase);
SAMPLE(lower_rng, &l, &phase);
} else {
SAMPLE(lower_rng, &l, &phase);
SAMPLE(this_rng, &l, &phase);
}
ptrdiff_t iabs[3] = {i, j, k};
ptrdiff_t ip = 0;
for(d = 0; d < 3; d ++) {
irel[d] = iabs[d] - pm->ORegion.start[d];
ip += pm->ORegion.strides[d] * irel[d];
}
if(irel[2] < 0) continue;
if(irel[2] >= pm->ORegion.size[2]) continue;
/* we want two numbers that are of std ~ 1/sqrt(2) */
ampl = sqrt(- log(ampl));
(delta_k + 2 * ip)[0] = ampl * cos(phase);
(delta_k + 2 * ip)[1] = ampl * sin(phase);
if(use_conj) {
(delta_k + 2 * ip)[1] *= -1;
}
if((pm->Nmesh[0] - iabs[0]) % pm->Nmesh[0] == iabs[0] &&
(pm->Nmesh[1] - iabs[1]) % pm->Nmesh[1] == iabs[1] &&
(pm->Nmesh[2] - iabs[2]) % pm->Nmesh[2] == iabs[2]) {
/* The mode is self conjuguate, thus imaginary mode must be zero */
(delta_k + 2 * ip)[1] = 0;
(delta_k + 2 * ip)[0] = ampl * cos(phase);
}
if(iabs[0] == 0 && iabs[1] == 0 && iabs[2] == 0) {
/* the mean is zero */
(delta_k + 2 * ip)[0] = 0;
(delta_k + 2 * ip)[1] = 0;
}
}
}
gsl_rng_free(lower_rng);
gsl_rng_free(this_rng);
}
for(i = 0; i < 2; i ++)
for(j = 0; j < 2; j ++) {
free(seedtable[i][j]);
}
/*
char * fn[1000];
sprintf(fn, "canvas.dump.f4.%d", pm->ThisTask);
fwrite(pm->canvas, sizeof(pm->canvas[0]), pm->ORegion.total * 2, fopen(fn, "w"));
*/
}
static void
pmic_fill_gaussian_fast(PM * pm, FastPMFloat * delta_k, int seed)
{
ptrdiff_t ind;
int d;
gsl_rng* random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
/* set uncorrelated seeds */
gsl_rng_set(random_generator, seed);
for(d = 0; d < pm->ThisTask * 8; d++) {
seed = 0x7fffffff * gsl_rng_uniform(random_generator);
}
gsl_rng_set(random_generator, seed);
FastPMFloat * g_x = pm_alloc(pm);
for(ind = 0; ind < pm->IRegion.total; ind += 2) {
double phase = gsl_rng_uniform(random_generator) * 2 * M_PI;
double ampl;
do
ampl = gsl_rng_uniform(random_generator);
while(ampl == 0.0);
/* we need two gaussians of std=1.0 in real space (see footnote 1) */
ampl = sqrt(-2.0 * log(ampl));
/* r2c will reduce the variance, so we compensate here. */
ampl *= sqrt(pm_norm(pm));
g_x[ind] = ampl * sin(phase);
g_x[ind + 1] = ampl * cos(phase);
}
pm_r2c(pm, g_x, delta_k);
pm_free(pm, g_x);
}
static void
pmic_fill_gaussian_slow(PM * pm, FastPMFloat * delta_k, int seed)
{
ptrdiff_t i[3] = {0};
int d;
gsl_rng* random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
gsl_rng_set(random_generator, seed);
FastPMFloat * g_x = pm_alloc(pm);
for(i[0] = 0; i[0] < pm->Nmesh[0]; i[0]++)
for(i[1] = 0; i[1] < pm->Nmesh[1]; i[1]++)
for(i[2] = 0; i[2] < pm->Nmesh[2]; i[2]++) {
double phase = gsl_rng_uniform(random_generator) * 2 * M_PI;
double ampl;
do
ampl = gsl_rng_uniform(random_generator);
while(ampl == 0.0);
ptrdiff_t ii[3];
ptrdiff_t ind = 0;
for(d = 0; d < 3; d ++) {
if(i[d] < pm->IRegion.start[d]) goto next;
if(i[d] >= pm->IRegion.start[d] + pm->IRegion.size[d]) goto next;
ii[d] = i[d] - pm->IRegion.start[d];
ind += ii[d] * pm->IRegion.strides[d];
}
/* we need two gaussians of std=1.0 in real space */
ampl = sqrt(-2.0 * log(ampl));
/* r2c will reduce the variance, so we compensate here. */
ampl *= sqrt(pm_norm(pm));
g_x[ind] = ampl * sin(phase);
next:
continue;
}
pm_r2c(pm, g_x, delta_k);
pm_free(pm, g_x);
gsl_rng_free(random_generator);
}
/* Footnotes */
/* 1):
* We want delta(k) = delta_real + I delta_imag, where delta_real and
* delta_imag are Gaussian random variables with variance given by
* power spectrum, \sigma^2=P(k). We can obtain this equivalently as
*
* delta(k) = A exp(i phase),
*
* where the phase is random (i.e. sampled from a uniform distribution)
* and the amplitude A follows a Rayleigh distribution (see
* https://en.wikipedia.org/wiki/Rayleigh_distribution). To sample from
* Rayleigh distribution, use inverse transform sampling
* (see https://en.wikipedia.org/wiki/Inverse_transform_sampling), i.e.
* start from uniform random variable in [0,1] and then apply inverse of CDF
* of Rayleigh distribution. From F(A)=CDF(A)=1-e^{-A^2/(2\sigma^2)} we get
* A = \sigma \sqrt{-2 ln(1-CDF)}. So if x is uniform random number in [0,1], then
* A = \sigma \sqrt(-2 ln(x)) follows Rayleigh distribution as desired.
* Here we used x instead of 1-x because this does not make a difference for a
* uniform random number in [0,1]. In the code below, we start with \sigma=1 and
* multiply by sqrt(P(k)) later.
*/
| {
"alphanum_fraction": 0.523115948,
"avg_line_length": 32.4164456233,
"ext": "c",
"hexsha": "f6ad5f73defe060cc32bd1d3183f8dd78246dbcc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z",
"max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sbird/FastPMRunner",
"max_forks_repo_path": "fastpm/libfastpm/initialcondition.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2",
"max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "sbird/FastPMRunner",
"max_issues_repo_path": "fastpm/libfastpm/initialcondition.c",
"max_line_length": 107,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sbird/FastPMRunner",
"max_stars_repo_path": "fastpm/libfastpm/initialcondition.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3818,
"size": 12221
} |
/*
Copyright (c) 2015, Patrick Weltevrede
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_min.h>
#include "gsl/gsl_roots.h"
#include "psrsalsa.h"
int minimize_1D_double_refine_borders(int findroot, double (*funk)(double, void *), void *params, int gridsearch, int investigateLocalMinima, double *x_lower, double *x_upper, int debug_verbose)
{
double x, y, ymin[3], ymin_new[3], dy[3], ymax, x_lower_new, x_upper_new, sign_old, gridsearch_margin, imin_new[3], i_originalgrid, imin1, imin2;
int imin[3], unset[3], i, minima;
unset[0] = unset[1] = unset[2] = 1;
for(i = 0; i < gridsearch; i++) {
x = *x_lower + i*(*x_upper - *x_lower)/(double)(gridsearch-1);
y = funk(x, params);
if(debug_verbose) {
fflush(stdout); fprintf(stderr, "x=%f y=%f\n", x, y);
}
if(findroot) {
if(i == 0) {
sign_old = y;
imin[0] = 0;
}else {
if(y < 0 && sign_old > 0) {
imin[0] = i;
}else if(y > 0 && sign_old < 0) {
imin[0] = i;
}
if(imin[0] != 0)
break;
}
}else {
if(unset[0]) {
imin[0] = i;
ymin[0] = y;
unset[0] = 0;
}else if(unset[1]) {
imin[1] = i;
ymin[1] = y;
unset[1] = 0;
}else if(unset[2]) {
imin[2] = i;
ymin[2] = y;
unset[2] = 0;
}else {
for(minima = 0; minima < 3; minima++) {
dy[minima] = ymin[minima] - y;
}
if(dy[0] > dy[1] && dy[0] > dy[2]) {
if(dy[0] > 0) {
imin[0] = i;
ymin[0] = y;
}
}else if(dy[1] > dy[0] && dy[1] > dy[2]) {
if(dy[1] > 0) {
imin[1] = i;
ymin[1] = y;
}
}else {
if(dy[2] > 0) {
imin[2] = i;
ymin[2] = y;
}
}
}
if(i == 0 || y > ymax) {
ymax = y;
}
}
}
if(findroot == 0) {
imin1 = imin[0];
imin2 = imin[0];
if(imin[1] < imin1)
imin1 = imin[1];
if(imin[2] < imin1)
imin1 = imin[2];
if(imin[1] > imin2)
imin2 = imin[1];
if(imin[2] > imin2)
imin2 = imin[2];
if(imin2-imin1 != 2 && debug_verbose) {
fflush(stdout); fprintf(stderr, "Found more than one possible minima (range = %.2f .. %.2f)\n", imin1, imin2);
}
if(imin2-imin1 > 0.3*gridsearch) {
if(investigateLocalMinima == 0) {
imin1 = imin[0];
imin2 = imin[0];
if(ymin[1] < ymin[0]) {
imin1 = imin[1];
imin2 = imin[1];
}else if(ymin[2] < ymin[0] && ymin[2] < ymin[1]) {
imin1 = imin[2];
imin2 = imin[2];
}
}else {
if(debug_verbose) {
fflush(stdout); fprintf(stderr, "Refining gridsearch around local minima\n");
}
unset[0] = unset[1] = unset[2] = 1;
for(minima = 0; minima < 3; minima++) {
for(x = *x_lower + (imin[minima]-1.5)*(*x_upper - *x_lower)/(double)(gridsearch-1); x < *x_lower + (imin[minima]+1.5)*(*x_upper - *x_lower)/(double)(gridsearch-1); x += 0.09*(*x_upper - *x_lower)/(double)(gridsearch-1)) {
y = funk(x, params);
if(debug_verbose) {
fflush(stdout); fprintf(stderr, "x=%f y=%f\n", x, y);
}
i_originalgrid = (x - *x_lower)*(double)(gridsearch-1)/(*x_upper - *x_lower);
if(unset[0] || y < ymin_new[0]) {
imin_new[0] = i_originalgrid;
ymin_new[0] = y;
unset[0] = 0;
}else if(unset[1] || y < ymin_new[1]) {
imin_new[1] = i_originalgrid;
ymin_new[1] = y;
unset[1] = 0;
}else if(unset[2] || y < ymin_new[2]) {
imin_new[2] = i_originalgrid;
ymin_new[2] = y;
unset[2] = 0;
}
}
}
imin1 = imin_new[0];
imin2 = imin_new[0];
if(imin_new[1] < imin1)
imin1 = imin_new[1];
if(imin_new[2] < imin1)
imin1 = imin_new[2];
if(imin_new[1] > imin2)
imin2 = imin_new[1];
if(imin_new[2] > imin2)
imin2 = imin_new[2];
if(imin2-imin1 != 2 && debug_verbose) {
fflush(stdout); fprintf(stderr, "Found more than one possible minima (range = %.2f .. %.2f)\n", imin1, imin2);
}
if(imin2-imin1 > 0.3*gridsearch) {
fflush(stdout); fprintf(stderr, "minimize_1D_double_refine_borders: Refining gridsearch around local minima failed\n");
exit(0);
}
}
}
}
gridsearch_margin = 0.1*(double)gridsearch;
if(gridsearch_margin < 1)
gridsearch_margin = 1;
if(findroot) {
if(imin[0] == 0) {
return 2;
}
x_lower_new = *x_lower + (imin[0]-gridsearch_margin)*(*x_upper - *x_lower)/(double)(gridsearch-1);
x_upper_new = *x_lower + (imin[0]+gridsearch_margin-1)*(*x_upper - *x_lower)/(double)(gridsearch-1);
*x_lower = x_lower_new;
*x_upper = x_upper_new;
}else {
x_lower_new = *x_lower + (imin1-gridsearch_margin)*(*x_upper - *x_lower)/(double)(gridsearch-1);
x_upper_new = *x_lower + (imin2+gridsearch_margin)*(*x_upper - *x_lower)/(double)(gridsearch-1);
*x_lower = x_lower_new;
*x_upper = x_upper_new;
}
return 0;
}
int minimize_1D_double(int findroot, double (*funk)(double, void *), void *params, double x_lower, double x_upper, int gridsearch, int investigateLocalMinima, int nested, double *x_minimum, int max_iter, double epsabs, double epsrel, int verbose, int debug_verbose)
{
const gsl_min_fminimizer_type *T_minimizer;
gsl_min_fminimizer *s_minimizer;
const gsl_root_fsolver_type *T_root;
gsl_root_fsolver *s_root;
int status;
int iter, i, ret, nest;
gsl_function F;
F.function = funk;
F.params = params;
iter = 0;
#if GSL_VERSION_NUMBER < 102
printerror(0, "ERROR minimize_1D_double: Not supported for GSL < 1.2");
exit(0);
#endif
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
if(findroot == 0)
printf("Minimising function between %f and %f\n", x_lower, x_upper);
else
printf("Finding root of function between %f and %f\n", x_lower, x_upper);
}
if(gridsearch > 1) {
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf(" Refining boundaries with a %d point grid search\n", gridsearch);
}
for(nest = 0; nest < 1+nested; nest++) {
ret = minimize_1D_double_refine_borders(findroot, funk, params, gridsearch, investigateLocalMinima, &x_lower, &x_upper, debug_verbose);
if(ret != 0) {
if(ret == 1) {
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf(" Maximum itterations (%d) exceeded while refining borders\n", max_iter);
}
}
return ret;
}
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf(" Refined boundaries are %f and %f\n", x_lower, x_upper);
}
}
}
*x_minimum = 0.5*(x_upper+x_lower);
if(findroot == 0) {
T_minimizer = gsl_min_fminimizer_brent;
s_minimizer = gsl_min_fminimizer_alloc(T_minimizer);
fflush(stdout);
gsl_min_fminimizer_set(s_minimizer, &F, *x_minimum, x_lower, x_upper);
}else {
T_root = gsl_root_fsolver_brent;
s_root = gsl_root_fsolver_alloc(T_root);
if(gridsearch == 0) {
double val1, val2;
val1 = funk(x_lower, params);
val2 = funk(x_upper, params);
if((val1 > 0 && val2 > 0) || (val1 < 0 && val2 < 0)) {
return 3;
}
}
gsl_root_fsolver_set(s_root, &F, x_lower, x_upper);
}
do {
iter++;
if(findroot == 0) {
status = gsl_min_fminimizer_iterate(s_minimizer);
#if GSL_VERSION_NUMBER >= 102
*x_minimum = gsl_min_fminimizer_x_minimum (s_minimizer);
#endif
x_lower = gsl_min_fminimizer_x_lower(s_minimizer);
x_upper = gsl_min_fminimizer_x_upper(s_minimizer);
}else {
status = gsl_root_fsolver_iterate(s_root);
*x_minimum = gsl_root_fsolver_root(s_root);
x_lower = gsl_root_fsolver_x_lower(s_root);
x_upper = gsl_root_fsolver_x_upper(s_root);
}
status = gsl_min_test_interval (x_lower, x_upper, epsabs, epsrel);
}while(status == GSL_CONTINUE && iter < max_iter);
if(findroot)
gsl_root_fsolver_free(s_root);
else
gsl_min_fminimizer_free(s_minimizer);
if(status == GSL_SUCCESS) {
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
if(findroot)
printf(" Root found at %f with error %f\n", *x_minimum, fabs(x_upper - x_lower));
else
printf(" Minimum found at %f with error %f\n", *x_minimum, fabs(x_upper - x_lower));
}
return 0;
}else if(iter == max_iter) {
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf(" Maximum itterations (%d) exceeded. Value confined to [%f, %f]\n", max_iter, x_lower, x_upper);
}
return 1;
}else {
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf(" Unknown error during minimization\n");
}
return 5;
}
return status;
}
double (*internal_funk_provided_by_user)(double *, void *);
int internal_paramnr;
double *internal_xminimum;
double internal_desired_chi2;
double internal_find_1D_error_funk(double x, void *params)
{
double chi2;
internal_xminimum[internal_paramnr] = x;
chi2 = internal_funk_provided_by_user(internal_xminimum, params);
chi2 -= internal_desired_chi2;
return chi2;
}
int find_1D_error(double (*funk)(double *, void *), double *xminimum, int paramnr, int nrparameters, double dx, double dxmax, void *params, double sigma, double chi2min, int max_itr, double epsabs, double epsrel, double *errorbar, int verbose)
{
int ittr, i, ret, debug_verbose;
double x_lower, x_upper, diff, xval, *xminimum_fiddle;
debug_verbose = 0;
dx = fabs(dx);
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf("Finding error at value %f with stepsize %f\n", xminimum[paramnr], dx);
}
xminimum_fiddle = malloc(nrparameters*sizeof(double));
if(xminimum_fiddle == NULL) {
fflush(stdout);
fprintf(stderr, "ERROR find_1D_error: Memory allocation error\n");
return 4;
}
memcpy(xminimum_fiddle, xminimum, nrparameters*sizeof(double));
internal_paramnr = paramnr;
internal_xminimum = xminimum_fiddle;
internal_funk_provided_by_user = funk;
internal_desired_chi2 = chi2min*(1+fabs(sigma));
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf(" Mimimum chi2 = %f, so %f sigma point corresponds to %f\n", chi2min, fabs(sigma), internal_desired_chi2);
}
x_lower = xminimum[paramnr];
x_upper = xminimum[paramnr];
ittr = 0;
diff = internal_find_1D_error_funk(x_upper, params);
if(diff > 0) {
fflush(stdout);
fprintf(stderr, "ERROR find_1D_error: Function called with initial parameters outside specified sigma limit: chi2 = %f higher than sigma border (%f).\n", diff, internal_desired_chi2);
exit(0);
}
do {
if(sigma >= 0) {
x_upper += dx;
if(dxmax >= 0) {
if(fabs(x_upper - xminimum[paramnr]) > dxmax) {
*errorbar = dxmax;
free(xminimum_fiddle);
return 0;
}
}
diff = internal_find_1D_error_funk(x_upper, params);
}else {
x_lower -= dx;
if(dxmax >= 0) {
if(fabs(x_lower - xminimum[paramnr]) > dxmax) {
*errorbar = dxmax;
free(xminimum_fiddle);
return 0;
}
}
diff = internal_find_1D_error_funk(x_lower, params);
}
ittr++;
if(ittr == max_itr) {
free(xminimum_fiddle);
return 1;
}
}while(diff < 0);
if(verbose) {
for(i = 0; i < verbose - 1; i++)
printf(" ");
printf(" Found brackets: [%f %f]\n", x_lower, x_upper);
verbose += 2;
}
ret = minimize_1D_double(1, internal_find_1D_error_funk, params, x_lower, x_upper, 0, 0, 0, &xval, max_itr, epsabs, epsrel, verbose, debug_verbose);
*errorbar = fabs(xval - xminimum[paramnr]);
if(verbose) {
verbose -= 2;
for(i = 0; i < verbose - 1; i++)
printf(" ");
if(ret == 0)
printf(" Found errorbar: %f\n", *errorbar);
else if(ret == 1)
printf(" Maximum nr of itterations reached, did not converge fully\n");
else if(ret == 2)
printf(" Did not find root in specified range\n");
else if(ret == 3)
printf(" Lower and upper limit do not bracket a root\n");
else {
ret = 5;
printf(" Other unspecified error\n");
}
}
free(xminimum_fiddle);
return ret;
}
| {
"alphanum_fraction": 0.6340679866,
"avg_line_length": 33.5463659148,
"ext": "c",
"hexsha": "f4bda75a0080a41a5d800021b1eabd1838e91981",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z",
"max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "David-McKenna/psrsalsa",
"max_forks_repo_path": "src/lib/minimize.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "David-McKenna/psrsalsa",
"max_issues_repo_path": "src/lib/minimize.c",
"max_line_length": 755,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "David-McKenna/psrsalsa",
"max_stars_repo_path": "src/lib/minimize.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z",
"num_tokens": 4199,
"size": 13385
} |
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* example_08-StructOfArrays-CellLinkedList-OuterOmp.c :
* Example of SPH Density Calculation using
* fast neighbor search the main density loop via
* Cell Linked List method, Struct of Arrays (SoA)
* data layout, OpenMP parallelization at the
* cell level, SIMD directives in the kernel
* and in the inner-most loop.
*
* (C) Copyright 2021 José Hugo Elsas
* Author: José Hugo Elsas <jhelsas@gmail.com>
*
* Command Line Options:
* -runs <int> : Set the number of repetitions (runs) for
* calculating the density. The value of
* the density is based on the last
* iteration.
* Default value: 1
* -run_seed <int>: Flag to set an alternative seed use for
* for the PRNG. Instead of feeding seed
* to the PRNG directly, it feeds
* seed + iteration, as to generate different
* configurations for each iteration.
* Default value: 0 - (possible 0/1)
* -seed <int>: Set the seed to use for the SPH particles
* uniform position generation in the box
* Default value: 123123123
*
* -N <int>: Set the number of SPH particles to be used
* Default value: 1e5 = 100,000
* -h <float>: Set the value of the smoothing kernel
* parameter h, which corresponds to half
* of the support of the kernel.
* Default value: 0.05
*
* -Nx <int>: Set the number of Cells in the X direction
* Default value: 10
* -Ny <int>: Set the number of Cells in the Y direction
* Default value: 10
* -Nz <int>: Set the number of Cells in the Z direction
* Default value: 10
*
* -Xmin <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 0.0
*
* -Xmax <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 1.0
* -Ymax <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 1.0
* -Zmax <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 1.0
*/
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/time.h>
#include <inttypes.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_heapsort.h>
#include "sph_data_types.h"
#include "sph_linked_list.h"
#include "sph_utils.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#define COMPUTE_BLOCKS 5
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times);
int compute_density_3d_outerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box);
int compute_density_3d_chunk_noomp(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho);
int count_box_pairs(linkedListBox *box);
int setup_box_pairs(linkedListBox *box,
int64_t *node_begin,int64_t *node_end,
int64_t *nb_begin,int64_t *nb_end);
double w_bspline_3d_constant(double h);
#pragma omp declare simd
double w_bspline_3d_simd(double q);
int main(int argc, char **argv){
bool run_seed = false; // By default the behavior is is to use the same seed
int runs = 1,err; // it only runs once
long int seed = 123123123; // The default seed is 123123123
int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000
double h=0.05; // The default kernel smoothing length is h = 0.05
linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method
SPHparticle *lsph; // Uninitialized array of SPH particles
box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain
// allow for command line customization of the run
arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options
// line arguments and override default values
err = SPHparticle_SoA_malloc(N,&lsph);
if(err)
fprintf(stderr,"error in SPHparticle_SoA_malloc\n");
void *swap_arr = malloc(N*sizeof(double));
double times[runs*COMPUTE_BLOCKS];
for(int run=0;run<runs;run+=1)
main_loop(run,run_seed,N,h,seed,swap_arr,box,lsph,times);
bool is_cll = true;
const char *prefix = "ex08,cll,SoA,outer,simd";
print_time_stats(prefix,is_cll,N,h,seed,runs,lsph,box,times);
print_sph_particles_density(prefix,is_cll,N,h,seed,runs,lsph,box);
SPHparticleSOA_safe_free(N,&lsph);
safe_free_box(box);
free(swap_arr);
return 0;
}
/*
* Function main_loop:
* Runs the main loop of the program, including the particle array generation,
* density calculation and the timings annotations.
*
* Arguments:
* run <int> : index (or value) or the present iteration
* run_seed <bool> : boolean defining whether to use run index for seed or not
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* seed <long int> : seed for GSL PRNG generator to generate particle positions
* box <linkedListBox> : Box of linked list cells, encapsulating the 3d domain
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* times <double> : Array to store the computation timings to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
* times <double> : Times is updated by reference
*/
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times)
{
int err;
if(run_seed)
err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);
else
err = gen_unif_rdn_pos_box(N,seed,box,lsph);
if(err)
fprintf(stderr,"error in gen_unif_rdn_pos\n");
// ------------------------------------------------------ //
double t0,t1,t2,t3,t4,t5;
t0 = omp_get_wtime();
err = compute_hash_MC3D(N,lsph,box); // Compute Morton Z 3D hash based on the
if(err) // cell index for each of the X, Y and Z
fprintf(stderr,"error in compute_hash_MC3D\n"); // directions, in which a given particle reside
t1 = omp_get_wtime();
qsort(lsph->hash,N,2*sizeof(int64_t),compare_int64_t); // Sort the Particle Hash Hashes, getting the shuffled
// index necessary to re-shuffle the remaining arrays
t2 = omp_get_wtime();
err = reorder_lsph_SoA(N,lsph,swap_arr); // Reorder all arrays according to the sorted hash,
if(err) // As to have a quick way to retrieve a cell
fprintf(stderr,"error in reorder_lsph_SoA\n"); // given its hash.
t3 = omp_get_wtime();
err = setup_interval_hashtables(N,lsph,box); // Annotate the begining and end of each cell
if(err) // on the cell linked list method for fast
fprintf(stderr,"error in setup_interval_hashtables\n"); // neighbor search
t4 = omp_get_wtime();
err = compute_density_3d_outerOmp(N,h,lsph,box); // Compute the density of the particles based
if(err) // on the cell linked list method for fast
fprintf(stderr,"error in compute_density\n"); // neighbor search
// ------------------------------------------------------ //
t5 = omp_get_wtime();
times[COMPUTE_BLOCKS*run+0] = t1-t0; // Time for compute morton Z 3d hash
times[COMPUTE_BLOCKS*run+1] = t2-t1; // Time for sorting the particles' hashes
times[COMPUTE_BLOCKS*run+2] = t3-t2; // Time for reordering all other arrays accordingly
times[COMPUTE_BLOCKS*run+3] = t4-t3; // Time for setting up the interval hash tables
times[COMPUTE_BLOCKS*run+4] = t5-t4; // Time for computing the SPH particle densities
return 0;
}
/*
* Function compute_density_3d_outerOmp:
* Computes the SPH density from the particles using cell linked list with
* vectorization at the compute_density_3d_chunk level, but the parallelization
* done at the level of the outer-most loop of the compute_density_3d_cll_outerOmp
* function, not at the chunk level.
*
* Arguments:
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
*/
int compute_density_3d_outerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box){
memset(lsph->rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero
#pragma omp parallel for // Execute the iteration in parallel
for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // Iterate over each receiver cell begin index
int64_t node_hash=-1,node_begin=0, node_end=0; // Start initializing the node indexes on the array
int64_t nb_begin= 0, nb_end = 0; // initialize the neighbor indexes
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; // prepare a list of potential neighbor hashes
if (kh_exist(box->hbegin, kbegin)){ // verify if that given iterator actually exists
khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); // Then get the end of the receiver cell iterator
node_hash = kh_key(box->hbegin, kbegin); // Then get the hash corresponding to it
node_begin = kh_value(box->hbegin, kbegin); // Get the receiver cell begin index in the array
node_end = kh_value(box->hend, kend); // Get the receiver cell end index in the array
neighbour_hash_3d(node_hash,nblist,box->width,box); // then find the hashes of its neighbors
for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and the iterate over them
if(nblist[j]>=0){ // if a given neighbor actually has particles
nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); // then get the contributing cell begin index
nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); // and get the contributing cell end index
compute_density_3d_chunk_noomp(node_begin,node_end,nb_begin,nb_end,h, // and compute the density contribution from
lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); // the contributing cell to the receiver cell
}
}
}
}
return 0;
}
/*
* Function compute_density_3d_chunk_noomp:
* Computes the SPH density contribution for a pair of cells, from nb_ indexes
* to the node_ indexes. No parallelization is performed with vectorization
* performed in the inner loop.
*
* Arguments:
* node_begin <int> : Begin index of the receiver cell
* node_end <int> : End index of the receiver cell
* nb_begin <int> : Begin index of the sender (neighbor) cell
* nb_end <int> : End index of the sender (neighbor) cell
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* x <double*> : Array of particles' X positions
* y <double*> : Array of particles' Y positions
* z <double*> : Array of particles' Z positions
* nu <double*> : Array of particles' density weights (i.e. masses)
* Returns:
* 0 : error code returned
* rho <double*> : Array of particles' densities
*/
int compute_density_3d_chunk_noomp(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho){
const double inv_h = 1./h;
const double kernel_constant = w_bspline_3d_constant(h);
for(int64_t ii=node_begin;ii<node_end;ii+=1){ // Iterate over the ii index of the chunk
double xii = x[ii]; // Load the X component of the ii particle position
double yii = y[ii]; // Load the Y component of the ii particle position
double zii = z[ii]; // Load the Z component of the ii particle position
double rhoii = 0.0; // Initialize the chunk contribution to density
#pragma omp simd // Hint at the compiler to vectorize
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ // Iterate over the each other particle in jj loop
double q = 0.; // Initialize the distance
double xij = xii-x[jj]; // Load and subtract jj particle's X position component
double yij = yii-y[jj]; // Load and subtract jj particle's Y position component
double zij = zii-z[jj]; // Load and subtract jj particle's Z position component
q += xij*xij; // Add the jj contribution to the ii distance in X
q += yij*yij; // Add the jj contribution to the ii distance in X
q += zij*zij; // Add the jj contribution to the ii distance in X
q = sqrt(q)*inv_h; // Sqrt to compute the distance
rhoii += nu[jj]*w_bspline_3d_simd(q); // Add up the contribution from the jj particle
} // to the intermediary density and then
rho[ii] += rhoii*kernel_constant; // add the intermediary density to the full density
}
return 0;
}
/*
* Function w_bspline_3d_constant:
* Returns the 3d normalization constant for the cubic b-spline SPH smoothing kernel
*
* Arguments:
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* Returns:
* 3d bspline normalization density <double>
*/
double w_bspline_3d_constant(double h){
return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel
}
/*
* Function w_bspline_3d_simd:
* Returns the un-normalized value of the cubic b-spline SPH smoothing kernel
*
* Arguments:
* q <double> : Distance between particles normalized by the smoothing length h
* Returns:
* wq <double> : Unnormalized value of the kernel
*
* Observation:
* Why not else if(q<2.)?
* Because if you use "else if", the compiler refuses to vectorize,
* This results in a large slowdown, as of 2.5x slower for example_04
*/
#pragma omp declare simd
double w_bspline_3d_simd(double q){
double wq=0;
double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline
double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline
if(q<2.) // If the distance is below 2
wq = wq2; // Use the 2nd polynomial for the spline
if(q<1.) // If the distance is below 1
wq = wq1; // Use the 1st polynomial for the spline
return wq; // return which ever value corresponds to the distance
} | {
"alphanum_fraction": 0.5638479784,
"avg_line_length": 48.6032171582,
"ext": "c",
"hexsha": "8ad322d32feafff0e75aa34ddc00d60a491a02b5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jhelsas/sphalerite",
"max_forks_repo_path": "SoA/exec/example_08-StructOfArrays-CellLinkedList-OuterOmp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "jhelsas/sphalerite",
"max_issues_repo_path": "SoA/exec/example_08-StructOfArrays-CellLinkedList-OuterOmp.c",
"max_line_length": 143,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jhelsas/sphalerite",
"max_stars_repo_path": "SoA/exec/example_08-StructOfArrays-CellLinkedList-OuterOmp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4320,
"size": 18129
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* Begin constants */
#define VERBOSE 0 //when set to 1, running smc_sampler(...) will generate A LOT of output.
#define M 200
#define MH_STEPS 10
#define N_MIXTURE_COMPONENTS 4
#define SIGMA 0.55
#define HLINE printf("\n--------------------------------------------------------------------------------\n")
const double MIXTURE_WEIGHTS[N_MIXTURE_COMPONENTS] = {0.25,0.25,0.25,0.25};
static double* xNew; //an array used for swapping
/* begin function-signatures */
int test(void);
void allocateParticle_swap(void);
double dnorm(const double x,const double mu);
double log_likelihood(const double * y, const int N_y, const double* mu);
_Bool ESS_is_largeEnough(const double * W,const int N_W);
double pi_updateStep(const double* y,const int N_y, const double* x, const int n);
void smc_sampler(const double* yObs,const int N_yObs ,const int n_particles , double** particles, double* weights);
void randParticle(double * x);
void resample(double ** particles, double * weights,const int n_particles, const double w0, gsl_rng * r, gsl_ran_discrete_t * wSampler);
void propagate_particle(double * x,const int n, const double* yObs,const int N_yObs,gsl_rng * r);
void smc_sampler_for_R( double* yObs, int* N_yObs, int* N_particles, double* X_vec, double* W, double* time);
void freeParticle_swap(void);
int main(){
allocateParticle_swap();
return test();
freeParticle_swap();
}
/* a wrapper function for calling smc_sampler from R */
void smc_sampler_for_R(
double* yObs,
int* N_yObs,
int* N_particles,
double* X_vec,
double* W,
double* t_SMC )
{
// allocate memmory for swapping
allocateParticle_swap();
// Generate an (N_particles x N_MIXTURE_COMPONENTS) array used to
// internally represent particles
double** X;
X = (double**) malloc(sizeof(double *) * (*N_particles));
size_t i = 0;
for(i=0 ; i < *N_particles ; ++i){
X[i] = (double*) malloc(sizeof(double)*N_MIXTURE_COMPONENTS);
}
//start timer
time_t t0 = time(NULL);
//run sampler
smc_sampler(yObs,*N_yObs,*N_particles,X,W);
//stop timer
time_t t1 = time(NULL);
//return runtime in secconds
*t_SMC = difftime(t1,t0);
//write to output vector
size_t j;
for( i = 0 ; i < (*N_particles) ; ++i){
for( j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){
X_vec[N_MIXTURE_COMPONENTS * i + j] = X[i][j];
}
}
//free up memory;
for(i=0 ; i < *N_particles ; ++i){
free(X[i]);
}
free(X);
freeParticle_swap();
/* //for debugging.
int i;
for(i=0 ; i < *N_particles ; ++i){
X_vec[i] = (double) i;
}
*/
}
/* Main function for running SMC sampler
yObs is an a vector of N_yObs observations
n_particles is the desired number of particles to be simulated
particles should be a double[n_particles][N_MIXTURE_COMPONENTS] array.
It will be used for storing results and doing computaations.
weights should be a double[n_particles] array.
It will be used for storing results and doing computations.
*/
void smc_sampler(
const double* yObs,
const int N_yObs,
const int n_particles,
double** particles,
double* weights)
{
time_t t0 = time(NULL);
time_t t1;
size_t i; //summation indices
gsl_rng * r = gsl_rng_alloc(gsl_rng_mt19937);
gsl_ran_discrete_t * wSampler;
if(VERBOSE) printf("Initializinng...");
/* Initialize weights and particles*/
double w0 = 1 / (double) n_particles; // default weight
for(i=0; i < n_particles ; ++i){
weights[i] = w0;
randParticle(particles[i]);
}
if(VERBOSE) printf("DONE!\n");
if(VERBOSE) time(&t1);
if(VERBOSE) printf("Elapsed time = %.0f sec\n",difftime(t1,t0));
if(VERBOSE) printf("Running sampling steps from 1 to 200...\n");
/* Iterate from n=1 to n=M */
int n = 1;
unsigned int resampleCounter = 0;
while(1){
// for diagnosing running time and output
if((n-1)%10 == 0){
if(VERBOSE) time(&t1);
if(VERBOSE) printf("Running steps %i...%i; \t",n,n+9);
if(VERBOSE) printf("elapsed time so far = %.0f sec\n",difftime(t1,t0));
if(VERBOSE){
printf("Printing the first 10 particles to check validity of output:\n");
size_t j;
for(i=0;i<10;++i){
printf(" x[%i]_(%i) = ",(int) i,n);
for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){
if(particles[i][j] >= 0) printf(" ");
if(fabs(particles[i][j]) < 10) printf(" ");
printf("%.3f\t",particles[i][j]);
}
printf(" \tW[%i](%i) = %f",(int) i , n, weights[i]);
printf("\n");
}
}
double sumW = 0;
for(i = 0 ; i < n_particles ; ++i){
sumW += weights[i];
}
if(VERBOSE) printf("sum of weights = %f",sumW);
if(VERBOSE) HLINE;
}
/* Resample and reset weights, if nessecary */
if(!(ESS_is_largeEnough(weights,n_particles))){
if(VERBOSE) ++resampleCounter;
if(VERBOSE) HLINE;
if(VERBOSE) printf("resampling in step n = %i\n",n);
if(VERBOSE) HLINE;
//Preprocessing for sampling from a discrete distribution
wSampler = gsl_ran_discrete_preproc (n_particles,weights);
//Resample (AND reset) weights
resample(particles,weights,n_particles,w0,r,wSampler);
}
/* Update particle weights */
double sumW = 0;
for(i = 0 ; i<n_particles ; ++i){
weights[i] *= pi_updateStep(yObs, N_yObs, particles[i] ,n);
sumW += weights[i];
}
double Z = (double) 1 / sumW;
for(i = 0 ; i<n_particles ; ++i){
weights[i] *= Z;
}
/* break out when n == M */
if(n==M) break;
/* Propagate particles */
for(i=0; i<n_particles ; ++i){
propagate_particle(particles[i], n, yObs, N_yObs,r);
}
/*increment counter*/
++n;
}
if(VERBOSE) printf("total number of resampling-steps = %i\n",resampleCounter);
gsl_rng_free(r);
// gsl_ran_discrete_free(wSampler);
}
/**********************
* Auxiliary Functions *
**********************/
void allocateParticle_swap(void){
//modify in case of parralelization
xNew = (double*) malloc(sizeof(double)*N_MIXTURE_COMPONENTS);
}
void freeParticle_swap(void){
//modify in case of parralelization
free(xNew);
}
double dnorm(const double x, const double mu){
return gsl_sf_erf_Z((x - mu)/SIGMA)/SIGMA;
}
/* returns log( p( y | mu , sigma , weights ) )
y should be a vector of doubles corresponding to observations
N_y corresponds to the length of y
mu coresponds to a vector of modes of length N_MIXTURE_COMPONENTS */
double log_likelihood(const double* y, const int N_y,const double* mu){
int i; int j; // initialize summation-indices
/* Verify that all modes are in [-10,10] */
for(i=0; i<N_MIXTURE_COMPONENTS; ++i){
//INFINITY is a macro defined in math.h
if( mu[i] > 10.0 || mu[i] < -10.0 ){
if(VERBOSE) printf("WOAH! particle out of range\n");
return -INFINITY;
}
}
/* Compute the log-likelihood iteratively */
double sum; // inner summation (over mu)
double Sum = 0; //outer summation (over y)
for(i = 0;i < N_y; ++i){
sum = 0;
for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){
sum += MIXTURE_WEIGHTS[j] * dnorm(y[i], mu[j]);
}
Sum += log(sum);
}
return Sum;
}
/* Generates a ranodm particle ie. 4 ind. samples uniformly from -10 to 10 */
/* Results are stored in x */
void randParticle(double* x){
unsigned char i;
for(i=0 ; i<N_MIXTURE_COMPONENTS; ++i){
x[i] = (double) -10 + (double) 20 * (double) rand() / (double) RAND_MAX;
}
}
_Bool ESS_is_largeEnough(const double * W,const int N_W){
double sumSq = 0;
int i;
for(i = 0 ; i < N_W ; ++i){
sumSq += W[i] * W[i];
}
return (_Bool) 1 >= sumSq * N_W / 2.0;
}
void resample(
double ** particles,
double * weights,
const int n_particles,
const double w0,
gsl_rng * r,
gsl_ran_discrete_t * wSampler)
{
size_t i; size_t j;
for(i=0; i< n_particles; ++i){
//iterate over particles
size_t i_new = gsl_ran_discrete(r,wSampler);
// copy the particle in question
for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){
particles[i][j] = particles[i_new][j];
}
}
//reset particle weights
for(i=0; i < n_particles ; ++i){
weights[i] = w0;
}
}
/*
A n auxiliary function for computing pi_n(x_(n-1)) / pi_(n-1)(x_(n-1))
\eqn{\propto} p( x_(n-1) | y ) ^ ((2n -1)/M^2). Used when updating weights.
@param y Observed data
@param x Our proposed value for Mu (a vector of modes)
*/
double pi_updateStep(const double* y,const int N_y, const double* x,const int n){
return exp( ( ((float) 2*n -1)/((float) (M*M)) ) * log_likelihood(y,N_y,x));
}
void propagate_particle(double * x,const int n, const double* yObs,const int N_yObs,gsl_rng * r){
//NOTE: xNew MUST have been allocated before calling this method!
size_t i = 0; size_t j;
for(i = 0 ; i < MH_STEPS ; ++i){
// Generate new observation
for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){
xNew[j] = x[j] + gsl_ran_gaussian(r,SIGMA);
}
/*
// REMOVE WHEN COMPILING FOR SPEED!
if(VERBOSE){
// printf("Acceptance! alpha = %0.3f\n",alpha);
printf(" x\t= ");
for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){
if(x[j] >= 0) printf(" ");
if(fabs(x[j]) < 10) printf(" ");
printf("%.3f\t",x[j]);
}
printf("\n x_new\t=");
for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){
if(xNew[j] >= 0) printf(" ");
if(fabs(xNew[j]) < 10) printf(" ");
printf("%.3f\t",xNew[j]);
}
printf("\n");
}
*/
// double logL_new = log_likelihood(yObs, N_yObs, xNew);
// double logL_old = log_likelihood(yObs, N_yObs, x);
double logL_Diff = log_likelihood(yObs, N_yObs, xNew) - log_likelihood(yObs, N_yObs, x);
double alpha = 1;
_Bool autoAccept = 1;
// Iff logL_Diff < 0 true, the sign of the argument fo exp() will be <1.
if(logL_Diff < 0){
double exponent = (double) n / (double) M;
exponent *= exponent; // square the exponent
alpha = exp(exponent * logL_Diff );
autoAccept = 0;
if(VERBOSE) printf("alpha = %.4f",alpha);
}
if( autoAccept || ((double) rand() / (double) RAND_MAX) < alpha){
if( VERBOSE && !autoAccept ) printf("\t new point accepted anyway\n");
for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){
x[j] = xNew[j];
}
} else {
if(VERBOSE) printf("\n");
}
}
if(VERBOSE) printf("\n");
}
/* A generic function to test during development
Returns 0 if test succcessfull*/
int test(void){
/*
double x = 1; double y;
double mu = 0; double sigma = 5;
y = dnorm(x,mu,sigma);
printf("Hello World!\nNormal(1;0,5) = %.10f\n",y);
*/
/*
double y[2] = {0,2};
double mu[4] = {-3,0,3,6};
double x = log_likelihood(y,2,mu);
printf("Hello World!\nx = %.10f\n",x);
*/
/*
double mu[4] = {-3,0,3,6};
if( mu[2] < 10 ) printf("Hello World!\n");
*/
/*
int N_W = 6;
double W1[6] = {1,0,0,0,0,0};
double W2[6] = {0.2,0.2,0.2,0.2,0.2,0};
if(!(ESS_is_largeEnough(W1,N_W))) printf("ESS1 is too small!\n");
if(ESS_is_largeEnough(W2,N_W)) printf("ESS2 on the other hand is groovy!\n");
*/
/*
double y[2] = {0,2};
double mu[4] = {-3,0,3,6};
double x = pi_updateStep(y,2,mu,180);
printf("Hello World!\nx = %.10f\n",x);
*/
/*
int i; int j;
double particles[10][4];
for(i = 0 ; i<10; ++i){
randParticle(particles[i]);
}
for(i=0 ; i<10 ; ++i){
printf("rand particles = (");
for(j=0 ; j< 4 ; ++j){
printf(" %.2f ",particles[i][j]);
}
printf( ")\n");
}
*/
/*
int N = 1000;
double* W;
W = (double*) malloc(sizeof(double)*N);
double** X;
X = (double**) malloc(sizeof(double *) * N);
size_t i = 0;
for(i=0 ; i < N ; ++i){
X[i] = (double*) malloc(sizeof(double*)*N_MIXTURE_COMPONENTS);
}
// double W;
// double* X[N][N_MIXTURE_COMPONENTS];
// data pasted in from R
// generated using sampleMM(100) from mixtureModel_SMC.R
int N_yObs = 100;
double yObs[100] =
{0.270469630282116 , 0.0948544266135598 , 4.82353957890236 ,
2.71176569013062 , -2.10140287048951 , -2.4639397242585 ,
-2.47096320311181 , 5.59163596897931 , -3.50775981783882 ,
3.26972797997964 , 3.32256384988976 , 5.73616849148524 ,
5.74816296903159 , -2.97620992270215 , -0.211030444261816 ,
5.56902016608288 , -3.69397287391297 , 5.71718272922272 ,
-0.375056085230512 , 0.290727561775271 , 3.53116678441137 ,
-2.92396872511173 , 5.44623183851942 , 5.60306594746839 ,
5.56855197639855 , 2.28105552916777 , 2.71638272346431 ,
3.7321825583144 , 6.10978497180474 , 6.7089442115652 ,
3.14182326021059 , -2.72341774114777 , -0.0919451805310823 ,
-3.05334875104901 , 6.00697089830724 , -2.81827687988051 ,
6.03028599825704 , 3.77081092101111 , -0.17554472859167 ,
5.57845673340545 , 6.25654424410659 , 6.40046681340197 ,
-2.39322730700275 , 0.937990298556008 , -3.61930611127869 ,
2.99419558349795 , -2.95427533963002 , 2.53999917081115 ,
-4.35170347149833 , 2.56389630336686 , 2.78219272857881 ,
-2.53796084626858 , 2.75783249644654 , 0.265653681397089 ,
-4.08489661583957 , 0.141285949971235 , -3.09744117607388 ,
-3.29683116823359 , -0.56348650880506 , 2.13298104427159 ,
5.81313774243827 , 2.90131666078861 , -0.870942485382193 ,
-0.653182465687133 , 3.24697479240955 , 3.46323186816872 ,
3.70853665171654 , -3.79582094987125 , 6.55169236217858 ,
-3.63836564940765 , 0.132152004366257 , 5.24827155186988 ,
2.53806422373366 , 5.6550753862474 , 2.42737960470922 ,
5.88968129179486 , 6.83133504027115 , -0.473386824297909 ,
-0.883286661476473 , 6.94044430889499 , 2.73913195305667 ,
3.02781182874733 , 6.53392928375413 , 6.53623960926176 ,
6.44586265929949 , 0.737757409838858 , -2.81327223680057 ,
0.534431297323472 , -3.28504638650391 , -0.0839400339092673 ,
-3.30271081947717 , 5.97247453668681 , -3.55468774001656 ,
-0.211152666301356 , 6.12181217531004 , 2.56643856048767 ,
0.200557127297898 , -3.97176332345347 , 0.0176492920069539 ,
2.87381823065611};
printf("Running SMC-sampler with %i particles, based on %i observations.\n",N,N_yObs);
time_t t1 = time(NULL);
smc_sampler(yObs,N_yObs,N,X,W);
time_t t2 = time(NULL);
printf("DONE!\nTotal elapsed time = %.0f\n",difftime(t2,t1));
HLINE;
printf("Printing the first 10 particles to check validity of output:\n");
size_t j;
for(i=0;i<10;++i){
printf(" x[%i] = ",(int) i);
for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){
if(X[i][j] >= 0) printf(" ");
if(fabs(X[i][j]) < 10) printf(" ");
printf("%.3f\t",X[i][j]);
}
printf("\n");
}
free(W);
// free(X)
for(i=0 ; i<N; ++i){
free(X[i]);
}
free(X);
*/
/*
int N_yObs = 100;
//DATA from R, so that the S-method and the .c method can be directly compated
double yObs[100] = {6.42614409154078,0.260646235868524,6.20077626783781,-3.54124388162526,3.16810352365003,-3.02631343546788,6.22743478871312,6.8131742684717,6.24776924281844,3.65204896173014,6.01102502511306,-2.78204404408537,6.54496067301763,2.86661732139087,6.41368106980899,-2.54549938986914,6.08430821908108,2.65819528014716,-4.10369954335742,-3.70836228135375,3.55973960494948,-3.99408019214758,-3.06751044524848,-0.560058224387682,0.625592793169344,2.58052593365431,0.689049384542289,0.494930560119956,0.390397430673082,2.87213201595585,6.08140477180053,-3.63073724259346,1.76368358083185,0.0978387885170348,6.49576360025151,6.65592881975105,-2.31116539097971,6.69822824187681,0.0197128170022586,-3.6584094557839,6.37219590110012,5.98608504754753,5.76477302651333,-2.49473884182791,3.68861876383596,6.71753596416937,-2.86065603329243,2.36234293889529,-2.13229209410826,-3.1821797074668,3.67640450999392,2.35200323180728,-2.90422204445312,3.85237110998024,5.73406945312462,3.61994874049274,-4.0561902744938,5.66696946993138,5.96245114627653,6.59816990256299,0.231879318383607,2.34472949459441,2.72937582033292,-0.444334698629388,2.22482121394123,3.15359838488669,5.79310254628412,2.95627482456672,0.0754282164405023,-3.27128946837834,-2.77302236660845,7.25710145940199,6.2324724323204,5.9296066592542,5.60999425487975,-0.286465744070193,0.587073138580418,-2.67791031284446,6.98129381109518,3.36137498170339,-3.16490919686681,-3.62156309636938,5.41982668735859,-3.07991914749654,-2.89255426727392,5.61010574600101,-3.10612256078391,3.48991878214866,2.58896632171936,0.703862729104843,4.72001741709978,-0.244802119787893,6.45395925612269,0.253461730596016,2.69213945052578,-2.90338536462303,3.28208239426602,-2.57167632631676,0.920364746339414,0.993277872559861};
int N_X = 5;
double X[5][4] = {
{0,3,-3,6},
{-3,0,3,6},
{0,0,0,0},
{9,9,9,9},
{0,6,3,15}
};
size_t i;
for(i = 0 ; i<N_X ; ++i){
double LL = log_likelihood(yObs,N_yObs,X[i]);
printf("log_L(X[%i]) = %f\n",(int) i,LL);
}
*/
return 0;
}
| {
"alphanum_fraction": 0.643991063,
"avg_line_length": 31.4962962963,
"ext": "c",
"hexsha": "fe6b7a838ae429c840e8f32acda2a933f4c59c88",
"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": "cd7b6846905d8374936dde5835d5732aa90fd56e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Cronjaeger/OxWaSP-Project7",
"max_forks_repo_path": "parallelComparisonpkg/src/SMC_sampler.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cd7b6846905d8374936dde5835d5732aa90fd56e",
"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": "Cronjaeger/OxWaSP-Project7",
"max_issues_repo_path": "parallelComparisonpkg/src/SMC_sampler.c",
"max_line_length": 1769,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cd7b6846905d8374936dde5835d5732aa90fd56e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Cronjaeger/OxWaSP-Project7",
"max_stars_repo_path": "parallelComparisonpkg/src/SMC_sampler.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5874,
"size": 17008
} |
/* specfunc/coupling.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_gamma.h"
#include "gsl_sf_coupling.h"
#include "error.h"
inline
static
int locMax3(const int a, const int b, const int c)
{
int d = GSL_MAX(a, b);
return GSL_MAX(d, c);
}
inline
static
int locMin3(const int a, const int b, const int c)
{
int d = GSL_MIN(a, b);
return GSL_MIN(d, c);
}
inline
static
int locMin5(const int a, const int b, const int c, const int d, const int e)
{
int f = GSL_MIN(a, b);
int g = GSL_MIN(c, d);
int h = GSL_MIN(f, g);
return GSL_MIN(e, h);
}
/* See: [Thompson, Atlas for Computing Mathematical Functions] */
static
int
delta(int ta, int tb, int tc, gsl_sf_result * d)
{
gsl_sf_result f1, f2, f3, f4;
int status = 0;
status += gsl_sf_fact_e((ta + tb - tc)/2, &f1);
status += gsl_sf_fact_e((ta + tc - tb)/2, &f2);
status += gsl_sf_fact_e((tb + tc - ta)/2, &f3);
status += gsl_sf_fact_e((ta + tb + tc)/2 + 1, &f4);
if(status != 0) {
OVERFLOW_ERROR(d);
}
d->val = f1.val * f2.val * f3.val / f4.val;
d->err = 4.0 * GSL_DBL_EPSILON * fabs(d->val);
return GSL_SUCCESS;
}
static
int
triangle_selection_fails(int two_ja, int two_jb, int two_jc)
{
return ((two_jb < abs(two_ja - two_jc)) || (two_jb > two_ja + two_jc));
}
static
int
m_selection_fails(int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc)
{
return ( abs(two_ma) > two_ja
|| abs(two_mb) > two_jb
|| abs(two_mc) > two_jc
|| GSL_IS_ODD(two_ja + two_ma)
|| GSL_IS_ODD(two_jb + two_mb)
|| GSL_IS_ODD(two_jc + two_mc)
|| (two_ma + two_mb + two_mc) != 0
);
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_coupling_3j_e(int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc,
gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(two_ja < 0 || two_jb < 0 || two_jc < 0) {
DOMAIN_ERROR(result);
}
else if( triangle_selection_fails(two_ja, two_jb, two_jc)
|| m_selection_fails(two_ja, two_jb, two_jc, two_ma, two_mb, two_mc)
) {
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
gsl_sf_result n1_a, n1_b, n3_a, n3_b;
gsl_sf_result d1_a, d1_b, d2_a, d2_b, d3_a, d3_b;
gsl_sf_result n1, n2, n3;
gsl_sf_result d1, d2, d3;
double norm;
double sign = (GSL_IS_ODD((two_ja - two_jb - two_mc)/2) ? -1.0 : 1.0);
int tk, tkmin, tkmax;
double sum_pos = 0.0;
double sum_neg = 0.0;
double phase;
int status = 0;
status += gsl_sf_fact_e((two_jc + two_ja - two_jb)/2, &n1_a);
status += gsl_sf_fact_e((two_jc - two_ja + two_jb)/2, &n1_b);
status += gsl_sf_fact_e((two_ja + two_jb - two_jc)/2, &n2);
status += gsl_sf_fact_e((two_jc - two_mc)/2, &n3_a);
status += gsl_sf_fact_e((two_jc + two_mc)/2, &n3_b);
status += gsl_sf_fact_e((two_ja + two_jb + two_jc)/2 + 1, &d1);
status += gsl_sf_fact_e((two_ja - two_ma)/2, &d2_a);
status += gsl_sf_fact_e((two_ja + two_ma)/2, &d2_b);
status += gsl_sf_fact_e((two_jb - two_mb)/2, &d3_a);
status += gsl_sf_fact_e((two_jb + two_mb)/2, &d3_b);
if(status != 0) {
OVERFLOW_ERROR(result);
}
n1.val = n1_a.val * n1_b.val;
n3.val = n3_a.val * n3_b.val;
d2.val = d2_a.val * d2_b.val;
d3.val = d3_a.val * d3_b.val;
norm = sign * sqrt(n1.val*n2.val*n3.val)/sqrt(d1.val*d2.val*d3.val);
tkmin = GSL_MAX(0, two_jb - two_ja - two_mc);
tkmax = GSL_MIN(two_jc - two_ja + two_jb, two_jc - two_mc);
phase = GSL_IS_ODD((tkmin + two_jb + two_mb)/2) ? -1.0 : 1.0;
for(tk=tkmin; tk<=tkmax; tk += 2) {
double term;
status = 0;
status += gsl_sf_fact_e((two_jb + two_jc + two_ma - tk)/2, &n1);
status += gsl_sf_fact_e((two_ja - two_ma + tk)/2, &n2);
status += gsl_sf_fact_e(tk/2, &d1_a);
status += gsl_sf_fact_e((two_jc - two_ja + two_jb - tk)/2, &d1_b);
status += gsl_sf_fact_e((two_jc - two_mc - tk)/2, &d2);
status += gsl_sf_fact_e((two_ja - two_jb + two_mc + tk)/2, &d3);
if(status != 0) {
OVERFLOW_ERROR(result);
}
d1.val = d1_a.val * d1_b.val;
term = phase * n1.val * n2.val / (d1.val * d2.val * d3.val);
phase = -phase;
if(norm*term >= 0.0) {
sum_pos += norm*term;
}
else {
sum_neg -= norm*term;
}
}
result->val = sum_pos - sum_neg;
result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);
result->err += 2.0 * GSL_DBL_EPSILON * (tkmax - tkmin) * fabs(result->val);
return GSL_SUCCESS;
}
}
int
gsl_sf_coupling_6j_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if( two_ja < 0 || two_jb < 0 || two_jc < 0
|| two_jd < 0 || two_je < 0 || two_je < 0
) {
DOMAIN_ERROR(result);
}
else if( triangle_selection_fails(two_ja, two_jb, two_je)
|| triangle_selection_fails(two_ja, two_jc, two_jf)
|| triangle_selection_fails(two_jb, two_jd, two_jf)
|| triangle_selection_fails(two_jc, two_jd, two_je)
) {
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
gsl_sf_result n1;
gsl_sf_result d1, d2, d3, d4, d5, d6;
double norm;
int tk, tkmin, tkmax;
double phase;
double sum_pos = 0.0;
double sum_neg = 0.0;
double sumsq_err = 0.0;
int status = 0;
status += delta(two_ja, two_jb, two_je, &d1);
status += delta(two_ja, two_jc, two_jf, &d2);
status += delta(two_jb, two_jd, two_jf, &d3);
status += delta(two_jc, two_jd, two_je, &d4);
if(status != GSL_SUCCESS) {
OVERFLOW_ERROR(result);
}
norm = sqrt(d1.val) * sqrt(d2.val) * sqrt(d3.val) * sqrt(d4.val);
tkmin = locMax3(0,
two_ja + two_jd - two_je - two_jf,
two_jb + two_jc - two_je - two_jf);
tkmax = locMin5(two_ja + two_jb + two_jc + two_jd + 2,
two_ja + two_jb - two_je,
two_jc + two_jd - two_je,
two_ja + two_jc - two_jf,
two_jb + two_jd - two_jf);
phase = GSL_IS_ODD((two_ja + two_jb + two_jc + two_jd + tkmin)/2)
? -1.0
: 1.0;
for(tk=tkmin; tk<=tkmax; tk += 2) {
double term;
double term_err;
gsl_sf_result den_1, den_2;
gsl_sf_result d1_a, d1_b;
status = 0;
status += gsl_sf_fact_e((two_ja + two_jb + two_jc + two_jd - tk)/2 + 1, &n1);
status += gsl_sf_fact_e(tk/2, &d1_a);
status += gsl_sf_fact_e((two_je + two_jf - two_ja - two_jd + tk)/2, &d1_b);
status += gsl_sf_fact_e((two_je + two_jf - two_jb - two_jc + tk)/2, &d2);
status += gsl_sf_fact_e((two_ja + two_jb - two_je - tk)/2, &d3);
status += gsl_sf_fact_e((two_jc + two_jd - two_je - tk)/2, &d4);
status += gsl_sf_fact_e((two_ja + two_jc - two_jf - tk)/2, &d5);
status += gsl_sf_fact_e((two_jb + two_jd - two_jf - tk)/2, &d6);
if(status != GSL_SUCCESS) {
OVERFLOW_ERROR(result);
}
d1.val = d1_a.val * d1_b.val;
d1.err = d1_a.err * fabs(d1_b.val) + fabs(d1_a.val) * d1_b.err;
den_1.val = d1.val*d2.val*d3.val;
den_1.err = d1.err * fabs(d2.val*d3.val);
den_1.err += d2.err * fabs(d1.val*d3.val);
den_1.err += d3.err * fabs(d1.val*d2.val);
den_2.val = d4.val*d5.val*d6.val;
den_2.err = d4.err * fabs(d5.val*d6.val);
den_2.err += d5.err * fabs(d4.val*d6.val);
den_2.err += d6.err * fabs(d4.val*d5.val);
term = phase * n1.val / den_1.val / den_2.val;
phase = -phase;
term_err = n1.err / fabs(den_1.val) / fabs(den_2.val);
term_err += fabs(term / den_1.val) * den_1.err;
term_err += fabs(term / den_2.val) * den_2.err;
if(term >= 0.0) {
sum_pos += norm*term;
}
else {
sum_neg -= norm*term;
}
sumsq_err += norm*norm * term_err*term_err;
}
result->val = sum_pos - sum_neg;
result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);
result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0));
result->err += 2.0 * GSL_DBL_EPSILON * (tkmax - tkmin + 2.0) * fabs(result->val);
return GSL_SUCCESS;
}
}
int
gsl_sf_coupling_9j_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji,
gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if( two_ja < 0 || two_jb < 0 || two_jc < 0
|| two_jd < 0 || two_je < 0 || two_jf < 0
|| two_jg < 0 || two_jh < 0 || two_ji < 0
) {
DOMAIN_ERROR(result);
}
else if( triangle_selection_fails(two_ja, two_jb, two_jc)
|| triangle_selection_fails(two_jd, two_je, two_jf)
|| triangle_selection_fails(two_jg, two_jh, two_ji)
|| triangle_selection_fails(two_ja, two_jd, two_jg)
|| triangle_selection_fails(two_jb, two_je, two_jh)
|| triangle_selection_fails(two_jc, two_jf, two_ji)
) {
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
int tk;
int tkmin = locMax3(abs(two_ja-two_ji), abs(two_jh-two_jd), abs(two_jb-two_jf));
int tkmax = locMin3(two_ja + two_ji, two_jh + two_jd, two_jb + two_jf);
double sum_pos = 0.0;
double sum_neg = 0.0;
double sumsq_err = 0.0;
double phase;
for(tk=tkmin; tk<=tkmax; tk += 2) {
gsl_sf_result s1, s2, s3;
double term;
double term_err;
int status = 0;
status += gsl_sf_coupling_6j_e(two_ja, two_ji, two_jd, two_jh, tk, two_jg, &s1);
status += gsl_sf_coupling_6j_e(two_jb, two_jf, two_jh, two_jd, tk, two_je, &s2);
status += gsl_sf_coupling_6j_e(two_ja, two_ji, two_jb, two_jf, tk, two_jc, &s3);
if(status != GSL_SUCCESS) {
OVERFLOW_ERROR(result);
}
term = s1.val * s2.val * s3.val;
term_err = s1.err * fabs(s2.val*s3.val);
term_err += s2.err * fabs(s1.val*s3.val);
term_err += s3.err * fabs(s1.val*s2.val);
if(term >= 0.0) {
sum_pos += (tk + 1) * term;
}
else {
sum_neg -= (tk + 1) * term;
}
sumsq_err += ((tk+1) * term_err) * ((tk+1) * term_err);
}
phase = GSL_IS_ODD(tkmin) ? -1.0 : 1.0;
result->val = phase * (sum_pos - sum_neg);
result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);
result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0));
result->err += 2.0 * GSL_DBL_EPSILON * (tkmax-tkmin + 2.0) * fabs(result->val);
return GSL_SUCCESS;
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_coupling_3j(int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc)
{
EVAL_RESULT(gsl_sf_coupling_3j_e(two_ja, two_jb, two_jc,
two_ma, two_mb, two_mc,
&result));
}
double gsl_sf_coupling_6j(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf)
{
EVAL_RESULT(gsl_sf_coupling_6j_e(two_ja, two_jb, two_jc,
two_jd, two_je, two_jf,
&result));
}
double gsl_sf_coupling_9j(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji)
{
EVAL_RESULT(gsl_sf_coupling_9j_e(two_ja, two_jb, two_jc,
two_jd, two_je, two_jf,
two_jg, two_jh, two_ji,
&result));
}
| {
"alphanum_fraction": 0.5827046772,
"avg_line_length": 30.4915254237,
"ext": "c",
"hexsha": "d5799933f6a0a0d650d8779d408afe140c328903",
"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/coupling.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/coupling.c",
"max_line_length": 88,
"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/coupling.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": 4418,
"size": 12593
} |
/* Copyright Koby Hayashi 2018 */
#ifndef DIMTREE_DDTTENSOR_H_
#define DIMTREE_DDTTENSOR_H_
#include <cblas.h>
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
/**
This is a header file that contains defiition for:
1) KTENSOR
2) TENSOR
3) Hadamard Product - Hadamard()
4) Multi_KR() - function do to multiple KR products
5) printM() - function to print a matrix in column major odering
6) compareM() - function for comparing two matrices using a certain
tolerance 7) TransposeM() 8) MHada()
Move function to its own c file with MTTKRP
make inputs to KR just a ktensor struct
NOTES and QUESTIONS:
-should we make functions that act like constructors that take points to
various structs and fill them with given argument values;
EXAMPLE: ktensor* ktensor_const(double ** factors, long int * dims, long
int nmodes, long int rank){//FILL VALUES}
*/
/**
KTENSOR definition
Should Include:
1) Array of Factor Matrices (double **)
2) Array of Dimensions (long int *)
3) Number of Modes (long int)
4) Rank (long int)
5) Weights or Lambda values
*/
typedef struct {
double **factors;
long int *dims;
long int nmodes;
long int rank;
long int dims_product;
double *lambdas;
} ktensor;
/**
TENSOR definition
Should Include:
1) Data (double *)
2) Dims (long int *)
3) Number of Modes (long int)
- the Data is stored column wise in a the first mode matricization of
the tensor.
*/
typedef struct {
double *data;
long int *dims;
long int nmodes;
long int dims_product;
} tensor;
/**
For processing command line inputs
*/
typedef struct {
long int rank;
long int nmodes;
double noise;
long int num_threads;
long int max_iters;
double tolerance;
long int *dims;
} tensor_inputs;
/**
Left or Right direction type
Used as an input for the MTTKRP 2Step function
*/
typedef enum { left, right } direction;
/**
Function Prototypes
*/
/**
Utility fuctions
printM_ColMajor() - prints a marix in column major order
printM_RowMajor() - prints a Matrix in row-major order
print_Ktensor_RowMajor() - prints a Ktensor object
TransposeM() - transposes the matrix A into A_T
CompareM() - compares two matrices of the same size
element by element compute_Iteration_Space() - divides up an iteration space
amongst threads Gen_Tensor() - generates a rank R tensor
clean_Up_Gen_Tensor() - cleans up a tensor and ktensor
print_dgemm_inputs() - prints inputs to a cblas_dgemm call
print_dgemv_inputs() - prints inputs to a cblas_dgemv call
Full_nMode_Matricization_RowMajor() - creates a matricization of a
tensor from a tensor model
*/
void printM_ColMajor(double *M, long int num_cols, long int num_rows);
void printM_RowMajor(double *M, long int num_cols, long int num_rows);
void print_Ktensor_RowMajor(ktensor *Y);
void TransposeM(double *A, double *A_T, long int rowsA, long int colsA);
long int CompareM(double *A, double *B, long int nRows, long int nCols,
double eps);
void compute_Iteration_Space(long int thread_id, long int num_threads,
long int iter_space, long int *start,
long int *end);
void Gen_Tensor(ktensor *Y, tensor *T, long int R, long int N, long int *D,
double noise);
void clean_Up_Gen_Tensor(ktensor *Y, tensor *T);
void print_tensor(tensor *T, long int show_data);
void print_dgemm_inputs(CBLAS_ORDER dgemm_layout, CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB, long int m, long int n,
long int k, double alpha, long int strideA,
long int strideB, double beta, long int strideC);
void print_dgemv_inputs(CBLAS_ORDER dgemv_layout, CBLAS_TRANSPOSE transA,
long int m, long int n, double alpha, long int T_offset,
long int tensor_stride, long int A_offset,
long int A_stride, double beta,
long int output_col_stride, long int output_stride);
void Full_nMode_Matricization_RowMajor(tensor *T, ktensor *Y, long int n);
/**
Sequential KRP functions
Multi_KR_RowMajor() - Does the rev-KRP of all factor
matrices of Y, skipping the nth mode, has reuse
KR_RowMajor() - Does the rev-KRP of 2 factor matrices
update_Partial_Hadamards() - Updates partial hadamards for
Multi_KR_RowMajor()
*/
void Multi_KR_RowMajor(ktensor *Y, double *C, long int n);
void KR_RowMajor(ktensor *Y, double *C, long int n);
void update_Partial_Hadamards(ktensor *Y, long int *indexers,
double *partial_Hadamards,
double **reordered_Factors);
/**
Parallel KRP functions
parallel_Multi_KR_RowMajor() - computes the pieces of a KRP
of all given factor matrices in Y
parallel_KR_RowMajor() - handles the Y->nmodes == 2
case fo above parallel_update_Partial_Hadamards() - updates the
Partial_Hadamards for the above
wrapper_Parallel_Multi_revKRP() - wrapper function for doing a
parallel revKRP, uses the 3 above functions
*/
void parallel_Multi_KR_RowMajor(ktensor *Y, double *C, long int start,
long int end);
void parallel_KR_RowMajor(ktensor *Y, double *C, long int start, long int end);
void parallel_update_Partial_Hadamards(ktensor *Y, long int *indexers,
double *partial_Hadamards);
void wrapper_Parallel_Multi_revKRP(ktensor *Y, long int num_threads,
double *KRP);
/**
CP_ALS functions
MTTKRP_rowMajor() - performs a slicing(no
permuting needed) MTTKRP in row major Upper_Hadamard_RowMajor()
- Hadamard product of upper part of symmetric matrices in row major order
normalize_Factor_Matrix_RowMajor() - normalizes the nth factor
matrix for a row major ktensor normalize_Ktensor_RowMajor() -
normalizes all the factor matrices for a row major ktensor
do_SYRKs_RowMajor() - does the SYRKS of all factor
matrices in a given Y and stores them approximation_Error()
- comptues the error of a given CP model against the original tensor
MHada_RowMajor() - does the hadamard product of
upper triangular matrices
*/
void MTTKRP_RowMajor(tensor *T, double *K, double *C, long int rank,
long int n);
void Upper_Hadamard_RowMajor(long int nRows, long int nCols, double *A,
double *B, double *C);
void normalize_Factor_Matrix_RowMajor(ktensor *Y, long int n);
void normalize_Ktensor_RowMajor(ktensor *Y);
void do_SYRKs_RowMajor(ktensor *Y, double **SYRKs);
double approximation_Error(double *X, double *KR, ktensor *Y, long int n);
double CP_ALS_efficient_error_computation(ktensor *Y, long int n,
double *MTTKRP, double *V, double *S,
double tensor_norm);
double CP_ALS_naive_error_computation(tensor *T, ktensor *Y, double *X,
double *KRP, long int n);
void MHada_RowMajor(ktensor *Y, double **SYRKs, double *V, long int n);
void reorder_Factors(ktensor *Y, double **reordered_Factors,
long int *reordered_Dims, long int n);
void reorder_Ktensor(ktensor *Y, ktensor *nY, long int n);
void compute_KRP_Indices(long int j, ktensor *Y, long int *indeces);
void update_Partial_Hadamards_2(ktensor *Y, long int *indexers,
double *partial_Hadamards);
/**
Input and object validity functions
dims_check() - checks an array of dimensions with the lenght
to verify the validity process_inputs() - processes general inputs for
generating a rank R tensor
*/
void dims_check(long int *dims, long int length);
void process_inputs(long int argc, char *argv[], tensor_inputs *inputs);
void destroy_inputs(tensor_inputs *inputs); // Parallel MTTKRP function
// Functions for manipulating and manageing ktensor and tensor objects
void LR_Ktensor_Reordering_newY(ktensor *Y, ktensor *nY, long int n,
direction D);
void LR_Ktensor_Reordering_existingY(ktensor *Y, ktensor *nY, long int n,
direction D);
void destruct_Ktensor(ktensor *Y, long int clear_factors);
void destruct_Tensor(tensor *T);
void LR_tensor_Reduction(tensor *T, tensor *nT, long int n, direction D);
void tensor_data_swap(tensor *t1, tensor *t2);
void ktensor_copy_constructor(ktensor *Y, ktensor *nY);
direction opposite_direction(direction D);
void remove_mode_Ktensor(ktensor *Y, long int n);
// mkl unavailable functions
void vdMul(long int, double *, double *, double *);
// define dgemm
extern "C" void dgemm_(char *transa, char *transb, int *m, int *n, int *k, double *alpha,
double *a, int *lda, double *b, int *ldb, double *beta, double *c,
int *ldc);
#endif // DIMTREE_DDTTENSOR_H_
| {
"alphanum_fraction": 0.6587934887,
"avg_line_length": 38.6790123457,
"ext": "h",
"hexsha": "eba67f878c0029be5bc4d95080cfecdf83984f1f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-08-02T21:30:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-29T21:55:33.000Z",
"max_forks_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61",
"max_forks_repo_licenses": [
"BSD-3-Clause",
"Unlicense"
],
"max_forks_repo_name": "rvangara/DnMFk",
"max_forks_repo_path": "planc-master/dimtree/ddttensor.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause",
"Unlicense"
],
"max_issues_repo_name": "rvangara/DnMFk",
"max_issues_repo_path": "planc-master/dimtree/ddttensor.h",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a6bca290bf7d57be07f7a80d049d6b7714fbdc61",
"max_stars_repo_licenses": [
"BSD-3-Clause",
"Unlicense"
],
"max_stars_repo_name": "lanl/DnMFkCPP",
"max_stars_repo_path": "planc-master/dimtree/ddttensor.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-29T21:56:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-29T21:56:02.000Z",
"num_tokens": 2344,
"size": 9399
} |
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <getopt.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
#include "../fewbody.h"
int calc_units(fb_hier_t hier, fb_units_t *units)
{
/* mass unit is total system mass */
units->m = hier.hier[hier.hi[1]+0].m + hier.hier[hier.hi[1]+1].m + \
hier.hier[hier.hi[1]+2].m + hier.hier[hier.hi[1]+3].m + \
hier.hier[hier.hi[1]+4].m;
/* length unit is one AU */
units->l = FB_CONST_AU;
/* everything else is derived */
units->E = FB_CONST_G * fb_sqr(units->m) / units->l;
units->v = sqrt(units->E/units->m);
units->t = units->l / units->v;
return(0);
}
int main(int argc, char *argv[])
{
int j;
double t;
fb_hier_t hier;
fb_input_t input;
fb_ret_t retval;
fb_units_t units;
char string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH];
/* set input parameters */
input.ks = 0; /* turn K-S regularization off */
input.tstop = 1.0e4; /* stopping time in units of units.t */
input.Dflag = 0; /* don't output dynamical info to stdout */
input.dt = 0.0; /* irrelevant when Dflag=0 */
input.tcpustop = 120.0; /* stopping CPU time in seconds */
input.absacc = 1.0e-9; /* integrator absolute accuracy */
input.relacc = 1.0e-9; /* integrator relative accuracy */
input.ncount = 500; /* number of integration steps between calls to fb_classify() */
input.tidaltol = 1.0e-6; /* tidal perturbation required to force numerical */
/* integration of a binary node */
input.fexp = 1.0; /* radius expansion factor of merger products */
fb_debug = 0;
/* initialize a few things */
t = 0.0;
hier.nstarinit = 5;
hier.nstar = 5;
fb_malloc_hier(&hier);
fb_init_hier(&hier);
/* set stellar properties */
for (j=0; j<hier.nstar; j++) {
hier.hier[hier.hi[1]+j].ncoll = 1;
hier.hier[hier.hi[1]+j].id[0] = j;
snprintf(hier.hier[hier.hi[1]+j].idstring, FB_MAX_STRING_LENGTH, "%d", j);
hier.hier[hier.hi[1]+j].n = 1;
hier.hier[hier.hi[1]+j].obj[0] = NULL;
hier.hier[hier.hi[1]+j].obj[1] = NULL;
hier.hier[hier.hi[1]+j].Eint = 0.0;
hier.hier[hier.hi[1]+j].Lint[0] = 0.0;
hier.hier[hier.hi[1]+j].Lint[1] = 0.0;
hier.hier[hier.hi[1]+j].Lint[2] = 0.0;
hier.hier[hier.hi[1]+j].R = 1.0e-3 * FB_CONST_RSUN;
hier.hier[hier.hi[1]+j].m = FB_CONST_MSUN;
hier.hier[hier.hi[1]+j].x[2] = 0.0; /* everything in x-y plane */
hier.hier[hier.hi[1]+j].v[2] = 0.0;
}
/* set some positions and velocities */
hier.hier[hier.hi[1]+0].x[0] = 10.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+0].x[1] = 0.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+0].v[0] = 10.0e5;
hier.hier[hier.hi[1]+0].v[1] = 0.0;
hier.hier[hier.hi[1]+1].x[0] = 10.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+1].x[1] = 10.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+0].v[0] = -10.0e5;
hier.hier[hier.hi[1]+0].v[1] = 0.0;
hier.hier[hier.hi[1]+2].x[0] = -30.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+2].x[1] = -5.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+0].v[0] = 0.0;
hier.hier[hier.hi[1]+0].v[1] = 5.0e5;
hier.hier[hier.hi[1]+3].x[0] = 0.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+3].x[1] = 27.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+0].v[0] = -5.0e5;
hier.hier[hier.hi[1]+0].v[1] = -4.0e5;
hier.hier[hier.hi[1]+4].x[0] = 10.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+4].x[1] = -32.0 * FB_CONST_AU;
hier.hier[hier.hi[1]+0].v[0] = 5.0e5;
hier.hier[hier.hi[1]+0].v[1] = -1.0e5;
/* set units with our own routine, then normalize */
calc_units(hier, &units);
fb_normalize(&hier, units);
/* call Fewbody to evolve system */
retval = fewbody(input, &hier, &t);
/* all the rest is parsing the output */
if (retval.retval == 1) {
fprintf(stderr, "encounter complete.\n");
} else {
fprintf(stderr, "encounter NOT complete.\n");
}
fprintf(stderr, "final configuration: %s (%s)\n",
fb_sprint_hier(hier, string1),
fb_sprint_hier_hr(hier, string2));
fprintf(stderr, "t_final=%.6g (%.6g yr) t_cpu=%.6g s\n", \
t, t*units.t/FB_CONST_YR, retval.tcpu);
fprintf(stderr, "DeltaL/L0=%.6g DeltaL=%.6g\n", retval.DeltaLfrac, retval.DeltaL);
fprintf(stderr, "DeltaE/E0=%.6g DeltaE=%.6g\n", retval.DeltaEfrac, retval.DeltaE);
fprintf(stderr, "Rmin=%.6g (%.6g RSUN) Rmin_i=%d Rmin_j=%d\n", \
retval.Rmin, retval.Rmin*units.l/FB_CONST_RSUN, retval.Rmin_i, retval.Rmin_j);
fprintf(stderr, "Nosc=%d (%s)\n", retval.Nosc,
(retval.Nosc>=1?"resonance":"non-resonance"));
fprintf(stderr, "orbital parameters of outermost binaries:\n");
for (j=0; j<hier.nobj; j++) {
if (hier.obj[j]->n >= 2) {
fprintf(stderr, "j=%d a=%.6g AU e=%.6g\n", j,
hier.obj[j]->a * units.l / FB_CONST_AU, hier.obj[j]->e);
}
}
fb_free_hier(hier);
return(0);
}
| {
"alphanum_fraction": 0.6113861386,
"avg_line_length": 34.3829787234,
"ext": "c",
"hexsha": "03a7df093c76187cd9eeb54cdec70cca409d9cc1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_forks_repo_licenses": [
"PSF-2.0"
],
"max_forks_repo_name": "gnodvi/cosmos",
"max_forks_repo_path": "ext/fewbod/fewbody-0.26/O/FEWBODY/doc/simple.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_licenses": [
"PSF-2.0"
],
"max_issues_repo_name": "gnodvi/cosmos",
"max_issues_repo_path": "ext/fewbod/fewbody-0.26/O/FEWBODY/doc/simple.c",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_stars_repo_licenses": [
"PSF-2.0"
],
"max_stars_repo_name": "gnodvi/cosmos",
"max_stars_repo_path": "ext/fewbod/fewbody-0.26/O/FEWBODY/doc/simple.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1910,
"size": 4848
} |
/*
Simbicon 1.5 Controller Editor Framework,
Copyright 2009 Stelian Coros, Philippe Beaudoin and Michiel van de Panne.
All rights reserved. Web: www.cs.ubc.ca/~van/simbicon_cef
This file is part of the Simbicon 1.5 Controller Editor Framework.
Simbicon 1.5 Controller Editor Framework 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.
Simbicon 1.5 Controller Editor Framework 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 Simbicon 1.5 Controller Editor Framework.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <MathLib/MathLib.h>
#include <MathLib/ThreeTuple.h>
#include <gsl/matrix/gsl_matrix.h>
#include <gsl/vector/gsl_vector.h>
#include <MathLib/Matrix.h>
#define VECTOR_AT(v, i) (*((v->data + (i * v->tda ))))
/*====================================================================================================================================================================*
| This class will be used to represent matrices of arbitrary sizes (m rows by n columns) that have elements of type double. The underlying data strucutre used by |
| this class is gsl's (Gnu Scientific Library) matrix class. This class also makes use of the ATLAS implementation of BLAS for some operations such as matrix-matrix |
| multiplication. This class is meant to improve performance, not necessarily ease of use. |
*====================================================================================================================================================================*/
class Vector : public Matrix{
public:
/**
constructor - creates an n row vector that is not initialized to any particular values
*/
Vector(int n);
/**
default constructor
*/
Vector();
/**
copy constructor - performs a deep copy of the matrix passed in as a parameter.
*/
Vector(const Vector& other);
/**
destructor.
*/
virtual ~Vector();
/**
copy operator - performs a deep copy of the Vector passed in as a parameter.
*/
Vector& operator=(const Vector &other);
/**
copy operator - performs a deep copy of the Vector passed in as a parameter.
*/
Vector& operator=(const Matrix &other);
/**
this method performs a shallow copy of the Vector that is passed in as a parameter.
*/
void shallowCopy(const Matrix& other);
/**
this method performs a deep copy of the vector that is passed in as a paramerer.
*/
void deepCopy(const Matrix& other);
/**
This method sets the current vector to be equal to one of the products: A * b or A'*b.
The value of transA indicates if A is transposed or not
*/
void setToProductOf(const Matrix& A, const Matrix& B, bool transA = false, bool transB = false);
/**
This method sets the current vector to be equal to one of the rows of A - shallow column only!
*/
void setToRow(const Matrix& A, int row, int start = 0, int howMany = -1);
/**
This method sets the current vector to be equal to one of the cols of A - shallow column only!
*/
void setToCol(const Matrix& A, int col, int start = 0, int howMany = -1);
/**
This method prints the contents of the matrix - testing purpose only.
*/
void printVector() const;
/**
This method returns a copy of the value of the matrix at (i,j)
*/
double get(int i) const;
/**
This method sets the value of the matrix at (i,j) to newVal.
*/
void set(int i, double newVal);
/**
Computes the 2-norm squared for the current vector.
*/
inline double normSquared(){
int r = getRowCount();
double result = 0;
for (int i=0;i<r;i++){
double n = MATRIX_AT(matrix, i, 0) ;
result += n*n;
}
return result;
}
};
void testVectorClass();
| {
"alphanum_fraction": 0.6420251961,
"avg_line_length": 30.2661870504,
"ext": "h",
"hexsha": "d14eebe9379293100eb71d25b8be87785a6693b1",
"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": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "scarensac/SPlisHSPlasH_for_cuda",
"max_forks_repo_path": "SPlisHSPlasH/MathLib/Vector.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca",
"max_issues_repo_issues_event_max_datetime": "2019-11-29T12:54:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-28T03:31:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "scarensac/SPlisHSPlasH_for_cuda",
"max_issues_repo_path": "SPlisHSPlasH/MathLib/Vector.h",
"max_line_length": 168,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "scarensac/SPlisHSPlasH_for_cuda",
"max_stars_repo_path": "SPlisHSPlasH/MathLib/Vector.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 963,
"size": 4207
} |
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <time.h>
#include <string.h>
/*
* A benchmark to test performance of calculating determinants of
* 6x6 matrices with the GNU Scientific Library (GSL) package.
*/
int main(int argc, char * argv[])
{
if (argc != 3 || strcmp(argv[1], "-h") == 0)
{
printf("Usage: ./gslDeterm N_MATRIX(<=1000) ITERATIONS(~1000)\n");
return 1;
}
srand(time(NULL));
int MAT_DIM = 6;
int N_MATRIX = atoi(argv[1]);
int ITERATIONS = atoi(argv[2]);
int i,j,k, count;
double start, end, t_time = 0.0;
printf("N_MATRIX: %d, ITERATIONS: %d\n", N_MATRIX, ITERATIONS);
gsl_permutation *p;
gsl_matrix *m_list[N_MATRIX];
// Do this ITERATIONS times, timing only the loop with the determinant
// finding
for (count=0; count<ITERATIONS; count++)
{
// initialise each element of m_list as a gsl_matrix
for (i=0; i<N_MATRIX; i++)
m_list[i] = gsl_matrix_alloc(MAT_DIM,MAT_DIM);
// initialise each element of each gsl_matrix as some random double
// less than 100
for (i=0; i<N_MATRIX; i++)
for (j=0; j<MAT_DIM; j++)
for (k=0; k<MAT_DIM; k++)
gsl_matrix_set (m_list[i], j, k, (double) (rand()%100));
volatile double det;
int signum;
p = gsl_permutation_alloc(m_list[0]->size1);
//start time: find the determinant of each matrix in m_list
start = (double)clock() /(double) CLOCKS_PER_SEC;
for (i=0; i<N_MATRIX; i++)
{
gsl_linalg_LU_decomp(m_list[0], p, &signum);
det = gsl_linalg_LU_det(m_list[0], signum);
}
end = (double)clock() / (double) CLOCKS_PER_SEC;
t_time += end - start;
}
printf("GSL: %d matrices, %d iterations, cpu time: %fs\n",
N_MATRIX, ITERATIONS, t_time);
gsl_permutation_free(p);
for (i=0; i<N_MATRIX; i++)
gsl_matrix_free(m_list[i]);
return 0;
}
| {
"alphanum_fraction": 0.6253270539,
"avg_line_length": 25.8243243243,
"ext": "c",
"hexsha": "babf7aac016c6cb971b618926a9fe5ab6af96896",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-02-25T06:53:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-04-21T08:25:26.000Z",
"max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tcrundall/chronostar",
"max_forks_repo_path": "benchmarks/matrix_library_tests/gslDeterm.c",
"max_issues_count": 13,
"max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_issues_repo_issues_event_max_datetime": "2021-11-08T23:44:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-08-14T07:30:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tcrundall/chronostar",
"max_issues_repo_path": "benchmarks/matrix_library_tests/gslDeterm.c",
"max_line_length": 72,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tcrundall/chronostar",
"max_stars_repo_path": "benchmarks/matrix_library_tests/gslDeterm.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-14T01:13:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-28T11:05:42.000Z",
"num_tokens": 587,
"size": 1911
} |
#ifndef boundary_h
#define boundary_h
#include <petsc.h>
typedef PetscErrorCode BCFunc(PetscInt, PetscReal, const PetscReal *, PetscInt,
PetscScalar *, void *);
BCFunc BCMMS, BCZero, BCClamp;
// -----------------------------------------------------------------------------
// Boundary Functions
// -----------------------------------------------------------------------------
// Note: If additional boundary conditions are added, an update is needed in
// elasticity.h for the boundaryOptions variable.
// BCMMS - boundary function
// Values on all points of the mesh is set based on given solution below
// for u[0], u[1], u[2]
PetscErrorCode BCMMS(PetscInt dim, PetscReal load_increment,
const PetscReal coords[], PetscInt num_comp_u,
PetscScalar *u, void *ctx);
// BCClamp - fix boundary values with affine transformation at fraction of load
// increment
PetscErrorCode BCClamp(PetscInt dim, PetscReal load_increment,
const PetscReal coords[], PetscInt num_comp_u,
PetscScalar *u, void *ctx);
#endif //boundary_h
| {
"alphanum_fraction": 0.5765217391,
"avg_line_length": 38.3333333333,
"ext": "h",
"hexsha": "7b01dd91374f319dd34d12a931e19bd5f3f19681",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/solids/include/boundary.h",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/solids/include/boundary.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/solids/include/boundary.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": 225,
"size": 1150
} |
/* interpolation/interp.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_interp.h>
#define DISCARD_STATUS(s) if ((s) != GSL_SUCCESS) { GSL_ERROR_VAL("interpolation error", (s), GSL_NAN); }
gsl_interp *
gsl_interp_alloc (const gsl_interp_type * T, size_t size)
{
gsl_interp * interp;
if (size < T->min_size)
{
GSL_ERROR_NULL ("insufficient number of points for interpolation type",
GSL_EINVAL);
}
interp = (gsl_interp *) malloc (sizeof(gsl_interp));
if (interp == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for interp struct",
GSL_ENOMEM);
}
interp->type = T;
interp->size = size;
if (interp->type->alloc == NULL)
{
interp->state = NULL;
return interp;
}
interp->state = interp->type->alloc(size);
if (interp->state == NULL)
{
free (interp);
GSL_ERROR_NULL ("failed to allocate space for interp state", GSL_ENOMEM);
};
return interp;
}
int
gsl_interp_init (gsl_interp * interp, const double x_array[], const double y_array[], size_t size)
{
if (size != interp->size)
{
GSL_ERROR ("data must match size of interpolation object", GSL_EINVAL);
}
interp->xmin = x_array[0];
interp->xmax = x_array[size - 1];
{
int status = interp->type->init(interp->state, x_array, y_array, size);
return status;
}
}
const char *
gsl_interp_name(const gsl_interp * interp)
{
return interp->type->name;
}
unsigned int
gsl_interp_min_size(const gsl_interp * interp)
{
return interp->type->min_size;
}
void
gsl_interp_free (gsl_interp * interp)
{
if (interp->type->free)
interp->type->free (interp->state);
free (interp);
}
int
gsl_interp_eval_e (const gsl_interp * interp,
const double xa[], const double ya[], double x,
gsl_interp_accel * a, double *y)
{
if (x < interp->xmin)
{
*y = ya[0];
return GSL_EDOM;
}
else if (x > interp->xmax)
{
*y = ya[interp->size - 1];
return GSL_EDOM;
}
return interp->type->eval (interp->state, xa, ya, interp->size, x, a, y);
}
double
gsl_interp_eval (const gsl_interp * interp,
const double xa[], const double ya[], double x,
gsl_interp_accel * a)
{
double y;
int status = interp->type->eval (interp->state, xa, ya, interp->size, x, a, &y);
DISCARD_STATUS(status);
return y;
}
int
gsl_interp_eval_deriv_e (const gsl_interp * interp,
const double xa[], const double ya[], double x,
gsl_interp_accel * a,
double *dydx)
{
if (x < interp->xmin)
{
*dydx = 0.0;
return GSL_EDOM;
}
else if (x > interp->xmax)
{
*dydx = 0.0;
return GSL_EDOM;
}
return interp->type->eval_deriv (interp->state, xa, ya, interp->size, x, a, dydx);
}
double
gsl_interp_eval_deriv (const gsl_interp * interp,
const double xa[], const double ya[], double x,
gsl_interp_accel * a)
{
double dydx;
int status = interp->type->eval_deriv (interp->state, xa, ya, interp->size, x, a, &dydx);
DISCARD_STATUS(status);
return dydx;
}
int
gsl_interp_eval_deriv2_e (const gsl_interp * interp,
const double xa[], const double ya[], double x,
gsl_interp_accel * a,
double * d2)
{
if (x < interp->xmin)
{
*d2 = 0.0;
return GSL_EDOM;
}
else if (x > interp->xmax)
{
*d2 = 0.0;
return GSL_EDOM;
}
return interp->type->eval_deriv2 (interp->state, xa, ya, interp->size, x, a, d2);
}
double
gsl_interp_eval_deriv2 (const gsl_interp * interp,
const double xa[], const double ya[], double x,
gsl_interp_accel * a)
{
double d2;
int status = interp->type->eval_deriv2 (interp->state, xa, ya, interp->size, x, a, &d2);
DISCARD_STATUS(status);
return d2;
}
int
gsl_interp_eval_integ_e (const gsl_interp * interp,
const double xa[], const double ya[],
double a, double b,
gsl_interp_accel * acc,
double * result)
{
if (a > b || a < interp->xmin || b > interp->xmax)
{
*result = 0.0;
return GSL_EDOM;
}
else if(a == b)
{
*result = 0.0;
return GSL_SUCCESS;
}
return interp->type->eval_integ (interp->state, xa, ya, interp->size, acc, a, b, result);
}
double
gsl_interp_eval_integ (const gsl_interp * interp,
const double xa[], const double ya[],
double a, double b,
gsl_interp_accel * acc)
{
double result;
int status = interp->type->eval_integ (interp->state, xa, ya, interp->size, acc, a, b, &result);
DISCARD_STATUS(status);
return result;
}
| {
"alphanum_fraction": 0.5932932072,
"avg_line_length": 23.7346938776,
"ext": "c",
"hexsha": "036173084e52d01e3cd37e88faf4d0490634735b",
"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/interpolation/interp.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/interpolation/interp.c",
"max_line_length": 106,
"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/interpolation/interp.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": 1531,
"size": 5815
} |
#ifndef _PYGSL_SOLVER_INTERN_H_
#define _PYGSL_SOLVER_INTERN_H_ 1
#define _PyGSL_SOLVER_API_MODULE 1
#include <pygsl/solver.h>
#undef _PyGSL_SOLVER_API_MODULE
#include <pygsl/general_helpers.h>
#include <pygsl/block_helpers.h>
#include <pygsl/function_helpers.h>
#include <setjmp.h>
#include <gsl/gsl_math.h>
/*
* Collect all element accessor methods which just need a pointer to the struct
* and return a value.
*/
struct _ElementAccessor{
int_m_t method;
const char * name;
};
static PyTypeObject PyGSL_solver_pytype;
#define PyGSL_solver_check(ob) ((ob)->ob_type == &PyGSL_solver_pytype)
#define _PyGSL_solver_n_init PyGSL_solver_n_init
static PyGSL_solver*
_PyGSL_solver_init(const struct _SolverStatic *mstatic);
static int
PyGSL_solver_set_called(PyGSL_solver *self);
#define PyGSL_SOLVER_SET_CALLED(ob) \
(((ob)->set_called == 1) ? GSL_SUCCESS: PyGSL_solver_set_called((ob)))
static int
PyGSL_solver_func_set(PyGSL_solver *self, PyObject *args, PyObject *f,
PyObject *df, PyObject *fdf);
#if 0
static PyObject *
_PyGSL_solver_np_init(PyObject *self, PyObject *args, const solver_alloc_struct * alloc);
static PyObject *
_PyGSL_solver_i_vvdd(PyObject * self, PyObject * args, int_f_vvdd_t func);
#endif
#endif /* _PYGSL_SOLVER_INTERN_H_ */
| {
"alphanum_fraction": 0.7718484145,
"avg_line_length": 23.9444444444,
"ext": "h",
"hexsha": "defb339559517946c313395a098ed63f3c30b839",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solver_intern.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solver_intern.h",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/solver_intern.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 365,
"size": 1293
} |
/*
* Gsl_matrix: test gsl_matrix
*
* Copyright (c) 2012 Jérémie Decock
*
* Required: GSL library (libgsl0-dev)
* Usage: gcc gsl_matrix.c -lgsl -lgslcblas -lm
* or: gcc gsl_matrix.c $(pkg-config --libs gsl)
*/
#include <gsl/gsl_matrix.h>
#define N 10
int main(int argc, char * argv[]) {
gsl_matrix * m1 = gsl_matrix_calloc(N, N);
gsl_matrix * m2 = gsl_matrix_calloc(N, N);
gsl_matrix_set_all(m1, 2.0);
gsl_matrix_set_all(m2, 6.0);
gsl_matrix_mul_elements(m1, m2);
gsl_matrix_fprintf(stdout, m1, "%.2f");
gsl_matrix_free(m1);
gsl_matrix_free(m2);
return 0;
}
| {
"alphanum_fraction": 0.6487804878,
"avg_line_length": 18.6363636364,
"ext": "c",
"hexsha": "de51be421571c225c779abd09afcf256fc20c470",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z",
"max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jeremiedecock/snippets",
"max_forks_repo_path": "c/gsl/gsl_matrix.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jeremiedecock/snippets",
"max_issues_repo_path": "c/gsl/gsl_matrix.c",
"max_line_length": 51,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jeremiedecock/snippets",
"max_stars_repo_path": "c/gsl/gsl_matrix.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z",
"num_tokens": 199,
"size": 615
} |
#pragma once
#include <type_traits>
#include <cuda/define_specifiers.hpp>
#include <cuda/runtime_api.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <gsl-lite/gsl-lite.hpp>
#include <cub/cub.cuh>
#include <thrustshift/constant.h>
#include <thrustshift/math.h>
#include <thrustshift/not-a-vector.h>
namespace thrustshift {
namespace device_function {
namespace implicit_unroll {
/*! \brief Write the selected values to the result if select_op is true.
*
* All threads check if their value should be selected. Afterwards, it is
* determined within the warp how many values were selected. Then, the first
* in the warp determines the range in the result, which is reserved for the
* warp via an atomic increment on `result_pos`. Subsequently, each thread with
* a selected value and `valid_write` writes the result into the reserved range.
* Only full warps are allowed to enter this function.
*
* \param x the value for each thread
* \param selected_values result range.
* \param selected_values_pos to an integer holding the ID of the first
* written result element by this function (usually initialized with
* zero). This counter is read and written atomically by the first lane of
* the warp. Usually this counter is shared among threads because it is
* incremented and read atomically.
* \param lane_id ID of the thread within the warp.
* \param valid_write some threads might be disabled with this flag (useful for
* handling range borders).
* \param select_op lambda to select the values.
*/
template <typename T, typename It, typename Bool, class F>
CUDA_FD void select_if_warp_aggregated(T x,
It selected_values,
int* selected_values_pos,
int lane_id,
Bool valid_write,
F select_op) {
const bool p = select_op(x) && valid_write;
const unsigned umask = __ballot_sync(0xffffffff, p);
const int num_selected_values = __popc(umask);
constexpr int source_lane = 0;
int pos;
if (lane_id == source_lane) {
pos = atomicAdd(selected_values_pos, num_selected_values);
}
const unsigned umask_before_me =
(~unsigned(0)) >> (sizeof(unsigned) * 8 - lane_id);
const int num_selected_values_before_me = __popc(umask & umask_before_me);
pos = __shfl_sync(0xffffffff, pos, source_lane);
pos += num_selected_values_before_me;
if (p) {
selected_values[pos] = x;
}
}
/*! \brief select_if as a block level primitive.
*
* \param values iterator to range of length N
* \param N length of input values
* \param selected_values iterator to range of length `*selected_values_pos + N`
* \param selected_values_pos pointer to an integer holding the ID of the first
* written selected_values element by this function (usually initialized
* with zero). This counter must be shared among all threads, which
* enter this function because it is incremented and read atomically.
* \param tid thread ID
* \param num_threads number of threads which enter this function.
* \param select_op lambda to select the values.
*/
template <typename It, typename ItResult, typename I0, typename I1, class F>
CUDA_FD void select_if(It values,
I0 N,
ItResult selected_values,
int* selected_values_pos,
int tid,
I1 num_threads,
F select_op) {
const int num_tiles = thrustshift::ceil_divide(N, num_threads);
for (int tile_id = 0; tile_id < num_tiles - 1; ++tile_id) {
const int j = tile_id * num_threads + tid;
auto x = values[j];
select_if_warp_aggregated(x,
selected_values,
selected_values_pos,
tid % warp_size,
std::bool_constant<true>(),
select_op);
}
auto rest = N % num_threads;
if (rest > 0) {
const int j = (num_tiles - 1) * num_threads + tid;
const bool valid_rw = tid < rest;
using T = typename std::remove_const<
typename std::iterator_traits<It>::value_type>::type;
const auto x = [&]() -> T {
if (valid_rw) {
return values[j];
}
return T{};
}();
select_if_warp_aggregated(x,
selected_values,
selected_values_pos,
tid % warp_size,
valid_rw,
select_op);
}
}
} // namespace implicit_unroll
} // namespace device_function
namespace async {
template <class ValuesRange,
class SelectedRange,
class NumSelectedPtr,
class SelectOp,
class MemoryResource>
void select_if(cuda::stream_t& stream,
ValuesRange&& values,
SelectedRange&& selected,
NumSelectedPtr num_selected_ptr,
SelectOp select_op,
MemoryResource& delayed_memory_resource) {
const std::size_t N = values.size();
gsl_Expects(selected.size() == N);
size_t tmp_bytes_size = 0;
void* tmp_ptr = nullptr;
using T = typename std::remove_reference<ValuesRange>::type::value_type;
auto exec = [&] {
cuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,
tmp_bytes_size,
values.data(),
selected.data(),
num_selected_ptr,
N,
select_op,
stream.handle()));
};
exec();
auto tmp =
make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);
tmp_ptr = tmp.to_span().data();
exec();
}
template <class ValuesIt,
class SelectedIt,
class NumSelectedPtr,
class SelectOp,
class MemoryResource>
void select_if(cuda::stream_t& stream,
ValuesIt values,
SelectedIt selected,
NumSelectedPtr num_selected_ptr,
size_t N,
SelectOp select_op,
MemoryResource& delayed_memory_resource) {
size_t tmp_bytes_size = 0;
void* tmp_ptr = nullptr;
auto exec = [&] {
cuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,
tmp_bytes_size,
values,
selected,
num_selected_ptr,
N,
select_op,
stream.handle()));
};
exec();
auto tmp =
make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);
tmp_ptr = tmp.to_span().data();
exec();
}
/*! \brief Select values based on predicate with their index.
*
* \param values Range of length N with value_type `T`
* \param selected Range of length N with a value type which is assignable
* by a thrust::tuple<T, int>.
* \param select_op select predicate with signature
* ```
* select_op = [] __device__ (const thrust::tuple<T, int>& tup) { ... };
* ```
*/
template <class ValuesRange,
class SelectedRange,
class NumSelectedPtr,
class SelectOp,
class MemoryResource>
void select_if_with_index(cuda::stream_t& stream,
ValuesRange&& values,
SelectedRange&& selected,
NumSelectedPtr num_selected_ptr,
SelectOp select_op,
MemoryResource& delayed_memory_resource) {
const std::size_t N = values.size();
gsl_Expects(selected.size() == N);
size_t tmp_bytes_size = 0;
void* tmp_ptr = nullptr;
using T = typename std::remove_reference<ValuesRange>::type::value_type;
auto cit = thrust::make_counting_iterator(0);
auto it = thrust::make_zip_iterator(thrust::make_tuple(values.data(), cit));
auto exec = [&] {
cuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,
tmp_bytes_size,
it,
selected.data(),
num_selected_ptr,
N,
select_op,
stream.handle()));
};
exec();
auto tmp =
make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);
tmp_ptr = tmp.to_span().data();
exec();
}
template <class ValuesRange,
class SelectedRange,
class SelectedIndexRange,
class NumSelectedPtr,
class SelectOp,
class MemoryResource>
void select_if_with_index(cuda::stream_t& stream,
ValuesRange&& values,
SelectedRange&& selected,
SelectedIndexRange&& selected_indices,
NumSelectedPtr num_selected_ptr,
SelectOp select_op,
MemoryResource& delayed_memory_resource) {
const std::size_t N = values.size();
gsl_Expects(selected.size() == N);
size_t tmp_bytes_size = 0;
void* tmp_ptr = nullptr;
using T = typename std::remove_reference<ValuesRange>::type::value_type;
auto cit = thrust::make_counting_iterator(0);
auto it = thrust::make_zip_iterator(thrust::make_tuple(values.data(), cit));
auto result_it = thrust::make_zip_iterator(
thrust::make_tuple(selected.data(), selected_indices.data()));
auto exec = [&] {
cuda::throw_if_error(cub::DeviceSelect::If(tmp_ptr,
tmp_bytes_size,
it,
result_it,
num_selected_ptr,
N,
select_op,
stream.handle()));
};
exec();
auto tmp =
make_not_a_vector<uint8_t>(tmp_bytes_size, delayed_memory_resource);
tmp_ptr = tmp.to_span().data();
exec();
}
} // namespace async
} // namespace thrustshift
| {
"alphanum_fraction": 0.5660554772,
"avg_line_length": 34.868852459,
"ext": "h",
"hexsha": "979fb31c72865e21886693c5aeb8b7d937eaf467",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pauleonix/thrustshift",
"max_forks_repo_path": "include/thrustshift/select-if.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"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": "pauleonix/thrustshift",
"max_issues_repo_path": "include/thrustshift/select-if.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pauleonix/thrustshift",
"max_stars_repo_path": "include/thrustshift/select-if.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2109,
"size": 10635
} |
/*
* testgen.c
* Patrick Alken
*
* Compile: gcc -g -O2 -Wall -o testgen testgen.c -lm -lgsl -llapack -lf77blas -lcblas -latlas -lg2c
*
* Usage: testgen [options]
*
* -i : incremental matrices
* -z : compute Schur vectors and test them
* -n size : size of matrices
* -l lower-bound : lower bound for matrix elements
* -u upper-bound : upper bound for matrix elements
* -c num : number of matrices to solve
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
typedef struct
{
gsl_eigen_gen_workspace *gen_p;
gsl_matrix *A;
gsl_matrix *B;
gsl_vector_complex *alpha;
gsl_vector *beta;
gsl_vector_complex *evals;
gsl_matrix *Q;
gsl_matrix *Z;
int compute_schur;
size_t n_evals;
} gen_workspace;
gen_workspace *gen_alloc(size_t n, int compute_schur);
void gen_free(gen_workspace *w);
int gen_proc(gen_workspace *w);
typedef struct
{
gsl_matrix *A;
gsl_matrix *B;
gsl_matrix *Q;
gsl_matrix *Z;
int N;
char jobvsl;
char jobvsr;
char sort;
int selctg;
int lda;
int ldb;
int sdim;
double *alphar;
double *alphai;
gsl_vector *beta;
int ldvsr;
int lwork;
int info;
double *work;
gsl_vector_complex *evals;
gsl_vector_complex *alpha;
size_t n_evals;
} lapack_workspace;
lapack_workspace *lapack_alloc(const size_t n);
void lapack_free(lapack_workspace *w);
int lapack_proc(lapack_workspace *w);
void dgges_(char *jobvsl, char *jobvsr, char *sort, int *selctg, int *n,
double *a, int *lda, double *b, int *ldb, int *sdim,
double *alphar, double *alphai, double *beta, double *vsl,
int *ldvsl, double *vsr, int *ldvsr, double *work, int *lwork,
int *bwork, int *info);
/*
* Global variables
*/
unsigned long count = 0;
/*
* Prototypes
*/
void make_random_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper);
void make_random_integer_matrix(gsl_matrix *m, gsl_rng *r, int lower,
int upper);
void make_start_matrix(gsl_matrix *m, int lower);
int inc_matrix (gsl_matrix *m, int lower, int upper);
void output_matrix(gsl_matrix *m);
void print_matrix(gsl_matrix *m, const char *str);
int test_evals(gsl_vector_complex *obs, gsl_vector_complex *expected,
gsl_matrix *A, gsl_matrix *B,
const char *obsname, const char *expname);
int test_alpha(gsl_vector_complex *obs, gsl_vector_complex *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname);
int test_beta(gsl_vector *obs, gsl_vector *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname);
void test_schur(gsl_matrix *A, gsl_matrix *S, gsl_matrix *Q, gsl_matrix *Z);
void print_vector(gsl_vector_complex *eval, const char *str);
int cmp(double a, double b);
int compare(const void *a, const void *b);
void sort_complex_vector(gsl_vector_complex *v);
gen_workspace *
gen_alloc(size_t n, int compute_schur)
{
gen_workspace *w;
w = (gen_workspace *) calloc(1, sizeof(gen_workspace));
w->gen_p = gsl_eigen_gen_alloc(n);
w->A = gsl_matrix_alloc(n, n);
w->B = gsl_matrix_alloc(n, n);
w->alpha = gsl_vector_complex_alloc(n);
w->beta = gsl_vector_alloc(n);
w->evals = gsl_vector_complex_alloc(n);
w->compute_schur = compute_schur;
if (compute_schur)
{
w->Q = gsl_matrix_alloc(n, n);
w->Z = gsl_matrix_alloc(n, n);
gsl_eigen_gen_params(1, 1, 0, w->gen_p);
}
return (w);
} /* gen_alloc() */
void
gen_free(gen_workspace *w)
{
if (w->gen_p)
gsl_eigen_gen_free(w->gen_p);
if (w->A)
gsl_matrix_free(w->A);
if (w->B)
gsl_matrix_free(w->B);
if (w->alpha)
gsl_vector_complex_free(w->alpha);
if (w->beta)
gsl_vector_free(w->beta);
if (w->evals)
gsl_vector_complex_free(w->evals);
if (w->Q)
gsl_matrix_free(w->Q);
if (w->Z)
gsl_matrix_free(w->Z);
free(w);
}
int
gen_proc(gen_workspace *w)
{
int s;
s = gsl_eigen_gen_QZ(w->A, w->B, w->alpha, w->beta, w->Q, w->Z, w->gen_p);
w->n_evals = w->gen_p->n_evals;
return s;
} /* gen_proc() */
lapack_workspace *
lapack_alloc(const size_t n)
{
lapack_workspace *w;
double work[1];
w = (lapack_workspace *) calloc(1, sizeof(lapack_workspace));
w->A = gsl_matrix_alloc(n, n);
w->B = gsl_matrix_alloc(n, n);
w->Q = gsl_matrix_alloc(n, n);
w->Z = gsl_matrix_alloc(n, n);
w->alphar = malloc(n * sizeof(double));
w->alphai = malloc(n * sizeof(double));
w->beta = gsl_vector_alloc(n);
w->alpha = gsl_vector_complex_alloc(n);
w->evals = gsl_vector_complex_alloc(n);
w->N = (int) n;
w->n_evals = 0;
w->jobvsl = 'N';
w->jobvsr = 'N';
w->sort = 'N';
w->info = 0;
w->lwork = -1;
dgges_(&w->jobvsl,
&w->jobvsr,
&w->sort,
(int *) 0,
&w->N,
w->A->data,
(int *) &w->A->tda,
w->B->data,
(int *) &w->B->tda,
&w->sdim,
w->alphar,
w->alphai,
w->beta->data,
w->Q->data,
(int *) &w->Q->tda,
w->Z->data,
(int *) &w->Z->tda,
work,
&w->lwork,
(int *) 0,
&w->info);
w->lwork = (int) work[0];
w->work = malloc(w->lwork * sizeof(double));
return (w);
} /* lapack_alloc() */
void
lapack_free(lapack_workspace *w)
{
if (w->A)
gsl_matrix_free(w->A);
if (w->B)
gsl_matrix_free(w->B);
if (w->Q)
gsl_matrix_free(w->Q);
if (w->Z)
gsl_matrix_free(w->Z);
if (w->work)
free(w->work);
if (w->alphar)
free(w->alphar);
if (w->alphai)
free(w->alphai);
if (w->beta)
gsl_vector_free(w->beta);
if (w->alpha)
gsl_vector_complex_free(w->alpha);
if (w->evals)
gsl_vector_complex_free(w->evals);
free(w);
} /* lapack_free() */
int
lapack_proc(lapack_workspace *w)
{
dgges_(&w->jobvsl,
&w->jobvsr,
&w->sort,
(int *) 0,
&w->N,
w->A->data,
(int *) &w->A->tda,
w->B->data,
(int *) &w->B->tda,
&w->sdim,
w->alphar,
w->alphai,
w->beta->data,
w->Q->data,
(int *) &w->Q->tda,
w->Z->data,
(int *) &w->Z->tda,
w->work,
&w->lwork,
(int *) 0,
&w->info);
return (w->info);
} /* lapack_proc() */
/**********************************************
* General routines
**********************************************/
void
make_random_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper)
{
size_t i, j;
size_t N = m->size1;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
gsl_matrix_set(m,
i,
j,
gsl_rng_uniform(r) * (upper - lower) + lower);
}
}
} /* make_random_matrix() */
void
make_random_integer_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper)
{
size_t i, j;
size_t N = m->size1;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
double a = gsl_rng_uniform(r) * (upper - lower) + lower;
gsl_matrix_set(m, i, j, floor(a));
}
}
} /* make_random_integer_matrix() */
void
make_start_matrix(gsl_matrix *m, int lower)
{
size_t i, j;
size_t N = m->size1;
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
gsl_matrix_set(m, i, j, (double)lower);
} /* make_start_matrix() */
int
inc_matrix (gsl_matrix *m, int lower, int upper)
{
size_t i = 0;
size_t N = m->size1 * m->size2;
int carry = 1;
for (i = 0; carry > 0 && i < N; i++)
{
double v = m->data[i] + carry;
carry = (v > upper) ? 1 : 0;
m->data[i] = (v > upper) ? lower : v;
}
return carry;
} /* inc_matrix() */
void
output_matrix(gsl_matrix *m)
{
size_t i, j;
size_t N = m->size1;
size_t M = m->size2;
for (i = 0; i < N; ++i)
{
for (j = 0; j < M; ++j)
{
printf("%10.18e%s",
/*printf("%10.18e%s",*/
gsl_matrix_get(m, i, j),
(j < M - 1) ? "," : ";\n");
}
}
}
void
print_matrix(gsl_matrix *m, const char *str)
{
size_t i, j;
size_t N = m->size1;
size_t M = m->size2;
gsl_matrix_view v;
size_t rows, cols;
size_t r, c;
char buf[100];
/*print_octave(m, str);
return;*/
/*rows = GSL_MIN(15, N);*/
rows = N;
cols = GSL_MIN(15, N);
/*cols = N;*/
for (i = 0; i < N; i += rows)
{
for (j = 0; j < M; j += cols)
{
r = GSL_MIN(rows, N - i);
c = GSL_MIN(cols, N - j);
v = gsl_matrix_submatrix(m, i, j, r, c);
sprintf(buf, "%s(%u:%u,%u:%u)",
str,
i + 1,
i + r,
j + 1,
j + c);
printf("%s = [\n", buf);
output_matrix(&v.matrix);
printf("]\n");
}
}
} /* print_matrix() */
int
test_evals(gsl_vector_complex *obs, gsl_vector_complex *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname)
{
size_t N = expected->size;
size_t i, k;
double max, max_abserr, max_relerr;
max = 0.0;
max_abserr = 0.0;
max_relerr = 0.0;
k = 0;
for (i = 0; i < N; ++i)
{
gsl_complex z = gsl_vector_complex_get(expected, i);
max = GSL_MAX_DBL(max, gsl_complex_abs(z));
}
for (i = 0; i < N; ++i)
{
gsl_complex z_obs = gsl_vector_complex_get(obs, i);
gsl_complex z_exp = gsl_vector_complex_get(expected, i);
double x_obs = GSL_REAL(z_obs);
double y_obs = GSL_IMAG(z_obs);
double x_exp = GSL_REAL(z_exp);
double y_exp = GSL_IMAG(z_exp);
double abserr_x = fabs(x_obs - x_exp);
double abserr_y = fabs(y_obs - y_exp);
double noise = max * GSL_DBL_EPSILON * N * N;
max_abserr = GSL_MAX_DBL(max_abserr, abserr_x + abserr_y);
if (abserr_x < noise && abserr_y < noise)
continue;
if (abserr_x > 1.0e-6 || abserr_y > 1.0e-6)
++k;
}
if (k)
{
printf("==== CASE %lu ===========================\n\n", count);
print_matrix(A, "A");
print_matrix(B, "B");
printf("=== eval - %s ===\n", expname);
print_vector(expected, expname);
printf("=== eval - %s ===\n", obsname);
print_vector(obs, obsname);
printf("max abserr = %g max relerr = %g\n", max_abserr, max_relerr);
printf("=========================================\n\n");
}
return k;
} /* test_evals() */
int
test_alpha(gsl_vector_complex *obs, gsl_vector_complex *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname)
{
size_t N = expected->size;
size_t i, k;
double max, max_abserr, max_relerr;
max = 0.0;
max_abserr = 0.0;
max_relerr = 0.0;
k = 0;
for (i = 0; i < N; ++i)
{
gsl_complex z = gsl_vector_complex_get(expected, i);
max = GSL_MAX_DBL(max, gsl_complex_abs(z));
}
for (i = 0; i < N; ++i)
{
gsl_complex z_obs = gsl_vector_complex_get(obs, i);
gsl_complex z_exp = gsl_vector_complex_get(expected, i);
double x_obs = GSL_REAL(z_obs);
double y_obs = fabs(GSL_IMAG(z_obs));
double x_exp = GSL_REAL(z_exp);
double y_exp = fabs(GSL_IMAG(z_exp));
double abserr_x = fabs(x_obs - x_exp);
double abserr_y = fabs(y_obs - y_exp);
double noise = max * GSL_DBL_EPSILON * N * N;
max_abserr = GSL_MAX_DBL(max_abserr, abserr_x + abserr_y);
if (abserr_x < noise && abserr_y < noise)
continue;
if (abserr_x > 1.0e-6 || abserr_y > 1.0e-6)
++k;
}
if (k)
{
printf("==== CASE %lu ===========================\n\n", count);
print_matrix(A, "A");
print_matrix(B, "B");
printf("=== alpha - %s ===\n", expname);
print_vector(expected, expname);
printf("=== alpha - %s ===\n", obsname);
print_vector(obs, obsname);
printf("max abserr = %g max relerr = %g\n", max_abserr, max_relerr);
printf("=========================================\n\n");
}
return k;
} /* test_alpha() */
int
test_beta(gsl_vector *obs, gsl_vector *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname)
{
size_t N = expected->size;
size_t i, k;
double max, max_abserr, max_relerr;
max = 0.0;
max_abserr = 0.0;
max_relerr = 0.0;
k = 0;
for (i = 0; i < N; ++i)
{
double z = gsl_vector_get(expected, i);
max = GSL_MAX_DBL(max, fabs(z));
}
for (i = 0; i < N; ++i)
{
double v_obs = gsl_vector_get(obs, i);
double v_exp = gsl_vector_get(expected, i);
double abserr = fabs(v_obs - v_exp);
double noise = max * GSL_DBL_EPSILON * N * N;
max_abserr = GSL_MAX_DBL(max_abserr, abserr);
if (abserr < noise)
continue;
if (abserr > 1.0e-6)
++k;
}
if (k)
{
printf("==== CASE %lu ===========================\n\n", count);
print_matrix(A, "A");
print_matrix(B, "B");
printf("=== beta - %s ===\n", expname);
printf("%s = [\n", expname);
gsl_vector_fprintf(stdout, expected, "%.12e");
printf("]\n");
printf("=== beta - %s ===\n", obsname);
printf("%s = [\n", obsname);
gsl_vector_fprintf(stdout, obs, "%.12e");
printf("]\n");
printf("max abserr = %g max relerr = %g\n", max_abserr, max_relerr);
printf("=========================================\n\n");
}
return k;
} /* test_beta() */
/* test if A = Q S Z^t */
void
test_schur(gsl_matrix *A, gsl_matrix *S, gsl_matrix *Q, gsl_matrix *Z)
{
const size_t N = A->size1;
gsl_matrix *T1, *T2;
size_t i, j, k;
double lhs, rhs;
double abserr;
T1 = gsl_matrix_alloc(N, N);
T2 = gsl_matrix_alloc(N, N);
/* compute T1 = S Z^t */
gsl_blas_dgemm(CblasNoTrans,
CblasTrans,
1.0,
S,
Z,
0.0,
T1);
/* compute T2 = Q T1 = Q S Z^t */
gsl_blas_dgemm(CblasNoTrans,
CblasNoTrans,
1.0,
Q,
T1,
0.0,
T2);
k = 0;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
lhs = gsl_matrix_get(A, i, j);
rhs = gsl_matrix_get(T2, i, j);
abserr = fabs(lhs - rhs);
if (abserr > 1.0e-6)
++k;
}
}
if (k)
{
printf("==== CASE %lu ===========================\n\n", count);
print_matrix(A, "A");
printf("=== Schur Form matrix ===\n");
print_matrix(S, "S");
printf("=== Left Schur matrix ===\n");
print_matrix(Q, "Q");
printf("=== Right Schur matrix ===\n");
print_matrix(Z, "Z");
printf("=== Q S Z^t ===\n");
print_matrix(T1, "Q S Z^t");
printf("=== A - Q S Z^t ===\n");
gsl_matrix_sub(T2, A);
print_matrix(T1, "A - Q S Z^t");
printf("=========================================\n\n");
}
gsl_matrix_free(T1);
gsl_matrix_free(T2);
} /* test_schur() */
void
print_vector(gsl_vector_complex *eval, const char *str)
{
size_t N = eval->size;
size_t i;
gsl_complex z;
printf("%s = [\n", str);
for (i = 0; i < N; ++i)
{
z = gsl_vector_complex_get(eval, i);
printf("%.18e %.18e;\n", GSL_REAL(z), GSL_IMAG(z));
}
printf("]\n");
} /* print_vector() */
int
cmp(double a, double b)
{
return ((a > b) ? 1 : ((a < b) ? -1 : 0));
} /* cmp() */
int
compare(const void *a, const void *b)
{
const double *x = a;
const double *y = b;
int r1 = cmp(y[0], x[0]);
int r2 = cmp(y[1], x[1]);
if (!gsl_finite(x[0]))
return 1;
if (!gsl_finite(y[0]))
return -1;
if (fabs(x[0] - y[0]) < 1.0e-8)
{
/* real parts are very close to each other */
return r2;
}
else
{
return r1 ? r1 : r2;
}
} /* compare() */
void
sort_complex_vector(gsl_vector_complex *v)
{
qsort(v->data, v->size, 2 * sizeof(double), &compare);
} /* sort_complex_vector() */
int
main(int argc, char *argv[])
{
gen_workspace *gen_workspace_p;
lapack_workspace *lapack_workspace_p;
size_t N;
int c;
int lower;
int upper;
int incremental;
size_t nmat;
gsl_matrix *A, *B;
gsl_rng *r;
int s;
int compute_schur;
size_t i;
gsl_ieee_env_setup();
gsl_rng_env_setup();
N = 30;
lower = -10;
upper = 10;
incremental = 0;
nmat = 0;
compute_schur = 0;
while ((c = getopt(argc, argv, "ic:n:l:u:z")) != (-1))
{
switch (c)
{
case 'i':
incremental = 1;
break;
case 'n':
N = strtol(optarg, NULL, 0);
break;
case 'l':
lower = strtol(optarg, NULL, 0);
break;
case 'u':
upper = strtol(optarg, NULL, 0);
break;
case 'c':
nmat = strtoul(optarg, NULL, 0);
break;
case 'z':
compute_schur = 1;
break;
case '?':
default:
printf("usage: %s [-i] [-z] [-n size] [-l lower-bound] [-u upper-bound] [-c num]\n", argv[0]);
exit(1);
break;
} /* switch (c) */
}
A = gsl_matrix_alloc(N, N);
B = gsl_matrix_alloc(N, N);
gen_workspace_p = gen_alloc(N, compute_schur);
lapack_workspace_p = lapack_alloc(N);
r = gsl_rng_alloc(gsl_rng_default);
if (incremental)
{
make_start_matrix(A, lower);
/* we need B to be non-singular */
make_random_integer_matrix(B, r, lower, upper);
}
fprintf(stderr, "testing N = %d", N);
if (incremental)
fprintf(stderr, " incrementally");
else
fprintf(stderr, " randomly");
fprintf(stderr, " on element range [%d, %d]", lower, upper);
if (compute_schur)
fprintf(stderr, ", with Schur vectors");
fprintf(stderr, "\n");
while (1)
{
if (nmat && (count >= nmat))
break;
++count;
if (!incremental)
{
make_random_matrix(A, r, lower, upper);
make_random_matrix(B, r, lower, upper);
}
else
{
s = inc_matrix(A, lower, upper);
if (s)
break; /* all done */
make_random_integer_matrix(B, r, lower, upper);
}
/*if (count != 89120)
continue;*/
/* make copies of matrices */
gsl_matrix_memcpy(gen_workspace_p->A, A);
gsl_matrix_memcpy(gen_workspace_p->B, B);
gsl_matrix_transpose_memcpy(lapack_workspace_p->A, A);
gsl_matrix_transpose_memcpy(lapack_workspace_p->B, B);
/* compute eigenvalues with LAPACK */
s = lapack_proc(lapack_workspace_p);
if (s != GSL_SUCCESS)
{
printf("LAPACK failed, case %lu\n", count);
exit(1);
}
#if 0
print_matrix(A, "A");
print_matrix(B, "B");
gsl_matrix_transpose(lapack_workspace_p->A);
gsl_matrix_transpose(lapack_workspace_p->B);
print_matrix(lapack_workspace_p->A, "S_lapack");
print_matrix(lapack_workspace_p->B, "T_lapack");
#endif
/* compute eigenvalues with GSL */
s = gen_proc(gen_workspace_p);
if (s != GSL_SUCCESS)
{
printf("=========== CASE %lu ============\n", count);
printf("Failed to converge: found %u eigenvalues\n",
gen_workspace_p->n_evals);
print_matrix(A, "A");
print_matrix(B, "B");
print_matrix(gen_workspace_p->A, "Af");
print_matrix(gen_workspace_p->B, "Bf");
print_matrix(lapack_workspace_p->A, "Ae");
print_matrix(lapack_workspace_p->B, "Be");
exit(1);
}
#if 0
print_matrix(gen_workspace_p->A, "S_gsl");
print_matrix(gen_workspace_p->B, "T_gsl");
#endif
/* compute alpha / beta vectors */
for (i = 0; i < N; ++i)
{
double beta;
gsl_complex alpha, z;
beta = gsl_vector_get(gen_workspace_p->beta, i);
if (beta == 0.0)
GSL_SET_COMPLEX(&z, GSL_POSINF, GSL_POSINF);
else
{
alpha = gsl_vector_complex_get(gen_workspace_p->alpha, i);
z = gsl_complex_div_real(alpha, beta);
}
gsl_vector_complex_set(gen_workspace_p->evals, i, z);
beta = gsl_vector_get(lapack_workspace_p->beta, i);
GSL_SET_COMPLEX(&alpha,
lapack_workspace_p->alphar[i],
lapack_workspace_p->alphai[i]);
if (beta == 0.0)
GSL_SET_COMPLEX(&z, GSL_POSINF, GSL_POSINF);
else
z = gsl_complex_div_real(alpha, beta);
gsl_vector_complex_set(lapack_workspace_p->evals, i, z);
gsl_vector_complex_set(lapack_workspace_p->alpha, i, alpha);
}
#if 0
gsl_sort_vector(gen_workspace_p->beta);
gsl_sort_vector(lapack_workspace_p->beta);
sort_complex_vector(gen_workspace_p->alpha);
sort_complex_vector(lapack_workspace_p->alpha);
s = test_alpha(gen_workspace_p->alpha,
lapack_workspace_p->alpha,
A,
B,
"gen",
"lapack");
s = test_beta(gen_workspace_p->beta,
lapack_workspace_p->beta,
A,
B,
"gen",
"lapack");
#endif
#if 1
sort_complex_vector(gen_workspace_p->evals);
sort_complex_vector(lapack_workspace_p->evals);
s = test_evals(gen_workspace_p->evals,
lapack_workspace_p->evals,
A,
B,
"gen",
"lapack");
#endif
if (compute_schur)
{
test_schur(A,
gen_workspace_p->A,
gen_workspace_p->Q,
gen_workspace_p->Z);
test_schur(B,
gen_workspace_p->B,
gen_workspace_p->Q,
gen_workspace_p->Z);
}
}
gsl_matrix_free(A);
gsl_matrix_free(B);
gen_free(gen_workspace_p);
lapack_free(lapack_workspace_p);
if (r)
gsl_rng_free(r);
return 0;
} /* main() */
| {
"alphanum_fraction": 0.5316567395,
"avg_line_length": 22.552238806,
"ext": "c",
"hexsha": "9d12d93d51a0afe1e9940e2d7003eac6fb5e0f30",
"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/eigen/testgen2.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/eigen/testgen2.c",
"max_line_length": 106,
"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/eigen/testgen2.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": 6774,
"size": 22665
} |
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Program fwhm_by_modsq
* to compute the Full Width at Half Maximum of an equivalent long exposure
* with the power spectrum (square modulus of the FFT)
* (by fitting a Kolmogorof law)
*
* JLP
* Version 11-05-99
-------------------------------------------------------------------*/
/*
#define DEBUG
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <math.h>
#include <fftw.h>
#include <jlp_ftoc.h>
static int fit_kolmo_center(float *in_image, int nx, int ny,
float *sigx, float *sigy);
static int aris_r0calc(float *modsq, int nx, int ny, float *r0);
main(argc,argv)
int argc;
char *argv[];
{
char in_name[61], comments[81];
float *in_image, *testi;
INT_PNTR pntr_image;
INT4 istatus, nx, ny;
float sigx, sigy;
register int i, j;
printf(" Program FWHM_BY_MODSQ to compute the Full Width at Half Maximum from the power spectrum)\n");
printf(" JLP Version 11-05-99 \n");
/* One parameters only is allowed to run the program: */
/* Carefull: 7 parameters always, using JLP "runs" */
if(argc == 7 && *argv[3]) argc = 4;
if(argc == 7 && *argv[2]) argc = 3;
if(argc == 7 && *argv[1]) argc = 2;
if(argc != 2 && argc != 1)
{
printf(" Syntax: fwhm_by_modsq filename\n");
printf(" Fatal: Syntax error: argc=%d\n",argc);
exit(-1);
}
/* Interactive input of parameters: */
if (argc == 2 )
{
strcpy(in_name,argv[1]);
}
else
{
printf(" Input file := ");scanf("%s",in_name);
}
/**********************************************************/
JLP_BEGIN();
JLP_INQUIFMT();
istatus = JLP_VM_READIMAG1(&pntr_image,&nx,&ny,in_name,comments);
if(istatus != 0) exit(-1);
in_image = (float *) pntr_image;
/* Computing the power spectrum (for debug purpose)
testi = (float *)malloc(nx * ny * sizeof(float));
for(i = 0; i < nx * ny; i++) testi[i] = 0.;
fftw_float(in_image,testi,nx,ny,1);
for(i = 0; i < nx * ny; i++) in_image[i] = in_image[i] * in_image[i]
+ testi[i] * testi[i];
*/
fit_kolmo_center(in_image, nx, ny, &sigx, &sigy);
JLP_END();
}
/*****************************************************************
* To fit a Kolmogorof law to f1(xx,yy)
*
* f1: array of values f1(xx[i],yy[i])
* xx, yy: arrays of coordinates x, y
* npts: number of points
*
* Parameters:
* sigx, sigy, xc, yc, rho
* error[sigx,sigy,xc,yc,rho]
*
* ifail = 0 if correct
* -3: all values are negative or null!
*****************************************************************/
static int fit_kolmo_center(float *in_image, INT4 nx, INT4 ny,
float *sigx, float *sigy)
{
float *ff2, *gg;
INT4 istatus, npts, ifail, nx1, ny1, istart, jstart, iw, jw;
float aa, bb, r0, fwhm;
register int i, j;
nx1 = 20; ny1 = 20;
istart = nx/2 - nx1/2;
jstart = ny/2 - ny1/2;
ff2 = (float *) malloc(nx1 * ny1 * sizeof(float));
gg = (float *) malloc(nx1 * ny1 * sizeof(float));
if(ff2 == NULL || gg == NULL)
{
printf("FWHM/Fatal error alocating memory space \n");
exit(-1);
}
#ifdef DEBUG
printf(" istart=%d jstart=%d nx1=%d ny1=%d\n",istart,jstart,nx1,ny1);
#endif
for(j = 0; j < ny1; j++)
for(i = 0; i < nx1; i++)
{
iw = i + istart;
jw = j + jstart;
ff2[i + j * nx1] = (iw - nx/2) * (iw - nx/2) + (jw - ny/2) * (jw - ny/2);
gg[i + j * nx1] = in_image[iw + jw * nx];
}
npts = nx1 * ny1;
jlp_fit_kolmogorof(ff2, gg, &npts, &aa, &bb, &ifail);
/* JLP99: I notice that the ratio between long exposure determination
* and this program is about 15: */
fwhm = pow((double)(bb/6.88),-0.6)/15.;
/* fwhm = lambda /r0 */
r0 = 1./fwhm;
#ifdef DEBUG
printf(" Full Kolmogorov fit: aa=%f bb=%f r0=%f fwhm~%f (10 mm)\n",
aa,bb,r0,fwhm);
#else
printf(" Full Kolmogorov fit: r0=%f fwhm~%f (10 mm)\n",r0,fwhm);
#endif
aris_r0calc(in_image, nx, ny, &r0);
/* To make it compatible with the previous fit: */
r0 *= 4.;
printf(" Eric Aristidi approximation: r0=%f fwhm=%f\n",r0,1./r0);
return(0);
}
/***************************************************************
* fit_kolmogorof
* To fit a Kolmogorof law to Log_intensity(|x|^2) as a function of
* in x^2 + y^2
*
* g(f) = rho * exp [ -6.88 * (lambda * f / r_0)^5/3 ]
*
* g(f) = rho * exp [ - b * f^5/3 ] with b = 6.88 * (lambda / r_0)^5/3
*
* Log_Intensity(x,y)
* G(f) = a - b f^(5/3) with f^2 = x^2 + y^2
*
* where:
* The problem is to find the coefficients (a, b)
* which minimize the sums:
* SUM on all the selected disk (x, y) of ( Log_intensity - G(x,y) ) **2
*
* The normal equation can be written as:
*
* n a - b SUM f^5/3 = SUM Log_g
* a SUM f^5/3 - b SUM f^10/3 = SUM f^5/3 Log_g
*
* Hence:
* a = 1/n * (SUM Log_g + b SUM f^5/3)
* b = (SUM f^5/3 Log_g - 1/n SUM Log_g SUM f^5/3)
* / ( 1/n * SUM f^5/3 * SUM f^5/3 - SUM f^10/3)
*
* where n is the number of points (SUM 1)
*
*
* gg: array of values gg(xx[i],yy[i])
*
* ff2: arrays of x^2 + y^2
* npts: number of points
*
* ifail = 0 if correct
* -3: all values are negative or null!
*****************************************************************/
int jlp_fit_kolmogorof(float *ff2, float *gg, INT4 *npts,
float *aa, float *bb, INT4 *ifail)
{
/* gg measured intensities */
/* log_g log of measured intensities */
double *log_g, *ff;
double sum_g, sum_f1, sum_f2, sum_gf, w1;
register int i, j, k;
*ifail = 0;
if((log_g = (double *) malloc(*npts * sizeof(double))) == NULL ||
(ff = (double *) malloc(*npts * sizeof(double))) == NULL )
{
printf("jlp_fit_gauss/Error allocating memory for array (npts=%d)\n",*npts);
*ifail = -1;
return(-1);
}
/* Transfer to double precision arrays and conversion of intensity to Log : */
i = 0;
for(k = 0; k < *npts; k++)
{
if(gg[k] > 0)
{
log_g[i] = log((double)gg[k]);
ff[i] = ff2[k];
i++;
}
}
*npts = i;
if(*npts == 0)
{
printf("jlp_fit_gauss/All input values are null!\n");
*ifail = -1;
return(-1);
}
/* Compute the sums: 5/3 = 1.667 (but 5/6=0.833 since x^2+y^2)*/
/* Compute the sums: 10/3 = 0.833 (but 5/3=1.667 since x^2+y^2)*/
sum_f1 = 0.; sum_f2 = 0.;
sum_g = 0.; sum_gf = 0.;
for(k = 0; k < *npts; k++)
{
w1 = pow(ff[k],0.833);
sum_f1 += w1;
sum_f2 += pow(ff[k],1.667);
sum_g += log_g[k];
sum_gf += w1 * log_g[k];
}
#ifdef DEBUG
printf("sum_f1=%f sum_f2=%f sum_g=%f sum_gf=%f npts=%d\n",
sum_f1,sum_f2,sum_g,sum_gf,*npts);
#endif
/* Result:
* a = 1/n * (SUM Log_g + b SUM f^5/3)
* b = (SUM f^5/3 Log_g - 1/n SUM Log_g SUM f^5/3)
* / ( 1/n * SUM f^5/3 * SUM f^5/3 - SUM f^10/3)
*/
*bb = (sum_gf - (1. / *npts) * sum_g * sum_f1)
/ ( (1. / *npts) * sum_f1 * sum_f1 - sum_f2);
*aa = (1. / *npts) * (sum_g + *bb * sum_f1);
return(0);
}
/**********************************************************/
/* Eric Aristidi's fit (approximation only) */
static int aris_r0calc(float *modsq, int nx, int ny, float *r0)
{
int f12_1, f12_2, dim, ixc, iyc;
float pix,lambda,x,y1,y2,r01,r02;
dim = nx;
ixc = nx/2;
iyc = ny/2;
x=modsq[ixc + iyc*dim];
f12_1=4;
y1=modsq[(ixc+f12_1) + iyc * dim] + modsq[ixc + (iyc+f12_1) * dim];
y1/=2.;
f12_2=3;
y2=modsq[(ixc+f12_2) + iyc * dim] + modsq[ixc + (iyc+f12_2) * dim];
y2/=2.;
// Compute r0
// ---------
pix=0.0119/206265.;lambda=0.00000065;
r01=pow(3.44/log(x/y1),0.6)*lambda*(float)f12_1/pix/dim;
r02=pow(3.44/log(x/y2),0.6)*lambda*(float)f12_2/pix/dim;
*r0=(r02+r01)/2.;
}
| {
"alphanum_fraction": 0.5397056874,
"avg_line_length": 26.7482269504,
"ext": "c",
"hexsha": "cab274427daf51309424d98dc9001c0b7c3dfc2d",
"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": "bf00cc91d9669f6e4ed51b89df357fb27eead711",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jlprieur/sourcc",
"max_forks_repo_path": "fwhm_by_modsq.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bf00cc91d9669f6e4ed51b89df357fb27eead711",
"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": "jlprieur/sourcc",
"max_issues_repo_path": "fwhm_by_modsq.c",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bf00cc91d9669f6e4ed51b89df357fb27eead711",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jlprieur/sourcc",
"max_stars_repo_path": "fwhm_by_modsq.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2731,
"size": 7543
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_eigen.h>
#include "chisq_dist.h"
int chisq_dist(int mode, int do_chisq, int nophotoerr, int ncalc, int ncol,
double *covmat, double *c, double *slope,
double *pivotmag, double *refmag, double *refmagerr, double *magerr,
double *color, double *lupcorr, double *dist, double sigint) {
//int i,j,k;
int i,j,k;
int nmag = ncol+1;
//gsl_matrix *mcovmat;
gsl_matrix_view mvcovmat;
gsl_matrix *cobs;
gsl_matrix *cimat;
gsl_matrix *cobsmat;
gsl_matrix *cobstemp;
gsl_matrix *mmetric;
gsl_matrix *mrotmat;
gsl_vector *vdcm;
gsl_permutation *pp;
gsl_vector *vdc;
int s;
double *covmat_temp = NULL;
int covmat_stride;
int test;
double val;
double chisq,norm;
int use_refmagerr=0;
norm = 1.0;
covmat_stride = ncol*ncol; //*sizeof(double);
mrotmat = gsl_matrix_alloc(ncol,nmag);
gsl_matrix_set_zero(mrotmat); // important!
for (i=0;i<ncol;i++) {
gsl_matrix_set(mrotmat, i, i, 1.0);
gsl_matrix_set(mrotmat, i, i+1, -1.0);
}
cobs = gsl_matrix_alloc(nmag, nmag);
cobsmat = gsl_matrix_alloc(ncol,ncol);
cobstemp = gsl_matrix_alloc(ncol,nmag);
pp=gsl_permutation_alloc(ncol);
mmetric=gsl_matrix_alloc(ncol,ncol);
vdc = gsl_vector_alloc(ncol);
vdcm=gsl_vector_alloc(ncol);
cimat = NULL;
if (refmagerr != NULL) {
use_refmagerr = 1;
cimat = gsl_matrix_alloc(ncol,ncol);
}
if (mode == 0) {
// mode = 0
// Many galaxies, one redshift
// - refmag/refmagerr is an array with ncalc (==ngal)
// - color is a matrix with ncol x ncalc (==ngal)
// - magerr is a matrix with nmag x ncalc (==ngal)
// - c is an array with ncol
// - slope is an array with ncol
// - pivotmag is a single value
// - lupcorr is a matrix with ncol x ncalc (==ngal)
// //- covmat is a matrix with ncol x ncol x ncalc (==ngal)
// - covmat is a matrix with ncol x ncol
//
// // covmat[ncol,ncol,ncalc]: (k*ncol+j)*ncol + i
// covmat[ncol,ncol]: k*ncol + j
// c[ncol]: j
// slope[ncol]: j
// pivotmag[0]
// refmag[ncalc]: i
// refmagerr[ncalc]: i
// magerr[nmag,ncalc]: i*nmag + j
// color[ncol,ncalc]: i*ncol + j
// lupcorr[ncol,ncalc]: i*ncol + j
// first make a buffer for the local copy of the covmat (which gets overwritten)
if ((covmat_temp = (double *)calloc(ncol*ncol, sizeof(double))) == NULL) {
return -1;
}
for (i=0;i<ncalc;i++) {
memcpy(covmat_temp,covmat,sizeof(double)*ncol*ncol);
gsl_matrix_set_identity(cobs);
for (j=0;j<nmag;j++) {
gsl_matrix_set(cobs, j, j, magerr[i*nmag+j]*magerr[i*nmag+j]);
}
gsl_matrix_set_zero(cobstemp);
gsl_blas_dgemm(CblasNoTrans, CblasTrans,
1.0, mrotmat, cobs,
0.0, cobstemp);
gsl_blas_dgemm(CblasNoTrans, CblasTrans,
1.0, mrotmat, cobstemp,
0.0, cobsmat);
//mvcovmat = gsl_matrix_view_array(&covmat[covmat_stride*i], ncol, ncol);
mvcovmat = gsl_matrix_view_array(covmat_temp, ncol, ncol);
// and the ci matrix
if (use_refmagerr) {
// make the C_i matrix for the refmag err
// this is a matrix with ncol x ncol size
gsl_matrix_set_zero(cimat);
for (j=0;j<ncol;j++) {
for (k=j;k<ncol;k++) {
val = slope[j] * slope[k] * refmagerr[i] * refmagerr[i];
gsl_matrix_set(cimat, j, k, val);
if (k != j) {
gsl_matrix_set(cimat, k, j, val);
}
}
}
}
// check sigint
test = 1;
for (j=0;j<ncol;j++) {
if (gsl_matrix_get(&mvcovmat.matrix, j, j) < sigint*sigint) {
test = 0;
}
}
if (test == 0) {
if (do_chisq) {
dist[i] = 1e11;
} else {
dist[i] = -1e11;
}
} else {
if (!nophotoerr) {
gsl_matrix_add(&mvcovmat.matrix, cobsmat);
}
if (use_refmagerr) {
gsl_matrix_add(&mvcovmat.matrix, cimat);
}
// check and fix the matrix if necessary
check_and_fix_covmat(&mvcovmat.matrix);
gsl_linalg_LU_decomp(&mvcovmat.matrix, pp, &s);
gsl_linalg_LU_invert(&mvcovmat.matrix, pp, mmetric);
if (!do_chisq) {
// need the determinant
norm = gsl_linalg_LU_det(&mvcovmat.matrix, s);
}
// now need the slope, etc.
for (j=0;j<ncol;j++) {
gsl_vector_set(vdc,j,
(c[j]+slope[j]*(refmag[i]-pivotmag[0])) + lupcorr[i*ncol+j] -
color[i*ncol+j]);
}
gsl_blas_dgemv(CblasNoTrans, 1.0, mmetric, vdc, 0.0, vdcm);
gsl_blas_ddot(vdcm, vdc, &chisq);
if (do_chisq) {
dist[i] = chisq;
} else {
dist[i]=-0.5*chisq-0.5*log(norm);
}
}
}
free(covmat_temp);
} else if (mode==1) {
// mode = 1
// One galaxy, many redshifts
// - refmag/refmagerr is a single value
// - color is an array with ncol values
// - magerr is an array with nmag=ncol+1 values
// - c is a matrix with ncol x ncalc (==nz)
// - slope is a matrix with ncol x ncalc (==nz)
// - pivotmag is an array with ncalc (==nz)
// - lupcorr is a matrix with ncol x ncalc (==nz)
// - covmat is a matrix with ncol x ncol x ncalc (==nz)
//
// covmat[ncol,ncol,ncalc] : (k*ncol+j)*ncol+i
// c[ncol,ncalc]: i*ncol+j
// slope[ncol,ncalc]: i*ncol+j
// pivotmag[ncalc]: i
// magerr[nmag]: j
// color[ncol]: j
// lupcorr[ncol,ncalc]: i*ncol + j
// refmag[0]
// refmagerr[0]
// first make a buffer for the local copy of the covmat (which gets overwritten)
if ((covmat_temp = (double *)calloc(ncol*ncol*ncalc, sizeof(double))) == NULL) {
return -1;
}
memcpy(covmat_temp,covmat,sizeof(double)*ncol*ncol*ncalc);
// We can generate the C_obs matrix (cobsmat) just once
gsl_matrix_set_identity(cobs);
for (j=0;j<nmag;j++) {
gsl_matrix_set(cobs,j,j,magerr[j]*magerr[j]);
}
gsl_matrix_set_zero(cobstemp);
gsl_blas_dgemm(CblasNoTrans, CblasTrans,
1.0, mrotmat, cobs,
0.0, cobstemp);
gsl_blas_dgemm(CblasNoTrans, CblasTrans,
1.0, mrotmat, cobstemp,
0.0, cobsmat);
for (i=0;i<ncalc;i++) {
mvcovmat = gsl_matrix_view_array(&covmat_temp[covmat_stride*i], ncol, ncol);
if (use_refmagerr) {
// make the C_i matrix for the refmag err
// this is a matrix with ncol x ncol size...
gsl_matrix_set_zero(cimat);
for (j=0;j<ncol;j++) {
for (k=j;k<ncol;k++) {
val = slope[i*ncol+j] * slope[i*ncol+k] * refmagerr[0] * refmagerr[0];
gsl_matrix_set(cimat, j, k, val);
if (k != j) {
gsl_matrix_set(cimat, k, j, val);
}
}
}
}
// check sigint
test = 1;
for (j=0;j<ncol;j++) {
if (gsl_matrix_get(&mvcovmat.matrix, j, j) < sigint*sigint) {
test = 0;
}
}
if (test == 0) {
if (do_chisq) {
dist[i] = 1e11;
} else {
dist[i] = -1e11;
}
} else {
if (!nophotoerr) {
gsl_matrix_add(&mvcovmat.matrix, cobsmat);
}
if (use_refmagerr) {
gsl_matrix_add(&mvcovmat.matrix, cimat);
}
// check and fix the matrix if necessary
check_and_fix_covmat(&mvcovmat.matrix);
gsl_linalg_LU_decomp(&mvcovmat.matrix, pp, &s);
gsl_linalg_LU_invert(&mvcovmat.matrix, pp, mmetric);
if (!do_chisq) {
norm = gsl_linalg_LU_det(&mvcovmat.matrix, s);
}
for (j=0;j<ncol;j++) {
gsl_vector_set(vdc,j,
(c[i*ncol+j] + slope[i*ncol+j]*(refmag[0] - pivotmag[i])) + lupcorr[i*ncol+j] -
color[j]);
}
gsl_blas_dgemv(CblasNoTrans, 1.0, mmetric, vdc, 0.0, vdcm);
gsl_blas_ddot(vdcm,vdc, &chisq);
if (do_chisq) {
dist[i] = chisq;
} else {
dist[i]=-0.5*chisq-0.5*log(norm);
}
}
}
free(covmat_temp);
} else {
// mode = 2
// Many galaxies, many redshifts
// - refmag/refmagerr is an array with ncalc (==ngal)
// - color is a matrix with ncol x ncalc (==ngal)
// - magerr is a matrix with nmag x ncalc (==ngal)
// - c is a matrix with ncol x ncalc (==ngal)
// - slope is a matrix with ncol x ncalc (==ngal)
// - pivotmag is an array with ncalc (==ngal)
// - lupcorr is a matrix with ncol x ncalc (==ngal)
// - covmat is a matrix with ncol x ncol x ncalc (==ngal)
//
// covmat[ncol,ncol,ncalc] : (k*ncol+j)*ncol+i -> mode 0
// c[ncol,ncalc]: i*ncol+j -> mode 1
// slope[ncol,ncalc]: i*ncol+j -> mode 1
// pivotmag[ncalc]: i -> mode 1
// refmag[ncalc]: i -> mode 0
// refmagerr[ncalc]: i -> mode 0
// magerr[nmag,ncalc]: i*nmag + j -> mode 0
// color[ncol,ncalc]: i*ncol + j -> mode 0
// lupcorr[ncol,ncalc]: i*ncol + j -> mode 0, 1
if ((covmat_temp = (double *)calloc(ncol*ncol*ncalc, sizeof(double))) == NULL) {
return -1;
}
memcpy(covmat_temp,covmat,sizeof(double)*ncol*ncol*ncalc);
for (i=0;i<ncalc;i++) {
// copy from mode 0
gsl_matrix_set_identity(cobs);
for (j=0;j<nmag;j++) {
// okay
gsl_matrix_set(cobs, j, j, magerr[i*nmag+j]*magerr[i*nmag+j]);
}
gsl_matrix_set_zero(cobstemp);
gsl_blas_dgemm(CblasNoTrans, CblasTrans,
1.0, mrotmat, cobs,
0.0, cobstemp);
gsl_blas_dgemm(CblasNoTrans, CblasTrans,
1.0, mrotmat, cobstemp,
0.0, cobsmat);
mvcovmat = gsl_matrix_view_array(&covmat_temp[covmat_stride*i], ncol, ncol);
// and the ci matrix
// copy from mode 0
if (use_refmagerr) {
// make the C_i matrix for the refmag err
// this is a matrix with ncol x ncol size
gsl_matrix_set_zero(cimat);
for (j=0;j<ncol;j++) {
for (k=j;k<ncol;k++) {
val = slope[j] * slope[k] * refmagerr[i] * refmagerr[i];
gsl_matrix_set(cimat, j, k, val);
if (k != j) {
gsl_matrix_set(cimat, k, j, val);
}
}
}
}
// check sigint
// copy from mode 0
test = 1;
for (j=0;j<ncol;j++) {
if (gsl_matrix_get(&mvcovmat.matrix, j, j) < sigint*sigint) {
test = 0;
}
}
if (test == 0) {
if (do_chisq) {
dist[i] = 1e11;
} else {
dist[i] = -1e11;
}
} else {
// copy from mode 0
if (!nophotoerr) {
gsl_matrix_add(&mvcovmat.matrix, cobsmat);
}
// copy from mode 0
if (use_refmagerr) {
gsl_matrix_add(&mvcovmat.matrix, cimat);
}
// check and fix the matrix if necessary
// copy from mode 0
check_and_fix_covmat(&mvcovmat.matrix);
gsl_linalg_LU_decomp(&mvcovmat.matrix, pp, &s);
gsl_linalg_LU_invert(&mvcovmat.matrix, pp, mmetric);
if (!do_chisq) {
// need the determinant
norm = gsl_linalg_LU_det(&mvcovmat.matrix, s);
}
// vdc is a vector with ncol...
// copy from mode 1
for (j=0;j<ncol;j++) {
gsl_vector_set(vdc,j,
(c[i*ncol+j] + slope[i*ncol+j]*(refmag[i] - pivotmag[i])) + lupcorr[i*ncol+j] -
color[i*ncol+j]);
}
gsl_blas_dgemv(CblasNoTrans, 1.0, mmetric, vdc, 0.0, vdcm);
gsl_blas_ddot(vdcm,vdc, &chisq);
if (do_chisq) {
dist[i] = chisq;
} else {
dist[i]=-0.5*chisq-0.5*log(norm);
}
}
}
free(covmat_temp);
}
gsl_matrix_free(mrotmat);
gsl_matrix_free(cobs);
gsl_matrix_free(cobsmat);
gsl_matrix_free(cobstemp);
if (use_refmagerr) gsl_matrix_free(cimat);
gsl_permutation_free(pp);
gsl_matrix_free(mmetric);
gsl_vector_free(vdcm);
gsl_vector_free(vdc);
return 0;
}
int check_and_fix_covmat(gsl_matrix *covmat) {
int i, s, test;
double eigenval_i;
gsl_vector_view diag;
int nelt;
gsl_matrix *mat;
gsl_vector *eigenval;
gsl_vector *eigenval_temp;
gsl_eigen_symm_workspace *wval;
gsl_eigen_symmv_workspace *wvec;
gsl_matrix *Q;
gsl_matrix *Qinv;
gsl_matrix *Lambda;
gsl_matrix *temp;
gsl_permutation *pp;
nelt = covmat->size1;
mat=gsl_matrix_alloc(nelt,nelt);
wval = gsl_eigen_symm_alloc(nelt);
wvec = gsl_eigen_symmv_alloc(nelt);
eigenval = gsl_vector_alloc(nelt);
// don't destroy the input matrix!
gsl_matrix_memcpy(mat, covmat);
// calculate eigenvalues...
gsl_eigen_symm(mat, eigenval, wval);
// test if the eigenvalues are negative...
test = 0;
for (i=0;i<nelt;i++) {
eigenval_i = gsl_vector_get(eigenval,i);
if (eigenval_i < MIN_EIGENVAL) {
test = 1;
gsl_vector_set(eigenval,i,MIN_EIGENVAL);
}
}
if (test) {
// initialize
Q=gsl_matrix_alloc(nelt,nelt);
Qinv=gsl_matrix_alloc(nelt,nelt);
Lambda=gsl_matrix_alloc(nelt,nelt);
temp=gsl_matrix_alloc(nelt,nelt);
eigenval_temp=gsl_vector_alloc(nelt);
pp=gsl_permutation_alloc(nelt);
// reset the matrix
gsl_matrix_memcpy(mat, covmat);
// calculate eigenvalues and eigenvector matrix Q
gsl_eigen_symmv(mat, eigenval_temp, Q, wvec);
// invert eigenvector matrix Q-> Qinv (leaving Q in place)
gsl_matrix_memcpy(temp,Q);
gsl_linalg_LU_decomp(temp, pp, &s);
gsl_linalg_LU_invert(temp, pp, Qinv);
// create a diagonal matrix Lambda
diag = gsl_matrix_diagonal(Lambda);
gsl_matrix_set_zero(Lambda);
gsl_vector_memcpy(&diag.vector, eigenval);
// do the multiplication
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Q, Lambda, 0.0, temp);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, temp, Qinv, 0.0, covmat);
gsl_matrix_free(Q);
gsl_matrix_free(Qinv);
gsl_matrix_free(Lambda);
gsl_matrix_free(temp);
gsl_vector_free(eigenval_temp);
gsl_permutation_free(pp);
}
gsl_matrix_free(mat);
gsl_vector_free(eigenval);
gsl_eigen_symm_free(wval);
gsl_eigen_symmv_free(wvec);
return 0;
}
| {
"alphanum_fraction": 0.5971135205,
"avg_line_length": 26.1785714286,
"ext": "c",
"hexsha": "a64d701bc9fad0f95192df3b709ee8d5b2c4b2d4",
"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": "bda5bd6f486fd5f18d35aa9ae4b875628e905604",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jacobic/redmapper",
"max_forks_repo_path": "redmapper/chisq_dist/chisq_dist.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bda5bd6f486fd5f18d35aa9ae4b875628e905604",
"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": "jacobic/redmapper",
"max_issues_repo_path": "redmapper/chisq_dist/chisq_dist.c",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bda5bd6f486fd5f18d35aa9ae4b875628e905604",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jacobic/redmapper",
"max_stars_repo_path": "redmapper/chisq_dist/chisq_dist.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4764,
"size": 13927
} |
#ifndef utils_h
#define utils_h
#include <ceed.h>
#include <petsc.h>
// Translate PetscMemType to CeedMemType
static inline CeedMemType MemTypeP2C(PetscMemType mem_type) {
return PetscMemTypeDevice(mem_type) ? CEED_MEM_DEVICE : CEED_MEM_HOST;
}
#endif // utils_h | {
"alphanum_fraction": 0.7865168539,
"avg_line_length": 22.25,
"ext": "h",
"hexsha": "4d85e777c503eb9b153b80196e1ca79a110ccae7",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/solids/include/utils.h",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/solids/include/utils.h",
"max_line_length": 72,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/solids/include/utils.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": 75,
"size": 267
} |
/// @file PosixDomain.h
/// @author Braxton Salyer <braxtonsalyer@gmail.com>
/// @brief `StatusCodeDomain` supporting platform-implementation-specific values of `errno` in
/// addition to those __required__ by POSIX
/// @version 0.1
/// @date 2021-11-10
///
/// MIT License
/// @copyright Copyright (c) 2021 Braxton Salyer <braxtonsalyer@gmail.com>
///
/// 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 <Hyperion/error/GenericDomain.h>
#include <Hyperion/error/StatusCode.h>
#include <cstring>
#include <gsl/gsl>
namespace hyperion::error {
class PosixDomain;
using PosixStatusCode = StatusCode<PosixDomain>;
using PosixErrorCode = ErrorCode<PosixDomain>;
/// @brief `PosixDomain` is the `StatusCodeDomain` that covers status codes covering a
/// platform's specific implementation of `errno` values in addition to those __strictly__
/// required by POSIX (those represented by `Errno`).
/// @ingroup error
/// @headerfile "Hyperion/error/PosixDomain.h"
class [[nodiscard("A StatusCodeDomain should always be used")]] PosixDomain {
public:
/// @brief The value type of `PosixDomain` status codes is `i64`
/// @ingroup error
using value_type = i64;
static const constexpr char(&UUID)[num_chars_in_uuid] // NOLINT
= "4a6a9b0f-c335-473e-bc42-d23974a25bb0";
static constexpr u64 ID = parse_uuid_from_string(UUID);
/// @brief Constructs a `PosixDomain` with the default UUID
/// @ingroup error
constexpr PosixDomain() noexcept = default;
/// @brief Constructs a `PosixDomain` with a user-specific UUID
///
/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program
/// should be constructed with the same custom UUID, otherwise equality comparison between
/// other domains and `PosixDomain` instances could give erroneous results, and equality
/// comparison between different `PosixDomain` instances will give erroneous results.
/// As a result, this constructor should only be used when you specifically require a custom
/// UUID and **YOU KNOW WHAT YOU ARE DOING™**
///
/// @param uuid - The UUID to use for `PosixDomain`
/// @ingroup error
explicit constexpr PosixDomain(u64 uuid) noexcept : m_uuid(uuid) {
}
/// @brief Constructs a `PosixDomain` with a user-specific UUID
///
/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program
/// should be constructed with the same custom UUID, otherwise equality comparison between
/// other domains and `PosixDomain` instances could give erroneous results, and equality
/// comparison between different `PosixDomain` instances will give erroneous results.
/// As a result, this constructor should only be used when you specifically require a custom
/// UUID and **YOU KNOW WHAT YOU ARE DOING™**
///
/// @param uuid - The UUID to use for `PosixDomain`
/// @ingroup error
template<UUIDString UUID>
explicit constexpr PosixDomain(UUID && uuid) noexcept // NOLINT (forwarding reference)
: m_uuid(parse_uuid_from_string(std::forward<UUID>(uuid))) {
}
/// @brief Copy-Constructor
/// @ingroup error
constexpr PosixDomain(const PosixDomain&) noexcept = default;
/// @brief Move-Constructor
/// @ingroup error
constexpr PosixDomain(PosixDomain &&) noexcept = default;
/// @brief Destructor
/// @ingroup error
constexpr ~PosixDomain() noexcept = default;
/// @brief Returns the UUID of the domain
///
/// @return the domain UUID
/// @ingroup error
[[nodiscard]] constexpr auto id() const noexcept->u64 {
return m_uuid;
}
/// @brief Returns the name of the domain
///
/// @return the domain name
/// @ingroup error
[[nodiscard]] constexpr auto name() const noexcept->std::string_view { // NOLINT
return "POSIX domain";
}
/// @brief Returns the textual message associated with the given status code
///
/// @param code - The status code to get the message for
///
/// @return the message associated with the code
/// @ingroup error
[[nodiscard]] auto message(value_type code) // NOLINT
const noexcept->std::string {
return as_string(code);
}
/// @brief Returns the textual message associated with the given status code
///
/// @param code - The status code to get the message for
///
/// @return the message associated with the code
/// @ingroup error
[[nodiscard]] auto message(const PosixStatusCode& code) // NOLINT
const noexcept->std::string {
return as_string(code.code());
}
/// @brief Returns whether the given status code represents an error
///
/// @param code - The status code to check
///
/// @return `true` if the code represents an error, otherwise `false`
/// @ingroup error
[[nodiscard]] constexpr auto is_error(const PosixStatusCode& code) // NOLINT
const noexcept->bool {
return code.code() != 0;
}
/// @brief Returns whether the given status code represents success
///
/// @param code - The status code to check
///
/// @return `true` if the code represents success, otherwise `false`
/// @ingroup error
[[nodiscard]] constexpr auto is_success(const PosixStatusCode& code) // NOLINT
const noexcept->bool {
return code.code() == 0;
}
/// @brief Returns whether the given status codes are semantically equivalent
///
/// Checks if the given codes are semantically equivalent. For most `StatusCodeDomain`s,
/// this usually means checking the codes for equality after being converted to
/// `GenericStatusCode`s.
///
/// @tparam Domain - The `StatusCodeDomain` of the second status code
/// @param lhs - The first status code to compare
/// @param rhs - The second status code to compare
/// @return `true` if the codes are semantically equivalent, `false` otherwise
/// @ingroup error
template<typename Domain>
[[nodiscard]] constexpr auto are_equivalent(const PosixStatusCode& lhs,
const StatusCode<Domain>& rhs)
const noexcept->bool {
if constexpr(ConvertibleToGenericStatusCode<StatusCode<Domain>>) {
return as_generic_code(lhs) == rhs.as_generic_code();
}
else if(rhs.domain() == *this) {
const auto lhs_code = lhs.code();
const auto rhs_code = rhs.code();
return lhs_code == rhs_code && lhs_code != -1 && rhs_code != -1;
}
else {
return false;
}
}
/// @brief Converts the given status code to a `GenericStatusCode`
///
/// This will convert the given code to its semantically equivalent counterpart in the
/// `GenericDomain`.
///
/// @param code - The status code to convert to a `GenericStatusCode`
/// @return The given status code as a `GenericStatusCode`
/// @note Not all status code values are convertible to the `GenericDomain`, even
/// from domains fully compatible with `GenericDomain` and that satisfy
/// `ConvertibleToGenericStatusCode`. In this case, they will map to `Errno::Unknown`.
/// Codes of value `Errno::Unknown` will never compare as semantically equivalent.
/// @ingroup error
[[nodiscard]] constexpr auto as_generic_code(const PosixStatusCode& code) // NOLINT
const noexcept->GenericStatusCode {
return make_status_code(to_generic_code(code.code()));
}
/// @brief Returns the value indicating success for this domain
///
/// @return The domain's success value
/// @ingroup error
[[nodiscard]] static inline constexpr auto success_value() noexcept->value_type {
return 0;
}
/// @brief Returns the most recent value of `errno`
///
/// @return the value of `errno` at the time of the call
/// @ingroup error
[[nodiscard]] static inline auto get_last_error() noexcept->value_type {
return errno;
}
/// @brief Domain equality comparison operator
///
/// @tparam Domain - The type of the second domain to compare
///
/// @param lhs - The left-hand domain to compare
/// @param rhs - The right-hand domain to compare
///
/// @return Whether the two domains are equal
/// @ingroup error
template<typename Domain>
friend constexpr auto operator==(const PosixDomain& lhs, const Domain& rhs) noexcept->bool {
return lhs.id() == rhs.id();
}
/// @brief Domain inequality comparison operator
///
/// @tparam Domain - The type of the second domain to compare
///
/// @param lhs - The left-hand domain to compare
/// @param rhs - The right-hand domain to compare
///
/// @return Whether the two domains are __not__ equal
/// @ingroup error
template<typename Domain>
friend constexpr auto operator!=(const PosixDomain& lhs, const Domain& rhs) noexcept->bool {
return lhs.id() != rhs.id();
}
/// @brief Copy-assignment operator
/// @ingroup error
constexpr auto operator=(const PosixDomain&) noexcept->PosixDomain& = default;
/// @brief Move-assignment operator
/// @ingroup error
constexpr auto operator=(PosixDomain&&) noexcept->PosixDomain& = default;
private:
u64 m_uuid = ID;
[[nodiscard]] static inline auto as_string(value_type code) noexcept->std::string {
char buffer[1024]; // NOLINT
#if HYPERION_PLATFORM_WINDOWS
strerror_s(buffer, 1024, gsl::narrow_cast<i32>(code)); // NOLINT
#elif defined(__gnu_linux__) && !defined(__ANDROID__)
char* message = strerror_r(gsl::narrow_cast<i32>(code), buffer, 1024); // NOLINT
if(message != nullptr) {
strncpy(buffer, message, 1024); // NOLINT
buffer[1023] = 0; // NOLINT
}
#else
str_error_r(code, buffer, 1024); // NOLINT
#endif
usize length = strlen(buffer); // NOLINT
return std::string(buffer, length); // NOLINT
}
[[nodiscard]] static inline constexpr auto to_generic_code(
value_type code) noexcept->Errno {
switch(code) {
case 0: return Errno::Success;
case EAFNOSUPPORT: return Errno::AddressFamilyNotSupported;
case EADDRINUSE: return Errno::AddressInUse;
case EADDRNOTAVAIL: return Errno::AddressNotAvailable;
case EISCONN: return Errno::AlreadyConnected;
case E2BIG: return Errno::ArgumentListTooLong;
case EDOM: return Errno::ArgumentOutOfDomain;
case EFAULT: return Errno::BadAddress;
case EBADF: return Errno::BadFileDescriptor;
case EBADMSG: return Errno::BadMessage;
case EPIPE: return Errno::BrokenPipe;
case ECONNABORTED: return Errno::ConnectionAborted;
case EALREADY: return Errno::ConnectionAlreadyInProgress;
case ECONNREFUSED: return Errno::ConnectionRefused;
case ECONNRESET: return Errno::ConnectionReset;
case EXDEV: return Errno::CrossDeviceLink;
case EDESTADDRREQ: return Errno::DestinationAddressRequired;
case EBUSY: return Errno::DeviceOrResourceBusy;
case ENOTEMPTY: return Errno::DirectoryNotEmpty;
case ENOEXEC: return Errno::ExecutableFormatError;
case EEXIST: return Errno::FileExists;
case EFBIG: return Errno::FileTooLarge;
case ENAMETOOLONG: return Errno::FilenameTooLong;
case ENOSYS: return Errno::FunctionNotSupported;
case EHOSTUNREACH: return Errno::HostUnreachable;
case EIDRM: return Errno::IdentifierRemoved;
case EILSEQ: return Errno::IllegalByteSequence;
case ENOTTY: return Errno::InappropriateIOControlOperation;
case EINTR: return Errno::Interrupted;
case EINVAL: return Errno::InvalidArgument;
case ESPIPE: return Errno::InvalidSeek;
case EIO: return Errno::IOError;
case EISDIR: return Errno::IsADirectory;
case EMSGSIZE: return Errno::MessageSize;
case ENETDOWN: return Errno::NetworkDown;
case ENETRESET: return Errno::NetworkReset;
case ENETUNREACH: return Errno::NetworkUnreachable;
case ENOBUFS: return Errno::NoBufferSpace;
case ECHILD: return Errno::NoChildProcess;
case ENOLINK: return Errno::NoLink;
case ENOLCK: return Errno::NoLockAvailable;
case ENODATA: return Errno::NoMessageAvailable;
case ENOMSG: return Errno::NoMessage;
case ENOPROTOOPT: return Errno::NoProtocolOption;
case ENOSPC: return Errno::NoSpaceOnDevice;
case ENOSR: return Errno::NoStreamResources;
case ENXIO: return Errno::NoSuchDeviceOrAddress;
case ENODEV: return Errno::NoSuchDevice;
case ENOENT: return Errno::NoSuchFileOrDirectory;
case ESRCH: return Errno::NoSuchProcess;
case ENOTDIR: return Errno::NotADirectory;
case ENOTSOCK: return Errno::NotASocket;
case ENOSTR: return Errno::NotAStream;
case ENOTCONN: return Errno::NotConnected;
case ENOMEM: return Errno::NotEnoughMemory;
#if ENOTSUP != EOPNOTSUPP
case ENOTSUP: return Errno::NotSupported;
#endif
case ECANCELED: return Errno::OperationCanceled;
case EINPROGRESS: return Errno::OperationInProgress;
case EPERM: return Errno::OperationNotPermitted;
case EOPNOTSUPP: return Errno::OperationNotSupported;
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK: return Errno::OperationWouldBlock;
#endif
case EOWNERDEAD: return Errno::OwnerDead;
case EACCES: return Errno::PermissionDenied;
case EPROTO: return Errno::ProtocolError;
case EPROTONOSUPPORT: return Errno::ProtocolNotSupported;
case EROFS: return Errno::ReadOnlyFileSystem;
case EDEADLK: return Errno::ResourceDeadlockWouldOccur;
case EAGAIN: return Errno::ResourceUnavailableTryAgain;
case ERANGE: return Errno::ResultOutOfRange;
case ENOTRECOVERABLE: return Errno::StateNotRecoverable;
case ETIME: return Errno::StreamTimeout;
case ETXTBSY: return Errno::TextFileBusy;
case ETIMEDOUT: return Errno::TimedOut;
case ENFILE: return Errno::TooManyFilesOpenInSystem;
case EMFILE: return Errno::TooManyFilesOpen;
case EMLINK: return Errno::TooManyLinks;
case ELOOP: return Errno::TooManySymbolicLinkLevels;
case EOVERFLOW: return Errno::ValueTooLarge;
case EPROTOTYPE: return Errno::WrongProtocolType;
default: return Errno::Unknown;
}
}
};
} // namespace hyperion::error
/// @brief Specialize `make_status_code_domain` for `PosixDomain` and `u64`.
/// Creates a `PosixDomain` with a custom UUID.
///
/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program
/// should be constructed with the same custom UUID, otherwise equality comparison between
/// other domains and `PosixDomain` instances could give erroneous results, and equality
/// comparison between different `PosixDomain` instances will give erroneous results.
/// As a result, this constructor should only be used when you specifically require a custom
/// UUID and **YOU KNOW WHAT YOU ARE DOING™**
///
/// @param uuid - The UUID to use for `PosixDomain`
///
/// @return a `PosixDomain`
/// @ingroup error
template<>
[[nodiscard]] inline constexpr auto
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
make_status_code_domain<hyperion::error::PosixDomain, hyperion::u64>(hyperion::u64&& uuid) noexcept
-> hyperion::error::PosixDomain {
return hyperion::error::PosixDomain(uuid);
}
/// @brief Specialize `make_status_code_domain` for `PosixDomain` and a `UUIDString`.
/// Creates a `PosixDomain` with a custom UUID.
///
/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program
/// should be constructed with the same custom UUID, otherwise equality comparison between
/// other domains and `PosixDomain` instances could give erroneous results, and equality
/// comparison between different `PosixDomain` instances will give erroneous results.
/// As a result, this constructor should only be used when you specifically require a custom
/// UUID and **YOU KNOW WHAT YOU ARE DOING™**
///
/// @param uuid - The UUID to use for `PosixDomain`
///
/// @return a `PosixDomain`
/// @ingroup error
template<>
[[nodiscard]] inline constexpr auto
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
make_status_code_domain<hyperion::error::PosixDomain,
const char (&)[hyperion::error::num_chars_in_uuid]> // NOLINT
(const char (&uuid)[hyperion::error::num_chars_in_uuid]) noexcept // NOLINT
-> hyperion::error::PosixDomain {
return hyperion::error::PosixDomain(uuid);
}
/// @brief Specialize `make_status_code_domain` for `PosixDomain` and an MS-style `UUIDString`.
/// Creates a `PosixDomain` with a custom UUID.
///
/// @note When using a custom UUID __**ALL**__ instances of `PosixDomain` in the program
/// should be constructed with the same custom UUID, otherwise equality comparison between
/// other domains and `PosixDomain` instances could give erroneous results, and equality
/// comparison between different `PosixDomain` instances will give erroneous results.
/// As a result, this constructor should only be used when you specifically require a custom
/// UUID and **YOU KNOW WHAT YOU ARE DOING™**
///
/// @param uuid - The UUID to use for `PosixDomain`
///
/// @return a `PosixDomain`
/// @ingroup error
template<>
[[nodiscard]] inline constexpr auto
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name)
make_status_code_domain<hyperion::error::PosixDomain,
const char (&)[hyperion::error::num_chars_in_ms_uuid]> // NOLINT
(const char (&uuid)[hyperion::error::num_chars_in_ms_uuid]) noexcept // NOLINT
-> hyperion::error::PosixDomain {
return hyperion::error::PosixDomain(uuid);
}
/// @brief Specialize `make_status_code_domain` for `PosixDomain` with no arguments. Creates
/// a `PosixDomain` with the default UUID.
///
/// @return a `PosixDomain`
/// @ingroup error
template<>
inline constexpr auto
make_status_code_domain<hyperion::error::PosixDomain>() noexcept -> hyperion::error::PosixDomain {
return {};
}
namespace hyperion::error {
static_assert(StatusCodeDomain<PosixDomain>);
} // namespace hyperion::error
| {
"alphanum_fraction": 0.7240264986,
"avg_line_length": 40.9867549669,
"ext": "h",
"hexsha": "ffd5987b7b5d1bd2630a600edca5a772f9c80518",
"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": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "braxtons12/Hyperion-Utils",
"max_forks_repo_path": "include/Hyperion/error/PosixDomain.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"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-Utils",
"max_issues_repo_path": "include/Hyperion/error/PosixDomain.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "braxtons12/Hyperion-Utils",
"max_stars_repo_path": "include/Hyperion/error/PosixDomain.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4821,
"size": 18567
} |
#ifndef __MATHINT_H_
#define __MATHINT_H_
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <immintrin.h>
#include <stdbool.h>
#if (defined __AVX__ || defined __SSE4_2__)
#include "math_x86.h"
#endif
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_integration.h>
#define pi 3.14159265358979323846264338327950288
#define MAX(a, b) ((a > b) ? a : b)
#define MIN(a, b) ((a > b) ? b : a)
#define EULER 0.577215664901532860606512090082402431042
#define EPSILON __DBL_EPSILON__
#define STACK_SIZE 100000 /*FIXME: This must be adpative.*/
double IncompBesselK0_Simpson(double tol, int *cnt, double bes_a, double bes_b, int der);
double computeK0(double a, double b);
double computeINCBK0(double a, double b, int der);
typedef struct {
double a;
double b;
} gsl_params;
double bessel_f(double x, void * p);
double bessel_f_der(double x, void * p);
double call_gsl_bessel_integrator(double a, double b,
gsl_integration_workspace *w, int der);
void inline set_zero_4(double *x)
{
x[0] = 0; x[1] = 0; x[2] = 0; x[3] = 0;
}
#endif
| {
"alphanum_fraction": 0.7162661738,
"avg_line_length": 25.1627906977,
"ext": "h",
"hexsha": "dfc3f78ed63ebfb64bfcfb7e4f9d086340fad47b",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2020-07-19T12:40:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-03T11:56:23.000Z",
"max_forks_repo_head_hexsha": "60c466e839032a6d2b2e2d9afb49a91d7d4f5dbd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ludvigak/SE_unified",
"max_forks_repo_path": "SE1P/mex/mathint.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "60c466e839032a6d2b2e2d9afb49a91d7d4f5dbd",
"max_issues_repo_issues_event_max_datetime": "2017-03-09T15:23:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-02-27T15:07:32.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ludvigak/SE_unified",
"max_issues_repo_path": "SE1P/mex/mathint.h",
"max_line_length": 89,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "60c466e839032a6d2b2e2d9afb49a91d7d4f5dbd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ludvigak/SE_unified",
"max_stars_repo_path": "SE1P/mex/mathint.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-29T22:11:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-02-27T14:54:44.000Z",
"num_tokens": 357,
"size": 1082
} |
#ifndef TTT_GFX_TEXT_H
#define TTT_GFX_TEXT_H
#include <SDL_render.h>
#include <SDL_ttf.h>
#include <gsl/pointers>
#include <gsl/util>
#include <memory>
#include <string_view>
#include <string>
#include <stdexcept>
#include <cstdint>
namespace ttt::gfx
{
class TextError final : public std::runtime_error
{
public:
TextError(const std::string &msg) noexcept;
};
inline TextError::TextError(const std::string &msg) noexcept
: runtime_error{msg}
{
}
// A very simple class for rendering text.
class Text final
{
public:
Text() = default;
Text(std::string_view str, gsl::not_null<TTF_Font *> font, const SDL_Colour &colour, bool shadow, gsl::not_null<SDL_Renderer *> renderer);
void setText(std::string_view str, gsl::not_null<TTF_Font *> font, const SDL_Colour &colour, bool shadow, gsl::not_null<SDL_Renderer *> renderer);
void clear() noexcept;
void render(gsl::not_null<SDL_Renderer *> renderer, const SDL_FPoint &pos, double angle = 0.0, const SDL_FPoint *centre = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE) const noexcept;
[[nodiscard]] SDL_Point getSize() const noexcept { return size; }
private:
using TexturePointer = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>;
TexturePointer primary{nullptr, SDL_DestroyTexture};
TexturePointer secondary{nullptr, SDL_DestroyTexture};
SDL_Point size{0, 0};
[[nodiscard]] TexturePointer createTexture(std::string_view str, gsl::not_null<TTF_Font *> font, const SDL_Colour &colour, gsl::not_null<SDL_Renderer *> renderer);
[[nodiscard]] SDL_Colour createShadowColour(const SDL_Colour &colour) const noexcept;
};
inline SDL_Colour Text::createShadowColour(const SDL_Colour &colour) const noexcept
{
return {
gsl::narrow_cast<std::uint8_t>(colour.r % 5),
gsl::narrow_cast<std::uint8_t>(colour.g % 5),
gsl::narrow_cast<std::uint8_t>(colour.b % 5),
colour.a
};
}
}
#endif | {
"alphanum_fraction": 0.7376445846,
"avg_line_length": 29.2615384615,
"ext": "h",
"hexsha": "77efc761b40b7c99f1d6c5d57f187ce4c4f22390",
"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": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "itsArtem/TicTacToe",
"max_forks_repo_path": "Source/Graphics/Text.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"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": "itsArtem/TicTacToe",
"max_issues_repo_path": "Source/Graphics/Text.h",
"max_line_length": 187,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "itsArtem/TicTacToe",
"max_stars_repo_path": "Source/Graphics/Text.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 520,
"size": 1902
} |
/* $Id$ */
/*--------------------------------------------------------------------*/
/*; Copyright (C) 2013 */
/*; Associated Universities, Inc. Washington DC, USA. */
/*; */
/*; This program is free software; you can redistribute it and/or */
/*; modify it under the terms of the GNU General Public License as */
/*; published by the Free Software Foundation; either version 2 of */
/*; the License, or (at your option) any later version. */
/*; */
/*; This program is distributed in the hope that it will be useful, */
/*; but WITHOUT ANY WARRANTY; without even the implied warranty of */
/*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/*; GNU General Public License for more details. */
/*; */
/*; You should have received a copy of the GNU General Public */
/*; License along with this program; if not, write to the Free */
/*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */
/*; MA 02139, USA. */
/*; */
/*;Correspondence about this software should be addressed as follows: */
/*; Internet email: bcotton@nrao.edu. */
/*; Postal address: William Cotton */
/*; National Radio Astronomy Observatory */
/*; 520 Edgemont Road */
/*; Charlottesville, VA 22903-2475 USA */
/*--------------------------------------------------------------------*/
#ifndef OBITRMFIT_H
#define OBITRMFIT_H
#include "Obit.h"
#include "ObitErr.h"
#include "ObitImage.h"
#include "ObitBeamShape.h"
#include "ObitThread.h"
#include "ObitInfoList.h"
#ifdef HAVE_GSL
#include <gsl/gsl_multifit_nlin.h>
#endif /* HAVE_GSL */
/*-------- Obit: Merx mollis mortibus nuper ------------------*/
/**
* \file ObitRMFit.h
*
* ObitRMFit Class for fitting rotatioin measures (RM) to Stokes Q and U image pixels
*
* This class does least squares fitting of RM and EVPA at 0 lambda^2
* Either an image cube or a set of single plane images at arbitrary
* lambda squares may be fitted.
* The result is an image cube of RM and EVPA at 0 lambda^2 as the planes.
* The function ObitRMFitEval will evaluate this fit and return an image
* with the flux densities at the desired frequencies.
*
* \section ObitRMFitaccess Creators and Destructors
* An ObitRMFit will usually be created using ObitRMFitCreate which allows
* specifying a name for the object as well as other information.
*
* A copy of a pointer to an ObitRMFit should always be made using the
* #ObitRMFitRef function which updates the reference count in the object.
* Then whenever freeing an ObitRMFit or changing a pointer, the function
* #ObitRMFitUnref will decrement the reference count and destroy the object
* when the reference count hits 0.
* There is no explicit destructor.
*/
/*--------------Class definitions-------------------------------------*/
/** ObitRMFit Class structure. */
typedef struct {
#include "ObitRMFitDef.h" /* this class definition */
} ObitRMFit;
/*----------------- Macroes ---------------------------*/
/**
* Macro to unreference (and possibly destroy) an ObitRMFit
* returns a ObitRMFit*.
* in = object to unreference
*/
#define ObitRMFitUnref(in) ObitUnref (in)
/**
* Macro to reference (update reference count) an ObitRMFit.
* returns a ObitRMFit*.
* in = object to reference
*/
#define ObitRMFitRef(in) ObitRef (in)
/**
* Macro to determine if an object is the member of this or a
* derived class.
* Returns TRUE if a member, else FALSE
* in = object to reference
*/
#define ObitRMFitIsA(in) ObitIsA (in, ObitRMFitGetClass())
/*---------------Public functions---------------------------*/
/** Public: Class initializer. */
void ObitRMFitClassInit (void);
/** Public: Default Constructor. */
ObitRMFit* newObitRMFit (gchar* name);
/** Public: Create/initialize ObitRMFit structures */
ObitRMFit* ObitRMFitCreate (gchar* name, olong nterm);
/** Typedef for definition of class pointer structure */
typedef ObitRMFit* (*ObitRMFitCreateFP) (gchar* name,
olong nterm);
/** Public: ClassInfo pointer */
gconstpointer ObitRMFitGetClass (void);
/** Public: Copy (deep) constructor. */
ObitRMFit* ObitRMFitCopy (ObitRMFit *in, ObitRMFit *out, ObitErr *err);
/** Public: Copy structure. */
void ObitRMFitClone (ObitRMFit *in, ObitRMFit *out, ObitErr *err);
/** Public: Fit spectrum to an image cube */
void ObitRMFitCube (ObitRMFit* in, ObitImage *inQImage, ObitImage *inUImage,
ObitImage *outImage, ObitErr *err);
/** Typedef for definition of class pointer structure */
typedef void(*ObitRMFitCubeFP) (ObitRMFit* in,
ObitImage *inQImage, ObitImage *inUImage,
ObitImage *outImage, ObitErr *err);
/** Public: Fit spectrum to an array of images */
void ObitRMFitImArr (ObitRMFit* in, olong nimage,
ObitImage **imQArr, ObitImage **imUArr,
ObitImage *outImage, ObitErr *err);
/** Typedef for definition of class pointer structure */
typedef void(*ObitRMFitImArrFP) (ObitRMFit* in, olong nimage,
ObitImage **imQArr, ObitImage **imUArr,
ObitImage *outImage, ObitErr *err);
/** Public: Fit single spectrum */
ofloat* ObitRMFitSingle (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2,
ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma,
ObitErr *err);
/** Typedef for definition of class pointer structure */
typedef ofloat*(*ObitRMFitSingleFP) (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2,
ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma,
ObitErr *err);
/** Public: Make fitting arg structure */
gpointer ObitRMFitMakeArg (olong nlamb2, olong nterm,
odouble refLamb2, odouble *lamb2,
ofloat **out, ObitErr *err);
/** Public: Fit single RM using arg */
void ObitRMFitSingleArg (gpointer arg,
ofloat *qflux, ofloat *qsigma,
ofloat *uflux, ofloat *usigma,
ofloat *out);
/** Public: Kill fitting arg structure */
void ObitRMFitKillArg (gpointer arg);
/*----------- ClassInfo Structure -----------------------------------*/
/**
* ClassInfo Structure.
* Contains class name, a pointer to any parent class
* (NULL if none) and function pointers.
*/
typedef struct {
#include "ObitRMFitClassDef.h"
} ObitRMFitClassInfo;
#endif /* OBITFRMFIT_H */
| {
"alphanum_fraction": 0.6097273397,
"avg_line_length": 40.3869047619,
"ext": "h",
"hexsha": "714d54462a6b48faf1e612dbbbf5f1ba7de04f0c",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z",
"max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_forks_repo_licenses": [
"Linux-OpenIB"
],
"max_forks_repo_name": "sarrvesh/Obit",
"max_forks_repo_path": "ObitSystem/Obit/include/ObitRMFit.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Linux-OpenIB"
],
"max_issues_repo_name": "sarrvesh/Obit",
"max_issues_repo_path": "ObitSystem/Obit/include/ObitRMFit.h",
"max_line_length": 97,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_stars_repo_licenses": [
"Linux-OpenIB"
],
"max_stars_repo_name": "sarrvesh/Obit",
"max_stars_repo_path": "ObitSystem/Obit/include/ObitRMFit.h",
"max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z",
"num_tokens": 1713,
"size": 6785
} |
/* multifit_nlinear/svd.c
*
* Copyright (C) 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This module handles the solution of the linear least squares
* system:
*
* [ J ] dx = - [ f ]
* [ sqrt(mu)*D ] [ 0 ]
*
* using an SVD approach. The system above is transformed to "standard form"
* via:
*
* J~ = J D^{-1}
* dx~ = D dx
*
* so that
*
* [ J~ ] dx~ = - [ f ]
* [ sqrt(mu)*I ] [ 0 ]
*
* can be solved with a standard SVD method, and then dx is recovered
* from dx~ via: dx = D^{-1} dx~
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multifit_nlinear.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
typedef struct
{
size_t n; /* number of residuals */
size_t p; /* number of parameters */
gsl_matrix *U; /* U factor of J, n-by-p */
gsl_matrix *V; /* V factor of J, p-by-p */
gsl_vector *S; /* singular values, size p */
gsl_vector *workp; /* workspace, length p */
double mu; /* LM parameter */
} svd_state_t;
static int svd_init(const void * vtrust_state, void * vstate);
static int svd_presolve(const double mu, const void * vtrust_state, void * vstate);
static int svd_solve(const gsl_vector * f, gsl_vector *x,
const void * vtrust_state, void *vstate);
static int svd_rcond(double * rcond, void * vstate);
static void *
svd_alloc (const size_t n, const size_t p)
{
svd_state_t *state;
(void)n;
state = calloc(1, sizeof(svd_state_t));
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate svd state", GSL_ENOMEM);
}
state->U = gsl_matrix_alloc(n, p);
if (state->U == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for U", GSL_ENOMEM);
}
state->V = gsl_matrix_alloc(p, p);
if (state->V == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for V", GSL_ENOMEM);
}
state->S = gsl_vector_alloc(p);
if (state->S == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for S",
GSL_ENOMEM);
}
state->workp = gsl_vector_alloc(p);
if (state->workp == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for workp",
GSL_ENOMEM);
}
state->mu = 0.0;
state->n = n;
state->p = p;
return state;
}
static void
svd_free(void *vstate)
{
svd_state_t *state = (svd_state_t *) vstate;
if (state->U)
gsl_matrix_free(state->U);
if (state->V)
gsl_matrix_free(state->V);
if (state->S)
gsl_vector_free(state->S);
if (state->workp)
gsl_vector_free(state->workp);
free(state);
}
/* compute svd of J */
static int
svd_init(const void * vtrust_state, void * vstate)
{
int status;
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
svd_state_t *state = (svd_state_t *) vstate;
size_t i;
gsl_matrix_set_zero(state->U);
/* compute U = J D^{-1} */
for (i = 0; i < state->p; ++i)
{
gsl_vector_const_view Ji = gsl_matrix_const_column(trust_state->J, i);
gsl_vector_view ui = gsl_matrix_column(state->U, i);
double di = gsl_vector_get(trust_state->diag, i);
gsl_blas_daxpy(1.0 / di, &Ji.vector, &ui.vector);
}
status = gsl_linalg_SV_decomp(state->U, state->V, state->S, state->workp);
return status;
}
static int
svd_presolve(const double mu, const void * vtrust_state, void * vstate)
{
svd_state_t *state = (svd_state_t *) vstate;
state->mu = mu;
(void)vtrust_state;
return GSL_SUCCESS;
}
static int
svd_solve(const gsl_vector * f, gsl_vector *x,
const void * vtrust_state, void *vstate)
{
int status = GSL_SUCCESS;
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
svd_state_t *state = (svd_state_t *) vstate;
const size_t p = state->p;
const double tol = GSL_DBL_EPSILON;
const double s0 = gsl_vector_get(state->S, 0);
size_t j;
/* compute workp = - U^T f */
gsl_blas_dgemv(CblasTrans, -1.0, state->U, f, 0.0, state->workp);
/*
* compute:
*
* workp = sum_i s_i / (s_i^2 + mu) (-u_i^T f)
*/
if (state->mu == 0.0)
{
/*
* compute Gauss-Newton direction by solving
* J x = -f
*/
for (j = 0; j < p; ++j)
{
double sj = gsl_vector_get(state->S, j);
double *ptr = gsl_vector_ptr(state->workp, j);
double alpha;
if (sj <= tol * s0)
alpha = 0.0;
else
alpha = 1.0 / sj;
*ptr *= alpha;
}
}
else
{
/*
* solve:
*
* [ J D^{-1} ] (D x) = -[ f ]
* [ sqrt(mu) I ] [ 0 ]
*
* using SVD factorization of J D^{-1}
*/
for (j = 0; j < p; ++j)
{
double sj = gsl_vector_get(state->S, j);
double *ptr = gsl_vector_ptr(state->workp, j);
*ptr *= sj / (sj*sj + state->mu);
}
}
/* compute: x = V * workp */
gsl_blas_dgemv(CblasNoTrans, 1.0, state->V, state->workp, 0.0, x);
/* compute D^{-1} x */
gsl_vector_div(x, trust_state->diag);
return status;
}
static int
svd_rcond(double * rcond, void * vstate)
{
int status = GSL_SUCCESS;
svd_state_t *state = (svd_state_t *) vstate;
double smax = gsl_vector_get(state->S, 0);
double smin = gsl_vector_get(state->S, state->p - 1);
*rcond = smin / smax;
return status;
}
static const gsl_multifit_nlinear_solver svd_type =
{
"svd",
svd_alloc,
svd_init,
svd_presolve,
svd_solve,
svd_rcond,
svd_free
};
const gsl_multifit_nlinear_solver *gsl_multifit_nlinear_solver_svd = &svd_type;
| {
"alphanum_fraction": 0.607208589,
"avg_line_length": 24.1481481481,
"ext": "c",
"hexsha": "6c2131bb505437b51e9366e3a329354570f4a8bc",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/svd.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/svd.c",
"max_line_length": 83,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multifit_nlinear/svd.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": 1946,
"size": 6520
} |
#pragma once
#include "Cesium3DTilesReader/Library.h"
#include <Cesium3DTiles/Tileset.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 tileset with
* {@link TilesetReader::readTileset}.
*/
struct CESIUM3DTILESREADER_API TilesetReaderResult {
/**
* @brief The read tileset, or std::nullopt if the tileset could not be read.
*/
std::optional<Cesium3DTiles::Tileset> tileset;
/**
* @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 Options for how to read a tileset.
*/
struct CESIUM3DTILESREADER_API ReadTilesetOptions {};
/**
* @brief Reads tilesets.
*/
class CESIUM3DTILESREADER_API TilesetReader {
public:
/**
* @brief Constructs a new instance.
*/
TilesetReader();
/**
* @brief Gets the context used to control how extensions are loaded from a
* tileset.
*/
CesiumJsonReader::ExtensionReaderContext& getExtensions();
/**
* @brief Gets the context used to control how extensions are loaded from a
* tileset.
*/
const CesiumJsonReader::ExtensionReaderContext& getExtensions() const;
/**
* @brief Reads a tileset.
*
* @param data The buffer from which to read the tileset.
* @param options Options for how to read the tileset.
* @return The result of reading the tileset.
*/
TilesetReaderResult readTileset(
const gsl::span<const std::byte>& data,
const ReadTilesetOptions& options = ReadTilesetOptions()) const;
private:
CesiumJsonReader::ExtensionReaderContext _context;
};
} // namespace Cesium3DTilesReader
| {
"alphanum_fraction": 0.7077483099,
"avg_line_length": 23.1686746988,
"ext": "h",
"hexsha": "967fb3b36ddc2f900c3361f4396b2ce781bc4daa",
"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": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "137734949/cesium-native",
"max_forks_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/TilesetReader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922",
"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": "137734949/cesium-native",
"max_issues_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/TilesetReader.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7fbccc0ff302f3645dc5829c3a2f3a5bdba83922",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "137734949/cesium-native",
"max_stars_repo_path": "Cesium3DTilesReader/include/Cesium3DTilesReader/TilesetReader.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 494,
"size": 1923
} |
#ifndef __TEST_UTILS_H__
#define __TEST_UTILS_H__
#define THEN_WHEN(x)
#define THEN_CHECK(x)
#include <initializer_list>
#include <memory>
#include <string>
#include <vector>
#include <gsl/gsl>
#include <gsl/string_span>
#include "base-utils/yaml.h"
#include "config/path.h"
#include "config/pattern.h"
#include "plugins/pluginUtils.h"
#include "executorStub.h"
namespace execHelper {
namespace config {
class SettingsNode;
} // namespace config
namespace test {
namespace baseUtils {
class ConfigFileWriter;
} // namespace baseUtils
} // namespace test
} // namespace execHelper
namespace std {
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& stream) {
for(const auto& element : stream) {
os << element << ", ";
}
return os;
}
template <typename T, typename U>
std::ostream& operator<<(std::ostream& os, const std::pair<T, U>& stream) {
os << stream.first << ": " << stream.second;
return os;
}
} // namespace std
namespace execHelper {
namespace test {
namespace utils {
using Patterns = std::vector<config::Pattern>;
using Arguments = std::vector<std::string>;
struct MainVariables {
int argc;
std::unique_ptr<char*[]> argv;
explicit MainVariables(const Arguments& arguments);
};
template <typename T> void appendVectors(T& appendTo, const T& appendFrom) {
appendTo.insert(std::end(appendTo), std::begin(appendFrom),
std::end(appendFrom));
}
baseUtils::YamlWriter toYaml(const config::SettingsNode& settings,
const config::Patterns& patterns) noexcept;
void writeSettingsFile(
gsl::not_null<baseUtils::ConfigFileWriter*> configFileWriter,
const config::SettingsNode& settings,
const config::Patterns& patterns) noexcept;
std::string convertToConfig(const Patterns& patterns) noexcept;
std::string
convertToConfig(const config::SettingsNode& rootSettings,
const std::string& prepend = std::string()) noexcept;
std::string
convertToConfig(const config::SettingsNode& settings, const Patterns& patterns,
const std::string& prepend = std::string()) noexcept;
std::string convertToConfig(std::string key, std::string value,
const std::string& prepend = std::string());
std::string convertToConfig(const std::string& key,
const std::initializer_list<std::string>& values,
const std::string& prepend = std::string());
std::string convertToConfig(const std::string& key,
const std::vector<std::string>& values,
const std::string& prepend = std::string());
std::string
convertToConfig(const std::initializer_list<std::string>& keys,
const std::string& value,
const std::string& prepend = std::string()) noexcept;
std::string
convertToConfig(const std::initializer_list<std::string>& keys,
const std::initializer_list<std::string>& values,
const std::string& prepend = std::string()) noexcept;
std::string
convertToConfig(const std::initializer_list<std::string>& keys,
const std::vector<std::string>& values,
const std::string& prepend = std::string()) noexcept;
std::string
convertToConfig(const std::vector<std::string>& keys,
const std::initializer_list<std::string>& values,
const std::string& prepend = std::string()) noexcept;
std::string
convertToConfig(const std::vector<std::string>& keys,
const std::vector<std::string>& values,
const std::string& prepend = std::string()) noexcept;
std::string basename(const std::string& file);
config::PatternCombinations createPatternCombination(
const std::initializer_list<config::PatternKey>& keys,
const std::initializer_list<config::PatternValue>& values) noexcept;
config::PatternCombinations
createPatternCombination(const config::PatternKeys& keys,
const config::PatternValues& values) noexcept;
plugins::PatternPermutator
makePatternPermutator(const config::Patterns& patterns) noexcept;
core::test::ExecutorStub::TaskQueue
getExpectedTasks(const core::Task& task,
const config::Patterns patterns) noexcept;
core::test::ExecutorStub::TaskQueue
getExpectedTasks(const core::test::ExecutorStub::TaskQueue& tasks,
const config::Patterns patterns) noexcept;
std::string toString(const config::SettingsNode& settings,
unsigned int nbOfTabs = 0) noexcept;
std::string inheritWorkingDirKey() noexcept;
Patterns getPredefinedPatterns() noexcept;
} // namespace utils
} // namespace test
} // namespace execHelper
#endif /* __TEST_UTILS_H__ */
| {
"alphanum_fraction": 0.6790356394,
"avg_line_length": 34.3165467626,
"ext": "h",
"hexsha": "ef5f96a411e4563b2b675c0e2541a9416b0922e8",
"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": "test/utils/include/utils/utils.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": "test/utils/include/utils/utils.h",
"max_line_length": 79,
"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": "test/utils/include/utils/utils.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": 1032,
"size": 4770
} |
/*
* Copyright 2016 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memcached/dockey.h>
#include <gsl/gsl>
#include <limits>
#include <memory>
#include <string>
#include <type_traits>
#include "ep_types.h"
class SerialisedDocKey;
/**
* StoredDocKey is a container for key data
*
* Internally an n byte key is stored in a n + sizeof(CollectionID) std::string.
* a) We zero terminate so that data() is safe for printing as a c-string.
* b) We store the CollectionID in byte 0:3. This is because StoredDocKey
* typically ends up being written to disk and the CollectionID forms part
* of the on-disk key. Accounting and for for the CollectionID means storage
* components don't have to create a new buffer into which they can layout
* CollectionID and key data.
*/
class StoredDocKey : public DocKeyInterface<StoredDocKey> {
public:
/**
* Construct empty - required for some std containers
*/
StoredDocKey() : keydata() {
}
/**
* Create a StoredDocKey from a DocKey
* @param key DocKey that is to be copied-in
*/
StoredDocKey(const DocKey& key) {
if (key.getEncoding() == DocKeyEncodesCollectionId::Yes) {
keydata.resize(key.size());
std::copy(key.data(), key.data() + key.size(), keydata.begin());
} else {
// This key is for the default collection (which has a fixed value)
keydata.resize(key.size() + 1);
keydata[0] = DefaultCollectionLeb128Encoded;
std::copy(key.data(), key.data() + key.size(), keydata.begin() + 1);
}
}
/**
* Create a StoredDocKey from a std::string (test code uses this)
* @param key std::string to be copied-in
* @param cid the CollectionID that the key applies to (and will be encoded
* into the stored data)
*/
StoredDocKey(const std::string& key, CollectionID cid);
const uint8_t* data() const {
return reinterpret_cast<const uint8_t*>(keydata.data());
}
size_t size() const {
return keydata.size();
}
DocNamespace getDocNamespace() const {
return getCollectionID();
}
CollectionID getCollectionID() const;
DocKeyEncodesCollectionId getEncoding() const {
return DocKeyEncodesCollectionId::Yes;
}
/**
* @return a DocKey that views this StoredDocKey but without any
* collection-ID prefix.
*/
DocKey makeDocKeyWithoutCollectionID() const;
/**
* Intended for debug use only
* @returns cid:key
*/
std::string to_string() const;
/**
* For tests only
* @returns the 'key' part of the StoredDocKey
*/
const char* c_str() const;
int compare(const StoredDocKey& rhs) const {
return keydata.compare(rhs.keydata);
}
bool operator==(const StoredDocKey& rhs) const {
return keydata == rhs.keydata;
}
bool operator!=(const StoredDocKey& rhs) const {
return !(*this == rhs);
}
bool operator<(const StoredDocKey& rhs) const {
return keydata < rhs.keydata;
}
operator DocKey() const {
return {keydata, DocKeyEncodesCollectionId::Yes};
}
protected:
std::string keydata;
};
std::ostream& operator<<(std::ostream& os, const StoredDocKey& key);
static_assert(sizeof(CollectionID) == sizeof(uint32_t),
"StoredDocKey: CollectionID has changed size");
/**
* A hash function for StoredDocKey so they can be used in std::map and friends.
*/
namespace std {
template <>
struct hash<StoredDocKey> {
std::size_t operator()(const StoredDocKey& key) const {
return key.hash();
}
};
}
class MutationLogEntryV2;
class StoredValue;
/**
* SerialisedDocKey maintains the key data in an allocation that is not owned by
* the class. The class is essentially immutable, providing a "view" onto the
* larger block.
*
* For example where a StoredDocKey needs to exist as part of a bigger block of
* data, SerialisedDocKey is the class to use.
*
* A limited number of classes are friends and only those classes can construct
* a SerialisedDocKey.
*/
class SerialisedDocKey : public DocKeyInterface<SerialisedDocKey> {
public:
/**
* The copy constructor is deleted due to the bytes living outside of the
* object.
*/
SerialisedDocKey(const SerialisedDocKey& obj) = delete;
const uint8_t* data() const {
return bytes;
}
size_t size() const {
return length;
}
DocNamespace getDocNamespace() const {
return getCollectionID();
}
CollectionID getCollectionID() const;
DocKeyEncodesCollectionId getEncoding() const {
return DocKeyEncodesCollectionId::Yes;
}
bool operator==(const DocKey& rhs) const;
/**
* Return how many bytes are (or need to be) allocated to this object
*/
size_t getObjectSize() const {
return getObjectSize(length);
}
/**
* Return how many bytes are needed to store the DocKey
* @param key a DocKey that needs to be stored in a SerialisedDocKey
*/
static size_t getObjectSize(const DocKey key) {
return getObjectSize(key.size());
}
/**
* Create a SerialisedDocKey and return a unique_ptr to the object.
* Note that the allocation is bigger than sizeof(SerialisedDocKey)
* @param key a DocKey to be stored as a SerialisedDocKey
*/
struct SerialisedDocKeyDelete {
void operator()(SerialisedDocKey* p) {
p->~SerialisedDocKey();
delete[] reinterpret_cast<uint8_t*>(p);
}
};
operator DocKey() const {
return {bytes, length, DocKeyEncodesCollectionId::Yes};
}
/**
* make a SerialisedDocKey and return a unique_ptr to it - this is used
* in test code only.
*/
static std::unique_ptr<SerialisedDocKey, SerialisedDocKeyDelete> make(
const StoredDocKey& key) {
std::unique_ptr<SerialisedDocKey, SerialisedDocKeyDelete> rval(
reinterpret_cast<SerialisedDocKey*>(
new uint8_t[getObjectSize(key)]));
new (rval.get()) SerialisedDocKey(key);
return rval;
}
protected:
/**
* These following classes are "white-listed". They know how to allocate
* and construct this object so are allowed access to the constructor.
*/
friend class MutationLogEntryV2;
friend class MutationLogEntryV3;
friend class StoredValue;
SerialisedDocKey() : length(0), bytes() {
}
/**
* Create a SerialisedDocKey from a DocKey. Protected constructor as
* this must be used by friends who know how to pre-allocate the object
* storage
* @param key a DocKey to be copied in
*/
SerialisedDocKey(const DocKey& key)
: length(gsl::narrow_cast<uint8_t>(key.size())) {
if (key.getEncoding() == DocKeyEncodesCollectionId::Yes) {
std::copy(key.data(), key.data() + key.size(), bytes);
} else {
// This key is for the default collection
bytes[0] = DefaultCollectionLeb128Encoded;
std::copy(key.data(), key.data() + key.size(), bytes + 1);
length++;
}
}
/**
* Create a SerialisedDocKey from a byte_buffer that has no collection data
* and requires the caller to state the collection-ID
* This is used by MutationLogEntryV1/V2 to V3 upgrades
*/
SerialisedDocKey(cb::const_byte_buffer key, CollectionID cid);
/**
* Create a SerialisedDocKey from a byte_buffer that has collection data
*/
SerialisedDocKey(cb::const_byte_buffer key)
: length(gsl::narrow_cast<uint8_t>(key.size())) {
std::copy(key.begin(), key.end(), bytes);
}
/**
* Returns the size in bytes of this object - fixed size plus the variable
* length for the bytes making up the key.
*/
static size_t getObjectSize(size_t len) {
return sizeof(SerialisedDocKey) +
(len - sizeof(SerialisedDocKey().bytes));
}
uint8_t length{0};
uint8_t bytes[1];
};
std::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key);
static_assert(std::is_standard_layout<SerialisedDocKey>::value,
"SeralisedDocKey: must satisfy is_standard_layout");
| {
"alphanum_fraction": 0.6472044099,
"avg_line_length": 29.8288590604,
"ext": "h",
"hexsha": "fa3590e1155abee6f28ca58c202f9bedb30788fb",
"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": "24d4546220f3181678d7eadedc68b4ea088d3538",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "t3rm1n4l/kv_engine",
"max_forks_repo_path": "engines/ep/src/storeddockey.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538",
"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": "t3rm1n4l/kv_engine",
"max_issues_repo_path": "engines/ep/src/storeddockey.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "t3rm1n4l/kv_engine",
"max_stars_repo_path": "engines/ep/src/storeddockey.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2140,
"size": 8889
} |
/* $Id$ */
/*
* Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#ifdef __linux__
#include <bsd/stdlib.h> /* arc4random() */
#endif
#include <string.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_histogram.h>
#include <kplot.h>
#include "extern.h"
enum kmltype {
KML_INIT = 0,
KML_KML,
KML_DOCUMENT,
KML_FOLDER,
KML_PLACEMARK,
KML_POINT,
KML_COORDINATES,
KML_DESCRIPTION,
KML__MAX
};
enum kmlkey {
KMLKEY_MEAN,
KMLKEY_MEAN_PERCENT,
KMLKEY_STDDEV,
KMLKEY_POPULATION,
KMLKEY__MAX
};
struct kmlsave {
FILE *f;
struct sim *cursim;
size_t curisland;
gchar *buf;
gsize bufsz;
gsize bufmax;
int buffering;
};
struct kmlparse {
enum kmltype elem; /* current element */
struct kmlplace *cur; /* currently-parsed kmlplace */
gchar *buf; /* current parse text buffer */
gsize bufsz; /* size in parse buffer */
gsize bufmax; /* maximum sized buffer */
gchar *altbuf;
gsize altbufsz;
gsize altbufmax;
GList *places; /* parsed places */
gchar *ign; /* element we're currently ignoring */
size_t ignstack; /* stack of "ign" while ignoring */
#define KML_STACKSZ 128
enum kmltype stack[128];
size_t stackpos;
};
static const char *const kmlkeys[KMLKEY__MAX] = {
"mean", /* KMLKEY_MEAN */
"meanpct", /* KMLKEY_MEAN_PERCENT */
"stddev", /* KMLKEY_STDDEV */
"population", /* KMLKEY_POPULATION */
};
static const char *const kmltypes[KML__MAX] = {
NULL, /* KML_INIT */
"kml", /* KML_KML */
"Document", /* KML_DOCUMENT */
"Folder", /* KML_FOLDER */
"Placemark", /* KML_PLACEMARK */
"Point", /* KML_POINT */
"coordinates", /* KML_COORDINATES */
"description", /* KML_DESCRIPTION */
};
static const double DEG_TO_RAD = 0.017453292519943295769236907684886;
static const double EARTH_RADIUS_IN_METERS = 6372797.560856;
static double
kml_dist(const struct kmlplace *from, const struct kmlplace *to)
{
double latitudeArc, longitudeArc,
latitudeH, lontitudeH, tmp;
latitudeArc = (from->lat - to->lat) * DEG_TO_RAD;
longitudeArc = (from->lng - to->lng) * DEG_TO_RAD;
latitudeH = sin(latitudeArc * 0.5);
latitudeH *= latitudeH;
lontitudeH = sin(longitudeArc * 0.5);
lontitudeH *= lontitudeH;
tmp = cos(from->lat * DEG_TO_RAD) *
cos(to->lat * DEG_TO_RAD);
return(EARTH_RADIUS_IN_METERS * 2.0 *
asin(sqrt(latitudeH + tmp * lontitudeH)));
}
static void
kml_append(gchar **buf, gsize *bufsz,
gsize *bufmax, const char *text, gsize sz)
{
/* XXX: no check for overflow... */
if (*bufsz + sz + 1 > *bufmax) {
*bufmax = *bufsz + sz + 1024;
*buf = g_realloc(*buf, *bufmax);
}
memcpy(*buf + *bufsz, text, sz);
*bufsz += sz;
(*buf)[*bufsz] = '\0';
g_assert(*bufsz <= *bufmax);
}
static enum kmltype
kml_lookup(const gchar *name)
{
enum kmltype i;
for (i = 0; i < KML__MAX; i++) {
if (NULL == kmltypes[i])
continue;
if (0 == g_strcmp0(kmltypes[i], name))
break;
}
return(i);
}
static void
kmlparse_free(gpointer dat)
{
struct kmlplace *place = dat;
if (NULL == place)
return;
free(place);
}
void
kml_free(struct kml *kml)
{
if (NULL == kml)
return;
g_list_free_full(kml->kmls, kmlparse_free);
if (NULL != kml->file)
g_mapped_file_unref(kml->file);
}
/*
* Try to find the string "@@population=NN@@", which stipulates the
* population for this particular island.
* If we don't find it, just return--we'll use the default.
* If we find a bad population, raise an error.
*/
static int
kml_placemark(const gchar *buf, struct kmlplace *place)
{
const gchar *cp;
gchar *ep;
gsize keysz;
gchar nbuf[22];
keysz = strlen("@@population=");
while (NULL != (cp = strstr(buf, "@@population="))) {
buf = cp + keysz;
if (NULL == (cp = strstr(buf, "@@")))
break;
if ((gsize)(cp - buf) >= sizeof(nbuf) - 1)
return(0);
memcpy(nbuf, buf, cp - buf);
nbuf[cp - buf] = '\0';
place->pop = g_ascii_strtoull(buf, &ep, 10);
if (ERANGE == errno || EINVAL == errno || ep == buf)
return(0);
break;
}
return(1);
}
static void
kml_elem_end(GMarkupParseContext *ctx,
const gchar *name, gpointer dat, GError **er)
{
struct kmlparse *p = dat;
enum kmltype t;
gchar **set;
if (NULL != p->ign) {
g_assert(p->ignstack > 0);
if (0 == g_strcmp0(p->ign, name))
p->ignstack--;
if (p->ignstack > 0)
return;
g_free(p->ign);
p->ign = NULL;
return;
}
t = kml_lookup(name);
g_assert(p->stackpos > 0);
g_assert(t == p->stack[p->stackpos - 1]);
p->stackpos--;
switch (p->stack[p->stackpos]) {
case (KML_PLACEMARK):
/*
* if we're ending a Placemark, first check whether
* we've listed a population somewhere in any of the
* nested text segments.
* Also make sure that we have some coordinates (the
* default value was 360 for both, which of course isn't
* a valid coordinate).
*/
g_assert(NULL != p->cur);
if ( ! kml_placemark(p->altbuf, p->cur)) {
*er = g_error_new_literal
(G_MARKUP_ERROR,
G_MARKUP_ERROR_INVALID_CONTENT,
"Cannot parse population");
break;
} else if (p->cur->lat > 180 || p->cur->lng > 180) {
*er = g_error_new_literal
(G_MARKUP_ERROR,
G_MARKUP_ERROR_INVALID_CONTENT,
"No coordinates for placemark");
break;
}
p->places = g_list_append(p->places, p->cur);
p->cur = NULL;
break;
case (KML_COORDINATES):
/*
* Parse coordinates from the mix.
* Coordinates are longitude,latitude,altitude.
* Parse quickly and just make sure they're valid.
*/
set = g_strsplit(p->buf, ",", 3);
p->cur->lng = g_ascii_strtod(set[0], NULL);
if (ERANGE == errno)
*er = g_error_new_literal
(G_MARKUP_ERROR,
G_MARKUP_ERROR_INVALID_CONTENT,
"Cannot parse longitude");
else if (p->cur->lng > 180.0 || p->cur->lng < -180.0)
*er = g_error_new_literal
(G_MARKUP_ERROR,
G_MARKUP_ERROR_INVALID_CONTENT,
"Invalid longitude");
p->cur->lat = g_ascii_strtod(set[1], NULL);
if (ERANGE == errno)
*er = g_error_new_literal
(G_MARKUP_ERROR,
G_MARKUP_ERROR_INVALID_CONTENT,
"Cannot parse latitude");
else if (p->cur->lat > 90.0 || p->cur->lat < -90.0)
*er = g_error_new_literal
(G_MARKUP_ERROR,
G_MARKUP_ERROR_INVALID_CONTENT,
"Invalid latitude");
g_strfreev(set);
break;
default:
break;
}
}
static void
kml_elem_start(GMarkupParseContext *ctx,
const gchar *name, const gchar **attrn,
const gchar **attrv, gpointer dat, GError **er)
{
enum kmltype t;
struct kmlparse *p = dat;
if (NULL != p->ign) {
g_assert(p->ignstack > 0);
if (0 == g_strcmp0(p->ign, name))
p->ignstack++;
return;
}
if (KML__MAX == (t = kml_lookup(name))) {
assert(0 == p->ignstack);
p->ign = g_strdup(name);
p->ignstack = 1;
return;
}
p->stack[p->stackpos++] = t;
p->bufsz = 0;
switch (p->stack[p->stackpos - 1]) {
case (KML_PLACEMARK):
/*
* If we're starting a Placemark, initialise ourselves
* with bad coorindates and a default population.
*/
if (NULL == p->cur) {
p->cur = g_malloc0(sizeof(struct kmlplace));
p->cur->lat = p->cur->lng = 360;
p->cur->pop = 2;
p->altbufsz = 0;
break;
}
*er = g_error_new_literal
(G_MARKUP_ERROR,
G_MARKUP_ERROR_INVALID_CONTENT,
"Nested placemarks not allowed.");
break;
default:
break;
}
}
static void
kml_text(GMarkupParseContext *ctx,
const gchar *txt, gsize sz, gpointer dat, GError **er)
{
struct kmlparse *p = dat;
if (NULL != p->cur)
kml_append(&p->altbuf, &p->altbufsz,
&p->altbufmax, txt, sz);
/* No collection w/o element or while ignoring. */
if (NULL != p->ign || 0 == p->stackpos)
return;
/* Each element for which we're going to collect text. */
switch (p->stack[p->stackpos - 1]) {
case (KML_COORDINATES):
break;
default:
return;
}
kml_append(&p->buf, &p->bufsz, &p->bufmax, txt, sz);
}
static void
kml_error(GMarkupParseContext *ctx, GError *er, gpointer dat)
{
g_warning("%s", er->message);
}
struct kml *
kml_torus(size_t islands, size_t islanders)
{
struct kml *kml;
struct kmlplace *p;
size_t i;
kml = g_malloc0(sizeof(struct kml));
for (i = 0; i < islands; i++) {
p = g_malloc0(sizeof(struct kmlplace));
p->pop = islanders;
p->lng = 360 * i / (double)islands - 180.0;
p->lat = 0.0;
kml->kmls = g_list_append(kml->kmls, p);
}
return(kml);
}
struct kml *
kml_rand(size_t islands, size_t islanders)
{
struct kml *kml;
struct kmlplace *p;
size_t i;
kml = g_malloc0(sizeof(struct kml));
for (i = 0; i < islands; i++) {
p = g_malloc0(sizeof(struct kmlplace));
p->pop = islanders;
p->lng = 360 * arc4random() / (double)UINT32_MAX - 180.0;
p->lat = 180 * arc4random() / (double)UINT32_MAX - 90.0;
kml->kmls = g_list_append(kml->kmls, p);
}
return(kml);
}
struct kml *
kml_parse(const gchar *file, GError **er)
{
GMarkupParseContext *ctx;
GMarkupParser parse;
GMappedFile *f;
int rc;
struct kmlparse data;
struct kml *kml;
if (NULL != er)
*er = NULL;
memset(&parse, 0, sizeof(GMarkupParser));
memset(&data, 0, sizeof(struct kmlparse));
data.elem = KML_INIT;
parse.start_element = kml_elem_start;
parse.end_element = kml_elem_end;
parse.text = kml_text;
parse.error = kml_error;
if (NULL == (f = g_mapped_file_new(file, FALSE, er)))
return(NULL);
ctx = g_markup_parse_context_new
(&parse, 0, &data, NULL);
g_assert(NULL != ctx);
rc = g_markup_parse_context_parse
(ctx, g_mapped_file_get_contents(f),
g_mapped_file_get_length(f), er);
g_markup_parse_context_free(ctx);
g_free(data.buf);
g_free(data.altbuf);
g_free(data.ign);
kmlparse_free(data.cur);
if (0 == rc) {
g_list_free_full(data.places, kmlparse_free);
g_mapped_file_unref(f);
return(NULL);
} else if (NULL == data.places) {
g_mapped_file_unref(f);
return(NULL);
}
g_assert(NULL != data.places);
kml = g_malloc0(sizeof(struct kml));
kml->file = f;
kml->kmls = data.places;
return(kml);
}
double **
kml_migration_twonearest(GList *list, enum maptop map)
{
double **p;
double dist, min;
size_t i, j, len, minj, min2j;
struct kmlplace *pl1, *pl2;
len = (size_t)g_list_length(list);
g_assert(len > 0);
if (1 == len) {
g_debug("Request for two nearest falling "
"back to nearest");
return(kml_migration_nearest(list, map));
}
p = g_malloc0_n(len, sizeof(double *));
/*
* Special case the torus, which has a well-defined layout
* between nodes, such that the next ("right") and previous
* ("left") islands, wrapping around, get the migrants.
*/
if (MAPTOP_TORUS == map) {
for (i = 0; i < len; i++) {
p[i] = g_malloc0_n(len, sizeof(double));
if (i < len - 1)
p[i][i + 1] = 0.5;
else
p[i][0] = 0.5;
if (i > 0)
p[i][i - 1] = 0.5;
else
p[i][len - 1] = 0.5;
}
return(p);
}
for (i = 0; i < len; i++) {
pl1 = g_list_nth_data(list, i);
p[i] = g_malloc0_n(len, sizeof(double));
for (minj = j = 0, min = DBL_MAX; j < len; j++) {
if (i == j)
continue;
pl2 = g_list_nth_data(list, j);
if ((dist = kml_dist(pl1, pl2)) < min) {
min = dist;
minj = j;
}
}
p[i][minj] = 0.5;
for (min2j = j = 0, min = DBL_MAX; j < len; j++) {
if (i == j || j == minj)
continue;
pl2 = g_list_nth_data(list, j);
if ((dist = kml_dist(pl1, pl2)) < min) {
min = dist;
min2j = j;
}
}
p[i][min2j] = 0.5;
g_assert(min2j != minj);
g_assert(i != min2j);
}
return(p);
}
double **
kml_migration_nearest(GList *list, enum maptop map)
{
double **p;
double dist, min;
size_t i, j, len, minj;
struct kmlplace *pl1, *pl2;
len = (size_t)g_list_length(list);
g_assert(len > 0);
p = g_malloc0_n(len, sizeof(double *));
/*
* Special case the torus, which has a well-defined layout
* between nodes, such that the next ("right") island, wrapping
* around, gets the migrant.
*/
if (MAPTOP_TORUS == map) {
for (i = 0; i < len; i++) {
p[i] = g_malloc0_n(len, sizeof(double));
p[i][(i + 1) % len] = 1.0;
}
return(p);
}
for (i = 0; i < len; i++) {
pl1 = g_list_nth_data(list, i);
p[i] = g_malloc0_n(len, sizeof(double));
for (minj = j = 0, min = DBL_MAX; j < len; j++) {
if (i == j)
continue;
pl2 = g_list_nth_data(list, j);
if ((dist = kml_dist(pl1, pl2)) < min) {
min = dist;
minj = j;
}
}
p[i][minj] = 1.0;
}
return(p);
}
double **
kml_migration_distance(GList *list, enum maptop map)
{
double **p;
double dist, sum;
size_t i, j, len;
struct kmlplace *pl1, *pl2;
len = (size_t)g_list_length(list);
g_assert(len > 0);
p = g_malloc0_n(len, sizeof(double *));
for (i = 0; i < len; i++) {
pl1 = g_list_nth_data(list, i);
p[i] = g_malloc0_n(len, sizeof(double));
for (sum = 0.0, j = 0; j < len; j++) {
if (i == j) {
p[i][j] = 0.0;
continue;
}
pl2 = g_list_nth_data(list, j);
dist = kml_dist(pl1, pl2);
p[i][j] = 1.0 / (dist * dist);
sum += p[i][j];
}
for (j = 0; j < len; j++)
if (i != j)
p[i][j] = p[i][j] / sum;
}
return(p);
}
| {
"alphanum_fraction": 0.6065528252,
"avg_line_length": 23.5008156607,
"ext": "c",
"hexsha": "adf305b5dcacb45a315a9348aa38727ed51b654f",
"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": "0280a899564031a5a14af87d9264cd239a89851f",
"max_forks_repo_licenses": [
"0BSD"
],
"max_forks_repo_name": "kristapsdz/bmigrate",
"max_forks_repo_path": "kml.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"0BSD"
],
"max_issues_repo_name": "kristapsdz/bmigrate",
"max_issues_repo_path": "kml.c",
"max_line_length": 76,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f",
"max_stars_repo_licenses": [
"0BSD"
],
"max_stars_repo_name": "kristapsdz/bmigrate",
"max_stars_repo_path": "kml.c",
"max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z",
"num_tokens": 4589,
"size": 14406
} |
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_hyperg.h>
#include <gsl/gsl_errno.h>
void inc_gamma_error_msg(const char* fn_name, const char* reason, const char* file, int line, int gsl_errno) {
fprintf(stderr, "Error in GSL %s\n", fn_name);
fprintf(stderr, "GSL Error %i: %s.\n", gsl_errno, gsl_strerror(gsl_errno));
fprintf(stderr, "%s in %s:%i.\n", reason, file, line);
}
void gamma_inc_lower_error_handler(const char* reason, const char* file, int line, int gsl_errno) {
if (gsl_errno != GSL_EUNDRFLW) {
inc_gamma_error_msg("gamma_inc_P while computing lower incomplete gamma ratio.", reason, file, line, gsl_errno);
abort();
}
}
void gamma_inc_upper_error_handler(const char* reason, const char* file, int line, int gsl_errno) {
if (gsl_errno != GSL_EUNDRFLW) {
inc_gamma_error_msg("gamma_inc while computing upper incomplete gamma ratio.", reason, file, line, gsl_errno);
abort();
}
}
#define INC_GAMMA_NO_UNDERFLOW(fn, handler) do { \
gsl_error_handler_t* old_handler = gsl_set_error_handler(& handler ); \
fn; \
gsl_set_error_handler(old_handler); \
} while (0)
void inc_gamma_check_value(long double val, const char* fn_name) {
if (isnan(val) || !isfinite(val)) {
fprintf(stderr, "Error while computing %s.\n", fn_name);
if (isnan(val)) {
fprintf(stderr, "NaN detected. ");
} else {
fprintf(stderr, "Infinity detected. ");
}
fprintf(stderr, "This is likely the result of an overflow.\n");
abort();
}
}
/*
Computes the upper Gamma(x+y,a)/Gamma(x) for x = [1 ... x_max]
*/
void inc_gamma_upper_ratio_ary(int x_max, double y, double a, double* result) {
// x = 1 case
size_t idx = 0;
int x = 1;
long double ln_gamma_xp1 = 0;
// With fn(x) = Gamma(x+y, a)/Gamma(x)
long double fn_x;
INC_GAMMA_NO_UNDERFLOW(fn_x = gsl_sf_gamma_inc(x+y, a), gamma_inc_upper_error_handler);
result[idx] = fn_x;
for (;x < x_max;) {
ln_gamma_xp1 += logl((long double) x);
// Using the recurrence relation Gamma(s+1,a) = s Gamma(s,a) + a^s exp(-a)
// We have Gamma((x+1)+y)/Gamma(x+1) = (x+y) ( Gamma(x+y)/Gamma(x) )/x + a^(x+y) exp(-a)/Gamma(x+1)
// -> fn(x+1) = (x+y) fn(x)/x + exp((x+y) ln a - a - ln Gamma(x+1))
long double fn_xp1 = (x+y) * fn_x/x + expl((x+y)*logl(a) - a - ln_gamma_xp1);
result[idx+1] = (double)fn_xp1;
fn_x = fn_xp1;
idx += 1;
x += 1;
}
// Make use of the fact that NaNs and infinities will propagate to the last value computed.
inc_gamma_check_value(result[x_max-1], "upper incomplete gamma ratio");
}
/*
Computes the lower gamma(x+y,a)/Gamma(x) for x = [1 ... x_max]
*/
void inc_gamma_lower_ratio_ary(int x_max, double y, double a, double* result) {
// x = x_max case
size_t idx = x_max - 1;
int x = x_max;
long double ln_gamma_x = gsl_sf_lngamma(x);
// With fn(x) = gamma(x+y, a)/Gamma(x)
long double fn_x;
//INC_GAMMA_NO_UNDERFLOW(fn_x = expl((x+y)*logl(a) - a - logl(x+y) - ln_gamma_x)*gsl_sf_hyperg_1F1(1, x+y+1, a), hyperg_error_handler);
INC_GAMMA_NO_UNDERFLOW(fn_x = gsl_sf_gamma_inc_P(x+y,a) * expl(gsl_sf_lngamma(x+y) - ln_gamma_x), gamma_inc_lower_error_handler);
result[idx] = fn_x;
for (;x>1;) {
x -= 1;
idx -= 1;
ln_gamma_x -= logl((long double) x);
long double fn_xp1 = fn_x;
// We have gamma(s,a) = (gamma(s+1, a) + a^s exp(-a))/s
// So gamma(x+y,a)/Gamma(x) = ( x gamma((x+1)+y, a)/Gamma(x+1) + a^(x+y) exp(-a)/Gamma(x) ) / s
// -> fn(x) = ( x fn(x+1) + exp( (x+y) ln a - a - ln Gamma(x)! ) ) / (x+y)
fn_x = ( x*fn_xp1 + expl( (x+y)*logl(a) - a - ln_gamma_x ) ) / (x+y);
result[idx] = (double)fn_x;
}
// Make use of the fact that NaNs and infinities will propagate to the last value computed.
inc_gamma_check_value(result[0], "lower incomplete gamma ratio");
}
| {
"alphanum_fraction": 0.6602428722,
"avg_line_length": 35.4018691589,
"ext": "h",
"hexsha": "0201c106289582ebecbc11a21186ae93c1a5850d",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-02-05T01:25:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-11-23T05:06:36.000Z",
"max_forks_repo_head_hexsha": "bb21439905d07e25fcf3351b321616f3ed2fcbd3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bsafdi/NPTFit",
"max_forks_repo_path": "NPTFit/incgamma_fct.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "bb21439905d07e25fcf3351b321616f3ed2fcbd3",
"max_issues_repo_issues_event_max_datetime": "2017-06-22T02:59:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-06-22T02:59:33.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "bsafdi/NPTFit",
"max_issues_repo_path": "NPTFit/incgamma_fct.h",
"max_line_length": 136,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "bb21439905d07e25fcf3351b321616f3ed2fcbd3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bsafdi/NPTFit",
"max_stars_repo_path": "NPTFit/incgamma_fct.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-07T03:31:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-01-17T20:00:53.000Z",
"num_tokens": 1266,
"size": 3788
} |
#ifndef AMICI_SUNDIALS_MATRIX_WRAPPER_H
#define AMICI_SUNDIALS_MATRIX_WRAPPER_H
#include <sunmatrix/sunmatrix_band.h> // SUNMatrix_Band
#include <sunmatrix/sunmatrix_dense.h> // SUNMatrix_Dense
#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrix_Sparse
#include <gsl/gsl-lite.hpp>
#include <vector>
#include "amici/vector.h"
namespace amici {
/**
* @brief A RAII wrapper for SUNMatrix structs.
*
* This can create dense, sparse, or banded matrices using the respective
* constructor.
*/
class SUNMatrixWrapper {
public:
SUNMatrixWrapper() = default;
/**
* @brief Create sparse matrix. See SUNSparseMatrix in sunmatrix_sparse.h
* @param M Number of rows
* @param N Number of columns
* @param NNZ Number of nonzeros
* @param sparsetype Sparse type
*/
SUNMatrixWrapper(sunindextype M, sunindextype N, sunindextype NNZ,
int sparsetype);
/**
* @brief Create dense matrix. See SUNDenseMatrix in sunmatrix_dense.h
* @param M Number of rows
* @param N Number of columns
*/
SUNMatrixWrapper(sunindextype M, sunindextype N);
/**
* @brief Create banded matrix. See SUNBandMatrix in sunmatrix_band.h
* @param M Number of rows and columns
* @param ubw Upper bandwidth
* @param lbw Lower bandwidth
*/
SUNMatrixWrapper(sunindextype M, sunindextype ubw, sunindextype lbw);
/**
* @brief Create sparse matrix from dense or banded matrix. See
* SUNSparseFromDenseMatrix and SUNSparseFromBandMatrix in
* sunmatrix_sparse.h
* @param A Wrapper for dense matrix
* @param droptol tolerance for dropping entries
* @param sparsetype Sparse type
*/
SUNMatrixWrapper(const SUNMatrixWrapper &A, realtype droptol,
int sparsetype);
/**
* @brief Wrap existing SUNMatrix
* @param mat
*/
explicit SUNMatrixWrapper(SUNMatrix mat);
~SUNMatrixWrapper();
/**
* @brief Copy constructor
* @param other
*/
SUNMatrixWrapper(const SUNMatrixWrapper &other);
/**
* @brief Move constructor
* @param other
*/
SUNMatrixWrapper(SUNMatrixWrapper &&other);
/**
* @brief Copy assignment
* @param other
* @return
*/
SUNMatrixWrapper &operator=(const SUNMatrixWrapper &other);
/**
* @brief Move assignment
* @param other
* @return
*/
SUNMatrixWrapper &operator=(SUNMatrixWrapper &&other);
/**
* @brief Reallocate space for sparse matrix according to specified nnz
* @param nnz new number of nonzero entries
*/
void reallocate(sunindextype nnz);
/**
* @brief Reallocate space for sparse matrix to used space according to last entry in indexptrs
*/
void realloc();
/**
* @brief Get the wrapped SUNMatrix
* @return raw SunMatrix object
* @note Even though the returned matrix_ pointer is const qualified, matrix_->content will not be const.
* This is a shortcoming in the underlying C library, which we cannot address and it is not intended that
* any of those values are modified externally. If matrix_->content is manipulated,
* cpp:meth:SUNMatrixWrapper:`refresh` needs to be called.
*/
SUNMatrix get() const;
/**
* @brief Get the number of rows
* @return number of rows
*/
sunindextype rows() const;
/**
* @brief Get the number of columns
* @return number of columns
*/
sunindextype columns() const;
/**
* @brief Get the number of specified non-zero elements (sparse matrices only)
* @note value will be 0 before indexptrs are set.
* @return number of nonzero entries
*/
sunindextype num_nonzeros() const;
/**
* @brief Get the number of indexptrs that can be specified (sparse matrices only)
* @return number of indexptrs
*/
sunindextype num_indexptrs() const;
/**
* @brief Get the number of allocated data elements
* @return number of allocated entries
*/
sunindextype capacity() const;
/**
* @brief Get raw data of a sparse matrix
* @return pointer to first data entry
*/
realtype *data();
/**
* @brief Get const raw data of a sparse matrix
* @return pointer to first data entry
*/
const realtype *data() const;
/**
* @brief Get data of a sparse matrix
* @param idx data index
* @return idx-th data entry
*/
realtype get_data(sunindextype idx) const;
/**
* @brief Get data entry for a dense matrix
* @param irow row
* @param icol col
* @return A(irow,icol)
*/
realtype get_data(sunindextype irow, sunindextype icol) const;
/**
* @brief Set data entry for a sparse matrix
* @param idx data index
* @param data data for idx-th entry
*/
void set_data(sunindextype idx, realtype data);
/**
* @brief Set data entry for a dense matrix
* @param irow row
* @param icol col
* @param data data for idx-th entry
*/
void set_data(sunindextype irow, sunindextype icol, realtype data);
/**
* @brief Get the index value of a sparse matrix
* @param idx data index
* @return row (CSC) or column (CSR) for idx-th data entry
*/
sunindextype get_indexval(sunindextype idx) const;
/**
* @brief Set the index value of a sparse matrix
* @param idx data index
* @param val row (CSC) or column (CSR) for idx-th data entry
*/
void set_indexval(sunindextype idx, sunindextype val);
/**
* @brief Set the index values of a sparse matrix
* @param vals rows (CSC) or columns (CSR) for data entries
*/
void set_indexvals(const gsl::span<const sunindextype> vals);
/**
* @brief Get the index pointer of a sparse matrix
* @param ptr_idx pointer index
* @return index where the ptr_idx-th column (CSC) or row (CSR) starts
*/
sunindextype get_indexptr(sunindextype ptr_idx) const;
/**
* @brief Set the index pointer of a sparse matrix
* @param ptr_idx pointer index
* @param ptr data-index where the ptr_idx-th column (CSC) or row (CSR) starts
*/
void set_indexptr(sunindextype ptr_idx, sunindextype ptr);
/**
* @brief Set the index pointers of a sparse matrix
* @param ptrs starting data-indices where the columns (CSC) or rows (CSR) start
*/
void set_indexptrs(const gsl::span<const sunindextype> ptrs);
/**
* @brief Get the type of sparse matrix
* @return matrix type
*/
int sparsetype() const;
/**
* @brief multiply with a scalar (in-place)
* @param a scalar value to multiply matrix
*/
void scale(realtype a);
/**
* @brief N_Vector interface for multiply
* @param c output vector, may already contain values
* @param b multiplication vector
* @param alpha scalar coefficient for matrix
*/
void multiply(N_Vector c, const_N_Vector b, realtype alpha = 1.0) const;
/**
* @brief Perform matrix vector multiplication c += alpha * A*b
* @param c output vector, may already contain values
* @param b multiplication vector
* @param alpha scalar coefficient
*/
void multiply(gsl::span<realtype> c, gsl::span<const realtype> b,
const realtype alpha = 1.0) const;
/**
* @brief Perform reordered matrix vector multiplication c += A[:,cols]*b
* @param c output vector, may already contain values
* @param b multiplication vector
* @param cols int vector for column reordering
* @param transpose bool transpose A before multiplication
*/
void multiply(N_Vector c,
const_N_Vector b,
gsl::span <const int> cols,
bool transpose) const;
/**
* @brief Perform reordered matrix vector multiplication c += A[:,cols]*b
* @param c output vector, may already contain values
* @param b multiplication vector
* @param cols int vector for column reordering
* @param transpose bool transpose A before multiplication
*/
void multiply(gsl::span<realtype> c,
gsl::span<const realtype> b,
gsl::span <const int> cols,
bool transpose) const;
/**
* @brief Perform matrix matrix multiplication C = A * B for sparse A, B, C
* @param C output matrix,
* @param B multiplication matrix
* @note will overwrite existing data, indexptrs, indexvals for C, but will use preallocated space for these vars
*/
void sparse_multiply(SUNMatrixWrapper &C,
const SUNMatrixWrapper &B) const;
/**
* @brief Perform sparse matrix matrix addition C = alpha * A + beta * B
* @param A addition matrix
* @param alpha scalar A
* @param B addition matrix
* @param beta scalar B
* @note will overwrite existing data, indexptrs, indexvals for C, but will use preallocated space for these vars
*/
void sparse_add(const SUNMatrixWrapper &A, realtype alpha,
const SUNMatrixWrapper &B, realtype beta);
/**
* @brief Perform matrix-matrix addition A = sum(mats(0)...mats(len(mats)))
* @param mats vector of sparse matrices
* @note will overwrite existing data, indexptrs, indexvals for A, but will use preallocated space for these vars
*/
void sparse_sum(const std::vector<SUNMatrixWrapper> &mats);
/**
* @brief Compute x = x + beta * A(:,k), where x is a dense vector and A(:,k) is sparse, and update
* the sparsity pattern for C(:,j) if applicable
*
* This function currently has two purposes:
* - perform parts of sparse matrix-matrix multiplication C(:,j)=A(:,k)*B(k,j)
* enabled by passing beta=B(k,j), x=C(:,j), C=C, w=sparsity of C(:,j) from B(k,0...j-1), nnz=nnz(C(:,0...j-1)
* - add the k-th column of the sparse matrix A multiplied by beta to the dense vector x.
* enabled by passing beta=*, x=x, C=nullptr, w=nullptr, nnz=*
*
* @param k column index
* @param beta scaling factor
* @param w index workspace, (w[i]<mark) indicates non-zeroness of C(i,j) (dimension: m),
* if this is a nullptr, sparsity pattern of C will not be updated (if applicable).
* @param x dense output vector (dimension: m)
* @param mark marker for w to indicate nonzero pattern
* @param C sparse output matrix, if this is a nullptr, sparsity pattern of C will not be updated
* @param nnz number of nonzeros that were already written to C
* @return updated number of nonzeros in C
*/
sunindextype scatter(const sunindextype k, const realtype beta,
sunindextype *w, gsl::span<realtype> x,
const sunindextype mark,
SUNMatrixWrapper *C, sunindextype nnz) const;
/**
* @brief Compute transpose A' of sparse matrix A and writes it to the matrix C = alpha * A'
*
* @param C output matrix (sparse or dense)
* @param alpha scalar multiplier
* @param blocksize blocksize for transposition. For full matrix transpose set to ncols/nrows
*/
void transpose(SUNMatrixWrapper &C, const realtype alpha,
sunindextype blocksize) const;
/**
* @brief Writes a sparse matrix A to a dense matrix D.
*
* @param D dense output matrix
*/
void to_dense(SUNMatrixWrapper &D) const;
/**
* @brief Writes the diagonal of sparse matrix A to a dense vector v.
*
* @param v dense outut vector
*/
void to_diag(N_Vector v) const;
/**
* @brief Set to 0.0, for sparse matrices also resets indexptr/indexvals
*/
void zero();
/**
* @brief Get matrix id
* @return SUNMatrix_ID
*/
SUNMatrix_ID matrix_id() const {return id_;};
/**
* @brief Update internal cache, needs to be called after external manipulation of matrix_->content
*/
void refresh();
private:
/**
* @brief SUNMatrix to which all methods are applied
*/
SUNMatrix matrix_ {nullptr};
/**
* @brief cache for SUNMatrixGetId(matrix_)
*/
SUNMatrix_ID id_ {SUNMATRIX_CUSTOM};
/**
* @brief cache for SUNMatrixGetId(matrix_)
*/
int sparsetype_ {CSC_MAT};
/**
* @brief cache for SM_INDEXPTRS_S(matrix_)[SM_NP_S(matrix_)]
*/
sunindextype num_nonzeros_ {0};
/**
* @brief cache for SM_NNZ_S(matrix_)
*/
sunindextype capacity_ {0};
/**
* @brief cache for SM_DATA_S(matrix_)
*/
realtype *data_ {nullptr};
/**
* @brief cache for SM_INDEXPTRS_S(matrix_)
*/
sunindextype *indexptrs_ {nullptr};
/**
* @brief cache for SM_INDEXVALS_S(matrix_)
*/
sunindextype *indexvals_ {nullptr};
/**
* @brief cache for SM_ROWS_X(matrix_)
*/
sunindextype num_rows_ {0};
/**
* @brief cache for SM_COLUMS_X(matrix_)
*/
sunindextype num_columns_ {0};
/**
* @brief cache for SM_NP_S(matrix_)
*/
sunindextype num_indexptrs_ {0};
/**
* @brief call update_ptrs & update_size
*/
void finish_init();
/**
* @brief update data_, indexptrs_, indexvals_ if applicable
*/
void update_ptrs();
/**
* @brief update num_rows_, num_columns_, num_indexptrs if applicable
*/
void update_size();
/**
* @brief indicator whether this wrapper allocated matrix_ and is responsible for deallocation
*/
bool ownmat = true;
};
} // namespace amici
namespace gsl {
/**
* @brief Create span from SUNMatrix
* @param m SUNMatrix
* @return Created span
*/
inline span<realtype> make_span(SUNMatrix m)
{
switch (SUNMatGetID(m)) {
case SUNMATRIX_DENSE:
return span<realtype>(SM_DATA_D(m), SM_LDATA_D(m));
case SUNMATRIX_SPARSE:
return span<realtype>(SM_DATA_S(m), SM_NNZ_S(m));
default:
throw amici::AmiException("Unimplemented SUNMatrix type for make_span");
}
}
} // namespace gsl
#endif // AMICI_SUNDIALS_MATRIX_WRAPPER_H
| {
"alphanum_fraction": 0.6336696536,
"avg_line_length": 30.3490364026,
"ext": "h",
"hexsha": "2ccc7622ab0daf286d01e33268a228bf01751632",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-09-20T14:53:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-20T14:53:43.000Z",
"max_forks_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "PaulJonasJost/AMICI",
"max_forks_repo_path": "include/amici/sundials_matrix_wrapper.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "PaulJonasJost/AMICI",
"max_issues_repo_path": "include/amici/sundials_matrix_wrapper.h",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "PaulJonasJost/AMICI",
"max_stars_repo_path": "include/amici/sundials_matrix_wrapper.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3611,
"size": 14173
} |
#include <stdio.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_math.h>
#include "timer.c"
#include "timer.h"
#include "integrand.h"
double dipole_approx (double r);
double gaussian (double *x, int dim);
int main (void)
{
double res, err;
size_t dim = 6;
double x1[] = { 0., 0., 0., 0., 0., 0., };
double xu[] = { 1., 1., 1., 1., 1., 1., };
double distmin = 1.001;
double distmax = 4.;
double dist;
int numpoints = 20;
double nt = (distmax - distmin) / (numpoints - 1);
double vegas[20], dipole[20], distance[20];
//vegas integration
gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2);
unsigned long seed = 1UL;
gsl_rng_set (r, seed);
size_t calls = 1000000;
dist = distmin;
gsl_monte_function G = { &g, dim, &dist };
gsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim);
gsl_monte_vegas_init (sv);
timer_start ();
for (int i = 0; i < numpoints; i++){
gsl_monte_vegas_integrate (&G, x1, xu, dim, calls / 5, r, sv, &res,
&err);
do
{
gsl_monte_vegas_integrate (&G, x1, xu, dim, calls, r, sv, &res,
&err);
fflush(stdout);
}
while (fabs (gsl_monte_vegas_chisq (sv) - 1.0) > 0.2);
dist += nt;
vegas[i] = res;
distance[i] = dist;
dipole[i] = -2. / pow (dist, 3.);
}
timer_stop();
//double vegastime = timer_stop();
gsl_monte_vegas_free (sv);
//Monte carlo integration
double sum;
double x[6];
long i, j, nn;
nn = 1000000;
timer_start ();
double monte[20];
dist = distmin;
for (j = 0; j < numpoints; j++)
{
sum = 0.;
for (i = 0; i < nn; i++)
{
for (int k = 0; k < (int) dim; k++)
{
x[k] = gsl_rng_uniform (r);
}
sum += g (x, dim, &dist);
}
res = sum/nn;
fflush(stdout);
dist += nt;
monte[j] = res;
}
timer_stop ();
//double montetime = timer_stop();
//printf("Vegas time: %f Monte time: %f", vegastime, montetime);
gsl_rng_free(r);
double monteerr = 0.0;
for (int jj = 0; jj < numpoints; jj++)
{
monteerr += fabs(monte[jj] - vegas[jj]);
}
//prints the output of each integration
printf("# Dist Vegas Monte Dipolapprox\n");
for( int l = 0; l < numpoints; l++)
{
double dd = distance[l];
double vv = fabs(vegas[l]);
double mm = fabs(monte[l]);
double di = fabs(dipole[l]);
printf(" %.6f %.6f %.6f %.6f\n", dd, vv, mm, di);
}
return 0;
}
| {
"alphanum_fraction": 0.5120593692,
"avg_line_length": 21.2204724409,
"ext": "c",
"hexsha": "203653a9221b232312e86eb8e6d70e951e3c8efe",
"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": "6f63f26819591cd46b2055a452ee0bf176d74fbe",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hrwhitelock/fin2",
"max_forks_repo_path": "main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6f63f26819591cd46b2055a452ee0bf176d74fbe",
"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": "hrwhitelock/fin2",
"max_issues_repo_path": "main.c",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6f63f26819591cd46b2055a452ee0bf176d74fbe",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hrwhitelock/fin2",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 871,
"size": 2695
} |
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
// reserved. See files LICENSE and NOTICE for details.
//
// This file is part of CEED, a collection of benchmarks, miniapps, software
// libraries and APIs for efficient high-order finite element and spectral
// element discretizations for exascale applications. For more information and
// source code availability see http://github.com/ceed.
//
// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
// a collaborative effort of two U.S. Department of Energy organizations (Office
// of Science and the National Nuclear Security Administration) responsible for
// the planning and preparation of a capable exascale ecosystem, including
// software, applications, hardware, advanced system engineering and early
// testbed platforms, in support of the nation's exascale computing imperative.
#ifndef setuparea_h
#define setuparea_h
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscfe.h>
#include <stdbool.h>
#include <string.h>
#include "qfunctions/area/areacube.h"
#include "qfunctions/area/areasphere.h"
#if PETSC_VERSION_LT(3,14,0)
# define DMPlexGetClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexGetClosureIndices(a,b,c,d,f,g,i)
# define DMPlexRestoreClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexRestoreClosureIndices(a,b,c,d,f,g,i)
#endif
#if PETSC_VERSION_LT(3,14,0)
# define DMPlexCreateSphereMesh(a,b,c,d,e) DMPlexCreateSphereMesh(a,b,c,e)
#endif
// -----------------------------------------------------------------------------
// PETSc Operator Structs
// -----------------------------------------------------------------------------
// Data for PETSc
typedef struct User_ *User;
struct User_ {
MPI_Comm comm;
DM dm;
Vec Xloc, Yloc, diag;
CeedVector xceed, yceed;
CeedOperator op;
Ceed ceed;
};
// -----------------------------------------------------------------------------
// libCEED Data Struct
// -----------------------------------------------------------------------------
// libCEED data struct for level
typedef struct CeedData_ *CeedData;
struct CeedData_ {
Ceed ceed;
CeedBasis basisx, basisu;
CeedElemRestriction Erestrictx, Erestrictu, Erestrictqdi;
CeedQFunction qf_apply;
CeedOperator op_apply, op_restrict, op_interp;
CeedVector qdata, uceed, vceed;
};
// -----------------------------------------------------------------------------
// Problem Option Data
// -----------------------------------------------------------------------------
// Problem options
typedef enum {
CUBE = 0, SPHERE = 1
} problemType;
static const char *const problemTypes[] = {"cube", "sphere",
"problemType", "AREA", NULL
};
// Problem specific data
typedef struct {
CeedInt ncompu, ncompx, qdatasize, qextra, topodim;
CeedQFunctionUser setupgeo, apply;
const char *setupgeofname, *applyfname;
CeedEvalMode inmode, outmode;
CeedQuadMode qmode;
} problemData;
static problemData problemOptions[6] = {
[CUBE] = {
.ncompx = 3,
.ncompu = 1,
.topodim = 2,
.qdatasize = 1,
.qextra = 1,
.setupgeo = SetupMassGeoCube,
.apply = Mass,
.setupgeofname = SetupMassGeoCube_loc,
.applyfname = Mass_loc,
.inmode = CEED_EVAL_INTERP,
.outmode = CEED_EVAL_INTERP,
.qmode = CEED_GAUSS
},
[SPHERE] = {
.ncompx = 3,
.ncompu = 1,
.topodim = 2,
.qdatasize = 1,
.qextra = 1,
.setupgeo = SetupMassGeoSphere,
.apply = Mass,
.setupgeofname = SetupMassGeoSphere_loc,
.applyfname = Mass_loc,
.inmode = CEED_EVAL_INTERP,
.outmode = CEED_EVAL_INTERP,
.qmode = CEED_GAUSS
}
};
// -----------------------------------------------------------------------------
// PETSc sphere auxiliary functions
// -----------------------------------------------------------------------------
// Utility function taken from petsc/src/dm/impls/plex/examples/tutorials/ex7.c
static PetscErrorCode ProjectToUnitSphere(DM dm) {
Vec coordinates;
PetscScalar *coords;
PetscInt Nv, v, dim, d;
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = DMGetCoordinatesLocal(dm, &coordinates); CHKERRQ(ierr);
ierr = VecGetLocalSize(coordinates, &Nv); CHKERRQ(ierr);
ierr = VecGetBlockSize(coordinates, &dim); CHKERRQ(ierr);
Nv /= dim;
ierr = VecGetArray(coordinates, &coords); CHKERRQ(ierr);
for (v = 0; v < Nv; ++v) {
PetscReal r = 0.0;
for (d = 0; d < dim; ++d) r += PetscSqr(PetscRealPart(coords[v*dim+d]));
r = PetscSqrtReal(r);
for (d = 0; d < dim; ++d) coords[v*dim+d] /= r;
}
ierr = VecRestoreArray(coordinates, &coords); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// PETSc Finite Element space setup
// -----------------------------------------------------------------------------
// Create FE by degree
static int PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,
PetscBool isSimplex, const char prefix[],
PetscInt order, PetscFE *fem) {
PetscQuadrature q, fq;
DM K;
PetscSpace P;
PetscDualSpace Q;
PetscInt quadPointsPerEdge;
PetscBool tensor = isSimplex ? PETSC_FALSE : PETSC_TRUE;
PetscErrorCode ierr;
PetscFunctionBeginUser;
/* Create space */
ierr = PetscSpaceCreate(PetscObjectComm((PetscObject) dm), &P); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) P, prefix); CHKERRQ(ierr);
ierr = PetscSpacePolynomialSetTensor(P, tensor); CHKERRQ(ierr);
ierr = PetscSpaceSetFromOptions(P); CHKERRQ(ierr);
ierr = PetscSpaceSetNumComponents(P, Nc); CHKERRQ(ierr);
ierr = PetscSpaceSetNumVariables(P, dim); CHKERRQ(ierr);
ierr = PetscSpaceSetDegree(P, order, order); CHKERRQ(ierr);
ierr = PetscSpaceSetUp(P); CHKERRQ(ierr);
ierr = PetscSpacePolynomialGetTensor(P, &tensor); CHKERRQ(ierr);
/* Create dual space */
ierr = PetscDualSpaceCreate(PetscObjectComm((PetscObject) dm), &Q);
CHKERRQ(ierr);
ierr = PetscDualSpaceSetType(Q,PETSCDUALSPACELAGRANGE); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) Q, prefix); CHKERRQ(ierr);
ierr = PetscDualSpaceCreateReferenceCell(Q, dim, isSimplex, &K); CHKERRQ(ierr);
ierr = PetscDualSpaceSetDM(Q, K); CHKERRQ(ierr);
ierr = DMDestroy(&K); CHKERRQ(ierr);
ierr = PetscDualSpaceSetNumComponents(Q, Nc); CHKERRQ(ierr);
ierr = PetscDualSpaceSetOrder(Q, order); CHKERRQ(ierr);
ierr = PetscDualSpaceLagrangeSetTensor(Q, tensor); CHKERRQ(ierr);
ierr = PetscDualSpaceSetFromOptions(Q); CHKERRQ(ierr);
ierr = PetscDualSpaceSetUp(Q); CHKERRQ(ierr);
/* Create element */
ierr = PetscFECreate(PetscObjectComm((PetscObject) dm), fem); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) *fem, prefix); CHKERRQ(ierr);
ierr = PetscFESetFromOptions(*fem); CHKERRQ(ierr);
ierr = PetscFESetBasisSpace(*fem, P); CHKERRQ(ierr);
ierr = PetscFESetDualSpace(*fem, Q); CHKERRQ(ierr);
ierr = PetscFESetNumComponents(*fem, Nc); CHKERRQ(ierr);
ierr = PetscFESetUp(*fem); CHKERRQ(ierr);
ierr = PetscSpaceDestroy(&P); CHKERRQ(ierr);
ierr = PetscDualSpaceDestroy(&Q); CHKERRQ(ierr);
/* Create quadrature */
quadPointsPerEdge = PetscMax(order + 1,1);
if (isSimplex) {
ierr = PetscDTStroudConicalQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,
&q); CHKERRQ(ierr);
ierr = PetscDTStroudConicalQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,
&fq); CHKERRQ(ierr);
} else {
ierr = PetscDTGaussTensorQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,
&q); CHKERRQ(ierr);
ierr = PetscDTGaussTensorQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,
&fq); CHKERRQ(ierr);
}
ierr = PetscFESetQuadrature(*fem, q); CHKERRQ(ierr);
ierr = PetscFESetFaceQuadrature(*fem, fq); CHKERRQ(ierr);
ierr = PetscQuadratureDestroy(&q); CHKERRQ(ierr);
ierr = PetscQuadratureDestroy(&fq); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// PETSc Setup for Level
// -----------------------------------------------------------------------------
// This function sets up a DM for a given degree
static int SetupDMByDegree(DM dm, PetscInt degree, PetscInt ncompu,
PetscInt dim) {
PetscInt ierr;
PetscFE fe;
PetscFunctionBeginUser;
// Setup FE
ierr = PetscFECreateByDegree(dm, dim, ncompu, PETSC_FALSE, NULL, degree, &fe);
CHKERRQ(ierr);
ierr = DMAddField(dm, NULL, (PetscObject)fe); CHKERRQ(ierr);
// Setup DM
ierr = DMCreateDS(dm); CHKERRQ(ierr);
ierr = DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL);
CHKERRQ(ierr);
ierr = PetscFEDestroy(&fe); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// libCEED Setup for Level
// -----------------------------------------------------------------------------
// Destroy libCEED operator objects
static PetscErrorCode CeedDataDestroy(CeedData data) {
PetscInt ierr;
CeedVectorDestroy(&data->qdata);
CeedVectorDestroy(&data->uceed);
CeedVectorDestroy(&data->vceed);
CeedBasisDestroy(&data->basisx);
CeedBasisDestroy(&data->basisu);
CeedElemRestrictionDestroy(&data->Erestrictu);
CeedElemRestrictionDestroy(&data->Erestrictx);
CeedElemRestrictionDestroy(&data->Erestrictqdi);
CeedQFunctionDestroy(&data->qf_apply);
CeedOperatorDestroy(&data->op_apply);
ierr = PetscFree(data); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// Auxiliary function to define CEED restrictions from DMPlex data
static int CreateRestrictionPlex(Ceed ceed, CeedInt P, CeedInt ncomp,
CeedElemRestriction *Erestrict, DM dm) {
PetscInt ierr;
PetscInt c, cStart, cEnd, nelem, nnodes, *erestrict, eoffset;
PetscSection section;
Vec Uloc;
PetscFunctionBegin;
// Get Nelem
ierr = DMGetSection(dm, §ion); CHKERRQ(ierr);
ierr = DMPlexGetHeightStratum(dm, 0, &cStart,& cEnd); CHKERRQ(ierr);
nelem = cEnd - cStart;
// Get indices
ierr = PetscMalloc1(nelem*P*P, &erestrict); CHKERRQ(ierr);
for (c=cStart, eoffset = 0; c<cEnd; c++) {
PetscInt numindices, *indices, i;
ierr = DMPlexGetClosureIndices(dm, section, section, c, PETSC_TRUE,
&numindices, &indices, NULL, NULL);
CHKERRQ(ierr);
for (i=0; i<numindices; i+=ncomp) {
for (PetscInt j=0; j<ncomp; j++) {
if (indices[i+j] != indices[i] + (PetscInt)(copysign(j, indices[i])))
SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
"Cell %D closure indices not interlaced", c);
}
// NO BC on closed surfaces
PetscInt loc = indices[i];
erestrict[eoffset++] = loc;
}
ierr = DMPlexRestoreClosureIndices(dm, section, section, c, PETSC_TRUE,
&numindices, &indices, NULL, NULL);
CHKERRQ(ierr);
}
// Setup CEED restriction
ierr = DMGetLocalVector(dm, &Uloc); CHKERRQ(ierr);
ierr = VecGetLocalSize(Uloc, &nnodes); CHKERRQ(ierr);
ierr = DMRestoreLocalVector(dm, &Uloc); CHKERRQ(ierr);
CeedElemRestrictionCreate(ceed, nelem, P*P, ncomp, 1, nnodes,
CEED_MEM_HOST, CEED_COPY_VALUES, erestrict,
Erestrict);
ierr = PetscFree(erestrict); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// Set up libCEED for a given degree
static int SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree,
CeedInt topodim, CeedInt qextra,
PetscInt ncompx, PetscInt ncompu,
PetscInt xlsize, problemType problemChoice,
CeedData data) {
int ierr;
DM dmcoord;
Vec coords;
const PetscScalar *coordArray;
CeedBasis basisx, basisu;
CeedElemRestriction Erestrictx, Erestrictu, Erestrictqdi;
CeedQFunction qf_setupgeo, qf_apply;
CeedOperator op_setupgeo, op_apply;
CeedVector xcoord, qdata, uceed, vceed;
CeedInt P, Q, cStart, cEnd, nelem,
qdatasize = problemOptions[problemChoice].qdatasize;
// CEED bases
P = degree + 1;
Q = P + qextra;
CeedBasisCreateTensorH1Lagrange(ceed, topodim, ncompu, P, Q,
problemOptions[problemChoice].qmode, &basisu);
CeedBasisCreateTensorH1Lagrange(ceed, topodim, ncompx, 2, Q,
problemOptions[problemChoice].qmode, &basisx);
// CEED restrictions
ierr = DMGetCoordinateDM(dm, &dmcoord); CHKERRQ(ierr);
ierr = DMPlexSetClosurePermutationTensor(dmcoord, PETSC_DETERMINE, NULL);
CHKERRQ(ierr);
ierr = CreateRestrictionPlex(ceed, 2, ncompx, &Erestrictx, dmcoord);
CHKERRQ(ierr);
ierr = CreateRestrictionPlex(ceed, P, ncompu, &Erestrictu, dm); CHKERRQ(ierr);
ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);
nelem = cEnd - cStart;
CeedElemRestrictionCreateStrided(ceed, nelem, Q*Q, qdatasize,
qdatasize*nelem*Q*Q,
CEED_STRIDES_BACKEND, &Erestrictqdi);
// Element coordinates
ierr = DMGetCoordinatesLocal(dm, &coords); CHKERRQ(ierr);
ierr = VecGetArrayRead(coords, &coordArray); CHKERRQ(ierr);
CeedElemRestrictionCreateVector(Erestrictx, &xcoord, NULL);
CeedVectorSetArray(xcoord, CEED_MEM_HOST, CEED_COPY_VALUES,
(PetscScalar *)coordArray);
ierr = VecRestoreArrayRead(coords, &coordArray);
// Create the vectors that will be needed in setup and apply
CeedInt nqpts;
CeedBasisGetNumQuadraturePoints(basisu, &nqpts);
CeedVectorCreate(ceed, qdatasize*nelem*nqpts, &qdata);
CeedVectorCreate(ceed, xlsize, &uceed);
CeedVectorCreate(ceed, xlsize, &vceed);
// Create the Q-function that builds the operator (i.e. computes its
// quadrature data) and set its context data
CeedQFunctionCreateInterior(ceed, 1, problemOptions[problemChoice].setupgeo,
problemOptions[problemChoice].setupgeofname,
&qf_setupgeo);
CeedQFunctionAddInput(qf_setupgeo, "x", ncompx, CEED_EVAL_INTERP);
CeedQFunctionAddInput(qf_setupgeo, "dx", ncompx*topodim, CEED_EVAL_GRAD);
CeedQFunctionAddInput(qf_setupgeo, "weight", 1, CEED_EVAL_WEIGHT);
CeedQFunctionAddOutput(qf_setupgeo, "qdata", qdatasize, CEED_EVAL_NONE);
// Set up the mass operator
CeedQFunctionCreateInterior(ceed, 1, problemOptions[problemChoice].apply,
problemOptions[problemChoice].applyfname,
&qf_apply);
CeedQFunctionAddInput(qf_apply, "u", ncompu,
problemOptions[problemChoice].inmode);
CeedQFunctionAddInput(qf_apply, "qdata", qdatasize, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_apply, "v", ncompu,
problemOptions[problemChoice].outmode);
// Create the operator that builds the quadrature data for the operator
CeedOperatorCreate(ceed, qf_setupgeo, NULL, NULL, &op_setupgeo);
CeedOperatorSetField(op_setupgeo, "x", Erestrictx, basisx,
CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setupgeo, "dx", Erestrictx, basisx,
CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setupgeo, "weight", CEED_ELEMRESTRICTION_NONE, basisx,
CEED_VECTOR_NONE);
CeedOperatorSetField(op_setupgeo, "qdata", Erestrictqdi,
CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
// Create the mass or diff operator
CeedOperatorCreate(ceed, qf_apply, NULL, NULL, &op_apply);
CeedOperatorSetField(op_apply, "u", Erestrictu, basisu, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_apply, "qdata", Erestrictqdi, CEED_BASIS_COLLOCATED,
qdata);
CeedOperatorSetField(op_apply, "v", Erestrictu, basisu, CEED_VECTOR_ACTIVE);
// Setup qdata
CeedOperatorApply(op_setupgeo, xcoord, qdata, CEED_REQUEST_IMMEDIATE);
// Cleanup
CeedQFunctionDestroy(&qf_setupgeo);
CeedOperatorDestroy(&op_setupgeo);
CeedVectorDestroy(&xcoord);
// Save libCEED data
data->basisx = basisx;
data->basisu = basisu;
data->Erestrictx = Erestrictx;
data->Erestrictu = Erestrictu;
data->Erestrictqdi = Erestrictqdi;
data->qf_apply = qf_apply;
data->op_apply = op_apply;
data->qdata = qdata;
data->uceed = uceed;
data->vceed = vceed;
PetscFunctionReturn(0);
}
#endif // setuparea_h
| {
"alphanum_fraction": 0.6334608945,
"avg_line_length": 38.1826484018,
"ext": "h",
"hexsha": "df2a7ecae0b48bf7a5c8a18d701d5ef12827b9c7",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-30T23:13:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-30T23:13:18.000Z",
"max_forks_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "barker29/libCEED",
"max_forks_repo_path": "examples/petsc/setuparea.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514",
"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": "barker29/libCEED",
"max_issues_repo_path": "examples/petsc/setuparea.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "barker29/libCEED",
"max_stars_repo_path": "examples/petsc/setuparea.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4525,
"size": 16724
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
#ifdef COSMIC_RAYS
#include "cosmic_rays.h"
#endif
void reconstruct_timebins(void)
{
int i, n, prev, bin;
long long glob_sum1, glob_sum2;
for(bin = 0; bin < TIMEBINS; bin++)
{
TimeBinCount[bin] = 0;
TimeBinCountSph[bin] = 0;
FirstInTimeBin[bin] = -1;
LastInTimeBin[bin] = -1;
#ifdef SFR
TimeBinSfr[bin] = 0;
#endif
#ifdef BLACK_HOLES
TimeBin_BH_mass[bin] = 0;
TimeBin_BH_dynamicalmass[bin] = 0;
TimeBin_BH_Mdot[bin] = 0;
TimeBin_BH_Medd[bin] = 0;
#endif
}
for(i = 0; i < NumPart; i++)
{
bin = P[i].TimeBin;
if(TimeBinCount[bin] > 0)
{
PrevInTimeBin[i] = LastInTimeBin[bin];
NextInTimeBin[i] = -1;
NextInTimeBin[LastInTimeBin[bin]] = i;
LastInTimeBin[bin] = i;
}
else
{
FirstInTimeBin[bin] = LastInTimeBin[bin] = i;
PrevInTimeBin[i] = NextInTimeBin[i] = -1;
}
TimeBinCount[bin]++;
if(P[i].Type == 0)
TimeBinCountSph[bin]++;
#ifdef SFR
if(P[i].Type == 0)
TimeBinSfr[bin] += SphP[i].Sfr;
#endif
#if BLACK_HOLES
if(P[i].Type == 5)
{
TimeBin_BH_mass[bin] += P[i].BH_Mass;
TimeBin_BH_dynamicalmass[bin] += P[i].Mass;
TimeBin_BH_Mdot[bin] += P[i].BH_Mdot;
TimeBin_BH_Medd[bin] += P[i].BH_Mdot / P[i].BH_Mass;
}
#endif
}
FirstActiveParticle = -1;
for(n = 0, prev = -1; n < TIMEBINS; n++)
{
if(TimeBinActive[n])
for(i = FirstInTimeBin[n]; i >= 0; i = NextInTimeBin[i])
{
if(prev == -1)
FirstActiveParticle = i;
if(prev >= 0)
NextActiveParticle[prev] = i;
prev = i;
}
}
if(prev >= 0)
NextActiveParticle[prev] = -1;
sumup_large_ints(1, &NumForceUpdate, &glob_sum1);
for(i = FirstActiveParticle, NumForceUpdate = 0; i >= 0; i = NextActiveParticle[i])
{
NumForceUpdate++;
if(i >= NumPart)
{
printf("Bummer i=%d\n", i);
endrun(12);
}
}
sumup_large_ints(1, &NumForceUpdate, &glob_sum2);
if(ThisTask == 0)
{
printf("sum1=%d%9d sum2=%d%9d\n",
(int) (glob_sum1 / 1000000000), (int) (glob_sum1 % 1000000000),
(int) (glob_sum2 / 1000000000), (int) (glob_sum2 % 1000000000));
}
if(glob_sum1 != glob_sum2 && All.NumCurrentTiStep > 0)
endrun(121);
}
void drift_particle(int i, int time1)
{
int j, time0, dt_step;
double dt_drift, dt_gravkick, dt_hydrokick, dt_entr;
#ifdef DISTORTIONTENSORPS
int j1, j2;
/*
Setup all numbers that are going to be written to caustic log file. Some of them will not be set, depending
on Makefile options. Therefore we assign zero to each value in the beginning.
*/
MyDouble s_1=0.0, s_2=0.0, s_3=0.0;
MyDouble smear_x=0.0, smear_y=0.0, smear_z=0.0;
MyDouble CurrentTurnaroundRadius=0.0;
MyDouble caustic_counter = 0.0;
MyDouble summed_annihilation = 0.0;
MyDouble D_xP = 0.0;
MyDouble init_density = 0.0;
MyDouble rho_normed_cutoff = 0.0;
MyDouble second_deriv_fac = 0.0;
MyDouble analytic_add_to_annihilation = 0.0;
/* things needed for caustics detection */
MyDouble determinant = 1.0;
MyDouble product_matrix[3][3];
MyDouble current_normed_stream_density;
MyDouble last_normed_stream_density;
#ifdef ANNIHILATION_RADIATION
/*1: if annihilation radiation was integrated analytically through the caustic, 0: otherwise */
int caustic_annihilation_flag = 0;
MyDouble rho_0, kappa_caustic;
#endif
#if SIM_ADAPTIVE_SOFT
CurrentTurnaroundRadius = All.CurrentTurnaroundRadius;
#endif
#endif /* DISTORTIONTENSORPS */
#ifdef COSMIC_RAYS
int CRpop;
#endif
#ifdef SOFTEREQS
double a3inv;
if(All.ComovingIntegrationOn)
a3inv = 1 / (All.Time * All.Time * All.Time);
else
a3inv = 1;
#endif
time0 = P[i].Ti_current;
if(time1 < time0)
{
printf("i=%d time0=%d time1=%d\n", i, time0, time1);
endrun(12);
}
if(time1 == time0)
return;
if(All.ComovingIntegrationOn)
{
dt_drift = get_drift_factor(time0, time1);
dt_gravkick = get_gravkick_factor(time0, time1);
dt_hydrokick = get_hydrokick_factor(time0, time1);
}
else
{
dt_drift = dt_gravkick = dt_hydrokick = (time1 - time0) * All.Timebase_interval;
}
for(j = 0; j < 3; j++)
P[i].Pos[j] += P[i].Vel[j] * dt_drift;
/* START PHASE-SPACE ANALYSIS ------------------------------------------------------ */
#ifdef DISTORTIONTENSORPS
/* do the DRIFT for distortion (this updates D_xq and D_xp; D_vq and D_vp are updated during kick) */
for(j1 = 0; j1 < 3; j1++)
for(j2 = 0; j2 < 6; j2++)
P[i].distortion_tensorps[j1][j2] += P[i].distortion_tensorps[j1 + 3][j2] * dt_drift;
#ifdef REINIT_AT_TURNAROUND
/* do we have to reinit distortion tensor? Only particles that are initially outside the turnaround radius are analyzed */
if ((P[i].Pos[0]*P[i].Vel[0]+P[i].Pos[1]*P[i].Vel[1]+P[i].Pos[2]*P[i].Vel[2] < 0.0) && (P[i].turnaround_flag == 0))
{
/* yes, particle turned around */
/* re-init distortion tensor */
for(j1 = 0; j1 < 6; j1++)
for(j2 = 0; j2 < 6; j2++)
{
if((j1 == j2))
{
P[i].distortion_tensorps[j1][j2] = 1.0;
}
else
{
P[i].distortion_tensorps[j1][j2] = 0.0;
}
}
/* mark particle so that we know that it already turned around */
P[i].turnaround_flag = 1;
/* set new initial sheet orientation since we start distortion from this point (analytic solution) */
for (j1=0; j1<=2; j1++)
for (j2=0; j2<=2; j2++)
P[i].V_matrix[j1][j2] = P[i].Pos[j1]*P[i].Pos[j2] / (P[i].Pos[0]*P[i].Pos[0]+P[i].Pos[1]*P[i].Pos[1]+P[i].Pos[2]*P[i].Pos[2]) *
(3.0/4.0*M_PI)*(3.0/4.0*M_PI) / (3.0 + 1.0/All.SIM_epsilon) * 1.0 / All.Time;
/*
The correct stream init density at turn around is given by rho_crit * 9.0 * M_PI * M_PI / (16.0*(3.0*epsilon+1.0)).
This is exactly the density at the turnaround radius for a given density perturbation index epsilon.
(see for example, Sikivie et al 1997)
*/
P[i].init_density = 9.0 * M_PI * M_PI / (16.0*(3.0*All.SIM_epsilon+1.0)) * 1.0 / (6.0 * M_PI * All.G * All.Time * All.Time);
/* reset last_stream_determinant (needed for caustic identification) */
P[i].last_stream_determinant = 1.0;
#ifdef ANNIHILATION_RADIATION
/* set annihilation radiation to zero */
P[i].annihilation = 0.0;
#endif
}
#endif
/* NOW CAUSTIC AND ANNIHILATION HANDLING */
#ifdef REINIT_AT_TURNAROUND
/* only analyse particle initially outside the turnaround radius, those initially inside have been set to P[i].turnaround_flag=-1 */
if (P[i].turnaround_flag >= 0)
{
#endif
/* CAUSTIC IDENTIFICATION PART */
/* projection phase-space distrtion matrix (see Vogelsberger et al, 2008 Eq. (22)) -> needed to check for caustic in drift */
product_matrix[0][0] = P[i].distortion_tensorps[0][0] +
P[i].distortion_tensorps[0][3] * P[i].V_matrix[0][0] +
P[i].distortion_tensorps[0][4] * P[i].V_matrix[1][0] +
P[i].distortion_tensorps[0][5] * P[i].V_matrix[2][0];
product_matrix[0][1] = P[i].distortion_tensorps[0][1] +
P[i].distortion_tensorps[0][3] * P[i].V_matrix[0][1] +
P[i].distortion_tensorps[0][4] * P[i].V_matrix[1][1] +
P[i].distortion_tensorps[0][5] * P[i].V_matrix[2][1];
product_matrix[0][2] = P[i].distortion_tensorps[0][2] +
P[i].distortion_tensorps[0][3] * P[i].V_matrix[0][2] +
P[i].distortion_tensorps[0][4] * P[i].V_matrix[1][2] +
P[i].distortion_tensorps[0][5] * P[i].V_matrix[2][2];
product_matrix[1][0] = P[i].distortion_tensorps[1][0] +
P[i].distortion_tensorps[1][3] * P[i].V_matrix[0][0] +
P[i].distortion_tensorps[1][4] * P[i].V_matrix[1][0] +
P[i].distortion_tensorps[1][5] * P[i].V_matrix[2][0];
product_matrix[1][1] = P[i].distortion_tensorps[1][1] +
P[i].distortion_tensorps[1][3] * P[i].V_matrix[0][1] +
P[i].distortion_tensorps[1][4] * P[i].V_matrix[1][1] +
P[i].distortion_tensorps[1][5] * P[i].V_matrix[2][1];
product_matrix[1][2] = P[i].distortion_tensorps[1][2] +
P[i].distortion_tensorps[1][3] * P[i].V_matrix[0][2] +
P[i].distortion_tensorps[1][4] * P[i].V_matrix[1][2] +
P[i].distortion_tensorps[1][5] * P[i].V_matrix[2][2];
product_matrix[2][0] = P[i].distortion_tensorps[2][0] +
P[i].distortion_tensorps[2][3] * P[i].V_matrix[0][0] +
P[i].distortion_tensorps[2][4] * P[i].V_matrix[1][0] +
P[i].distortion_tensorps[2][5] * P[i].V_matrix[2][0];
product_matrix[2][1] = P[i].distortion_tensorps[2][1] +
P[i].distortion_tensorps[2][3] * P[i].V_matrix[0][1] +
P[i].distortion_tensorps[2][4] * P[i].V_matrix[1][1] +
P[i].distortion_tensorps[2][5] * P[i].V_matrix[2][1];
product_matrix[2][2] = P[i].distortion_tensorps[2][2] +
P[i].distortion_tensorps[2][3] * P[i].V_matrix[0][2] +
P[i].distortion_tensorps[2][4] * P[i].V_matrix[1][2] +
P[i].distortion_tensorps[2][5] * P[i].V_matrix[2][2];
/* this determinant will change sign when we pass through a caustic -> criterion for caustics */
determinant = ((product_matrix[0][0]) * (product_matrix[1][1]) * (product_matrix[2][2]) +
(product_matrix[0][1]) * (product_matrix[1][2]) * (product_matrix[2][0]) +
(product_matrix[0][2]) * (product_matrix[1][0]) * (product_matrix[2][1]) -
(product_matrix[0][2]) * (product_matrix[1][1]) * (product_matrix[2][0]) -
(product_matrix[0][0]) * (product_matrix[1][2]) * (product_matrix[2][1]) -
(product_matrix[0][1]) * (product_matrix[1][0]) * (product_matrix[2][2]));
/*
Current and last NORMED stream density, linear order result of the last and current timestep.
*/
current_normed_stream_density = 1.0/fabs(determinant);
last_normed_stream_density = 1.0/fabs(P[i].last_stream_determinant);
#ifdef ANNIHILATION_RADIATION
/* avarage stream density */
rho_0 = (current_normed_stream_density + last_normed_stream_density) / 2;
/* extract phase-space information for annihilation radiation calculation -> cutoff density */
P[i].rho_normed_cutoff_last = P[i].rho_normed_cutoff_current;
P[i].rho_normed_cutoff_current = analyse_phase_space(i, &s_1, &s_2, &s_3, &smear_x, &smear_y, &smear_z, &D_xP, &second_deriv_fac);
#endif
/* CAUSTIC FOUND? -> was there a caustics between the last and the current timestep and does the particle type fit? */
if((determinant * P[i].last_stream_determinant < 0.0) && (((1 << P[i].Type) & (CAUSTIC_FINDER))))
{
#ifdef ANNIHILATION_RADIATION
/* get normed_cutoff density */
rho_normed_cutoff = P[i].rho_normed_cutoff_current;
/*
If rho_0 = (current_normed_stream_density + last_normed_stream_density) / 2 (so the average of current and last
normed stream density) is below current normed cutoff density, we integrate analytically through the caustic
for that time step.
rho
^
| * <--- rho_normed_cutoff
| ***
| *****
| ******* <-- area under curve ~ diverges logarithmicly
| *********
| ***********
| ************* <--- rho_0
|---|-----|-----|----> t
t_last t_c t_current
Note that the stream density is assumed to be symmetric around the caustic point: t_caustic = (t_last + t_current) / 2
So we can center everything around t=0:
rho
^
| * <--- rho_normed_cutoff
| ***
| *****
| ******* <-- area under curve ~ diverges logarithmicly
| *********
| ***********
| ************* <--- rho_0
|---|-----|-----|----> t
-dt_drift/2 0 +dt_drift/2
t_caustic = 0 and dt_drift = t_current - t_last
The fact that the numerical normed density near the caustic is below the cutoff, means that we cannot
numerically resolve the very high caustic density within the time step.
The analytic integration exploits the logarithmic divergence:
Ansatz:
rho(t) = kappa / |t| ---> rho_0 = kappa / |dt_drift/2| ---> kappa = dt_drift/2 * rho_0
Integrated annihilation rate:
2 \int_{-dt_drift/2}^{+dt_drift/2} dt rho(t) =
2 - 2 kappa \int_{-dt_drift/2}^{0} dt 1/t = [ substitute drho / dt = + kappa/t^2 for t <0]
2 2 kappa \int_{rho_0}^{rho_c} drho 1/rho =
2 2 kappa ln(rho_c/rho_0)
Therefore we need to add 2 kappa ln(\rho_c/\rho_0) when passing through an unresolved caustic,
where rho_c is the calculated maximum density in the caustic.
Note:
We assume that the maximum density for the current and last time step do not differ much, so
that we can compare rho_0 always to the current maximum density.
*/
#ifdef REINIT_AT_TURNAROUND
/*
We only integrate annihilation for particles that turned around already (otherwise wrong initial density)
This is a security check, since each particle going through a caustic in general already turned around before.
*/
if (P[i].turnaround_flag == 1)
{
#endif
/* if this condition is true we have to integrate analyitcally through the caustic */
if (rho_0 < P[i].rho_normed_cutoff_current)
{
/* we do have an analytic integration through the caustic -> increase the counter and mark the flag */
P[i].analytic_caustics += 1.0;
caustic_annihilation_flag = 1;
/* calculate analytic contribution */
kappa_caustic = dt_drift / 2.0 * rho_0;
analytic_add_to_annihilation = 2.0 * kappa_caustic * log(fabs(P[i].rho_normed_cutoff_current/rho_0));
/* add contribution to annihilation radiation */
P[i].annihilation += analytic_add_to_annihilation;
}
summed_annihilation = P[i].annihilation;
#ifdef REINIT_AT_TURNAROUND
} /* end if (P[i].turnaround_flag == 1) */
#endif
#endif /* ANNIHILATION_RADIATION */
/* increase caustic counter by one */
P[i].caustic_counter += 1.0;
caustic_counter = P[i].caustic_counter;
#ifdef OUTPUT_LAST_CAUSTIC
P[i].lc_Time = All.Time;
P[i].lc_Pos[0] = P[i].Pos[0];
P[i].lc_Pos[1] = P[i].Pos[1];
P[i].lc_Pos[2] = P[i].Pos[2];
P[i].lc_Vel[0] = P[i].Vel[0];
P[i].lc_Vel[1] = P[i].Vel[1];
P[i].lc_Vel[2] = P[i].Vel[2];
#ifdef ANNIHILATION_RADIATION
P[i].lc_rho_normed_cutoff = P[i].rho_normed_cutoff_current;
#else
P[i].lc_rho_normed_cutoff = 0.0;
#endif
#endif
init_density = P[i].init_density;
/* write data to caustic log file -> allows caustics to be tracked on time-stepping frequency */
fprintf(FdCaustics, "%g %g %d %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g\n",
(MyOutputFloat) All.Time,
(MyOutputFloat) determinant,
P[i].ID,
(MyOutputFloat) P[i].Pos[0], (MyOutputFloat) P[i].Pos[1], (MyOutputFloat) P[i].Pos[2],
(MyOutputFloat) P[i].Vel[0], (MyOutputFloat) P[i].Vel[1], (MyOutputFloat) P[i].Vel[2],
caustic_counter,
s_1, s_2, s_3, smear_x, smear_y, smear_z,
summed_annihilation,
CurrentTurnaroundRadius,
D_xP,
init_density / (1.0/(6.0*M_PI*All.G*All.Time*All.Time)),
rho_normed_cutoff,
second_deriv_fac,
analytic_add_to_annihilation);
fflush(FdCaustics);
}
#ifdef ANNIHILATION_RADIATION
/* is the numerical stream density above the normed_cutoff -> cut it */
if (rho_0 > P[i].rho_normed_cutoff_current)
{
rho_0 = P[i].rho_normed_cutoff_current;
}
/* save cutted averaged stream density in physical units -> multiply with initial stream density */
P[i].stream_density = P[i].init_density * rho_0;
#ifdef REINIT_AT_TURNAROUND
/*
We only integrate annihilation for particles that turned around already (otherwise wrong initial density)
This is a security check, since each particle going through a caustic in general already turned around before.
*/
if (P[i].turnaround_flag == 1)
{
#endif
/* integrate normed annihilation radiation -> multiplication with initial stream density is done in io.c to reduce round-off */
if (caustic_annihilation_flag == 0)
P[i].annihilation += rho_0 * dt_drift;
#ifdef REINIT_AT_TURNAROUND
} /* end if (P[i].turnaround_flag == 1) */
#endif
#ifdef NO_CENTER_ANNIHILATION
/* ignore the center for annihilation */
if (sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]) < All.SofteningTable[P[i].Type])
{
/* set everything to zero in center */
P[i].annihilation = 0.0;
P[i].stream_density = 0.0;
}
#endif
#endif /*ANNIHILATION_RADIATION */
#ifdef REINIT_AT_TURNAROUND
} /* end if (P[i].turnaround_flag >= 0) */
#endif
/* update determinant, so we can identify the next caustic along the orbit */
P[i].last_stream_determinant = determinant;
#endif /* DISTORTIONTENSORPS */
/* END PHASE-SPACE ANALYSIS ------------------------------------------------------ */
#ifndef HPM
if(P[i].Type == 0)
{
#ifdef PMGRID
for(j = 0; j < 3; j++)
SphP[i].VelPred[j] +=
(P[i].g.GravAccel[j] + P[i].GravPM[j]) * dt_gravkick + SphP[i].a.HydroAccel[j] * dt_hydrokick;
#else
for(j = 0; j < 3; j++)
SphP[i].VelPred[j] += P[i].g.GravAccel[j] * dt_gravkick + SphP[i].a.HydroAccel[j] * dt_hydrokick;
#endif
SphP[i].d.Density *= exp(-SphP[i].v.DivVel * dt_drift);
PPP[i].Hsml *= exp(0.333333333333 * SphP[i].v.DivVel * dt_drift);
if(PPP[i].Hsml < All.MinGasHsml)
PPP[i].Hsml = All.MinGasHsml;
#ifndef WAKEUP
dt_step = (P[i].TimeBin ? (1 << P[i].TimeBin) : 0);
#else
dt_step = P[i].dt_step;
#endif
dt_entr = (time1 - (P[i].Ti_begstep + dt_step / 2)) * All.Timebase_interval;
#ifndef EOS_DEGENERATE
#ifndef MHM
#ifndef SOFTEREQS
#ifndef VORONOI_MESHRELAX
SphP[i].Pressure = (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA);
#endif
#else
if(SphP[i].d.Density * a3inv >= All.PhysDensThresh)
SphP[i].Pressure =
All.FactorForSofterEQS * (SphP[i].Entropy +
SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density,
GAMMA) + (1 -
All.
FactorForSofterEQS) *
GAMMA_MINUS1 * SphP[i].d.Density * All.InitGasU;
else
SphP[i].Pressure = (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA);
#endif
#else
/* Here we use an isothermal equation of state */
SphP[i].Pressure = GAMMA_MINUS1 * SphP[i].d.Density * All.InitGasU;
SphP[i].Entropy = SphP[i].Pressure / pow(SphP[i].d.Density, GAMMA);
#endif
#else
/* call tabulated eos with physical units */
#ifdef EOS_ENERGY
eos_calc_egiven2(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc,
SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr * All.UnitTime_in_s, &SphP[i].temp,
&SphP[i].Pressure);
SphP[i].Pressure /= All.UnitPressure_in_cgs;
#else
eos_calc_sgiven(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc,
SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr * All.UnitTime_in_s, &SphP[i].temp,
&SphP[i].Pressure, &SphP[i].u);
SphP[i].Pressure /= All.UnitPressure_in_cgs;
#endif
#endif
#ifdef COSMIC_RAYS
#if defined( CR_UPDATE_PARANOIA )
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
CR_Particle_Update(SphP + i, CRpop);
#endif
#ifndef CR_NOPRESSURE
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
SphP[i].Pressure += CR_Comoving_Pressure(SphP + i, CRpop);
#endif
#endif
#if defined(MAGNETIC) && !defined(EULERPOTENTIALS)
for(j = 0; j < 3; j++)
SphP[i].BPred[j] += SphP[i].DtB[j] * dt_entr;
#ifdef DIVBCLEANING_DEDNER
SphP[i].PhiPred += SphP[i].DtPhi * dt_entr;
#endif
#endif
}
#endif /* end of HPM */
P[i].Ti_current = time1;
}
void move_particles(int time1)
{
int i;
if(ThisTask == 0)
printf("MOVE\n");
for(i = 0; i < NumPart; i++)
drift_particle(i, time1);
}
/*! This function makes sure that all particle coordinates (Pos) are
* periodically mapped onto the interval [0, BoxSize]. After this function
* has been called, a new domain decomposition should be done, which will
* also force a new tree construction.
*/
#ifdef PERIODIC
void do_box_wrapping(void)
{
int i, j;
double boxsize[3];
for(j = 0; j < 3; j++)
boxsize[j] = All.BoxSize;
#ifdef LONG_X
boxsize[0] *= LONG_X;
#endif
#ifdef LONG_Y
boxsize[1] *= LONG_Y;
#endif
#ifdef LONG_Z
boxsize[2] *= LONG_Z;
#endif
for(i = 0; i < NumPart; i++)
for(j = 0; j < 3; j++)
{
while(P[i].Pos[j] < 0)
P[i].Pos[j] += boxsize[j];
while(P[i].Pos[j] >= boxsize[j])
P[i].Pos[j] -= boxsize[j];
}
}
#endif
/*
#ifdef XXLINFO
#ifdef MAGNETIC
double MeanB_part = 0, MeanB_sum;
#ifdef TRACEDIVB
double MaxDivB_part = 0, MaxDivB_all;
double dmax1, dmax2;
#endif
#endif
#ifdef TIME_DEP_ART_VISC
double MeanAlpha_part = 0, MeanAlpha_sum;
#endif
#endif
#ifdef XXLINFO
if(Flag_FullStep == 1)
{
#ifdef MAGNETIC
MeanB_part += sqrt(SphP[i].BPred[0] * SphP[i].BPred[0] +
SphP[i].BPred[1] * SphP[i].BPred[1] + SphP[i].BPred[2] * SphP[i].BPred[2]);
#ifdef TRACEDIVB
MaxDivB_part = DMAX(MaxDivB, fabs(SphP[i].divB));
#endif
#endif
#ifdef TIME_DEP_ART_VISC
MeanAlpha_part += SphP[i].alpha;
#endif
}
#endif
#ifdef XXLINFO
if(Flag_FullStep == 1)
{
#ifdef MAGNETIC
MPI_Reduce(&MeanB_part, &MeanB_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if(ThisTask == 0)
MeanB = MeanB_sum / All.TotN_gas;
#ifdef TRACEDIVB
MPI_Reduce(&MaxDivB_part, &MaxDivB_all, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if(ThisTask == 0)
MaxDivB = MaxDivB_all;
#endif
#endif
#ifdef TIME_DEP_ART_VISC
MPI_Reduce(&MeanAlpha_part, &MeanAlpha_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if(ThisTask == 0)
MeanAlpha = MeanAlpha_sum / All.TotN_gas;
#endif
}
#endif
*/
| {
"alphanum_fraction": 0.5992787626,
"avg_line_length": 32.9742120344,
"ext": "c",
"hexsha": "d068ee12c4691618618da4f4651c1dff85907ce7",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/predict.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/predict.c",
"max_line_length": 147,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/predict.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7396,
"size": 23016
} |
// rand.h
#ifndef RAND_H
#define RAND_H
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#define URNG generator
class generator{
const gsl_rng_type * T;
public:
gsl_rng * r;
generator();
~generator();
void seed(unsigned long int s);
};
#include "types.h"
class r_lognorm{
double zeta;
double sigma;
public:
r_lognorm(REAL mean,REAL sigma);
~r_lognorm();
REAL operator()(URNG& g);
};
REAL lognorm_func(URNG& g,REAL mean,REAL sig);
class r_hypgeo{
unsigned int n1;
unsigned int n2;
unsigned int t;
public:
r_hypgeo(unsigned int population1,unsigned int population2,unsigned int samples);
~r_hypgeo();
unsigned int operator()(URNG& g);
};
unsigned int hypgeo_func(URNG& g,unsigned int population1,unsigned int population2,unsigned int samples);
class r_uni{
double a;
double b;
public:
r_uni(REAL min,REAL max);
~r_uni();
REAL operator()(URNG& g);
};
REAL unif_func(URNG& g,REAL min,REAL max);
REAL exp_func(URNG& g,REAL mu);
int ber_func(URNG& g ,REAL p);
#endif
| {
"alphanum_fraction": 0.6629732225,
"avg_line_length": 17.1904761905,
"ext": "h",
"hexsha": "5af17fc1bf3f6b8d8c6052117690b559b350beb6",
"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": "91ddc34a191723a615c10f33ab43b9b346f95ca0",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "fabianrost84/clasim",
"max_forks_repo_path": "src/rand.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "91ddc34a191723a615c10f33ab43b9b346f95ca0",
"max_issues_repo_issues_event_max_datetime": "2019-04-15T09:56:36.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-03-15T09:41:46.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "fabianrost84/clasim",
"max_issues_repo_path": "src/rand.h",
"max_line_length": 105,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "91ddc34a191723a615c10f33ab43b9b346f95ca0",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "fabianrost84/clasim",
"max_stars_repo_path": "src/rand.h",
"max_stars_repo_stars_event_max_datetime": "2019-03-15T09:48:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-15T09:48:54.000Z",
"num_tokens": 306,
"size": 1083
} |
/***********************************
V2 IMPLEMENTATION USING DATASETS
************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <cblas.h>
#include <string.h>
#include <mpi.h>
#include "../inc/knnring.h"
#include "../inc/readlib.h"
#include "../inc/vptring.h"
#define B 3
int main(int argc,char *argv[]){
int p_rank;
int p_size;
int n;
int d;
int k = 10;
double *X;
//CHOOSE WHICH DATASET
char file_path[200] = "../data/ColorHistogram.asc";
//INITIALIZE MPI COMMUNICATIONS
//MPI_Init(&argc,&argv); doesn't need any argument
MPI_Init(NULL,NULL);
MPI_Comm_size(MPI_COMM_WORLD, &p_size);
MPI_Comm_rank(MPI_COMM_WORLD, &p_rank);
MPI_Status status; // STATUS COMMUNICATION
int tag = 1; // COMMUNICATION TAG
//time variables to measure time
struct timespec ts_start;
struct timespec ts_end;
double time;
if(p_rank == 0){
//read all the data
double *X_total;
int n_total;
X_total = read_data(file_path,&n_total,&d);
//send n,d variables and the points coordinates to other processes.
n = n_total/p_size;
X = (double *)malloc(n*d*sizeof(double));
for(int i=1;i<p_size;i++){
for(int j=0;j<n*d;j++){
X[j] = X_total[i*n*d+j];
}
//send to every PROCESS
MPI_Send(&n,1, MPI_INT, i, tag, MPI_COMM_WORLD);
MPI_Send(&d,1, MPI_INT, i, tag, MPI_COMM_WORLD);
MPI_Send(X,n*d,MPI_DOUBLE, i, tag, MPI_COMM_WORLD);
}
//keep the first n points for myself.
for(int j=0;j<n*d;j++){
X[j] = X_total[j];
}
free(X_total);
clock_gettime(CLOCK_MONOTONIC, &ts_start);
knnresult results = distrV2(X,n,d,k,B);
clock_gettime(CLOCK_MONOTONIC, &ts_end);
time = 1000000*(double)(ts_end.tv_sec-ts_start.tv_sec)+(double)(ts_end.tv_nsec-ts_start.tv_nsec)/1000;
printf("TOTAL V2 time: %lf\n",time);
//WRITE TO FILE
char str[200];
snprintf(str,sizeof(str),"results/dist_v2_%d_%d_%d.txt",n,d,k);
write_to_file(str,results.nidx,results.ndist,n*k,results.k);
for(int p=1;p<p_size;p++){
MPI_Recv(results.nidx, n*k, MPI_INT,p,tag,MPI_COMM_WORLD, &status);
MPI_Recv(results.ndist,n*k, MPI_DOUBLE,p,tag,MPI_COMM_WORLD, &status);
write_to_file(str,results.nidx,results.ndist,n*k,results.k);
}
}
else{
//receive number of points n and distances.
MPI_Recv(&n,1,MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
MPI_Recv(&d,1,MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
//receive coordinates
X = (double *)malloc(n*d*sizeof(double));
MPI_Recv(X,n*d,MPI_DOUBLE, 0, tag, MPI_COMM_WORLD, &status);
clock_gettime(CLOCK_MONOTONIC, &ts_start);
knnresult results = distrV2(X,n,d,k,B);
clock_gettime(CLOCK_MONOTONIC, &ts_end);
time = 1000000*(double)(ts_end.tv_sec-ts_start.tv_sec)+(double)(ts_end.tv_nsec-ts_start.tv_nsec)/1000;
//printf("TOTAL V2 time: %lf from process %d\n",time,p_rank);
//send back the results
MPI_Send(results.nidx, n*k, MPI_INT ,0,tag,MPI_COMM_WORLD);
MPI_Send(results.ndist,n*k, MPI_DOUBLE,0,tag,MPI_COMM_WORLD);
}
//execution is over
MPI_Finalize();
printf("DONE ....=>EXITING\n");
return 0;
}
| {
"alphanum_fraction": 0.6330275229,
"avg_line_length": 27.9487179487,
"ext": "c",
"hexsha": "18174ebbb2469d963109edde8e8037eadeb83ff3",
"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": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kv13/Parallel-And-Distributed-Systems",
"max_forks_repo_path": "assignment2/src/v2_mpi2_2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c",
"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": "kv13/Parallel-And-Distributed-Systems",
"max_issues_repo_path": "assignment2/src/v2_mpi2_2.c",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kv13/Parallel-And-Distributed-Systems",
"max_stars_repo_path": "assignment2/src/v2_mpi2_2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 958,
"size": 3270
} |
/* -*- linux-c -*- */
/* fewbody.h
Copyright (C) 2002-2004 John M. Fregeau
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _FEWBODY_H
#define _FEWBODY_H 1
#include <stdio.h>
#include <gsl/gsl_nan.h>
#include <gsl/gsl_rng.h>
/* version information */
#define FB_VERSION "0.26"
#define FB_NICK "Oblivion"
#define FB_DATE "Mon Sep 6 09:05:47 EDT 2010"
/* dimensionless constants */
#define FB_CONST_PI 3.141592653589793238462643
/* constants, in cgs units */
#define FB_CONST_MSUN 1.989e+33
#define FB_CONST_RSUN 6.9599e+10
#define FB_CONST_C 2.99792458e+10
#define FB_CONST_G 6.67259e-8
#define FB_CONST_AU 1.496e+13
#define FB_CONST_PARSEC 3.0857e+18
#define FB_CONST_YR 3.155693e+7
/* these usually shouldn't need to be changed */
#define FB_H 1.0e-2
#define FB_SSTOP GSL_POSINF
#define FB_AMIN GSL_POSINF
#define FB_RMIN GSL_POSINF
#define FB_ROOTSOLVER_MAX_ITER 100
#define FB_ROOTSOLVER_ABS_ACC 1.0e-11
#define FB_ROOTSOLVER_REL_ACC 1.0e-11
#define FB_MAX_STRING_LENGTH 2048
#define FB_MAX_LOGENTRY_LENGTH (32 * FB_MAX_STRING_LENGTH)
/* a struct containing the units used */
typedef struct{
double v; /* velocity */
double l; /* length */
double t; /* time */
double m; /* mass */
double E; /* energy */
} fb_units_t;
/* the fundamental object */
typedef struct fb_obj{
int ncoll; /* total number of stars collided together in this star */
long *id; /* numeric id array */
char idstring[FB_MAX_STRING_LENGTH]; /* string id */
double m; /* mass */
double R; /* radius */
double Eint; /* internal energy (used to check energy conservation) */
double Lint[3]; /* internal ang mom (used to check ang mom conservation) */
double x[3]; /* position */
double v[3]; /* velocity */
int n; /* total number of stars in hierarchy */
struct fb_obj *obj[2]; /* pointers to children */
double a; /* semimajor axis */
double e; /* eccentricity */
double Lhat[3]; /* angular momentum vector */
double Ahat[3]; /* Runge-Lenz vector */
double t; /* time at which node was upsynced */
double mean_anom; /* mean anomaly when node was upsynced */
} fb_obj_t;
/* parameters for the K-S integrator */
typedef struct{
int nstar; /* number of actual stars */
int kstar; /* nstar*(nstar-1)/2, number of separations */
double *m; /* m[nstar] */
double *M; /* M[kstar] */
double **amat; /* amat[nstar][kstar] */
double **Tmat; /* Tmat[kstar][kstar] */
double Einit; /* initial energy used in integration scheme */
} fb_ks_params_t;
/* parameters for the non-regularized integrator */
typedef struct{
int nstar; /* number of actual stars */
double *m; /* m[nstar] */
} fb_nonks_params_t;
/* the hierarchy data structure */
typedef struct{
int nstarinit; /* initial number of stars (may not equal nstar if there are collisions) */
int nstar; /* number of stars */
int nobj; /* number of binary trees */
int *hi; /* hierarchical index array */
int *narr; /* narr[i] = number of hierarchical objects with i elements */
fb_obj_t *hier; /* memory location of hierarchy information */
fb_obj_t **obj; /* array of pointers to top nodes of binary trees */
} fb_hier_t;
/* input parameters */
typedef struct{
int ks; /* 0=no regularization, 1=K-S regularization */
double tstop; /* stopping time, in units of t_dyn */
int Dflag; /* 0=don't print to stdout, 1=print to stdout */
double dt; /* time interval between printouts will always be greater than this value */
double tcpustop; /* cpu stopping time, in units of seconds */
double absacc; /* absolute accuracy of the integrator */
double relacc; /* relative accuracy of the integrator */
int ncount; /* number of integration steps between each call to fb_classify() */
double tidaltol; /* tidal tolerance */
char firstlogentry[FB_MAX_LOGENTRY_LENGTH]; /* first entry to put in printout log */
double fexp; /* expansion factor for a merger product: R = f_exp (R_1+R_2) */
} fb_input_t;
/* return parameters */
typedef struct{
long count; /* number of integration steps */
int retval; /* return value; 1=success, 0=failure */
long iclassify; /* number of times classify was called */
double tcpu; /* cpu time taken */
double DeltaE; /* change in energy */
double DeltaEfrac; /* change in energy, as a fraction of initial energy */
double DeltaL; /* change in ang. mom. */
double DeltaLfrac; /* change in ang. mom., as a fraction of initial ang. mom. */
double Rmin; /* minimum distance of close approach during interaction */
int Rmin_i; /* index of star i participating in minimum close approach */
int Rmin_j; /* index of star j participating in minimum close approach */
int Nosc; /* number of oscillations of the quantity s^2 (McMillan & Hut 1996) (Nosc=Nmin-1, so resonance if Nosc>=1) */
} fb_ret_t;
/* fewbody.c */
fb_ret_t fewbody(fb_input_t input, fb_hier_t *hier, double *t);
/* fewbody_classify.c */
int fb_classify(fb_hier_t *hier, double t, double tidaltol);
int fb_is_stable(fb_obj_t *obj);
int fb_is_stable_binary(fb_obj_t *obj);
int fb_is_stable_triple(fb_obj_t *obj);
int fb_is_stable_quad(fb_obj_t *obj);
int fb_mardling(fb_obj_t *obj, int ib, int is);
/* fewbody_coll.c */
int fb_is_collision(double r, double R1, double R2);
int fb_collide(fb_hier_t *hier, double f_exp);
void fb_merge(fb_obj_t *obj1, fb_obj_t *obj2, int nstarinit, double f_exp);
/* fewbody_hier.c */
void fb_malloc_hier(fb_hier_t *hier);
void fb_init_hier(fb_hier_t *hier);
void fb_free_hier(fb_hier_t hier);
void fb_trickle(fb_hier_t *hier, double t);
void fb_elkcirt(fb_hier_t *hier, double t);
int fb_create_indices(int *hi, int nstar);
int fb_n_hier(fb_obj_t *obj);
char *fb_sprint_hier(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH]);
char *fb_sprint_hier_hr(fb_hier_t hier, char string[FB_MAX_STRING_LENGTH]);
void fb_upsync(fb_obj_t *obj, double t);
void fb_randorient(fb_obj_t *obj, gsl_rng *rng);
void fb_downsync(fb_obj_t *obj, double t);
void fb_objcpy(fb_obj_t *obj1, fb_obj_t *obj2);
/* fewbody_int.c */
void fb_malloc_ks_params(fb_ks_params_t *ks_params);
void fb_init_ks_params(fb_ks_params_t *ks_params, fb_hier_t hier);
void fb_free_ks_params(fb_ks_params_t ks_params);
void fb_malloc_nonks_params(fb_nonks_params_t *nonks_params);
void fb_init_nonks_params(fb_nonks_params_t *nonks_params, fb_hier_t hier);
void fb_free_nonks_params(fb_nonks_params_t nonks_params);
/* fewbody_io.c */
void fb_print_version(FILE *stream);
void fb_print_story(fb_obj_t *star, int nstar, double t, char *logentry);
/* fewbody_isolate.c */
int fb_collapse(fb_hier_t *hier, double t, double tidaltol);
int fb_expand(fb_hier_t *hier, double t, double tidaltol);
/* fewbody_ks.c */
double fb_ks_dot(double x[4], double y[4]);
double fb_ks_mod(double x[4]);
void fb_calc_Q(double q[4], double Q[4]);
void fb_calc_ksmat(double Q[4], double Qmat[4][4]);
void fb_calc_amat(double **a, int nstar, int kstar);
void fb_calc_Tmat(double **a, double *m, double **T, int nstar, int kstar);
int fb_ks_func(double s, const double *y, double *f, void *params);
double fb_ks_Einit(const double *y, fb_ks_params_t params);
void fb_euclidean_to_ks(fb_obj_t **star, double *y, int nstar, int kstar);
void fb_ks_to_euclidean(double *y, fb_obj_t **star, int nstar, int kstar);
/* fewbody_nonks.c */
int fb_nonks_func(double t, const double *y, double *f, void *params);
int fb_nonks_jac(double t, const double *y, double *dfdy, double *dfdt, void *params);
void fb_euclidean_to_nonks(fb_obj_t **star, double *y, int nstar);
void fb_nonks_to_euclidean(double *y, fb_obj_t **star, int nstar);
/* fewbody_scat.c */
void fb_init_scattering(fb_obj_t *obj0, fb_obj_t *obj1, double vinf, double b, double rtid);
void fb_normalize(fb_hier_t *hier, fb_units_t units);
/* fewbody_utils.c */
double *fb_malloc_vector(int n);
double **fb_malloc_matrix(int nr, int nc);
void fb_free_vector(double *v);
void fb_free_matrix(double **m);
double fb_sqr(double x);
double fb_cub(double x);
double fb_dot(double x[3], double y[3]);
double fb_mod(double x[3]);
int fb_cross(double x[3], double y[3], double z[3]);
int fb_angmom(fb_obj_t *star, int nstar, double L[3]);
void fb_angmomint(fb_obj_t *star, int nstar, double L[3]);
double fb_einttot(fb_obj_t *star, int nstar);
double fb_petot(fb_obj_t *star, int nstar);
double fb_ketot(fb_obj_t *star, int nstar);
double fb_outerpetot(fb_obj_t **obj, int nobj);
double fb_outerketot(fb_obj_t **obj, int nobj);
double fb_kepler(double e, double mean_anom);
double fb_keplerfunc(double mean_anom, void *params);
double fb_reltide(fb_obj_t *bin, fb_obj_t *single, double r);
/* fewbody_ui.c */
int fbui_new_hier(fb_hier_t *hier, int n);
int fbui_delete_hier(fb_hier_t *hier);
fb_obj_t *fbui_hierarchy_element(fb_hier_t *hier, int n, int m);
fb_obj_t *fbui_hierarchy_single(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_binary(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_triple(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_quadruple(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_quintuple(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_sextuple(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_septuple(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_octuple(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_nonuple(fb_hier_t *hier, int m);
fb_obj_t *fbui_hierarchy_decuple(fb_hier_t *hier, int m);
int fbui_make_pair(fb_obj_t *parentobj, fb_obj_t *obj1, fb_obj_t *obj2);
int fbui_initialize_single(fb_obj_t *single, long id, char idstring[FB_MAX_STRING_LENGTH]);
fb_obj_t *fbui_tree(fb_hier_t *hier, int n);
int fbui_obj_ncoll_set(fb_obj_t *obj, int ncoll);
int fbui_obj_ncoll_get(fb_obj_t *obj);
int fbui_obj_id_set(fb_obj_t *obj, int index, long id);
long fbui_obj_id_get(fb_obj_t *obj, int index);
int fbui_obj_idstring_set(fb_obj_t *obj, char idstring[FB_MAX_STRING_LENGTH]);
char *fbui_obj_idstring_get(fb_obj_t *obj);
int fbui_obj_mass_set(fb_obj_t *obj, double mass);
double fbui_obj_mass_get(fb_obj_t *obj);
int fbui_obj_radius_set(fb_obj_t *obj, double radius);
double fbui_obj_radius_get(fb_obj_t *obj);
int fbui_obj_Eint_set(fb_obj_t *obj, double Eint);
double fbui_obj_Eint_get(fb_obj_t *obj);
int fbui_obj_Lint_set(fb_obj_t *obj, double Lint[3]);
int fbui_obj_Linti_set(fb_obj_t *obj, double Lint0, double Lint1, double Lint2);
double *fbui_obj_Lint_get(fb_obj_t *obj);
int fbui_obj_x_set(fb_obj_t *obj, double x[3]);
int fbui_obj_xi_set(fb_obj_t *obj, double x0, double x1, double x2);
double *fbui_obj_x_get(fb_obj_t *obj);
int fbui_obj_v_set(fb_obj_t *obj, double v[3]);
int fbui_obj_vi_set(fb_obj_t *obj, double v0, double v1, double v2);
double *fbui_obj_v_get(fb_obj_t *obj);
int fbui_obj_n_set(fb_obj_t *obj, int n);
int fbui_obj_n_get(fb_obj_t *obj);
int fbui_obj_obj_set(fb_obj_t *obj, int i, fb_obj_t *objtopointto);
int fbui_obj_left_child_set(fb_obj_t *obj, fb_obj_t *objtopointto);
int fbui_obj_right_child_set(fb_obj_t *obj, fb_obj_t *objtopointto);
fb_obj_t *fbui_obj_obj_get(fb_obj_t *obj, int i);
fb_obj_t *fbui_obj_left_child_get(fb_obj_t *obj);
fb_obj_t *fbui_obj_right_child_get(fb_obj_t *obj);
int fbui_obj_a_set(fb_obj_t *obj, double a);
double fbui_obj_a_get(fb_obj_t *obj);
int fbui_obj_e_set(fb_obj_t *obj, double e);
double fbui_obj_e_get(fb_obj_t *obj);
int fbui_obj_Lhat_set(fb_obj_t *obj, double Lhat[3]);
int fbui_obj_Lhati_set(fb_obj_t *obj, double Lhat0, double Lhat1, double Lhat2);
double *fbui_obj_Lhat_get(fb_obj_t *obj);
int fbui_obj_Ahat_set(fb_obj_t *obj, double Ahat[3]);
int fbui_obj_Ahati_set(fb_obj_t *obj, double Ahat0, double Ahat1, double Ahat2);
double *fbui_obj_Ahat_get(fb_obj_t *obj);
int fbui_obj_t_set(fb_obj_t *obj, double t);
double fbui_obj_t_get(fb_obj_t *obj);
int fbui_obj_mean_anom_set(fb_obj_t *obj, double mean_anom);
double fbui_obj_mean_anom_get(fb_obj_t *obj);
/* macros */
/* The variadic macro syntax here conforms to the C99 standard, but for some
reason won't compile on Mac OSX with gcc. */
/* #define fb_dprintf(...) if (fb_debug) fprintf(stderr, __VA_ARGS__) */
/* The variadic macro syntax here is the old gcc standard, and compiles on
Mac OSX with gcc. */
#define fb_dprintf(args...) if (fb_debug) fprintf(stderr, args)
#define FB_MIN(a, b) ((a)<=(b)?(a):(b))
#define FB_MAX(a, b) ((a)>=(b)?(a):(b))
#define FB_DELTA(i, j) ((i)==(j)?1:0)
#define FB_KS_K(i, j, nstar) ((i)*(nstar)-((i)+1)*((i)+2)/2+(j))
/* there is just one global variable */
extern int fb_debug;
#endif /* fewbody.h */
| {
"alphanum_fraction": 0.7469591994,
"avg_line_length": 41.6346153846,
"ext": "h",
"hexsha": "a4b4a5dcef440b54f73a6fa2831aca74a7887d88",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_forks_repo_licenses": [
"PSF-2.0"
],
"max_forks_repo_name": "gnodvi/cosmos",
"max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_licenses": [
"PSF-2.0"
],
"max_issues_repo_name": "gnodvi/cosmos",
"max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody.h",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_stars_repo_licenses": [
"PSF-2.0"
],
"max_stars_repo_name": "gnodvi/cosmos",
"max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3867,
"size": 12990
} |
/* Copyright (C) 2010-2021 Barcelona Supercomputing Center and University of
* Illinois at Urbana-Champaign
* SPDX-License-Identifier: MIT
*/
/** \file
* \brief Wrapper routines for GSL random number functions.
*/
/* clang-format off */
#include <gsl/gsl_errno.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <stdio.h>
#include <time.h>
/** \brief Private internal-use variable to store the random number
* generator.
*/
static gsl_rng *camp_rand_gsl_rng = NULL;
/** \brief Result code indicating successful completion.
*/
#define CAMP_RAND_GSL_SUCCESS 0
/** \brief Result code indicating initialization failure.
*/
#define CAMP_RAND_GSL_INIT_FAIL 1
/** \brief Result code indicating the generator was not initialized
* when it should have been.
*/
#define CAMP_RAND_GSL_NOT_INIT 2
/** \brief Result code indicating the generator was already
* initialized when an initialization was attempted.
*/
#define CAMP_RAND_GSL_ALREADY_INIT 3
/** \brief Initialize the random number generator with the given seed.
*
* This must be called before any other GSL random number functions
* are called.
*
* \param seed The random seed to use.
* \return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.
* \sa camp_rand_finalize_gsl() to cleanup the generator.
*/
int camp_srand_gsl(int seed)
{
if (camp_rand_gsl_rng) {
return CAMP_RAND_GSL_ALREADY_INIT;
}
gsl_set_error_handler_off(); // turn off automatic error handling
camp_rand_gsl_rng = gsl_rng_alloc(gsl_rng_mt19937);
if (camp_rand_gsl_rng == NULL) {
return CAMP_RAND_GSL_INIT_FAIL;
}
gsl_rng_set(camp_rand_gsl_rng, seed);
return CAMP_RAND_GSL_SUCCESS;
}
/** \brief Cleanup and deallocate the random number generator.
*
* This must be called after camp_srand_gsl().
*
* \return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.
*/
int camp_rand_finalize_gsl()
{
if (!camp_rand_gsl_rng) {
return CAMP_RAND_GSL_NOT_INIT;
}
gsl_rng_free(camp_rand_gsl_rng);
camp_rand_gsl_rng = NULL;
return CAMP_RAND_GSL_SUCCESS;
}
/** \brief Generate a uniform random number in \f$[0,1)\f$.
*
* \param harvest A pointer to the generated random number.
* \return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.
*/
int camp_rand_gsl(double *harvest)
{
if (!camp_rand_gsl_rng) {
return CAMP_RAND_GSL_NOT_INIT;
}
*harvest = gsl_rng_uniform(camp_rand_gsl_rng);
return CAMP_RAND_GSL_SUCCESS;
}
/** \brief Generate a uniform random integer in \f$[1,n]\f$.
*
* \param n The upper limit of the random integer.
* \param harvest A pointer to the generated random number.
* \return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.
*/
int camp_rand_int_gsl(int n, int *harvest)
{
if (!camp_rand_gsl_rng) {
return CAMP_RAND_GSL_NOT_INIT;
}
*harvest = gsl_rng_uniform_int(camp_rand_gsl_rng, n) + 1;
return CAMP_RAND_GSL_SUCCESS;
}
/** \brief Generate a normally-distributed random number.
*
* \param mean The mean of the distribution.
* \param stddev The standard deviation of the distribution.
* \param harvest A pointer to the generated random number.
* \return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.
*/
int camp_rand_normal_gsl(double mean, double stddev, double *harvest)
{
if (!camp_rand_gsl_rng) {
return CAMP_RAND_GSL_NOT_INIT;
}
*harvest = gsl_ran_gaussian(camp_rand_gsl_rng, stddev) + mean;
return CAMP_RAND_GSL_SUCCESS;
}
/** \brief Generate a Poisson-distributed random integer.
*
* \param mean The mean of the distribution.
* \param harvest A pointer to the generated random number.
* \return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.
*/
int camp_rand_poisson_gsl(double mean, int *harvest)
{
if (!camp_rand_gsl_rng) {
return CAMP_RAND_GSL_NOT_INIT;
}
*harvest = gsl_ran_poisson(camp_rand_gsl_rng, mean);
return CAMP_RAND_GSL_SUCCESS;
}
/** \brief Generate a Binomial-distributed random integer.
*
* \param n The sample size for the distribution.
* \param p The sample probability for the distribution.
* \param harvest A pointer to the generated random number.
* \return CAMP_RAND_GSL_SUCCESS on success, otherwise an error code.
*/
int camp_rand_binomial_gsl(int n, double p, int *harvest)
{
unsigned int u;
if (!camp_rand_gsl_rng) {
return CAMP_RAND_GSL_NOT_INIT;
}
u = n;
*harvest = gsl_ran_binomial(camp_rand_gsl_rng, p, u);
return CAMP_RAND_GSL_SUCCESS;
}
/* clang-format on */
| {
"alphanum_fraction": 0.697470207,
"avg_line_length": 30.4649681529,
"ext": "c",
"hexsha": "72fbff71413533f863891d19914b6865dbd13edd",
"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": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "open-atmos/camp",
"max_forks_repo_path": "src/rand_gsl.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3",
"max_issues_repo_issues_event_max_datetime": "2022-01-22T11:42:07.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-10-06T18:14:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "open-atmos/camp",
"max_issues_repo_path": "src/rand_gsl.c",
"max_line_length": 76,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "open-atmos/camp",
"max_stars_repo_path": "src/rand_gsl.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T05:32:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-05T21:35:20.000Z",
"num_tokens": 1193,
"size": 4783
} |
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
///@brief
///@file DenseMatrixMultiplication.h
#ifndef CORE_DATATYPES_DENSEMATRIXMULTIPLICATION_H
#define CORE_DATATYPES_DENSEMATRIXMULTIPLICATION_H
#if defined(HAVE_CBLAS)
#if defined(__APPLE__)
#include <vecLib/cblas.h>
#else
extern "C"{
#include <cblas.h>
}
#endif
#endif
namespace SCIRun {
template <typename T>
void
DenseMatrixGeneric<T>::mult(const ColumnMatrix& x, ColumnMatrix& b,
index_type beg, index_type end,
int spVec) const
{
ASSERTEQ(x.nrows(), this->ncols_);
ASSERTEQ(b.nrows(), this->nrows_);
if (beg == -1) beg = 0;
if (end == -1) end = this->nrows_;
#if defined(HAVE_CBLAS)
double ALPHA = 1.0;
double BETA = 0.0;
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, (end-beg),
1, this->ncols_, ALPHA, dataptr_+(beg*this->ncols_), this->ncols_,
x.get_data_pointer(), 1, BETA,
b.get_data_pointer()+beg, 1);
#else
double* xdata = x.get_data_pointer();
double* bdata = b.get_data_pointer();
size_type m8 = (this->ncols_)/8;
size_type m = (this->ncols_)-m8*8;
index_type i, j;
if(!spVec)
{
for (i=beg; i<end; i++)
{
double sum=0;
double* row=data[i];
double* xd=xdata;
for (j=0; j<m8; j++)
{
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
}
for (j=0; j<m; j++)
{
sum+=(*row)*(*xd);
row++; xd++;
}
(*bdata)=sum;
bdata++;
}
}
else
{
for (i=beg; i<end; i++) b[i]=0;
for (j=0; j<this->ncols_; j++)
{
if (x[j])
for (i=beg; i<end; i++)
{
b[i]+=data[i][j]*x[j];
}
}
}
#endif
}
template <typename T>
void
DenseMatrixGeneric<T>::multiply(ColumnMatrix& x, ColumnMatrix& b) const
{
index_type i, j;
double* xdata = x.get_data_pointer();
double* bdata = b.get_data_pointer();
size_type m8 = (this->ncols_)/8;
size_type m = (this->ncols_)-m8*8;
for (i=0; i<this->nrows_; i++)
{
double sum=0;
double* row = data[i];
double* xd = xdata;
for (j=0; j<m8; j++)
{
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
sum+=(*row)*(*xd);
row++; xd++;
}
for (j=0; j<m; j++)
{
sum+=(*row)*(*xd);
row++; xd++;
}
*bdata=sum;
bdata++;
}
}
template <typename T>
void
DenseMatrixGeneric<T>::mult_transpose(const ColumnMatrix& x, ColumnMatrix& b,
index_type beg, index_type end,
int spVec) const
{
// Compute At*x=b
ASSERT(x.nrows() == this->nrows_);
ASSERT(b.nrows() == this->ncols_);
if (beg == -1) beg = 0;
if (end == -1) end = this->ncols_;
index_type i, j;
if (!spVec)
{
for (i=beg; i<end; i++)
{
double sum=0;
for (j=0; j<this->nrows_; j++)
{
sum+=data[j][i]*x[j];
}
b[i]=sum;
}
}
else
{
for (i=beg; i<end; i++) b[i]=0;
for (j=0; j<this->nrows_; j++)
if (x[j])
{
double *row=data[j];
for (i=beg; i<end; i++)
b[i]+=row[i]*x[j];
}
}
}
template <typename T>
DenseMatrix*
DenseMatrixGeneric<T>::make_diagonal_from_column(const ColumnMatrix& column, size_type rows, size_type cols)
{
DenseMatrix* result = zero_matrix(rows, cols);
for (size_type i = 0; i < column.nrows(); ++i)
(*result)[i][i] = column[i];
return result;
}
} // End namespace SCIRun
#endif
| {
"alphanum_fraction": 0.5581704308,
"avg_line_length": 23.2114537445,
"ext": "h",
"hexsha": "eb127bec2ede780e3660e9ee136a5c3fc23a36da",
"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": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "mhansen1/SCIRun",
"max_forks_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrixMultiplication.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "mhansen1/SCIRun",
"max_issues_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrixMultiplication.h",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "mhansen1/SCIRun",
"max_stars_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrixMultiplication.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1558,
"size": 5269
} |
#pragma once
#include <gsl/gsl>
#include <codecvt>
#include <locale>
#include <string>
#ifdef _MSC_VER
#include <string_view>
#else
// llvm-libc++ included with Android NDK r15c hasn't yet promoted the C++1z library fundamentals
// technical specification to the final C++17 specification for string_view.
// Force promote the types we need up into the std namespace.
#include <experimental/string_view>
namespace std
{
using string_view = experimental::string_view;
using wstring_view = experimental::wstring_view;
}
#endif
namespace arcana
{
inline std::string utf16_to_utf8(gsl::cwzstring<> input)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(input);
}
inline std::wstring utf8_to_utf16(gsl::czstring<> input)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.from_bytes(input);
}
inline std::string utf16_to_utf8(std::wstring_view input)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(input.data(), input.data() + input.size());
}
inline std::wstring utf8_to_utf16(std::string_view input)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(input.data(), input.data() + input.size());
}
struct string_compare
{
using is_transparent = std::true_type;
bool operator()(gsl::cstring_span<> a, gsl::cstring_span<> b) const
{
return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());
}
bool operator()(gsl::czstring_span<> a, gsl::czstring_span<> b) const
{
return (*this)(a.as_string_span(), b.as_string_span());
}
bool operator()(gsl::czstring<> a, gsl::czstring<> b) const
{
return strcmp(a, b) < 0;
}
};
}
| {
"alphanum_fraction": 0.6566018424,
"avg_line_length": 28.7352941176,
"ext": "h",
"hexsha": "1b904e395f912b86fa7dd067bda198ca07208736",
"lang": "C",
"max_forks_count": 18,
"max_forks_repo_forks_event_max_datetime": "2021-12-26T14:24:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-09T23:07:44.000Z",
"max_forks_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrei-datcu/arcana.cpp",
"max_forks_repo_path": "Source/Shared/arcana/string.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5",
"max_issues_repo_issues_event_max_datetime": "2022-01-03T20:12:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-08-13T03:18:30.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrei-datcu/arcana.cpp",
"max_issues_repo_path": "Source/Shared/arcana/string.h",
"max_line_length": 96,
"max_stars_count": 65,
"max_stars_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrei-datcu/arcana.cpp",
"max_stars_repo_path": "Source/Shared/arcana/string.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T15:05:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-08T01:53:22.000Z",
"num_tokens": 473,
"size": 1954
} |
/// @brief Hyperion logging facilities.
///
/// Hyperion's logging facilities are robust and composable.
/// Behavioral (Policy) configuration is configurable at compile time with via template parameters,
/// and output configuration is configurable by supplying the desired `Sink`s on creation
#pragma once
#include <Hyperion/BasicTypes.h>
#include <Hyperion/FmtIO.h>
#include <Hyperion/Logger.h>
#include <Hyperion/Option.h>
#include <Hyperion/logging/Config.h>
#include <Hyperion/logging/Entry.h>
#include <Hyperion/logging/Queue.h>
#include <Hyperion/logging/Sink.h>
#include <Hyperion/synchronization/ReadWriteLock.h>
#include <atomic>
#include <chrono>
#include <filesystem>
#include <gsl/gsl>
#include <iostream>
#include <memory>
#include <mutex>
#include <system_error>
#include <thread>
namespace hyperion {
/// @brief Possible Error categories that can occur when using the logger
enum class LoggerErrorCategory : i8 {
/// @brief No Error occurred
Success = 0,
/// @brief failed to queue the entry for logging
QueueingError,
/// @brief the requested log level for the entry is
/// lower than the minimum level for the logger
LogLevelError,
LoggerNotInitialized,
Unknown = -1
};
/// @brief Alias for the Error type we might receive from the internal queue
using QueueError = LoggingQueueError;
class LoggerErrorDomain {
public:
using value_type = LoggerErrorCategory;
using LoggerStatusCode = error::StatusCode<LoggerErrorDomain>;
using LoggerErrorCode = error::ErrorCode<LoggerErrorDomain>;
static const constexpr char (&UUID)[error::num_chars_in_uuid] // NOLINT
= "045dd371-9552-4ce1-bd4d-8e95b654fbe0";
static constexpr u64 ID = error::parse_uuid_from_string(UUID);
constexpr LoggerErrorDomain() noexcept = default;
explicit constexpr LoggerErrorDomain(u64 uuid) noexcept : m_uuid(uuid) {
}
explicit constexpr LoggerErrorDomain(const error::UUIDString auto& uuid) noexcept
: m_uuid(error::parse_uuid_from_string(uuid)) {
}
constexpr LoggerErrorDomain(const LoggerErrorDomain&) noexcept = default;
constexpr LoggerErrorDomain(LoggerErrorDomain&&) noexcept = default;
constexpr ~LoggerErrorDomain() noexcept = default;
[[nodiscard]] inline constexpr auto id() const noexcept -> u64 {
return m_uuid;
}
[[nodiscard]] inline constexpr auto name() const noexcept -> std::string_view { // NOLINT
return "LoggerErrorDomain";
}
[[nodiscard]] inline constexpr auto message(value_type code) // NOLINT
const noexcept -> std::string_view {
if(code == value_type::Success) {
return "Success";
}
else if(code == value_type::QueueingError) {
return "Logger failed to queue log entry.";
}
else if(code == value_type::LogLevelError) {
return "Requested log level for entry is lower than minimum level configured for "
"logger.";
}
else {
return "Unknown Logger error.";
}
}
[[nodiscard]] inline constexpr auto message(const LoggerStatusCode& code) // NOLINT
const noexcept -> std::string_view {
return message(code.code());
}
[[nodiscard]] inline constexpr auto is_error(const LoggerStatusCode& code) // NOLINT
const noexcept -> bool {
return code.code() != value_type::Success;
}
[[nodiscard]] inline constexpr auto is_success(const LoggerStatusCode& code) // NOLINT
const noexcept -> bool {
return code.code() == value_type::Success;
}
template<typename Domain2>
[[nodiscard]] inline constexpr auto
are_equivalent(const LoggerStatusCode& lhs,
const error::StatusCode<Domain2>& rhs) const noexcept -> bool {
if constexpr(concepts::Same<LoggerStatusCode, error::StatusCode<Domain2>>) {
return lhs.code() == rhs.code();
}
else {
return false;
}
}
[[nodiscard]] inline constexpr auto as_generic_code(const LoggerStatusCode& code) // NOLINT
const noexcept -> error::GenericStatusCode {
if(code.code() == value_type::Success || code.code() == value_type::Unknown) {
return make_status_code(static_cast<error::Errno>(code.code()));
}
else {
return make_status_code(error::Errno::Unknown);
}
}
[[nodiscard]] inline static constexpr auto success_value() noexcept -> value_type {
return value_type::Success;
}
template<typename Domain>
friend inline constexpr auto
operator==(const LoggerErrorDomain& lhs, const Domain& rhs) noexcept -> bool {
return rhs.id() == lhs.id();
}
template<typename Domain>
friend inline constexpr auto
operator!=(const LoggerErrorDomain& lhs, const Domain& rhs) noexcept -> bool {
return rhs.id() != lhs.id();
}
constexpr auto operator=(const LoggerErrorDomain&) noexcept -> LoggerErrorDomain& = default;
constexpr auto operator=(LoggerErrorDomain&&) noexcept -> LoggerErrorDomain& = default;
private:
u64 m_uuid = ID;
};
using LoggerStatusCode = LoggerErrorDomain::LoggerStatusCode;
using LoggerErrorCode = LoggerErrorDomain::LoggerErrorCode;
using LoggerError = error::Error<LoggerErrorDomain>;
} // namespace hyperion
template<>
inline constexpr auto
make_status_code_domain<hyperion::LoggerErrorDomain>() noexcept -> hyperion::LoggerErrorDomain {
return {};
}
namespace hyperion {
static_assert(error::StatusCodeDomain<LoggerErrorDomain>);
template<>
struct error::status_code_enum_info<LoggerErrorCategory> {
using domain_type = LoggerErrorDomain;
static constexpr bool value = true;
};
IGNORE_PADDING_START
namespace detail {
#if HYPERION_HAS_JTHREAD
using thread = std::jthread;
#else
using thread = std::thread;
#endif
static constexpr fmt::text_style MESSAGE_STYLE = fmt::fg(fmt::color::white);
static constexpr fmt::text_style TRACE_STYLE = fmt::fg(fmt::color::steel_blue);
static constexpr fmt::text_style INFO_STYLE
= fmt::fg(fmt::color::light_green) | fmt::emphasis::italic;
static constexpr fmt::text_style WARN_STYLE
= fmt::fg(fmt::color::orange) | fmt::emphasis::bold;
static constexpr fmt::text_style ERROR_STYLE
= fmt::fg(fmt::color::red) | fmt::emphasis::bold;
IGNORE_UNNEEDED_INTERNAL_DECL_START
[[nodiscard]] inline static auto create_time_stamp() noexcept -> std::string {
return fmt::format("[{:%Y-%m-%d|%H-%M-%S}]", fmt::localtime(std::time(nullptr)));
}
inline static auto
create_default_sinks() noexcept -> Sinks { // NOLINT(bugprone-exception-escape)
auto file = FileSink::create_file();
auto file_sink = make_sink<FileSink>(file.expect("Failed to create default log file"));
auto stdout_sink = make_sink<StdoutSink<>>();
auto stderr_sink = make_sink<StderrSink<>>();
return Sinks({std::move(file_sink), std::move(stdout_sink), std::move(stderr_sink)});
}
IGNORE_UNNEEDED_INTERNAL_DECL_STOP
IGNORE_UNUSED_TEMPLATES_START
template<LogLevel Level, typename... Args>
inline static auto
format_entry(Option<usize> thread_id, // NOLINT(bugprone-exception-escape)
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept -> Entry {
const auto timestamp = create_time_stamp();
const auto entry = fmt::format(format_string, std::forward<Args>(args)...);
const auto id = thread_id.is_some() ?
thread_id.unwrap() :
std::hash<std::thread::id>()(std::this_thread::get_id());
std::string log_type;
if constexpr(Level == LogLevel::MESSAGE) {
log_type = "MESSAGE"s;
}
else if constexpr(Level == LogLevel::TRACE) {
log_type = "TRACE"s;
}
else if constexpr(Level == LogLevel::INFO) {
log_type = "INFO"s;
}
else if constexpr(Level == LogLevel::WARN) {
log_type = "WARN"s;
}
else if constexpr(Level == LogLevel::ERROR) {
log_type = "ERROR"s;
}
return make_entry<entry_level_t<Level>>("{0} [Thread ID: {1}] [{2}]: {3}",
timestamp,
id,
log_type,
entry);
}
IGNORE_UNUSED_TEMPLATES_STOP
template<LogLevel MinimumLevel = DefaultLogParameters::minimum_level,
LogThreadingPolicy ThreadingPolicy = DefaultLogParameters::threading_policy,
LogAsyncPolicy AsyncPolicy = DefaultLogParameters::async_policy,
usize QueueSize = DefaultLogParameters::queue_size>
class LogBase;
template<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy>
class LogBase<MinimumLevel, LogThreadingPolicy::SingleThreaded, AsyncPolicy> {
public:
static constexpr auto THREADING_POLICY = LogThreadingPolicy::SingleThreaded;
static constexpr auto ASYNC_POLICY = AsyncPolicy;
static constexpr auto MINIMUM_LEVEL = MinimumLevel;
LogBase() : LogBase(create_default_sinks()) {
}
explicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)) {
}
LogBase(const LogBase&) = delete;
LogBase(LogBase&&) noexcept = default;
~LogBase() noexcept = default;
template<LogLevel Level, typename... Args>
inline auto log(Option<usize> thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept -> void {
const auto message = format_entry<Level>(std::move(thread_id),
std::move(format_string),
std::forward<Args>(args)...);
std::for_each(m_sinks.begin(), m_sinks.end(), [&](Sink& sink) noexcept -> void {
sink.sink(message);
});
}
template<LogLevel, typename... Args>
inline auto
log(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept -> void {
return log(None(), std::move(format_string), std::forward<Args>(args)...);
}
inline auto flush() const noexcept -> void {
// intentionally does nothing
}
auto operator=(const LogBase&) -> LogBase& = delete;
auto operator=(LogBase&&) noexcept -> LogBase& = default;
private:
Sinks m_sinks;
};
template<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy, usize QueueSize>
class LogBase<MinimumLevel,
LogThreadingPolicy::SingleThreadedAsync,
AsyncPolicy,
QueueSize> {
public:
static constexpr auto THREADING_POLICY = LogThreadingPolicy::SingleThreadedAsync;
static constexpr auto ASYNC_POLICY = AsyncPolicy;
static constexpr auto MINIMUM_LEVEL = MinimumLevel;
static constexpr usize QUEUE_SIZE = QueueSize;
LogBase() : LogBase(create_default_sinks()) {
}
explicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)), m_queue() {
#if HYPERION_HAS_JTHREAD
m_logging_thread = detail::thread(
[&](const std::stop_token& token) { message_thread_function(token); });
#else
m_logging_thread = detail::thread([&]() { message_thread_function(); });
#endif
}
LogBase(const LogBase&) = delete;
LogBase(LogBase&& logger) noexcept {
std::atomic_thread_fence(std::memory_order_acquire);
logger.request_thread_stop();
logger.m_logging_thread.join();
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
m_sinks = std::move(logger.m_sinks);
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
m_queue = std::move(logger.m_queue);
#if HYPERION_HAS_JTHREAD
m_logging_thread = detail::thread(
[&](const std::stop_token& token) { message_thread_function(token); });
#else
m_logging_thread = detail::thread([&]() { message_thread_function(); });
#endif
std::atomic_thread_fence(std::memory_order_release);
}
~LogBase() noexcept {
request_thread_stop();
m_logging_thread.join();
}
template<LogLevel Level, typename... Args>
inline auto log(Option<usize> thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
if constexpr(Level >= MINIMUM_LEVEL && MINIMUM_LEVEL != LogLevel::DISABLED) {
auto message = format_entry<Level>(std::move(thread_id),
std::move(format_string),
std::forward<Args>(args)...);
if constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {
return log_dropping(std::move(message));
}
else if constexpr(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {
log_flushing(std::move(message));
}
else {
log_overwriting(std::move(message));
}
}
else {
ignore(format_string, std::forward<Args>(args)...);
return Err(LoggerError(make_error_code(LoggerErrorCategory::LogLevelError)));
}
}
template<LogLevel, typename... Args>
inline auto log(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return log(None(), std::move(format_string), std::forward<Args>(args)...);
}
inline auto flush() noexcept -> void {
m_flush.store(true);
}
auto operator=(const LogBase&) -> LogBase& = delete;
auto operator=(LogBase&& logger) noexcept -> LogBase& {
std::atomic_thread_fence(std::memory_order_acquire);
if(this == &logger) {
return *this;
}
logger.request_thread_stop();
logger.m_logging_thread.join();
m_sinks = std::move(logger.m_sinks);
m_queue = std::move(logger.m_queue);
std::atomic_thread_fence(std::memory_order_release);
return *this;
}
private:
[[nodiscard]] inline static consteval auto get_queue_policy() noexcept -> QueuePolicy {
if constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull
|| ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull)
{
return QueuePolicy::ErrWhenFull;
}
else {
return QueuePolicy::OverwriteWhenFull;
}
}
using Queue = LoggingQueue<Entry, get_queue_policy(), QUEUE_SIZE>;
Sinks m_sinks;
Queue m_queue;
std::atomic_bool m_flush = false;
#if !HYPERION_HAS_JTHREAD
std::atomic_bool m_exit_flag = false;
#endif
detail::thread m_logging_thread;
inline auto request_thread_stop() noexcept -> void {
#if HYPERION_HAS_JTHREAD
ignore(m_logging_thread.request_stop());
#else
m_exit_flag.store(true);
#endif
}
inline auto log_dropping(Entry&& message) noexcept -> Result<bool, LoggerError>
requires(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {
return m_queue.push(std::move(message))
.map_err([]([[maybe_unused]] const QueueError& error) {
return LoggerError(LoggerErrorCategory::QueueingError);
});
}
inline auto log_overwriting(Entry&& message) noexcept
-> void requires(ASYNC_POLICY == LogAsyncPolicy::OverwriteWhenFull) {
m_queue.push(std::move(message));
}
inline auto log_flushing(Entry&& message) noexcept
-> void requires(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {
if(m_queue.full()) {
m_flush.store(true);
}
const auto& mess = message;
while(!m_queue.push(mess)) {
}
}
inline auto try_read() noexcept -> Result<Entry, QueueError> {
return m_queue.read();
}
#if HYPERION_HAS_JTHREAD
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
inline auto message_thread_function(const std::stop_token& token) noexcept -> void {
while(!token.stop_requested()) {
#else
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
inline auto message_thread_function() noexcept -> void {
while(!m_exit_flag.load()) {
#endif
auto res = try_read();
if(res) {
const auto message = res.unwrap();
std::atomic_thread_fence(std::memory_order_acquire);
std::for_each(m_sinks.begin(),
m_sinks.end(),
[&](Sink& sink) noexcept -> void { sink.sink(message); });
std::atomic_thread_fence(std::memory_order_release);
}
if(m_flush.load()) {
m_flush.store(false);
do {
auto res2 = m_queue.read();
if(res2) {
const auto message = res2.unwrap();
std::atomic_thread_fence(std::memory_order_acquire);
std::for_each(
m_sinks.begin(),
m_sinks.end(),
[&](Sink& sink) noexcept -> void { sink.sink(message); });
std::atomic_thread_fence(std::memory_order_release);
}
else {
break;
}
} while(true);
}
}
do {
auto res2 = m_queue.read();
if(res2) {
const auto message = res2.unwrap();
std::atomic_thread_fence(std::memory_order_acquire);
std::for_each(m_sinks.begin(),
m_sinks.end(),
[&](Sink& sink) noexcept -> void { sink.sink(message); });
std::atomic_thread_fence(std::memory_order_release);
}
else {
break;
}
} while(true);
}
};
template<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy>
class LogBase<MinimumLevel, LogThreadingPolicy::MultiThreaded, AsyncPolicy> {
public:
static constexpr auto THREADING_POLICY = LogThreadingPolicy::MultiThreaded;
static constexpr auto ASYNC_POLICY = AsyncPolicy;
static constexpr auto MINIMUM_LEVEL = MinimumLevel;
LogBase() : LogBase(create_default_sinks()) {
}
explicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)) {
}
LogBase(const LogBase&) = delete;
LogBase(LogBase&&) noexcept = default;
~LogBase() noexcept = default;
template<LogLevel Level, typename... Args>
inline auto log(Option<usize> thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept -> void {
const auto message = format_entry<Level>(std::move(thread_id),
std::move(format_string),
std::forward<Args>(args)...);
{
auto sinks_guard = m_sinks.write();
std::for_each(sinks_guard->begin(),
sinks_guard->end(),
[&](Sink& sink) noexcept -> void { sink.sink(message); });
}
}
template<LogLevel, typename... Args>
inline auto
log(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept -> void {
return log(None(), std::move(format_string), std::forward<Args>(args)...);
}
inline auto flush() const noexcept -> void {
// intentionally does nothing
}
auto operator=(const LogBase&) -> LogBase& = delete;
auto operator=(LogBase&&) noexcept -> LogBase& = default;
private:
ReadWriteLock<Sinks> m_sinks;
};
template<LogLevel MinimumLevel, LogAsyncPolicy AsyncPolicy, usize QueueSize>
class LogBase<MinimumLevel,
LogThreadingPolicy::MultiThreadedAsync,
AsyncPolicy,
QueueSize> {
public:
static constexpr auto THREADING_POLICY = LogThreadingPolicy::MultiThreadedAsync;
static constexpr auto ASYNC_POLICY = AsyncPolicy;
static constexpr auto MINIMUM_LEVEL = MinimumLevel;
static constexpr usize QUEUE_SIZE = QueueSize;
LogBase() : LogBase(create_default_sinks()) {
}
explicit LogBase(Sinks&& sinks) noexcept : m_sinks(std::move(sinks)), m_queue() {
#if HYPERION_HAS_JTHREAD
m_logging_thread = detail::thread(
[&](const std::stop_token& token) { message_thread_function(token); });
#else
m_logging_thread = detail::thread([&]() { message_thread_function(); });
#endif
}
LogBase(const LogBase&) = delete;
LogBase(LogBase&& logger) noexcept {
std::atomic_thread_fence(std::memory_order_seq_cst);
logger.request_thread_stop();
logger.m_logging_thread.join();
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
m_sinks = std::move(logger.m_sinks);
// NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
m_queue = std::move(logger.m_queue);
#if HYPERION_HAS_JTHREAD
m_logging_thread = detail::thread(
[&](const std::stop_token& token) { message_thread_function(token); });
#else
m_logging_thread = detail::thread([&]() { message_thread_function(); });
#endif
std::atomic_thread_fence(std::memory_order_seq_cst);
}
~LogBase() noexcept {
request_thread_stop();
m_logging_thread.join();
}
template<LogLevel Level, typename... Args>
inline auto log(Option<usize> thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
if constexpr(Level >= MINIMUM_LEVEL && MINIMUM_LEVEL != LogLevel::DISABLED) {
auto message = format_entry<Level>(std::move(thread_id),
std::move(format_string),
std::forward<Args>(args)...);
if constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {
return log_dropping(std::move(message));
}
else if constexpr(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {
log_flushing(std::move(message));
}
else {
log_overwriting(std::move(message));
}
}
else {
ignore(format_string, std::forward<Args>(args)...);
return Err(LoggerError(make_error_code(LoggerErrorCategory::LogLevelError)));
}
}
template<LogLevel, typename... Args>
inline auto log(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return log(None(), std::move(format_string), std::forward<Args>(args)...);
}
inline auto flush() noexcept -> void {
m_flush.store(true);
}
auto operator=(const LogBase&) -> LogBase& = delete;
auto operator=(LogBase&& logger) noexcept -> LogBase& {
std::atomic_thread_fence(std::memory_order_seq_cst);
if(this == &logger) {
return *this;
}
logger.request_thread_stop();
logger.m_logging_thread.join();
m_sinks = std::move(logger.m_sinks);
m_queue = std::move(logger.m_queue);
std::atomic_thread_fence(std::memory_order_seq_cst);
return *this;
}
private:
[[nodiscard]] inline static consteval auto get_queue_policy() noexcept -> QueuePolicy {
if constexpr(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull
|| ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull)
{
return QueuePolicy::ErrWhenFull;
}
else {
return QueuePolicy::OverwriteWhenFull;
}
}
using Queue = LoggingQueue<Entry, get_queue_policy(), QUEUE_SIZE>;
Sinks m_sinks;
Queue m_queue;
std::atomic_bool m_flush = false;
#if !HYPERION_HAS_JTHREAD
std::atomic_bool m_exit_flag = false;
#endif
detail::thread m_logging_thread;
inline auto request_thread_stop() noexcept -> void {
std::atomic_thread_fence(std::memory_order_seq_cst);
#if HYPERION_HAS_JTHREAD
ignore(m_logging_thread.request_stop());
#else
m_exit_flag.store(true);
#endif
std::atomic_thread_fence(std::memory_order_seq_cst);
}
inline auto log_dropping(Entry&& message) noexcept -> Result<bool, LoggerError>
requires(ASYNC_POLICY == LogAsyncPolicy::DropWhenFull) {
std::atomic_thread_fence(std::memory_order_seq_cst);
auto res = m_queue.push(std::move(message))
.map_err([]([[maybe_unused]] const QueueError& error) {
return LoggerError(LoggerErrorCategory::QueueingError);
});
std::atomic_thread_fence(std::memory_order_seq_cst);
return res;
}
inline auto log_overwriting(Entry&& message) noexcept
-> void requires(ASYNC_POLICY == LogAsyncPolicy::OverwriteWhenFull) {
std::atomic_thread_fence(std::memory_order_seq_cst);
m_queue.push(std::move(message));
std::atomic_thread_fence(std::memory_order_seq_cst);
}
inline auto log_flushing(Entry&& message) noexcept
-> void requires(ASYNC_POLICY == LogAsyncPolicy::FlushWhenFull) {
std::atomic_thread_fence(std::memory_order_seq_cst);
if(m_queue.full()) {
m_flush.store(true);
}
const auto& mess = message;
while(!m_queue.push(mess)) {
}
std::atomic_thread_fence(std::memory_order_seq_cst);
}
inline auto try_read() noexcept -> Result<Entry, QueueError> {
std::atomic_thread_fence(std::memory_order_seq_cst);
return m_queue.read();
}
#if HYPERION_HAS_JTHREAD
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
inline auto message_thread_function(const std::stop_token& token) noexcept -> void {
while(!token.stop_requested()) {
#else
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
inline auto message_thread_function() noexcept -> void {
while(!m_exit_flag.load()) {
#endif
auto res = try_read();
if(res) {
std::atomic_thread_fence(std::memory_order_seq_cst);
const auto message = res.unwrap();
std::for_each(m_sinks.begin(),
m_sinks.end(),
[&](Sink& sink) noexcept -> void { sink.sink(message); });
std::atomic_thread_fence(std::memory_order_seq_cst);
}
if(m_flush.load()) {
m_flush.store(false);
do {
std::atomic_thread_fence(std::memory_order_seq_cst);
auto res2 = m_queue.read();
if(res2) {
const auto message = res2.unwrap();
std::for_each(
m_sinks.begin(),
m_sinks.end(),
[&](Sink& sink) noexcept -> void { sink.sink(message); });
std::atomic_thread_fence(std::memory_order_seq_cst);
}
else {
std::atomic_thread_fence(std::memory_order_seq_cst);
break;
}
} while(true);
}
}
do {
std::atomic_thread_fence(std::memory_order_seq_cst);
auto res2 = m_queue.read();
if(res2) {
const auto message = res2.unwrap();
std::for_each(m_sinks.begin(),
m_sinks.end(),
[&](Sink& sink) noexcept -> void { sink.sink(message); });
std::atomic_thread_fence(std::memory_order_seq_cst);
}
else {
std::atomic_thread_fence(std::memory_order_seq_cst);
break;
}
} while(true);
}
};
} // namespace detail
/// @brief Hyperion logging type for formatted logging.
/// Uses fmtlib/fmt for entry formatting and stylizing
///
/// @tparam LogParameters - The parameters for how this logger should operate
template<LoggerParametersType LogParameters = DefaultLogParameters>
class Logger : public detail::LogBase<LogParameters::minimum_level,
LogParameters::threading_policy,
LogParameters::async_policy,
LogParameters::queue_size> {
public:
static constexpr LogThreadingPolicy THREADING_POLICY = LogParameters::threading_policy;
static constexpr LogAsyncPolicy ASYNC_POLICY = LogParameters::async_policy;
static constexpr LogLevel MINIMUM_LEVEL = LogParameters::minimum_level;
static constexpr usize QUEUE_SIZE = LogParameters::queue_size;
using LogBase = detail::LogBase<LogParameters::minimum_level,
LogParameters::threading_policy,
LogParameters::async_policy,
LogParameters::queue_size>;
Logger() = default;
explicit Logger(Sinks&& sinks) noexcept : LogBase(std::move(sinks)) {
}
Logger(const Logger& logger) noexcept = delete;
Logger(Logger&& logger) noexcept = default;
~Logger() noexcept = default;
template<typename... Args>
inline auto message(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return this->template log<LogLevel::MESSAGE>(thread_id,
std::move(format_string),
std::forward<Args>(args)...);
}
template<typename... Args>
inline auto message(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return message(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto trace(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return this->template log<LogLevel::TRACE>(thread_id,
std::move(format_string),
std::forward<Args>(args)...);
}
template<typename... Args>
inline auto trace(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return trace(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto info(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return this->template log<LogLevel::INFO>(thread_id,
std::move(format_string),
std::forward<Args>(args)...);
}
template<typename... Args>
inline auto info(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return info(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto warn(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return this->template log<LogLevel::WARN>(thread_id,
std::move(format_string),
std::forward<Args>(args)...);
}
template<typename... Args>
inline auto warn(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return warn(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto error(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return this->template log<LogLevel::ERROR>(thread_id,
std::move(format_string),
std::forward<Args>(args)...);
}
template<typename... Args>
inline auto error(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return error(None(), std::move(format_string), std::forward<Args>(args)...);
}
auto operator=(const Logger& logger) noexcept -> Logger& = delete;
auto operator=(Logger&& logger) noexcept -> Logger& = default;
};
IGNORE_PADDING_STOP
IGNORE_UNUSED_TEMPLATES_START
#ifndef HYPERION_LOG_GLOBAL_LOGGER_PARAMETERS
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define HYPERION_LOG_GLOBAL_LOGGER_PARAMETERS DefaultLogParameters
#endif
struct GlobalLog {
using Parameters = HYPERION_LOG_GLOBAL_LOGGER_PARAMETERS;
static UniquePtr<Logger<Parameters>> GLOBAL_LOGGER; // NOLINT
[[nodiscard]] inline static auto
get_global_logger() noexcept -> Result<Logger<Parameters>*, LoggerError> {
if(GLOBAL_LOGGER == nullptr) {
return Err(LoggerError(LoggerErrorCategory::LoggerNotInitialized));
}
return Ok(GLOBAL_LOGGER.get());
}
inline static auto set_global_logger(Logger<Parameters>&& logger) noexcept -> void {
GLOBAL_LOGGER = make_unique<Logger<Parameters>>(std::move(logger));
}
template<typename... Args>
inline static auto MESSAGE(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return get_global_logger()
.expect("Global Logger not initialized!")
->message(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto
MESSAGE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return MESSAGE(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto TRACE(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return get_global_logger()
.expect("Global Logger not initialized!")
->trace(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto
TRACE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return TRACE(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto INFO(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return get_global_logger()
.expect("Global Logger not initialized!")
->info(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto
INFO(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return INFO(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto WARN(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return get_global_logger()
.expect("Global Logger not initialized!")
->warn(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto
WARN(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return WARN(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto ERROR(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return get_global_logger()
.expect("Global Logger not initialized!")
->error(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto
ERROR(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return ERROR(None(), std::move(format_string), std::forward<Args>(args)...);
}
};
UniquePtr<Logger<GlobalLog::Parameters>> GlobalLog::GLOBAL_LOGGER = nullptr; // NOLINT
template<typename... Args>
inline auto MESSAGE(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return GlobalLog::MESSAGE(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto
MESSAGE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return GlobalLog::MESSAGE(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto TRACE(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return GlobalLog::TRACE(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline static auto TRACE(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return GlobalLog::TRACE(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto INFO(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return GlobalLog::INFO(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto INFO(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return GlobalLog::INFO(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto WARN(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return GlobalLog::WARN(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto WARN(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return GlobalLog::WARN(None(), std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto ERROR(const Option<usize>& thread_id,
fmt::format_string<Args...>&& format_string,
Args&&... args) noexcept {
return GlobalLog::ERROR(thread_id, std::move(format_string), std::forward<Args>(args)...);
}
template<typename... Args>
inline auto ERROR(fmt::format_string<Args...>&& format_string, Args&&... args) noexcept {
return GlobalLog::ERROR(None(), std::move(format_string), std::forward<Args>(args)...);
}
IGNORE_UNUSED_TEMPLATES_STOP
} // namespace hyperion
| {
"alphanum_fraction": 0.6805702067,
"avg_line_length": 34.1196498054,
"ext": "h",
"hexsha": "a8a83c2a7ff9868dacf75122bb340d3dc24bd5cd",
"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": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "braxtons12/Hyperion-Utils",
"max_forks_repo_path": "include/Hyperion/Logger.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"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-Utils",
"max_issues_repo_path": "include/Hyperion/Logger.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "braxtons12/Hyperion-Utils",
"max_stars_repo_path": "include/Hyperion/Logger.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8604,
"size": 35075
} |
#ifndef CONTROLLERS_FEATURE_DETECTOR_CONTROLLER_H
#define CONTROLLERS_FEATURE_DETECTOR_CONTROLLER_H
#include <QObject>
#include <QAction>
#include <s3d/cv/features/match_finder_cv.h>
#include <s3d/cv/disparity/disparity_analyzer_stan.h>
#include <gsl/gsl>
class FeatureDetectorControllerBase : QObject {
Q_OBJECT
public:
FeatureDetectorControllerBase(gsl::not_null<QAction*> action,
gsl::not_null<s3d::DisparityAnalyzerSTAN*> disparityAnalyzer);
virtual std::unique_ptr<s3d::MatchFinderCV> createMatchFinder() = 0;
private:
QAction* m_action;
s3d::DisparityAnalyzerSTAN* m_disparityAnalyzer;
};
template <class T>
class FeatureDetectorController : public FeatureDetectorControllerBase {
FeatureDetectorController(gsl::not_null<QAction*> action,
gsl::not_null<s3d::DisparityAnalyzerSTAN*> disparityAnalyzer)
: FeatureDetectorControllerBase(action, disparityAnalyzer) {}
std::unique_ptr<s3d::MatchFinderCV> createMatchFinder() override {
return std::make_unique<T>();
}
};
#endif //CONTROLLERS_FEATURE_DETECTOR_CONTROLLER_H
| {
"alphanum_fraction": 0.7584973166,
"avg_line_length": 27.95,
"ext": "h",
"hexsha": "8ddcf142e539f731153a3f815775d2db7e5ebdb0",
"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/feature_detector_controller.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/feature_detector_controller.h",
"max_line_length": 94,
"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/feature_detector_controller.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": 265,
"size": 1118
} |
/**
* Created when : 2021.11.19;
* Last Update : 2021.12.02;
* Author : G. Marino <gcmarino404@gmail.com>;
* Notes : Header to the program Newton-main and correlated files.
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <complex.h>
#include <gsl/gsl_rng.h>
// Size of the visualization grid of area N*N;
#define N 1000
// How close the guessed root given the point used as guest must be to the real root of the equation, Tol is for Tolerance;
#define Tol 1e-8
#define iterations 1000
#define phi (1+sqrt(5))/2
// Struct used to create arrays of complex numbers which ones are the roots of the studied equation;
struct cmplx {
double real; // Real part of the given complex number;
double imag; // Imaginary part of the given complex number;
};
// Output (op) function, print the results into .dat archives;
void op(int *arr) {
int i, j;
FILE *file;
char name[100];
sprintf(name, "dat/Fractal.dat");
file = fopen(name, "w");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
fprintf(file, "%d ", arr[i*N+j]);
};
fprintf(file, "\n");
};
fclose(file);
};
| {
"alphanum_fraction": 0.586017282,
"avg_line_length": 28.9318181818,
"ext": "h",
"hexsha": "f8ac5c47a256e9183ee2b4cd1dd85f4021312351",
"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": "8509b9e7dbb285cc0c519125cf903ac7b7612fbe",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Gabriel-Marino/marino-Newton-Fractal",
"max_forks_repo_path": "fractals.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8509b9e7dbb285cc0c519125cf903ac7b7612fbe",
"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": "Gabriel-Marino/marino-Newton-Fractal",
"max_issues_repo_path": "fractals.h",
"max_line_length": 125,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8509b9e7dbb285cc0c519125cf903ac7b7612fbe",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Gabriel-Marino/marino-Newton-Fractal",
"max_stars_repo_path": "fractals.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 341,
"size": 1273
} |
#ifndef MOBULA_INC_CONTEXT_CPU_CTX_H_
#define MOBULA_INC_CONTEXT_CPU_CTX_H_
#define MOBULA_KERNEL void
#define MOBULA_DEVICE
#include <algorithm>
#include <cmath>
#include <cstring>
#include <mutex>
#include <thread>
#include "../ctypes.h"
#include "./common.h"
namespace mobula {
#if USING_CBLAS
#include <cblas.h>
inline void blas_gemm(const int axis, const bool tA, const bool tB, const int M,
const int N, const int K, const float alpha,
const float *A, const int lda, const float *B,
const int ldb, const float beta, float *C,
const int ldc) {
cblas_sgemm(axis == 0 ? CblasRowMajor : CblasColMajor,
tA ? CblasTrans : CblasNoTrans, tB ? CblasTrans : CblasNoTrans, M,
N, K, alpha, A, lda, B, ldb, beta, C, ldc);
}
#endif
using std::abs;
using std::max;
using std::min;
#if HOST_NUM_THREADS > 1 || USING_OPENMP
constexpr int NUM_MOBULA_ATOMIC_ADD_MUTEXES = HOST_NUM_THREADS * 8;
static std::mutex MOBULA_ATOMIC_ADD_MUTEXES[NUM_MOBULA_ATOMIC_ADD_MUTEXES];
inline MOBULA_DEVICE float atomic_add(const float val, float *address) {
uintptr_t id = (reinterpret_cast<uintptr_t>(address) / sizeof(float)) %
NUM_MOBULA_ATOMIC_ADD_MUTEXES;
MOBULA_ATOMIC_ADD_MUTEXES[id].lock();
*address += val;
MOBULA_ATOMIC_ADD_MUTEXES[id].unlock();
return *address;
}
#else
// no lock for single thread mode
inline MOBULA_DEVICE float atomic_add(const float val, float *address) {
*address += val;
return *address;
}
#endif
template <typename T>
T *new_array(size_t size) {
return new T[size];
}
template <typename T>
void del_array(T *p) {
delete[] p;
}
template <typename T>
T *MemcpyHostToDev(T *dst, const T *src, size_t size) {
if (dst == src) return dst;
return static_cast<T *>(memcpy(dst, src, size));
}
template <typename T>
T *MemcpyDevToHost(T *dst, const T *src, size_t size) {
if (dst == src) return dst;
return static_cast<T *>(memcpy(dst, src, size));
}
template <typename T>
T *MemcpyDevToDev(T *dst, const T *src, size_t size) {
if (dst == src) return dst;
return static_cast<T *>(memcpy(dst, src, size));
}
} // namespace mobula
#define KERNEL_RUN_BEGIN(device_id) \
{ \
UNUSED(device_id)
#define KERNEL_RUN_END() }
#define KERNEL_RUN_STREAM(a, strm) KERNEL_RUN(a)
#if USING_OPENMP
#include "./openmp_ctx.h"
#else
#include "./naive_ctx.h"
#endif
#endif // MOBULA_INC_CONTEXT_CPU_CTX_H_
| {
"alphanum_fraction": 0.6767878546,
"avg_line_length": 26.0729166667,
"ext": "h",
"hexsha": "816b34cea4aa44e6358e4822ffb0d64524d57739",
"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": "49e4062f6578b31918ddcc613e38e0fbb92bb015",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hustzxd/MobulaOP",
"max_forks_repo_path": "mobula/inc/context/cpu_ctx.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "49e4062f6578b31918ddcc613e38e0fbb92bb015",
"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": "hustzxd/MobulaOP",
"max_issues_repo_path": "mobula/inc/context/cpu_ctx.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "49e4062f6578b31918ddcc613e38e0fbb92bb015",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hustzxd/MobulaOP",
"max_stars_repo_path": "mobula/inc/context/cpu_ctx.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 674,
"size": 2503
} |
/*
* Copyright (C) 2010-2011 Freescale Semiconductor, Inc. All Rights Reserved.
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <gsl.h>
#include <linux/timer.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/hardirq.h>
#include <linux/semaphore.h>
typedef struct _gsl_autogate_t {
struct timer_list timer;
spinlock_t lock;
int active;
/* pending indicate the timer has been fired but clock not yet disabled. */
int pending;
int timeout;
gsl_device_t *dev;
struct work_struct dis_task;
} gsl_autogate_t;
static gsl_autogate_t *g_autogate[2];
static DECLARE_MUTEX(sem_dev);
#define KGSL_DEVICE_IDLE_TIMEOUT 5000 /* unit ms */
static void clk_disable_task(struct work_struct *work)
{
gsl_autogate_t *autogate;
autogate = container_of(work, gsl_autogate_t, dis_task);
if (autogate->dev->ftbl.device_idle)
autogate->dev->ftbl.device_idle(autogate->dev, GSL_TIMEOUT_DEFAULT);
kgsl_clock(autogate->dev->id, 0);
autogate->pending = 0;
}
static int _kgsl_device_active(gsl_device_t *dev, int all)
{
unsigned long flags;
int to_active = 0;
gsl_autogate_t *autogate = dev->autogate;
if (!autogate) {
printk(KERN_ERR "%s: autogate has exited!\n", __func__);
return 0;
}
// printk(KERN_ERR "%s:%d id %d active %d\n", __func__, __LINE__, dev->id, autogate->active);
spin_lock_irqsave(&autogate->lock, flags);
if (in_interrupt()) {
if (!autogate->active && !autogate->pending)
BUG();
} else {
to_active = !autogate->active;
autogate->active = 1;
}
mod_timer(&autogate->timer, jiffies + msecs_to_jiffies(autogate->timeout));
spin_unlock_irqrestore(&autogate->lock, flags);
if (to_active)
kgsl_clock(autogate->dev->id, 1);
if (to_active && all) {
int index;
index = autogate->dev->id == GSL_DEVICE_G12 ? GSL_DEVICE_YAMATO - 1 :
GSL_DEVICE_G12 - 1;
down(&sem_dev);
if (g_autogate[index])
_kgsl_device_active(g_autogate[index]->dev, 0);
up(&sem_dev);
}
return 0;
}
int kgsl_device_active(gsl_device_t *dev)
{
return _kgsl_device_active(dev, 0);
}
static void kgsl_device_inactive(unsigned long data)
{
gsl_autogate_t *autogate = (gsl_autogate_t *)data;
unsigned long flags;
// printk(KERN_ERR "%s:%d id %d active %d\n", __func__, __LINE__, autogate->dev->id, autogate->active);
del_timer(&autogate->timer);
spin_lock_irqsave(&autogate->lock, flags);
WARN(!autogate->active, "GPU Device %d is already inactive\n", autogate->dev->id);
if (autogate->active) {
autogate->active = 0;
autogate->pending = 1;
schedule_work(&autogate->dis_task);
}
spin_unlock_irqrestore(&autogate->lock, flags);
}
int kgsl_device_clock(gsl_deviceid_t id, int enable)
{
int ret = GSL_SUCCESS;
gsl_device_t *device;
device = &gsl_driver.device[id-1]; // device_id is 1 based
if (device->flags & GSL_FLAGS_INITIALIZED) {
if (enable)
kgsl_device_active(device);
else
kgsl_device_inactive((unsigned long)device);
} else {
printk(KERN_ERR "%s: Dev %d clock is already off!\n", __func__, id);
ret = GSL_FAILURE;
}
return ret;
}
int kgsl_device_autogate_init(gsl_device_t *dev)
{
gsl_autogate_t *autogate;
// printk(KERN_ERR "%s:%d id %d\n", __func__, __LINE__, dev->id);
autogate = kzalloc(sizeof(gsl_autogate_t), GFP_KERNEL);
if (!autogate) {
printk(KERN_ERR "%s: out of memory!\n", __func__);
return -ENOMEM;
}
down(&sem_dev);
autogate->dev = dev;
autogate->active = 1;
spin_lock_init(&autogate->lock);
autogate->timeout = KGSL_DEVICE_IDLE_TIMEOUT;
init_timer(&autogate->timer);
autogate->timer.expires = jiffies + msecs_to_jiffies(autogate->timeout);
autogate->timer.function = kgsl_device_inactive;
autogate->timer.data = (unsigned long)autogate;
add_timer(&autogate->timer);
INIT_WORK(&autogate->dis_task, clk_disable_task);
dev->autogate = autogate;
g_autogate[dev->id - 1] = autogate;
up(&sem_dev);
return 0;
}
void kgsl_device_autogate_exit(gsl_device_t *dev)
{
gsl_autogate_t *autogate = dev->autogate;
// printk(KERN_ERR "%s:%d id %d active %d\n", __func__, __LINE__, dev->id, autogate->active);
down(&sem_dev);
del_timer_sync(&autogate->timer);
if (!autogate->active)
kgsl_clock(autogate->dev->id, 1);
flush_work(&autogate->dis_task);
g_autogate[dev->id - 1] = NULL;
up(&sem_dev);
kfree(autogate);
dev->autogate = NULL;
}
| {
"alphanum_fraction": 0.719227675,
"avg_line_length": 28.9069767442,
"ext": "c",
"hexsha": "210ce79eda7a0c5e7986dc05d19a292c965625e8",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T12:39:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-19T16:42:53.000Z",
"max_forks_repo_head_hexsha": "ab09fbd1194c8148131cf0a37425419253a137b0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "isabella232/wireless-media-drive",
"max_forks_repo_path": "linux-2.6.35.3/drivers/mxc/amd-gpu/platform/hal/linux/misc.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "ab09fbd1194c8148131cf0a37425419253a137b0",
"max_issues_repo_issues_event_max_datetime": "2021-02-24T05:16:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-24T05:16:58.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "SanDisk-Open-Source/wireless-media-drive",
"max_issues_repo_path": "linux-2.6.35.3/drivers/mxc/amd-gpu/platform/hal/linux/misc.c",
"max_line_length": 103,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "ab09fbd1194c8148131cf0a37425419253a137b0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "isabella232/wireless-media-drive",
"max_stars_repo_path": "linux-2.6.35.3/drivers/mxc/amd-gpu/platform/hal/linux/misc.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-16T04:57:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-02-28T21:05:37.000Z",
"num_tokens": 1521,
"size": 4972
} |
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <time.h>
#include <math.h>
using namespace std;
| {
"alphanum_fraction": 0.7317073171,
"avg_line_length": 17.5714285714,
"ext": "h",
"hexsha": "53dcf4a1124be3a4eb5e390c3a1471ef375cdddf",
"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": "320cd613be7219166e7dc953e69c6755d445d8e7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "EddieKHHo/AsexualMutAccum",
"max_forks_repo_path": "IncludeFiles.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "320cd613be7219166e7dc953e69c6755d445d8e7",
"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": "EddieKHHo/AsexualMutAccum",
"max_issues_repo_path": "IncludeFiles.h",
"max_line_length": 28,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "320cd613be7219166e7dc953e69c6755d445d8e7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "EddieKHHo/AsexualMutAccum",
"max_stars_repo_path": "IncludeFiles.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 61,
"size": 246
} |
/* cdf/tdist.c
*
* Copyright (C) 2002 Jason H. Stover.
*
* 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.
*/
/*
* Computes the Student's t cumulative distribution function using
* the method detailed in
*
* W.J. Kennedy and J.E. Gentle, "Statistical Computing." 1980.
* Marcel Dekker. ISBN 0-8247-6898-1.
*
* G.W. Hill and A.W. Davis. "Generalized asymptotic expansions
* of Cornish-Fisher type." Annals of Mathematical Statistics,
* vol. 39, 1264-1273. 1968.
*
* G.W. Hill. "Algorithm 395: Student's t-distribution," Communications
* of the ACM, volume 13, number 10, page 617. October 1970.
*
* G.W. Hill, "Remark on algorithm 395: Student's t-distribution,"
* Transactions on Mathematical Software, volume 7, number 2, page
* 247. June 1982.
*/
#include <config.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "beta_inc.c"
static double
poly_eval (const double c[], unsigned int n, double x)
{
unsigned int i;
double y = c[0] * x;
for (i = 1; i < n; i++)
{
y = x * (y + c[i]);
}
y += c[n];
return y;
}
/*
* Use the Cornish-Fisher asymptotic expansion to find a point u such
* that gsl_cdf_gauss(y) = tcdf(t).
*
*/
static double
cornish_fisher (double t, double n)
{
const double coeffs6[10] = {
0.265974025974025974026,
5.449696969696969696970,
122.20294372294372294372,
2354.7298701298701298701,
37625.00902597402597403,
486996.1392857142857143,
4960870.65,
37978595.55,
201505390.875,
622437908.625
};
const double coeffs5[8] = {
0.2742857142857142857142,
4.499047619047619047619,
78.45142857142857142857,
1118.710714285714285714,
12387.6,
101024.55,
559494.0,
1764959.625
};
const double coeffs4[6] = {
0.3047619047619047619048,
3.752380952380952380952,
46.67142857142857142857,
427.5,
2587.5,
8518.5
};
const double coeffs3[4] = {
0.4,
3.3,
24.0,
85.5
};
double a = n - 0.5;
double b = 48.0 * a * a;
double z2 = a * log1p (t * t / n);
double z = sqrt (z2);
double p5 = z * poly_eval (coeffs6, 9, z2);
double p4 = -z * poly_eval (coeffs5, 7, z2);
double p3 = z * poly_eval (coeffs4, 5, z2);
double p2 = -z * poly_eval (coeffs3, 3, z2);
double p1 = z * (z2 + 3.0);
double p0 = z;
double y = p5;
y = (y / b) + p4;
y = (y / b) + p3;
y = (y / b) + p2;
y = (y / b) + p1;
y = (y / b) + p0;
if (t < 0)
y *= -1;
return y;
}
#if 0
/*
* Series approximation for t > 4.0. This needs to be fixed;
* it shouldn't subtract the result from 1.0. A better way is
* to use two different series expansions. Figuring this out
* means rummaging through Fisher's paper in Metron, v5, 1926,
* "Expansion of Student's integral in powers of n^{-1}."
*/
#define MAXI 40
static double
normal_approx (const double x, const double nu)
{
double y;
double num;
double diff;
double q;
int i;
double lg1, lg2;
y = 1 / sqrt (1 + x * x / nu);
num = 1.0;
q = 0.0;
diff = 2 * GSL_DBL_EPSILON;
for (i = 2; (i < MAXI) && (diff > GSL_DBL_EPSILON); i += 2)
{
diff = q;
num *= y * y * (i - 1) / i;
q += num / (nu + i);
diff = q - diff;
}
q += 1 / nu;
lg1 = gsl_sf_lngamma (nu / 2.0);
lg2 = gsl_sf_lngamma ((nu + 1.0) / 2.0);
diff = lg2 - lg1;
q *= pow (y, nu) * exp (diff) / sqrt (M_PI);
return q;
}
#endif
double
gsl_cdf_tdist_P (const double x, const double nu)
{
double P;
double x2 = x * x;
if (nu > 30 && x2 < 10 * nu)
{
double u = cornish_fisher (x, nu);
P = gsl_cdf_ugaussian_P (u);
return P;
}
if (x2 < nu)
{
double u = x2 / nu;
double eps = u / (1 + u);
if (x >= 0)
{
P = beta_inc_AXPY (0.5, 0.5, 0.5, nu / 2.0, eps);
}
else
{
P = beta_inc_AXPY (-0.5, 0.5, 0.5, nu / 2.0, eps);
}
}
else
{
double v = nu / (x * x);
double eps = v / (1 + v);
if (x >= 0)
{
P = beta_inc_AXPY (-0.5, 1.0, nu / 2.0, 0.5, eps);
}
else
{
P = beta_inc_AXPY (0.5, 0.0, nu / 2.0, 0.5, eps);
}
}
return P;
}
double
gsl_cdf_tdist_Q (const double x, const double nu)
{
double Q;
double x2 = x * x;
if (nu > 30 && x2 < 10 * nu)
{
double u = cornish_fisher (x, nu);
Q = gsl_cdf_ugaussian_Q (u);
return Q;
}
if (x2 < nu)
{
double u = x2 / nu;
double eps = u / (1 + u);
if (x >= 0)
{
Q = beta_inc_AXPY (-0.5, 0.5, 0.5, nu / 2.0, eps);
}
else
{
Q = beta_inc_AXPY (0.5, 0.5, 0.5, nu / 2.0, eps);
}
}
else
{
double v = nu / (x * x);
double eps = v / (1 + v);
if (x >= 0)
{
Q = beta_inc_AXPY (0.5, 0.0, nu / 2.0, 0.5, eps);
}
else
{
Q = beta_inc_AXPY (-0.5, 1.0, nu / 2.0, 0.5, eps);
}
}
return Q;
}
| {
"alphanum_fraction": 0.5623907725,
"avg_line_length": 21.0367647059,
"ext": "c",
"hexsha": "b324482986c8c94ce36a7161f9e9efe9a74d5e61",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cdf/tdist.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cdf/tdist.c",
"max_line_length": 74,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/cdf/tdist.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": 2074,
"size": 5722
} |
#define _GNU_SOURCE
#include <cblas.h>
#include <lapacke.h>
int main(int argc, char **argv)
{
int N = 3;
double X[] = { 1, 2, 3 };
int INCX = 1;
double res = cblas_dnrm2(N, X, INCX);
return 0;
}
| {
"alphanum_fraction": 0.6,
"avg_line_length": 15.7692307692,
"ext": "c",
"hexsha": "d9dab9486c5752401702a71fcec2a0687fe7d173",
"lang": "C",
"max_forks_count": 1019,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T15:38:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-01T18:23:07.000Z",
"max_forks_repo_head_hexsha": "6497d139d82bed2dc2301fcdac2484c838055311",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "fpottier/opam-repository",
"max_forks_repo_path": "packages/conf-openblas/conf-openblas.0.2.1/files/test.c",
"max_issues_count": 15979,
"max_issues_repo_head_hexsha": "6497d139d82bed2dc2301fcdac2484c838055311",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T19:04:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-02T18:44:58.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "fpottier/opam-repository",
"max_issues_repo_path": "packages/conf-openblas/conf-openblas.0.2.1/files/test.c",
"max_line_length": 38,
"max_stars_count": 382,
"max_stars_repo_head_hexsha": "e18367630320c97c1f8b557b3656eda6cbf0db81",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "reneweb/opam-repository",
"max_stars_repo_path": "packages/conf-openblas/conf-openblas.0.2.1/files/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T12:56:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T15:17:16.000Z",
"num_tokens": 79,
"size": 205
} |
/*
Copyright (c) 2015, Patrick Weltevrede
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <time.h>
#include <sys/time.h>
#include <math.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_cdf.h>
#include "psrsalsa.h"
long randomUnsignedInt()
{
time_t seconds;
struct timeval precisetime;
time(&seconds);
gettimeofday(&precisetime,0x0);
return (long)seconds*(long)precisetime.tv_usec;
}
void randomize_idnum(long *idnum)
{
*idnum = -randomUnsignedInt();
}
int find_peak_correlation(float *data1, float *data2, int ndata, int zeropad, int circularpad, int duplicate, int remove_baseline, int *lag, float *correl_max, verbose_definition verbose)
{
int i, lag_max;
int npoints;
float *paddata1, *paddata2, *ans, ans_max, ans_min;
if(duplicate)
duplicate = ndata;
if(verbose.verbose) {
for(i = 0; i < verbose.indent; i++)
printf(" ");
printf("%d points in the data\n", ndata);
if(zeropad != 0) {
for(i = 0; i < verbose.indent; i++)
printf(" ");
printf("Padding at least %d points before and after data\n", zeropad);
}
if(duplicate) {
for(i = 0; i < verbose.indent; i++)
printf(" ");
printf("Duplicating data to avoid wrap problems enabled.\n");
}
}
i = (int) (log10(1.0 * (ndata+2*zeropad+duplicate))/0.301031);
npoints = pow(2.0,(i+1));
if(verbose.verbose) {
for(i = 0; i < verbose.indent; i++)
printf(" ");
printf("Going to zero-pad it to %d points\n", npoints);
}
paddata1 = (float *)malloc(npoints*sizeof(float));
paddata2 = (float *)malloc(npoints*sizeof(float));
ans = (float *)malloc(2*npoints*sizeof(float));
if(paddata1 == NULL || paddata2 == NULL || ans == NULL) {
fflush(stdout);
printerror(verbose.debug, "ERROR find_peak_correlation: Memory allocation error.");
return 0;
}
zeropad = (npoints - duplicate - ndata)/2;
for(i = 0; i < ndata; i++) {
paddata1[i+zeropad] = data1[i];
paddata2[i+zeropad] = data2[i];
if(duplicate) {
paddata1[i+ndata+zeropad] = data1[i];
paddata2[i+ndata+zeropad] = data2[i];
}
}
for(i = 0; i < zeropad; i++) {
paddata1[i] = data1[i-zeropad+ndata];
paddata2[i] = data2[i-zeropad+ndata];
}
for(i = ndata+duplicate+zeropad; i < npoints; i++) {
paddata1[i] = data1[i-duplicate-zeropad-ndata];
paddata2[i] = data2[i-duplicate-zeropad-ndata];
}
if(crosscorrelation_fft(paddata1, paddata2, npoints, ans, remove_baseline, verbose) == 0) {
fflush(stdout);
printerror(verbose.debug, "ERROR find_peak_correlation: Cross correlation failed.");
return 0;
}
lag_max = 0;
ans_max = ans[0];
ans_min = ans[0];
for(i = 1; i < npoints; i++) {
if(ans[i] > ans_max) {
ans_max = ans[i];
lag_max = i;
}
if(ans[i] < ans_min)
ans_min = ans[i];
}
if(lag_max >= npoints/2)
lag_max -= npoints;
*correl_max = ans_max/ans_min;
*lag = lag_max;
if(verbose.verbose) {
for(i = 0; i < verbose.indent; i++)
printf(" ");
printf("Found a lag of %d (correlation %f higher)\n", *lag, *correl_max);
}
free(paddata1);
free(paddata2);
free(ans);
return 1;
}
long calculate_bin_number(double x, double dx, double min_x, int centered_at_zero, double extra_phase)
{
long bin, step, binzero;
if(min_x < 0)
step = -min_x/dx+10;
else
step = 0;
bin = ( x+(step+0.5*centered_at_zero-extra_phase)*dx)/dx;
binzero = (min_x+(step+0.5*centered_at_zero-extra_phase)*dx)/dx;
bin -= binzero;
return bin;
}
double calculate_bin_location(long binnr, double dx, double min_x, int centered_at_zero, double extra_phase)
{
long step, binzero;
double x;
if(min_x < 0)
step = -min_x/dx+10;
else
step = 0;
binzero = (min_x+(step+0.5*centered_at_zero-extra_phase)*dx)/dx;
binnr = binnr + binzero;
x = binnr*dx - (step+0.5*centered_at_zero-extra_phase)*dx;
x += 0.5*dx;
return x;
}
double calculate_required_bin_width(double x, long binnr, double min_x, int centered_at_zero, double extra_phase, verbose_definition verbose)
{
long lastbin, ok, timesinloop;
double dx, offset;
dx = (x - min_x)/(double)(binnr+0.5);
timesinloop = 0;
offset = 0;
do {
ok = 1;
dx = (x - min_x)/(double)(binnr+0.5) + offset;
lastbin = calculate_bin_number(x, dx, min_x, centered_at_zero, extra_phase);
if(lastbin < binnr) {
offset += (x-min_x-0.5*dx)/(double)(binnr+0.5) - dx;
ok = 0;
}else if(lastbin > binnr) {
offset += (x-min_x+0.5*dx)/(double)(binnr+0.5) -dx;
ok = 0;
}
timesinloop++;
if(timesinloop > 10) {
printerror(verbose.debug, "ERROR calculate_required_bin_width: Cannot find suitable binsize.\n");
return dx;
}
}while(ok == 0);
return dx;
}
int set_binning_histogram(double min_x_data, double max_x_data, int rangex_set, double rangex_min, double rangex_max, int nrbins_specified, long nrbins, int centered_at_zero, double extra_phase, double *min_x, double *max_x, double *dx, verbose_definition verbose)
{
int reset;
do {
reset = 0;
*min_x = min_x_data;
*max_x = max_x_data;
if(rangex_set) {
*min_x = rangex_min;
*max_x = rangex_max;
}
if(nrbins_specified) {
*dx = calculate_required_bin_width(*max_x, nrbins-1, *min_x, centered_at_zero, extra_phase, verbose);
if(verbose.verbose)
fprintf(stdout, "Going to use binsize %e.\n", *dx);
}
{
long firstbin;
firstbin = calculate_bin_number(*min_x, *dx, *min_x, centered_at_zero, extra_phase);
if(firstbin != 0) {
printerror(verbose.debug, "ERROR set_binning_histogram: Expected first bin to be number zero (it is %ld).\n", firstbin);
return 2;
}
}
long i;
double diff;
i = calculate_bin_number(*max_x, *dx, *min_x, centered_at_zero, extra_phase);
diff = *max_x - calculate_bin_location(i, *dx, *min_x, centered_at_zero, extra_phase);
diff = diff/(*dx);
if(verbose.debug) {
printf("Current set max value (%e) is falling at phase=%e w.r.t. centre of last generated bin.\n", *max_x, diff);
}
if(diff > -0.501 && diff < -0.499) {
if(rangex_set) {
rangex_max -= 0.5*(*dx);
printwarning(verbose.debug, "WARNING set_binning_histogram: Adjusting maximum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.", rangex_max);
reset = 1;
}
}
if(diff > 0.499 && diff < 0.501) {
if(rangex_set) {
rangex_max += 0.5*(*dx);
printwarning(verbose.debug, "WARNING set_binning_histogram: Adjusting maximum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.", rangex_max);
reset = 1;
}else {
*max_x += 0.5*(*dx);
if(nrbins_specified) {
printwarning(verbose.debug, "WARNING set_binning_histogram: Nr of bins might be different from what was requested to avoid rounding errors.");
}
}
}
i = calculate_bin_number(*min_x, *dx, *min_x, centered_at_zero, extra_phase);
diff = *min_x - calculate_bin_location(i, *dx, *min_x, centered_at_zero, extra_phase);
diff = diff/(*dx);
if(verbose.debug) {
printf("Current set min value (%e) is falling at phase=%e w.r.t. centre of first generated bin.\n", *min_x, diff);
}
if(diff > -0.501 && diff < -0.499) {
if(rangex_set) {
rangex_min -= 0.5*(*dx);
printwarning(verbose.debug, "WARNING set_binning_histogram: Adjusting minimum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.", rangex_min);
reset = 1;
}else {
*min_x -= 0.5*(*dx);
if(nrbins_specified) {
printwarning(verbose.debug, "WARNING set_binning_histogram: Nr of bins might be different from what was requested to avoid rounding errors.");
}
}
}
if(diff > 0.499 && diff < 0.501) {
if(rangex_set) {
rangex_min += 0.5*(*dx);
printwarning(verbose.debug, "WARNING set_binning_histogram: Adjusting minimum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.", rangex_min);
reset = 1;
}
}
if(reset) {
printwarning(verbose.debug, "WARNING set_binning_histogram: Re-adjusting choosen binning.\n", rangex_max);
}
}while(reset == 1);
return 0;
}
double kstest_cdf_flat(double x, double min_x, double max_x)
{
if(x <= min_x)
return 0;
if(x >= max_x)
return 1;
return (x-min_x)/(max_x-min_x);
}
double kstest_cdf_sin(double x)
{
if(x <= 0)
return 0;
if(x >= 90)
return 1;
return 1-cos(x*M_PI/180.0);
}
void kstest(double *data1, long n1, double *data2, long n2, int cdf_type, double input_value1, double input_value2, double (*cdf)(double), double *max_diff, double *prob, verbose_definition verbose)
{
long i1, i2;
double effective_n, ks_statistic, sign, cur_term, last_term, coeff;
int converged;
gsl_sort(data1, 1, n1);
if(n2 > 0 && data2 != NULL)
gsl_sort(data2, 1, n2);
*max_diff = 0;
if(n2 > 0 && data2 != NULL) {
i1 = 0;
i2 = 0;
while(i1 < n1 && i2 < n2) {
double diff;
if(data1[i1] == data2[i2]) {
i1++;
i2++;
}else if(data1[i1] < data2[i2]) {
i1++;
}else {
i2++;
}
diff = fabs(i1/(double)n1 - i2/(double)n2);
if(diff > *max_diff)
*max_diff = diff;
}
effective_n=n1*n2/(double)(n1+n2);
}else {
double cdf_right, cdf_left, cdf_model;
cdf_left = 0;
for(i1 = 0; i1 < n1; i1++) {
cdf_right = (i1+1)/(double)n1;
if(cdf_type == 0) {
cdf_model = (*cdf)(data1[i1]);
}else if(cdf_type == 1) {
cdf_model = kstest_cdf_flat(data1[i1], data1[0], data1[n1-1]);
if(i1 == 0) {
printwarning(verbose.debug, "WARNING kstest: Probability will be overestimated, since the minimum/maximum of the uniform distribution is based on the input values.");
}
}else if(cdf_type == 3) {
cdf_model = kstest_cdf_flat(data1[i1], input_value1, input_value2);
}else if(cdf_type == 2) {
cdf_model = kstest_cdf_sin(data1[i1]);
}else {
fflush(stdout);
printerror(verbose.debug, "ERROR kstest: Undefined type of cdf is specified.");
exit(0);
}
if(fabs(cdf_right-cdf_model) > *max_diff)
*max_diff = fabs(cdf_right-cdf_model);
if(fabs(cdf_left-cdf_model) > *max_diff)
*max_diff = fabs(cdf_left-cdf_model);
cdf_left = cdf_right;
}
effective_n=n1;
}
if(effective_n < 4) {
printwarning(verbose.debug, "WARNING kstest: Number of data-points is too low to make use of approximations used in this implementation of the KS-test.");
}
effective_n=sqrt(effective_n);
ks_statistic = (*max_diff)*(effective_n+0.12+0.11/effective_n);
coeff = -2.0*ks_statistic*ks_statistic;
*prob = 0;
sign = 1;
last_term = 0;
converged = 0;
for(i1 = 1; i1 <= 100; i1++) {
cur_term = sign*2.0*exp(coeff*i1*i1);
*prob += cur_term;
if(fabs(cur_term) <= 1e-5*fabs(last_term) || fabs(cur_term) <= 1e-10*(*prob)) {
converged = 1;
break;
}
last_term = cur_term;
sign = -sign;
}
if(!converged)
*prob = 1;
if(verbose.verbose) {
printf("KS-test statistic max_diff: %lf = %e\n", *max_diff, *max_diff);
printf("KS-test probability: %lf = %e\nA small probability means the two sets of points are drawn from a different distribution.\n", *prob, *prob);
printf("The null hypothesis ");
if(n2 > 0 && data2 != NULL) {
printf("(data sets are drawn from the same distribution) ");
}else {
printf("(data set is drawn from the specified distribution) ");
}
#if GSL_VERSION_NUMBER >= 104
printf("can be rejected at the %.2lf sigma level.\n", gsl_cdf_gaussian_Pinv(0.5*(1.0-*prob)+0.5, 1.0));
#else
printf("can be rejected at the XXXX sigma level (need GSL >= 1.4 to get this number).\n");
#endif
}
}
| {
"alphanum_fraction": 0.6629479636,
"avg_line_length": 36.1519337017,
"ext": "c",
"hexsha": "109b189caa6cc68848181c78224f6222bbe6578b",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z",
"max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "weltevrede/psrsalsa",
"max_forks_repo_path": "src/lib/statistics.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008",
"max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "weltevrede/psrsalsa",
"max_issues_repo_path": "src/lib/statistics.c",
"max_line_length": 755,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "weltevrede/psrsalsa",
"max_stars_repo_path": "src/lib/statistics.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z",
"num_tokens": 3924,
"size": 13087
} |
// Copyright Jean Pierre Cimalando 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <SimpleIni.h>
#include <gsl/gsl>
#include <string>
#include <memory>
const std::string &get_configuration_dir();
std::string get_configuration_file(gsl::cstring_span name);
std::unique_ptr<CSimpleIniA> create_configuration();
std::unique_ptr<CSimpleIniA> load_configuration(gsl::cstring_span name);
bool save_configuration(gsl::cstring_span name, const CSimpleIniA &ini);
std::unique_ptr<CSimpleIniA> load_global_configuration();
bool save_global_configuration(const CSimpleIniA &ini);
| {
"alphanum_fraction": 0.7696551724,
"avg_line_length": 34.5238095238,
"ext": "h",
"hexsha": "0f0bbe191b872a5688209e9e64efd5a6a34b3bae",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z",
"max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "jpcima/smf-dsp",
"max_forks_repo_path": "sources/configuration.h",
"max_issues_count": 19,
"max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "jpcima/smf-dsp",
"max_issues_repo_path": "sources/configuration.h",
"max_line_length": 72,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "jpcima/smf-dsp",
"max_stars_repo_path": "sources/configuration.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z",
"num_tokens": 174,
"size": 725
} |
/* specfunc/gsl_sf_coupling.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_COUPLING_H__
#define __GSL_SF_COUPLING_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
/* 3j Symbols: / ja jb jc \
* \ ma mb mc /
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_coupling_3j_e(int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc,
gsl_sf_result * result
);
double gsl_sf_coupling_3j(int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc
);
/* 6j Symbols: / ja jb jc \
* \ jd je jf /
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_coupling_6j_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
gsl_sf_result * result
);
double gsl_sf_coupling_6j(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf
);
/* 9j Symbols: / ja jb jc \
* | jd je jf |
* \ jg jh ji /
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_coupling_9j_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji,
gsl_sf_result * result
);
double gsl_sf_coupling_9j(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji
);
__END_DECLS
#endif /* __GSL_SF_COUPLING_H__ */
| {
"alphanum_fraction": 0.625,
"avg_line_length": 29.3636363636,
"ext": "h",
"hexsha": "50dd1b881e498ce951d6583e4919be6e0709ade9",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coupling.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coupling.h",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coupling.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 725,
"size": 2584
} |
// Distributed under MIT License, see LICENSE file
// (c) 2018 Zbigniew Skowron, zbychs@gmail.com
#pragma once
#include "text_buffer.h"
#include "text_parser.h"
#include "text_renderer.h"
#include "geometry.h"
#include <string>
#include <vector>
#include <iostream>
#include <gsl/span>
namespace terminal_editor {
/// This class describes position in a TextBuffer.
/// Positions are logically between characters.
struct GraphemePosition : Position {
int screenColumn; ///< Column on the screen (zero indexed).
GraphemePosition() : screenColumn(0) {}
GraphemePosition(Position position, int screenColumn) : Position(position), screenColumn(screenColumn) {}
friend std::ostream& operator<<(std::ostream& os, GraphemePosition graphemePosition) {
return os << "GraphemePosition{" << graphemePosition.row << ", " << graphemePosition.column << ", scrCol=" << graphemePosition.screenColumn << "}";
}
};
/// This class is an editable container of lines of graphemes.
/// @note By screen coordinates below we mean coordinates that take into account rendered sizes of graphemes in screen cells, but not window position or text offset inside a window.
/// @note This is a very straighforward implementation. It is not efficient.
class GraphemeBuffer {
private:
TextBuffer& m_textBuffer;
std::vector<std::vector<Grapheme>> renderedLines; ///< Will always have at least one line.
public:
GraphemeBuffer(TextBuffer& textBuffer);
/// Empty virtual destructor.
virtual ~GraphemeBuffer() {
}
/// Replaces contents of this text buffer with contents of given file.
/// @param fileName Name of file to load.
virtual void loadFile(const std::string& fileName);
/// Returns number of lines in this text buffer.
/// @note It will always be 1 + number of LF's in file.
int getNumberOfLines() const;
/// Returns length of the longest line, on screen.
int getLongestLineLength() const;
/// Returns contents of given line.
/// If row is less than zero or greater than number of lines - 1, empty span is returned.
/// Span is valid only until next edit on the buffer.
/// @param row Row to return (zero indexed).
gsl::span<const Grapheme> getLine(int row) const;
/// Returns part of given line from colStart (inclusive) to colEnd (exclusive).
/// colStart and colEnd are first clamped to the range 0 (inclusive) to line length (inclusive).
/// Span is valid only until next edit on the buffer.
/// @param row Row to return (zero indexed).
/// @param colStart First grapheme to return (zero indexed).
/// @param colEnd One past last grapheme to return (zero indexed).
gsl::span<const Grapheme> getLineRange(int row, int colStart, int colEnd) const;
/// Returns Point that corresponds to screen coordinates of given Position.
/// @param Position Position of a grapheme (can be one past end of line).
/// @return Point in screen coordinates of first cell of the grapheme.
[[nodiscard]]
Point positionToPoint(Position position);
/// Returns Position that corresponds to given Point in screen coordinates.
/// @note If point row is outside of row bounds, it is clamped to valid range.
/// @note If point is after the line end, returns position one past end of line.
/// @note If point is before the line start, returns position of first grapheme in line.
/// @param point Point in screen coordinates.
/// @param after If point is not on first screen cell of a grapheme, return position after a grapheme.
/// Otherwise return position of grapheme under point.
/// @return Position of grapheme under point (can be one past end of line).
/// Returned Position is clamped to valid line row/column.
[[nodiscard]]
Position pointToPosition(Point point, bool after);
/// Inserts given text into this grapheme buffer.
/// position is first clamped to a valid range.
/// @param position Position to insert into.
/// @param text Text to insert. May contain new lines. Doesn't have to be valid UTF-8.
/// @returns Position of the end of inserted text in the new grapheme buffer.
virtual Position insertText(Position position, const std::string& text);
/// Deletes text between two positions: from startPosition (inclusive) to endPosition (exclusive).
/// positions are first clamped to valid range.
/// positions can be on different lines.
/// If startPosition is past endPosition no characters are removed.
/// @param startPosition Start position. This is first position that will be removed.
/// @param endPosition End position. This is first position that will not be removed.
/// @returns Characters removed (including newlines).
virtual std::string deleteText(Position startPosition, Position endPosition);
/// Clamps position to a valid range, so:
/// - row is clamped to range from 0 to number of lines (inclusive),
/// - column is clamped to range from 0 to line length (inclusive).
[[nodiscard]]
Position clampPosition(Position position) const;
protected:
/// Maps grapheme position to position in underlying text buffer.
[[nodiscard]]
Position positionToTextPosition(Position position) const;
/// Maps position in underlying text buffer to grapheme position.
/// @param after If position is not on first byte of a grapheme, return position after a grapheme.
/// Otherwise return position of grapheme with given byte.
[[nodiscard]]
Position textPositionToPosition(Position textPosition, bool after) const;
/// Re-renders all lines based on TextBuffer.
/// renderedLines is re-initialized.
void rerenderAllLines();
/// Re-renders given line.
void rerenderLine(int row);
};
} // namespace terminal_editor
| {
"alphanum_fraction": 0.6992570078,
"avg_line_length": 44.8636363636,
"ext": "h",
"hexsha": "fd74b73a29b9364c3d421b1c9ffd904e10c750f7",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z",
"max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Zbyl/terminal-editor",
"max_forks_repo_path": "editorlib/grapheme_buffer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58",
"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": "Zbyl/terminal-editor",
"max_issues_repo_path": "editorlib/grapheme_buffer.h",
"max_line_length": 181,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Zbyl/terminal-editor",
"max_stars_repo_path": "editorlib/grapheme_buffer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1292,
"size": 5922
} |
/*
* PARTICLE SWARM OPTIMIZATION
* ===========================
*
* Author: Gabriel E Leventhal, 2011-12-02
*
* adapted from
* Author: Tomas V. Arredondo
* SimPSOLib: A simple yet flexible PSO implementation in C++.
*
*/
#ifndef __PSO_SWARM__
#define __PSO_SWARM__
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <ctime>
#include <queue>
using namespace std;
#include "GSLRng.h"
#include <gsl/gsl_math.h>
#include "Particle.h"
#include "Point.h"
#include "Parameters.h"
#include "Network.h"
#ifdef USE_MPI
#include "mpi.h"
#endif
namespace PSO {
class Swarm {
public:
Swarm() {}
Swarm(int size, int np, Parameters* pars)
: swarmSize(size), numParams(np), numEvals(0), curIt(0),
numInform(3),
phiPi(np,2.5), phiPf(np,0.5), phiGi(np,0.5),phiGf(np,2.5),
omegai(np,0.721), omegaf(np,0.721), p(pars),
bestVal(-INFINITY), bestParticle(-1),
mpi_type(0), mpi_rank(0), mpi_ntasks(1)
{
bestPos = Point(np,0.0);
setInformants(numInform);
}
virtual ~Swarm() { destroy(); }
inline void setMPI(int type) { mpi_type = (type >= 0) ? type : 0; }
inline void setVars(const Point& pp, const Point& pg, const Point& o) {
phiPi = pp; phiGi = pg; omegai = o;
phiPf = pp; phiGf = pg; omegaf = o;
phiP = pp; phiG = pg; omega = o;
}
inline void setInformants(int K) {
numInform = (K > swarmSize-1) ? swarmSize-1 : K;
links.resize(swarmSize);
init_network();
}
double maximum_swarm_radius() const;
double search_space_diameter() const;
// get everything ready to go
void begin(int argc, char* argv[]);
// finish up stuff
void end();
void initialize(int type = 0);
void display(ostream* out = &cout, string prefix = "");
virtual void evaluate(int vflag = 0, ostream* out = NULL, ostream* hist = NULL);
virtual double evaluateParticle(int j);
void updateVelocity(int j, bool bestVals = true);
void updateVelocity(bool bestVals = true);
void updatePosition(int j);
void updatePosition();
void randomizeInf(int maxTries = 1000);
void randomPosition(int j);
virtual void run(int numIt, int slowdown = 0, int vflag = 0,
ostream* out = NULL, ostream* hist = NULL);
inline bool is_master() const { return (mpi_rank == 0); }
inline void seed_rng(unsigned long seed) { rng.set(seed); }
inline const Particle& at(size_t i) const { return *swarm[i]; }
inline Particle best() const { return *swarm[bestParticle]; }
inline double fitness(int i) const { return swarm.at(i)->fitness(); }
inline int size() const { return swarmSize; }
inline int nextIt() { return ++curIt; }
inline void setIt(int i) { curIt = i; }
double mean(int i) const;
double var(int i) const;
Point mean() const;
Point var() const;
#ifdef USE_MPI
virtual void evaluate_slave();
void run_mpi(int numInt, int vflag = 0, ostream* out = NULL, ostream* hist = NULL);
virtual void run_master(int numInt, int vflag, ostream* out, ostream* hist);
inline void evaluate_master(int vflag = 0) { run_master(-1,vflag,NULL,NULL); }
#endif
protected:
void create();
void destroy();
void init_network();
int find_best();
int swarmSize; /* swarm size */
vector<Particle*> swarm; /* swarm */
int numParams; /* number of parameters */
int numEvals; /* current number of function evaluations */
int curIt; /* current swarm iteration */
int numInform; /* number of informants */
Network links; /* information network */
Point phiP;
Point phiG;
Point omega;
Point phiPi; /* phiP initial */
Point phiPf; /* phiP final */
Point phiGi; /* phiG initial */
Point phiGf; /* phiG final */
Point omegai; /* omega initial */
Point omegaf; /* omega final */
Parameters* p;
double bestVal; /* current best value */
Point bestPos; /* current best position */
int bestParticle;
myGSL::Rng rng;
int mpi_type;
int mpi_rank;
int mpi_ntasks;
};
}
#endif // __PSO_SWARM__
| {
"alphanum_fraction": 0.5478297514,
"avg_line_length": 29.2962962963,
"ext": "h",
"hexsha": "26d6a2f301cf2843ea6fc8a7ef7ae7de8c2e8660",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2022-03-17T09:34:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-11T13:00:48.000Z",
"max_forks_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "marieberth/tiff_opt",
"max_forks_repo_path": "Swarm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062",
"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": "marieberth/tiff_opt",
"max_issues_repo_path": "Swarm.h",
"max_line_length": 92,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "9c831df9bdcd2eb9890a4d12c47f1935e53a7062",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "marieberth/tiff_opt",
"max_stars_repo_path": "Swarm.h",
"max_stars_repo_stars_event_max_datetime": "2021-03-03T11:02:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-28T07:13:41.000Z",
"num_tokens": 1151,
"size": 4746
} |
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_real_float.h>
#define BASE_DOUBLE
#include "templates_on.h"
#include "real_pass.h"
#include "real_init.c"
#include "real_main.c"
#include "real_pass_2.c"
#include "real_pass_3.c"
#include "real_pass_4.c"
#include "real_pass_5.c"
#include "real_pass_n.c"
#include "real_radix2.c"
#include "real_unpack.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "real_pass.h"
#include "real_init.c"
#include "real_main.c"
#include "real_pass_2.c"
#include "real_pass_3.c"
#include "real_pass_4.c"
#include "real_pass_5.c"
#include "real_pass_n.c"
#include "real_radix2.c"
#include "real_unpack.c"
#include "templates_off.h"
#undef BASE_FLOAT
| {
"alphanum_fraction": 0.7557077626,
"avg_line_length": 21.3658536585,
"ext": "c",
"hexsha": "512f8b25fc10ca6c7273c630922e7ef8e92d158b",
"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/fft/real.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/fft/real.c",
"max_line_length": 35,
"max_stars_count": 14,
"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/fft/real.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": 243,
"size": 876
} |
/*
NAME:
logsum
PURPOSE:
calculate the log of the sum of numbers which are given as logs using as much of the dynamic range as possible
CALLING SEQUENCE:
logsum(gsl_matrix * q, int row, bool isrow,bool partial, int partial_indx[3])
INPUT:
q - matrix of which we will sum a row/column
row - row/column number
isrow - are we summing a row or a column
OUTPUT:
log of the sum
REVISION HISTORY:
2008-09-21 - Written Bovy
*/
#include <stdbool.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_matrix.h>
#include <proj_gauss_mixtures.h>
double logsum(gsl_matrix * q, int row, bool isrow){
double logxmin = log(DBL_MIN);
double logxmax = log(DBL_MAX);
int l = (isrow) ? q->size2 : q->size1;
/* First find the maximum and mininum */
double max, min;
minmax(q,row,isrow,&min,&max);//,allfixed);
min *= -1.;
min += logxmin;
max *= -1.;
max += logxmax - log(l);
(min > max) ? (max=max) : (max=min);
double loglike=0.0;
int dd;
if (isrow)
for (dd = 0; dd != q->size2; ++dd)
loglike += exp(gsl_matrix_get(q,row,dd)+max);
else
for (dd = 0; dd != q->size1; ++dd)
loglike += exp(gsl_matrix_get(q,dd,row)+max);
return log(loglike)-max;
}
| {
"alphanum_fraction": 0.6184419714,
"avg_line_length": 25.16,
"ext": "c",
"hexsha": "824e2f4c31dac0cd076da74cd492cc1025a79b96",
"lang": "C",
"max_forks_count": 26,
"max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z",
"max_forks_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_forks_repo_path": "src/logsum.c",
"max_issues_count": 24,
"max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_issues_repo_path": "src/logsum.c",
"max_line_length": 115,
"max_stars_count": 73,
"max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_stars_repo_path": "src/logsum.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z",
"num_tokens": 396,
"size": 1258
} |
/* Author: Edward Hutter */
#ifndef SHARED
#define SHARED
// System includes
#include <fstream>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <complex>
#include <vector>
#include <map>
#include <algorithm>
#include <utility>
#include <tuple>
#include <cmath>
#include <string>
#include <assert.h>
#include <complex>
#include <mpi.h>
#include "mkl.h"
#ifdef CRITTER
#include "critter.h"
#else
//#ifdef PORTER
//#include <cblas.h>
//#include "/home/hutter2/hutter2/external/BLAS/OpenBLAS/lapack-netlib/LAPACKE/include/lapacke.h"
//#endif
#define CRITTER_START(ARG)
#define CRITTER_STOP(ARG)
#endif
template<typename ScalarType>
class mpi_type;
template<>
class mpi_type<float>{
public:
constexpr static size_t type = MPI_FLOAT;
};
template<>
class mpi_type<double>{
public:
constexpr static size_t type = MPI_DOUBLE;
};
#endif /*SHARED*/
| {
"alphanum_fraction": 0.7331081081,
"avg_line_length": 16.7547169811,
"ext": "h",
"hexsha": "b7aa2beca2ddc97fbdd412b63d0590300b4017ab",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-20T01:13:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-20T01:13:23.000Z",
"max_forks_repo_head_hexsha": "574dc04caf4a2eefd7af77517123b6eb4f9a18cc",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "tbennun/capital",
"max_forks_repo_path": "src/util/shared.h",
"max_issues_count": 16,
"max_issues_repo_head_hexsha": "574dc04caf4a2eefd7af77517123b6eb4f9a18cc",
"max_issues_repo_issues_event_max_datetime": "2019-10-21T22:01:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-15T00:37:37.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "tbennun/capital",
"max_issues_repo_path": "src/util/shared.h",
"max_line_length": 97,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "574dc04caf4a2eefd7af77517123b6eb4f9a18cc",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "tbennun/capital",
"max_stars_repo_path": "src/util/shared.h",
"max_stars_repo_stars_event_max_datetime": "2021-03-20T01:13:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-20T01:13:21.000Z",
"num_tokens": 221,
"size": 888
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <sys/time.h>
// ***************************************************************************************
// * Pre-Port Entwicklung und Testen eines OMP-parallisierten, adaptiven Simpson-integrators für
// * die fiesen doppelintgrale in imd_colrad.c
// ***************************************************************************************
int num_threads;
int simpson_error;
int funcevals;
int iter;
const double tolmax=1e-30;
#define INITIAL_STACK_SIZE 128; //128 /* initial size of new stacks */
const double alpha=0.816496580927726;
const double beta=0.447213595499958;
static const double xgkq[12] =
{
0.0,
-0.942882415695480,
-0.816496580927726,
-0.641853342345781,
-0.447213595499958,
-0.236383199662150,
0.0,
0.236383199662150,
0.447213595499958,
0.641853342345781,
0.816496580927726,
0.942882415695480
};
/* the stack structure */
struct stack_s{
int el_count; /* count of elements on stack */
int el_size; /* size of an element */
int mem_reserve; /* allocated memory for stack */
void* elements; /* pointer to begin of stack */
};
struct my_f_params { double ne; double T;double mu; double E;double DeltaE; int allowed;};
typedef struct _work_t{
double a;
double b;
double tol;
double S;
double fa;
double fb;
double fm;
double rec;
int iter;
struct my_f_params * p; //pointer auf params
} work_t;
typedef struct stack_s* stack_t;
typedef struct _work_t_gkq{
double a;
double b;
double toler;
double I_13;
double fa;
double fb;
struct my_f_params * p; //pointer auf params
double (*f)(double, struct my_f_params*);
stack_t stack_inner;
short int is_parent;
short int subtask_nr; //inner task nr
short int task_nr; //outer task nr
short int subtasks_left; //erst pop'n wenn aller inner tasks (intergals) vollständig!
double inner_integrals[5];
} work_gkq;
// **************************************** FUNCTION DEFS *************************************************
void create_stack(stack_t* stack, int element_size);
int empty_stack(stack_t stack);
void push_stack(stack_t stack, void* element);
void pop_stack(stack_t stack, void* element);
double
integral2( double (*f)(double, struct my_f_params*), /* function to integrate */
stack_t stack);
double gkq_adapt_double(stack_t stack);
double gkq_adapt_single(stack_t stack); //for single integral, first integral
double gkq_double(double (*f)(double, struct my_f_params*), double (*finner)(double, struct my_f_params*),
double a, double b,
double TOL, struct my_f_params* p,stack_t stack);
double gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b, double fa,double fb, double toler,double I_13, struct my_f_params* p);
work_gkq gkq_create_inner_task(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p);
double gkq_single(double (*f)(double, struct my_f_params*), double a, double b,
double TOL, struct my_f_params* p,stack_t stack);
int terminate_serial;
int terminate_gkq;
// static double myfun(double x,struct my_f_params* p)
// {
// double T=p->T;
// double fermi=1/(1+exp(-x/T));
// double fermi2=1- 1/(1+exp(-x/T));
// double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen
// // return exp(-x*x)/p->T+log(x*pow(p->T,2.0))/p->ne;
// return fermi*fermi2*sigma;
// }
// static double myfun2(double x,void* pv)
// {
// struct my_f_params *p= (struct my_f_params*) pv;
// double T=p->T;
// double fermi=1/(1+exp(-x/T));
// double fermi2=1- 1/(1+exp(-x/T));
// double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen
// // return exp(-x*x)/p->T+log(x*pow(p->T,2.0))/p->ne;
// return fermi*fermi2*sigma;
// }
static double inner_integrand(double x,void *pv)
{
struct my_f_params *p= (struct my_f_params*) pv;
double T=p->T;
double fermi=1/(1+exp(-x/T));
double fermi2=1- 1/(1+exp(-x/T));
return exp(-x*x); //fermi*fermi2;
}
static double inner_integrand2(double x,struct my_f_params* p)
{
double T=p->T;
double fermi=1/(1+exp(-x/T));
double fermi2=1- 1/(1+exp(-x/T));
return fermi*fermi2;
}
void get_integ_bounds_inner(double *integ_bnd, double x, struct my_f_params *p)
{
integ_bnd[0]=-4;
integ_bnd[1]=4;
}
gsl_integration_workspace * gsinner;
gsl_integration_workspace * gsinner2;
static double myfun(double x,struct my_f_params* p)
{
double T=p->T;
double fermi=1/(1+exp(-x/T));
double fermi2=1- 1/(1+exp(-x/T));
double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen
// double result, err;
// gsl_function gslfun;
// gslfun.function=&inner_integrand;
// gslfun.params=p;
// gsl_integration_qag(&gslfun, x, 300, 0.0, 1e-3, 1000,1,
// gsinner2, &result, &err);
// gsl_integration_workspace_free(gsinner2);
// stack_t stack2;
// create_stack(&stack2, sizeof(work_gkq));
//double result=gkq(inner_integrand2, x, 600, 1e-3, p);//, stack);
// free(stack2->elements);
return sigma;
//return exp(-x*x);
};
static double myfun_gsl(double x,void* pv)
{
struct my_f_params *p= (struct my_f_params*) pv;
double T=p->T;
double fermi=1/(1+exp(-x/T));
double fermi2=1- 1/(1+exp(-x/T));
double sigma=x/T*log(x/T*2)/pow(1/x,2.0); //einfach nur ärger machen
gsl_function gslfun;
gslfun.function=&inner_integrand;
gslfun.params=pv;
double result, err;
gsl_integration_qag(&gslfun, x, 600, 0.0, 1e-3, 1000,1,
gsinner, &result, &err);
return sigma*result;
}
// static double myfun2(double x,void* pv)
// {
// struct my_f_params *p= (struct my_f_params*) pv;
// static float sinfc(float x) { return sinf(x); }
// static double frand48c(double x) { funcevals++; return (double) drand48(); }
// *************************************************************************************************************
int main(int argc,char** argv)
{
iter=0;
num_threads=omp_get_num_threads();
funcevals=0;
simpson_error=0;
struct timeval start, end;
double gsltime, simpsontime;
// ************************************************
gsinner= gsl_integration_workspace_alloc (1000);
// double gslinteg=0.0;
// double integ_err;
// gsl_function gslfun;
// gslfun.function=&myfun;
// **********************************************
double pi=3.141592653589793;
double xmin, xmax;
double answer = 0.0;
int i;
xmin=2;
xmax=100;
// ***********************************************
double T0=1;
double ne0=1e5;
struct my_f_params ptest;
ptest.T=T0;
ptest.ne=ne0;
// *************************************************
int method=GSL_INTEG_GAUSS61;
gsl_function gslfun;
gslfun.function=&myfun_gsl;
gslfun.params=&ptest;
gsl_integration_workspace * gswork=NULL;
gswork= gsl_integration_workspace_alloc (1000);
double gslinteg=0.0;
double integ_err;
gettimeofday(&start, NULL);
gsl_integration_qag(&gslfun, xmin, xmax, 0.0, 1e-8, 1000,1,
gswork, &gslinteg, &integ_err);
gettimeofday(&end, NULL);
gsltime = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) /1.e6;
printf("gslres:%.12e, gsltime:%.4e\n", gslinteg, gsltime);
// *************************************************
stack_t stack; //global stack
create_stack(&stack, sizeof(work_gkq));
gettimeofday(&start, NULL);
double integ=gkq_double(myfun,inner_integrand2, xmin, xmax, 1e-2, &ptest,stack);
gettimeofday(&end, NULL);
free(stack->elements);
free(stack);
double partime = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) /1.e6;
printf("my:%.12e, partime:%.4e\n", integ,partime);
return 0;
}
/******************************************
* create new stack
******************************************/
void create_stack(
stack_t* stack, /* stack to create */
int element_size) /* size of a stack element */
{
int initial_size = INITIAL_STACK_SIZE;
/* allocate memory for new stack struct */
(*stack) = (stack_t) malloc(sizeof(struct stack_s));
if (!(*stack)){
fprintf(stderr, "error: could not allocate memory for stack.. Abort.\n");
exit(1);
}
/* allocate memory for stack elements */
(*stack)->elements = (void*) malloc(element_size * initial_size);
(*stack)->mem_reserve = initial_size;
if (!(*stack)->elements){
fprintf(stderr, "error: could not allocate memory for stack.. Abort.\n");
exit(1);
}
(*stack)->el_size = element_size;
(*stack)->el_count = 0;
}
/*****************************************
* check if the stack is empty
*****************************************/
int empty_stack(stack_t stack)
{
//MYMOD
if(stack==NULL)
return 1;
//ENDOF MYMOD
return stack->el_count <= 0;
}
/*****************************************
* push a element on stack
*****************************************/
void push_stack(
stack_t stack, /* target stack */
void* element) /* element to push */
{
int i, new_reserve;
int log2_count;
/* check if we need more memory for stack */
if (stack->el_count >= stack->mem_reserve)
{
/* calculate new size for the stack
it should be a power of two */
// for (i = stack->el_count, log2_count = 0; i > 0; i>>1, log2_count++);
// new_reserve = 1 << log2_count;
log2_count=0;
for(i=stack->el_count;i>0; i=i*0.5) //i>>1)
{
log2_count++;
}
new_reserve= 1 << log2_count;
/* reallocate memory for phase thread tables
and nullify new values */
stack->elements = (void *) realloc(stack->elements,
stack->el_size * new_reserve);
if (!stack->elements){
fprintf(stderr, "error: can't reallocate stack.. Aborting\n");
exit(1);
}
stack->mem_reserve = new_reserve;
}
/* now push the element on top of the stack */
memcpy((char*)stack->elements + stack->el_count*stack->el_size,
element, stack->el_size);
stack->el_count++;
}
/*****************************************
* pop an element from stack
*****************************************/
void pop_stack(
stack_t stack, /* target stack */
void* element) /* where poped el. should be stored */
{
if (stack->el_count <= 0){
fprintf(stderr, "error: trying to pop from empty stack.\n");
exit(2);
}
stack->el_count--;
memcpy(element,
(char*)stack->elements + stack->el_count*stack->el_size,
stack->el_size);
}
// ***************************************************************************
// * Gauss-kronard quadrature
// ***************************************************************************
work_gkq gkq_create_inner_task(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p)
{
work_gkq work;
work.f=f;
struct my_f_params* pinner;
pinner=(struct my_f_params*) malloc(sizeof(struct my_f_params)); //ACHTUNG: Muss wieder gefreed werden
pinner->mu= p->mu;
pinner->T=p->T;
pinner->ne=p->ne;
work.p=pinner;
work.a=a;
work.b=b;
work.subtasks_left=0;//beliebig!
double m=0.5*(a+b);
double h=0.5*(b-a);
double y[13];
double fa=y[0]=f(a,p);
double fb=y[12]=f(b,p);
int i;
for(i=1;i<12;i++)
y[i]=f(m+xgkq[i]*h,p);
double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto
double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod
625.0*(y[4]+y[8])+672.0*y[6]);
double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+
0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+
0.242611071901408*y[6]); //13-point Kronrod
double Err1=fabs(I_7-I_13);
double Err2=fabs(I_4-I_13);
double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;
double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL;
if(I_13 == 0)
I_13=b-a;
I_13=fabs(I_13);
// printf("create inner task: a:%f, b:%f, I4:%f,I7:%f,I13:%f\n",a,b,I_4,I_7,I_13);
work.toler = toler;
work.I_13=I_13;
work.fa=fa;
work.fb=fb;
work.is_parent=0;
for(i=0;i<5;i++)
work.inner_integrals[i]=0.0;
return work;
}
double gkq_double(double (*f)(double, struct my_f_params*), double (*finner)(double, struct my_f_params*),
double a, double b,
double TOL, struct my_f_params* p,stack_t stack)
{
//1st integration
//create parent task
double result=0.0;
// *********************************************
double m=0.5*(a+b);
double h=0.5*(b-a);
int i;
double y[13];
stack_t st;
create_stack(&st, sizeof(work_gkq));
double integ_bnd[2];
get_integ_bounds_inner(integ_bnd, a, p);
y[0]=f(a,p)* gkq_single(finner,integ_bnd[0],integ_bnd[1],1e-3, p, st);
for(i=1;i<12;i++)
{
get_integ_bounds_inner(integ_bnd, m+xgkq[i]*h, p);
y[i]=f(m+xgkq[i]*h,p)*gkq_single(finner,integ_bnd[0],integ_bnd[1],1e-3,p,st);
}
get_integ_bounds_inner(integ_bnd, b, p);
y[12]=f(b,p)*gkq_single(finner,integ_bnd[0],integ_bnd[1],1e-3, p, st);
free(st->elements);
free(st);
double fa=y[0];
double fb=y[12];
double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto
double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod
625.0*(y[4]+y[8])+672.0*y[6]);
double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+
0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+
0.242611071901408*y[6]); //13-point Kronrod
double Err1=fabs(I_7-I_13);
double Err2=fabs(I_4-I_13);
double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;
double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL;
if(I_13 == 0)
I_13=b-a;
I_13=fabs(I_13);
printf("First approx I_13:%.4e\n",I_13);
//Prepare work and push onto stack
work_gkq work;
work.a = a;
work.b = b;
work.toler = toler;
work.I_13=I_13;
work.fa=fa;
work.fb=fb;
work.p=p;
work.f=f;
work.is_parent=1;
work.task_nr=0; //fange bei 0 das zählen an
for(i=0;i<5;i++)
work.inner_integrals[i]=0.0;
// ALLOC INNER WS FOR INTEGR.
// gsl_integration_workspace *gsinner2= gsl_integration_workspace_alloc (1000);
stack_t stack_inner;
create_stack(&stack_inner, sizeof(work_gkq));
work.stack_inner=stack_inner;
//push work on inner stack
//for comp of 5 inner intgrals
work_gkq winner;
double m_inner, h_inner, mll_inner,ml_inner, mr_inner, mrr_inner;
m_inner= (work.a+work.b)/2;
h_inner= (work.a+work.b)/2;
mll_inner=(m_inner-alpha*h_inner);
ml_inner= (m_inner-beta*h_inner);
mr_inner= (m_inner+beta*h_inner);
mrr_inner=(m_inner+alpha*h_inner);
//1st subtask
get_integ_bounds_inner(integ_bnd, mll_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);
winner.subtask_nr=0;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//2nd subtask
get_integ_bounds_inner(integ_bnd, ml_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);
winner.subtask_nr=1;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//3rd subtask
get_integ_bounds_inner(integ_bnd, m_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);
winner.subtask_nr=2;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//4th subtask
get_integ_bounds_inner(integ_bnd, mr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);
winner.subtask_nr=3;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//5th subtask
get_integ_bounds_inner(integ_bnd, mrr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0], integ_bnd[1],1e-3, work.p);
winner.subtask_nr=4;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//push outer integtand work on outer stack
work.subtasks_left=5;
push_stack(stack, &work);
/*
int elemsinner=work.stack_inner->el_count;
int elout=stack->el_count;
work_gkq* top=(work_gkq*) stack->elements +(stack->el_count-1); //get top element
int inner2=0;
inner2=top->stack_inner->el_count;
*/
// printf("elemsinner:%d,ou:%d,in2:%d\n",elemsinner,elout, inner2);
// int in2= top->stack_inner->el_count;
result=gkq_adapt_double(stack);//,stack);
// result=gkq_adapt_serial(f,a,b,fa,fb,toler,I_13, p);
// gsl_integration_workspace_free(gsinner2);
// free(stack->elements);
return result;
}
double gkq_single(double (*f)(double, struct my_f_params*), double a, double b,
double TOL, struct my_f_params* p,stack_t stack)
{
double result=0.0;
// *********************************************
double m=0.5*(a+b);
double h=0.5*(b-a);
int i;
double y[13];
double fa=y[0]=f(a,p);
double fb=y[12]=f(b,p);
for(i=1;i<12;i++) //hier müssen direkt 13 integrale berechnet werden!!!
y[i]=f(m+xgkq[i]*h,p); //auch das sollte parallel erfolgen (pragma parfor?)
double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto
double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod
625.0*(y[4]+y[8])+672.0*y[6]);
double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+
0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+
0.242611071901408*y[6]); //13-point Kronrod
double Err1=fabs(I_7-I_13);
double Err2=fabs(I_4-I_13);
double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;
double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL;
if(I_13 == 0)
I_13=b-a;
I_13=fabs(I_13);
//Prepare work and push onto stack
work_gkq work;
work.a = a;
work.b = b;
work.toler = toler;
work.I_13=I_13;
work.fa=fa;
work.fb=fb;
work.p=p;
work.a=a;
work.f=f;
push_stack(stack, &work);
result=gkq_adapt_single(stack);//,stack);
return result;
}
double gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b,
double fa,double fb, double toler,double I_13, struct my_f_params* p)
{
double m = (a+b)/2;
double h = (b-a)/2;
double mll=m-alpha*h;
double ml=m-beta*h;
double mr=m+beta*h;
double mrr=m+alpha*h;
double fmll=f(mll,p);
double fml=f(ml,p);
double fm=f(m,p);
double fmr=f(mr,p);
double fmrr=f(mrr,p);
double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.
double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);
if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr)
{
if ((mll <= a || b <= mrr) && !terminate_serial) //Error
{
// out_of_tolerance=true; // Interval contains no more machine numbers
printf("OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\n", mll,b,b,mrr);
terminate_serial=1;
}
// printf("me ok:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\n", omp_get_thread_num(), a,b,toler,I_4,I_7);
return I_7;
}
else
{
// printf("me NOOOO:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\n", omp_get_thread_num(), a,b,toler,I_4,I_7);
return gkq_adapt_serial(f, a,mll,fa,fmll,toler,I_13,p) +
gkq_adapt_serial(f, mll,ml,fmll,fml,toler,I_13,p) +
gkq_adapt_serial(f, ml,m,fml,fm,toler,I_13,p) +
gkq_adapt_serial(f, m,mr,fm,fmr,toler,I_13,p) +
gkq_adapt_serial(f, mr,mrr,fmr,fmrr,toler,I_13,p) +
gkq_adapt_serial(f, mrr,b,fmrr,fb,toler,I_13,p);
}
}
double gkq_adapt_single(stack_t stack)
{
work_gkq work;
// work.iter=0;
int ready, idle, busy;
double integral_result = 0.0;
busy = 0;
terminate_gkq=0;
#pragma omp parallel default(none) \
shared(stack, integral_result,busy) \
private(work, idle, ready)
{
// printf("me:%d, err:%d\n",omp_get_thread_num(),simpson_error);
ready = 0;
idle = 1;
while(!ready) // && !terminate_gkq)// && !simpson_error) //<-- so NICHT!
{
#pragma omp critical (stack)
{
if (!empty_stack(stack))
{
/* we have new work */
pop_stack(stack, &work);
if (idle)
{
/* say others i'm busy */
busy += 1;
idle = 0;
}
}
else
{
/* no new work on stack */
if (!idle){
busy -= 1;
idle = 1;
}
/* nobody has anything to do; let us leave the loop */
if (busy == 0)
{
ready = 1;
}
}
} /* end critical(stack) */
if (idle)
continue; //if ready==1 --> leave loop
// double I_prev=work.I_prev;
double (*f)(double, struct my_f_params*)=work.f;
double a = work.a;
double b = work.b;
double toler = work.toler;
double I_13=work.I_13;
double fa=work.fa;
double fb=work.fb;
// int iter=work.iter;
// double *y= work.y; // brauch ich nicht!
struct my_f_params * p = work.p;
double m = (a+b)/2;
double h = (b -a)/2;
double mll=m-alpha*h;
double ml=m-beta*h;
double mr=m+beta*h;
double mrr=m+alpha*h;
double fmll=f(mll,p);
double fml=f(ml,p);
double fm=f(m,p);
double fmr=f(mr,p);
double fmrr=f(mrr,p);
double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.
double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);
// if(myid==1)
// printf("I_7:%.4e, I_13:%.4e,I_4:%.4e, minus:%.4e, to:%.4e\n",I_7,I_13,I_4,I_7-I_4, toler*I_13);
// int maxiter=50; //max. subdivisions
// double abstol=1e-30;
// work.I_prev=I_7; // für abstolcheck in nächster recursion
if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr) // || iter > maxiter || fabs(I_7-I_prev) < abstol )
{
if ((mll <= a || b <= mrr)) //Error
{
// out_of_tolerance=true; // Interval contains no more machine numbers
// printf("OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e,I_7-I_4:%.4e, tol:%.4e,I_13:%.4e\n",
// mll,b,b,mrr,I_7-I_4, toler*I_13,I_13);
}
#pragma omp critical (integral_result)
{
integral_result += I_7; //Terminate recursion.
}
}
else //subdivide interval and push new work on stack
{
#pragma omp critical (stack)
{
// work.iter=iter+1;
work.a=a;
work.b=mll;
work.fa=fa;
work.fb=fmll;
push_stack(stack, &work);
work.a=mll;
work.b=ml;
work.fa=fmll;
work.fb=fml;
push_stack(stack, &work);
work.a=ml;
work.b=m;
work.fa=fml;
work.fb=fm;
push_stack(stack, &work);
work.a=m;
work.b=mr;
work.fa=fm;
work.fb=fmr;
push_stack(stack, &work);
work.a=mr;
work.b=mrr;
work.fa=fmr;
work.fb=fmrr;
push_stack(stack, &work);
work.a=mrr;
work.b=b;
work.fa=fmrr;
work.fb=fb;
push_stack(stack, &work);
} // pragma critical stack
} // else ..non-acceptable error
} // while
} /* end omp parallel */
return integral_result;
}
double gkq_adapt_double(stack_t stack)
{
work_gkq work;
work_gkq* pwork_outer;
int ready, idle, busy;
double integral_result = 0.0;
busy = 0;
int myid;
int elcnt; //nr of outer task elements on stack
#pragma omp parallel default(none) \
shared(stack, integral_result,busy,iter,elcnt) \
private(work, idle, ready,myid,pwork_outer)
{
myid=omp_get_thread_num();
ready = 0;
idle = 1;
while(!ready) // && !terminate_gkq)// && !simpson_error) //<-- so NICHT!
{
// printf("\n NEXT, curapprox:%.4e\n",integral_result);
#pragma omp critical (stack)
{
//pointer to outer work element
//work_gkq* pwork=(work_gkq*) stack->elements + stack->el_count*stack->el_size;
elcnt=stack->el_count;
// if(elcnt>1)
// getchar();
stack_t stack_inner;
if(elcnt>0)
{
pwork_outer=(work_gkq*) stack->elements +(elcnt-1); //get top element
//IST WOHL SUBOPTIMAL
while(pwork_outer->task_nr > 0 && pwork_outer->subtasks_left==0) //this task is complete, goto next outer task
{
printf("myid:%d, outer task nr:%d, complete:subs:%d, decrement\n",myid,pwork_outer->task_nr,pwork_outer->subtasks_left);
pwork_outer--;
}
stack_inner=pwork_outer->stack_inner;
}
else
{
stack_inner=NULL;
pwork_outer=NULL;
}
printf("myid:%d,elcnt:%d,sinner:%p,pwout:%p\n",myid,elcnt,stack_inner,pwork_outer);
{ //stackinner gehört zu work, und work ist private!
if(!empty_stack(stack_inner))
{
printf("myid:%d,iter:%d, inner stack not empty,pop..\n",myid,iter);
pop_stack(stack_inner, &work);
//if letztes inner-work elem, blockiere outer work elem bis ich das integral hab
iter++;
if (idle)
{
busy += 1;
idle = 0;
}
}
else //inner stack is empty, pop from outer
{
printf("myid:%d,iter:%d, inner stack is empty?\n",myid,iter);
if (!empty_stack(stack)) //work elem ist blockiert solange inner integs nicht vollständig
{
// printf("myid:%d,iter:%d, inner stack empty. work on outer with cnt=%d\n",myid,iter,pwork_outer->subtasks_left);
if(pwork_outer->subtasks_left==0)
{
printf("myid:%d,iter:%d, outer stack not empty\n",myid,iter);
pop_stack(stack, &work);
iter++;
if (idle)
{
busy += 1;
idle = 0;
}
}
else
{
printf("myid:%d,iter:%d, inner integs not complete:%d\n",myid,iter,pwork_outer->subtasks_left);
if (!idle)
{
busy -= 1;
idle = 1;
}
}
}
else //auch outer stack ist leer
{
printf("myid:%d,iter:%d, outer stack empty too\n",myid,iter);
if (!idle)
{
busy -= 1;
idle = 1;
}
if (busy == 0)
{
ready = 1;
}
}
}
} // critical inner stack
} //critical outer stack
if (idle)
{
printf("myid:%d,iter:%d, noth8ing to do\n",myid,iter);
continue; //if ready==1 --> leave loop
}
//work on inner tasks first, if available
if(work.is_parent==0)
{
printf("myid:%d,iter:%d,tasknr:%d,innertask:%d, left subs:%d\n",
myid,iter,work.task_nr,work.subtask_nr,pwork_outer->subtasks_left); //subtasks nr nicht immer aktuell!
// getchar();
double (*f)(double, struct my_f_params*) = work.f;
double a = work.a;
double b = work.b;
double toler = work.toler;
double I_13=work.I_13;
double fa=work.fa;
double fb=work.fb;
// double *y= work.y; // brauch ich nicht!
struct my_f_params * p = work.p;
double m = (a+b)/2;
double h = (b -a)/2;
double mll=m-alpha*h;
double ml=m-beta*h;
double mr=m+beta*h;
double mrr=m+alpha*h;
double fmll=f(mll,p);
double fml=f(ml,p);
double fm=f(m,p);
double fmr=f(mr,p);
double fmrr=f(mrr,p);
double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.
double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);
// printf("myid:%d,iter:%d non parent checkpoint 1 passed\n",myid,iter);
if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr)
{
if ((mll <= a || b <= mrr))// && !terminate_gkq) //Error
{
printf("OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\n", mll,a,b,mrr);
}
// printf("myid:%d,iter:%d non parent checkpoint 2.1 passed\n",myid,iter);
int tasknr=work.subtask_nr;
printf("myid:%d,iter:%d, winner error acceptable: I_7:%.4e, I_4:%.4e, I_13:%.4e,toler*I_13:%.4e,toler:%.4e\n",
myid,iter,I_7,I_4, I_13,toler*I_13,toler);
#pragma omp critical (innerinteg) // workers greifen auf selbes array zu.nur an anderer Stelle..evtl. besser 6 versch.doubles statt array?
{
double *inner_integrals=pwork_outer->inner_integrals;
inner_integrals[tasknr]+=I_7;
pwork_outer->subtasks_left=pwork_outer->subtasks_left-1; //hier sollte subtasks_left aktuell sein
printf("myid:%d,iter:%d, inner_integral[%d]:%.4e added:%.4e,subtask left:%d\n",
myid,iter,tasknr,inner_integrals[tasknr],I_7,pwork_outer->subtasks_left);
}
}
else //subdivide interval and push new work on stack
{
stack_t stack_inner;
#pragma omp critical //(stack) //(stack_inner)
{
stack_inner = pwork_outer->stack_inner;
pwork_outer->subtasks_left=pwork_outer->subtasks_left-1;//weil dieser stack durch 6 andere ersetzt wird
work.task_nr=pwork_outer->task_nr; //inner task soll auch wissen wer sein outer task is (bisher nur für debug)
//subtasknr bleibt dieselbe (bezogen auf parent task)
work.a=a;
work.b=mll;
work.fa=fa;
work.fb=fmll;
push_stack(stack_inner, &work);
work.a=mll;
work.b=ml;
work.fa=fmll;
work.fb=fml;
push_stack(stack_inner, &work);
work.a=ml;
work.b=m;
work.fa=fml;
work.fb=fm;
push_stack(stack_inner, &work);
work.a=m;
work.b=mr;
work.fa=fm;
work.fb=fmr;
push_stack(stack_inner, &work);
work.a=mr;
work.b=mrr;
work.fa=fmr;
work.fb=fmrr;
push_stack(stack_inner, &work);
work.a=mrr;
work.b=b;
work.fa=fmrr;
work.fb=fb;
push_stack(stack_inner, &work);
pwork_outer->subtasks_left=pwork_outer->subtasks_left+6;
printf("myid:%d,iter:%d, inner_integral approx not accurate..subdivided: I_4:%f,I_7:%f,I_13:%f,left subs:%d\n",
myid,iter,I_4,I_7,I_13,pwork_outer->subtasks_left);
} // pragma critical stack_inner
} // else ..non-acceptable error
}// !isparent
else //parent task without any inner tasks
{
printf("myid:%d,iter:%d, work is parent,subs left:%d\n",myid,iter,work.subtasks_left);
// stack_t stack_inner = work.stack_inner; //brauch ich hier nicht
// free(stack_inner->elements);
// free(stack_inner);
double (*f)(double, struct my_f_params*) = work.f;
double a = work.a;
double b = work.b;
double toler = work.toler;
double I_13=work.I_13;
double fa=work.fa;
double fb=work.fb;
// double *y= work.y; // brauch ich nicht!
struct my_f_params * p = work.p;
double m = (a+b)/2;
double h = (b -a)/2;
double mll=m-alpha*h;
double ml=m-beta*h;
double mr=m+beta*h;
double mrr=m+alpha*h;
//the inner intergrals are pre-calculated and saved in an array
//the function only calculates a prefactor...
double fmll=f(mll,p)*work.inner_integrals[0];
double fml= f(ml,p)*work.inner_integrals[1];
double fm= f(m,p)*work.inner_integrals[2];
double fmr= f(mr,p)*work.inner_integrals[3];
double fmrr= f(mrr,p)*work.inner_integrals[4];
double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.
double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);
if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr)
{
if ((mll <= a || b <= mrr))// && !terminate_gkq) //Error
{
// out_of_tolerance=true; // Interval contains no more machine numbers
printf("outer task OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\n", mll,b,b,mrr);
}
//#pragma omp critical(integal_result)
{
#pragma omp atomic
integral_result += I_7;
printf("myid:%d,iter:%d, I7 added, integs: 0=%f,1=%f,2=%f,3=%f,4=%f\n", myid,iter,
work.inner_integrals[0],work.inner_integrals[1],work.inner_integrals[2],
work.inner_integrals[3],work.inner_integrals[4]);
}
}
else //subdivide interval and push new work on stack
{
printf("myid:%d,iter:%d, iouter_integral approx not accurate: I_7=%.4e,I_4=%.4e,I_13=%.4e, toler*I_13:%.4e\n"
"integs: 0=%f,1=%f,2=%f,3=%f,4=%f..subdivide\n",
myid,iter,I_7,I_4,I_13,I_13*toler,work.inner_integrals[0],work.inner_integrals[1],work.inner_integrals[2],
work.inner_integrals[3],work.inner_integrals[4] );
stack_t stack_inner = work.stack_inner;
#pragma omp critical (stack)
{
//create sub-stack for inner-integrals
work.subtasks_left=5; //for all new outer work elements
create_stack(&stack_inner, sizeof(work_gkq));
work.is_parent=1;
work_gkq winner;
//outer task elem
work.a=a;
work.b=mll;
work.fa=fa;
work.fb=fmll;
double m_inner= (work.a+work.b)/2;
double h_inner= (work.a+work.b)/2;
double mll_inner=(m_inner-alpha*h_inner);
double ml_inner= (m_inner-beta*h_inner);
double mr_inner= (m_inner+beta*h_inner);
double mrr_inner=(m_inner+alpha*h_inner);
//Jedes subinterval bekommt 5 inner tasks für die inneren integrale!
int curcnt=stack->el_count;
work.task_nr=curcnt; //weil ich bei 0 anfange zu zählen und push_stack gleich el_count incrementiert
double integ_bnd[2];
//1st subtask
get_integ_bounds_inner(integ_bnd, mll_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.task_nr=work.task_nr;
winner.subtask_nr=0;
push_stack(work.stack_inner,&winner);
//2nd subtask
get_integ_bounds_inner(integ_bnd, ml_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=1;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//3rd subtask
get_integ_bounds_inner(integ_bnd, m_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=2;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//4th subtask
get_integ_bounds_inner(integ_bnd, mr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=3;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//5th subtask
get_integ_bounds_inner(integ_bnd, mrr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=4;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
push_stack(stack, &work);
// *************************
// * 2nd subinterval
// **************************
work.a=mll;
work.b=ml;
work.fa=fmll;
work.fb=fml;
work.task_nr++;
m_inner= (work.a+work.b)/2;
h_inner= (work.a+work.b)/2;
mll_inner=(m_inner-alpha*h_inner);
ml_inner= (m_inner-beta*h_inner);
mr_inner= (m_inner+beta*h_inner);
mrr_inner=(m_inner+alpha*h_inner);
//1st subtask
get_integ_bounds_inner(integ_bnd, mll_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=0;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//2nd subtask
get_integ_bounds_inner(integ_bnd, ml_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=1;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//3rd subtask
get_integ_bounds_inner(integ_bnd, m_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=2;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//4th subtask
get_integ_bounds_inner(integ_bnd, mr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=3;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//5th subtask
get_integ_bounds_inner(integ_bnd, mrr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=4;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
// #pragma omp critical (stack)
// {
push_stack(stack, &work);
// }
// *************************
// * 3rd subinterval
// **************************
work.a=ml;
work.b=m;
work.fa=fml;
work.fb=fm;
work.task_nr++;
m_inner= (work.a+work.b)/2;
h_inner= (work.a+work.b)/2;
mll_inner=(m_inner-alpha*h_inner);
ml_inner= (m_inner-beta*h_inner);
mr_inner= (m_inner+beta*h_inner);
mrr_inner=(m_inner+alpha*h_inner);
//1st subtask
get_integ_bounds_inner(integ_bnd, mll_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=0;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//2nd subtask
get_integ_bounds_inner(integ_bnd, ml_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=1;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//3rd subtask
get_integ_bounds_inner(integ_bnd, m_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=2;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//4th subtask
get_integ_bounds_inner(integ_bnd, mr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=3;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//5th subtask
get_integ_bounds_inner(integ_bnd, mrr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2, integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=4;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
// #pragma omp critical (stack)
// {
push_stack(stack, &work);
// }
// *************************
// * 4th subinterval
// **************************
work.a=m;
work.b=mr;
work.fa=fm;
work.fb=fmr;
work.task_nr++;
m_inner= (work.a+work.b)/2;
h_inner= (work.a+work.b)/2;
mll_inner=(m_inner-alpha*h_inner);
ml_inner= (m_inner-beta*h_inner);
mr_inner= (m_inner+beta*h_inner);
mrr_inner=(m_inner+alpha*h_inner);
//1st subtask
get_integ_bounds_inner(integ_bnd, mll_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=0;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//2nd subtask
get_integ_bounds_inner(integ_bnd, ml_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=1;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//3rd subtask
get_integ_bounds_inner(integ_bnd, m_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=2;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//4th subtask
get_integ_bounds_inner(integ_bnd, mr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=3;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//5th subtask
get_integ_bounds_inner(integ_bnd, mrr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=4;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
// #pragma omp critical (stack)
{
push_stack(stack, &work);
}
// *************************
// * 5th subinterval
// **************************
work.a=mr;
work.b=mrr;
work.fa=fmr;
work.fb=fmrr;
work.task_nr++;
m_inner= (work.a+work.b)/2;
h_inner= (work.a+work.b)/2;
mll_inner=(m_inner-alpha*h_inner);
ml_inner= (m_inner-beta*h_inner);
mr_inner= (m_inner+beta*h_inner);
mrr_inner=(m_inner+alpha*h_inner);
//1st subtask
get_integ_bounds_inner(integ_bnd, mll_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=0;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//2nd subtask
get_integ_bounds_inner(integ_bnd, ml_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=1;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//3rd subtask
get_integ_bounds_inner(integ_bnd, m_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=2;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//4th subtask
get_integ_bounds_inner(integ_bnd, mr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=3;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//5th subtask
get_integ_bounds_inner(integ_bnd, mrr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=4;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
// #pragma omp critical (stack)
{
push_stack(stack, &work);
}
// *************************
// * 6th subinterval
// **************************
work.a=mrr;
work.b=b;
work.fa=fmrr;
work.fb=fb;
work.task_nr++;
m_inner= (work.a+work.b)/2;
h_inner= (work.a+work.b)/2;
mll_inner=(m_inner-alpha*h_inner);
ml_inner= (m_inner-beta*h_inner);
mr_inner= (m_inner+beta*h_inner);
mrr_inner=(m_inner+alpha*h_inner);
//1st subtask
get_integ_bounds_inner(integ_bnd, mll_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=0;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//2nd subtask
get_integ_bounds_inner(integ_bnd, ml_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=1;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//3rd subtask
get_integ_bounds_inner(integ_bnd, m_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=2;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//4th subtask
get_integ_bounds_inner(integ_bnd, mr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=3;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
//5th subtask
get_integ_bounds_inner(integ_bnd, mrr_inner, work.p);
winner=gkq_create_inner_task(inner_integrand2,integ_bnd[0],integ_bnd[1],1e-3, work.p);
winner.subtask_nr=4;
winner.task_nr=work.task_nr;
push_stack(work.stack_inner,&winner);
// #pragma omp critical (stack)
{
push_stack(stack, &work);
}
printf("myid:%d,iter:%d, 6 subinvtervals with 5 subtasks each pushed to stack outer\n",myid,iter);
} // pragma critical
} // else ..non-acceptable error
}
} // while
} /* end omp parallel */
return integral_result;
}
//SIMPSON
// *****************************************************************************************************************************************
// double integral2(double (*f)(double, struct my_f_params*), stack_t stack)
// {
// work_t work;
// int ready, idle, busy;
// double integral_result = 0.0;
// busy = 0;
// #pragma omp parallel default(none) \
// shared(stack, integral_result,f,busy,simpson_error) \
// private(work, idle, ready)
// {
// // printf("me:%d, err:%d\n",omp_get_thread_num(),simpson_error);
// ready = 0;
// idle = 1;
// while(!ready && !simpson_error) //<-- so NICHT!
// {
// #pragma omp critical (stack)
// {
// if (!empty_stack(stack))
// {
// /* we have new work */
// pop_stack(stack, &work);
// if (idle)
// {
// /* say others i'm busy */
// busy += 1;
// idle = 0;
// }
// }
// else{
// /* no new work on stack */
// if (!idle){
// busy -= 1;
// idle = 1;
// }
// /* nobody has anything to do; let us leave the loop */
// if (busy == 0)
// {
// ready = 1;
// }
// }
// } /* end critical(stack) */
// if (idle)
// continue; //if ready==1 --> leave loop
// double b = work.b;
// double a = work.a;
// double tol = work.tol;
// double S=work.S; // previous TOTAL integral
// double fa=work.fa;
// double fb=work.fb;
// double fm=work.fm;
// int rec=work.rec;
// double h = (b - a)/2;
// double mid = (a+b)/2;
// double lm=(a+mid)/2;
// double rm=(mid+b)/2;
// double flm=f(lm,work.p);
// double frm=f(rm,work.p);
// double Sl=h/6*(fa+4*flm+fm);
// double Sr=h/6*(fm+4*frm+fb);
// double delta=Sl+Sr-S;
// // serious numerical trouble: it won't converge
// if ((tol/2 == tol) || fabs(a-lm) <= tol) // || tol < tolmax)
// {
// simpson_error = 1;
// #pragma omp critical (integral_result)
// integral_result = S;
// }
// //need something against spurious convergence
// //for now: iter > 5 (c.f. numerical recipes)
// if( work.iter > 5 && (rec <= 0 || fabs(delta) <= 15*tol)) //error acceptable
// {
// #pragma omp critical (integral_result)
// integral_result += Sl+Sr+delta/15;
// }
// else // error not acceptable
// {
// //push new subintervals to stack
// work.a = a;
// work.b = mid;
// work.tol = tol/2;
// work.S = Sl;
// work.fa=fa;
// work.fb=fm;
// work.fm=flm;
// work.rec=rec-1;
// work.iter=work.iter+1;
// #pragma omp critical (stack)
// {
// //LEFT
// push_stack(stack, &work);
// //prepare RIGHT side and push to stack
// work.a = mid;
// work.b = b;
// work.tol = tol/2;
// work.S=Sr;
// work.fa=fm;
// work.fb=fb;
// work.fm=frm;
// work.rec=rec-1;
// push_stack(stack, &work);
// }
// }
// } /* while */
// } /* end omp parallel */
// return integral_result;
// } | {
"alphanum_fraction": 0.5365078178,
"avg_line_length": 30.4834663626,
"ext": "c",
"hexsha": "ff471e5ec64b45f7b10b410406dac0fe1f07dbbd",
"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": "38c053355a1fa43168d3c785d8b55d789b07f222",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "fmqeisfeld/IMD",
"max_forks_repo_path": "simpson_omp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222",
"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": "fmqeisfeld/IMD",
"max_issues_repo_path": "simpson_omp.c",
"max_line_length": 156,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "fmqeisfeld/IMD",
"max_stars_repo_path": "simpson_omp.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-08T07:49:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-30T08:23:34.000Z",
"num_tokens": 15410,
"size": 53468
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_cdf.h>
#include <omp.h>
#include "util.h"
int main(int argc, char *argv[]) {
char* input_fileName1 = argv[1];
char* input_fileName2 = argv[2];
int N_doc_bg = atoi(argv[3]);
int N_kw = atoi(argv[4]);
int N_obs = atoi(argv[5]);
int N_iter = atoi(argv[6]);
int m = atoi(argv[7]);
double p = 0.89;
double q = atof(argv[8]);
char* output_fileName = argv[9];
int N_doc = 480000/2;
int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs);
int* matrix_bg = (int*) malloc(sizeof(int) * N_kw * N_kw);
int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs);
int* true_index = (int*) malloc(sizeof(int) * N_kw);
int* permutation = (int*) malloc(sizeof(int) * N_obs);
gsl_matrix* matrix_obs;
// Setup
for (int round = 0; round < 10; round++)
{
char input_fileName1_extend[40];
char input_fileName2_extend[40];
sprintf(input_fileName1_extend, "%s%d", input_fileName1, round);
sprintf(input_fileName2_extend, "%s%d", input_fileName2, round);
struct timeval tv1,tv2;
gettimeofday(&tv1, NULL);
read_matrix(&true_index, &matrix_bg, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend);
read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend);
gettimeofday(&tv2, NULL);
printf("Reading done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
for (int iter = 0; iter < 10; iter++)
{
printf("Run %d\n", iter);
matrix_obs = gsl_matrix_alloc(N_obs, N_obs);
gettimeofday(&tv1, NULL);
pad_matrix(&matrix_padded, &matrix, m, p, q, N_obs, N_doc);
gettimeofday(&tv2, NULL);
printf("Padding done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
gettimeofday(&tv1, NULL);
observe_matrix(matrix_obs, &matrix_padded, N_obs);
gettimeofday(&tv2, NULL);
printf("Observed matrix generated: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
// Permute observed matrix randomly and attack
gettimeofday(&tv1, NULL);
attack(matrix_obs, &matrix_bg, &permutation, m, p, q, N_kw, N_obs, N_doc, N_iter);
gettimeofday(&tv2, NULL);
printf("Main attack done: %f.\n", (double) ((tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)) / N_iter);
fflush(stdout);
//for (int ii = 0; ii < 20; ii++)
// printf("%d, %d, %d, %d, %d\n", permutation[ii], true_index[ii], matrix[ii*N_obs+ii], matrix_bg[true_index[ii]*N_kw+true_index[ii]], matrix_bg[permutation[ii]*N_kw+permutation[ii]]);
char output_fileName_full[40];
sprintf(output_fileName_full, "%s%d-%d", output_fileName, round, iter);
print_result(output_fileName_full, &permutation, &true_index, N_obs);
//sprintf(output_fileName_full, "%s-%d-full", output_fileName, iter);
//print_full_result(output_fileName_full, permutation_matrix, N_kw);
}
}
free(matrix);
free(matrix_bg);
free(matrix_padded);
gsl_matrix_free(matrix_obs);
return(0);
}
double log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int m, double p, double q, int N_kw, int N_doc)
{
int idx1_m = (*permutation)[idx1];
int idx2_m = (*permutation)[idx2];
double score = 0.0;
if (idx1 == idx2)
{
int N1 = m * (*matrix)[idx1_m*N_kw + idx2_m];
double N1_mean = p * N1;
double N1_var = p * (1-p) * N1 + (m * N_doc - N1) * N1 * 1.0 / N_doc / m;
int N2 = m * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);
double N2_mean = q * N2;
double N2_var = q * (1-q) * N2 + (m * N_doc - N2) * N2 * 1.0 / N_doc / m;
double N3_var = 1.0 * m / N_doc * (*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);
int k = (int) gsl_matrix_get(matrix_obs, idx1, idx2);
score = gsl_cdf_gaussian_P(floor(k - N1_mean - N2_mean) + 0.5, sqrt(N1_var + N2_var + N3_var));
score -= gsl_cdf_gaussian_P(floor(k - N1_mean - N2_mean) - 0.5, sqrt(N1_var + N2_var + N3_var));
}
else
{
int N1 = m * (*matrix)[idx1_m*N_kw + idx2_m];
double N1_mean = p * p * N1;
double N1_var = p * p * (1-p) * (1-p)* N1;
int N2 = m * ((*matrix)[idx1_m*N_kw + idx1_m] + (*matrix)[idx2_m*N_kw + idx2_m] - 2*(*matrix)[idx1_m*N_kw + idx2_m]);
double N2_mean = p * q * N2;
double N2_var = p * q * (1-p) * (1-q) * N2;
int N3 = m * N_doc - N1 - N2;
double N3_mean = q * q * N3;
double N3_var = q * q * (1-q) * (1-q) * N3;
double N4_var = 1.0 * m / N_doc * (*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);
int M = (int) gsl_matrix_get(matrix_obs, idx1, idx2);
score = gsl_cdf_gaussian_P(floor(M - N1_mean - N2_mean - N3_mean) + 0.5, sqrt(N1_var + N2_var + N3_var + N4_var));
score -= gsl_cdf_gaussian_P(floor(M - N1_mean - N2_mean - N3_mean) - 0.5, sqrt(N1_var + N2_var + N3_var + N4_var));
}
if (score == 0)
return(-500.0);
return(log(score));
}
void attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int m, double p, double q, int N_kw, int N_obs, int N_doc, int N_iter)
{
// Initialise data structures
double* score_matrix = (double*) malloc(sizeof(double) * N_kw * N_kw);
double* score_row1 = (double*) malloc(sizeof(double) * N_kw);
double* score_row2 = (double*) malloc(sizeof(double) * N_kw);
int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs);
int* permutation_inv = (int*) malloc(sizeof(int) * N_kw);
// Initialising RNG
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
struct timeval tv1,tv2;
gettimeofday(&tv1, NULL);
solution_initial(permutation, matrix_obs, matrix, m, p, q, N_kw, N_obs, N_doc);
for (int ii = 0; ii < N_obs; ii++)
permutation_tmp[ii] = (*permutation)[ii];
for (int ii = 0; ii < N_kw; ii++)
permutation_inv[ii] = -1;
for (int ii = 0; ii < N_obs; ii++)
permutation_inv[permutation_tmp[ii]] = ii;
// Compute initial score
#pragma omp parallel for shared(score_matrix, matrix_obs, matrix)
for (int ii = 0; ii < N_obs * N_obs; ii++)
score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, m, p, q, N_kw, N_doc);
gettimeofday(&tv2, NULL);
printf("Initial score computed: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
// Iterations of simulated annealing
double temp = (double) N_kw;
int N_stuck = 0;
for (int iter = 0; iter < N_iter; iter++)
{
/* Status code */
if (iter % (N_iter / 10) == 0)
{
gettimeofday(&tv1, NULL);
printf("Iteration: %d, %d, %d.\n", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec));
fflush(stdout);
gettimeofday(&tv2, NULL);
}
if (N_stuck >= (N_iter / 20))
iter = N_iter;
int idx1, idx2;
permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, matrix_obs, matrix, m, p, q, N_kw, N_obs, N_doc);
if (idx1 == idx2)
{
N_stuck++;
continue;
}
int ii = 0;
#pragma omp parallel for shared(score_row1)
for (ii = 0; ii < N_obs; ii++)
score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, m, p, q, N_kw, N_doc);
if (idx2 >= 0)
#pragma omp parallel for shared(score_row2)
for (ii = 0; ii < N_obs; ii++)
score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, m, p, q, N_kw, N_doc);
double score_diff = 0;
for (int ii = 0; ii < N_obs; ii++)
score_diff += score_row1[ii];
for (int ii = 0; ii < N_obs; ii++)
score_diff -= score_matrix[idx1*N_obs + ii];
if (idx2 >= 0)
{
for (int ii = 0; ii < N_obs; ii++)
score_diff += score_row2[ii];
for (int ii = 0; ii < N_obs; ii++)
score_diff -= score_matrix[idx2*N_obs + ii];
}
// compute difference in score, with exponentiation
score_diff = score_diff / temp;
if (score_diff < -40)
score_diff = 0;
else if (score_diff > 0)
score_diff = 1.01;
else
score_diff = exp(score_diff);
if (gsl_ran_flat(r, 0, 1) < score_diff)
{
// Update the scores
for (int ii = 0; ii < N_obs; ii++)
score_matrix[idx1*N_obs + ii] = score_row1[ii];
for (int ii = 0; ii < N_obs; ii++)
score_matrix[ii*N_obs + idx1] = score_row1[ii];
if (idx2 >= 0)
{
for (int ii = 0; ii < N_obs; ii++)
score_matrix[idx2*N_obs + ii] = score_row2[ii];
for (int ii = 0; ii < N_obs; ii++)
score_matrix[ii*N_obs + idx2] = score_row2[ii];
}
// Update the permutation
permutation_inv[(*permutation)[idx1]] = -1;
(*permutation)[idx1] = permutation_tmp[idx1];
permutation_inv[permutation_tmp[idx1]] = idx1;
if (idx2 >= 0)
{
(*permutation)[idx2] = permutation_tmp[idx2];
permutation_inv[permutation_tmp[idx2]] = idx2;
}
N_stuck = 0;
}
else
{
// Update the permutation
permutation_tmp[idx1] = (*permutation)[idx1];
if (idx2 >= 0)
permutation_tmp[idx2] = (*permutation)[idx2];
N_stuck += 1;
}
temp *= 0.995;
}
free(score_matrix);
free(score_row1);
free(score_row2);
gsl_rng_free(r);
}
void print_result(char* output_fileName, int** permutation, int** true_index, int N_obs)
{
FILE* fp = fopen(output_fileName, "w");
int count = 0;
int count2 = 0;
for (int ii = 0; ii < N_obs; ii++)
if ((*permutation)[ii] == (*true_index)[ii])
count++;
fprintf(fp, "%d\n", count);
fclose(fp);
printf("Success: %d/%d.\n", count, N_obs);
}
void print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs)
{
FILE* fp = fopen(output_fileName, "w");
int count = 0;
for (int ii = 0; ii < N_obs; ii++)
if ((*permutation)[ii] == (*true_index)[ii])
count++;
fprintf(fp, "%d\n", count);
fclose(fp);
} | {
"alphanum_fraction": 0.5585177286,
"avg_line_length": 35.165625,
"ext": "c",
"hexsha": "31fd86512611923e8739731be2727105d4670c8d",
"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": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_forks_repo_path": "DPAP-SE/attack_mp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"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": "RethinkingSSE/Attacks-on-SSE",
"max_issues_repo_path": "DPAP-SE/attack_mp.c",
"max_line_length": 198,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_stars_repo_path": "DPAP-SE/attack_mp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3366,
"size": 11253
} |
/*solver/fixed_point.c
* Solves a fixed point equation using
* sequence acceleration.
*
* Author: Benjamin Vatter j.
* email : benjaminvatterj@gmail.com
* date: 15 August 2015
*/
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include "fixed_point.h"
/*
* Finds the fixed point of a function f
* Translated from SciPy's fixed_point function
*/
void fixed_point(int n, ff_function *f, double *x0,
double xtol, int maxiter, double *out)
{
//out = malloc(sizeof(double)*n);
double *p = malloc(sizeof(double)*n);
double *p1, *p2;
double d;
int pass;
int i, j;
for (i=0; i<n; i++)
out[i] = x0[i];
for (i=0; i<maxiter; i++)
{
p1 = malloc(sizeof(double)*n);
p2 = malloc(sizeof(double)*n);
f->function(out, f->params, p1);
f->function(p1, f->params, p2);
pass = 1;
for (j=0; j<n; j++)
{
d = p2[j] - 2.0*p1[j] + out[j];
if (d==0) {
p[j] = p2[j];
} else {
p[j] = out[j] - pow(p1[j] - out[j], 2.0) / d;
}
if (out[j] == 0 && fabs(p[j]) > xtol){
pass = 0;
}
if (out[j] != 0 && (p[j] - out[j])/out[j] > xtol){
pass = 0;
}
out[j] = p[j];
}
if (pass == 1) {
free(p1);
free(p2);
break;
}
if(i+1 >= maxiter){
free(p1);
free(p2);
pass = -1;
break;
}
free(p1);
free(p2);
}
free(p);
// Free garbage result in case of no convergence
if (pass == -1) {
free(out);
}
}
| {
"alphanum_fraction": 0.5455197133,
"avg_line_length": 17.8846153846,
"ext": "c",
"hexsha": "1c2c9a9bc56735e984aac4839f8fe516e44d208c",
"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": "0e38ce207ed835e7a3d49381966113809d394dc2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "benjaminvatterj/multidim_integration",
"max_forks_repo_path": "fixed_point.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2",
"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": "benjaminvatterj/multidim_integration",
"max_issues_repo_path": "fixed_point.c",
"max_line_length": 55,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "benjaminvatterj/multidim_integration",
"max_stars_repo_path": "fixed_point.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 512,
"size": 1395
} |
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file rk_4_3.c
* \brief Source file to optimize Runge-Kutta 4 steps 3rd order methods.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <string.h>
#include <math.h>
#include <libxml/parser.h>
#include <glib.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#include "config.h"
#include "utils.h"
#include "optimize.h"
#include "rk.h"
#include "rk_4_3.h"
#define DEBUG_RK_4_3 0 ///< macro to debug.
/**
* Function to obtain the coefficients of a 4 steps 3rd order Runge-Kutta
* method.
*/
int
rk_tb_4_3 (Optimize * optimize) ///< Optimize struct.
{
long double *tb, *r;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_tb_4_3: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t4 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b32 (tb) = r[4];
b43 (tb) = r[5];
b42 (tb) = ((1.L / 3.L - b43 (tb) * sqr (t3 (tb)))
- t1 (tb) * (0.5L - b43 (tb) * t3 (tb)))
/ (t2 (tb) * (t2 (tb) - t1 (tb)));
if (isnan (b42 (tb)))
return 0;
b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb);
if (isnan (b41 (tb)))
return 0;
b31 (tb) = ((1.L / 6.L - b42 (tb) * b21 (tb) * t1 (tb)) / b43 (tb)
- b32 (tb) * t2 (tb)) / t1 (tb);
if (isnan (b31 (tb)))
return 0;
rk_b_4 (tb);
#if DEBUG_RK_4_3
fprintf (stderr, "rk_tb_4_3: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 4 steps 3rd order, 4th order in
* equations depending only in time, Runge-Kutta method.
*/
int
rk_tb_4_3t (Optimize * optimize) ///< Optimize struct.
{
long double *tb, *r;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_tb_4_3t: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t4 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b32 (tb) = r[4];
b43 (tb) = (0.25L - 1.L / 3.L * t1 (tb)
- (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb))
/ (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb)));
b42 (tb) = ((1.L / 3.L - b43 (tb) * sqr (t3 (tb)))
- t1 (tb) * (0.5L - b43 (tb) * t3 (tb)))
/ (t2 (tb) * (t2 (tb) - t1 (tb)));
b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb);
b31 (tb) = ((1.L / 6.L - b42 (tb) * b21 (tb) * t1 (tb)) / b43 (tb)
- b32 (tb) * t2 (tb)) / t1 (tb);
rk_b_4 (tb);
#if DEBUG_RK_4_3
fprintf (stderr, "rk_tb_4_3t: end\n");
#endif
if (isnan (b31 (tb)) || isnan (b41 (tb)) || isnan (b42 (tb))
|| isnan (b43 (tb)))
return 0;
return 1;
}
/**
* Function to obtain the coefficients of a 4 steps 2nd-3rd order Runge-Kutta
* pair.
*/
int
rk_tb_4_3p (Optimize * optimize) ///< Optimize struct.
{
long double *tb;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_tb_4_3p: start\n");
#endif
if (!rk_tb_4_3 (optimize))
return 0;
tb = optimize->coefficient;
e41 (tb) = 0.5L / t1 (tb);
e42 (tb) = 0.L;
rk_e_4 (tb);
#if DEBUG_RK_4_3
rk_print_e (optimize, "rk_tb_4_3p", stderr);
fprintf (stderr, "rk_tb_4_3p: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 4 steps 2nd-3rd order, 3rd-4th order
* in equations depending only in time, Runge-Kutta pair.
*/
int
rk_tb_4_3tp (Optimize * optimize) ///< Optimize struct.
{
long double *tb;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_tb_4_3tp: start\n");
#endif
if (!rk_tb_4_3t (optimize))
return 0;
tb = optimize->coefficient;
e42 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb)));
e41 (tb) = (0.5L - e42 (tb) * t2 (tb)) / t1 (tb);
rk_e_4 (tb);
#if DEBUG_RK_4_3
rk_print_e (optimize, "rk_tb_4_3tp", stderr);
fprintf (stderr, "rk_tb_4_3tp: end\n");
#endif
if (isnan (e42 (tb)) || isnan (e41 (tb)))
return 0;
return 1;
}
/**
* Function to calculate the objective function of a 4 steps 3rd order
* Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_4_3 (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b31 (tb) < 0.L)
o += b31 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_4_3: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 4 steps 3rd order, 4th
* oder in equations depending only in time, Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_4_3t (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3t: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b31 (tb) < 0.L)
o += b31 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3t: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_4_3t: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 4 steps 2nd-3rd order
* Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_4_3p (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3p: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b31 (tb) < 0.L)
o += b31 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (e40 (tb) < 0.L)
o += e40 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3p: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_4_3p: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 4 steps 2nd-3rd order,
* 3rd-4th oder in equations depending only in time, Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_4_3tp (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3tp: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b31 (tb) < 0.L)
o += b31 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (e40 (tb) < 0.L)
o += e40 (tb);
if (e41 (tb) < 0.L)
o += e41 (tb);
if (e42 (tb) < 0.L)
o += e42 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_4_3
fprintf (stderr, "rk_objective_tb_4_3tp: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_4_3tp: end\n");
#endif
return o;
}
| {
"alphanum_fraction": 0.5890761681,
"avg_line_length": 25.5422343324,
"ext": "c",
"hexsha": "34f65a4bd481a8ff05fa18b4d79593e5e70d9fce",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ode",
"max_forks_repo_path": "rk_4_3.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/ode",
"max_issues_repo_path": "rk_4_3.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ode",
"max_stars_repo_path": "rk_4_3.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3574,
"size": 9374
} |
#include <gbpLib.h>
#include <gbpMisc.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_spline.h>
void compute_triaxiality(double *x_in,
double *y_in,
double *z_in,
double x_cen,
double y_cen,
double z_cen,
double box_size,
int n_particles,
size_t *sort_index,
double return_values[3],
double return_vectors[3][3]) {
double s, s_new;
double q, q_new;
double a_new;
double b_new;
double c_new;
int i, j;
double M_tmp;
double x_tmp;
double y_tmp;
double z_tmp;
double * m_p;
double * x;
double * y;
double * z;
double inv_q2;
double inv_s2;
double inv_r2, r2;
double M[9];
int n_iterations;
int continue_flag;
double convergence = 0.0001;
int n_iterations_max = 200;
gsl_vector * eigen_vector;
gsl_matrix * eigen_matrix;
gsl_eigen_symmv_workspace *w;
gsl_matrix_view m;
// Initialize a bunch of stuff
a_new = 1.;
b_new = 1.;
c_new = 1.;
q_new = 1.;
s_new = 1.;
return_vectors[0][0] = 1.;
return_vectors[1][0] = 0.;
return_vectors[2][0] = 0.;
return_vectors[0][1] = 0.;
return_vectors[1][1] = 1.;
return_vectors[2][1] = 0.;
return_vectors[0][2] = 0.;
return_vectors[1][2] = 0.;
return_vectors[2][2] = 1.;
if(n_particles > 0)
continue_flag = GBP_TRUE;
else
continue_flag = GBP_FALSE;
eigen_vector = gsl_vector_alloc(3);
eigen_matrix = gsl_matrix_alloc(3, 3);
w = gsl_eigen_symmv_alloc(3);
m_p = (double *)SID_malloc(sizeof(double) * n_particles);
x = (double *)SID_malloc(sizeof(double) * n_particles);
y = (double *)SID_malloc(sizeof(double) * n_particles);
z = (double *)SID_malloc(sizeof(double) * n_particles);
if(sort_index != NULL) {
for(i = 0; i < n_particles; i++) {
m_p[i] = 1.;
x[i] = d_periodic((double)x_in[sort_index[i]] - x_cen, box_size);
y[i] = d_periodic((double)y_in[sort_index[i]] - y_cen, box_size);
z[i] = d_periodic((double)z_in[sort_index[i]] - z_cen, box_size);
}
} else {
for(i = 0; i < n_particles; i++) {
m_p[i] = 1.;
x[i] = d_periodic((double)x_in[i] - x_cen, box_size);
y[i] = d_periodic((double)y_in[i] - y_cen, box_size);
z[i] = d_periodic((double)z_in[i] - z_cen, box_size);
}
}
// Iterate until convergence
n_iterations = 0;
while(continue_flag) {
q = q_new;
s = s_new;
inv_q2 = 1. / (q * q);
inv_s2 = 1. / (s * s);
// Construct the moment of inertia tensor
for(i = 0; i < 9; i++)
M[i] = 0.;
for(i = 0; i < n_particles; i++) {
x_tmp = x[i];
y_tmp = y[i];
z_tmp = z[i];
M_tmp = m_p[i];
r2 = x_tmp * x_tmp + y_tmp * y_tmp * inv_q2 + z_tmp * z_tmp * inv_s2;
if(r2 > 0.) {
inv_r2 = 1. / r2;
M[0] += x_tmp * x_tmp * M_tmp * inv_r2;
M[1] += y_tmp * x_tmp * M_tmp * inv_r2;
M[2] += z_tmp * x_tmp * M_tmp * inv_r2;
M[3] += x_tmp * y_tmp * M_tmp * inv_r2;
M[4] += y_tmp * y_tmp * M_tmp * inv_r2;
M[5] += z_tmp * y_tmp * M_tmp * inv_r2;
M[6] += x_tmp * z_tmp * M_tmp * inv_r2;
M[7] += y_tmp * z_tmp * M_tmp * inv_r2;
M[8] += z_tmp * z_tmp * M_tmp * inv_r2;
}
}
// Solve for (and sort) the eigen values and eigen vectors
m = gsl_matrix_view_array(M, 3, 3);
gsl_eigen_symmv(&m.matrix, eigen_vector, eigen_matrix, w);
gsl_eigen_symmv_sort(eigen_vector, eigen_matrix, GSL_EIGEN_SORT_ABS_DESC);
// Convert gsl vectors and such into something simpler to use
for(i = 0; i < 3; i++) {
return_values[i] = sqrt(gsl_vector_get(eigen_vector, i));
return_vectors[i][0] = gsl_matrix_get(eigen_matrix, 0, i);
return_vectors[i][1] = gsl_matrix_get(eigen_matrix, 1, i);
return_vectors[i][2] = gsl_matrix_get(eigen_matrix, 2, i);
}
q_new = return_values[1] / return_values[0];
s_new = return_values[2] / return_values[0];
// Check for convergence
n_iterations++;
if(n_iterations >= n_iterations_max)
continue_flag = GBP_FALSE;
if((double)fabs((float)((q_new - q) / q)) < convergence && (double)fabs((float)((s_new - s) / s)) < convergence)
continue_flag = GBP_FALSE;
}
// Clean-up
gsl_eigen_symmv_free(w);
gsl_vector_free(eigen_vector);
gsl_matrix_free(eigen_matrix);
SID_free((void **)(&x));
SID_free((void **)(&y));
SID_free((void **)(&z));
SID_free((void **)(&m_p));
}
| {
"alphanum_fraction": 0.469928108,
"avg_line_length": 37.2745098039,
"ext": "c",
"hexsha": "0fc7f329993a9ac7daae2dbdacb82efbe12cef39",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpMath/gbpMisc/compute_triaxiality.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpMath/gbpMisc/compute_triaxiality.c",
"max_line_length": 120,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpMath/gbpMisc/compute_triaxiality.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 1533,
"size": 5703
} |
/* ode-initval/bsimp.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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.
*/
/* Bulirsch-Stoer Implicit */
/* Author: G. Jungman
*/
/* Bader-Deuflhard implicit extrapolative stepper.
* [Numer. Math., 41, 373 (1983)]
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_odeiv.h>
#include "odeiv_util.h"
#define SEQUENCE_COUNT 8
#define SEQUENCE_MAX 7
/* Bader-Deuflhard extrapolation sequence */
static const int bd_sequence[SEQUENCE_COUNT] =
{ 2, 6, 10, 14, 22, 34, 50, 70 };
typedef struct
{
gsl_matrix *d; /* workspace for extrapolation */
gsl_matrix *a_mat; /* workspace for linear system matrix */
gsl_permutation *p_vec; /* workspace for LU permutation */
double x[SEQUENCE_MAX]; /* workspace for extrapolation */
/* state info */
size_t k_current;
size_t k_choice;
double h_next;
double eps;
/* workspace for extrapolation step */
double *yp;
double *y_save;
double *yerr_save;
double *y_extrap_save;
double *y_extrap_sequence;
double *extrap_work;
double *dfdt;
double *y_temp;
double *delta_temp;
double *weight;
gsl_matrix *dfdy;
/* workspace for the basic stepper */
double *rhs_temp;
double *delta;
/* order of last step */
size_t order;
}
bsimp_state_t;
/* Compute weighting factor */
static void
compute_weights (const double y[], double w[], size_t dim)
{
size_t i;
for (i = 0; i < dim; i++)
{
double u = fabs(y[i]);
w[i] = (u > 0.0) ? u : 1.0;
}
}
/* Calculate a choice for the "order" of the method, using the
* Deuflhard criteria.
*/
static size_t
bsimp_deuf_kchoice (double eps, size_t dimension)
{
const double safety_f = 0.25;
const double small_eps = safety_f * eps;
double a_work[SEQUENCE_COUNT];
double alpha[SEQUENCE_MAX][SEQUENCE_MAX];
int i, k;
a_work[0] = bd_sequence[0] + 1.0;
for (k = 0; k < SEQUENCE_MAX; k++)
{
a_work[k + 1] = a_work[k] + bd_sequence[k + 1];
}
for (i = 0; i < SEQUENCE_MAX; i++)
{
alpha[i][i] = 1.0;
for (k = 0; k < i; k++)
{
const double tmp1 = a_work[k + 1] - a_work[i + 1];
const double tmp2 = (a_work[i + 1] - a_work[0] + 1.0) * (2 * k + 1);
alpha[k][i] = pow (small_eps, tmp1 / tmp2);
}
}
a_work[0] += dimension;
for (k = 0; k < SEQUENCE_MAX; k++)
{
a_work[k + 1] = a_work[k] + bd_sequence[k + 1];
}
for (k = 0; k < SEQUENCE_MAX - 1; k++)
{
if (a_work[k + 2] > a_work[k + 1] * alpha[k][k + 1])
break;
}
return k;
}
static void
poly_extrap (gsl_matrix * d,
const double x[],
const unsigned int i_step,
const double x_i,
const double y_i[],
double y_0[], double y_0_err[], double work[], const size_t dim)
{
size_t j, k;
DBL_MEMCPY (y_0_err, y_i, dim);
DBL_MEMCPY (y_0, y_i, dim);
if (i_step == 0)
{
for (j = 0; j < dim; j++)
{
gsl_matrix_set (d, 0, j, y_i[j]);
}
}
else
{
DBL_MEMCPY (work, y_i, dim);
for (k = 0; k < i_step; k++)
{
double delta = 1.0 / (x[i_step - k - 1] - x_i);
const double f1 = delta * x_i;
const double f2 = delta * x[i_step - k - 1];
for (j = 0; j < dim; j++)
{
const double q_kj = gsl_matrix_get (d, k, j);
gsl_matrix_set (d, k, j, y_0_err[j]);
delta = work[j] - q_kj;
y_0_err[j] = f1 * delta;
work[j] = f2 * delta;
y_0[j] += y_0_err[j];
}
}
for (j = 0; j < dim; j++)
{
gsl_matrix_set (d, i_step, j, y_0_err[j]);
}
}
}
/* Basic implicit Bulirsch-Stoer step. Divide the step h_total into
* n_step smaller steps and do the Bader-Deuflhard semi-implicit
* iteration. */
static int
bsimp_step_local (void *vstate,
size_t dim,
const double t0,
const double h_total,
const unsigned int n_step,
const double y[],
const double yp[],
const double dfdt[],
const gsl_matrix * dfdy,
double y_out[],
const gsl_odeiv_system * sys)
{
bsimp_state_t *state = (bsimp_state_t *) vstate;
gsl_matrix *const a_mat = state->a_mat;
gsl_permutation *const p_vec = state->p_vec;
double *const delta = state->delta;
double *const y_temp = state->y_temp;
double *const delta_temp = state->delta_temp;
double *const rhs_temp = state->rhs_temp;
double *const w = state->weight;
gsl_vector_view y_temp_vec = gsl_vector_view_array (y_temp, dim);
gsl_vector_view delta_temp_vec = gsl_vector_view_array (delta_temp, dim);
gsl_vector_view rhs_temp_vec = gsl_vector_view_array (rhs_temp, dim);
const double h = h_total / n_step;
double t = t0 + h;
double sum;
/* This is the factor sigma referred to in equation 3.4 of the
paper. A relative change in y exceeding sigma indicates a
runaway behavior. According to the authors suitable values for
sigma are >>1. I have chosen a value of 100*dim. BJG */
const double max_sum = 100.0 * dim;
int signum, status;
size_t i, j;
size_t n_inter;
/* Calculate the matrix for the linear system. */
for (i = 0; i < dim; i++)
{
for (j = 0; j < dim; j++)
{
gsl_matrix_set (a_mat, i, j, -h * gsl_matrix_get (dfdy, i, j));
}
gsl_matrix_set (a_mat, i, i, gsl_matrix_get (a_mat, i, i) + 1.0);
}
/* LU decomposition for the linear system. */
gsl_linalg_LU_decomp (a_mat, p_vec, &signum);
/* Compute weighting factors */
compute_weights (y, w, dim);
/* Initial step. */
for (i = 0; i < dim; i++)
{
y_temp[i] = h * (yp[i] + h * dfdt[i]);
}
gsl_linalg_LU_solve (a_mat, p_vec, &y_temp_vec.vector, &delta_temp_vec.vector);
sum = 0.0;
for (i = 0; i < dim; i++)
{
const double di = delta_temp[i];
delta[i] = di;
y_temp[i] = y[i] + di;
sum += fabs(di) / w[i];
}
if (sum > max_sum)
{
return GSL_EFAILED ;
}
/* Intermediate steps. */
status = GSL_ODEIV_FN_EVAL (sys, t, y_temp, y_out);
if (status)
{
return status;
}
for (n_inter = 1; n_inter < n_step; n_inter++)
{
for (i = 0; i < dim; i++)
{
rhs_temp[i] = h * y_out[i] - delta[i];
}
gsl_linalg_LU_solve (a_mat, p_vec, &rhs_temp_vec.vector, &delta_temp_vec.vector);
sum = 0.0;
for (i = 0; i < dim; i++)
{
delta[i] += 2.0 * delta_temp[i];
y_temp[i] += delta[i];
sum += fabs(delta[i]) / w[i];
}
if (sum > max_sum)
{
return GSL_EFAILED ;
}
t += h;
status = GSL_ODEIV_FN_EVAL (sys, t, y_temp, y_out);
if (status)
{
return status;
}
}
/* Final step. */
for (i = 0; i < dim; i++)
{
rhs_temp[i] = h * y_out[i] - delta[i];
}
gsl_linalg_LU_solve (a_mat, p_vec, &rhs_temp_vec.vector, &delta_temp_vec.vector);
sum = 0.0;
for (i = 0; i < dim; i++)
{
y_out[i] = y_temp[i] + delta_temp[i];
sum += fabs(delta_temp[i]) / w[i];
}
if (sum > max_sum)
{
return GSL_EFAILED ;
}
return GSL_SUCCESS;
}
static void *
bsimp_alloc (size_t dim)
{
bsimp_state_t *state = (bsimp_state_t *) malloc (sizeof (bsimp_state_t));
state->d = gsl_matrix_alloc (SEQUENCE_MAX, dim);
state->a_mat = gsl_matrix_alloc (dim, dim);
state->p_vec = gsl_permutation_alloc (dim);
state->yp = (double *) malloc (dim * sizeof (double));
state->y_save = (double *) malloc (dim * sizeof (double));
state->yerr_save = (double *) malloc (dim * sizeof (double));
state->y_extrap_save = (double *) malloc (dim * sizeof (double));
state->y_extrap_sequence = (double *) malloc (dim * sizeof (double));
state->extrap_work = (double *) malloc (dim * sizeof (double));
state->dfdt = (double *) malloc (dim * sizeof (double));
state->y_temp = (double *) malloc (dim * sizeof (double));
state->delta_temp = (double *) malloc (dim * sizeof(double));
state->weight = (double *) malloc (dim * sizeof(double));
state->dfdy = gsl_matrix_alloc (dim, dim);
state->rhs_temp = (double *) malloc (dim * sizeof(double));
state->delta = (double *) malloc (dim * sizeof (double));
{
size_t k_choice = bsimp_deuf_kchoice (GSL_SQRT_DBL_EPSILON, dim); /*FIXME: choice of epsilon? */
state->k_choice = k_choice;
state->k_current = k_choice;
state->order = 2 * k_choice;
}
state->h_next = -GSL_SQRT_DBL_MAX;
return state;
}
/* Perform the basic semi-implicit extrapolation
* step, of size h, at a Deuflhard determined order.
*/
static int
bsimp_apply (void *vstate,
size_t dim,
double t,
double h,
double y[],
double yerr[],
const double dydt_in[],
double dydt_out[],
const gsl_odeiv_system * sys)
{
bsimp_state_t *state = (bsimp_state_t *) vstate;
double *const x = state->x;
double *const yp = state->yp;
double *const y_save = state->y_save;
double *const yerr_save = state->yerr_save;
double *const y_extrap_sequence = state->y_extrap_sequence;
double *const y_extrap_save = state->y_extrap_save;
double *const extrap_work = state->extrap_work;
double *const dfdt = state->dfdt;
gsl_matrix *d = state->d;
gsl_matrix *dfdy = state->dfdy;
const double t_local = t;
size_t i, k;
if (h + t_local == t_local)
{
return GSL_EUNDRFLW; /* FIXME: error condition */
}
DBL_MEMCPY (y_extrap_save, y, dim);
/* Save inputs */
DBL_MEMCPY (y_save, y, dim);
DBL_MEMCPY (yerr_save, yerr, dim);
/* Evaluate the derivative. */
if (dydt_in != NULL)
{
DBL_MEMCPY (yp, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t_local, y, yp);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Evaluate the Jacobian for the system. */
{
int s = GSL_ODEIV_JA_EVAL (sys, t_local, y, dfdy->data, dfdt);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Make a series of refined extrapolations,
* up to the specified maximum order, which
* was calculated based on the Deuflhard
* criterion upon state initialization. */
for (k = 0; k <= state->k_current; k++)
{
const unsigned int N = bd_sequence[k];
const double r = (h / N);
const double x_k = r * r;
int status = bsimp_step_local (state,
dim, t_local, h, N,
y_extrap_save, yp,
dfdt, dfdy,
y_extrap_sequence,
sys);
if (status == GSL_EFAILED)
{
/* If the local step fails, set the error to infinity in
order to force a reduction in the step size */
for (i = 0; i < dim; i++)
{
yerr[i] = GSL_POSINF;
}
break;
}
else if (status != GSL_SUCCESS)
{
return status;
}
x[k] = x_k;
poly_extrap (d, x, k, x_k, y_extrap_sequence, y, yerr, extrap_work, dim);
}
/* Evaluate dydt_out[]. */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);
if (s != GSL_SUCCESS)
{
DBL_MEMCPY (y, y_save, dim);
DBL_MEMCPY (yerr, yerr_save, dim);
return s;
}
}
return GSL_SUCCESS;
}
static unsigned int
bsimp_order (void *vstate)
{
bsimp_state_t *state = (bsimp_state_t *) vstate;
return state->order;
}
static int
bsimp_reset (void *vstate, size_t dim)
{
bsimp_state_t *state = (bsimp_state_t *) vstate;
state->h_next = 0;
DBL_ZERO_MEMSET (state->yp, dim);
return GSL_SUCCESS;
}
static void
bsimp_free (void * vstate)
{
bsimp_state_t *state = (bsimp_state_t *) vstate;
free (state->delta);
free (state->rhs_temp);
gsl_matrix_free (state->dfdy);
free (state->weight);
free (state->delta_temp);
free (state->y_temp);
free (state->dfdt);
free (state->extrap_work);
free (state->y_extrap_sequence);
free (state->y_extrap_save);
free (state->y_save);
free (state->yerr_save);
free (state->yp);
gsl_permutation_free (state->p_vec);
gsl_matrix_free (state->a_mat);
gsl_matrix_free (state->d);
free (state);
}
static const gsl_odeiv_step_type bsimp_type = {
"bsimp", /* name */
1, /* can use dydt_in */
1, /* gives exact dydt_out */
&bsimp_alloc,
&bsimp_apply,
&bsimp_reset,
&bsimp_order,
&bsimp_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_bsimp = &bsimp_type;
| {
"alphanum_fraction": 0.5753513983,
"avg_line_length": 24.2992957746,
"ext": "c",
"hexsha": "235519505192c1f1f58e1c857062788e1b9e2b85",
"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/bsimp.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/bsimp.c",
"max_line_length": 100,
"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/bsimp.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": 4082,
"size": 13802
} |
/* eigen/nonsymm.c
*
* Copyright (C) 2006 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_vector_complex.h>
#include <gsl/gsl_matrix.h>
/*
* This module computes the eigenvalues of a real nonsymmetric
* matrix, using the double shift Francis method.
*
* See the references in francis.c.
*
* This module gets the matrix ready by balancing it and
* reducing it to Hessenberg form before passing it to the
* francis module.
*/
/*
gsl_eigen_nonsymm_alloc()
Allocate a workspace for solving the nonsymmetric eigenvalue problem.
The size of this workspace is O(2n)
Inputs: n - size of matrix
Return: pointer to workspace
*/
gsl_eigen_nonsymm_workspace *
gsl_eigen_nonsymm_alloc(const size_t n)
{
gsl_eigen_nonsymm_workspace *w;
if (n == 0)
{
GSL_ERROR_NULL ("matrix dimension must be positive integer",
GSL_EINVAL);
}
w = (gsl_eigen_nonsymm_workspace *)
malloc (sizeof (gsl_eigen_nonsymm_workspace));
if (w == 0)
{
GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM);
}
w->size = n;
w->Z = NULL;
w->do_balance = 0;
w->diag = gsl_vector_alloc(n);
if (w->diag == 0)
{
GSL_ERROR_NULL ("failed to allocate space for balancing vector", GSL_ENOMEM);
}
w->tau = gsl_vector_alloc(n);
if (w->tau == 0)
{
GSL_ERROR_NULL ("failed to allocate space for hessenberg coefficients", GSL_ENOMEM);
}
w->francis_workspace_p = gsl_eigen_francis_alloc();
if (w->francis_workspace_p == 0)
{
GSL_ERROR_NULL ("failed to allocate space for francis workspace", GSL_ENOMEM);
}
return (w);
} /* gsl_eigen_nonsymm_alloc() */
/*
gsl_eigen_nonsymm_free()
Free workspace w
*/
void
gsl_eigen_nonsymm_free (gsl_eigen_nonsymm_workspace * w)
{
gsl_vector_free(w->tau);
gsl_vector_free(w->diag);
gsl_eigen_francis_free(w->francis_workspace_p);
free(w);
} /* gsl_eigen_nonsymm_free() */
/*
gsl_eigen_nonsymm_params()
Set some parameters which define how we solve the eigenvalue
problem.
Inputs: compute_t - 1 if we want to compute T, 0 if not
balance - 1 if we want to balance the matrix, 0 if not
w - nonsymm workspace
*/
void
gsl_eigen_nonsymm_params (const int compute_t, const int balance,
gsl_eigen_nonsymm_workspace *w)
{
gsl_eigen_francis_T(compute_t, w->francis_workspace_p);
w->do_balance = balance;
} /* gsl_eigen_nonsymm_params() */
/*
gsl_eigen_nonsymm()
Solve the nonsymmetric eigenvalue problem
A x = \lambda x
for the eigenvalues \lambda using the Francis method.
Here we compute the real Schur form
T = Z^t A Z
with the diagonal blocks of T giving us the eigenvalues.
Z is a matrix of Schur vectors which is not computed by
this algorithm. See gsl_eigen_nonsymm_Z().
Inputs: A - general real matrix
eval - where to store eigenvalues
w - workspace
Return: success or error
Notes: If T is computed, it is stored in A on output. Otherwise
the diagonal of A contains the 1-by-1 and 2-by-2 eigenvalue
blocks.
*/
int
gsl_eigen_nonsymm (gsl_matrix * A, gsl_vector_complex * eval,
gsl_eigen_nonsymm_workspace * w)
{
const size_t N = A->size1;
/* check matrix and vector sizes */
if (N != A->size2)
{
GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR);
}
else if (eval->size != N)
{
GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN);
}
else
{
int s;
if (w->do_balance)
{
/* balance the matrix */
gsl_linalg_balance_matrix(A, w->diag);
}
/* compute the Hessenberg reduction of A */
gsl_linalg_hessenberg(A, w->tau);
if (w->Z)
{
/*
* initialize the matrix Z to U, which is the matrix used
* to construct the Hessenberg reduction.
*/
/* compute U and store it in Z */
gsl_linalg_hessenberg_unpack(A, w->tau, w->Z);
/* find the eigenvalues and Schur vectors */
s = gsl_eigen_francis_Z(A, eval, w->Z, w->francis_workspace_p);
if (w->do_balance)
{
/*
* The Schur vectors in Z are the vectors for the balanced
* matrix. We now must undo the balancing to get the
* vectors for the original matrix A.
*/
gsl_linalg_balance_accum(w->Z, w->diag);
}
}
else
{
/* find the eigenvalues only */
s = gsl_eigen_francis(A, eval, w->francis_workspace_p);
}
w->n_evals = w->francis_workspace_p->n_evals;
return s;
}
} /* gsl_eigen_nonsymm() */
/*
gsl_eigen_nonsymm_Z()
Solve the nonsymmetric eigenvalue problem
A x = \lambda x
for the eigenvalues \lambda.
Here we compute the real Schur form
T = Z^t A Z
with the diagonal blocks of T giving us the eigenvalues.
Z is the matrix of Schur vectors.
Inputs: A - general real matrix
eval - where to store eigenvalues
Z - where to store Schur vectors
w - workspace
Return: success or error
Notes: If T is computed, it is stored in A on output. Otherwise
the diagonal of A contains the 1-by-1 and 2-by-2 eigenvalue
blocks.
*/
int
gsl_eigen_nonsymm_Z (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix * Z, gsl_eigen_nonsymm_workspace * w)
{
/* check matrix and vector sizes */
if (A->size1 != A->size2)
{
GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR);
}
else if (eval->size != A->size1)
{
GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN);
}
else if ((Z->size1 != Z->size2) || (Z->size1 != A->size1))
{
GSL_ERROR ("Z matrix has wrong dimensions", GSL_EBADLEN);
}
else
{
int s;
w->Z = Z;
s = gsl_eigen_nonsymm(A, eval, w);
w->Z = NULL;
return s;
}
} /* gsl_eigen_nonsymm_Z() */
| {
"alphanum_fraction": 0.6479827089,
"avg_line_length": 24.2657342657,
"ext": "c",
"hexsha": "de9088a4588bf1caae3de3267af914d51bf6a8dd",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/eigen/nonsymm.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/eigen/nonsymm.c",
"max_line_length": 90,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/eigen/nonsymm.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": 1868,
"size": 6940
} |
/* randist/logarithmic.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* Logarithmic distribution
prob(n) = p^n / (n log(1/(1-p)) for n = 1, 2, 3, ...
We use Kemp's second accelerated generator, from Luc Devroye's book
on "Non-Uniform Random Variate Generation", Springer */
unsigned int
gsl_ran_logarithmic (const gsl_rng * r, const double p)
{
double c = log (1-p) ;
double v = gsl_rng_uniform_pos (r);
if (v >= p)
{
return 1 ;
}
else
{
double u = gsl_rng_uniform_pos (r);
double q = 1 - exp (c * u);
if (v <= q*q)
{
double x = 1 + log(v)/log(q) ;
return x ;
}
else if (v <= q)
{
return 2;
}
else
{
return 1 ;
}
}
}
double
gsl_ran_logarithmic_pdf (const unsigned int k, const double p)
{
if (k == 0)
{
return 0 ;
}
else
{
double P = pow(p, (double)k) / (double) k / log(1/(1-p)) ;
return P;
}
}
| {
"alphanum_fraction": 0.630777903,
"avg_line_length": 23.038961039,
"ext": "c",
"hexsha": "37dffbdab209fd7a97497361a3188e18fd5bc7e2",
"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/randist/logarithmic.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/randist/logarithmic.c",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/randist/logarithmic.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": 527,
"size": 1774
} |
#include <gsl/gsl_combination.h>
#include <gsl/gsl_errno.h>
#include <stdio.h>
int mgsl_combination_fwrite(const char *filename, const gsl_combination *p)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_combination_fwrite(fp, p) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_combination_fread(const char *filename, gsl_combination *p)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_combination_fread(fp, p) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_combination_fprintf(const char *filename, const gsl_combination *p, const char *format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_combination_fprintf(fp, p, format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_combination_fscanf(const char *filename, gsl_combination *p)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_combination_fscanf(fp, p) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.7226596675,
"avg_line_length": 28.575,
"ext": "c",
"hexsha": "2e54e30c238c19d64b576665364f12b108024d8a",
"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": "3e14b5a2265f762e62e24dde3127faac2c69e4f6",
"max_forks_repo_licenses": [
"Artistic-2.0"
],
"max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Combination",
"max_forks_repo_path": "src/combination.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3e14b5a2265f762e62e24dde3127faac2c69e4f6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Artistic-2.0"
],
"max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Combination",
"max_issues_repo_path": "src/combination.c",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3e14b5a2265f762e62e24dde3127faac2c69e4f6",
"max_stars_repo_licenses": [
"Artistic-2.0"
],
"max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Combination",
"max_stars_repo_path": "src/combination.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 329,
"size": 1143
} |
/**
* @file square_root.h
* @brief Updating complex Cholesky factorizations.
* @author John McDonough and Kenichi Kumatani
*/
#ifndef SQUARE_ROOT_H
#define SQUARE_ROOT_H
#include <stdio.h>
#include <assert.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include "common/jexception.h"
void cholesky_backsub(const gsl_matrix* A, gsl_vector* x);
void vector_matrix_product(const gsl_vector_complex* vec,
const gsl_matrix_complex* mat, gsl_matrix* D);
void make_conjugate_symmetric(gsl_matrix_complex* mat);
void cholesky_forwardsub(const gsl_matrix* A, gsl_vector* x);
void cholesky_forwardsub_complex(const gsl_matrix_complex* lt,
const gsl_vector_complex* rhs,
gsl_vector_complex* lhs,
bool conjugate = false);
void cholesky_backsub_complex(const gsl_matrix_complex* lt,
const gsl_vector_complex* rhs,
gsl_vector_complex* lhs,
bool conjugate = false);
void rank_one_update_cholesky_factor(gsl_matrix_complex* A11,
const double alpha_m,
const gsl_vector_complex* c_m);
void propagate_covar_square_root_real(gsl_matrix* A11,
gsl_matrix* A12,
gsl_matrix* A21,
gsl_matrix* A22, bool flag = false);
void sweep_lower_triangular(gsl_matrix* A, gsl_matrix* B);
void propagate_covar_square_root_step1(gsl_matrix_complex* A12,
gsl_matrix_complex* A22);
void propagate_covar_square_root_step2a(gsl_matrix_complex* A11,
gsl_matrix_complex* A12,
gsl_matrix_complex* A21,
gsl_matrix_complex* A22);
void propagate_covar_square_root_step2b(gsl_matrix_complex* A22);
void propagate_covar_square_root(gsl_matrix_complex* A11,
gsl_matrix_complex* A12,
gsl_matrix_complex* A21,
gsl_matrix_complex* A22);
void propagate_info_square_root(gsl_matrix_complex* sqrt_Pm_inv,
gsl_matrix_complex* A12,
gsl_vector_complex* a_21,
gsl_vector_complex* a_22, bool rankOneA12 = true);
void propagate_info_square_root_step2_rls(gsl_matrix_complex* sqrt_Pm_inv,
gsl_vector_complex* a_12,
gsl_vector_complex* a_21,
gsl_complex a_22);
void propagate_info_square_root_rls(gsl_matrix_complex* sqrt_Pm_inv,
gsl_vector_complex* a_12,
gsl_vector_complex* a_21,
gsl_complex a_22);
void add_diagonal_loading(gsl_matrix_complex* sqrt_Pm_inv, int dim, double wght);
gsl_vector* cholesky_diagonal(gsl_vector* v, const gsl_matrix* m);
gsl_vector* square_diagonal(gsl_vector* v, const gsl_matrix* m);
#endif
| {
"alphanum_fraction": 0.597869102,
"avg_line_length": 38.1976744186,
"ext": "h",
"hexsha": "94fe3110f274bc47281a886775a3dec9ecfa5610",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/square_root/square_root.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/square_root/square_root.h",
"max_line_length": 82,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/square_root/square_root.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 657,
"size": 3285
} |
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include "gaussianInt2.h"
#include "blit3.h"
#ifndef verbose
#define verbose 1
#endif
double rand_range(double A, double B)
// A random number between A and B
{
if(A==B)
return A;
if(B>A)
return A + (double) rand() / RAND_MAX * (B-A);
//if(A>B)
return B + (double) rand() / RAND_MAX * (A-B);
}
int blit3g(double * T, uint32_t Tm, uint32_t Tn, uint32_t Tp,
double * D, size_t nD, photonw pw, int one_indexing)
// T: target volume
// nD: number of dots
// D: list of dots (x,y,z, nphot, sigmax, sigmay, sigmaz)
{
const int nF = 7; // stride for D
double sigma_max = -1;
for(size_t kk = 0; kk < nD; kk++)
{
for(int ll = 0; ll < 3; ll++)
{
if( D[nF*kk+4 + ll] > sigma_max)
sigma_max = D[nF*kk+4 + ll];
}
}
const size_t w = ceil(sigma_max)*3*2 + 1;
const int hw = (w-1)/2;
// allocate temporary space for the Gaussian
double * G = malloc(w*w*w*sizeof(double));
double sigma[] = {1.6,1.6,2.1};
double mu[] = {0,0,0};
double nPhot;
for(uint32_t pp = 0; pp<nD; pp++) {
// Round the location
int64_t Pm =(int64_t) (D[nF*pp+0]-.5);
int64_t Pn =(int64_t) (D[nF*pp+1]-.5);
int64_t Pp =(int64_t) (D[nF*pp+2]-.5);
// printf("%lu %lu %lu\n", Pm,Pn,Pp);
// Get the offset from the centre of the pixel
mu[0] = -roundf(D[nF*pp+0])+D[nF*pp+0];
mu[1] = -roundf(D[nF*pp+1])+D[nF*pp+1];
mu[2] = -roundf(D[nF*pp+2])+D[nF*pp+2];
// printf("%f %f %f\n", mu[0], mu[1], mu[1]);
// printf("mu: %f %f %f\n", mu[0], mu[1], mu[2]);
sigma[0] = D[nF*pp+4];
sigma[1] = D[nF*pp+5];
sigma[2] = D[nF*pp+6];
nPhot = D[nF*pp+3];
// Create the kernel
if(!gaussianInt3(G, mu, sigma, w))
{
printf("Failed to allocate space for Gaussian kernel\n");
return 1;
}
if(pw == xyz_volume)
for(size_t tt =0; tt<w*w*w; tt++)
G[tt] = G[tt]*nPhot;
if(pw == xy_plane)
{
double wgt = 0;
for(size_t tt =0; tt<w*w; tt++)
wgt += G[tt+w*w*(w-1)/2];
for(size_t tt =0; tt<w*w*w; tt++)
G[tt] = G[tt]*nPhot/wgt;
}
if(pw == mid_point)
{
const double wgt = G[(w*w*w-1)/2];
for(size_t tt =0; tt<w*w*w; tt++)
G[tt] = G[tt]*nPhot/wgt;
}
// blit it
if(one_indexing){
blit3(T, Tm, Tn, Tp,
G, w, w, w,
Pm-hw, Pn-hw, Pp-hw,
0);
} else {
blit3(T, Tm, Tn, Tp,
G, w, w, w,
Pm-hw+1, Pn-hw+1, Pp-hw+1,
0);
}
}
free(G);
return 0;
}
void blit3(double * T, uint32_t Tm, uint32_t Tn, uint32_t Tp,
double * S, uint32_t Sm, uint32_t Sn, uint32_t Sp,
int64_t Pm, int64_t Pn, int64_t Pp,
int8_t anchor)
// T: target image
{
// anchor, 0=corner, 1=center of S
assert(anchor == 0);
// Which ranges in T to be visited
// in [Pma, Pmb]
uint32_t Tma = GSL_MAX(0, Pm);
uint32_t Tmb = GSL_MIN(Tm-1, Pm+Sm-1);
uint32_t Tna = GSL_MAX(0, Pn);
uint32_t Tnb = GSL_MIN(Tn-1, Pn+Sn-1);
uint32_t Tpa = GSL_MAX(0, Pp);
uint32_t Tpb = GSL_MIN(Tp-1, Pp+Sp-1);
uint32_t Sma = 0;
if(Pm<0)
Sma = -Pm;
uint32_t Sna = 0;
if(Pn<0)
Sna = -Pn;
uint32_t Spa = 0;
if(Pp<0)
Spa = -Pp;
#if verbose > 0
uint32_t Smb = GSL_MIN(Sm-1, Tm-Pm-1);
uint32_t Snb = GSL_MIN(Sn-1, Tn-Pn-1);
uint32_t Spb = GSL_MIN(((int64_t) Sp)-1, Tp-Pp-1);
printf("Size of T: %u x %u x %u\n", Tm, Tn, Tp);
printf("Size of S: %u x %u x %u\n", Sm, Sn, Sp);
printf("P: %ld %ld %ld\n", Pm, Pn, Pp);
printf("Will visit:\n");
printf("T: [%u %u]x[%u %u]x[%u %u] (%u)\n", Tma, Tmb, Tna, Tnb, Tpa, Tpb, (Tmb-Tma+1)*(Tnb-Tna+1)*(Tpb-Tpa+1));
printf("S: [%u %u]x[%u %u]x[%u %u] (%u)\n", Sma, Smb, Sna, Snb, Spa, Spb, (Smb-Sma+1)*(Snb-Sna+1)*(Spb-Spa+1));
#endif
uint32_t ppos, npos; // For pre-caluclation of multiplications
uint32_t smm=Sma, snn=Sna, spp=Spa;
for(uint32_t pp = Tpa; pp<=Tpb; pp++, spp++) {
snn = Sna;
ppos = pp*Tm*Tn;
for(uint32_t nn = Tna; nn<=Tnb; nn++, snn++) {
npos = nn*Tm;
smm = Sma;
for(uint32_t mm = Tma; mm<=Tmb; mm++, smm++) {
#if verbose > 1
printf("T(%u %u %u) := S(%u %u %u)\n", mm, nn, pp, smm, snn, spp);
#endif
T[mm + npos + ppos] += S[smm + snn*Sm + spp*Sm*Sn];
}
}
}
}
#ifdef standalone
int unit_tests()
{
printf("Testing \n");
uint32_t Tm = 10;
uint32_t Tn = 11;
uint32_t Tp = 12;
double * T = malloc(Tm*Tn*Tp*sizeof(double));
for(size_t kk = 0; kk<Tm*Tn*Tp; kk++) {
T[kk] = 0;
}
uint32_t Sm = 13;
uint32_t Sn = 15;
uint32_t Sp = 17;
double * S = malloc(Sm*Sn*Sp*sizeof(double));
for(size_t kk = 0; kk<Sm*Sn*Sp; kk++) {
S[kk] = 1;
}
int64_t Pm = -7;
int64_t Pn = -8;
int64_t Pp = -9;
blit3(T, Tm, Tn, Tp, S, Sm, Sn, Sp, Pm, Pn, Pp, 0);
if(Pm>-1 && Pn>-1 && Pp>-1)
if(Pm<Tm && Pn<Tn && Pp<Tp)
printf("T(%ld,%ld,%ld) = %f\n", Pm, Pn, Pp, T[Pm + Pn*Tm + Pp*Tm*Tn]);
free(S);
free(T);
printf("--> blit3g\n");
size_t Gm = 11;
size_t Gn = 11;
size_t Gp = 11;
double * G = calloc(Gm*Gn*Gp,sizeof(double));
double * Dot = calloc(7,sizeof(double));
Dot[0] = 7; Dot[1] = 7; Dot[2] = 7;
Dot[3] = 100;
Dot[4] = 1; Dot[5]=1; Dot[6]=1;
blit3g(G, Gm, Gn, Gp, Dot, 1, mid_point, 0);
double maxg = 0;
for(size_t kk=0; kk<Gm*Gn*Gp; kk++)
maxg = GSL_MAX(maxg, G[kk]);
printf("max(G): %f\n", maxg);
double midg = G[7+7*Gm+7*Gm*Gn];
printf("G(7,7,7)=%f\n", midg);
assert(midg == maxg);
free(G);
free(Dot);
return 0;
}
int main(int argc, char ** argv)
{
printf("%s\n", argv[0]);
if(argc == 1)
return unit_tests();
}
#endif
| {
"alphanum_fraction": 0.5069513406,
"avg_line_length": 23.3281853282,
"ext": "c",
"hexsha": "b8b881adfa02ad0ef9d92886688826ba3f0d6521",
"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": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "elgw/dotter",
"max_forks_repo_path": "common/mex/blit3.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"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": "elgw/dotter",
"max_issues_repo_path": "common/mex/blit3.c",
"max_line_length": 114,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "elgw/dotter",
"max_stars_repo_path": "common/mex/blit3.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z",
"num_tokens": 2458,
"size": 6042
} |
/* normal.c
*
* Copyright (C) 2015, 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_multilarge.h>
typedef struct
{
size_t p; /* number of columns of LS matrix */
gsl_matrix *ATA; /* A^T A, p-by-p */
gsl_vector *ATb; /* A^T b, p-by-1 */
double normb; /* || b || */
gsl_matrix *work_ATA; /* workspace for chol(ATA), p-by-p */
gsl_vector *workp; /* workspace size p */
gsl_vector *work3p; /* workspace size 3*p */
gsl_vector *D; /* scale factors for ATA, size p */
gsl_vector *c; /* solution vector for L-curve */
int eigen; /* 1 if eigenvalues computed */
double eval_min; /* minimum eigenvalue */
double eval_max; /* maximum eigenvalue */
gsl_eigen_symm_workspace *eigen_p;
} normal_state_t;
static void *normal_alloc(const size_t p);
static void normal_free(void *vstate);
static int normal_reset(void *vstate);
static int normal_accumulate(gsl_matrix * A, gsl_vector * b,
void * vstate);
static int normal_solve(const double lambda, gsl_vector * x,
double * rnorm, double * snorm,
void * vstate);
static int normal_rcond(double * rcond, void * vstate);
static int normal_lcurve(gsl_vector * reg_param, gsl_vector * rho,
gsl_vector * eta, void * vstate);
static const gsl_matrix * normal_ATA(const void * vstate);
static const gsl_vector * normal_ATb(const void * vstate);
static int normal_solve_system(const double lambda, gsl_vector * x,
normal_state_t *state);
static int normal_solve_cholesky(gsl_matrix * ATA, const gsl_vector * ATb,
gsl_vector * x, normal_state_t *state);
static int normal_calc_norms(const gsl_vector *x, double *rnorm,
double *snorm, normal_state_t *state);
static int normal_eigen(normal_state_t *state);
/*
normal_alloc()
Allocate workspace for solving large linear least squares
problems using the normal equations approach
Inputs: p - number of columns of LS matrix
Return: pointer to workspace
*/
static void *
normal_alloc(const size_t p)
{
normal_state_t *state;
if (p == 0)
{
GSL_ERROR_NULL("p must be a positive integer",
GSL_EINVAL);
}
state = calloc(1, sizeof(normal_state_t));
if (!state)
{
GSL_ERROR_NULL("failed to allocate normal state", GSL_ENOMEM);
}
state->p = p;
state->ATA = gsl_matrix_alloc(p, p);
if (state->ATA == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate ATA matrix", GSL_ENOMEM);
}
state->work_ATA = gsl_matrix_alloc(p, p);
if (state->work_ATA == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate temporary ATA matrix", GSL_ENOMEM);
}
state->ATb = gsl_vector_alloc(p);
if (state->ATb == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate ATb vector", GSL_ENOMEM);
}
state->D = gsl_vector_alloc(p);
if (state->D == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate D vector", GSL_ENOMEM);
}
state->workp = gsl_vector_alloc(p);
if (state->workp == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate temporary ATb vector", GSL_ENOMEM);
}
state->work3p = gsl_vector_alloc(3 * p);
if (state->work3p == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate work3p", GSL_ENOMEM);
}
state->c = gsl_vector_alloc(p);
if (state->c == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate c vector", GSL_ENOMEM);
}
state->eigen_p = gsl_eigen_symm_alloc(p);
if (state->eigen_p == NULL)
{
normal_free(state);
GSL_ERROR_NULL("failed to allocate eigen workspace", GSL_ENOMEM);
}
normal_reset(state);
return state;
}
static void
normal_free(void *vstate)
{
normal_state_t *state = (normal_state_t *) vstate;
if (state->ATA)
gsl_matrix_free(state->ATA);
if (state->work_ATA)
gsl_matrix_free(state->work_ATA);
if (state->ATb)
gsl_vector_free(state->ATb);
if (state->D)
gsl_vector_free(state->D);
if (state->workp)
gsl_vector_free(state->workp);
if (state->work3p)
gsl_vector_free(state->work3p);
if (state->c)
gsl_vector_free(state->c);
if (state->eigen_p)
gsl_eigen_symm_free(state->eigen_p);
free(state);
}
static int
normal_reset(void *vstate)
{
normal_state_t *state = (normal_state_t *) vstate;
gsl_matrix_set_zero(state->ATA);
gsl_vector_set_zero(state->ATb);
state->normb = 0.0;
state->eigen = 0;
state->eval_min = 0.0;
state->eval_max = 0.0;
return GSL_SUCCESS;
}
/*
normal_accumulate()
Add a new block of rows to the normal equations system
Inputs: A - new block of rows, n-by-p
b - new rhs vector n-by-1
vstate - workspace
Return: success/error
*/
static int
normal_accumulate(gsl_matrix * A, gsl_vector * b, void * vstate)
{
normal_state_t *state = (normal_state_t *) vstate;
const size_t n = A->size1;
if (A->size2 != state->p)
{
GSL_ERROR("columns of A do not match workspace", GSL_EBADLEN);
}
else if (n != b->size)
{
GSL_ERROR("A and b have different numbers of rows", GSL_EBADLEN);
}
else
{
int s;
/* ATA += A^T A, using only the lower half of the matrix */
s = gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, A, 1.0, state->ATA);
if (s)
return s;
/* ATb += A^T b */
s = gsl_blas_dgemv(CblasTrans, 1.0, A, b, 1.0, state->ATb);
if (s)
return s;
/* update || b || */
state->normb = gsl_hypot(state->normb, gsl_blas_dnrm2(b));
return GSL_SUCCESS;
}
}
/*
normal_solve()
Solve normal equations system:
(A^T A + \lambda^2 I) x = A^T b
using Cholesky decomposition
Inputs: lambda - regularization parameter
x - (output) solution vector p-by-1
rnorm - (output) residual norm ||b - A x||
snorm - (output) solution norm ||x||
vstate - workspace
Return: success/error
*/
static int
normal_solve(const double lambda, gsl_vector * x,
double * rnorm, double * snorm,
void * vstate)
{
normal_state_t *state = (normal_state_t *) vstate;
if (x->size != state->p)
{
GSL_ERROR("solution vector does not match workspace", GSL_EBADLEN);
}
else
{
int status;
/* solve system (A^T A) x = A^T b */
status = normal_solve_system(lambda, x, state);
if (status)
{
GSL_ERROR("failed to solve normal equations", status);
}
/* compute residual norm ||y - X c|| and solution norm ||x|| */
normal_calc_norms(x, rnorm, snorm, state);
return GSL_SUCCESS;
}
}
static int
normal_rcond(double * rcond, void * vstate)
{
normal_state_t *state = (normal_state_t *) vstate;
int status = GSL_SUCCESS;
double rcond_ATA;
status = gsl_linalg_cholesky_rcond(state->work_ATA, &rcond_ATA, state->work3p);
if (status == GSL_SUCCESS)
*rcond = sqrt(rcond_ATA);
return status;
}
/*
normal_lcurve()
Compute L-curve of least squares system
Inputs: reg_param - (output) vector of regularization parameters
rho - (output) vector of residual norms
eta - (output) vector of solution norms
vstate - workspace
Return: success/error
*/
static int
normal_lcurve(gsl_vector * reg_param, gsl_vector * rho,
gsl_vector * eta, void * vstate)
{
normal_state_t *state = (normal_state_t *) vstate;
int status;
double smin, smax; /* minimum/maximum singular values */
size_t i;
if (state->eigen == 0)
{
status = normal_eigen(state);
if (status)
return status;
}
if (state->eval_max < 0.0)
{
GSL_ERROR("matrix is not positive definite", GSL_EDOM);
}
/* compute singular values which are sqrts of eigenvalues */
smax = sqrt(state->eval_max);
if (state->eval_min > 0.0)
smin = sqrt(state->eval_min);
else
smin = 0.0;
/* compute vector of regularization parameters */
gsl_multifit_linear_lreg(smin, smax, reg_param);
/* solve normal equations for each regularization parameter */
for (i = 0; i < reg_param->size; ++i)
{
double lambda = gsl_vector_get(reg_param, i);
double rnorm, snorm;
status = normal_solve_system(lambda, state->c, state);
if (status)
return status;
/* compute ||y - X c|| and ||c|| */
normal_calc_norms(state->c, &rnorm, &snorm, state);
gsl_vector_set(rho, i, rnorm);
gsl_vector_set(eta, i, snorm);
}
return GSL_SUCCESS;
}
static const gsl_matrix *
normal_ATA(const void * vstate)
{
const normal_state_t *state = (const normal_state_t *) vstate;
return state->ATA;
}
static const gsl_vector *
normal_ATb(const void * vstate)
{
const normal_state_t *state = (const normal_state_t *) vstate;
return state->ATb;
}
/*
normal_solve_system()
Compute solution to normal equations:
(A^T A + lambda^2*I) x = A^T b
using LDL decomposition.
Inputs: x - (output) solution vector
state - workspace
Return: success/error
*/
static int
normal_solve_system(const double lambda, gsl_vector * x, normal_state_t *state)
{
int status;
const double lambda_sq = lambda * lambda;
gsl_vector_view d = gsl_matrix_diagonal(state->work_ATA);
/* copy ATA matrix to temporary workspace and regularize */
gsl_matrix_tricpy(CblasLower, CblasNonUnit, state->work_ATA, state->ATA);
gsl_vector_add_constant(&d.vector, lambda_sq);
/* solve with Cholesky decomposition */
status = normal_solve_cholesky(state->work_ATA, state->ATb, x, state);
if (status)
return status;
return status;
}
static int
normal_solve_cholesky(gsl_matrix * ATA, const gsl_vector * ATb,
gsl_vector * x, normal_state_t *state)
{
int status;
status = gsl_linalg_cholesky_decomp2(ATA, state->D);
if (status)
return status;
status = gsl_linalg_cholesky_solve2(ATA, state->D, ATb, x);
if (status)
return status;
return GSL_SUCCESS;
}
/*
normal_calc_norms()
Compute residual norm ||y - X c|| and solution
norm ||c||
Inputs: x - solution vector
rnorm - (output) residual norm ||y - X c||
snorm - (output) solution norm ||c||
state - workspace
*/
static int
normal_calc_norms(const gsl_vector *x, double *rnorm,
double *snorm, normal_state_t *state)
{
double r2;
/* compute solution norm ||x|| */
*snorm = gsl_blas_dnrm2(x);
/* compute residual norm ||b - Ax|| */
/* compute: A^T A x - 2 A^T b */
gsl_vector_memcpy(state->workp, state->ATb);
gsl_blas_dsymv(CblasLower, 1.0, state->ATA, x, -2.0, state->workp);
/* compute: x^T A^T A x - 2 x^T A^T b */
gsl_blas_ddot(x, state->workp, &r2);
/* add b^T b */
r2 += state->normb * state->normb;
*rnorm = sqrt(r2);
return GSL_SUCCESS;
}
/*
normal_eigen()
Compute eigenvalues of A^T A matrix, which
are stored in state->workp on output. Also,
state->eval_min and state->eval_max are set
to the minimum/maximum eigenvalues
*/
static int
normal_eigen(normal_state_t *state)
{
int status;
/* copy lower triangle of ATA to temporary workspace */
gsl_matrix_tricpy(CblasLower, CblasNonUnit, state->work_ATA, state->ATA);
/* compute eigenvalues of ATA */
status = gsl_eigen_symm(state->work_ATA, state->workp, state->eigen_p);
if (status)
return status;
gsl_vector_minmax(state->workp, &state->eval_min, &state->eval_max);
state->eigen = 1;
return GSL_SUCCESS;
}
static const gsl_multilarge_linear_type normal_type =
{
"normal",
normal_alloc,
normal_reset,
normal_accumulate,
normal_solve,
normal_rcond,
normal_lcurve,
normal_ATA,
normal_ATb,
normal_free
};
const gsl_multilarge_linear_type * gsl_multilarge_linear_normal =
&normal_type;
| {
"alphanum_fraction": 0.6507629153,
"avg_line_length": 24.8288461538,
"ext": "c",
"hexsha": "64cd3bce2725bef8231df885b16a7af75408e82a",
"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/multilarge/normal.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/multilarge/normal.c",
"max_line_length": 81,
"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/multilarge/normal.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": 3546,
"size": 12911
} |
/* bst/gsl_bst_rb.h
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_BST_RB_H__
#define __GSL_BST_RB_H__
#include <gsl/gsl_math.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
#ifndef GSL_BST_RB_MAX_HEIGHT
#define GSL_BST_RB_MAX_HEIGHT 48
#endif
/* red-black node */
struct gsl_bst_rb_node
{
struct gsl_bst_rb_node *rb_link[2]; /* subtrees */
void *rb_data; /* pointer to data */
unsigned char rb_color; /* color */
};
/* red-black tree data structure */
typedef struct
{
struct gsl_bst_rb_node *rb_root; /* tree's root */
gsl_bst_cmp_function *rb_compare; /* comparison function */
void *rb_param; /* extra argument to |rb_compare| */
const gsl_bst_allocator *rb_alloc; /* memory allocator */
size_t rb_count; /* number of items in tree */
unsigned long rb_generation; /* generation number */
} gsl_bst_rb_table;
/* red-black traverser structure */
typedef struct
{
const gsl_bst_rb_table *rb_table; /* tree being traversed */
struct gsl_bst_rb_node *rb_node; /* current node in tree */
struct gsl_bst_rb_node *rb_stack[GSL_BST_RB_MAX_HEIGHT];
/* all the nodes above |rb_node| */
size_t rb_height; /* number of nodes in |rb_parent| */
unsigned long rb_generation; /* generation number */
} gsl_bst_rb_traverser;
__END_DECLS
#endif /* __GSL_BST_RB_H__ */
| {
"alphanum_fraction": 0.6926369863,
"avg_line_length": 31.5675675676,
"ext": "h",
"hexsha": "a581ffe16c38cedccdc57f1078811a040024e832",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vinej/sml",
"max_forks_repo_path": "include/gsl/gsl_bst_rb.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "vinej/sml",
"max_issues_repo_path": "include/gsl/gsl_bst_rb.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vinej/sml",
"max_stars_repo_path": "include/gsl/gsl_bst_rb.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 577,
"size": 2336
} |
/* randrand - how random is rand(), mostly for comparison with the
* random numbers signal/jitterbits.c produces. produces 256 different
* random values which in an ideal world should be evenly distributed
*
* ./randrand | r-fu equichisq
*
* even with gsl_rng_uniform_int() and the "maximally equidistributed"
* Tausworthe generator (mark II), the p-values over 100 runs of this
* version of the program on Mac OS X vary wildly, with a mean of 0.55
* and standard deviation of 0.28 (and similar stats from OpenBSD) */
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
#include <gsl/gsl_rng.h>
#define TIMES 10000000
int Return_Value = EXIT_SUCCESS;
int main(void)
{
unsigned long i;
gsl_rng *gslrng;
#ifdef __OpenBSD__
if (pledge("stdio", NULL) == -1)
err(1, "pledge failed");
#endif
if (!(gslrng = gsl_rng_alloc(gsl_rng_taus2)))
err(EX_SOFTWARE, "call to gsl_rng_alloc() failed");
gsl_rng_set(gslrng, arc4random());
/* for instead rand() */
//srandomdev();
for (i = 0; i < TIMES; i++) {
/* for instead rand() */
//printf("%u\n", rand() % 256);
/* for instead arc4random() */
//printf("%u\n", arc4random() % 256);
printf("%lu\n", gsl_rng_uniform_int(gslrng, 256));
/* reseeding influences things? (no?) */
//if (i % 100 == 0)
// gsl_rng_set(gslrng, arc4random());
}
exit(Return_Value);
}
| {
"alphanum_fraction": 0.6346666667,
"avg_line_length": 26.3157894737,
"ext": "c",
"hexsha": "939612c6925087f575461ccdc3a53ce39bce7ded",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-17T09:25:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-01-03T15:58:46.000Z",
"max_forks_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221",
"max_forks_repo_licenses": [
"0BSD"
],
"max_forks_repo_name": "thrig/scripts",
"max_forks_repo_path": "random/randrand.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221",
"max_issues_repo_issues_event_max_datetime": "2020-01-04T08:43:07.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-04T08:43:07.000Z",
"max_issues_repo_licenses": [
"0BSD"
],
"max_issues_repo_name": "thrig/scripts",
"max_issues_repo_path": "random/randrand.c",
"max_line_length": 70,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221",
"max_stars_repo_licenses": [
"0BSD"
],
"max_stars_repo_name": "thrig/scripts",
"max_stars_repo_path": "random/randrand.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-14T06:31:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-01-30T18:00:47.000Z",
"num_tokens": 419,
"size": 1500
} |
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <galpy_potentials.h>
// Reflex Motion potential - based on Moving Object Potential
// 3 arguments: amp, t0, tf
void constrain_range2(double * d) {
// Constrains index to be within interpolation range
if (*d < 0) *d = 0.0;
if (*d > 1) *d = 1.0;
}
double ReflexMotionRforce(double R,double z, double phi,
double t,
struct potentialArg * potentialArgs){
double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z,obj_R,obj_phi,RF;
double * args= potentialArgs->args;
//Get args
amp= *args;
t0= *(args+1);
tf= *(args+2);
d_ind= (t-t0)/(tf-t0);
x= R*cos(phi);
y= R*sin(phi);
constrain_range2(&d_ind);
// Interpolate x, y, z
obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
*(potentialArgs->acc1d+1));
obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,
*(potentialArgs->acc1d+2));
// Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
obj_R = pow(pow(obj_x,2) + pow(obj_y,2),0.5);
obj_phi = atan2(obj_y,obj_x);
// Calculate R force
RF= calcRforce(obj_R,obj_z,obj_phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg);
return -amp*RF*(cos(phi)*cos(obj_phi)+sin(phi)*sin(obj_phi));
}
double ReflexMotionzforce(double R,double z,double phi,
double t,
struct potentialArg * potentialArgs){
double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, obj_R, obj_phi;
double * args= potentialArgs->args;
//Get args
amp= *args;
t0= *(args+1);
tf= *(args+2);
d_ind= (t-t0)/(tf-t0);
x= R*cos(phi);
y= R*sin(phi);
constrain_range2(&d_ind);
// Interpolate x, y, z
obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
*(potentialArgs->acc1d+1));
obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,
*(potentialArgs->acc1d+2));
// Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
obj_R = pow(pow(obj_x,2) + pow(obj_y,2),0.5);
obj_phi = atan2(obj_y,obj_x);
// Calculate z force
return -amp * calczforce(obj_R,obj_z,obj_phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg);
}
double ReflexMotionphiforce(double R,double z,double phi,
double t,
struct potentialArg * potentialArgs){
double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, obj_R, obj_phi, RF;
double * args= potentialArgs->args;
//Get args
amp= *args;
t0= *(args+1);
tf= *(args+2);
d_ind= (t-t0)/(tf-t0);
x= R*cos(phi);
y= R*sin(phi);
constrain_range2(&d_ind);
// Interpolate x, y, z
obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
*(potentialArgs->acc1d+1));
obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,
*(potentialArgs->acc1d+2));
// Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
obj_R = pow(pow(obj_x,2) + pow(obj_y,2),0.5);
obj_phi = atan2(obj_y,obj_x);
// Calculate phiforce
RF= calcRforce(obj_R,obj_z,obj_phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg);
return amp*RF*(sin(phi)*cos(obj_phi)-cos(phi)*sin(obj_phi));
}
// double MovingObjectPotentialPlanarRforce(double R, double phi,
// double t,
// struct potentialArg * potentialArgs){
// double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF;
// double * args= potentialArgs->args;
//Get args
// amp= *args;
// t0= *(args+1);
// tf= *(args+2);
// d_ind= (t-t0)/(tf-t0);
// x= R*cos(phi);
// y= R*sin(phi);
// constrain_range(&d_ind);
// Interpolate x, y
// obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
// obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
// *(potentialArgs->acc1d+1));
// Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
// Calculate R force
// RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped,
// potentialArgs->wrappedPotentialArg);
// return -amp*RF*(cos(phi)*(obj_x-x)+sin(phi)*(obj_y-y))/Rdist;
//}
// double MovingObjectPotentialPlanarphiforce(double R, double phi,
// double t,
// struct potentialArg * potentialArgs){
// double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF;
// double * args= potentialArgs->args;
// Get args
// amp= *args;
// t0= *(args+1);
// tf= *(args+2);
// d_ind= (t-t0)/(tf-t0);
// x= R*cos(phi);
// y= R*sin(phi);
// constrain_range(&d_ind);
// Interpolate x, y
// obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
// obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
// *(potentialArgs->acc1d+1));
// Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
// Calculate phiforce
// RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped,
// potentialArgs->wrappedPotentialArg);
// return -amp*RF*R*(cos(phi)*(obj_y-y)-sin(phi)*(obj_x-x))/Rdist;
//}
| {
"alphanum_fraction": 0.6619009263,
"avg_line_length": 34.4861111111,
"ext": "c",
"hexsha": "401f0f0445e19b4ac851b12a01774927adb9b9cb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "radsouza/galpy",
"max_forks_repo_path": "galpy/potential/potential_c_ext/ReflexMotion.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "radsouza/galpy",
"max_issues_repo_path": "galpy/potential/potential_c_ext/ReflexMotion.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "radsouza/galpy",
"max_stars_repo_path": "galpy/potential/potential_c_ext/ReflexMotion.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1709,
"size": 4966
} |
#include <math.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <gsl/gsl_vector.h>
// #include "libiomp/omp.h"
#include <omp.h>
#include "../include/type.h"
#include "../include/util.h"
#include "../include/global.h"
extern clock_t dur;
extern char *optarg;
extern int optind;
char c_getopt(int argc, char *argv[], char *pattern) {
static size_t i = 0;
int j;
char ret;
++optind;
if (optind > (int)strlen(pattern)) {
return -1;
}
ret = pattern[i++];
for (j = 0; j < argc; ++j) {
if (argv[j][0] == '-' && argv[j][1] == ret) {
optarg = argv[j+1];
}
}
return ret;
}
/**
* @brief initiator of odiff.
*
* @param inc1
* @param inc2
* @param skp1
* @param skp2
* @param inclu_len
* @param skip_len
* @param flag
* @param id
*
* @return
*/
odiff* diff_alloc(gsl_vector* inc1, gsl_vector* inc2,
gsl_vector* skp1, gsl_vector* skp2,
int inclu_len, int skip_len, int flag, char* id) {
odiff *diff = (odiff*)malloc(sizeof(odiff));
diff->inc1 = inc1, diff->skp1 = skp1, diff->inc2 = inc2, diff->skp2 = skp2;
diff->inclu_len = inclu_len, diff->skip_len = skip_len;
diff->flag = flag, diff->id = (char*)malloc(sizeof(char)*(strlen(id)+1));
strcpy(diff->id, id);
return diff;
}
/**
* @brief performing unary operation on gsl_vector.
* @param vec
* @param fun
*/
void unary_operate_vec(gsl_vector *vec, double (*fun) (double)) {
size_t i;
for (i = 0; i < vec->size; ++i) {
gsl_vector_set(vec, i, fun(gsl_vector_get(vec, i)));
}
return;
}
/**
* @brief performing binary operation on gsl_vector.
*
* @param vec
* @param pa
* @param fun
*/
void binary_operate_vec(gsl_vector *vec, double pa, double (*fun) (double, const double)) {
size_t i;
for (i = 0; i < vec->size; ++i) {
gsl_vector_set(vec, i, fun(gsl_vector_get(vec, i), pa));
}
return;
}
/**
* @brief performing element-wise operation on gsl_vector.
*
* @param vec
* @param fun
* @param argc
* @param ...
*/
void element_wise_vec(gsl_vector *vec, double (*fun) (double, va_list), int argc, ...) {
va_list argv;
size_t i;
for (i = 0; i < vec->size; ++i) {
va_start(argv, argc);
gsl_vector_set(vec, i, fun(gsl_vector_get(vec, i), argv));
va_end(argv);
}
return;
}
/**
* @brief cumulative summation of a gsl_vector.
*
* @param vec
* @param fun
* @param argc
* @param ...
*
* @return
*/
double cuscumsum(gsl_vector *vec, double (*fun) (double, va_list), int argc, ...) {
va_list argv, tmp;
double sum = 0;
size_t i;
va_start(argv, argc);
for (i = 0; i < vec->size; ++i) {
va_copy(tmp, argv);
sum += fun(gsl_vector_get(vec, i), tmp);
}
va_end(tmp);
va_end(argv);
return sum;
}
int parse_title(char* str, char** output) {
int idx = 0;
char *token = strtok(str, " \t\r\n\v\f");
while(token) {
output[idx] = (char*)malloc(sizeof(char)*TITLE_ELEMENT_LEN);
strcpy(output[idx++], token);
token = strtok(NULL, " \t\r\n\v\f");
}
// int base = 0;
// do {
// base += idx? strlen(output[idx-1]) + LEN_OF_NT : 0;
// output[idx] = (char*)malloc(sizeof(char)*TITLE_ELEMENT_LEN);
// } while(sscanf(str + base, "%s \t\n", output[idx++]) != EOF);
return idx-1;
}
/**
* @brief
*
* @param input a string in format '1,2,3,4,5,6,...'.
* @param vec
*
* @return
*/
int str_to_vector(char* input, gsl_vector** vec) {
int idx = 0, count = 1;
size_t i = 0;
// gsl_vector_free(*vec);
for (i = 0; i < strlen(input); ++i) {
if (input[i] == ',') {
++count;
}
}
*vec = gsl_vector_alloc(count);
char *str = strtok(input, ",");
while(str) {
if (strcmp(str, "NA") == 0 || strcmp(str, "NAN") == 0 ||
strcmp(str, "na") == 0 || strcmp(str, "nan") == 0) {
return -1;
}
gsl_vector_set(*vec, idx++, atof(str));
str = strtok(NULL, ",");
}
return count;
}
int parse_line(char* str, char* id, gsl_vector** inc1, gsl_vector** skp1,
gsl_vector** inc2, gsl_vector** skp2,
int* inclu_len, int* skip_len) {
int idx = 0;
char output[7][COLUMN_LEN];
char *token = strtok(str, " \t\r\n\v\f");
while(token) {
strcpy(output[idx++], token);
token = strtok(NULL, " \t\r\n\v\f");
}
// int base = 0;
// do {
// base += idx? strlen(output[idx-1]) + LEN_OF_NT : 0;
// } while(sscanf(str + base, "%s \t\n", output[idx++]) != EOF);
strcpy(id, output[0]);
if (str_to_vector(output[1], inc1) == -1 ||
str_to_vector(output[2], skp1) == -1 ||
str_to_vector(output[3], inc2) == -1 ||
str_to_vector(output[4], skp2) == -1) {
printf("An error occured. rMATS cannot handle missing value. Sample Id: %s\n", id);
printf("Exiting.\n");
exit(0);
}
*inclu_len = atoi(output[5]);
*skip_len = atoi(output[6]);
return idx-1;
}
int parse_file(const char* filename, diff_list_node* list, char** title_element_list) {
FILE *ifp;
size_t olen = MAX_LINE;
char *str_line = (char*)malloc(sizeof(char)*olen);
char title[TITLE_LEN], id[MAX_LINE];
int row_num=0, inclu_len, skip_len;
gsl_vector *inc1 = NULL, *skp1 = NULL, *inc2 = NULL, *skp2 = NULL;
if ((ifp = fopen(filename, "r")) == NULL) {
printf("Fail to open!");
return 0;
}
fgets(title, TITLE_LEN, ifp);
parse_title(title, title_element_list);
while (getline(&str_line, &olen, ifp) != -1) {
++row_num;
parse_line(str_line, id, &inc1, &skp1, &inc2, &skp2, &inclu_len, &skip_len);
if (inc1->size != skp1->size || inc2->size != skp2->size) {
printf("An error occured. The length of the pair of vector should be equal. Sample Id: %s\n", id);
printf("Size of vector: %ld, %ld, %ld, %ld\n", inc1->size, skp1->size, inc2->size, skp2->size);
printf("Exiting\n");
exit(0);
}
gsl_vector_add(inc1, skp1), gsl_vector_add(inc2, skp2);
// TODO | or || ?
// According to original python code 'if (vecprod(vecadd(inc1,skp1))==0) | (vecprod(vecadd(inc2,skp2))==0):',
// it's a bit arithmetic '|'. However, it should be a logical 'or' in such senario.
if (cumprod(inc1) == 0 || cumprod(inc2) == 0) {
gsl_vector_sub(inc1, skp1), gsl_vector_sub(inc2, skp2);
diff_append(list, diff_alloc(inc1, inc2, skp1, skp2, inclu_len, skip_len, 0, id));
} else {
gsl_vector_sub(inc1, skp1), gsl_vector_sub(inc2, skp2);
// TODO According to original python code, this function will not change anything.
// original comment: add 1 in both inclusion and skipping counts for robustness in small sample size
gsl_vector_add_constant(inc1, 0.0), gsl_vector_add_constant(skp1, 0.0);
gsl_vector_add_constant(inc2, 0.0), gsl_vector_add_constant(skp2, 0.0);
diff_append(list, diff_alloc(inc1, inc2, skp1, skp2, inclu_len, skip_len, 1, id));
}
}
free(str_line);
fclose(ifp);
return row_num;
}
void display_dvector(const gsl_vector* vec) {
size_t i;
for (i = 0; i < vec->size; ++i) {
printf("%.10f ", gsl_vector_get(vec, i));
}
}
/**
* @brief handy function.
*
* @param i
* @param argv
*
* @return
*/
double logit(double i) {
if (i < 0.01) {
i = 0.01;
} else if (i > 0.99) {
i = 0.99;
}
return log(i/(1-i));
}
/*
double log_and_minus_x(const double i, va_list argv) {
double pa = va_arg(argv, double);
return logit(i) - logit(pa);
}
double rev_log_and_minus_x(const double i, va_list argv) {
double pa = va_arg(argv, double);
return pow(M_E, i + log(pa));
}
*/
/**
* @brief cumulative production of a gsl_vector.
*
* @param vec
*
* @return
*/
double cumprod(const gsl_vector* vec) {
double res = 1;
size_t i;
for (i = 0; i < vec->size; ++i) {
res *= gsl_vector_get(vec, i);
}
return res;
}
// for multivar, 1, 2
double sum_for_multivar(const double i, va_list argv) {
double pa = va_arg(argv, double);
return pow(logit(i)-logit(pa), 2);
}
// for multivar_der, 1_der, 2_der
double sum_for_multivar_der(const double i, va_list argv) {
double pa = va_arg(argv, double);
// return -2 * (logit(i) - logit(pa))/(pa*(1-pa));
return 2 * (logit(i) - logit(pa))/(pa*pa-pa);
}
double myfunc_marginal_2der(const double x, const double I, const double S,
const double beta, const double var,
const int inclu_len, const int skip_len) {
double tmp1, tmp2, tmp3, one_x = 1-x;
double powx = pow(x,2), pow1_x = pow(one_x,2), pow_len = pow(inclu_len*x + skip_len*one_x,2);
tmp1 = (((2 * x - 1) * (logit(beta) - logit(x)) - 1)/var - 1)/(powx*pow1_x);
tmp2 = I * skip_len * (2*inclu_len*x+skip_len)/(powx * pow_len);
tmp3 = S * inclu_len * (inclu_len+2*skip_len*one_x)/(pow1_x * pow_len);
return tmp1 - tmp2 - tmp3;
}
// for marginal
double sum_for_marginal(const double i, va_list argv) {
int *idx = va_arg(argv, int*);
double beta = va_arg(argv, double);
double I_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);
double S_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);
double var = va_arg(argv, double), new_psi, f1, f1_2der;
int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);
*idx += 1;
new_psi = inclu_len * i/(inclu_len * i + skip_len * (1 - i));
f1 = I_ * log(new_psi) + S_ * log(1 - new_psi) -
pow(logit(i) - logit(beta),2)/(2*var) - log(i) - log(1-i);
f1_2der = fabs(myfunc_marginal_2der(i, I_, S_, beta,
var, inclu_len, skip_len));
return 0.5 * log(fabs(f1_2der) + 0.00001) - f1;
}
// for marginal_der
double sum_for_marginal_der(const double i, va_list argv) {
int *idx = va_arg(argv, int*);
double beta = va_arg(argv, double);
double I_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);
double S_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);
double var = va_arg(argv, double);
int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);
double f1_1der, f1_2der, f1_3der, one_i = 1-i;
*idx += 1;
double powi = pow(i,2), pow1_i = pow(one_i,2);
f1_3der = (2 * i - 1)/(powi * pow1_i*beta*(1-beta)*var);
f1_2der = myfunc_marginal_2der(i, I_, S_, beta, var, inclu_len, skip_len);
f1_1der = (logit(i) - logit(beta))/(beta * (1-beta) * var);
return 0.5 * f1_3der/f1_2der - f1_1der;
}
// function used to manipulate our linked list.
int diff_append(diff_list_node* header, odiff* data) {
diff_list_node *tmp = (diff_list_node*)malloc(sizeof(diff_list_node));
tmp->data = data;
tmp->end = tmp;
tmp->next = NULL;
header->end->next = tmp;
header->end->end = tmp;
header->end = tmp;
return 0;
}
int diff_insert(diff_list_node* header, odiff* data, int idx) {
return 6;
}
int diff_get_next(diff_list_node* header, odiff* data) {
return 6;
}
int diff_get_at(diff_list_node* header, odiff* data, int idx) {
int i;
diff_list_node* tmp = header;
for (i = 0; i <= idx; ++i) {
tmp = tmp->next;
}
*data = *(tmp->data);
return 0;
}
void split_data_list(int lenofl, int batch_size, diff_list_node* list, batch_datum *ret) {
int i = 0, group = lenofl/batch_size, carry = lenofl % batch_size;
diff_list_node *node = list;
odiff **datum = (odiff**)malloc(sizeof(odiff*)*(group+1));
for (i = 0; i < group+1; ++i) {
datum[i] = (odiff*)malloc(sizeof(odiff)*batch_size);
}
for (i = 0; i < lenofl; ++i) {
node = node->next;
datum[i/batch_size][i%batch_size] = *(node->data);
}
for (i = 0; i < group; ++i) {
ret[i].batch_size = batch_size;
ret[i].datum = (void**)&datum[i];
}
ret[group].batch_size = carry;
ret[group].datum = (void**)&datum[group];
return;
}
void mp_threadpool(int nthread, int ntask, void* (*func)(void *), void** datum, void **ret) {
int i;
omp_set_num_threads(nthread);
#pragma omp parallel for private(i)
for (i = 0; i < ntask; ++i) {
ret[i] = (*func)(datum[i]);
}
return;
}
/**
* @brief C wrapper of Fortran l_bfgs_b routine.
*
* @param n
* @param m
* @param x[]
* @param l[]
* @param u[]
* @param nbd[]
* @param fp
* @param gp
* @param factr
* @param pgtol
* @param iprint
* @param maxiter
* @param argc
* @param ...
*
* @return
********************************************************************
c --------------------------------------------------------------
c DESCRIPTION OF THE VARIABLES IN L-BFGS-B
c --------------------------------------------------------------
c
c n is an INTEGER variable that must be set by the user to the
c number of variables. It is not altered by the routine.
c
c m is an INTEGER variable that must be set by the user to the
c number of corrections used in the limited memory matrix.
c It is not altered by the routine. Values of m < 3 are
c not recommended, and large values of m can result in excessive
c computing time. The range 3 <= m <= 20 is recommended.
c
c x is a DOUBLE PRECISION array of length n. On initial entry
c it must be set by the user to the values of the initial
c estimate of the solution vector. Upon successful exit, it
c contains the values of the variables at the best point
c found (usually an approximate solution).
c
c l is a DOUBLE PRECISION array of length n that must be set by
c the user to the values of the lower bounds on the variables. If
c the i-th variable has no lower bound, l(i) need not be defined.
c
c u is a DOUBLE PRECISION array of length n that must be set by
c the user to the values of the upper bounds on the variables. If
c the i-th variable has no upper bound, u(i) need not be defined.
c
c nbd is an INTEGER array of dimension n that must be set by the
c user to the type of bounds imposed on the variables:
c nbd(i)=0 if x(i) is unbounded,
c 1 if x(i) has only a lower bound,
c 2 if x(i) has both lower and upper bounds,
c 3 if x(i) has only an upper bound.
c
c f is a DOUBLE PRECISION variable. If the routine setulb returns
c with task(1:2)= 'FG', then f must be set by the user to
c contain the value of the function at the point x.
c
c g is a DOUBLE PRECISION array of length n. If the routine setulb
c returns with taskb(1:2)= 'FG', then g must be set by the user to
c contain the components of the gradient at the point x.
c
c factr is a DOUBLE PRECISION variable that must be set by the user.
c It is a tolerance in the termination test for the algorithm.
c The iteration will stop when
c
c (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch
c
c where epsmch is the machine precision which is automatically
c generated by the code. Typical values for factr on a computer
c with 15 digits of accuracy in double precision are:
c factr=1.d+12 for low accuracy;
c 1.d+7 for moderate accuracy;
c 1.d+1 for extremely high accuracy.
c The user can suppress this termination test by setting factr=0.
c
c pgtol is a double precision variable.
c On entry pgtol >= 0 is specified by the user. The iteration
c will stop when
c
c max{|proj g_i | i = 1, ..., n} <= pgtol
c
c where pg_i is the ith component of the projected gradient.
c The user can suppress this termination test by setting pgtol=0.
c
c wa is a DOUBLE PRECISION array of length
c (2mmax + 4)nmax + 12mmax^2 + 12mmax used as workspace.
c This array must not be altered by the user.
c
c iwa is an INTEGER array of length 3nmax used as
c workspace. This array must not be altered by the user.
c
c task is a CHARACTER string of length 60.
c On first entry, it must be set to 'START'.
c On a return with task(1:2)='FG', the user must evaluate the
c function f and gradient g at the returned value of x.
c On a return with task(1:5)='NEW_X', an iteration of the
c algorithm has concluded, and f and g contain f(x) and g(x)
c respectively. The user can decide whether to continue or stop
c the iteration.
c When
c task(1:4)='CONV', the termination test in L-BFGS-B has been
c satisfied;
c task(1:4)='ABNO', the routine has terminated abnormally
c without being able to satisfy the termination conditions,
c x contains the best approximation found,
c f and g contain f(x) and g(x) respectively;
c task(1:5)='ERROR', the routine has detected an error in the
c input parameters;
c On exit with task = 'CONV', 'ABNO' or 'ERROR', the variable task
c contains additional information that the user can print.
c This array should not be altered unless the user wants to
c stop the run for some reason. See driver2 or driver3
c for a detailed explanation on how to stop the run
c by assigning task(1:4)='STOP' in the driver.
c
c iprint is an INTEGER variable that must be set by the user.
c It controls the frequency and type of output generated:
c iprint<0 no output is generated;
c iprint=0 print only one line at the last iteration;
c 0<iprint<99 print also f and |proj g| every iprint iterations;
c iprint=99 print details of every iteration except n-vectors;
c iprint=100 print also the changes of active set and final x;
c iprint>100 print details of every iteration including x and g;
c When iprint > 0, the file iterate.dat will be created to
c summarize the iteration.
c
c csave is a CHARACTER working array of length 60.
c
c lsave is a LOGICAL working array of dimension 4.
c On exit with task = 'NEW_X', the following information is
c available:
c lsave(1) = .true. the initial x did not satisfy the bounds;
c lsave(2) = .true. the problem contains bounds;
c lsave(3) = .true. each variable has upper and lower bounds.
c
c isave is an INTEGER working array of dimension 44.
c On exit with task = 'NEW_X', it contains information that
c the user may want to access:
c isave(30) = the current iteration number;
c isave(34) = the total number of function and gradient
c evaluations;
c isave(36) = the number of function value or gradient
c evaluations in the current iteration;
c isave(38) = the number of free variables in the current
c iteration;
c isave(39) = the number of active constraints at the current
c iteration;
c
c see the subroutine setulb.f for a description of other
c information contained in isave
c
c dsave is a DOUBLE PRECISION working array of dimension 29.
c On exit with task = 'NEW_X', it contains information that
c the user may want to access:
c dsave(2) = the value of f at the previous iteration;
c dsave(5) = the machine precision epsmch generated by the code;
c dsave(13) = the infinity norm of the projected gradient;
c
c see the subroutine setulb.f for a description of other
c information contained in dsave
c
c --------------------------------------------------------------
c END OF THE DESCRIPTION OF THE VARIABLES IN L-BFGS-B
c --------------------------------------------------------------
c
c << An example of subroutine 'timer' for AIX Version 3.2 >>
c
c subroutine timer(ttime)
c double precision ttime
c integer itemp, integer mclock
c itemp = mclock()
c ttime = dble(itemp)*1.0d-2
c return
c end
*********************************************************************
*/
double l_bfgs_b_wrapper(integer n, integer m, doublereal x[], doublereal l[],
doublereal u[], integer nbd[],
double (*fp) (const double x[], va_list argv),
void (*gp) (const double x[], double res[], va_list argv),
doublereal factr, doublereal pgtol, integer iprint,
int maxfun, int maxiter, int argc, ...) {
va_list argv, tmp;
char task[SIXTY], csave[SIXTY];
logical lsave[4];
integer iwa[3*n], isave[44];
doublereal dsave[29], wa[2*m*n+5*n+11*m*m+8*m];
va_start(argv, argc);
strcpy(task,"START");
int i, count = 0, funcount = 0, maxls = 20;
for(i=5;i<SIXTY;i++) {
task[i]=' ';
}
doublereal f = 0, g[n];
for (i = 0; i < n; ++i) {
g[i] = 0;
}
// TODO # The minimization routine wants f and g at the current x.
// # Note that interruptions due to maxfun are postponed
// # until the completion of the current minimization iteration.
// # Overwrite f and g:
do {
setulb_(&n,&m,x,l,u,nbd,&f,g,&factr,&pgtol,wa,iwa,task,&iprint,
csave,lsave,isave,dsave, &maxls);
if (strncmp(task,"FG",2)==0) {
va_copy(tmp, argv);
f = fp(x, tmp);
va_copy(tmp, argv);
gp(x, g, tmp);
++funcount;
} else if(strncmp(task,"NEW_X",5)==0){
++count;
} else {
break;
}
} while(count < maxiter && funcount < maxfun);
f = fp(x, argv);
va_end(argv);
va_end(tmp);
return f;
}
| {
"alphanum_fraction": 0.5839157665,
"avg_line_length": 31.2982954545,
"ext": "c",
"hexsha": "df8c01b5adbe9b099531d7e18c91a725a38eb28c",
"lang": "C",
"max_forks_count": 39,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z",
"max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_forks_repo_path": "rMATS_C/src/util.c",
"max_issues_count": 163,
"max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_issues_repo_path": "rMATS_C/src/util.c",
"max_line_length": 117,
"max_stars_count": 88,
"max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_stars_repo_path": "rMATS_C/src/util.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z",
"num_tokens": 6395,
"size": 22034
} |
/* histogram/test1d_resample.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include "urand.c"
void
test1d_resample (void)
{
size_t i;
int status = 0;
gsl_histogram *h;
gsl_ieee_env_setup ();
h = gsl_histogram_calloc_uniform (10, 0.0, 1.0);
gsl_histogram_increment (h, 0.1);
gsl_histogram_increment (h, 0.2);
gsl_histogram_increment (h, 0.2);
gsl_histogram_increment (h, 0.3);
{
gsl_histogram_pdf *p = gsl_histogram_pdf_alloc (10);
gsl_histogram *hh = gsl_histogram_calloc_uniform (100, 0.0, 1.0);
gsl_histogram_pdf_init (p, h);
for (i = 0; i < 100000; i++)
{
double u = urand();
double x = gsl_histogram_pdf_sample (p, u);
gsl_histogram_increment (hh, x);
}
for (i = 0; i < 100; i++)
{
double y = gsl_histogram_get (hh, i) / 2500;
double x, xmax;
size_t k;
double ya;
gsl_histogram_get_range (hh, i, &x, &xmax);
gsl_histogram_find (h, x, &k);
ya = gsl_histogram_get (h, k);
if (ya == 0)
{
if (y != 0)
{
printf ("%d: %g vs %g\n", (int) i, y, ya);
status = 1;
}
}
else
{
double err = 1 / sqrt (gsl_histogram_get (hh, i));
double sigma = fabs ((y - ya) / (ya * err));
if (sigma > 3)
{
status = 1;
printf ("%g vs %g err=%g sigma=%g\n", y, ya, err, sigma);
}
}
}
gsl_histogram_pdf_free (p) ;
gsl_histogram_free (hh);
gsl_test (status, "gsl_histogram_pdf_sample within statistical errors");
}
gsl_histogram_free (h);
}
| {
"alphanum_fraction": 0.5931748466,
"avg_line_length": 26.08,
"ext": "c",
"hexsha": "525c1266103738fef2f12bbfe15d0777eb19cb59",
"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/histogram/test1d_resample.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/histogram/test1d_resample.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/histogram/test1d_resample.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": 725,
"size": 2608
} |
#ifndef AMICI_SUNDIALS_MATRIX_WRAPPER_H
#define AMICI_SUNDIALS_MATRIX_WRAPPER_H
#include <sunmatrix/sunmatrix_band.h> // SUNMatrix_Band
#include <sunmatrix/sunmatrix_dense.h> // SUNMatrix_Dense
#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrix_Sparse
#include <gsl/gsl-lite.hpp>
#include <vector>
#include "amici/vector.h"
namespace amici {
/**
* @brief A RAII wrapper for SUNMatrix structs.
*
* This can create dense, sparse, or banded matrices using the respective
* constructor.
*/
class SUNMatrixWrapper {
public:
SUNMatrixWrapper() = default;
/**
* @brief Create sparse matrix. See SUNSparseMatrix in sunmatrix_sparse.h
* @param M Number of rows
* @param N Number of columns
* @param NNZ Number of nonzeros
* @param sparsetype Sparse type
*/
SUNMatrixWrapper(int M, int N, int NNZ, int sparsetype);
/**
* @brief Create dense matrix. See SUNDenseMatrix in sunmatrix_dense.h
* @param M Number of rows
* @param N Number of columns
*/
SUNMatrixWrapper(int M, int N);
/**
* @brief Create banded matrix. See SUNBandMatrix in sunmatrix_band.h
* @param M Number of rows and columns
* @param ubw Upper bandwidth
* @param lbw Lower bandwidth
*/
SUNMatrixWrapper(int M, int ubw, int lbw);
/**
* @brief Create sparse matrix from dense or banded matrix. See
* SUNSparseFromDenseMatrix and SUNSparseFromBandMatrix in
* sunmatrix_sparse.h
* @param A Wrapper for dense matrix
* @param droptol tolerance for dropping entries
* @param sparsetype Sparse type
*/
SUNMatrixWrapper(const SUNMatrixWrapper &A, realtype droptol,
int sparsetype);
/**
* @brief Wrap existing SUNMatrix
* @param mat
*/
explicit SUNMatrixWrapper(SUNMatrix mat);
~SUNMatrixWrapper();
/**
* @brief Copy constructor
* @param other
*/
SUNMatrixWrapper(const SUNMatrixWrapper &other);
/**
* @brief Move constructor
* @param other
*/
SUNMatrixWrapper(SUNMatrixWrapper &&other);
/**
* @brief Copy assignment
* @param other
* @return
*/
SUNMatrixWrapper &operator=(const SUNMatrixWrapper &other);
/**
* @brief Move assignment
* @param other
* @return
*/
SUNMatrixWrapper &operator=(SUNMatrixWrapper &&other);
/**
* @brief Access raw data
* @return raw data pointer
*/
realtype *data() const;
/**
* @brief Get the wrapped SUNMatrix
* @return SlsMat
*/
SUNMatrix get() const;
/**
* @brief Get the number of rows
* @return number
*/
sunindextype rows() const;
/**
* @brief Get the number of columns
* @return number
*/
sunindextype columns() const;
/**
* @brief Get the number of non-zero elements (sparse matrices only)
* @return number
*/
sunindextype nonzeros() const;
/**
* @brief Get the index values of a sparse matrix
* @return index array
*/
sunindextype *indexvals() const;
/**
* @brief Get the index pointers of a sparse matrix
* @return index array
*/
sunindextype *indexptrs() const;
/**
* @brief Get the type of sparse matrix
* @return index array
*/
int sparsetype() const;
/**
* @brief reset data to zeroes
*/
void reset();
/**
* @brief multiply with a scalar (in-place)
* @param a scalar value to multiply matrix
*/
void scale(realtype a);
/**
* @brief N_Vector interface for multiply
* @param c output vector, may already contain values
* @param b multiplication vector
*/
void multiply(N_Vector c, const_N_Vector b) const;
/**
* @brief Perform matrix vector multiplication c += A*b
* @param c output vector, may already contain values
* @param b multiplication vector
*/
void multiply(gsl::span<realtype> c, gsl::span<const realtype> b) const;
/**
* @brief Perform reordered matrix vector multiplication c += A[:,cols]*b
* @param c output vector, may already contain values
* @param b multiplication vector
* @param cols int vector for column reordering
* @param transpose bool transpose A before multiplication
*/
void multiply(N_Vector c,
const N_Vector b,
gsl::span <const int> cols,
bool transpose) const;
/**
* @brief Perform reordered matrix vector multiplication c += A[:,cols]*b
* @param c output vector, may already contain values
* @param b multiplication vector
* @param cols int vector for column reordering
* @param transpose bool transpose A before multiplication
*/
void multiply(gsl::span<realtype> c,
gsl::span<const realtype> b,
gsl::span <const int> cols,
bool transpose) const;
/**
* @brief Perform matrix matrix multiplication
C[:, :] += A * B
for sparse A, B, C
* @param C output matrix, may already contain values
* @param B multiplication matrix
*/
void sparse_multiply(SUNMatrixWrapper *C,
SUNMatrixWrapper *B) const;
/**
* @brief Set to 0.0
*/
void zero();
private:
void update_ptrs();
/**
* @brief CSC matrix to which all methods are applied
*/
SUNMatrix matrix_ {nullptr};
realtype *data_ptr_ {nullptr};
sunindextype *indexptrs_ptr_ {nullptr};
sunindextype *indexvals_ptr_ {nullptr};
};
} // namespace amici
namespace gsl {
/**
* @brief Create span from SUNMatrix
* @param nv
* @return
*/
inline span<realtype> make_span(SUNMatrix m)
{
switch (SUNMatGetID(m)) {
case SUNMATRIX_DENSE:
return span<realtype>(SM_DATA_D(m), SM_LDATA_D(m));
case SUNMATRIX_SPARSE:
return span<realtype>(SM_DATA_S(m), SM_NNZ_S(m));
default:
throw amici::AmiException("Unimplemented SUNMatrix type for make_span");
}
}
} // namespace gsl
#endif // AMICI_SUNDIALS_MATRIX_WRAPPER_H
| {
"alphanum_fraction": 0.6224572823,
"avg_line_length": 25.4979253112,
"ext": "h",
"hexsha": "aeb04643c61915743aa8136ad12d872967951d7b",
"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": "7a1dc5ed1299273b3670239f5d614eec835f1299",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "lcontento/AMICI",
"max_forks_repo_path": "include/amici/sundials_matrix_wrapper.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299",
"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": "lcontento/AMICI",
"max_issues_repo_path": "include/amici/sundials_matrix_wrapper.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "lcontento/AMICI",
"max_stars_repo_path": "include/amici/sundials_matrix_wrapper.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1525,
"size": 6145
} |
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include "gsl_utils.h"
#define ROUND(x) (int)(((x) >= 0) ? ((x) + 0.5) : ((x) - 0.5))
void dfs(VFloat** Dfs,gsl_matrix_float* pinvX,gsl_matrix_float* X,gsl_matrix_float* con,int numlags)
{
int numcon = 1;
int n = X->size2;
/* these vals represent the matlab interval 2:n */
int k1 = 1;
int k2 = n-1;
int i;
/* X^T */
gsl_matrix_float* transX = gsl_matrix_float_alloc(X->size2, X->size1);
gsl_matrix_float_transpose_memcpy(transX,X);
gsl_vector_float* CorX2 = gsl_vector_float_alloc(numcon);
gsl_vector_float_set_zero(CorX2);
/* cpinvX=contrast^T*pinvX */
gsl_matrix_float* cpinvX = fmat_x_mat(con, pinvX, NULL);
/* CovX0=cpinvX*cpinvX' */
gsl_matrix_float* CovX0 = fmat_x_matT(cpinvX,cpinvX,NULL);
if(numlags == 1) {
/* CovX1=cpinvX(:,k1)*cpinvX(:,k1-1)' */
gsl_matrix_float_view sub1 =
gsl_matrix_float_submatrix(cpinvX,0,k1,cpinvX->size1,k2);
gsl_matrix_float_view sub2 =
gsl_matrix_float_submatrix(cpinvX,0,k1-1,cpinvX->size1,k2);
gsl_matrix_float* CovX1 = fmat_x_matT(&sub1.matrix, &sub2.matrix, NULL);
gsl_vector_float_view CovX1diag = gsl_matrix_float_diagonal(CovX1);
gsl_vector_float_view CovX0diag = gsl_matrix_float_diagonal(CovX0);
gsl_vector_float_div (&CovX1diag.vector, &CovX0diag.vector);
gsl_vector_float_mul (&CovX1diag.vector, &CovX1diag.vector);
gsl_vector_float_memcpy (CorX2, &CovX1diag.vector);
}
else {
int lag;
gsl_matrix_float_view sub1, sub2;
gsl_matrix_float* CovX1 = gsl_matrix_float_alloc(cpinvX->size1,cpinvX->size1);
for(lag=0;lag<numlags;lag++){
sub1 = gsl_matrix_float_submatrix(cpinvX,0,0,cpinvX->size1,k2-lag);
sub2 = gsl_matrix_float_submatrix(cpinvX,0,lag+1,cpinvX->size1,k2-lag);
fmat_x_matT(&sub1.matrix, &sub2.matrix,CovX1);
gsl_vector_float_view CovX1diag = gsl_matrix_float_diagonal(CovX1);
gsl_vector_float_view CovX0diag = gsl_matrix_float_diagonal(CovX0);
gsl_vector_float_div (&CovX1diag.vector, &CovX0diag.vector);
gsl_vector_float_mul (&CovX1diag.vector, &CovX1diag.vector);
gsl_vector_float_add(CorX2,&CovX1diag.vector);
}
gsl_matrix_float_free(CovX1);
}
float dfresid = n-rank(transX);
float dfmin = dfresid;
for (i=0;i<numcon;i++) {
(*Dfs)[i] = (VFloat)ROUND(dfresid / (1 + 2*gsl_vector_float_get(CorX2,i)));
if ((*Dfs)[i]<dfmin) dfmin = (*Dfs)[i];
}
(*Dfs)[numcon] = dfresid;
/*
if(dfmin < 100)
fprintf(stderr, " warning, dfmin= %f\n",dfmin);
*/
gsl_matrix_float_free(cpinvX);
gsl_matrix_float_free(transX);
gsl_matrix_float_free(CovX0);
gsl_vector_float_free(CorX2);
}
| {
"alphanum_fraction": 0.6903225806,
"avg_line_length": 30.3608247423,
"ext": "c",
"hexsha": "4e06cff82b3453288272e51cf2642078012c8669",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_prewhitening/dfs.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_prewhitening/dfs.c",
"max_line_length": 101,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_prewhitening/dfs.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 1001,
"size": 2945
} |
/* matrix/gsl_matrix_short.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_SHORT_H__
#define __GSL_MATRIX_SHORT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_short.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;
short * data;
gsl_block_short * block;
int owner;
} gsl_matrix_short;
typedef struct
{
gsl_matrix_short matrix;
} _gsl_matrix_short_view;
typedef _gsl_matrix_short_view gsl_matrix_short_view;
typedef struct
{
gsl_matrix_short matrix;
} _gsl_matrix_short_const_view;
typedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view;
/* Allocation */
GSL_EXPORT
gsl_matrix_short *
gsl_matrix_short_alloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_short *
gsl_matrix_short_calloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_short *
gsl_matrix_short_alloc_from_block (gsl_block_short * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_EXPORT
gsl_matrix_short *
gsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_EXPORT
gsl_vector_short *
gsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m,
const size_t i);
GSL_EXPORT
gsl_vector_short *
gsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m,
const size_t j);
GSL_EXPORT void gsl_matrix_short_free (gsl_matrix_short * m);
/* Views */
GSL_EXPORT
_gsl_matrix_short_view
gsl_matrix_short_submatrix (gsl_matrix_short * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_short_view
gsl_matrix_short_row (gsl_matrix_short * m, const size_t i);
GSL_EXPORT
_gsl_vector_short_view
gsl_matrix_short_column (gsl_matrix_short * m, const size_t j);
GSL_EXPORT
_gsl_vector_short_view
gsl_matrix_short_diagonal (gsl_matrix_short * m);
GSL_EXPORT
_gsl_vector_short_view
gsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k);
GSL_EXPORT
_gsl_vector_short_view
gsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k);
GSL_EXPORT
_gsl_matrix_short_view
gsl_matrix_short_view_array (short * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_short_view
gsl_matrix_short_view_array_with_tda (short * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_short_view
gsl_matrix_short_view_vector (gsl_vector_short * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_short_view
gsl_matrix_short_view_vector_with_tda (gsl_vector_short * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_short_const_view
gsl_matrix_short_const_submatrix (const gsl_matrix_short * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_short_const_view
gsl_matrix_short_const_row (const gsl_matrix_short * m,
const size_t i);
GSL_EXPORT
_gsl_vector_short_const_view
gsl_matrix_short_const_column (const gsl_matrix_short * m,
const size_t j);
GSL_EXPORT
_gsl_vector_short_const_view
gsl_matrix_short_const_diagonal (const gsl_matrix_short * m);
GSL_EXPORT
_gsl_vector_short_const_view
gsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m,
const size_t k);
GSL_EXPORT
_gsl_vector_short_const_view
gsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m,
const size_t k);
GSL_EXPORT
_gsl_matrix_short_const_view
gsl_matrix_short_const_view_array (const short * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_short_const_view
gsl_matrix_short_const_view_array_with_tda (const short * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_short_const_view
gsl_matrix_short_const_view_vector (const gsl_vector_short * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_short_const_view
gsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_EXPORT short gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x);
GSL_EXPORT short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_EXPORT const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_short_set_zero (gsl_matrix_short * m);
GSL_EXPORT void gsl_matrix_short_set_identity (gsl_matrix_short * m);
GSL_EXPORT void gsl_matrix_short_set_all (gsl_matrix_short * m, short x);
GSL_EXPORT int gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ;
GSL_EXPORT int gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ;
GSL_EXPORT int gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m);
GSL_EXPORT int gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format);
GSL_EXPORT int gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src);
GSL_EXPORT int gsl_matrix_short_swap(gsl_matrix_short * m1, gsl_matrix_short * m2);
GSL_EXPORT int gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_short_transpose (gsl_matrix_short * m);
GSL_EXPORT int gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src);
GSL_EXPORT short gsl_matrix_short_max (const gsl_matrix_short * m);
GSL_EXPORT short gsl_matrix_short_min (const gsl_matrix_short * m);
GSL_EXPORT void gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out);
GSL_EXPORT void gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax);
GSL_EXPORT void gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin);
GSL_EXPORT void gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_EXPORT int gsl_matrix_short_isnull (const gsl_matrix_short * m);
GSL_EXPORT int gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_EXPORT int gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_EXPORT int gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_EXPORT int gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_EXPORT int gsl_matrix_short_scale (gsl_matrix_short * a, const double x);
GSL_EXPORT int gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x);
GSL_EXPORT int gsl_matrix_short_add_diagonal (gsl_matrix_short * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_EXPORT int gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i);
GSL_EXPORT int gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j);
GSL_EXPORT int gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v);
GSL_EXPORT int gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v);
/* inline functions if you are using GCC */
#ifdef HAVE_INLINE
extern inline
short
gsl_matrix_short_get(const gsl_matrix_short * 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_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short 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
short *
gsl_matrix_short_ptr(gsl_matrix_short * 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 (short *) (m->data + (i * m->tda + j)) ;
}
extern inline
const short *
gsl_matrix_short_const_ptr(const gsl_matrix_short * 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 short *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_SHORT_H__ */
| {
"alphanum_fraction": 0.6796686227,
"avg_line_length": 33.7842565598,
"ext": "h",
"hexsha": "ab72bd196f23b47dc0ee1b64bd2d9a39432fadba",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_short.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_short.h",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_short.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2787,
"size": 11588
} |
/***************************************************************************/
/* */
/* matrix.c - Matrix class for mruby */
/* Copyright (C) 2015 Paolo Bosetti */
/* paolo[dot]bosetti[at]unitn.it */
/* Department of Industrial Engineering, University of Trento */
/* */
/* This library is free software. You can redistribute it and/or */
/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0. */
/* */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* Artistic License 2.0 for more details. */
/* */
/* See the file LICENSE */
/* */
/***************************************************************************/
#include <gsl/gsl_blas.h>
#include <gsl/gsl_rng.h>
#include "matrix.h"
#include "vector.h"
#pragma mark -
#pragma mark • Utilities
// Garbage collector handler, for play_data struct
// if play_data contains other dynamic data, free it too!
// Check it with GC.start
void matrix_destructor(mrb_state *mrb, void *p_) {
gsl_matrix *v = (gsl_matrix *)p_;
gsl_matrix_free(v);
};
// Creating data type and reference for GC, in a const struct
const struct mrb_data_type matrix_data_type = {"matrix_data",
matrix_destructor};
// Utility function for getting the struct out of the wrapping IV @data
void mrb_matrix_get_data(mrb_state *mrb, mrb_value self, gsl_matrix **data) {
mrb_value data_value;
data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data"));
// Loading data from data_value into p_data:
Data_Get_Struct(mrb, data_value, &matrix_data_type, *data);
if (!*data)
mrb_raise(mrb, E_RUNTIME_ERROR, "Could not access @data");
}
#pragma mark -
#pragma mark • Initializations and setup
// Data Initializer C function (not exposed!)
static void mrb_matrix_init(mrb_state *mrb, mrb_value self, mrb_int n,
mrb_int m) {
mrb_value data_value; // this IV holds the data
gsl_matrix *p_data; // pointer to the C struct
data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data"));
// if @data already exists, free its content:
if (!mrb_nil_p(data_value)) {
Data_Get_Struct(mrb, data_value, &matrix_data_type, p_data);
free(p_data);
}
// Allocate and zero-out the data struct:
p_data = gsl_matrix_calloc(n, m);
if (!p_data)
mrb_raise(mrb, E_RUNTIME_ERROR, "Could not allocate @data");
// Wrap struct into @data:
mrb_iv_set(
mrb, self, mrb_intern_lit(mrb, "@data"), // set @data
mrb_obj_value( // with value hold in struct
Data_Wrap_Struct(mrb, mrb->object_class, &matrix_data_type, p_data)));
}
static mrb_value mrb_matrix_initialize(mrb_state *mrb, mrb_value self) {
mrb_int n, m;
mrb_get_args(mrb, "ii", &n, &m);
// Call strcut initializer:
mrb_matrix_init(mrb, self, n, m);
mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@nrows"), mrb_fixnum_value(n));
mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@ncols"), mrb_fixnum_value(m));
mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@format"),
mrb_str_new_cstr(mrb, "%10.3f"));
return mrb_nil_value();
}
static mrb_value mrb_matrix_dup(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_matrix *p_mat = NULL, *p_mat_other = NULL;
mrb_value args[2];
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
args[0] = mrb_fixnum_value(p_mat->size1);
args[1] = mrb_fixnum_value(p_mat->size2);
other = mrb_obj_new(mrb, mrb_class_get(mrb, "Matrix"), 2, args);
mrb_matrix_get_data(mrb, other, &p_mat_other);
gsl_matrix_memcpy(p_mat_other, p_mat);
return other;
}
static mrb_value mrb_matrix_rnd_fill(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat = NULL;
const gsl_rng_type *T;
gsl_rng *r;
mrb_int h, k;
mrb_matrix_get_data(mrb, self, &p_mat);
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
for (k = 0; k < p_mat->size2; k++) {
for (h = 0; h < p_mat->size1; h++) {
gsl_matrix_set(p_mat, h, k, gsl_rng_uniform(r));
}
}
return self;
}
static mrb_value mrb_matrix_all(mrb_state *mrb, mrb_value self) {
mrb_float v;
gsl_matrix *p_mat = NULL;
mrb_get_args(mrb, "f", &v);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
gsl_matrix_set_all(p_mat, v);
return self;
}
static mrb_value mrb_matrix_zero(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat = NULL;
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
gsl_matrix_set_zero(p_mat);
return self;
}
static mrb_value mrb_matrix_identity(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat = NULL;
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
gsl_matrix_set_identity(p_mat);
return self;
}
#pragma mark -
#pragma mark • Tests
static mrb_value mrb_matrix_equal(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_matrix *p_mat, *p_mat_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
mrb_matrix_get_data(mrb, other, &p_mat_other);
if (1 == gsl_matrix_equal(p_mat, p_mat_other))
return mrb_true_value();
else
return mrb_false_value();
}
#pragma mark -
#pragma mark • Accessors
static mrb_value mrb_matrix_get_row(mrb_state *mrb, mrb_value self) {
mrb_int i, n;
mrb_value result, args[1];
gsl_matrix *p_mat = NULL;
gsl_vector *p_vec = NULL;
n = mrb_get_args(mrb, "|i", &i);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (n == 1) {
if (i >= p_mat->size1) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix index out of range!");
}
args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@ncols"));
result = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args);
mrb_vector_get_data(mrb, result, &p_vec);
gsl_matrix_get_row(p_vec, p_mat, i);
}
else {
result = mrb_ary_new_capa(mrb, p_mat->size1);
for (i = 0; i < p_mat->size1; i++) {
mrb_ary_push(mrb, result, mrb_funcall(mrb, self, "get_row", 1, mrb_fixnum_value(i)));
}
}
return result;
}
static mrb_value mrb_matrix_get_col(mrb_state *mrb, mrb_value self) {
mrb_int i;
mrb_value res, args[1];
gsl_matrix *p_mat = NULL;
gsl_vector *p_vec = NULL;
mrb_get_args(mrb, "i", &i);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (i >= p_mat->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix index out of range!");
}
args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@nrows"));
res = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args);
mrb_vector_get_data(mrb, res, &p_vec);
gsl_matrix_get_col(p_vec, p_mat, i);
return res;
}
static mrb_value mrb_matrix_get_ij(mrb_state *mrb, mrb_value self) {
mrb_value result;
mrb_int i, j;
gsl_matrix *p_mat = NULL;
mrb_int n;
n = mrb_get_args(mrb, "|ii", &i, &j);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (n == 2) {
if (i >= p_mat->size1 || j >= p_mat->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix index out of range!");
}
result = mrb_float_value(mrb, gsl_matrix_get(p_mat, (size_t)i, (size_t)j));
} else {
result = mrb_matrix_get_row(mrb, self);
}
return result;
}
static mrb_value mrb_matrix_set_ij(mrb_state *mrb, mrb_value self) {
mrb_int i, j;
mrb_float f;
gsl_matrix *p_mat = NULL;
mrb_get_args(mrb, "iif", &i, &j, &f);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (i >= p_mat->size1 || j >= p_mat->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix index out of range!");
}
gsl_matrix_set(p_mat, (size_t)i, (size_t)j, (double)f);
return mrb_float_value(mrb, f);
}
static mrb_value mrb_matrix_set_row(mrb_state *mrb, mrb_value self) {
mrb_int i;
mrb_value other;
gsl_matrix *p_mat = NULL;
gsl_vector *p_vec = NULL;
mrb_get_args(mrb, "io", &i, &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (i >= p_mat->size1) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix row index out of range!");
}
mrb_vector_get_data(mrb, other, &p_vec);
if (p_mat->size2 != p_vec->size) {
mrb_raise(mrb, E_MATRIX_ERROR, "Size mismatch!");
}
gsl_matrix_set_row(p_mat, i, p_vec);
return self;
}
static mrb_value mrb_matrix_set_col(mrb_state *mrb, mrb_value self) {
mrb_int i;
mrb_value other;
gsl_matrix *p_mat = NULL;
gsl_vector *p_vec = NULL;
mrb_get_args(mrb, "io", &i, &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (i >= p_mat->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix col index out of range!");
}
mrb_vector_get_data(mrb, other, &p_vec);
if (p_mat->size1 != p_vec->size) {
mrb_raise(mrb, E_MATRIX_ERROR, "Size mismatch!");
}
gsl_matrix_set_col(p_mat, i, p_vec);
return self;
}
#pragma mark -
#pragma mark • Properties
static mrb_value mrb_matrix_max(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat = NULL;
mrb_matrix_get_data(mrb, self, &p_mat);
return mrb_float_value(mrb, gsl_matrix_max(p_mat));
}
static mrb_value mrb_matrix_min(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat = NULL;
mrb_matrix_get_data(mrb, self, &p_mat);
return mrb_float_value(mrb, gsl_matrix_min(p_mat));
}
static mrb_value mrb_matrix_max_index(mrb_state *mrb, mrb_value self) {
size_t i, j;
mrb_value res = mrb_ary_new_capa(mrb, 2);
gsl_matrix *p_mat = NULL;
mrb_matrix_get_data(mrb, self, &p_mat);
gsl_matrix_max_index(p_mat, &i, &j);
mrb_ary_push(mrb, res, mrb_fixnum_value(i));
mrb_ary_push(mrb, res, mrb_fixnum_value(j));
return res;
}
static mrb_value mrb_matrix_min_index(mrb_state *mrb, mrb_value self) {
size_t i, j;
mrb_value res = mrb_ary_new_capa(mrb, 2);
gsl_matrix *p_mat = NULL;
mrb_matrix_get_data(mrb, self, &p_mat);
gsl_matrix_min_index(p_mat, &i, &j);
mrb_ary_push(mrb, res, mrb_fixnum_value(i));
mrb_ary_push(mrb, res, mrb_fixnum_value(j));
return res;
}
#pragma mark -
#pragma mark • Operations
static mrb_value mrb_matrix_add(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_matrix *p_mat, *p_mat_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Matrix"))) {
mrb_matrix_get_data(mrb, other, &p_mat_other);
if (p_mat->size1 != p_mat_other->size1 ||
p_mat->size2 != p_mat_other->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix dimensions don't match!");
}
gsl_matrix_add(p_mat, p_mat_other);
} else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Numeric"))) {
gsl_matrix_add_constant(p_mat, mrb_to_flo(mrb, other));
}
return self;
}
static mrb_value mrb_matrix_sub(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_matrix *p_mat, *p_mat_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
mrb_matrix_get_data(mrb, other, &p_mat_other);
if (p_mat->size1 != p_mat_other->size1 ||
p_mat->size2 != p_mat_other->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix dimensions don't match!");
}
gsl_matrix_sub(p_mat, p_mat_other);
return self;
}
static mrb_value mrb_matrix_mul(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_matrix *p_mat, *p_mat_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Matrix"))) {
mrb_matrix_get_data(mrb, other, &p_mat_other);
if (p_mat->size1 != p_mat_other->size1 ||
p_mat->size2 != p_mat_other->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix dimensions don't match!");
}
gsl_matrix_mul_elements(p_mat, p_mat_other);
} else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Numeric"))) {
gsl_matrix_scale(p_mat, mrb_to_flo(mrb, other));
}
return self;
}
static mrb_value mrb_matrix_prod(mrb_state *mrb, mrb_value self) {
mrb_value other, res;
gsl_matrix *p_mat, *p_mat_other, *p_mat_res;
gsl_vector *p_vec_other, *p_vec_res;
mrb_value args[2];
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Matrix"))) {
args[1] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@nrows"));
args[0] = mrb_iv_get(mrb, other, mrb_intern_lit(mrb, "@ncols"));
res = mrb_obj_new(mrb, mrb_class_get(mrb, "Matrix"), 2, args);
mrb_matrix_get_data(mrb, other, &p_mat_other);
mrb_matrix_get_data(mrb, res, &p_mat_res);
if (p_mat->size2 != p_mat_other->size1) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix dimensions don't match!");
}
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, p_mat, p_mat_other, 0.0,
p_mat_res);
} else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Vector"))) {
args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@nrows"));
res = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args);
mrb_vector_get_data(mrb, other, &p_vec_other);
mrb_vector_get_data(mrb, res, &p_vec_res);
if (p_mat->size2 != p_vec_other->size) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix dimensions don't match!");
}
gsl_blas_dgemv(CblasNoTrans, 1.0, p_mat, p_vec_other, 0.0, p_vec_res);
}
return res;
}
static mrb_value mrb_matrix_div(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_matrix *p_mat, *p_mat_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
mrb_matrix_get_data(mrb, other, &p_mat_other);
if (p_mat->size1 != p_mat_other->size1 ||
p_mat->size2 != p_mat_other->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix dimensions don't match!");
}
gsl_matrix_div_elements(p_mat, p_mat_other);
return self;
}
static mrb_value mrb_matrix_transpose_self(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat;
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (p_mat->size1 != p_mat->size2) {
mrb_raise(mrb, E_MATRIX_ERROR, "matrix must be square!");
}
if (gsl_matrix_transpose(p_mat)) {
mrb_raise(mrb, E_MATRIX_ERROR, "Cannot calculate transposed matrix");
}
return self;
}
static mrb_value mrb_matrix_transpose(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_matrix *p_mat, *p_mat_other;
mrb_value args[2];
// swap dimensions!
args[1] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@nrows"));
args[0] = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@ncols"));
other = mrb_obj_new(mrb, mrb_class_get(mrb, "Matrix"), 2, args);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
mrb_matrix_get_data(mrb, other, &p_mat_other);
if (gsl_matrix_transpose_memcpy(p_mat_other, p_mat)) {
mrb_raise(mrb, E_MATRIX_ERROR, "Cannot calculate transposed matrix");
}
return other;
}
static mrb_value mrb_matrix_swap_rows(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat;
mrb_int i, j;
mrb_get_args(mrb, "ii", &i, &j);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (gsl_matrix_swap_rows(p_mat, i, j)) {
mrb_raise(mrb, E_MATRIX_ERROR, "Cannot swap rows");
}
return self;
}
static mrb_value mrb_matrix_swap_cols(mrb_state *mrb, mrb_value self) {
gsl_matrix *p_mat;
mrb_int i, j;
mrb_get_args(mrb, "ii", &i, &j);
// call utility for unwrapping @data into p_data:
mrb_matrix_get_data(mrb, self, &p_mat);
if (gsl_matrix_swap_columns(p_mat, i, j)) {
mrb_raise(mrb, E_MATRIX_ERROR, "Cannot swap cols");
}
return self;
}
#pragma mark -
#pragma mark • Gem setup
void mrb_gsl_matrix_init(mrb_state *mrb) {
struct RClass *gsl;
mrb_load_string(mrb, "class MatrixError < Exception; end");
gsl = mrb_define_class(mrb, "Matrix", mrb->object_class);
mrb_define_method(mrb, gsl, "initialize", mrb_matrix_initialize,
MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "dup", mrb_matrix_dup, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "all", mrb_matrix_all, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "zero", mrb_matrix_zero, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "identity", mrb_matrix_identity, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "rnd_fill", mrb_matrix_rnd_fill, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "===", mrb_matrix_equal, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "[]", mrb_matrix_get_ij, MRB_ARGS_OPT(2));
mrb_define_method(mrb, gsl, "row", mrb_matrix_get_row, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "col", mrb_matrix_get_col, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "[]=", mrb_matrix_set_ij, MRB_ARGS_REQ(3));
mrb_define_method(mrb, gsl, "get_row", mrb_matrix_get_row, MRB_ARGS_OPT(1));
mrb_define_method(mrb, gsl, "get_col", mrb_matrix_get_col, MRB_ARGS_OPT(1));
mrb_define_method(mrb, gsl, "set_row", mrb_matrix_set_row, MRB_ARGS_REQ(2));
mrb_define_method(mrb, gsl, "set_col", mrb_matrix_set_col, MRB_ARGS_REQ(2));
mrb_define_method(mrb, gsl, "max", mrb_matrix_max, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "max_index", mrb_matrix_max_index,
MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "min", mrb_matrix_min, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "min_index", mrb_matrix_min_index,
MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "add!", mrb_matrix_add, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "sub!", mrb_matrix_sub, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "mul!", mrb_matrix_mul, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "div!", mrb_matrix_div, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "^", mrb_matrix_prod, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "t!", mrb_matrix_transpose_self, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "t", mrb_matrix_transpose, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "swap_rows", mrb_matrix_swap_rows,
MRB_ARGS_REQ(2));
mrb_define_method(mrb, gsl, "swap_cols", mrb_matrix_swap_cols,
MRB_ARGS_REQ(2));
}
| {
"alphanum_fraction": 0.6700971984,
"avg_line_length": 35.1076642336,
"ext": "c",
"hexsha": "8a2d3fbeb800515f90ded14838d75c37f5a6bb11",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_forks_repo_path": "src/matrix.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_issues_repo_path": "src/matrix.c",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_stars_repo_path": "src/matrix.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5604,
"size": 19239
} |
//
// gemmtest.c
//
// J. Makino
// Time-stamp: <10/10/17 13:43:33 makino>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <timerlib.h>
#ifndef NOBLAS
#include <cblas.h>
#endif
#ifdef USEGDR
#include "gdrdgemm.h"
#endif
#define FTYPE double
#include <emmintrin.h>
typedef double v2df __attribute__((vector_size(16)));
typedef union {v2df v; double s[2];}v2u;
#ifndef USEGDR
void gdrsetboardid(int boardid)
{}
#endif
void matmul2_host(int n,
FTYPE a[n][n],
FTYPE b[n][n],
FTYPE c[n][n])
{
int i, j, k;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
c[i][j]=0.0e0;
for(k=0;k<n;k++) c[i][j]+= a[i][k]*b[k][j];
}
}
}
// simplest version
void matmul_for_small_nk_0(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int kk,
int n)
{
// simplest version
int i,j,k;
for(j=0;j<n;j++)
for(i=0;i<m;i++)
for(k=0;k<kk;k++)
c[i][j] -= a[i][k]*b[k][j];
}
// XMM registers
#define X0 "%xmm0"
#define X1 "%xmm1"
#define X2 "%xmm2"
#define X3 "%xmm3"
#define X4 "%xmm4"
#define X5 "%xmm5"
#define X6 "%xmm6"
#define X7 "%xmm7"
#define X8 "%xmm8"
#define X9 "%xmm9"
#define X10 "%xmm10"
#define X11 "%xmm11"
#define X12 "%xmm12"
#define X13 "%xmm13"
#define X14 "%xmm14"
#define X15 "%xmm15"
#define LOADPD(mem, reg) asm("movapd %0, %"reg::"m"(mem));
#define STORPD(reg, mem) asm("movapd %"reg " , %0"::"m"(mem));
#define MOVNTPD(reg, mem) asm("movntpd %"reg " , %0"::"m"(mem));
#define MOVAPD(src, dst) asm("movapd " src "," dst);
#define MOVQ(src, dst) asm("movq " src "," dst);
#define BCAST0(reg) asm("shufpd $0x00, " reg "," reg);
#define BCAST1(reg) asm("shufpd $0xff, " reg "," reg);
#define MULPD(src, dst) asm("mulpd " src "," dst);
#define ADDPD(src, dst) asm("addpd " src "," dst);
#define SUBPD(src, dst) asm("subpd " src "," dst);
void daxpy(v2df a[], v2df b[], v2df c[], int n)
{
int i;
for(i=0;i<n; i+=8){
b[i] += a[i]*c[0];
b[i+1] += a[i+1]*c[0];
b[i+2] += a[i+2]*c[0];
b[i+3] += a[i+3]*c[0];
b[i+4] += a[i+4]*c[0];
b[i+5] += a[i+5]*c[0];
b[i+6] += a[i+6]*c[0];
b[i+7] += a[i+7]*c[0];
}
}
void matmul_for_nk16_0a(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 16;
int nh = n/2;
register int k;
v2df bcopy2[nh][kk];
for(j=0;j<nh;j++)
for(k=0;k<kk;k++)
// bcopy2[j][k] = *((v2df*)(b[k]+j+j));
bcopy2[j][k] = *(((v2df*)b)+j*n2+k);
for(i=0;i<m;i+=2){
// BEGIN_TSC;
v2df *ap = (v2df*) a[i];
v2df * cp = (v2df*) (&(c[i][0]));
v2df *app = (v2df*) a[i+1];
v2df * cpp = (v2df*) (&(c[i+1][0]));
int k;
for(j=0;j<nh;j+=2){
v2df * bvp0 = bcopy2[j];
v2df * bvp1 = bcopy2[j+1];
LOADPD(cp[j],X12);
LOADPD(cp[j+1],X13);
LOADPD(cpp[j],X14);
LOADPD(cpp[j+1],X15);
for(k=0;k<8;k++){
LOADPD(ap[k],X0);
LOADPD(app[k],X2);
LOADPD(bvp0[k*2],X4);
LOADPD(bvp1[k*2],X5);
LOADPD(bvp0[k*2+1],X8);
LOADPD(bvp1[k*2+1],X9);
MOVAPD(X4,X6);
MOVAPD(X5,X7);
MOVAPD(X8,X10);
MOVAPD(X9,X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MOVAPD(X2,X3);
BCAST0(X2);
BCAST1(X3);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X1,X8);
MULPD(X1,X9);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X8,X12);
SUBPD(X9,X13);
MULPD(X2,X6);
MULPD(X2,X7);
MULPD(X3,X10);
MULPD(X3,X11);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X10,X14);
SUBPD(X11,X15);
}
STORPD(X12,cp[j+0]);
STORPD(X13,cp[j+1]);
STORPD(X14,cpp[j+0]);
STORPD(X15,cpp[j+1]);
}
}
}
void matmul_for_nk16_test1(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j,k;
int kk = 16;
int nh = n/2;
v2df bcopy[nh][kk];
for(j=0;j<nh;j++)
for(k=0;k<kk;k++)
bcopy[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i+=2){
v2df csub[nh][2];
for(j=0;j<2;j++){
v2df * src = (v2df*) c[i+j];
for(k=0;k<nh;k++){
csub[k][j]=src[k];
}
}
for(k=0;k<kk;k+=4){
v2df *ap = (v2df*) a[i]+k;
v2df *app = (v2df*) a[i+1]+k;
LOADPD(ap[0],X8);
LOADPD(ap[1],X9);
LOADPD(app[0],X10);
LOADPD(app[1],X11);
MOVAPD(X8,X0);
BCAST0(X0);
MOVAPD(X8,X1);
BCAST1(X1);
MOVAPD(X9,X2);
BCAST0(X2);
MOVAPD(X9,X3);
BCAST1(X3);
MOVAPD(X10,X4);
BCAST0(X4);
MOVAPD(X10,X5);
BCAST1(X5);
MOVAPD(X11,X6);
BCAST0(X6);
MOVAPD(X11,X7);
BCAST1(X7);
// 2x4 a, size doubled to 4x4
for(j=0;j<nh;j++){
v2df * bvp = bcopy[j]+k;
v2df * cvp = csub[k];
LOADPD(bvp[0],X8);
LOADPD(bvp[1],X9);
MOVAPD(X8,X14);
MOVAPD(X9,X15);
MULPD(X0,X14);
MULPD(X1,X15);
LOADPD(bvp[2],X10);
LOADPD(bvp[3],X11);
LOADPD(cvp[0],X12);
LOADPD(cvp[1],X13);
SUBPD(X14,X12);
SUBPD(X15,X12);
MOVAPD(X10,X14);
MOVAPD(X11,X15);
MULPD(X2,X14);
MULPD(X3,X15);
SUBPD(X14,X12);
SUBPD(X15,X12);
MULPD(X4,X8);
MULPD(X5,X9);
MULPD(X6,X10);
MULPD(X7,X11);
SUBPD(X8,X13);
SUBPD(X9,X13);
SUBPD(X10,X13);
SUBPD(X11,X13);
STORPD(X12, cvp[0]);
STORPD(X13, cvp[1]);
}
}
// copyback cmat
for(j=0;j<2;j++){
v2df * dest = (v2df*) c[i+j];
for(k=0;k<nh;k++){
dest[k] = csub[k][j];
}
}
}
}
void matmul_for_nk16_0c(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 16;
int nh = n/2;
register int k;
v2df bcopy2[nh][kk];
#ifdef PREFETCHL
#undef PREFETCHL
#endif
#define PREFETCHL 16
for(i=0;i<PREFETCHL;i++){
__builtin_prefetch((double*)a[i],0,0);
__builtin_prefetch((double*)a[i]+8,0,0);
__builtin_prefetch(c[i+8],1,0);
__builtin_prefetch(c[i+8]+8,1,0);
}
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy2[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i++){
// BEGIN_TSC;
v2df *ap = (v2df*) a[i];
v2df * cp = (v2df*) (&(c[i][0]));
__builtin_prefetch((double*)a[i+PREFETCHL],0,0);
__builtin_prefetch((double*)a[i+PREFETCHL]+8,0,0);
int k;
for(j=0;j<nh;j+=4){
__builtin_prefetch(c[i+PREFETCHL]+j,1,0);
v2df * bvp0 = bcopy2[j];
v2df * bvp1 = bcopy2[j+1];
v2df * bvp2 = bcopy2[j+2];
v2df * bvp3 = bcopy2[j+3];
LOADPD(cp[j],X12);
LOADPD(cp[j+1],X13);
LOADPD(cp[j+2],X14);
LOADPD(cp[j+3],X15);
for(k=0;k<8;k++){
LOADPD(ap[k],X0);
LOADPD(bvp0[k*2],X4);
LOADPD(bvp1[k*2],X5);
LOADPD(bvp2[k*2],X6);
LOADPD(bvp3[k*2],X7);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
LOADPD(bvp0[k*2+1],X8);
LOADPD(bvp1[k*2+1],X9);
LOADPD(bvp2[k*2+1],X10);
LOADPD(bvp3[k*2+1],X11);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
}
STORPD(X12,cp[j+0]);
STORPD(X13,cp[j+1]);
STORPD(X14,cp[j+2]);
STORPD(X15,cp[j+3]);
}
}
}
void matmul_for_nk32_0(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 32;
int nh = n/2;
register int k;
v2df bcopy2[nh][kk];
#ifdef PREFETCHL
#undef PREFETCHL
#endif
#define PREFETCHL 8
for(i=0;i<PREFETCHL;i++){
__builtin_prefetch((double*)a[i],0,0);
__builtin_prefetch((double*)a[i]+8,0,0);
__builtin_prefetch((double*)a[i]+16,0,0);
__builtin_prefetch((double*)a[i]+24,0,0);
__builtin_prefetch(c[i+8],1,0);
__builtin_prefetch(c[i+8]+8,1,0);
__builtin_prefetch(c[i+8]+16,1,0);
__builtin_prefetch(c[i+8]+24,1,0);
}
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy2[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i++){
// BEGIN_TSC;
v2df *ap = (v2df*) a[i];
v2df * cp = (v2df*) (&(c[i][0]));
__builtin_prefetch((double*)a[i+PREFETCHL],0,0);
__builtin_prefetch((double*)a[i+PREFETCHL]+8,0,0);
__builtin_prefetch((double*)a[i+PREFETCHL]+16,0,0);
__builtin_prefetch((double*)a[i+PREFETCHL]+24,0,0);
int k;
for(j=0;j<nh;j+=4){
__builtin_prefetch(c[i+PREFETCHL]+j,1,0);
v2df * bvp0 = bcopy2[j];
v2df * bvp1 = bcopy2[j+1];
v2df * bvp2 = bcopy2[j+2];
v2df * bvp3 = bcopy2[j+3];
LOADPD(cp[j],X12);
LOADPD(cp[j+1],X13);
LOADPD(cp[j+2],X14);
LOADPD(cp[j+3],X15);
for(k=0;k<16;k++){
LOADPD(ap[k],X0);
LOADPD(bvp0[k*2],X4);
LOADPD(bvp1[k*2],X5);
LOADPD(bvp2[k*2],X6);
LOADPD(bvp3[k*2],X7);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
LOADPD(bvp0[k*2+1],X8);
LOADPD(bvp1[k*2+1],X9);
LOADPD(bvp2[k*2+1],X10);
LOADPD(bvp3[k*2+1],X11);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
}
STORPD(X12,cp[j+0]);
STORPD(X13,cp[j+1]);
STORPD(X14,cp[j+2]);
STORPD(X15,cp[j+3]);
}
}
}
void matmul_for_nk16_0b(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 16;
int nh = n/2;
register int k;
v2df bcopy2[nh][kk];
#ifdef PREFETCHL
#undef PREFETCHL
#endif
#define PREFETCHL 16
for(i=0;i<PREFETCHL;i++){
__builtin_prefetch((double*)a[i],0,0);
__builtin_prefetch((double*)a[i]+8,0,0);
__builtin_prefetch(c[i+8],1,0);
__builtin_prefetch(c[i+8]+8,1,0);
}
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy2[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i++){
// BEGIN_TSC;
v2df *ap = (v2df*) a[i];
v2df * cp = (v2df*) (&(c[i][0]));
__builtin_prefetch((double*)a[i+PREFETCHL],0,0);
__builtin_prefetch((double*)a[i+PREFETCHL]+8,0,0);
int k;
for(j=0;j<nh;j+=4){
__builtin_prefetch(c[i+PREFETCHL]+j,1,0);
v2df * bvp0 = bcopy2[j];
v2df * bvp1 = bcopy2[j+1];
v2df * bvp2 = bcopy2[j+2];
v2df * bvp3 = bcopy2[j+3];
LOADPD(cp[j],X12);
LOADPD(cp[j+1],X13);
LOADPD(cp[j+2],X14);
LOADPD(cp[j+3],X15);
LOADPD(ap[0],X0);
LOADPD(bvp0[0],X4);
LOADPD(bvp1[0],X5);
LOADPD(bvp2[0],X6);
LOADPD(bvp3[0],X7);
LOADPD(bvp0[1],X8);
LOADPD(bvp1[1],X9);
LOADPD(bvp2[1],X10);
LOADPD(bvp3[1],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
LOADPD(ap[1],X0);
LOADPD(bvp0[2],X4);
LOADPD(bvp1[2],X5);
LOADPD(bvp2[2],X6);
LOADPD(bvp3[2],X7);
LOADPD(bvp0[3],X8);
LOADPD(bvp1[3],X9);
LOADPD(bvp2[3],X10);
LOADPD(bvp3[3],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
LOADPD(ap[2],X0);
LOADPD(bvp0[4],X4);
LOADPD(bvp1[4],X5);
LOADPD(bvp2[4],X6);
LOADPD(bvp3[4],X7);
LOADPD(bvp0[5],X8);
LOADPD(bvp1[5],X9);
LOADPD(bvp2[5],X10);
LOADPD(bvp3[5],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
LOADPD(ap[3],X0);
LOADPD(bvp0[6],X4);
LOADPD(bvp1[6],X5);
LOADPD(bvp2[6],X6);
LOADPD(bvp3[6],X7);
LOADPD(bvp0[7],X8);
LOADPD(bvp1[7],X9);
LOADPD(bvp2[7],X10);
LOADPD(bvp3[7],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
LOADPD(ap[4],X0);
LOADPD(bvp0[8],X4);
LOADPD(bvp1[8],X5);
LOADPD(bvp2[8],X6);
LOADPD(bvp3[8],X7);
LOADPD(bvp0[9],X8);
LOADPD(bvp1[9],X9);
LOADPD(bvp2[9],X10);
LOADPD(bvp3[9],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
LOADPD(ap[5],X0);
LOADPD(bvp0[10],X4);
LOADPD(bvp1[10],X5);
LOADPD(bvp2[10],X6);
LOADPD(bvp3[10],X7);
LOADPD(bvp0[11],X8);
LOADPD(bvp1[11],X9);
LOADPD(bvp2[11],X10);
LOADPD(bvp3[11],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
LOADPD(ap[6],X0);
LOADPD(bvp0[12],X4);
LOADPD(bvp1[12],X5);
LOADPD(bvp2[12],X6);
LOADPD(bvp3[12],X7);
LOADPD(bvp0[13],X8);
LOADPD(bvp1[13],X9);
LOADPD(bvp2[13],X10);
LOADPD(bvp3[13],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
LOADPD(ap[7],X0);
LOADPD(bvp0[14],X4);
LOADPD(bvp1[14],X5);
LOADPD(bvp2[14],X6);
LOADPD(bvp3[14],X7);
LOADPD(bvp0[15],X8);
LOADPD(bvp1[15],X9);
LOADPD(bvp2[15],X10);
LOADPD(bvp3[15],X11);
MOVAPD(X0,X1);
BCAST0(X0);
BCAST1(X1);
MULPD(X0,X4);
MULPD(X0,X5);
MULPD(X0,X6);
MULPD(X0,X7);
MULPD(X1,X8);
MULPD(X1,X9);
MULPD(X1,X10);
MULPD(X1,X11);
SUBPD(X4,X12);
SUBPD(X5,X13);
SUBPD(X6,X14);
SUBPD(X7,X15);
SUBPD(X8,X12);
SUBPD(X9,X13);
SUBPD(X10,X14);
SUBPD(X11,X15);
STORPD(X12,cp[j+0]);
STORPD(X13,cp[j+1]);
STORPD(X14,cp[j+2]);
STORPD(X15,cp[j+3]);
}
}
}
void matmul_for_nk8_0d(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 8;
int nh = n/2;
register int k;
double bcopy[n][kk];
v2df bcopy2[nh][kk];
v2df acopy[kk];
v2df acopy2[kk];
v2df awork[4];
v2df awork2[4];
double *acp = (double*) acopy;
double *acp2 = (double*) acopy2;
unsigned long bpcount, apcount, dotcount;
bpcount= apcount= dotcount=0;
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy2[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i++){
// BEGIN_TSC;
double *ap=a[i];
register v2df tmp, tmp2;
v2df * cp = (v2df*) (&(c[i][0]));
v2df * aa = (v2df*)(ap);
__builtin_prefetch((double*)a[i+8],0,0);
v2df acopy0=(v2df){a[i][0], a[i][0]};
v2df acopy1=(v2df){a[i][1], a[i][1]};
v2df acopy2=(v2df){a[i][2], a[i][2]};
v2df acopy3=(v2df){a[i][3], a[i][3]};
v2df acopy4=(v2df){a[i][4], a[i][4]};
v2df acopy5=(v2df){a[i][5], a[i][5]};
v2df acopy6=(v2df){a[i][6], a[i][6]};
v2df acopy7=(v2df){a[i][7], a[i][7]};
v2df zero=(v2df){0.0, 0.0};
LOADPD(acopy0,X0);
LOADPD(acopy1,X1);
LOADPD(acopy2,X2);
LOADPD(acopy3,X3);
LOADPD(acopy4,X4);
LOADPD(acopy5,X5);
LOADPD(acopy6,X6);
LOADPD(acopy7,X7);
for(j=0;j<nh;j++){
__builtin_prefetch(c[i+8]+j,1,0);
v2df * bvp = bcopy2[j];
LOADPD(cp[j],X14);
LOADPD(bvp[0],X8);
LOADPD(bvp[1],X9);
MULPD(X0,X8);
MULPD(X1,X9);
LOADPD(bvp[2],X10);
LOADPD(bvp[3],X11);
ADDPD(X9,X8);
MULPD(X2,X10);
MULPD(X3,X11);
ADDPD(X11,X10);
LOADPD(bvp[4],X9);
LOADPD(bvp[5],X11);
LOADPD(bvp[6],X12);
LOADPD(bvp[7],X13);
MULPD(X4,X9);
MULPD(X5,X11);
ADDPD(X10,X8);
ADDPD(X11,X9);
MULPD(X6,X12);
MULPD(X7,X13);
ADDPD(X13,X12);
ADDPD(X9,X8);
ADDPD(X12,X8);
SUBPD(X8,X14);
STORPD(X14,cp[j]);
}
}
}
void matmul_for_nk8_0c(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 8;
int nh = n/2;
register int k;
double bcopy[n][kk];
v2df bcopy2[nh][kk];
v2df acopy[kk];
v2df acopy2[kk];
v2df awork[4];
v2df awork2[4];
double *acp = (double*) acopy;
double *acp2 = (double*) acopy2;
unsigned long bpcount, apcount, dotcount;
bpcount= apcount= dotcount=0;
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy2[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i++){
// BEGIN_TSC;
double *ap=a[i];
register v2df tmp, tmp2;
v2df * cp = (v2df*) (&(c[i][0]));
v2df * aa = (v2df*)(ap);
__builtin_prefetch((double*)a[i+8],0,0);
register v2df acopy0=(v2df){a[i][0], a[i][0]};
register v2df acopy1=(v2df){a[i][1], a[i][1]};
register v2df acopy2=(v2df){a[i][2], a[i][2]};
register v2df acopy3=(v2df){a[i][3], a[i][3]};
register v2df acopy4=(v2df){a[i][4], a[i][4]};
register v2df acopy5=(v2df){a[i][5], a[i][5]};
register v2df acopy6=(v2df){a[i][6], a[i][6]};
register v2df acopy7=(v2df){a[i][7], a[i][7]};
for(j=0;j<nh;j++){
tmp = (v2df){0.0,0.0};
v2df ctmp= cp[j];
v2df * bp = bcopy2[j];
__builtin_prefetch(c[i+4]+j,1,0);
v2df *bvp = bp;
tmp += acopy0*bvp[0];
tmp +=acopy1*bvp[1];
tmp +=acopy2*bvp[2];
tmp +=acopy3*bvp[3];
tmp +=acopy4*bvp[4];
tmp +=acopy5*bvp[5];
tmp +=acopy6*bvp[6];
tmp +=acopy7*bvp[7];
cp[j] = ctmp -tmp;
}
}
// printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n,
// (double)bpcount, (double)apcount, (double)dotcount);
}
void matmul_for_nk8_0b(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 8;
int nh = n/2;
register int k;
double bcopy[n][kk];
v2df bcopy2[nh][kk];
v2df acopy[kk];
v2df acopy2[kk];
v2df awork[4];
v2df awork2[4];
double *acp = (double*) acopy;
double *acp2 = (double*) acopy2;
unsigned long bpcount, apcount, dotcount;
bpcount= apcount= dotcount=0;
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy2[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i++){
// BEGIN_TSC;
double *ap=a[i];
register v2df tmp, tmp2;
v2df * cp = (v2df*) (&(c[i][0]));
v2df * aa = (v2df*)(ap);
__builtin_prefetch((double*)a[i+8],0,0);
acopy[0]=(v2df){a[i][0], a[i][0]};
acopy[1]=(v2df){a[i][1], a[i][1]};
acopy[2]=(v2df){a[i][2], a[i][2]};
acopy[3]=(v2df){a[i][3], a[i][3]};
acopy[4]=(v2df){a[i][4], a[i][4]};
acopy[5]=(v2df){a[i][5], a[i][5]};
acopy[6]=(v2df){a[i][6], a[i][6]};
acopy[7]=(v2df){a[i][7], a[i][7]};
for(j=0;j<nh;j++){
tmp = tmp2= (v2df){0.0,0.0};
v2df ctmp= cp[j];
v2df * bp = bcopy2[j];
__builtin_prefetch(c[i+4]+j,1,0);
v2df *avp = acopy;
v2df *bvp = bp;
tmp += avp[0]*bvp[0];
tmp +=avp[1]*bvp[1];
tmp +=avp[2]*bvp[2];
tmp +=avp[3]*bvp[3];
tmp += avp[4]*bvp[4];
tmp +=avp[5]*bvp[5];
tmp +=avp[6]*bvp[6];
tmp +=avp[7]*bvp[7];
cp[j] = ctmp -tmp;
}
}
// printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n,
// (double)bpcount, (double)apcount, (double)dotcount);
}
void matmul_for_nk8_0a(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j;
int kk = 8;
int nh = n/2;
register int k;
double bcopy[n][kk];
v2df bcopy2[nh][kk];
v2df acopy[kk];
v2df acopy2[kk];
v2df awork[4];
v2df awork2[4];
double *acp = (double*) acopy;
double *acp2 = (double*) acopy2;
unsigned long bpcount, apcount, dotcount;
bpcount= apcount= dotcount=0;
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy2[j][k] = *((v2df*)(b[k]+j+j));
for(i=0;i<m;i+=2){
// BEGIN_TSC;
double *ap=a[i];
double *ap2=a[i+1];
register v2df tmp, tmp2;
v2df * cp = (v2df*) (&(c[i][0]));
v2df * cp2 = (v2df*) (&(c[i+1][0]));
v2df * aa = (v2df*)(ap);
__builtin_prefetch((double*)a[i+8],0,0);
__builtin_prefetch((double*)a[i+9],0,0);
acopy[0]=(v2df){a[i][0], a[i][0]};
acopy[1]=(v2df){a[i][1], a[i][1]};
acopy[2]=(v2df){a[i][2], a[i][2]};
acopy[3]=(v2df){a[i][3], a[i][3]};
acopy[4]=(v2df){a[i][4], a[i][4]};
acopy[5]=(v2df){a[i][5], a[i][5]};
acopy[6]=(v2df){a[i][6], a[i][6]};
acopy[7]=(v2df){a[i][7], a[i][7]};
aa = (v2df*)(ap2);
acopy2[0]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0);
acopy2[1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff);
aa++;
acopy2[2]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0);
acopy2[3]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff);
aa++;
acopy2[4]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0);
acopy2[5]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff);
aa++;
acopy2[6]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0);
acopy2[7]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff);
aa++;
for(j=0;j<nh;j++){
tmp = tmp2= (v2df){0.0,0.0};
v2df ctmp= cp[j];
v2df ctmp2 = cp2[j] ;
v2df * bp = bcopy2[j];
__builtin_prefetch(c[i+4]+j,1,0);
__builtin_prefetch(c[i+5]+j,1,0);
v2df *avp = acopy;
v2df *avp2 = acopy2;
v2df *bvp = bp;
tmp += avp[0]*bvp[0];
tmp2 += avp2[0]*bvp[0];
tmp +=avp[1]*bvp[1];
tmp2+=avp2[1]*bvp[1];
tmp +=avp[2]*bvp[2];
tmp2+=avp2[2]*bvp[2];
tmp +=avp[3]*bvp[3];
tmp2+=avp2[3]*bvp[3];
tmp += avp[4]*bvp[4];
tmp2 += avp2[4]*bvp[4];
tmp +=avp[5]*bvp[5];
tmp2+=avp2[5]*bvp[5];
tmp +=avp[6]*bvp[6];
tmp2+=avp2[6]*bvp[6];
tmp +=avp[7]*bvp[7];
tmp2+=avp2[7]*bvp[7];
cp[j] = ctmp -tmp;
cp2[j] = ctmp2 -tmp2;
}
}
// printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n,
// (double)bpcount, (double)apcount, (double)dotcount);
}
void matmul_for_nk8_1(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j,k;
const int kk = 8;
const int kh = kk/2;
int nh = n/2;
v2df bcopy[n][kh];
v2df acopy[kk][kh];
unsigned long bpcount, apcount, dotcount;
bpcount= apcount= dotcount=0;
for(j=0;j<n;j++)
for(k=0;k<kh;k++)
bcopy[j][k] = (v2df){b[k*2][j],b[k*2+1][j]};
// printf("copy b end\n");
for(i=0;i<m;i+=kk){
for(k=0;k<kk;k++){
v2df *ak = (v2df*)(a[i+k]);
v2df * awp =acopy+k;
awp[0]=ak[0];
awp[1]=ak[1];
awp[2]=ak[2];
awp[3]=ak[3];
}
// printf("copy a end\n");
for(k=0;k<kk;k++){
v2u tmp, tmp1;
v2df * ap = acopy[k];
for(j=0;j<n;j+=2){
tmp.v = ap[0]*bcopy[j][0]
+ ap[1]*bcopy[j][1]
+ ap[2]*bcopy[j][2]
+ ap[3]*bcopy[j][3];
tmp1.v = ap[0]*bcopy[j+1][0]
+ ap[1]*bcopy[j+1][1]
+ ap[2]*bcopy[j+1][2]
+ ap[3]*bcopy[j+1][3];
c[k+i][j] -= tmp.s[0]+tmp.s[1];
c[k+i][j+1] -= tmp1.s[0]+tmp1.s[1];
}
}
// printf("calc c end\n");
}
// printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n,
// (double)bpcount, (double)apcount, (double)dotcount);
}
void matmul_for_nk8_2(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j,k;
const int kk = 8;
const int kh = kk/2;
int nh = n/2;
v2df bcopy[nh][kk];
v2df acopy[kk][kh];
v2df ccopy[kk][kh];
v2df acopy2[kk][kk];
unsigned long bpcount, apcount, dotcount;
bpcount= apcount= dotcount=0;
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy[j][k] = *((v2df*)(b[k]+j+j));
// printf("copy b end\n");
for(i=0;i<m;i+=kk){
for(k=0;k<kk;k++){
__builtin_prefetch(a+i+k+8,0,0);
__builtin_prefetch(c+i+k+8,1,0);
v2df *ak = (v2df*)(a[i+k]);
v2df * awp = (v2df*)(acopy+k);
v2df *ck = (v2df*)(c[i+k]);
v2df * cwp = (v2df*)(ccopy+k);
awp[0]=ak[0];
awp[1]=ak[1];
awp[2]=ak[2];
awp[3]=ak[3];
cwp[0]=ck[0];
cwp[1]=ck[1];
cwp[2]=ck[2];
cwp[3]=ck[3];
}
for (j=0;j<n;j++){
double * ap = (double*)( acopy+j);
for (k=0;k<kk;k++){
acopy2[j][k]=(v2df){ap[k],ap[k]};
}
}
// printf("copy a end\n");
for(k=0;k<kk;k++){
v2df * cp = (v2df*) ccopy[k];
v2df * ap = acopy2[k];
for(j=0;j<nh;j++){
v2df * bp = bcopy[j];
cp[j] -= ap[0]*bp[0]
+ ap[1]*bp[1]
+ ap[2]*bp[2]
+ ap[3]*bp[3]
+ ap[4]*bp[4]
+ ap[5]*bp[5]
+ ap[6]*bp[6]
+ ap[7]*bp[7];
}
}
for(k=0;k<kk;k++){
v2df *ck = (v2df*)(c[i+k]);
v2df * cwp = (v2df*)(ccopy+k);
#if 0
ck[0] = cwp[0];
ck[1] = cwp[1];
ck[2] = cwp[2];
ck[3] = cwp[3];
#endif
__builtin_ia32_movntpd((double*)(ck),cwp[0]);
__builtin_ia32_movntpd((double*)(ck+1),cwp[1]);
__builtin_ia32_movntpd((double*)(ck+2),cwp[2]);
__builtin_ia32_movntpd((double*)(ck+3),cwp[3]);
}
// printf("calc c end\n");
}
// printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n,
// (double)bpcount, (double)apcount, (double)dotcount);
}
void matmul_for_nk8(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int i,j,k;
const int kk = 8;
const int kh = kk/2;
int nh = n/2;
v2df bcopy[nh][kk];
v2df acopy2[kk][kk];
// unsigned long bpcount, apcount, dotcount;
// bpcount= apcount= dotcount=0;
for(k=0;k<kk;k++)
for(j=0;j<nh;j++)
bcopy[j][k] = *((v2df*)(b[k]+j+j));
// END_TSC(bpcount);
// printf("copy b end\n");
#pragma omp parallel for private(i,j,k,acopy2) schedule(static)
for(i=0;i<m;i+=kk){
// BEGIN_TSC;
for(k=0;k<kk;k++){
__builtin_prefetch(a+i+k+16,0,0);
__builtin_prefetch(c+i+k+16,1,0);
}
for (j=0;j<n;j++){
double * ap = (double*)( a[i+j]);
for (k=0;k<kk;k++){
acopy2[j][k]=(v2df){ap[k],ap[k]};
}
}
// END_TSC(apcount);
// printf("copy a end\n");
// BEGIN_TSC;
for(k=0;k<kk;k++){
v2df * cp = (v2df*) (c[i+k]);
v2df * ap = acopy2[k];
for(j=0;j<nh;j++){
v2df * bp = bcopy[j];
cp[j] -= ap[0]*bp[0] + ap[1]*bp[1]
+ ap[2]*bp[2] + ap[3]*bp[3]
+ ap[4]*bp[4] + ap[5]*bp[5]
+ ap[6]*bp[6] + ap[7]*bp[7];
}
}
// printf("calc c end\n");
// END_TSC(dotcount);
}
// printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n,
// (double)bpcount, (double)apcount, (double)dotcount);
}
void matmul_for_nk16(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int ii;
int dm = (m+63)/64;
dm*= 16;
#pragma omp parallel for private(ii) schedule(static)
for(ii=0;ii<4;ii++){
int ifirst, iend;
ifirst = ii*dm;
iend = ifirst+dm;
if (iend > m) iend = m;
// fprintf(stderr, "m, i, ifirst, iend = %d %d %d %d\n", m, ii, ifirst, iend);
if (ifirst < m){
matmul_for_nk16_0a(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n);
}
}
}
void matmul_for_nk32(int n1, double a[][n1],
int n2, double b[][n2],
int n3, double c[][n3],
int m,
int n)
{
int ii;
int dm = (m+127)/128;
dm*= 32;
#pragma omp parallel for private(ii) schedule(static)
for(ii=0;ii<4;ii++){
int ifirst, iend;
ifirst = ii*dm;
iend = ifirst+dm;
if (iend > m) iend = m;
// fprintf(stderr, "m, i, ifirst, iend = %d %d %d %d\n", m, ii, ifirst, iend);
if (ifirst < m){
matmul_for_nk32_0(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n);
}
}
}
#ifndef USEGDR
void gdrsetforceswapab(){}
void gdrresetforceswapab(){}
void gdrsetskipsendjmat(){};
void gdrresetskipsendjmat(){}
void gdrsetnboards(){}
void set_matmul_msg_level(int level){}
#endif
#define N 1024
#define K 16
int main()
{
double a[N][K];
double c[N][K];
double b[K][K];
int i,j;
for(i=0;i<N;i++)
for(j=0;j<K;j++){
a[i][j] = i*j;
c[i][j] = 0;
}
for(i=0;i<K;i++)
for(j=0;j<K;j++)
b[i][j] = i*j;
int k;
unsigned long int start, end;
rdtscl(&start);
#define NT 5000
for(i=0;i<NT;i++){
matmul_for_nk16_test1(K, a, K, b, K, c, N, K);
}
rdtscl(&end);
printf("cycles = %e; %e ops/clock\n",
(double)(end-start), (N*K*K*(NT+0.0))/((double)(end-start)));
}
| {
"alphanum_fraction": 0.5203683418,
"avg_line_length": 21.6545589325,
"ext": "c",
"hexsha": "7d7d7b9fb10172eb495caf9f87536322499a71dc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-13T15:31:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-13T15:31:32.000Z",
"max_forks_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jmakino/lu2",
"max_forks_repo_path": "gemmtest.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf",
"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": "jmakino/lu2",
"max_issues_repo_path": "gemmtest.c",
"max_line_length": 79,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jmakino/lu2",
"max_stars_repo_path": "gemmtest.c",
"max_stars_repo_stars_event_max_datetime": "2020-05-04T05:00:16.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-07T09:18:43.000Z",
"num_tokens": 12868,
"size": 29212
} |
//This does CELL (~soma) stage of LSTM (long short-term memory) model.
//This requires each neuron to have 4 input time series, Xc, Xi, Xf, Xo,
//where Xc is the usual (or "cellular") input and Xi, Xf, Xo the inputs for the input, forget, output gates.
//Xc, Xi, Xf, Xo are the output of separate linear IN stages (weights and baises).
//For dim=0, C[:,t] = tanh{Xc[:,t] + Uc*Y[:,t-1]} \n";
// I[:,t] = sig{Xi[:,t] + Ui*Y[:,t-1]} \n";
// F[:,t] = sig{Xf[:,t] + Uf*Y[:,t-1]} \n";
// O[:,t] = sig{Xo[:,t] + Uo*Y[:,t-1]} \n";
// H[:,t] = I[:,t].*C[:,t] + F[:,t].*H[:,t-1] \n";
// Y[:,t] = O[:,t].*tanh{H[:,t]} \n";
//with sizes Xc, Xi, Xf, Xo: N x T \n";
// Uc, Ui, Uf, Uo: N x N \n";
// Y : N x T \n";
//
//For dim=1, C[t,:] = tanh{Xc[t,:] + Y[t-1,:]*Uc} \n";
// I[t,:] = sig{Xi[t,:] + Y[t-1,:]*Ui} \n";
// F[t,:] = sig{Xf[t,:] + Y[t-1,:]*Uf} \n";
// O[t,:] = sig{Xo[t,:] + Y[t-1,:]*Uo} \n";
// H[t,:] = I[t,:].*C[t,:] + F[t,:].*H[t-1,:] \n";
// Y[t,:] = O[t,:].*tanh{H[t,:]} \n";
//with sizes Xc, Xi, Xf, Xo: T x N \n";
// Uc, Ui, Uf, Uo: N x N \n";
// Y : T x N \n";
//
//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),
//I is the input gate, F is the forget gate, O is the output gate,
//C is the "cell input activation vector",
//H is an intermediate (hidden) vector (sometimes called the "cell state vector"),
//Uc, Ui, Uf, Uo are NxN matrices, and Y is the final output (sometimes called the "hidden state vector").
//Note that, the neurons of a layer are independent only if Uc, Ui, Uf, Uo are diagonal matrices.
//This is only really a CELL (~soma) stage in that case.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#ifdef I
#undef I
#endif
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int lstm4_s (float *Y, const float *Xc, const float *Xi, const float *Xf, const float *Xo, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm4_d (double *Y, const double *Xc, const double *Xi, const double *Xf, const double *Xo, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm4_inplace_s (float *Xc, const float *Xi, const float *Xf, const float *Xo, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm4_inplace_d (double *Xc, const double *Xi, const double *Xf, const double *Xo, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm4_s (float *Y, const float *Xc, const float *Xi, const float *Xf, const float *Xo, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
size_t nT, tN;
float *C, *I, *F, *O, *H;
if (!(C=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_s: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
//C[0] = tanhf(Xc[0]);
//I[0] = 1.0f / (1.0f+expf(-Xi[0]));
//F[0] = 1.0f / (1.0f+expf(-Xf[0]));
//O[0] = 1.0f / (1.0f+expf(-Xo[0]));
//H[0] = I[0] * C[0];
//Y[0] = O[0] * tanhf(H[0]);
H[0] = tanhf(Xc[0]) / (1.0f+expf(-Xi[0]));
Y[0] = tanhf(H[0]) / (1.0f+expf(-Xo[0]));
for (size_t t=1; t<T; ++t)
{
//C[0] = tanhf(Xc[t]+Uc[0]*Y[t-1]);
//I[0] = 1.0f / (1.0f+expf(-Xi[t]-Ui[0]*Y[t-1]));
//F[0] = 1.0f / (1.0f+expf(-Xf[t]-Uf[0]*Y[t-1]));
//O[0] = 1.0f / (1.0f+expf(-Xo[t]-Uo[0]*Y[t-1]));
//H[0] = I[0]*C[0] + F[0]*H[0];
//Y[t] = O[0] * tanhf(H[0]);
H[0] = tanhf(Xc[t]+Uc[0]*Y[t-1])/(1.0f+expf(-Xi[t]-Ui[0]*Y[t-1])) + H[0]/(1.0f+expf(-Xf[t]-Uf[0]*Y[t-1]));
Y[t] = tanhf(H[0]) / (1.0f+expf(-Xo[t]-Uo[0]*Y[t-1]));
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
//C[n] = tanhf(Xc[n]);
//I[n] = 1.0f / (1.0f+expf(-Xi[n]));
//F[n] = 1.0f / (1.0f+expf(-Xf[n]));
//O[n] = 1.0f / (1.0f+expf(-Xo[n]));
//H[n] = I[n] * C[n];
//Y[n] = O[n] * tanhf(H[n]);
H[n] = tanhf(Xc[n]) / (1.0f+expf(-Xi[n]));
Y[n] = tanhf(H[n]) / (1.0f+expf(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xc[tN],1,C,1); cblas_scopy((int)N,&Xi[tN],1,I,1);
cblas_scopy((int)N,&Xf[tN],1,F,1); cblas_scopy((int)N,&Xo[tN],1,O,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
//C[n] = tanhf(C[n]);
//I[n] = 1.0f / (1.0f+expf(-I[n]));
//F[n] = 1.0f / (1.0f+expf(-F[n]));
//O[n] = 1.0f / (1.0f+expf(-O[n]));
//H[n] = I[n]*C[n] + F[n]*H[n];
//Y[tN+n] = O[n] * tanhf(H[n]);
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Y[tN+n] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
//C[n] = tanhf(Xc[nT])
//I[n] = 1.0f / (1.0f+expf(-Xi[nT]));
//F[n] = 1.0f / (1.0f+expf(-Xf[nT]));
//O[n] = 1.0f / (1.0f+expf(-Xo[nT]));
//H[n] = I[n] * C[n];
//Y[nT] = O[n] * tanhf(H[n]);
H[n] = tanhf(Xc[nT]) / (1.0f+expf(-Xi[nT]));
Y[nT] = tanhf(H[n]) / (1.0f+expf(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xc[t],(int)T,C,1); cblas_scopy((int)N,&Xi[t],(int)T,I,1);
cblas_scopy((int)N,&Xf[t],(int)T,F,1); cblas_scopy((int)N,&Xo[t],(int)T,O,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
//C[n] = tanhf(C[n]);
//I[n] = 1.0f / (1.0f+expf(-I[n]));
//F[n] = 1.0f / (1.0f+expf(-F[n]));
//O[n] = 1.0f / (1.0f+expf(-O[n]));
//H[n] = I[n]*C[n] + F[n]*H[n];
//Y[t+n*T] = O[n] * tanhf(H[n]);
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Y[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
H[n] = tanhf(Xc[nT]) / (1.0f+expf(-Xi[nT]));
Y[nT] = tanhf(H[n]) / (1.0f+expf(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xc[t],(int)T,C,1); cblas_scopy((int)N,&Xi[t],(int)T,I,1);
cblas_scopy((int)N,&Xf[t],(int)T,F,1); cblas_scopy((int)N,&Xo[t],(int)T,O,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Y[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(Xc[n]) / (1.0f+expf(-Xi[n]));
Y[n] = tanhf(H[n]) / (1.0f+expf(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xc[tN],1,C,1); cblas_scopy((int)N,&Xi[tN],1,I,1);
cblas_scopy((int)N,&Xf[tN],1,F,1); cblas_scopy((int)N,&Xo[tN],1,O,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Y[tN+n] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm4_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int lstm4_d (double *Y, const double *Xc, const double *Xi, const double *Xf, const double *Xo, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
size_t nT, tN;
double *C, *I, *F, *O, *H;
if (!(C=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_d: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
H[0] = tanh(Xc[0]) / (1.0+exp(-Xi[0]));
Y[0] = tanh(H[0]) / (1.0+exp(-Xo[0]));
for (size_t t=1; t<T; ++t)
{
H[0] = tanh(Xc[t]+Uc[0]*Y[t-1])/(1.0+exp(-Xi[t]-Ui[0]*Y[t-1])) + H[0]/(1.0+exp(-Xf[t]-Uf[0]*Y[t-1]));
Y[t] = tanh(H[0]) / (1.0+exp(-Xo[t]-Uo[0]*Y[t-1]));
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(Xc[n]) / (1.0+exp(-Xi[n]));
Y[n] = tanh(H[n]) / (1.0+exp(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xc[tN],1,C,1); cblas_dcopy((int)N,&Xi[tN],1,I,1);
cblas_dcopy((int)N,&Xf[tN],1,F,1); cblas_dcopy((int)N,&Xo[tN],1,O,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Y[tN+n] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
H[n] = tanh(Xc[nT]) / (1.0+exp(-Xi[nT]));
Y[nT] = tanh(H[n]) / (1.0+exp(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xc[t],(int)T,C,1); cblas_dcopy((int)N,&Xi[t],(int)T,I,1);
cblas_dcopy((int)N,&Xf[t],(int)T,F,1); cblas_dcopy((int)N,&Xo[t],(int)T,O,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Y[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
H[n] = tanh(Xc[nT]) / (1.0+exp(-Xi[nT]));
Y[nT] = tanh(H[n]) / (1.0+exp(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xc[t],(int)T,C,1); cblas_dcopy((int)N,&Xi[t],(int)T,I,1);
cblas_dcopy((int)N,&Xf[t],(int)T,F,1); cblas_dcopy((int)N,&Xo[t],(int)T,O,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Y[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(Xc[n]) / (1.0+exp(-Xi[n]));
Y[n] = tanh(H[n]) / (1.0+exp(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xc[tN],1,C,1); cblas_dcopy((int)N,&Xi[tN],1,I,1);
cblas_dcopy((int)N,&Xf[tN],1,F,1); cblas_dcopy((int)N,&Xo[tN],1,O,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Y[tN+n] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm4_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int lstm4_inplace_s (float *Xc, const float *Xi, const float *Xf, const float *Xo, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
size_t nT, tN;
float *C, *I, *F, *O, *H;
if (!(C=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm4_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
H[0] = tanhf(Xc[0]) / (1.0f+expf(-Xi[0]));
Xc[0] = tanhf(H[0]) / (1.0f+expf(-Xo[0]));
for (size_t t=1; t<T; ++t)
{
H[0] = tanhf(Xc[t]+Uc[0]*Xc[t-1])/(1.0f+expf(-Xi[t]-Ui[0]*Xc[t-1])) + H[0]/(1.0f+expf(-Xf[t]-Uf[0]*Xc[t-1]));
Xc[t] = tanhf(H[0]) / (1.0f+expf(-Xo[t]-Uo[0]*Xc[t-1]));
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(Xc[n]) / (1.0f+expf(-Xi[n]));
Xc[n] = tanhf(H[n]) / (1.0f+expf(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xc[tN],1,C,1); cblas_scopy((int)N,&Xi[tN],1,I,1);
cblas_scopy((int)N,&Xf[tN],1,F,1); cblas_scopy((int)N,&Xo[tN],1,O,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[tN-N],1,o,C,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[tN-N],1,o,I,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[tN-N],1,o,F,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Xc[tN+n] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
H[n] = tanhf(Xc[nT]) / (1.0f+expf(-Xi[nT]));
Xc[nT] = tanhf(H[n]) / (1.0f+expf(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xc[t],(int)T,C,1); cblas_scopy((int)N,&Xi[t],(int)T,I,1);
cblas_scopy((int)N,&Xf[t],(int)T,F,1); cblas_scopy((int)N,&Xo[t],(int)T,O,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[t-1],(int)T,o,C,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[t-1],(int)T,o,I,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[t-1],(int)T,o,F,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Xc[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
H[n] = tanhf(Xc[nT]) / (1.0f+expf(-Xi[nT]));
Xc[nT] = tanhf(H[n]) / (1.0f+expf(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xc[t],(int)T,C,1); cblas_scopy((int)N,&Xi[t],(int)T,I,1);
cblas_scopy((int)N,&Xf[t],(int)T,F,1); cblas_scopy((int)N,&Xo[t],(int)T,O,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[t-1],(int)T,o,C,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[t-1],(int)T,o,I,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[t-1],(int)T,o,F,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Xc[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(Xc[n]) / (1.0f+expf(-Xi[n]));
Xc[n] = tanhf(H[n]) / (1.0f+expf(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xc[tN],1,C,1); cblas_scopy((int)N,&Xi[tN],1,I,1);
cblas_scopy((int)N,&Xf[tN],1,F,1); cblas_scopy((int)N,&Xo[tN],1,O,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[tN-N],1,o,C,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[tN-N],1,o,I,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[tN-N],1,o,F,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n]));
Xc[tN+n] = tanhf(H[n]) / (1.0f+expf(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm4_inplace_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int lstm4_inplace_d (double *Xc, const double *Xi, const double *Xf, const double *Xo, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
size_t nT, tN;
double *C, *I, *F, *O, *H;
if (!(C=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm4_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
H[0] = tanh(Xc[0]) / (1.0+exp(-Xi[0]));
Xc[0] = tanh(H[0]) / (1.0+exp(-Xo[0]));
for (size_t t=1; t<T; ++t)
{
H[0] = tanh(Xc[t]+Uc[0]*Xc[t-1])/(1.0+exp(-Xi[t]-Ui[0]*Xc[t-1])) + H[0]/(1.0+exp(-Xf[t]-Uf[0]*Xc[t-1]));
Xc[t] = tanh(H[0]) / (1.0+exp(-Xo[t]-Uo[0]*Xc[t-1]));
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(Xc[n]) / (1.0+exp(-Xi[n]));
Xc[n] = tanh(H[n]) / (1.0+exp(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xc[tN],1,C,1); cblas_dcopy((int)N,&Xi[tN],1,I,1);
cblas_dcopy((int)N,&Xf[tN],1,F,1); cblas_dcopy((int)N,&Xo[tN],1,O,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[tN-N],1,o,C,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[tN-N],1,o,I,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[tN-N],1,o,F,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Xc[tN+n] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
H[n] = tanh(Xc[nT]) / (1.0+exp(-Xi[nT]));
Xc[nT] = tanh(H[n]) / (1.0+exp(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xc[t],(int)T,C,1); cblas_dcopy((int)N,&Xi[t],(int)T,I,1);
cblas_dcopy((int)N,&Xf[t],(int)T,F,1); cblas_dcopy((int)N,&Xo[t],(int)T,O,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[t-1],(int)T,o,C,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[t-1],(int)T,o,I,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[t-1],(int)T,o,F,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Xc[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
H[n] = tanh(Xc[nT]) / (1.0+exp(-Xi[nT]));
Xc[nT] = tanh(H[n]) / (1.0+exp(-Xo[nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xc[t],(int)T,C,1); cblas_dcopy((int)N,&Xi[t],(int)T,I,1);
cblas_dcopy((int)N,&Xf[t],(int)T,F,1); cblas_dcopy((int)N,&Xo[t],(int)T,O,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[t-1],(int)T,o,C,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[t-1],(int)T,o,I,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[t-1],(int)T,o,F,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[t-1],(int)T,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Xc[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(Xc[n]) / (1.0+exp(-Xi[n]));
Xc[n] = tanh(H[n]) / (1.0+exp(-Xo[n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xc[tN],1,C,1); cblas_dcopy((int)N,&Xi[tN],1,I,1);
cblas_dcopy((int)N,&Xf[tN],1,F,1); cblas_dcopy((int)N,&Xo[tN],1,O,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Xc[tN-N],1,o,C,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Xc[tN-N],1,o,I,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Xc[tN-N],1,o,F,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Xc[tN-N],1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n]));
Xc[tN+n] = tanh(H[n]) / (1.0+exp(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm4_inplace_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4562564633,
"avg_line_length": 47.3246329527,
"ext": "c",
"hexsha": "39f8e0cf75a1ca866ec87380caca6679ed13e2e5",
"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": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/nn",
"max_forks_repo_path": "c/lstm4.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"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/nn",
"max_issues_repo_path": "c/lstm4.c",
"max_line_length": 241,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/nn",
"max_stars_repo_path": "c/lstm4.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z",
"num_tokens": 10947,
"size": 29010
} |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#define DEBUG
#ifndef DEBUG
#define IN 64
#define OUT 32
#define NUM_ITS 1000000
#else
#define IN 4
#define OUT 2
#define NUM_ITS 1
#endif
#define INIT_VAL 0.4711
#ifdef USE_BLAS
#include <cblas.h>
#endif
double *
mtrx(int rows, int cols) {
int row, col;
double *d, *it;
d = (double *) malloc(rows * cols * sizeof(double));
it = d;
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
// Not very random, but makes debugging easier.
*it = INIT_VAL;
it++;
}
}
return d;
}
void
forward(const int rows, const int cols, double *W, double *x,
double *a) {
#ifndef USE_BLAS
int row, col;
double *W_it, *x_it, *a_it;
W_it = W;
a_it = a;
for (row = 0; row < rows; row++) {
*a_it = 0.0;
x_it = x;
for (col = 0; col < cols; col++) {
*a_it += *W_it * *x_it;
W_it++;
x_it++;
}
*a_it = tanh(*a_it);
a_it++;
}
#else /* USE_BLAS */
int row;
cblas_dgemv(CblasColMajor, CblasNoTrans, rows, cols, 1.0, W, rows, x, 1,
0.0, a, 1);
for (row = 0; row < rows; row++) {
a[row] = tanh(a[row]);
}
#endif /* USE_BLAS */
}
void
backward(const int rows, const int cols, double *x, double *a, double *d,
double *b) {
#ifndef USE_BLAS
int row, col;
double ad;
double *x_it, *a_it, *d_it, *b_it;
a_it = a;
d_it = d;
b_it = b;
for (row = 0; row < rows; row++) {
ad = (1.0 - pow(*a_it, 2)) * *d_it;
x_it = x;
for (col = 0; col < cols; col++) {
*b_it = ad * *x_it;
b_it++;
x_it++;
}
a_it++;
d_it++;
}
#else /* USE_BLAS */
int row;
double *tmp;
tmp = (double *) malloc(rows * sizeof(double));
for (row = 0; row < rows; row++) {
tmp[row] = (1.0 - pow(a[row], 2)) * d[row];
}
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, rows, cols, 1, 1.0,
tmp, 1, x, 1, 0.0, b, rows);
free(tmp);
#endif /* USE_BLAS */
}
int
main() {
int i;
double *W, *x, *d, *a, *b;
struct timespec tic, toc;
W = mtrx(OUT, IN);
x = mtrx(IN, 1);
d = mtrx(OUT, 1);
a = malloc(OUT * sizeof(double));
b = malloc(OUT * IN * sizeof(double));
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tic);
for (i = 0; i < NUM_ITS; i++) {
forward(OUT, IN, W, x, a);
backward(OUT, IN, x, a, d, b);
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &toc);
#ifdef DEBUG
for (int j = 0; j < OUT; j++) {
printf("%f ", a[j]);
}
printf("\n");
double *b_it = b;
for (int u = 0; u < OUT; u++) {
for (int v = 0; v < IN; v++) {
printf("%f ", *b_it);
b_it++;
}
printf("\n");
}
#endif
printf("%f\n", (toc.tv_nsec - tic.tv_nsec) / 100000000.0);
free(b);
free(a);
free(d);
free(x);
free(W);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.4796929965,
"avg_line_length": 20.5723684211,
"ext": "c",
"hexsha": "7345bd7037abdc8fb2383a77b55eb799349bc1df",
"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": "0687213243f11390e18250a7a7476eb0bc3cd7ed",
"max_forks_repo_licenses": [
"0BSD"
],
"max_forks_repo_name": "ninjin/ppod",
"max_forks_repo_path": "hck/rnn_perf/rnn_perf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0687213243f11390e18250a7a7476eb0bc3cd7ed",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"0BSD"
],
"max_issues_repo_name": "ninjin/ppod",
"max_issues_repo_path": "hck/rnn_perf/rnn_perf.c",
"max_line_length": 76,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "0687213243f11390e18250a7a7476eb0bc3cd7ed",
"max_stars_repo_licenses": [
"0BSD"
],
"max_stars_repo_name": "ninjin/ppod",
"max_stars_repo_path": "hck/rnn_perf/rnn_perf.c",
"max_stars_repo_stars_event_max_datetime": "2016-04-19T01:12:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-27T14:05:13.000Z",
"num_tokens": 1050,
"size": 3127
} |
#ifndef SCOL_H
#define SCOL_H
#include "Common.h"
// SP_IVP.h
// Spherical Collapse IVP
//#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <cvode/cvode.h> /* prototypes for CVODE fcts., consts. */
#include <nvector/nvector_serial.h> /* access to serial N_Vector */
#include <sunmatrix/sunmatrix_dense.h> /* access to dense SUNMatrix */
#include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver */
#include <cvode/cvode_direct.h> /* access to CVDls interface */
#include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */
#include <sundials/sundials_math.h> /* contains the macros ABS, SUNSQR, EXP */
#define Ith(v,i) NV_Ith_S(v,i-1) /* Ith numbers components 1..NEQ */
#define IJth(A,i,j) SM_ELEMENT_D(A,i-1,j-1) /* IJth numbers rows,cols 1..NEQ */
#define NEQ 2 /* number of equations */
#define Y1 RCONST(0.0) /* initial y components */
#define RTOL RCONST(1.0e-5) /* scalar relative tolerance */
#define ATOL1 RCONST(1.0e-11) /* vector absolute tolerance components */
#define ATOL2 RCONST(1.0e-11)
#define T00 RCONST(-10.41431317630211772495840705232694745063781738281250) /* initial time */
#define NOUT 1024 /* number of output times */
#define NOUT_DC 10 /* number of output times */
#define HALF RCONST(0.5) /* 0.5 */
#define ONE RCONST(1.0) /* 1.0 */
#define TWO RCONST(2.0)
#define THREE RCONST(3.0) /* 3.0 */
#define DELTA1 RCONST(3e-5) /* Delta_i1 */
#define DELTA2 RCONST(0.00012) /* Delta_i2 */
#define EPSILON RCONST(1.0e-9)
#define ZERO RCONST(0.0)
#define NINE RCONST(9.0)
#define TEN RCONST(10.0)
#define Gnewton RCONST(4.302e-09)
#define coef RCONST(8987404.41) // 1/H0^2
// structures to store spherical collapse calculations
typedef struct arrays{
int count;
double xx[1002];
double yy[1002]; } *arrays_T;
typedef struct arrays3D{
int count;
double xx[1002];
double yy[1002];
double zz[1002]; } *arrays_T3;
typedef struct usdat {
realtype IC;
realtype OM;
realtype Rth;
realtype T1;
double par1;
double par2;
double par3;
int mymg;
double maxt;
gsl_spline *spline;
gsl_interp_accel *acc;
} *UserData;
extern int check_flagscol(void *flagvalue, const char *funcname, int opt); //
class SCOL {
public:
// used functions in example file
double maxP_zeta(double sig2, double dsig2dR, double OM, double Z);
double Delta_Lambda(double OM, double Z); //
// solves for y_enviornment
int yenv(double OM_REAL, double XF, double delta_envi, arrays_T xxyy); // gives the environmental dependence of spherical collapse
// solves for y_halo
int SphericalCollapse(double *dC, arrays_T3 xxyyzz, UserData data_vec, double TMULT_REAL, double delta_g); // spherical collapse solver
// solves for a_virial
double myscol(double myscolparams[], double acol, double omega0, double Rthp, double sig1, double sig2, double pars[], int mymg, int yenvf); // solves for virial quantities and stores them in array myscolparams
void PrintOutput(realtype t, realtype y1, realtype y2);
void PrintRootInfo(int root_f1); //
double funcscol(double xi, void *user_data); //
};
#endif
| {
"alphanum_fraction": 0.6591422122,
"avg_line_length": 34.4077669903,
"ext": "h",
"hexsha": "e76371f440afb43eba7b66abaae0969a7df34cdf",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-08-31T15:35:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-08-31T15:35:28.000Z",
"max_forks_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "PedroCarrilho/ReACT",
"max_forks_repo_path": "reactions/src/SCOL.h",
"max_issues_count": 11,
"max_issues_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50",
"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": [
"MIT"
],
"max_issues_repo_name": "PedroCarrilho/ReACT",
"max_issues_repo_path": "reactions/src/SCOL.h",
"max_line_length": 213,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PedroCarrilho/ReACT",
"max_stars_repo_path": "reactions/src/SCOL.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-15T12:48:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-07T11:34:02.000Z",
"num_tokens": 1038,
"size": 3544
} |
/* interpolation/accel.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_interp.h>
gsl_interp_accel *
gsl_interp_accel_alloc (void)
{
gsl_interp_accel *a = (gsl_interp_accel *) malloc (sizeof (gsl_interp_accel));
if (a == 0)
{
GSL_ERROR_NULL("could not allocate space for gsl_interp_accel", GSL_ENOMEM);
}
a->cache = 0;
a->hit_count = 0;
a->miss_count = 0;
return a;
}
int
gsl_interp_accel_reset (gsl_interp_accel * a)
{
a->cache = 0;
a->hit_count = 0;
a->miss_count = 0;
return GSL_SUCCESS;
}
#ifndef HIDE_INLINE_STATIC
size_t
gsl_interp_accel_find (gsl_interp_accel * a, const double xa[], size_t len, double x)
{
size_t x_index = a->cache;
if (x < xa[x_index])
{
a->miss_count++;
a->cache = gsl_interp_bsearch (xa, x, 0, x_index);
}
else if (x > xa[x_index + 1])
{
a->miss_count++;
a->cache = gsl_interp_bsearch (xa, x, x_index, len - 1);
}
else
{
a->hit_count++;
}
return a->cache;
}
#endif
void
gsl_interp_accel_free (gsl_interp_accel * a)
{
free (a);
}
| {
"alphanum_fraction": 0.6765316719,
"avg_line_length": 23.2048192771,
"ext": "c",
"hexsha": "72d9345971c111ef580c8e3d60e68b1e930ed9c7",
"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/interpolation/accel.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/interpolation/accel.c",
"max_line_length": 85,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/interpolation/accel.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": 558,
"size": 1926
} |
#include<stdio.h>
#include<sys/time.h>
#include <stdlib.h>
#include <cblas.h>
#include "LibShalom.h"
static double gtod_ref_time_sec = 0.0;
double dclock()
{
double the_time, norm_sec;
struct timeval tv;
gettimeofday( &tv, NULL );
if ( gtod_ref_time_sec == 0.0 )
gtod_ref_time_sec = ( double ) tv.tv_sec;
norm_sec = ( double ) tv.tv_sec - gtod_ref_time_sec;
the_time = norm_sec + tv.tv_usec * 1.0e-6;
return the_time;
}
void random_matrix( int m, int n, float *a)
{
double drand48();
int i,j;
for ( i=0; i<m; i++ )
for ( j=0; j<n; j++ )
a[i*n+j]= 2.0 * (float)drand48( ) - 1.0 ;
}
void random_matrix1( int m, int n, float *a)
{
double drand48();
int i,j;
for ( i=0; i<m; i++ )
for ( j=0; j<n; j++ )
a[i*n+j]= 1.0 ;
}
void transpose( int m, int n, float *a)
{
float *temp_a = ( float * ) malloc( m* n * sizeof( float ) );
int i, j;
for( i =0 ;i< m; i++)
{
for( j= 0;j < n; j++)
{
temp_a[j * m + i] = a[i*n + j];
}
}
for( i =0 ; i< n; i++)
{
for( j =0; j< m; j++)
{
a[ i * m+j] = temp_a[i*m+j];
}
}
}
int main()
{
LibShalom_set_thread_nums(64);
int i,j,k;
int loop= 5 ;
long M, N, K;
float *C1;
double start, cost;
double gflops;
int flag =0 ;
char transa = 'N', transb = 'N';
int pc;
FILE *fp;
if( (fp=fopen("NSMM_small.txt","w")) == NULL )
{
puts("Fail to open file!");
exit(0);
}
for( j =8; j < 9; j = j + 8)
{
M = 256 ;
N = 4096;
K = 5000;
//M= N = K = j;
double ops = M *N *K * 1.0e-09 * 2;
fprintf(fp, "%d %d %d", M,N,K);
for(pc =0 ;pc < 1; pc++)
{
int flag =0 ;
int lda = K;
int ldb = K;
int ldc = N;
float *A = ( float * ) malloc( K* M * sizeof( float ) );
float *B = ( float * ) malloc( K* N * sizeof( float ) );
float *C = ( float * ) malloc( M* N * sizeof( float ) );
float *C1 = ( float * ) malloc( M* N * sizeof( float ) );
float *SB= ( float * ) malloc( K* N * sizeof( float ) );
random_matrix(M,K,A);
random_matrix(K,N,B);
transpose(K, N, B);
for( i =0 ;i< 2; i++)
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, M, N, K, 1.0, A, lda, B, ldb, 0.0, C1, ldc);
start = dclock();
for(i= 0; i<loop ;i++)
{
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, M, N, K, 1.0, A, lda, B, ldb, 0.0, C1, ldc);
}
for( i =0 ;i< 5; i++)
LibShalom_sgemm_mp(NoTrans, Trans, C, A, B, M, N, K);
start = dclock();
for( i= 0; i< loop ;i++)
LibShalom_sgemm_mp(NoTrans, Trans, C, A, B, M, N, K);
cost =(dclock()-start)/loop;
ops = M * N * K * 1.0e-09 * 2;
printf("N_SMM: M= %d N=%d K=%d flops = %lf effic= %.3lf %\n", M, N, K,
ops/cost, ops/cost/17.6 * 100/ 64);
fprintf(fp, " %.3f", ops/cost);
for( i= 0; i< M; i++)
{
for( j= 0 ;j<N;j++)
{
if((C[i*N+j]- C1[i*N+j] > 0.0001 || C[i*N+j]- C1[i*N+j] < -0.0001) )
{
printf("i = %d, j= %d\n",i ,j );
printf("C= %lf , C1= %lf\n", C[i*N+j], C1[i*N+j]);
flag =1;
printf("error\n");
break;
}
}
if(flag ==1)
break;
}
if(flag == 0)
printf("结果正确\n");
free(A);
free(B);
free(C);
free(SB);
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
/*
int main()
{
LibShalom_thread_nums(32);
// printf("%d\n", vec.size());
int i,j,k;
int loop= 100 ;
long M, N, K;
float *C1;
double start, cost;
double gflops;
int flag =0 ;
char transa = 'N', transb = 'N';
int pc;
FILE *fp;
long Me[5]={5,13,13,23,26},
Ne[5]={5,5,13,23,26},
Ke[5]={5,13,13,23,13};
if( (fp=fopen("NSMM_small.txt","w")) == NULL )
{
puts("Fail to open file!");
exit(0);
}
for( j = 0; j < 5; j++)
{
M = Me[j];
N = Ne[j];
K = Ke[j];
//M= N = K = j;
double ops = M *N *K * 1.0e-09 * 2;
fprintf(fp, "%d %d %d", M,N,K);
for(pc =0 ;pc < 5; pc++)
{
double *A = ( double * ) malloc( K* M * sizeof( double ) );
double *B = ( double * ) malloc( K* N * sizeof( double ) );
double *C = ( double * ) malloc( M* N * sizeof( double ) );
double *SB= ( double * ) malloc( K* N * sizeof( double ) );
for( i =0 ;i< 5; i++)
LibShalom_dgemm(NoTrans, NoTrans, C, A, B, M, N, K);
start = dclock();
for( i= 0; i< loop ;i++)
LibShalom_dgemm(NoTrans, NoTrans, C, A, B, M, N, K);
cost =(dclock()-start)/loop;
ops = M * N * K * 1.0e-09 * 2;
printf("N_SMM: M= %d N=%d K=%d flops = %lf effic= %.3lf %\n", M, N, K,
ops/cost, ops/cost/8.8 * 100);
fprintf(fp, " %.3f", ops/cost);
free(A);
free(B);
free(C);
free(SB);
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
*/ | {
"alphanum_fraction": 0.4725433526,
"avg_line_length": 18.4182509506,
"ext": "c",
"hexsha": "d9fe6942102e7e6b4b185451c1ba9c1c97270132",
"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/benchmark.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/benchmark.c",
"max_line_length": 105,
"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/benchmark.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": 1885,
"size": 4844
} |
#ifndef DATA_STRUCTURES_LINKED_LIST_SINGLY_LINKED_LIST_WITH_TAIL_H_INCLUDED
#define DATA_STRUCTURES_LINKED_LIST_SINGLY_LINKED_LIST_WITH_TAIL_H_INCLUDED
#include <gsl/gsl>
#include <iostream>
#include <memory>
#include <utility>
#include <stdexcept>
namespace datastructures {
template <typename T>
struct Node {
T value;
Node* next;
};
template <typename T>
class LinkedListWithTail {
private:
datastructures::Node<T>* head_;
datastructures::Node<T>* tail_;
size_t size_;
public:
LinkedListWithTail() :
head_(nullptr),
size_(0) {}
~LinkedListWithTail() {
if (head_ != nullptr) {
while (head_->next != nullptr) {
datastructures::Node<T>* tmp = head_;
head_ = head_->next;
delete tmp;
}
delete head_;
head_ = nullptr;
tail_ = nullptr;
size_ = 0;
}
}
LinkedListWithTail<T>(const LinkedListWithTail<T>& other) {
datastructures::Node<T>* current = other.head_;
datastructures::Node<T>* newNode = new datastructures::Node<T>();
head_ = newNode;
tail_ = newNode;
size_ = other.size();
while (current != nullptr) {
newNode->value = current->value;
newNode->next = new datastructures::Node<T>();
newNode = newNode->next;
current = current->next;
tail_ = current;
}
}
// assignment operator
LinkedListWithTail<T>& operator=(const LinkedListWithTail<T>& rhs) {
if (this != &rhs) {
auto tmp(rhs);
std::swap(head_, tmp.head_);
std::swap(tail_, tmp.tail_);
std::swap(size_, tmp.size_);
}
return *this;
}
void push_back(const T& value) {
if (head_ == nullptr) {
head_ = tail_ = new datastructures::Node<T>();
head_->value = value;
size_++;
return;
}
tail_->next = new datastructures::Node<T>();
tail_->next->value = value;
tail_ = tail_->next;
size_++;
}
T pop_back() {
if (head_ == nullptr) {
throw std::out_of_range("head is null");
}
// we need a previous pointer to make it point to nullptr
datastructures::Node<T>* current = head_;
datastructures::Node<T>* previous = head_;
while (current->next != nullptr) {
previous = current;
current = current->next;
}
previous->next = nullptr;
tail_ = previous;
// store return value, because we are going to delete this node
T tmp = current->value;
// update size
--size_;
// if we do not have nodes, update head pointer
if (size_ == 0) {
head_ = nullptr;
tail_ = nullptr;
}
// delete last node
delete current;
// return value
return tmp;
}
T back() const {
if (head_ == nullptr) {
throw std::out_of_range("head is null");
}
return tail_->value;
}
T front() const {
if (head_ == nullptr) {
throw std::out_of_range("head is null");
}
return head_->value;
}
void insert(unsigned int index, const T& value) {
if (index > size_) {
throw std::out_of_range("index out of bounds");
}
// handle head_
if (index == 0) {
datastructures::Node<T>* newNode =
new datastructures::Node<T>();
newNode->value = value;
newNode->next = head_;
// handle the case where the list is empty
if (head_ == nullptr) {
tail_ = newNode;
}
// update head
head_ = newNode;
size_++;
return;
}
// handle middle index
datastructures::Node<T>* current = head_;
for (int i = 0; i < index - 1; i++) {
current = current->next;
}
datastructures::Node<T>* after = current->next;
current->next = new datastructures::Node<T>();
current->next->value = value;
current->next->next = after;
// handle last node
if (after == nullptr) {
tail_ = current->next;
}
size_++;
}
void push_front(const T& value) {
if (head_ == nullptr) {
head_ = new datastructures::Node<T>();
if (!head_) {
throw "out of memory";
}
head_->value = value;
tail_ = head_;
size_++;
return;
}
datastructures::Node<T>* newNode = new datastructures::Node<T>();
newNode->value = value;
newNode->next = head_;
head_ = newNode;
size_++;
}
T pop_front() {
if (head_ == nullptr) {
throw std::out_of_range("head is null");
}
datastructures::Node<T> *tmp = head_;
T tmpValue = head_->value;
head_ = head_->next;
--size_;
if (head_ == nullptr) {
tail_ == nullptr;
}
delete tmp;
return tmpValue;
}
T& value_at(int index) {
if (index >= size_) {
throw "index out of bounds";
}
if (index == 0) {
return head_->value;
}
datastructures::Node<T>* current = head_;
for (int i = 0; i < index; i++) {
if (current->next == nullptr) {
throw "out of range";
}
current = current->next;
}
return current->value;
}
void erase(unsigned int index) {
if (index > size_) {
throw std::out_of_range("index out of bounds");
}
datastructures::Node<T>* current = head_;
datastructures::Node<T>* previous = current;
// handle TAIL
if (index == size_) {
while (current->next != nullptr) {
previous = current;
current = current->next;
if (current->next == nullptr) {
previous->next = nullptr;
size_--;
delete current;
tail_ = previous;
return;
}
}
}
// handle head_
if (index == 0) {
head_ = head_->next;
delete current;
size_--;
return;
}
// handle middle nodes
for (int i = 0; i < index - 1; i++) {
current = current->next;
}
current->next = current->next->next;
size_--;
}
datastructures::Node<T>* head() const {
return head_;
}
T getNthValueFromTail(int index) {
if (index >= size_) {
throw std::out_of_range("out of range");
}
size_t toIterate = size_ - index - 1;
datastructures::Node<T>* ptr = head_;
for (size_t i = 0; i < toIterate; i++) {
ptr = ptr->next;
}
return ptr->value;
}
void reverse() {
if (head_ == nullptr) {
return;
}
datastructures::Node<T> *current = head_;
datastructures::Node<T> *follower = head_;
datastructures::Node<T> *tmp;
// update tail
tail_ = current;
// start iterating
current = current->next;
while (current->next != nullptr) {
// processingNode = current->value;
tmp = current->next;
current->next = follower;
// currentNodeNextIsEqualTo = follower->value;
follower = current;
// followerIsNow = current->value;
current = tmp;
// currentIsNow = current->value;
}
current->next = follower;
head_->next = nullptr;
head_ = current;
}
void removeValue(const T &value) {
if (head_ == nullptr) {
return;
}
if (head_->value == value) {
datastructures::Node<T> *tmp = head_->next;
delete head_;
head_ = tmp;
// handle tail, because the list may now be empty
if (head_ == nullptr) {
tail_ = nullptr;
}
--size_;
return;
}
datastructures::Node<T> *current = head_;
datastructures::Node<T> *follower = head_;
while (current->next != nullptr) {
current = current->next;
if (current->value == value) {
follower->next = current->next;
if (current->next == nullptr) {
tail_ = follower;
}
delete current;
--size_;
return;
}
follower = follower->next;
}
}
int size() const {
return size_;
}
bool empty() const {
return head_ == nullptr;
}
};
}
#endif
| {
"alphanum_fraction": 0.4813191629,
"avg_line_length": 25.2127071823,
"ext": "h",
"hexsha": "e4802fcfc19a9edd38bf3731fb12311b40e69bca",
"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": "af08794fd21f67ee603c3538bb07a4cd9b5bc999",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tiagoinacio/algorithms_cpp",
"max_forks_repo_path": "src/data-structures/linked-list/singly-linked-list-with-tail.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "af08794fd21f67ee603c3538bb07a4cd9b5bc999",
"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": "tiagoinacio/algorithms_cpp",
"max_issues_repo_path": "src/data-structures/linked-list/singly-linked-list-with-tail.h",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "af08794fd21f67ee603c3538bb07a4cd9b5bc999",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tiagoinacio/algorithms_cpp",
"max_stars_repo_path": "src/data-structures/linked-list/singly-linked-list-with-tail.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2038,
"size": 9127
} |
/**
* Subroutines to calculate the
* various contamination models
*/
#include <time.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_interp.h>
#include "inout_aper.h"
#include "spc_model.h"
#include "spce_sect.h"
#include "spc_back.h"
#include "spce_PET.h"
#include "aXe_errors.h"
#include "fringe_conf.h"
#include "spc_resp.h"
#include "spce_pathlength.h"
#include "aper_conf.h"
#include "specmodel_utils.h"
#define MAX(x,y) (((x)>(y))?(x):(y))
#define MIN(x,y) (((x)<(y))?(x):(y))
#define SQR(x) ((x)*(x))
/*-------------------
* Section 1: Gauss contamination and directly
* dependent subroutines
*/
/**
* Function: compute_gauss_cont
* The subroutine computes ans stores the quantitative contamination
* using the Gaussian emission model. The emitting object with Gaussian
* shape and SED as derived from the AB filter magnitudes are composed
* The individual nbeams are modelled, then the complete contamination
* image is composed from the beam models.
* Finally, the contaminating flux is computed by subtracting the
* beam emission from the contamination image for all PET pixels.
*
* Parameters:
* @param grism_file - the full name of the grism file
* @param OAF_file - the name of the aperture file
* @param CONF_file - the full name of configuration file
* @param specmod_file- fits table with the model spectra
* @param model_scale - the scale for extension of the direct object area
* @param inter_type - the interpolation method for the flux values
* @param lambda_psf - wavelength the Gaussian parameters were determined at
* @param obs - the observation
* @param PET_file - the name of the PET which is modified
* @param map_file - the name of the contamination map
* @param store - flag whether the contamination image is stored or not
*
* Returns:
* @return status - returns success or failure
*/
int
compute_gauss_cont(char grism_file[], char OAF_file[], char CONF_file[],
const char specmod_file[], const double model_scale,
const int inter_type, const double lambda_psf,
observation *obs, const char PET_file[], char map_file[],
const int store)
{
object **oblist;
dirobject **dirlist;
beamspec **speclist;
spectral_models *spec_mod;
//dirobject *actdir;
gsl_matrix *all_models;
char model_name[60];
px_point npixels;
//time_t timer;
// load the object list
fprintf (stdout, "aXe_PETCONT: Loading object aperture list...");
oblist = file_to_object_list_seq (OAF_file, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
// check whether highres models
// are given
if (strlen(specmod_file) > 0)
// load the spectral models
spec_mod = load_spectral_models(specmod_file);
else
// or set the struct to NULL
spec_mod = NULL;
// get the image dimensions
npixels = get_npixel(obs);
// create the list of direct objects to be simulated
dirlist = oblist_to_dirlist(grism_file, CONF_file, npixels, oblist, spec_mod, model_scale, inter_type);
// timer=time(NULL);
// printf("The current time is %s.\n",asctime(localtime(&timer)));
speclist = make_gauss_spectra(oblist, dirlist, lambda_psf, npixels, CONF_file);
// timer=time(NULL);
// printf("The current time is %s.\n",asctime(localtime(&timer)));
// compose the contamination image from the modelled beams
all_models = make_model_image(npixels, obs, speclist);
// check whether the contamination image
// should be stored
if (store)
// store the contamination image
gsl_to_FITSimage (all_models, map_file, 1, NULL);
// store the name of the
// contamination model
sprintf (model_name, "GAUSS");
// put the contamination info into the PET
fill_contam_info(PET_file, speclist, all_models, model_name);
// release allocated memory
// in the various structures
gsl_matrix_free(all_models);
if (spec_mod != NULL)
free_spectral_models(spec_mod);
free_dirlist(dirlist);
free_speclist(speclist);
if (oblist !=NULL)
free_oblist (oblist);
// return always '1'
return 1;
}
/**
* Function: compute_gaussdirim_cont
* The subroutine computes ans stores the quantitative contamination
* using the Gaussian emission model. The object shape can be defined
* in a fits file with object models, and the SED may be defined in a
* fits table with high resolution spectra. If no detailed object shape
* or SED is given for an individual object, Gaussian shape and SED as
* derived from the AB filter magnitudes are composed.
* The individual nbeams are modelled, then the complete contamination
* image is composed from the beam models.
* Finally, the contaminating flux is computed by subtracting the
* beam emission from the contamination image for all PET pixels.
*
* Parameters:
* @param grism_file - the full name of the grism file
* @param OAF_file - the name of the aperture file
* @param CONF_file - the full name of configuration file
* @param specmod_file- fits table with the model spectra
* @param objmod_file - fits image with object models
* @param model_scale - the scale for extension of the direct object area
* @param inter_type - the interpolation method for the flux values
* @param lambda_psf - wavelength the Gaussian parameters were determined at
* @param obs - the observation
* @param PET_file - the name of the PET which is modified
* @param map_file - the name of the contamination map
* @param store - flag whether the contamination image is stored or not
*
* Returns:
* @return status - returns success or failure
*/
int
compute_gaussdirim_cont(char grism_file[], char OAF_file[], char CONF_file[],
const char specmod_file[], const char objmod_file[],
const double model_scale, const int inter_type,
const double lambda_psf, observation *obs,
const char PET_file[], char map_file[], const int store)
{
object **oblist;
dirobject **dirlist;
beamspec **speclist;
spectral_models *spec_mod;
object_models *obj_mod;
//dirobject *actdir;
gsl_matrix *all_models;
char model_name[60];
px_point npixels;
//time_t timer;
// load the object list
fprintf (stdout, "aXe_PETCONT: Loading object aperture list...");
oblist = file_to_object_list_seq (OAF_file, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
// check whether highres models
// are given
if (strlen(specmod_file) > 0)
// load the spectral models
spec_mod = load_spectral_models(specmod_file);
else
// or set the struct to NULL
spec_mod = NULL;
// check whether direct emission models
// are given
if (strlen(objmod_file) > 0)
obj_mod = load_object_models(objmod_file);
else
obj_mod = NULL;
// get the image dimensions
npixels = get_npixel(obs);
// create the list of direct objects to be simulated
dirlist = oblist_to_dirlist2(grism_file, CONF_file, npixels, oblist,
spec_mod, obj_mod, model_scale, inter_type);
//timer=time(NULL);
//printf("The current time is %s.\n",asctime(localtime(&timer)));
speclist = make_gauss_spectra2(oblist, dirlist, lambda_psf, npixels, CONF_file);
//timer=time(NULL);
//printf("The current time is %s.\n",asctime(localtime(&timer)));
// compose the contamination image from the modelled beams
all_models = make_model_image(npixels, obs, speclist);
// check whether the contamination image
// should be stored
if (store)
// store the contamination image
gsl_to_FITSimage (all_models, map_file, 1, NULL);
// store the name of the
// contamination model
if (obj_mod != NULL)
sprintf (model_name, "DIRIM");
else
sprintf (model_name, "GAUSS");
// check whether a PET exists
if (strlen(PET_file) > 0)
// put the contamination info into the PET
fill_contam_info(PET_file, speclist, all_models, model_name);
// release allocated memory
// in the various structures
gsl_matrix_free(all_models);
if (spec_mod != NULL)
free_spectral_models(spec_mod);
free_dirlist(dirlist);
if (obj_mod != NULL)
free_object_models(obj_mod);
free_speclist(speclist);
if (oblist !=NULL)
free_oblist (oblist);
// return always '1'
return 1;
}
/**
* Function: make_gauss_spectra2
* The function creates a spectral model for the beams
* that are considered in the contamination. The modelled
* beams are returned as a list.
*
* Parameters:
* @param oblist - the object list as input to select beams
* @param dirlist - the direct object list to dimension the models
* @param lambda_psf - the wavelength the object psf was determined at
* @param npixels - the dimensions of the model for the whole image
* @param CONF_file - the name of the configuration file
*
* Returns:
* @return speclist - the list of modelled beams
*/
beamspec **
make_gauss_spectra2(object **oblist, dirobject **dirlist,
const double lambda_psf, const px_point npixels,
char CONF_file[])
{
beamspec **speclist;
dirobject *actdir;
aperture_conf *conf;
calib_function *wl_calibration;
spectrum *resp;
beam actbeam;
tracedata *acttrace;
//double eval=0.0;
double psf_offset=0;
//int nspecs;
//int i=0;
//int j=0;
//int jj=0;
int ii=0;
int nobjects;
//int kk, ll;
double sval;
double frac_prev, frac;
int nx, ny;
d_point dpixel;
// determine the number of objects in the object list
nobjects = object_list_size(oblist);
// load the configuration file
conf = get_aperture_descriptor (CONF_file);
// allocate ther list of spectral beams
speclist = alloc_beamlist_from_dirlist(oblist, dirlist, npixels, conf);
// go over each beam model
ii = 0;
while (speclist[ii] != NULL)
{
// get the direct object for the actual model spectrum
actdir = get_dirobject_from_list(dirlist, speclist[ii]->objectID);
// get the beam for the actual model spectrum
actbeam = get_beam_for_beamspec(oblist,nobjects,speclist[ii]);
// get the psf offset values
psf_offset = get_psf_offset(conf, actbeam);
// get the wavelength calibration for the actual model spectrum
wl_calibration = get_calib_function(speclist[ii], actdir, CONF_file, conf);
// get the sensitivity data for the actual model spectrum
resp = get_throughput_spec(speclist[ii], CONF_file);
// fill the tracedata structure for the model spectrum
//acttrace = compute_tracedata(actbeam,actdir, wl_calibration,speclist[ii]);
acttrace = compute_short_tracedata(conf, actbeam,actdir, wl_calibration,speclist[ii]);
if (acttrace->npoints < 1)
{
// release the space for the various structures
free_calib(wl_calibration);
free_spectrum(resp);
free_tracedata(acttrace);
// give feedback to the screen
fprintf(stderr, "aXe_PETCONT: skipping object %i beam %c ...", speclist[ii]->objectID, BEAM(speclist[ii]->beamID));
// enhance the spectral beam counter
// and go to the next
ii++;
continue;
}
// fill the flux information int the tracedata
fill_fluxfrom_SED(actdir, acttrace);
// give feedback to the screen
fprintf(stdout, "aXe_PETCONT: modelling object %i beam %c ...", speclist[ii]->objectID, BEAM(speclist[ii]->beamID));
frac_prev=10.0;
// go over each pixel in the direct object area
for (nx=actdir->ix_min; nx<=actdir->ix_max; nx++)
{
//----------------------------------------------
// compute the percentage that has been computed
// report progress in 10% increments
frac = fmod(100.0*(nx - actdir->ix_min)/(actdir->ix_max - actdir->ix_min),10);
if (frac < frac_prev)
{
fprintf(stdout, " %i ", (int)100.0*(nx - actdir->ix_min)/(actdir->ix_max - actdir->ix_min));
fflush(stdout);
}
frac_prev=frac;
//----------------------------------------------
for (ny=actdir->iy_min; ny<=actdir->iy_max; ny++)
{
// fill the dpixel structure
dpixel.x = (double)nx;
dpixel.y = (double)ny;
if (actdir->dirim)
{
sval = get_diremission_value(actdir->dirim, dpixel.x - actbeam.refpoint.x, dpixel.y - actbeam.refpoint.y);
gsl_vector_set_all (acttrace->gvalue, sval);
}
else
{
// check whether a wavelength-dependent
// emission profile is given
if ((conf->psfcoeffs && conf->psfrange) || psf_offset)
{
// fill in the wavelength dependend
// emission values
fill_gaussvalues(dpixel, actbeam, actdir, lambda_psf, conf, psf_offset, acttrace);
}
else
{
// do a subsampling over the pixel
// to get a more appropriate value for the
// emission val
sval = get_sub_emodel_value(dpixel, actbeam, actdir->drzscale);
gsl_vector_set_all (acttrace->gvalue, sval);
}
}
// insert the spectrum of this direct object pixel in the beam spectrum
fill_pixel_in_speed(actdir, acttrace, dpixel, resp, speclist[ii], wl_calibration);
}
}
// release the space for the various structures
fprintf(stdout, " Done\n");
free_calib(wl_calibration);
free_spectrum(resp);
free_tracedata(acttrace);
// enhance the counter
ii++;
}
// free the memory in the conf structure
free_aperture_conf(conf);
// return the list of modelled beams
return speclist;
}
/**
* Function: make_gauss_spectra
* The function creates a spectral model for the beams
* that are considered in the contamination. The modelled
* beams are returned as a list.
*
* Parameters:
* @param oblist - the object list as input to select beams
* @param dirlist - the direct object list to dimension the models
* @param lambda_psf - the wavelength the object psf was determined at
* @param npixels - the dimensions of the model for the whole image
* @param CONF_file - the name of the configuration file
*
* Returns:
* @return speclist - the list of modelled beams
*/
beamspec **
make_gauss_spectra(object **oblist, dirobject **dirlist,
const double lambda_psf, const px_point npixels,
char CONF_file[])
{
beamspec **speclist;
dirobject *actdir;
aperture_conf *conf;
calib_function *wl_calibration;
spectrum *resp;
beam actbeam;
tracedata *acttrace;
//double eval=0.0;
double psf_offset=0;
int nspecs;
int i=0;
int j=0;
int jj=0,ii=0;
int nobjects;
//int kk, ll;
double sval;
int nx, ny;
d_point dpixel;
// determine the number of objects in the object list
nobjects = object_list_size(oblist);
// load the configuration file
conf = get_aperture_descriptor (CONF_file);
// get the number of beams included in the contamination
// (mag < mag_mark(BEAM)
nspecs = get_beamspec_size(oblist);
speclist = (beamspec **) malloc((nspecs+1) * sizeof(beamspec *));
if (speclist == NULL)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"make_model_spectra:" " Could not allocate"
" memory for pointers to %i beamspec objects", nspecs+1);
fprintf(stdout, "aXe_PETCONT: %i beams are included in the contamination.\n",nspecs);
// go over all objects
for (i = 0; i < nobjects; i++)
{
// go over each beam in an object
for (j=0; j < oblist[i]->nbeams; j++)
{
// check whether the beam is included in the contamination
if (oblist[i]->beams[j].ignore != 1)
{
// get the direct object for the beam
actdir = get_dirobject_from_list(dirlist, oblist[i]->ID);
// check whether the beam is inside the image,
// if yes, allocate space for the beam model
speclist[jj] = dimension_beamspec(actdir, oblist[i], npixels, conf, j);
// increment the counter if space was allocated
if (speclist[jj] != NULL)
jj++;
}
}
}
fprintf(stdout, "aXe_PETCONT: %i beams are modelled.\n",jj);
// terminate the beamspec list with NULL's
for (ii=jj; ii < nspecs+1; ii++)
speclist[ii] = NULL;
// go over each beam model
ii = 0;
while (speclist[ii] != NULL)
{
// fprintf(stdout, "modelling 1: %i\n", ii);
// get the direct object for the actual model spectrum
actdir = get_dirobject_from_list(dirlist, speclist[ii]->objectID);
// get the beam for the actual model spectrum
actbeam = get_beam_for_beamspec(oblist,nobjects,speclist[ii]);
// fprintf(stdout, "modelling 2: %i\n", ii);
psf_offset = get_psf_offset(conf, actbeam);
// fprintf(stdout, "modelling 3: %i\n", ii);
// get the wavelength calibration for the actual model spectrum
wl_calibration = get_calib_function(speclist[ii], actdir, CONF_file, conf);
// get the sensitivity data for the actual model spectrum
resp = get_throughput_spec(speclist[ii], CONF_file);
// fill the tracedata structure for the model spectrum
acttrace = compute_tracedata(actbeam,actdir, wl_calibration,speclist[ii]);
// fprintf(stdout, "modelling 4: %i\n", ii);
if (acttrace->npoints < 1)
{
// release the space for the various structures
// fprintf(stdout, "modelling 50: %i\n", ii);
free_calib(wl_calibration);
free_spectrum(resp);
free_tracedata(acttrace);
fprintf(stderr, "aXe_PETCONT: skipping object %i beam %c ...", speclist[ii]->objectID, BEAM(speclist[ii]->beamID));
ii++;
continue;
}
// fprintf(stdout, "modelling 51: %i\n", ii);
// fill the flux information int the tracedata
fill_fluxfrom_SED(actdir, acttrace);
// fprintf(stderr, "modelling 6: %i\n", ii);
fprintf(stdout, "aXe_PETCONT: modelling object %i beam %c ...", speclist[ii]->objectID, BEAM(speclist[ii]->beamID));
// go over each pixel in the direct object area
for (nx=actdir->ix_min; nx<=actdir->ix_max; nx++)
{
for (ny=actdir->iy_min; ny<=actdir->iy_max; ny++)
{
//fprintf(stderr, "point %i %i %i <-> %i %i <-> %i \n", nx, ny, actdir->ix_min, actdir->ix_max, actdir->iy_min, actdir->iy_max);
// fill the dpixel structure
dpixel.x = (double)nx;
dpixel.y = (double)ny;
// check whether a wavelength-dependent
// emission profile is given
if ((conf->psfcoeffs && conf->psfrange) || psf_offset)
{
// fill in the wavelength dependend
// emission values
fill_gaussvalues(dpixel, actbeam, actdir, lambda_psf, conf, psf_offset, acttrace);
}
else
{
// do a subsampling over the pixel
// to get a more appropriate value for the
// emission val
sval = get_sub_emodel_value(dpixel, actbeam, actdir->drzscale);
gsl_vector_set_all (acttrace->gvalue, sval);
}
//
fill_pixel_in_speed(actdir, acttrace, dpixel, resp, speclist[ii], wl_calibration);
}
}
// release the space for the various structures
fprintf(stdout, " Done\n");
free_calib(wl_calibration);
free_spectrum(resp);
free_tracedata(acttrace);
// enhance the counter
ii++;
}
// fre the memory in the conf structure
free_aperture_conf(conf);
// return the list of modelled beams
return speclist;
}
/*-------------------
* Section 2: Fluxcube contamination and directly
* dependent subroutines
*/
/*
* Function: compute_fcube_cont
* The subroutine computes ans stores the quantitative contamination
* using the Fluxcube emission model. The emitting objects are defined
* in fluxcube images, which were derived from MultiDrizzled direct images.
* The individual nbeams are modelled, then the complete contamination
* image is composed from the beam models.
* Finally, the contaminating flux is computed by subtracting the
* beam emission from the contamination image for all PET pixels.
*
*
* Parameters:
* @param grism_file - the full name of the grism file
* @param OAF_file - the name of the aperture file
* @param fcube_file - the name of the fluxcube file
* @param CONF_file - the full name of configuration file
* @param model_scale - the scale for extension of the direct object area
* @param inter_type - the interpolation method for the flux values
* @param obs - the observation
* @param PET_file - the name of the PET which is modified
* @param map_file - the name of the contamination map
* @param store - flag whether the contamination image is stored or not
*
* Returns:
* @return status - returns success or failure
*/
int
compute_fcube_cont(char grism_file[], char OAF_file[], char fcube_file[],
char CONF_file[], const double model_scale, const int inter_type,
observation *obs, const char PET_file[], char map_file[],
const int store)
{
object **oblist;
dirobject **dirlist;
beamspec **speclist;
flux_cube *fcube;
//dirobject *actdir;
gsl_matrix *all_models;
char model_name[60];
px_point npixels;
int i_type;
fprintf (stdout, "aXe_PETCONT: Loading fluxcube image %s ...", fcube_file);
fcube = load_fluxcube(fcube_file);
fprintf (stdout, " Done\n");
// load the object list
fprintf (stdout, "aXe_PETCONT: Loading object aperture list...");
oblist = file_to_object_list_seq (OAF_file, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
// get the dimension of the grism images
npixels = get_npixel(obs);
// generate the list of emitters from the
// fluxcube image
dirlist = fluxcube_to_dirlist(fcube, oblist);
// make the offsets??
fill_xy_offsets(dirlist, CONF_file);
// check whether there is enough information
// for the desired interpolation type
i_type = check_interp_type(inter_type, fcube->n_fimage, 0);
// model the beams
speclist = make_fcube_spectra(oblist, dirlist, npixels, CONF_file, fcube, i_type);
// compute the contamination image from the
// modelled beams
all_models = make_model_image(npixels, obs, speclist);
// check whether the contamination
// image should be stored
if (store)
// store the contamination image
gsl_to_FITSimage (all_models, map_file, 1, NULL);
// store the name of the contamination model
sprintf (model_name, "FLUXCUBE");
// check whether a PET exists
if (strlen(PET_file) > 0)
// compute and transfer the contamination
// information fot the PET pixels
fill_contam_info(PET_file, speclist, all_models, model_name);
// free the memory allocated
// in the various structures
gsl_matrix_free(all_models);
free_speclist(speclist);
free_dirlist (dirlist);
free_fluxcube(fcube);
if (oblist != NULL)
free_oblist (oblist);
// return '1' as a dummy
return 1;
}
/**
* Function: make_fcube_spectra
* The function creates a spectral model for the beams
* that are considered in the contamination. It uses
* the fluxcube emission model to calculate the emission
* in the different beams.
*
* Parameters:
* @param oblist - the object list as input to select beams
* @param dirlist - the direct object list to dimension the models
* @param npixels - the dimensions of the model for the whole image
* @param CONF_file - the name of the configuration file
* @param fcube - the fluxcube to get the flux data from
*
* Returns:
* @return speclist - the list of modelled beams
*/
beamspec **
make_fcube_spectra(object **oblist, dirobject **dirlist,
const px_point npixels, char CONF_file[],
const flux_cube *fcube, const int inter_type)
{
beamspec **speclist;
dirobject *actdir;
aperture_conf *conf;
calib_function *wl_calibration;
spectrum *resp;
beam actbeam;
tracedata *acttrace;
int i;
int nobjects;
int nx, ny;
//d_point dpixel;
d_point dflt_point;
px_point fcube_point;
d_point tmp2;
// determine the number of objects in the object list
nobjects = object_list_size(oblist);
// load the configuration file
conf = get_aperture_descriptor (CONF_file);
speclist = alloc_beamlist_from_dirlist(oblist, dirlist, npixels, conf);
// go over each beam model
i = 0;
while (speclist[i] != NULL)
{
// get the direct object for the actual model spectrum
actdir = get_dirobject_from_list(dirlist, speclist[i]->objectID);
// get the beam for the actual model spectrum
actbeam = get_beam_for_beamspec(oblist,nobjects,speclist[i]);
// get the wavelength calibration for the actual model spectrum
wl_calibration = get_calib_function(speclist[i], actdir, CONF_file, conf);
// get the sensitivity data for the actual model spectrum
resp = get_throughput_spec(speclist[i], CONF_file);
// fill the tracedata structure for the model spectrum
acttrace = compute_tracedata(actbeam,actdir, wl_calibration,speclist[i]);
if (acttrace->npoints < 1)
{
// release the space for the various structures
free_calib(wl_calibration);
free_spectrum(resp);
free_tracedata(acttrace);
fprintf(stdout, "aXe_PETCONT: skipping object %i beam %c ...", speclist[i]->objectID, BEAM(speclist[i]->beamID));
continue;
}
fprintf(stdout, "aXe_PETCONT: modelling object %i beam %c ...", speclist[i]->objectID, BEAM(speclist[i]->beamID));
// go over each pixel in the direct object area
for (nx=actdir->ix_min; nx<=actdir->ix_max; nx++)
{
for (ny=actdir->iy_min; ny<=actdir->iy_max; ny++)
{
// transform the flt-coordinates
// to fcube coordinates
dflt_point.x = (double)nx;
dflt_point.y = (double)ny;
tmp2 = flt_to_fcube_trans(fcube, dflt_point);
fcube_point.x = (int)tmp2.x;
fcube_point.y = (int)tmp2.y;
// check whether the coordinate point actually
// does belong to the spectral beam
if ( gsl_matrix_int_get(fcube->segmentation, fcube_point.x,fcube_point.y) == actdir->ID)
{
// transfer the flux information from the current pixel
// to the SED of the direct object
fill_fluxvalues(fcube, fcube_point, actdir, inter_type);
// fill theflux-vector of the tracedata
fill_fluxfrom_SED(actdir, acttrace);
// compute the contribution of the current pixel to the
// current beam object
fill_pixel_in_speed(actdir, acttrace, dflt_point, resp, speclist[i], wl_calibration);
}
}
}
// release the space fpr the various structures
fprintf(stdout, " Done\n");
free_calib(wl_calibration);
free_spectrum(resp);
free_tracedata(acttrace);
i++;
}
// release memory
free_aperture_conf(conf);
// return the spectrum list
return speclist;
}
/**
* Function: alloc_beamlist_from_dirlist
* The function determines which beams of a direct object
* are included in the contamination model. Then the size for each
* of the spectral beams is estimated, and the space is allocated.
*
* Parameters:
* @param oblist - the object list as input to select beams
* @param dirlist - the direct object list to dimension the models
* @param npixels - the dimensions of the model for the whole image
* @param conf - configuration structure
*
* Returns:
* @return speclist - the list of modelled beams
*/
beamspec **
alloc_beamlist_from_dirlist(object **oblist, dirobject **dirlist,
const px_point npixels, aperture_conf *conf)
{
beamspec **speclist;
//dirobject *actdir;
//object *actobj;
int nspecs;
int i, j, jj=0;
int objindex;
// get the number of beams included in the contamination
// (mag < mag_mark(BEAM)
nspecs = get_beamspec_size(oblist);
// allocate space for the vector of spectral beams
speclist = (beamspec **) malloc((nspecs+1) * sizeof(beamspec *));
if (speclist == NULL)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"make_model_spectra:" " Could not allocate"
" memory for pointers to %i beamspec objects", nspecs+1);
fprintf(stdout, "aXe_PETCONT: %i beams are included in the contamination.\n",nspecs);
// go over all objects
i=0;
while (dirlist[i] != NULL)
{
// find the object structure to the directo object
objindex = find_object_in_object_list(oblist, dirlist[i]->ID);
if (objindex < 0)
{
i++;
continue;
}
// go over each beam in an object
for (j=0; j < oblist[objindex]->nbeams; j++)
{
// check whether the beam is included in the contamination
if (oblist[objindex]->beams[j].ignore != 1)
{
// check whether the beam is inside the image,
// if yes, allocate space for the beam model
// fprintf(stdout, "Trying %i, beam %c\n", dirlist[i]->ID, BEAM(j));
speclist[jj] = dimension_beamspec(dirlist[i], oblist[objindex], npixels, conf, j);
// increment the counter if space was allocated
if (speclist[jj] != NULL)
jj++;
}
}
i++;
}
fprintf(stdout, "aXe_PETCONT: %i beams are modelled.\n",jj);
// terminate the beamspec list with NULL's
for (i=jj; i < nspecs+1; i++)
speclist[i] = NULL;
// return the list of spectral beams
return speclist;
}
/*-------------------
* Section 3: Subroutines directly dependent
* from Gaussian AND Fluxcube contamination
*/
/**
* Function: dimension_beamspec
* The function checks the boundaries of a candidate
* model spectrum of a beam. In case that the
* model spectrum is completely outside the frame,
* a NULL model spectrum is returned.
* Otherwise space is allocated for the model spectrum and
* the matrix therein, and the data are filled in.
* Only the matrix is not defined and filled.
*
* Parameters:
* @param dirlist - the list with all dirobjects
* @param actobject - one beam of this object is examined
* @param npixels - the size of the CCD
* @param conf - the configutration structure
* @param j - the beam number to be examined
*
* Returns:
* @return actspec - the beamspec object created
*/
beamspec *
dimension_beamspec(dirobject *actdir, object *actobject,
const px_point npixels, const aperture_conf * conf, int j)
{
beamspec *actspec;
trace_func *tracefun;
gsl_matrix *stamp;
double dx0, dy0, dx1, dy1;
double xmin, xmax, ymin, ymax;
// allocate space for the beamspoec
actspec = (beamspec *)malloc(sizeof(beamspec));
if (actspec == NULL)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"make_model_spectra:" " Could not allocate"
" memory for a beamspec object");
// determine the range of x-values covered by that beam
// (relative to a refpoint)
tracefun = actobject->beams[j].spec_trace;
dx0 = (double)conf->beam[actobject->beams[j].ID].offset.dx0;
dx1 = (double)conf->beam[actobject->beams[j].ID].offset.dx1;
// determine the range of y-values covered by that beam
// (relative to a refpoint)
dy0 = tracefun->func (dx0, tracefun->data);
dy1 = tracefun->func (dx1, tracefun->data);
// apply the positional corrections;
// in case of the fluxcube model
// they are needed to transform
// the coordinates from the direct
// image to the grism image system
dx0 = dx0 + actdir->xy_off[j].x;
dx1 = dx1 + actdir->xy_off[j].x;
dy0 = dy0 + actdir->xy_off[j].y;
dy1 = dy1 + actdir->xy_off[j].y;
// using the corners of the direct image object as refpoints,
// translate the x- and y-ranges to the real area subtended
// bye that model beam on the CCD
xmin = floor(MIN((double)actdir->ix_min + dx0, (double)actdir->ix_min + dx1)+0.5);
xmax = floor(MAX((double)actdir->ix_max + dx0, (double)actdir->ix_max + dx1)+0.5);
ymin = floor(MIN((double)actdir->iy_min + dy0, (double)actdir->iy_min + dy1)+0.5);
ymax = floor(MAX((double)actdir->iy_max + dy0, (double)actdir->iy_max + dy1)+0.5);
// check whether the area is completely outside the CCD
if ((xmax < 0.0) || (ymax < 0.0))
{
// fprintf(stdout, "Beam's too low: %i %i\n",actobject->ID, actobject->beams[j].ID);
// if yes, release the memory and return NULL
free(actspec);
actspec = NULL;
return actspec;
}
// check whether the area is completely outside the CCD
if ((xmin > (double)(npixels.x-1)) || (ymin > (double)(npixels.y-1)))
{
// fprintf(stdout, "Beam's too high: %i %i\n",actobject->ID, actobject->beams[j].ID);
// if yes, release the memory and return NULL
free(actspec);
actspec = NULL;
return actspec;
}
// check whether part of the are is outside;
// correct if necessary
xmin = MAX(xmin-1, 0.0);
ymin = MAX(ymin-1, 0.0);
// check whether part of the are is outside;
// correct if necessary
xmax = MIN(xmax+1, (double)(npixels.x-1.0));
ymax = MIN(ymax+1, (double)(npixels.y-1.0));
// transfer the ID's to the model beam
actspec->objectID = actobject->ID;
actspec->beamID = actobject->beams[j].ID;
// transfer the coo's of the starting point;
// leave one pixel for the 'drizzling'
actspec->model_ref.x = (int)xmin;
actspec->model_ref.y = (int)ymin;
// allocate space for the matrix;
// give two pixels more on each side for 'drizzling';
// set the matrix to 0.0 and give it to the model beam
stamp = gsl_matrix_alloc((int)(xmax-xmin)+1, (int)(ymax-ymin)+1);
if (stamp == NULL)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"dimension_beamspec:" " Could not allocate"
" memory for %i x %i GSL matrix", (int)(xmax-xmin)+1, (int)(ymax-ymin)+1);
gsl_matrix_set_all(stamp, 0.0);
actspec->model = stamp;
// return the beam created
return actspec;
}
/**
* Function: fill_pixel_in_speed
* The function determines and coadds the contribution of a single pixel in
* the direct image area to the model spectrum.
*
* Parameters:
* @param actdir - the direct object of the model spectrum
* @param acttrace - the tracedata of the model spectrum
* @param dpixel - the coordinates of the modelled pixel
* @param eval - the emission value of the source at the modelled pixel
* @param resp - the sensitivity data
* @param actspec - the structure for the model spectrum
*
* Returns:
* @return 1 -
*/
int
fill_pixel_in_speed(const dirobject *actdir, const tracedata *acttrace,
const d_point dpixel, const spectrum *resp,
beamspec *actspec, const calib_function *wl_calibration)
{
double dx;
double sens;
double fval;
double tmp1;
//double tmp2, tmp3;
double ddx, ddy;
int ix, iy;
int xstart, xend;
int xact;
int ipos;
int nguess;
// define the dx-range for which a pixel is modelled
xstart = actspec->model_ref.x;
xend = actspec->model_ref.x + actspec->model->size1;
// nguess is the approximate possition
// to find a wavelength in the sensitivity table.
// should speed upt things
nguess=0;
// go over the dx-range
for (xact = xstart; xact < xend; xact++)
{
// compute the actual dx-value
dx = xact-dpixel.x;
// get the index to find the data for the actual
ipos = get_index_for_tracepoint(acttrace, dx);
// in case that the dx-value is not in the tracedata,
// something is wrong. exit
if (ipos <0)
{
//if (wl_calibration->pr_range == NULL)
// aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
// "aXe_PETCONT: " "tracepoint is outside the prepared range!\n");
//else
continue;
}
// compute the y-position in the matrix of the beamspec
iy = (int)floor(gsl_vector_get(acttrace->dy,ipos) + actdir->xy_off[actspec->beamID].y + 0.5) + (int)dpixel.y - actspec->model_ref.y;
// the same quantity as a double
ddy = gsl_vector_get(acttrace->dy,ipos) + actdir->xy_off[actspec->beamID].y + dpixel.y - actspec->model_ref.y;
// if the y-position is outside, go to the next dx value
if (iy < 0 || iy > (int)actspec->model->size2-1)
continue;
// in case that the actual wavelength is outside the range
// of the sensitivity data, continue with the next dx-value
if (gsl_vector_get(acttrace->lambda, ipos) < resp->lambdamin || gsl_vector_get(acttrace->lambda, ipos) > resp->lambdamax)
continue;
// compute the x-position in the matrix of the beamspec
ix = (int)(gsl_vector_get(acttrace->dx,ipos) + actdir->xy_off[actspec->beamID].x) + (int)dpixel.x - actspec->model_ref.x;
// the same quantity as double
ddx = gsl_vector_get(acttrace->dx,ipos) + actdir->xy_off[actspec->beamID].x + dpixel.x - actspec->model_ref.x;
// get the total flux value of the source at the wavelength of the actual dx-value
fval = gsl_vector_get(acttrace->gvalue, ipos) * gsl_vector_get(acttrace->flux, ipos);
// get the sensitivity at the wavelength of the actual dx-value
sens = get_response_value_plus(resp, gsl_vector_get(acttrace->lambda, ipos), &nguess);
// compute the contribution of the actual dx-value to the model spectrum
tmp1 = fval * sens * gsl_vector_get(acttrace->dlambda,ipos);
// double check whether we are inside the image
if (ix < 0 || iy < 0 || ix > (int)(actspec->model->size1-1) || iy > (int)(actspec->model->size2-1))
{
fprintf(stdout, "xval: %i, yval: %i, size1: %zi, size2: %zi\n",ix, iy, actspec->model->size1, actspec->model->size2);
}
else
{
// add the contribution of the actual dx value to
// the model spectrum, using NO diffusion
// no_diffuse_spectrum(ix, iy, tmp1, actspec);
// add the contribution of the actual dx value to
// the model spectrum, using GRID diffusion
// diffuse_spectrum(ddx, ddy, tmp1, actspec);
// add the contribution of the actual dx value to
// the model spectrum, using PROPORTIONAL diffusion
diffuse_spectrumII(ddx, ddy, tmp1, actspec);
}
}
// return a dummy
return 1;
}
/**
* Function: get_index_for_tracepoint
* For a given dx-value, the function derives the index
* under which data for this dx-value is stored in a tracedata structure.
* The index is simply returned. If the dx-value is not inside
* the tracedata, '-1' is returned.
* In contrast to the first attempt (now 'get_index_for_tracepoint2')
* this routine uses the minimum dx value stored in the tracedata
* structure. It becomes much much faster by that!
*
* Parameters:
* @param acttrace - the tracedata to search an index
* @param dx - the dx-value to identify in the tracedata
*
* Returns:
* @return ipos - the index where the dx-value is stored
*/
int
get_index_for_tracepoint(const tracedata *acttrace, const double dx)
{
int ipos;
// compute the index using the minimum dx value
// stored in the structure
ipos = (int)(dx - acttrace->dx_start);
// check whether the index is within the acceptable range
// make it -1 if not
if (ipos < 0 || ipos > (acttrace->npoints -1))
ipos=-1;
// return the index
return ipos;
}
/**
* Function no_diffuse_spectrum
* Adds the simulated flux for one pixel exactly into
* one pixel, using the integer value of the correct
* position.
*
* Parameters:
* @param ix - the integer x-position in the beam
* @param iy - the integer y-position in the beam
* @param cps - the cps-value for one entire pixel
* @param actspec - the beam to model
*
* Returns:
* @return 1.0 - return a dummy value
*/
int
no_diffuse_spectrum(int ix, int iy, double cps, beamspec *actspec)
{
double tmp = 0.0;
// add the contribution of the actual dx value to the model spectrum
tmp = gsl_matrix_get(actspec->model, ix, iy);
// set the new value
gsl_matrix_set(actspec->model, ix, iy, cps + tmp);
// return a dummy
return 1;
}
/**
* Function diffuse_spectrum
* Distribute the flux simulated for the area of one pixel
* square in the emission model over a pixel square in
* the beam model.
* This method uses sub-steps starting from the exact
* center of the light
* This smoothes the modelled beam by avoiding integer
* rounding effects.
*
* Parameters:
* @param ddx - the exact x-position in the beam
* @param ddy - the exact y-position in the beam
* @param cps - the cps-value for one entire pixel
* @param actspec - the beam to model
*
* Returns:
* @return 1.0 - return a dummy value
*/
int
diffuse_spectrum(double ddx, double ddy, double cps, beamspec *actspec)
{
double step;
double offset;
double ncps;
double oldvalue;
double sum=0.0;
double dx_act;
double dy_act;
int irange;
int kk, ll;
int ix, iy;
// convert the number of steps to a local integer
irange = (int)NDIFF;
// compute the step size
step = 1.0/(2.0*(double)NDIFF);
// compute the initial offset
offset = step/2.0;
// compute the incremental flux
ncps = cps * step * step;
for (kk=-irange; kk < irange; kk++)
{
for (ll=-irange; ll < irange; ll++)
{
// determine the actual grid position
dx_act = ddx + (double)kk * step + offset;
dy_act = ddy + (double)ll * step + offset;
// get the current pixel grid value
ix = floor(dx_act + 0.5);
iy = floor(dy_act + 0.5);
// double check whether we are inside the image
if (ix < 0 || iy < 0 || ix > (int)(actspec->model->size1-1) || iy > (int)(actspec->model->size2-1))
continue;
// add the contribution of the actual dx value to the model spectrum
oldvalue = gsl_matrix_get(actspec->model, ix, iy);
gsl_matrix_set(actspec->model, ix, iy, oldvalue + ncps);
sum += ncps;
}
}
// return a dummy
return 1.0;
}
/**
* Function diffuse_spectrumII
* Distribute the flux simulated for the area of one pixel
* square in the emission model over a pixel square in
* the beam model.
* Starting from the exact center of the light, the exact fraction
* falling on the four affected pixels is comuted and then added
* to the spectral beam.
* This smoothes the modelled beam by avoiding integer
* rounding effects.
*
* Parameters:
* @param ddx - the exact x-position in the beam
* @param ddy - the exact y-position in the beam
* @param cps - the cps-value for one entire pixel
* @param actspec - the beam to model
*
* Returns:
* @return 1.0 - return a dummy value
*/
int
diffuse_spectrumII(double ddx, double ddy, double cps, beamspec *actspec)
{
int ix;
int iy;
int ix_rem;
int iy_rem;
double p=0.0;
double q=0.0;
double p_rem=0.0;
double q_rem=0.0;
double d_incr = 0.0;
double oldvalue;
double sum = 0.0;
// compute the indices
// of the pixels involved
ix = (int)floor(ddx);
iy = (int)floor(ddy);
ix_rem = ix + 1;
iy_rem = iy + 1;
// compute the basic
// quantities for
// the increments;
// it seems to be the wrong way,
// however we are talking about
// pixels, not coordinates...
p_rem = ddx - floor(ddx);
q_rem = ddy - floor(ddy);
p = 1.0 - p_rem;
q = 1.0 - q_rem;
// increment the first quarter
// double check whether we are inside the image
if ( ! (ix < 0 || iy < 0 || ix > (int)(actspec->model->size1-1) || iy > (int)(actspec->model->size2-1)))
{
// compute the area
d_incr = p * q;
// add the fractional contribution to the model spectrum
oldvalue = gsl_matrix_get(actspec->model, ix, iy);
gsl_matrix_set(actspec->model, ix, iy, oldvalue + d_incr*cps);
sum += d_incr;
}
// increment the second quarter
// double check whether we are inside the image
if ( ! (ix < 0 || iy_rem < 0 || ix > (int)(actspec->model->size1-1) || iy_rem > (int)(actspec->model->size2-1)))
{
// compute the area
d_incr = p * q_rem;
// add the fractional contribution to the model spectrum
oldvalue = gsl_matrix_get(actspec->model, ix, iy_rem);
gsl_matrix_set(actspec->model, ix, iy_rem, oldvalue + d_incr*cps);
sum += d_incr;
}
// increment the third quarter
// double check whether we are inside the image
if ( ! (ix_rem < 0 || iy < 0 || ix_rem > (int)(actspec->model->size1-1) || iy > (int)(actspec->model->size2-1)))
{
// compute the area
d_incr = p_rem * q;
// add the fractional contribution to the model spectrum
oldvalue = gsl_matrix_get(actspec->model, ix_rem, iy);
gsl_matrix_set(actspec->model, ix_rem, iy, oldvalue + d_incr*cps);
sum += d_incr;
}
// increment the fourth quarter
// double check whether we are inside the image
if ( ! (ix_rem < 0 || iy_rem < 0 || ix_rem > (int)(actspec->model->size1-1) || iy_rem > (int)(actspec->model->size2-1)))
{
// compute the area
d_incr = p_rem * q_rem;
// add the fractional contribution to the model spectrum
oldvalue = gsl_matrix_get(actspec->model, ix_rem, iy_rem);
gsl_matrix_set(actspec->model, ix_rem, iy_rem, oldvalue + d_incr*cps);
sum += d_incr;
}
// return a dummy
return 1.0;
}
/**
*
* Function: make_model_image
* Sums up the modeled spectral beams to create a
* spectral model for the whole image.
*
* Parameters:
* @param npixels - the dimensions of the input grism image
* @param speclist - the list of modelled beams
*
* Returns:
* @return all_models - the model for the whole image
*/
gsl_matrix *
make_model_image(const px_point npixels, observation *obs, beamspec **speclist)
{
gsl_matrix *all_models;
double oldval, addval;
int i=0;
int xact, yact;
int ix, iy;
// allocate space for the result,
// set the matrix to 0.0
// all_models = gsl_matrix_alloc(npixels.x, npixels.y);
all_models = obs->grism;
gsl_matrix_set_all(all_models,0.0);
fprintf (stdout, "\naXe_PETCONT: Summing up the model beam spectra\n");
// go over each beam in the list
while (speclist[i] != NULL)
{
fprintf(stdout, "aXe_PETCONT: summing up object %i beam %c ...", speclist[i]->objectID, BEAM(speclist[i]->beamID));
// go over each pixel in the array of the beam model
for (xact=0; xact < (int)speclist[i]->model->size1; xact++)
{
for (yact=0; yact < (int)speclist[i]->model->size2; yact++)
{
// find the coordinates of the pixels in the whole image model
ix = speclist[i]->model_ref.x + xact;
iy = speclist[i]->model_ref.y + yact;
// check for safety reasons whether the coordinates are inside
if (ix < 0 || iy < 0 || ix > (npixels.x-1) || ix > (npixels.x-1)){
fprintf(stdout, "This should not happen!\n");
}
else{
// summ up the pixel
addval = gsl_matrix_get(speclist[i]->model, xact, yact);
oldval = gsl_matrix_get(all_models, ix, iy);
gsl_matrix_set(all_models, ix, iy, oldval+addval);
}
}
}
fprintf(stdout, " Done\n");
// increment the counter
i++;
}
// return the model
return all_models;
}
/**
* Function: fill_contam_info
* The function fills the contamination information into the
* PET. To do that it transfers the information from the
* aperture mask matrix into each PET. Self contamination is
* taken into account by subtracting the value from the modelled
* spectrum before storing the contamination.
*
* Parameters:
* @param PET_file - the PET file to add contamination
* @param speclist - the list of modelled spectra
* @param all_models - the contamination image
*
* Returns:
* @return 1 - returns always 1
*/
int
fill_contam_info(const char PET_file[], beamspec **speclist,
const gsl_matrix *all_models, char model_name[])
{
fitsfile *OPET_ptr;
ap_pixel *PET;
beamspec *actspec;
//FITScards *cards;
char ID[60];
double c;
double m;
int aperID, beamID;
int f_status=0;
int status;
int ix, iy;
int j;
// Open the OPET file for reading/writing
ffopen (&OPET_ptr, PET_file, READWRITE, &f_status);
if (f_status){
ffrprt(stdout, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PETCONT: Could not open file: %s\n",
PET_file);
}
// store the contamination model name in the PET
update_contam_model(OPET_ptr, model_name);
// report the action
fprintf (stdout, "\naXe_PETCONT: Writing the contamination into the PET.\n");
while (1)
{
// get the PET at the actual position of the PET file
PET = get_ALL_from_next_in_PET(OPET_ptr, &aperID, &beamID);
// leave the while loop if there is the end
if ((aperID==-1) && (beamID==-1))
break;
// report progress
fprintf(stdout, "aXe_PETCONT: writing contamination for object %i beam %c ... ", aperID, BEAM(beamID));
// skip the PET if empty
if (PET==NULL)
{
fprintf (stdout, ".Done\n");
continue;
}
// get the model spectrum for the actual PET
actspec = get_beamspec_from_list(speclist, aperID, beamID);
// go over all PET entries
j=0;
while (PET[j].p_x != -1)
{
// get the value from the contamination matrix
c = gsl_matrix_get(all_models,PET[j].p_x,PET[j].p_y);
m = 0.0;
// correct for self-contamination if the beams was modelled
if (actspec != NULL){
// get the coordinates in the model array
ix = PET[j].p_x - actspec->model_ref.x;
iy = PET[j].p_y - actspec->model_ref.y;
// check whether the PET entry is outside of the model array.
// correct for self contamination if the PET-etry is inside
if (ix > -1 && iy >-1 && ix < (int)actspec->model->size1 && iy < (int)actspec->model->size2)
{
m = gsl_matrix_get(actspec->model, ix, iy);
c = c - m;
}
}
// well, it should never be below zero
if (c < 0.0)
c = 0.0;
// write the contamination into the PET-entry
PET[j].contam = c;
PET[j].model = m;
// enhance the counter
j++;
}
// write the updated PET into the PET file
sprintf (ID, "%d%c", aperID, BEAM (beamID));
add_ALL_to_PET (PET, ID, OPET_ptr,1);
// free PET memory
if (PET!=NULL)
{
free(PET);
PET=NULL;
}
fprintf (stdout, ".Done\n");
}
// close the PET file
fits_close_file (OPET_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PETCONT: " "Error closing PET: %s \n",
PET_file);
}
// set the status to 'success' and return it
status=1;
return status;
}
/*-------------------
* Section 4: Geometrical contamination
*/
/**
* Function: compute_geometr_cont
* The subroutine computes the original, geometrical contamination
* model where every beams contaminates the area he occupies.
* Source brightness and source shape are not taken into account.
* For every beam the sum of all contaminations by othe beams is
* written into the PET.
*
* Parameters:
* @param OAF_file - the name of the aperture file
* @param obs - the observation
* @param PET_file - the name of the PET which is modified
* @param map_file - the name of the contamination map
* @param store - flagg whether the contamination image is stored or not
*
* Returns:
* @return status - returns success or failure
*/
int
compute_geometr_cont(char OAF_file[], observation *obs,
const char PET_file[], char map_file[],
const int store){
object **oblist;
ap_pixel *PET;
int f_status=0;
fitsfile *OPET_ptr;
int aperID, beamID, objindex;
gsl_matrix *aper_mask;
int status=0;
char model_name[60];
// load the object list
fprintf (stdout, "aXe_PETCONT: Loading object aperture list...");
oblist = file_to_object_list_seq (OAF_file, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
// Open the OPET file for reading/writing
ffopen (&OPET_ptr, PET_file, READWRITE, &f_status);
if (f_status)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PETCONT: Could not open file: %s\n",
PET_file);
// store the contamination model name in the PET
sprintf (model_name, "GEOM");
update_contam_model(OPET_ptr, model_name);
// do something in case that there are objects
if (oblist!=NULL)
{
// make the aperture mask
aper_mask = aperture_mask(obs,oblist);
// store the aperture mask into a fits file if requested
if (store)
gsl_to_FITSimage (aper_mask, map_file, 1, NULL);
// loop over all beams
while (1)
{
// get the PET at the actual position of the PET file
PET = get_ALL_from_next_in_PET(OPET_ptr, &aperID, &beamID);
// leave the while loop if there is the end
if ((aperID==-1) && (beamID==-1))
break;
// search for the particular beam in 'oblist', continue
// if PET is empty
fprintf (stdout, "aXe_PETCONT: BEAM %d%c", aperID, BEAM(beamID));
objindex = find_object_in_object_list(oblist,aperID);
if (PET==NULL)
{
fprintf (stdout, ".Done\n");
continue;
}
// transfer the information from the aperture mask
// into the beam
{
int j = 0;
double c;
// go over all PET entries
while (PET[j].p_x != -1)
{
// subtract self contamination, then store the contamination
c = gsl_matrix_get(aper_mask,PET[j].p_x,PET[j].p_y)-1.0;
if (c < 0.0)
c = 0.0;
PET[j].contam = c;
j++;
}
}
// write the updated PET into the PET file
{
char ID[60];
sprintf (ID, "%d%c", oblist[objindex]->ID, BEAM (oblist[objindex]->beams[beamID].ID));
add_ALL_to_PET (PET, ID, OPET_ptr,1);
}
// free PET memory
if (PET!=NULL)
{
free(PET);
PET=NULL;
}
fprintf (stdout, ".Done\n");
}
}
// free obl;ist memory
if (oblist!=NULL)
free_oblist (oblist);
// free observation memory
free_observation(obs);
// close the PET file
fits_close_file (OPET_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PETCONT: " "Error closing PET: %s \n",
PET_file);
}
// set the status to 'success' and return it
status=1;
return status;
}
/*-------------------
* Section 5: Simualting dirdct images with Gaussians
*/
/**
* Function: compute_gauss_dirim
*
* @param grism_file - the full name of the grism file
* @param OAF_file - the name of the aperture file
* @param obs - the observation
* @param PET_file - the name of the PET which is modified
* @param CONF_file - the full name of configuration file
* @param map_file - the name of the contamination map
* @param model_scale - the scale for extension of the direct object area
* @param store - flagg whether the contamination image is stored or not
*
* @return status - returns success or failure
*/
int
compute_gauss_dirim(char grism_file[], char OAF_file[], char CONF_file[],
const double model_scale, const int inter_type,
const double lambda_psf, observation *obs,
const char PET_file[], char map_file[], const int store){
object **oblist;
dirobject **dirlist;
//dirobject *actdir;
gsl_matrix *all_models;
//char model_name[60];
px_point npixels;
// load the object list
fprintf (stdout, "aXe_PETCONT: Loading object aperture list...");
oblist = file_to_object_list_seq (OAF_file, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
npixels = get_npixel(obs);
dirlist = oblist_to_dirlist(grism_file, CONF_file, npixels, oblist, NULL, model_scale, inter_type);
all_models = make_gauss_dirim(oblist, dirlist, lambda_psf, npixels, CONF_file, obs);
if (store)
gsl_to_FITSimage (all_models, map_file, 1, NULL);
gsl_matrix_free(all_models);
free_dirlist (dirlist);
if (oblist != NULL)
free_oblist (oblist);
return 1;
}
/**
* Function: make_gauss_dirim
* The function creates a spectral model for the beams
* that are considered in the contamination. The modelled
* beams are returned as a list.
*
* Parameters:
* @param oblist - the object list as input to select beams
* @param dirlist - the direct object list to dimension the models
* @param npixels - the dimensions of the model for the whole image
* @param CONF_file - the name of the configuration file
*
* Returns:
* @return speclist - the list of modelled beams
*/
gsl_matrix *
make_gauss_dirim(object **oblist, dirobject **dirlist,
const double lambda_psf, const px_point npixels,
char CONF_file[], observation *obs)
{
gsl_matrix *all_models;
dirobject *actdir;
beam actbeam;
//int nspecs;
//int i=0;
//int j=0;
//int jj=0;
int ii=0;
int nobjects;
//int kk;
//int ll;
double sval=0.0;
double flux=0.0;
double value=0.0;
int nx, ny;
d_point dpixel;
// determine the number of objects in the object list
nobjects = object_list_size(oblist);
// allocate space for the result,
// set the matrix to 0.0
// all_models = gsl_matrix_alloc(npixels.x, npixels.y);
all_models = obs->grism;
gsl_matrix_set_all(all_models,0.0);
// go over each beam model
ii = 0;
while (oblist[ii] != NULL)
{
// get the direct object for the actual model spectrum
actdir = get_dirobject_from_list(dirlist, oblist[ii]->ID);
// get the beam for the actual model spectrum
actbeam = oblist[ii]->beams[0];
fprintf(stdout, "aXe_PETCONT: modelling object %i ...", oblist[ii]->ID);
// go over each pixel in the direct object area
for (nx=actdir->ix_min; nx<=actdir->ix_max; nx++)
{
for (ny=actdir->iy_min; ny<=actdir->iy_max; ny++)
{
// fill the dpixel structure
dpixel.x = (double)nx;
dpixel.y = (double)ny;
sval = get_sub_emodel_value(dpixel, actbeam, actdir->drzscale);
flux = get_flux_from_SED(actdir->SED, 890.0);
if (nx > -1 && ny > -1 && nx < npixels.x && ny < npixels.y)
{
value = gsl_matrix_get(all_models, nx, ny) + sval*flux;
gsl_matrix_set(all_models, nx, ny, value);
}
}
}
// release the space for the various structures
fprintf(stdout, " Done\n");
ii++;
}
return all_models;
}
| {
"alphanum_fraction": 0.630129802,
"avg_line_length": 31.2262026612,
"ext": "c",
"hexsha": "2b73214ae22f141d4bebff7eed34bc612f250bca",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spc_model.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/spc_model.c",
"max_line_length": 142,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spc_model.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 16071,
"size": 61016
} |
#ifndef PINHOLE_H_I3RZULX9
#define PINHOLE_H_I3RZULX9
#include <cmath>
#include <gsl/gsl>
#include <sens_loc/camera_models/concepts.h>
#include <sens_loc/math/constants.h>
#include <sens_loc/math/coordinate.h>
#include <type_traits>
namespace sens_loc {
/// This namespace contains all camera and projection models and implements
/// them as necessary.
namespace camera_models {
/// This struct contains all parameters for the general pinhole camera model.
/// For more information you can check the
/// <a href="https://docs.opencv.org/master/d9/d0c/group__calib3d.html"
/// target="_blank">OpenCV documentation (Section 'Detailed Description')</a>.
///
/// \tparam Real floating point type that determines the precision of the
/// calculations.
/// \sa is_intrinsic_v
template <typename Real = float>
class pinhole {
public:
static_assert(std::is_floating_point_v<Real>);
using real_type = Real;
pinhole() = default;
/// Initialize the pinhole model with it's essential parameters.
/// \param w,h image dimensions
/// \param fx,fy focal point
/// \param cx,cy image center
pinhole(int w, int h, Real fx, Real fy, Real cx, Real cy) noexcept
: _w(w)
, _h(h)
, _fx(fx)
, _fy(fy)
, _cx(cx)
, _cy(cy) {
Expects(w > 0);
Expects(h > 0);
Expects(_fx > Real(0.));
Expects(_fy > Real(0.));
Expects(_cx > Real(0.));
Expects(_cy > Real(0.));
}
/// Return the width of the image corresponding to this calibration.
[[nodiscard]] int w() const noexcept { return _w; }
/// Return the height of the image corresponding to this calibration.
[[nodiscard]] int h() const noexcept { return _h; }
/// Return the x-component of the focal point.
[[nodiscard]] Real fx() const noexcept { return _fx; }
/// Return the y-component of the focal point.
[[nodiscard]] Real fy() const noexcept { return _fy; }
/// Return the x-component of the image center.
[[nodiscard]] Real cx() const noexcept { return _cx; }
/// Return the y-component of the image center.
[[nodiscard]] Real cy() const noexcept { return _cy; }
template <typename Number = int>
[[nodiscard]] math::image_coord<Real>
transform_to_image(const math::pixel_coord<Number>& p) const noexcept;
/// This methods calculates the inverse projection of the camera model
/// to get the direction of the lightray for the pixel at \p p.
///
/// \tparam _Real either integer or floating point value for pixel or
/// subpixel precision
/// \param p non-negative pixel coordinates
/// \warning This does not respect a distortion model at all!
/// \pre \p fx > 0
/// \pre \p fy > 0
/// \pre \p cx > 0
/// \pre \p cy > 0
/// \pre \p p1 == \p p2 == \p k1 == \p k2 == \p k3 == 0!!
/// \post \f$\lVert result \rVert_2 = 1.\f$
/// \returns normalized vector in camera coordinates
/// \note if \p _Real is an integer-type the value is itself backprojected,
/// which usually means the bottom left corner of the pixel and __NOT__
/// its center!
template <typename _Real = int>
[[nodiscard]] math::sphere_coord<Real>
pixel_to_sphere(const math::pixel_coord<_Real>& p) const noexcept;
/// The same as \p project_to_sphere but the coordinate is already
/// in the image frame of reference.
/// \sa pinhole::project_to_sphere
[[nodiscard]] math::sphere_coord<Real>
image_to_sphere(const math::image_coord<Real>& p) const noexcept;
/// Project points in camera coordinates to pixel coordinates.
/// \note if the point can not be projected (\c p.z() == 0) the pixel
/// coordinate {-1, -1} is returned.
/// \sa pinhole::project_to_sphere
template <typename _Real = Real>
[[nodiscard]] math::pixel_coord<_Real>
camera_to_pixel(const math::camera_coord<Real>& p) const noexcept;
private:
int _w = 0; ///< width of the image
int _h = 0; ///< height of the image
Real _fx = 0.0; ///< x-coordinate of focal length
Real _fy = 0.0; ///< y-corrdiante of focal length
Real _cx = 0.0; ///< x-coordinate of image center
Real _cy = 0.0; ///< y-coordinate of image center
Real p1 = 0.0; ///< first order tangential distortion coefficient
Real p2 = 0.0; ///< second order tangential distortion coefficient
Real k1 = 0.0; ///< first order radial distortion coefficient
Real k2 = 0.0; ///< second order radial distortion coefficient
Real k3 = 0.0; ///< third order radial distortion coefficient
};
template <typename Real>
template <typename _Real>
math::image_coord<Real>
pinhole<Real>::transform_to_image(const math::pixel_coord<_Real>& p) const
noexcept {
static_assert(std::is_arithmetic_v<_Real>);
Expects(_fx > 0.);
Expects(_fy > 0.);
Expects(_cx > 0.);
Expects(_cy > 0.);
Expects(p1 == 0.);
Expects(p2 == 0.);
Expects(k1 == 0.);
Expects(k2 == 0.);
Expects(k3 == 0.);
Expects(p.u() >= 0.);
Expects(p.u() < w());
Expects(p.v() >= 0.);
Expects(p.v() < h());
return math::image_coord<Real>((p.u() - _cx) / _fx, (p.v() - _cy) / _fy);
}
template <typename Real>
template <typename _Real>
inline math::sphere_coord<Real>
pinhole<Real>::pixel_to_sphere(const math::pixel_coord<_Real>& p) const
noexcept {
static_assert(std::is_arithmetic_v<_Real>);
return image_to_sphere(transform_to_image(p));
}
template <typename Real>
inline math::sphere_coord<Real>
pinhole<Real>::image_to_sphere(const math::image_coord<Real>& p) const
noexcept {
const double x = p.x();
const double y = p.y();
const double z = 1.;
const double cse = 1. + x * x + y * y;
const double factor = 1. / std::sqrt(cse);
using gsl::narrow_cast;
math::sphere_coord<Real> res(narrow_cast<Real>(factor * x),
narrow_cast<Real>(factor * y),
narrow_cast<Real>(factor * z));
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
Ensures(std::abs(res.norm() - 1.) < 0.000001);
return res;
}
template <typename Real>
template <typename _Real>
math::pixel_coord<_Real>
pinhole<Real>::camera_to_pixel(const math::camera_coord<Real>& p) const
noexcept {
static_assert(std::is_arithmetic_v<_Real>);
Expects(fx() > 0.);
Expects(fy() > 0.);
Expects(cx() > 0.);
Expects(cy() > 0.);
Expects(p1 == 0.);
Expects(p2 == 0.);
Expects(k1 == 0.);
Expects(k2 == 0.);
Expects(k3 == 0.);
if (p.Z() == Real(0.0))
return {_Real(-1), _Real(-1)};
const math::image_coord<Real> i{p.X() / p.Z(), p.Y() / p.Z()};
const auto u = gsl::narrow_cast<_Real>(fx() * i.x() + cx());
const auto v = gsl::narrow_cast<_Real>(fy() * i.y() + cy());
if (u < _Real(0.0) || u > gsl::narrow_cast<Real>(w()) || v < _Real(0.0) ||
v > gsl::narrow_cast<Real>(h()))
return {_Real(-1), _Real(-1)};
return {u, v};
}
} // namespace camera_models
} // namespace sens_loc
#endif /* end of include guard: PINHOLE_H_I3RZULX9 */
| {
"alphanum_fraction": 0.6279298246,
"avg_line_length": 34.5873786408,
"ext": "h",
"hexsha": "b28fabce0e3550de8bf384e5b9e17b2452c3eca6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "JonasToth/depth-conversions",
"max_forks_repo_path": "src/include/sens_loc/camera_models/pinhole.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "JonasToth/depth-conversions",
"max_issues_repo_path": "src/include/sens_loc/camera_models/pinhole.h",
"max_line_length": 79,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "JonasToth/depth-conversions",
"max_stars_repo_path": "src/include/sens_loc/camera_models/pinhole.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z",
"num_tokens": 1991,
"size": 7125
} |
/*This program is the first step in solving the Merlin-Salgado equation.
It produces a .dat file with the scale factor in terms of the conformal time and the cosmic time.
The .dat file columns are formatted in the next way:
cosmic_time conformal_fime scale_factor cosmic_time_der_scale_factor*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#define NLINES 11
#define H0 0.1 //Hubble paramater
#define OMEGAMAT 0.3 //Omega matter
#define OMEGALAM 0.7 //Omega lambda
/*Structure with parameters needed for the function to integrate
hubble: The Hubble parameter
omega_m: Density parameter for matter (dark matter and baryonic)
omega_l: Density parameter for dark energy*/
struct Iparams
{
double hubble;
double omega_m;
double omega_l;
};
/*This function multiplied by the differential of the scale factor is the differential of cosmic time*/
double integrando_cosmictime(double a, void *parameters)
{
struct Iparams *p = (struct Iparams *) parameters; //Structure of parameters
double h0 = p->hubble;
double om = p->omega_m;
double ol = p->omega_l;
double f = (1/h0)/(sqrt(om*pow(a,-1) + ol*pow(a,2))); //Integrate to cosmic time
return f;
}
/*This function multiplied by the differential of the scale factor is the differential of conformal time*/
double integrando_conformaltime(double a, void *parameters)
{
struct Iparams *p = (struct Iparams *) parameters; //Structure of parameters
double h0 = p->hubble;
double om = p->omega_m;
double ol = p->omega_l;
double f = (1/h0)/(sqrt(om*a + ol*pow(a,4))); //Integrate to conformal time
return f;
}
/*Derivative of the scale factor as a function of scale factor*/
double der_scale_factor(double a)
{
double adot = H0*sqrt(OMEGAMAT*pow(a,-1)+OMEGALAM*pow(a,2));
return adot;
}
int main (void)
{
/*Variable for temporary saving derivative of scale factor in interations*/
double adot;
struct Iparams parameters; // Structure of parameters for functions to integrate
/*Asign values to the structure of parameters*/
parameters.hubble = H0;
parameters.omega_m = OMEGAMAT;
parameters.omega_l = OMEGALAM;
/*File to be written with data*/
FILE *pf;
pf = fopen("scale_factor.dat","w");
/*GSL object. Necessary object to separate enough space in memory for integration. 1 and 2 refer to cosmic and conformal time respectively*/
gsl_integration_workspace *w1;
gsl_integration_workspace *w2;
/*result: Result of integration. error: Maximum relative error. 1 and 2 refer to cosmic and conformal time respectively*/
double result1, result2, error1, error2, epsrel = 1.0e-11;
size_t limit = 1000; //Maximum number of subintervals for integration
/*a: Inferior integration limit. b: Superior integration limit*/
double a = 0.0, b = 0.0;
/*GSL object. Contain all information about the integrand.*/
gsl_function Fcosmic, Fconformal;
/*Defining Fcosmic*/
Fcosmic.function = &integrando_cosmictime;
Fcosmic.params = ¶meters;
/*Defining Fconformal*/
Fconformal.function = &integrando_conformaltime;
Fconformal.params = ¶meters;
/*Allocate space in memory*/
w1 = gsl_integration_workspace_alloc(limit);
w2 = gsl_integration_workspace_alloc(limit);
for(b = 0.0001;b <= 1.0;b += 0.0001)
{
/*Numerical integration of functions*/
gsl_integration_qags(&Fcosmic, a, b, 0, epsrel, limit, w1, &result1, &error1);
gsl_integration_qags(&Fconformal, a, b, 0, epsrel, limit, w2, &result2, &error2);
adot = der_scale_factor(b);
fprintf(pf, "%.12f %.12f %.12f %.12f\n", result1, result2, b, adot);
}
/*Close streams and free space in memory*/
fclose(pf);
gsl_integration_workspace_free(w1);
gsl_integration_workspace_free(w2);
}
| {
"alphanum_fraction": 0.7225721785,
"avg_line_length": 33.4210526316,
"ext": "c",
"hexsha": "b4b0a3a47866bdbded83e16e74f31fba1ae1ed36",
"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": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CesarArroyo09/light_geodesics_thesis",
"max_forks_repo_path": "scale_factor.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68",
"max_issues_repo_issues_event_max_datetime": "2016-09-19T20:33:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-05-26T05:36:42.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "CesarArroyo09/light_geodesics_thesis",
"max_issues_repo_path": "scale_factor.c",
"max_line_length": 142,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CesarArroyo09/light_geodesics_thesis",
"max_stars_repo_path": "scale_factor.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-21T03:59:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-21T03:59:02.000Z",
"num_tokens": 1050,
"size": 3810
} |
/* Odeint solver */
#include <pygsl/utils.h>
#include <pygsl/block_helpers.h>
#include <pygsl/error_helpers.h>
#include <Python.h>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_errno.h>
char odeiv_module_doc[] = "XXX odeiv module doc missing!\n";
static char this_file[] = __FILE__;
static PyObject *module = NULL; /* set by initodeiv */
static void /* generic instance destruction */
generic_dealloc (PyObject *self)
{
DEBUG_MESS(1, " *** generic_dealloc %p\n", (void *) self);
PyMem_Free(self);
}
typedef struct {
PyObject_HEAD
gsl_odeiv_step * step;
gsl_odeiv_system system;
PyObject *py_func;
PyObject *py_jac;
PyObject *arguments;
jmp_buf buffer;
}
PyGSL_odeiv_step;
typedef struct {
PyObject_HEAD
PyGSL_odeiv_step * step;
gsl_odeiv_control * control;
} PyGSL_odeiv_control;
typedef struct {
PyObject_HEAD
PyGSL_odeiv_step * step;
PyGSL_odeiv_control * control;
gsl_odeiv_evolve * evolve;
} PyGSL_odeiv_evolve;
typedef struct {
PyObject_HEAD
gsl_odeiv_step_type * step_type;
} PyGSL_odeiv_step_type;
typedef struct {
PyObject_HEAD
gsl_odeiv_control_type * control_type;
} PyGSL_odeiv_control_type;
/*---------------------------------------------------------------------------
* Declaration of the various Methods
*---------------------------------------------------------------------------*/
/*
* stepper
*/
static int
PyGSL_odeiv_func(double t, const double y[], double f[], void *params);
static int
PyGSL_odeiv_jac(double t, const double y[], double *dfdy, double dfdt[],
void *params);
static PyObject *
PyGSL_odeiv_step_apply(PyGSL_odeiv_step *self, PyObject *args);
static PyObject *
PyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args);
static void
PyGSL_odeiv_step_free(PyGSL_odeiv_step * self);
static PyObject *
PyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args);
static PyObject *
PyGSL_odeiv_step_order(PyGSL_odeiv_step *self, PyObject *args);
/*
* control
*/
static PyObject *
PyGSL_odeiv_control_hadjust(PyGSL_odeiv_control *self, PyObject *args);
static void
PyGSL_odeiv_control_free(PyGSL_odeiv_control * self);
static PyObject *
PyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args);
/*
* evolve
*/
static void
PyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self);
static PyObject *
PyGSL_odeiv_evolve_apply(PyGSL_odeiv_evolve *self, PyObject *args);
static PyObject *
PyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args);
/*---------------------------------------------------------------------------*/
static char PyGSL_odeiv_step_type_doc[] = "A odeiv step type\n";
static char PyGSL_odeiv_control_type_doc[] = "A odeiv control type\n";
static char PyGSL_odeiv_evolve_type_doc[] = "A odeiv evolve type\n";
#define PyGSL_ODEIV_GENERIC_TYPE_PYTYPE_ALL \
static PyTypeObject PyGSL_ODEIV_GENERIC_TYPE_PYTYPE = { \
PyObject_HEAD_INIT(NULL) /* fix up the type slot in initodeiv */ \
0, /* ob_size */ \
PyGSL_ODEIV_GENERIC_TYPE_NAME, /* tp_name */ \
sizeof(PyGSL_ODEIV_GENERIC_TYPE), /* tp_basicsize */ \
0, /* tp_itemsize */ \
\
/* standard methods */ \
(destructor) generic_dealloc, /* tp_dealloc ref-count==0 */ \
(printfunc) 0, /* tp_print "print x" */ \
(getattrfunc) 0, /* tp_getattr "x.attr" */ \
(setattrfunc) 0, /* tp_setattr "x.attr=v" */ \
(cmpfunc) 0, /* tp_compare "x > y" */ \
(reprfunc) 0, /* tp_repr `x`, print x */ \
\
/* type categories */ \
0, /* tp_as_number +,-,*,/,%,&,>>,pow...*/ \
0, /* tp_as_sequence +,[i],[i:j],len, ...*/ \
0, /* tp_as_mapping [key], len, ...*/ \
\
/* more methods */ \
(hashfunc) 0, /* tp_hash "dict[x]" */ \
(ternaryfunc) 0, /* tp_call "x()" */ \
(reprfunc) 0, /* tp_str "str(x)" */ \
(getattrofunc) 0, /* tp_getattro */ \
(setattrofunc) 0, /* tp_setattro */ \
0, /* tp_as_buffer */ \
0L, /* tp_flags */ \
PyGSL_ODEIV_GENERIC_TYPE_DOC /* tp_doc */ \
};
#define PyGSL_ODEIV_GENERIC_TYPE PyGSL_odeiv_step_type
#define PyGSL_ODEIV_GENERIC_TYPE_PYTYPE PyGSL_odeiv_step_type_pytype
#define PyGSL_ODEIV_GENERIC_TYPE_NAME "PyGSL_odeiv_step_type"
#define PyGSL_ODEIV_GENERIC_TYPE_DOC PyGSL_odeiv_step_type_doc
PyGSL_ODEIV_GENERIC_TYPE_PYTYPE_ALL
#undef PyGSL_ODEIV_GENERIC_TYPE
#undef PyGSL_ODEIV_GENERIC_TYPE_PYTYPE
#undef PyGSL_ODEIV_GENERIC_TYPE_NAME
#undef PyGSL_ODEIV_GENERIC_TYPE_DOC
#define PyGSL_ODEIV_GENERIC_TYPE PyGSL_odeiv_control_type
#define PyGSL_ODEIV_GENERIC_TYPE_PYTYPE PyGSL_odeiv_control_type_pytype
#define PyGSL_ODEIV_GENERIC_TYPE_NAME "PyGSL_odeiv_control_type"
#define PyGSL_ODEIV_GENERIC_TYPE_DOC PyGSL_odeiv_control_type_doc
PyGSL_ODEIV_GENERIC_TYPE_PYTYPE_ALL
#define PyGSLOdeivStepType_Check(v) ((v)->ob_type == &PyGSL_odeiv_step_type_pytype)
#define PyGSLOdeivControlType_Check(v) ((v)->ob_type == &PyGSL_odeiv_control_type_pytype)
#define PyGSLOdeivEvolveType_Check(v) ((v)->ob_type == &PyGSL_odeiv_evolve_type_pytype)
#define PyGSL_ODEIV_GENERIC_ALL \
static PyObject * \
PyGSL_ODEIV_GENERIC_GETATTR(PyGSL_ODEIV_GENERIC *self, char *name) \
{ \
PyObject *tmp = NULL; \
\
FUNC_MESS_BEGIN(); \
\
tmp = Py_FindMethod(PyGSL_ODEIV_GENERIC_METHODS, (PyObject *) self, name); \
if(NULL == tmp){ \
PyGSL_add_traceback(module, __FILE__, "odeiv.__attr__", __LINE__ - 1); \
return NULL; \
} \
return tmp; \
} \
static PyTypeObject PyGSL_ODEIV_GENERIC_PYTYPE = { \
PyObject_HEAD_INIT(NULL) /* fix up the type slot in initcrng */ \
0, /* ob_size */ \
PyGSL_ODEIV_GENERIC_NAME, /* tp_name */ \
sizeof(PyGSL_ODEIV_GENERIC), /* tp_basicsize */ \
0, /* tp_itemsize */ \
\
/* standard methods */ \
(destructor) PyGSL_ODEIV_GENERIC_DELETE, /* tp_dealloc ref-count==0 */ \
(printfunc) 0, /* tp_print "print x" */ \
(getattrfunc) PyGSL_ODEIV_GENERIC_GETATTR, /* tp_getattr "x.attr" */ \
(setattrfunc) 0, /* tp_setattr "x.attr=v" */ \
(cmpfunc) 0, /* tp_compare "x > y" */ \
(reprfunc) 0, /* tp_repr `x`, print x */ \
\
/* type categories */ \
0, /* tp_as_number +,-,*,/,%,&,>>,pow...*/ \
0, /* tp_as_sequence +,[i],[i:j],len, ...*/ \
0, /* tp_as_mapping [key], len, ...*/ \
\
/* more methods */ \
(hashfunc) 0, /* tp_hash "dict[x]" */ \
(ternaryfunc) 0, /* tp_call "x()" */ \
(reprfunc) 0, /* tp_str "str(x)" */ \
(getattrofunc) 0, /* tp_getattro */ \
(setattrofunc) 0, /* tp_setattro */ \
0, /* tp_as_buffer */ \
0L, /* tp_flags */ \
PyGSL_ODEIV_GENERIC_DOC /* doc */ \
};
#define PyGSL_ODEIV_GENERIC PyGSL_odeiv_step
#define PyGSL_ODEIV_GENERIC_NAME "PyGSL_odeiv_step"
#define PyGSL_ODEIV_GENERIC_PYTYPE PyGSL_odeiv_step_pytype
#define PyGSL_ODEIV_GENERIC_DOC PyGSL_odeiv_step_doc
#define PyGSL_ODEIV_GENERIC_GETATTR PyGSL_odeiv_step_getattr
#define PyGSL_ODEIV_GENERIC_METHODS PyGSL_odeiv_step_methods
#define PyGSL_ODEIV_GENERIC_DELETE PyGSL_odeiv_step_free
PyGSL_ODEIV_GENERIC_ALL
/**/;
#undef PyGSL_ODEIV_GENERIC
#undef PyGSL_ODEIV_GENERIC_NAME
#undef PyGSL_ODEIV_GENERIC_PYTYPE
#undef PyGSL_ODEIV_GENERIC_DOC
#undef PyGSL_ODEIV_GENERIC_GETATTR
#undef PyGSL_ODEIV_GENERIC_METHODS
#undef PyGSL_ODEIV_GENERIC_DELETE
#define PyGSL_ODEIV_GENERIC PyGSL_odeiv_control
#define PyGSL_ODEIV_GENERIC_NAME "PyGSL_odeiv_control"
#define PyGSL_ODEIV_GENERIC_PYTYPE PyGSL_odeiv_control_pytype
#define PyGSL_ODEIV_GENERIC_DOC PyGSL_odeiv_control_doc
#define PyGSL_ODEIV_GENERIC_GETATTR PyGSL_odeiv_control_getattr
#define PyGSL_ODEIV_GENERIC_METHODS PyGSL_odeiv_control_methods
#define PyGSL_ODEIV_GENERIC_DELETE PyGSL_odeiv_control_free
PyGSL_ODEIV_GENERIC_ALL
/**/;
#undef PyGSL_ODEIV_GENERIC
#undef PyGSL_ODEIV_GENERIC_NAME
#undef PyGSL_ODEIV_GENERIC_PYTYPE
#undef PyGSL_ODEIV_GENERIC_DOC
#undef PyGSL_ODEIV_GENERIC_GETATTR
#undef PyGSL_ODEIV_GENERIC_METHODS
#undef PyGSL_ODEIV_GENERIC_DELETE
#define PyGSL_ODEIV_GENERIC PyGSL_odeiv_evolve
#define PyGSL_ODEIV_GENERIC_NAME "PyGSL_odeiv_evolve"
#define PyGSL_ODEIV_GENERIC_PYTYPE PyGSL_odeiv_evolve_pytype
#define PyGSL_ODEIV_GENERIC_DOC PyGSL_odeiv_evolve_doc
#define PyGSL_ODEIV_GENERIC_GETATTR PyGSL_odeiv_evolve_getattr
#define PyGSL_ODEIV_GENERIC_METHODS PyGSL_odeiv_evolve_methods
#define PyGSL_ODEIV_GENERIC_DELETE PyGSL_odeiv_evolve_free
PyGSL_ODEIV_GENERIC_ALL
/**/;
static void
PyGSL_odeiv_step_free(PyGSL_odeiv_step * self)
{
assert(PyGSL_ODEIV_STEP_Check(self));
Py_DECREF(self->py_func);
Py_XDECREF(self->py_jac);
Py_DECREF(self->arguments);
gsl_odeiv_step_free(self->step);
PyMem_Free(self);
}
static PyObject *
PyGSL_odeiv_step_reset(PyGSL_odeiv_step *self, PyObject *args)
{
assert(PyGSL_ODEIV_STEP_Check(self));
gsl_odeiv_step_reset(self->step);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
PyGSL_odeiv_step_name(PyGSL_odeiv_step *self, PyObject *args)
{
assert(PyGSL_ODEIV_STEP_Check(self));
return PyString_FromString(gsl_odeiv_step_name(self->step));
}
{
assert(PyGSL_ODEIV_STEP_Check(self));
return PyInt_FromLong((long) gsl_odeiv_step_order(self->step));
}
/* --------------------------------------------------------------------------- */
/* control_hadjust needs a few arrays */
/*
extern int
gsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s,
const double y0[], const double yerr[],
const double dydt[], double * h);
*/
static void
PyGSL_odeiv_control_free(PyGSL_odeiv_control * self)
{
assert(PyGSL_ODEIV_CONTROL_Check(self));
Py_DECREF(self->step);
//gsl_odeiv_control_free(self->control);
PyMem_Free(self);
}
static PyObject *
PyGSL_odeiv_control_name(PyGSL_odeiv_control *self, PyObject *args)
{
assert(PyGSL_ODEIV_CONTROL_Check(self));
return PyString_FromString(gsl_odeiv_control_name(self->control));
}
static void
PyGSL_odeiv_evolve_free(PyGSL_odeiv_evolve * self)
{
assert(PyGSL_ODEIV_EVOLVE_Check(self));
Py_DECREF(self->step);
Py_DECREF(self->control);
gsl_odeiv_evolve_free(self->evolve);
PyMem_Free(self);
}
static PyObject *
PyGSL_odeiv_evolve_reset(PyGSL_odeiv_evolve *self, PyObject *args)
{
assert(PyGSL_ODEIV_EVOLVE_Check(self));
gsl_odeiv_evolve_reset(self->evolve);
Py_INCREF(Py_None);
return Py_None;
}
#if 0
static
void create_odeiv_step_types(PyObject *module_dict)
{
PyGSL_odeiv_step_type *a_odeiv_step = NULL;
PyObject *item=NULL;
gsl_odeiv_step_type ** thistype;
gsl_odeiv_step_type const * const step_types[] ={
gsl_odeiv_step_rk2,
gsl_odeiv_step_rk4,
gsl_odeiv_step_rkf45,
gsl_odeiv_step_rkck,
gsl_odeiv_step_rk8pd,
gsl_odeiv_step_rk2imp,
gsl_odeiv_step_rk4imp,
gsl_odeiv_step_bsimp,
gsl_odeiv_step_gear1,
gsl_odeiv_step_gear2,
NULL
};
FUNC_MESS_BEGIN();
thistype = (gsl_odeiv_step_type **) step_types;
while((*thistype) != NULL){
a_odeiv_step = PyObject_NEW(PyGSL_odeiv_step_type, &PyGSL_odeiv_step_type_pytype);
assert(a_odeiv_step);
a_odeiv_step->step_type = (gsl_odeiv_step_type *) *thistype;
item = PyString_FromString((*thistype)->name);
DEBUG_MESS(2, "Preparing step type -->%s<--", PyString_AsString(item));
PyGSL_clear_name(PyString_AsString(item), PyString_Size(item));
DEBUG_MESS(2, "Adding step type -->%s<--", PyString_AsString(item));
assert(item);
PyDict_SetItem(module_dict, item, (PyObject *) a_odeiv_step);
/* Py_DECREF(item); */
item = NULL;
thistype++;
}
FUNC_MESS_END();
}
#endif
static PyMethodDef PyGSL_odeiv_module_functions[] = {
{"step_rk2", PyGSL_odeiv_step_init_rk2, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk4", PyGSL_odeiv_step_init_rk4, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rkf45", PyGSL_odeiv_step_init_rkf45, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rkck", PyGSL_odeiv_step_init_rkck, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk8pd", PyGSL_odeiv_step_init_rk8pd, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk2imp", PyGSL_odeiv_step_init_rk2imp, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_rk4imp", PyGSL_odeiv_step_init_rk4imp, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_bsimp", PyGSL_odeiv_step_init_bsimp, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_gear1", PyGSL_odeiv_step_init_gear1, METH_VARARGS|METH_KEYWORDS, NULL},
{"step_gear2", PyGSL_odeiv_step_init_gear2, METH_VARARGS|METH_KEYWORDS, NULL},
{"control_standard_new", PyGSL_odeiv_control_init_standard_new, METH_VARARGS, NULL},
{"control_y_new", PyGSL_odeiv_control_init_y_new, METH_VARARGS, NULL},
{"control_yp_new", PyGSL_odeiv_control_init_yp_new, METH_VARARGS, NULL},
{"evolve", PyGSL_odeiv_evolve_init, METH_VARARGS, NULL},
{NULL, NULL, 0} /* Sentinel */
};
void
initodeiv(void)
{
PyObject *m=NULL, *item=NULL, *dict=NULL;
FUNC_MESS_BEGIN();
fprintf(stderr, "Compiled at %s %s\n", __DATE__, __TIME__);
m = Py_InitModule("odeiv", PyGSL_odeiv_module_functions);
assert(m);
module = m;
import_array();
init_pygsl();
PyGSL_odeiv_step_type_pytype.ob_type = &PyType_Type;
PyGSL_odeiv_control_type_pytype.ob_type = &PyType_Type;
PyGSL_odeiv_step_pytype.ob_type = &PyType_Type;
PyGSL_odeiv_control_pytype.ob_type = &PyType_Type;
PyGSL_odeiv_evolve_pytype.ob_type = &PyType_Type;
dict = PyModule_GetDict(m);
/* create_odeiv_step_types(dict); */
if(!dict)
goto fail;
if (!(item = PyString_FromString(odeiv_module_doc))){
PyErr_SetString(PyExc_ImportError,
"I could not generate module doc string!");
goto fail;
}
if (PyDict_SetItemString(dict, "__doc__", item) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not init doc string!");
goto fail;
}
FUNC_MESS_END();
return;
fail:
FUNC_MESS("Fail");
fprintf(stderr, "Import of module odeiv failed!\n");
}
| {
"alphanum_fraction": 0.6543136868,
"avg_line_length": 34.1233183857,
"ext": "c",
"hexsha": "639f8d785c9647ec0b184433c005d64be88bf22b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old.c",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/old/odeiv_old.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4537,
"size": 15219
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_histogram2d.h>
#include <gsl/gsl_errno.h>
int mgsl_histogram_fwrite(const char *filename, const gsl_histogram *h)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_histogram_fwrite(fp, h) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_histogram_fread(const char *filename, gsl_histogram *h)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_histogram_fread(fp, h) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_histogram_fprintf(const char *filename, const gsl_histogram *h, const char *range_format, const char *bin_format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_histogram_fprintf(fp, h, range_format, bin_format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_histogram_fscanf(const char *filename, gsl_histogram *h)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_histogram_fscanf(fp, h) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_histogram2d_fwrite(const char *filename, const gsl_histogram2d *h)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_histogram2d_fwrite(fp, h) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_histogram2d_fread(const char *filename, gsl_histogram2d *h)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_histogram2d_fread(fp, h) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_histogram2d_fprintf(const char *filename, const gsl_histogram2d *h, const char *range_format, const char *bin_format)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_histogram2d_fprintf(fp, h, range_format, bin_format) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_histogram2d_fscanf(const char *filename, gsl_histogram2d *h)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_histogram2d_fscanf(fp, h) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.7248927039,
"avg_line_length": 29.8717948718,
"ext": "c",
"hexsha": "f8f3a850ce81db515eef0731f2ae8d367e6e5fa9",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-05T07:22:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-05T07:22:44.000Z",
"max_forks_repo_head_hexsha": "7c17262fbc4e5cdf693a97291336a8d7d54c9eca",
"max_forks_repo_licenses": [
"Artistic-2.0"
],
"max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Histograms",
"max_forks_repo_path": "src/histogram.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "7c17262fbc4e5cdf693a97291336a8d7d54c9eca",
"max_issues_repo_issues_event_max_datetime": "2022-02-05T09:15:08.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-05T09:15:08.000Z",
"max_issues_repo_licenses": [
"Artistic-2.0"
],
"max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Histograms",
"max_issues_repo_path": "src/histogram.c",
"max_line_length": 126,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7c17262fbc4e5cdf693a97291336a8d7d54c9eca",
"max_stars_repo_licenses": [
"Artistic-2.0"
],
"max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Histograms",
"max_stars_repo_path": "src/histogram.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 671,
"size": 2330
} |
#ifndef __MAIN_H__
#define __MAIN_H__ 1
#ifdef PARALLEL
#include "mpi.h"
#endif
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <gsl/gsl_randist.h>
//#include "NNopt.h"
#include "bambi.h"
#ifdef __INTEL_COMPILER // if the MultiNest library was compiled with ifort
#define NESTRUN nested_mp_nestrun_
#elif defined __GNUC__ // if the MultiNest library was compiled with gfortran
#define NESTRUN __nested_MOD_nestrun
#else
#error Do not know how to link to Fortran libraries, check symbol table for your platform (nm libnest3.a | grep nestrun) & edit example_eggbox_C++/eggbox.cc
#endif
extern float thL[3],logLRange,tol;
extern float *omicron;
extern double *maxsigma;
extern double logZero;
extern int nNN,nNNerr,totpar,loglcalls,ncheck,myid,nproc;
extern char root[100],networkinputs[100];
extern bool likenetinit,converged,lastconverged,netres,firstrun,discardpts;
extern int ignoredbambicalls,counter;
extern size_t nlayers,nnodes[10];
extern int doBAMBI,useNN,whitenin,whitenout,resume;
/***************************************** C++ Interface to MultiNest **************************************************/
namespace nested
{
// map the Fortran 90 entry points of libnest3.a to C++ functions
// module nested, function nestRun maps to nested::run
// the pass-by-reference nature of most of the Fortran is translated away
// *apart* from the callbacks. The provided call back functions must still accept
// references rather than values. There is also some confusion as to the type
// of the first argument of LogLike.
// Should it be a double * or an farray<double, 1> *? The former seems to
// work and is simpler.
// This structure is reverse engineered from looking
// at gfortran stack traces. It is probably wrong
template<typename type, int ndims> class farray_traits;
template<> class farray_traits<double, 1> { public: static const int id = 537; };
template<> class farray_traits<double, 2> { public: static const int id = 538; };
template<> class farray_traits<int, 1> { public: static const int id = 265; };
template<> class farray_traits<int, 2> { public: static const int id = 266; };
// the extra data for f90 that defines how arrays are arranged.
template<typename T, int ndim> class farray
{
public:
farray(T *_data, int w, int h = 0) : data(_data), offset(0), type(farray_traits<T, ndim>::id),
x_stride(1), x_lbound(1), x_ubound(w), y_stride(w), y_lbound(1), y_ubound(h) {};
T *data;
int offset;
int type;
int x_stride, x_lbound, x_ubound;
int y_stride, y_lbound, y_ubound;
};
extern "C" {
void NESTRUN(int &mmodal, int &ceff, int &nlive, double &tol, double &efr, int &ndims,
int &nPar, int &nClsPar, int &maxModes, int &updInt, double &Ztol, char *root, int &seed,
int *pWrap, int &fb, int &resume, int &outfile, int &initMPI, double &logZero, int &maxiter,
void (*Loglike)(double *Cube, int &n_dim, int &n_par, double &lnew, void *),
void (*dumper)(int &, int &, int &, double **, double **, double **, double &, double &, double &, void *),
void (*bambi)(int &, int &, double **, double &), void *context, int &root_len);
}
static void run(bool mmodal, bool ceff, int nlive, double tol, double efr, int ndims, int nPar, int nClsPar, int maxModes,
int updInt, double Ztol, const std::string & root, int seed, int *pWrap, bool fb, bool resume, bool outfile,
bool initMPI, double logZero, int maxiter, void (*LogLike)(double *Cube, int &n_dim, int &n_par, double &lnew, void *),
void (*dumper)(int &, int &, int &, double **, double **, double **, double &, double &, double &, void *),
void (*bambi)(int &, int &, double **, double &), void *context)
{
char t_root[100];
std::fill(t_root, t_root + 100, ' ');
snprintf(t_root, 99, "%s", root.c_str());
int root_len = strlen(t_root);
t_root[strlen(t_root)] = ' ';
int t_fb = fb;
int t_resume = resume;
int t_outfile = outfile;
int t_initMPI = initMPI;
int t_mmodal = mmodal;
int t_ceff = ceff;
NESTRUN(t_mmodal, t_ceff, nlive, tol, efr, ndims, nPar, nClsPar, maxModes, updInt, Ztol, t_root, seed, pWrap, t_fb,
t_resume, t_outfile, t_initMPI, logZero, maxiter, LogLike, dumper, bambi, context, root_len);
}
}
/***********************************************************************************************************************/
#endif
| {
"alphanum_fraction": 0.6626966292,
"avg_line_length": 38.6956521739,
"ext": "h",
"hexsha": "0d7c26eaa948fd299c720ff32efd840857d50a42",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-03-12T13:20:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-03-06T20:20:40.000Z",
"max_forks_repo_head_hexsha": "cc6038c84b0e0366cfe0e4c6abb5b2dc640526f5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "anjmittu/SwiftGRB_PEanalysis-master",
"max_forks_repo_path": "src/main.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cc6038c84b0e0366cfe0e4c6abb5b2dc640526f5",
"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": "anjmittu/SwiftGRB_PEanalysis-master",
"max_issues_repo_path": "src/main.h",
"max_line_length": 163,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "cc6038c84b0e0366cfe0e4c6abb5b2dc640526f5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "anjmittu/SwiftGRB_PEanalysis-master",
"max_stars_repo_path": "src/main.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-19T12:24:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-04T18:20:32.000Z",
"num_tokens": 1296,
"size": 4450
} |
#ifndef DELTAFREADER_H
#define DELTAFREADER_H
#include "ParameterReader.h"
#include "readindata.h"
#include "GaussThermal.h"
#include <fstream>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp.h>
using namespace std;
class Deltaf_Data
{
private:
ParameterReader * paraRdr;
int hrg_eos; // type of pdg file for hadron resonance gas EoS
int mode; //type of freezeout surface, VH or VAH
int df_mode; // type of delta-f correction (e.g. 14-moment, CE, or modified distribution)
int include_baryon;
string hrg_eos_path;
string urqmd = "deltaf_coefficients/vh/urqmd/"; // directories of df coefficient tables
string smash = "deltaf_coefficients/vh/smash/";
string smash_box = "deltaf_coefficients/vh/smash_box/";
public:
int points_T;
int points_muB;
double T_min;
double muB_min;
double dT;
double dmuB;
double * T_array;
double * muB_array;
// Coefficients of 14 moment approximation (vhydro)
// df ~ ((c0-c2)m^2 + b.c1(u.p) + (4c2-c0)(u.p)^2).Pi + (b.c3 + c4(u.p))p_u.V^u + c5.p_u.p_v.pi^uv
double ** c0_data;
double ** c1_data;
double ** c2_data;
double ** c3_data;
double ** c4_data;
// Coefficients of Chapman Enskog expansion (vhydro)
// df ~ ((c0-c2)m^2 + b.c1(u.p) + (4c2-c0)(u.p)^2).Pi + (b.c3 + c4(u.p))p_u.V^u + c5.p_u.p_v.pi^uv
double ** F_data;
double ** G_data;
double ** betabulk_data;
double ** betaV_data;
double ** betapi_data;
// cubic splines of the coefficients as function of temperature only (neglect muB, nB, Vmu)
// (c1, G = 0) for muB = 0 and (c3, c4, betaV) aren't needed since they couple to baryon diffusion
// so in the cubic spline evaluation: just set (G, c1, c3, c4) = 0 and betaV = 1 (betaV is in denominator)
gsl_spline * c0_spline;
gsl_spline * c2_spline;
gsl_spline * c3_spline;
gsl_spline * F_spline;
gsl_spline * betabulk_spline;
gsl_spline * betaV_spline;
gsl_spline * betapi_spline;
// Jonah coefficients
const int jonah_points = 301; // # lambda interpolation points
const double lambda_min = -1.0; // lambda min / max values
const double lambda_max = 2.0;
const double delta_lambda = (lambda_max - lambda_min) / ((double)jonah_points - 1.0);
double * lambda_squared_array; // squared isotropic momentum scale
double * z_array; // renormalization factor (apart from detLambda)
double * bulkPi_over_Peq_array; // bulk pressure output
double bulkPi_over_Peq_max; // the maximum bulk pressure in the array
gsl_spline * lambda_squared_spline; // cubic splines for lambda^2(bulkPi/Peq) and z(bulkPi/Peq)
gsl_spline * z_spline;
Deltaf_Data(ParameterReader * paraRdr_in);
~Deltaf_Data();
void load_df_coefficient_data(); // read the data files in /deltaf_coefficients/vh
void construct_cubic_splines();
// I skip the photon because I think it breaks down for lambda = -1
void compute_jonah_coefficients(particle_info * particle_data, int Nparticle);
deltaf_coefficients evaluate_df_coefficients(double T, double muB, double E, double P, double bulkPi);
deltaf_coefficients cubic_spline(double T, double E, double P, double bulkPi);
double calculate_bilinear(double ** f_data, double T, double muB, double TL, double TR, double muBL, double muBR, int iTL, int iTR, int imuBL, int imuBR);
deltaf_coefficients bilinear_interpolation(double T, double muB, double E, double P, double bulkPi);
void test_df_coefficients(double bulkPi_over_P);
void compute_particle_densities(particle_info * particle_data, int Nparticle);
};
#endif
| {
"alphanum_fraction": 0.6429109159,
"avg_line_length": 36.5596330275,
"ext": "h",
"hexsha": "a9e990a24c9283955d966cf04a70ec1ca0cb3c33",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-13T21:36:16.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-13T21:36:16.000Z",
"max_forks_repo_head_hexsha": "231b8279554232e34946997776b513cfc5d84a39",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LipeiDu/iS3D2",
"max_forks_repo_path": "src/cpp/DeltafData.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "231b8279554232e34946997776b513cfc5d84a39",
"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": "LipeiDu/iS3D2",
"max_issues_repo_path": "src/cpp/DeltafData.h",
"max_line_length": 162,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "231b8279554232e34946997776b513cfc5d84a39",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LipeiDu/iS3D2",
"max_stars_repo_path": "src/cpp/DeltafData.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-08T21:26:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-08T21:26:12.000Z",
"num_tokens": 1098,
"size": 3985
} |
/* Copyright 2019-2020 Canaan Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "allocator.h"
#include "model.h"
#include "result.h"
#include "runtime_module.h"
#include <gsl/gsl-lite.hpp>
#include <memory>
#include <unordered_map>
BEGIN_NS_NNCASE_RUNTIME
class NNCASE_API options_dict
{
public:
template <class T>
result<T> get(const char *name)
{
auto it = values_.find(name);
if (it != values_.end())
return ok(it->second.as<T>());
else
return err(std::errc::result_out_of_range);
}
template <class T>
result<void> set(const char *name, T value)
{
values_[name] = scalar(value);
return ok();
}
private:
std::unordered_map<const char *, scalar> values_;
};
class NNCASE_API interpreter
{
public:
interpreter() noexcept;
interpreter(interpreter &) = delete;
interpreter(interpreter &&) = default;
NNCASE_NODISCARD result<void> load_model(gsl::span<const gsl::byte> buffer) noexcept;
size_t inputs_size() const noexcept;
size_t outputs_size() const noexcept;
const memory_range &input_desc(size_t index) const noexcept;
const memory_range &output_desc(size_t index) const noexcept;
const runtime_shape_t &input_shape(size_t index) const noexcept;
const runtime_shape_t &output_shape(size_t index) const noexcept;
result<runtime_tensor> input_tensor(size_t index) noexcept;
result<void> input_tensor(size_t index, runtime_tensor tensor) noexcept;
result<runtime_tensor> output_tensor(size_t index) noexcept;
result<void> output_tensor(size_t index, runtime_tensor tensor) noexcept;
result<void> run() noexcept;
result<runtime_module *> find_module_by_id(size_t index) noexcept;
options_dict &options() noexcept;
private:
std::vector<std::unique_ptr<runtime_module>> modules_;
runtime_module *main_module_;
options_dict options_;
};
END_NS_NNCASE_RUNTIME
| {
"alphanum_fraction": 0.716069271,
"avg_line_length": 30.2804878049,
"ext": "h",
"hexsha": "a068ba12cdecc781c4ed8a2a8e1c318d9971a571",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T09:48:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-21T01:27:37.000Z",
"max_forks_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "13129176346/nncase",
"max_forks_repo_path": "include/nncase/runtime/interpreter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d",
"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": "13129176346/nncase",
"max_issues_repo_path": "include/nncase/runtime/interpreter.h",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0ce252641826d65e12621347992cc9865874e6e1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "zhen8838/kendryte-standalone-sdk",
"max_stars_repo_path": "lib/nncase/v1/include/nncase/runtime/interpreter.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T09:53:44.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-31T09:53:44.000Z",
"num_tokens": 569,
"size": 2483
} |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Josef Gajdusek
*
* 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 <stdio.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multifit.h>
#include "log.h"
#include "coords.h"
static projPJ proj_wgs;
void init_projs()
{
proj_wgs = pj_init_plus("+init=epsg:4326");
}
cl_float2 wgs84_to_meters(cl_float2 wgs, projPJ proj_meters)
{
cl_float2 ret;
// The X and Ys are switched intentionally
double ry = wgs.x * DEG_TO_RAD;
double rx = wgs.y * DEG_TO_RAD;
int err = pj_transform(proj_wgs, proj_meters, 1, 1, &ry, &rx, NULL);
if (err) {
log_error("Coordinate conversion failed: %s", pj_strerrno(err));
}
ret.x = rx;
ret.y = ry;
return ret;
}
void generate_translation_tile(int xtile, int ytile, int zoom, cl_float4 *out, projPJ proj_meters)
{
int side = 20;
int npoints = side * side;
gsl_multifit_linear_workspace *gwsp = gsl_multifit_linear_alloc(npoints, 3);
gsl_vector *yx = gsl_vector_alloc(npoints);
gsl_vector *yy = gsl_vector_alloc(npoints);
gsl_matrix *X = gsl_matrix_alloc(npoints, 3);
gsl_vector *cx = gsl_vector_alloc(3);
gsl_vector *cy = gsl_vector_alloc(3);
gsl_matrix *cov = gsl_matrix_alloc(npoints, npoints);
double chisq;
// Generate side x side training points
for (int x = 0; x < side; x++) {
for (int y = 0; y < side; y++) {
cl_float2 tile = {.x = xtile + (double)x / side,
.y = ytile + (double)y / side};
cl_float2 wgs = tile_to_wgs84(tile, zoom);
cl_float2 mets = wgs84_to_meters(wgs, proj_meters);
int pt = x * side + y;
// Inputs
gsl_matrix_set(X, pt, 0, tile.x - xtile);
gsl_matrix_set(X, pt, 1, tile.y - ytile);
gsl_matrix_set(X, pt, 2, 1);
// Outputs
gsl_vector_set(yx, pt, mets.x);
gsl_vector_set(yy, pt, mets.y);
}
}
// Fit
gsl_multifit_linear(X, yx, cx, cov, &chisq, gwsp);
gsl_multifit_linear(X, yy, cy, cov, &chisq, gwsp);
gsl_matrix *mtrans = gsl_matrix_alloc(3, 2);
gsl_matrix_set_col(mtrans, 0, cx);
gsl_matrix_set_col(mtrans, 1, cy);
// Output
out[0].x = gsl_matrix_get(mtrans, 0, 0);
out[0].y = gsl_matrix_get(mtrans, 1, 0);
out[0].z = gsl_matrix_get(mtrans, 2, 0);
out[1].x = gsl_matrix_get(mtrans, 0, 1);
out[1].y = gsl_matrix_get(mtrans, 1, 1);
out[1].z = gsl_matrix_get(mtrans, 2, 1);
gsl_matrix_free(mtrans);
gsl_matrix_free(cov);
gsl_vector_free(cy);
gsl_vector_free(cx);
gsl_matrix_free(X);
gsl_vector_free(yy);
gsl_vector_free(yx);
gsl_multifit_linear_free(gwsp);
}
| {
"alphanum_fraction": 0.708743323,
"avg_line_length": 30.4017094017,
"ext": "c",
"hexsha": "ffb7541524ccd66aa868a27a01e41b86bf9e8973",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-07-29T06:28:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-07-29T06:28:25.000Z",
"max_forks_repo_head_hexsha": "84ce0fc1698fd7dd768f92ed3361b94ec9263773",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "atalax/cl-heatmap",
"max_forks_repo_path": "src/coords.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "84ce0fc1698fd7dd768f92ed3361b94ec9263773",
"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": "atalax/cl-heatmap",
"max_issues_repo_path": "src/coords.c",
"max_line_length": 98,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "84ce0fc1698fd7dd768f92ed3361b94ec9263773",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "atalax/cl-heatmap",
"max_stars_repo_path": "src/coords.c",
"max_stars_repo_stars_event_max_datetime": "2019-09-09T04:17:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-09T04:17:17.000Z",
"num_tokens": 1077,
"size": 3557
} |
#ifndef _ASA_H
#define _ASA_H
#include <iostream>
#include <memory>
#include <type_traits>
#include <vector>
#include <array>
#include <gsl/gsl_siman.h>
namespace gsl{
class SimulatedAnnealing{
public:
SimulatedAnnealing();
virtual ~SimulatedAnnealing();
typedef gsl_siman_params_t Parameters;
/* Struct defined in gsl/gsl_siman.h (gsl2.5) access on Jan 9, 2019 as:
* 51 typedef struct {
* 52 int n_tries; // how many points to try for each step
* 53 int iters_fixed_T; // how many iterations at each temperature?
* 54 double step_size; // max step size in the random walk
* 55 // the following parameters are for the Boltzmann distribution
* 56 double k, t_initial, mu_t, t_min;
* 57 } gsl_siman_params_t;
*/
protected:
const gsl_rng_type * workspace;
gsl_rng * randomNumberGenerator;
double (*energy) (void*);
double (*measure)(void*,
void*);
void (*step) (const gsl_rng*,
void*,
double);
void (*print) (void*);
Parameters asaParameters;
public:
Parameters& set_parameters(const Parameters&
_asaParameters){
asaParameters = _asaParameters;
return asaParameters;
}
void run(void* init,
size_t byteSize,
size_t _n_tries = 1000);
void run(std::vector<double>& init,
size_t _n_tries = 1000);
template<size_t N>
void run(std::array<double,N>& init,
size_t _n_tries = 1000){
asaParameters.n_tries = _n_tries;
void* data = static_cast<void*>(init.data());
gsl_siman_solve(randomNumberGenerator, data,
energy, step,
measure, print,
NULL, NULL, NULL,
sizeof(double)*N, asaParameters);
}
template<class State>
void run(State& init, unsigned _size){
void* data = static_cast<void*>(&init);
gsl_siman_solve(randomNumberGenerator, data,
energy, step,
measure, print,
NULL, NULL, NULL,
_size, asaParameters);
}
void set_energy (double (*)(void*));
void set_measure(double (*)(void*,
void*));
void set_step (void (*)(const gsl_rng*,
void*,
double));
void set_print (void (*)(void*));
}; // end of class SimulatedAnnealing
template<typename T>
T myself(T t){
return t;
}
template<typename R,typename ...T>
R pass(T... args __attribute__((unused))){
if constexpr(std::is_void<R>::value) return;
if constexpr(std::is_arithmetic<R>::value){
if constexpr(sizeof...(args)==2) return R(1);
else return R(0);
}
return R();
}
} // end of namespace gsl
#endif
| {
"alphanum_fraction": 0.5533915379,
"avg_line_length": 28.0943396226,
"ext": "h",
"hexsha": "8a9dd9728953ab4aac4d575a0ad0663f26f088b0",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-01T21:38:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-07-01T12:38:06.000Z",
"max_forks_repo_head_hexsha": "15062984e837a938819e548c83f6f5414fa47103",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "adujovic/JorG",
"max_forks_repo_path": "JorGpi/asa/asa.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "15062984e837a938819e548c83f6f5414fa47103",
"max_issues_repo_issues_event_max_datetime": "2019-06-24T08:20:25.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-06-07T11:53:48.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "adujovic/JorG",
"max_issues_repo_path": "JorGpi/asa/asa.h",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "15062984e837a938819e548c83f6f5414fa47103",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "adujovic/JorG",
"max_stars_repo_path": "JorGpi/asa/asa.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-22T11:05:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-22T11:05:03.000Z",
"num_tokens": 690,
"size": 2978
} |
/*
* Copyright (c) 2011-2020 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 "dplasma/types.h"
#include "dplasmaaux.h"
static int
dplasma_zlaset_operator( parsec_execution_stream_t *es,
const parsec_tiled_matrix_t *descA,
void *_A,
dplasma_enum_t uplo, int m, int n,
void *args )
{
int tempmm, tempnn, ldam;
dplasma_complex64_t *alpha = (dplasma_complex64_t*)args;
dplasma_complex64_t *A = (dplasma_complex64_t*)_A;
(void)es;
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 );
if (m == n) {
LAPACKE_zlaset_work(
LAPACK_COL_MAJOR, dplasma_lapack_const( uplo ), tempmm, tempnn,
alpha[0], alpha[1], A, ldam);
} else {
LAPACKE_zlaset_work(
LAPACK_COL_MAJOR, 'A', tempmm, tempnn,
alpha[0], alpha[0], A, ldam);
}
return 0;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlaset_New - Generates the taskpool that set the elements of the matrix
* A on the diagonal to beta and the off-diagonals eklements to alpha.
*
* See parsec_apply_New() for further information.
*
*
*******************************************************************************
*
* @param[in] uplo
* Specifies which part of matrix A is set:
* = dplasmaUpperLower: All matrix is referenced.
* = dplasmaUpper: Only upper part is referenced.
* = dplasmaLower: Only lower part is referenced.
*
* @param[in] alpha
* The constant to which the off-diagonal elements are to be set.
*
* @param[in] beta
* The constant to which the diagonal elements are to be set.
*
* @param[in,out] A
* Descriptor of the distributed matrix A. Any tiled matrix
* descriptor can be used.
* On exit, A has been set accordingly.
*
*******************************************************************************
*
* @return
* \retval NULL if incorrect parameters are given.
* \retval The parsec taskpool describing the operation that can be
* enqueued in the runtime with parsec_context_add_taskpool(). It, then, needs to be
* destroy with dplasma_zlaset_Destruct();
*
*******************************************************************************
*
* @sa dplasma_zlaset
* @sa dplasma_zlaset_Destruct
* @sa dplasma_claset_New
* @sa dplasma_dlaset_New
* @sa dplasma_slaset_New
*
******************************************************************************/
parsec_taskpool_t*
dplasma_zlaset_New( dplasma_enum_t uplo,
dplasma_complex64_t alpha,
dplasma_complex64_t beta,
parsec_tiled_matrix_t *A )
{
dplasma_complex64_t *params = (dplasma_complex64_t*)malloc(2 * sizeof(dplasma_complex64_t));
params[0] = alpha;
params[1] = beta;
return parsec_apply_New( uplo, A, dplasma_zlaset_operator, params );
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlaset_Destruct - Free the data structure associated to an taskpool
* created with dplasma_zlaset_New().
*
*******************************************************************************
*
* @param[in,out] taskpool
* On entry, the taskpool to destroy.
* On exit, the taskpool cannot be used anymore.
*
*******************************************************************************
*
* @sa dplasma_zlaset_New
* @sa dplasma_zlaset
*
******************************************************************************/
void
dplasma_zlaset_Destruct( parsec_taskpool_t *tp )
{
parsec_apply_Destruct(tp);
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlaset - Set the elements of the matrix
* A on the diagonal to beta and the off-diagonals eklements to alpha.
*
*
*******************************************************************************
*
* @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 set:
* = dplasmaUpperLower: All matrix is referenced.
* = dplasmaUpper: Only upper part is refrenced.
* = dplasmaLower: Only lower part is referenced.
*
* @param[in] alpha
* The constant to which the off-diagonal elements are to be set.
*
* @param[in] beta
* The constant to which the diagonal elements are to be set.
*
* @param[in,out] A
* Descriptor of the distributed matrix A. Any tiled matrix
* descriptor can be used.
* On exit, A has been set accordingly.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_zlaset_New
* @sa dplasma_zlaset_Destruct
* @sa dplasma_claset
* @sa dplasma_dlaset
* @sa dplasma_slaset
*
******************************************************************************/
int
dplasma_zlaset( parsec_context_t *parsec,
dplasma_enum_t uplo,
dplasma_complex64_t alpha,
dplasma_complex64_t beta,
parsec_tiled_matrix_t *A )
{
parsec_taskpool_t *parsec_zlaset = NULL;
/* Check input arguments */
if ((uplo != dplasmaLower) &&
(uplo != dplasmaUpper) &&
(uplo != dplasmaUpperLower))
{
dplasma_error("dplasma_zlaset", "illegal value of type");
return -1;
}
parsec_zlaset = dplasma_zlaset_New(uplo, alpha, beta, A);
if ( parsec_zlaset != NULL ) {
parsec_context_add_taskpool(parsec, (parsec_taskpool_t*)parsec_zlaset);
dplasma_wait_until_completion(parsec);
dplasma_zlaset_Destruct( parsec_zlaset );
}
return 0;
}
| {
"alphanum_fraction": 0.5139036621,
"avg_line_length": 32.1024390244,
"ext": "c",
"hexsha": "aee6e782a3821da8ed2fa82387da6ae80d30209d",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z",
"max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "therault/dplasma",
"max_forks_repo_path": "src/zlaset_wrapper.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "therault/dplasma",
"max_issues_repo_path": "src/zlaset_wrapper.c",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "therault/dplasma",
"max_stars_repo_path": "src/zlaset_wrapper.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z",
"num_tokens": 1550,
"size": 6581
} |
#ifndef PETSC4PY_COMPAT_H
#define PETSC4PY_COMPAT_H
#include <petsc.h>
#include "compat/mpi.h"
#include "compat/hdf5.h"
#include "compat/tao.h"
#endif/*PETSC4PY_COMPAT_H*/
| {
"alphanum_fraction": 0.7643678161,
"avg_line_length": 17.4,
"ext": "h",
"hexsha": "b55a49da37318045d2910ef4fc0e2879621e9833",
"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": "33408c70b4211b801c24f8c3cdb859f5aaf59367",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "zonca/petsc4py",
"max_forks_repo_path": "src/include/compat.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367",
"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": "zonca/petsc4py",
"max_issues_repo_path": "src/include/compat.h",
"max_line_length": 27,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "33408c70b4211b801c24f8c3cdb859f5aaf59367",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "zonca/petsc4py",
"max_stars_repo_path": "src/include/compat.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 54,
"size": 174
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.