Search is not available for this dataset
text string | meta dict |
|---|---|
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#pragma once
#include <mcbp/protocol/status.h>
#include <cstdint>
#include <functional>
#include <gsl/gsl>
struct EngineIface;
/**
* Callback for any function producing stats.
*
* @param key the stat's key
* @param value the stat's value in an ascii form (e.g. text form of a number)
* @param cookie magic callback cookie
*/
using AddStatFn = std::function<void(std::string_view key,
std::string_view value,
gsl::not_null<const void*> cookie)>;
/**
* Callback for adding a response backet
* @param key The key to put in the response
* @param extras The data to put in the extended field in the response
* @param body The data body
* @param datatype This is currently not used and should be set to 0
* @param status The status code of the return packet (see in protocol_binary
* for the legal values)
* @param cas The cas to put in the return packet
* @param cookie The cookie provided by the frontend
* @return true if return message was successfully created, false if an
* error occured that prevented the message from being sent
*/
using AddResponseFn = std::function<bool(std::string_view key,
std::string_view extras,
std::string_view body,
uint8_t datatype,
cb::mcbp::Status status,
uint64_t cas,
const void* cookie)>;
| {
"alphanum_fraction": 0.579293836,
"avg_line_length": 39.7857142857,
"ext": "h",
"hexsha": "43dec8d6476e663c226c7e5af071d4ae81ceeff3",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z",
"max_forks_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "rohansuri/kv_engine",
"max_forks_repo_path": "include/memcached/engine_common.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "rohansuri/kv_engine",
"max_issues_repo_path": "include/memcached/engine_common.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "rohansuri/kv_engine",
"max_stars_repo_path": "include/memcached/engine_common.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 339,
"size": 1671
} |
// Copyright The Authors 2018.
// Distributed under the 3-Clause BSD License.
// (See accompanying file LICENSE or copy at
// https://opensource.org/licenses/BSD-3-Clause)
#pragma once
#include <cstdint> // for std::uint8_t etc.
#include <type_traits> // for std::underlying_type_t<>
#include <gsl/gsl> // for gsl::span
#include <p2p/kademlia/buffer.h>
#include <p2p/kademlia/node.h>
namespace blocxxi {
namespace p2p {
namespace kademlia {
/*!
* @brief Represents a message header block.
*
* In its serialized form, every message is composed of a header and a body. The
* header contains the protocol version, the message body type, the ID (hash
* 160) of the source node and a random token (hash 160) used to correlate
* requests and responses.
*
* A serialized header uses the following layout:
* ```
* <-----------------><-------...-------><-------...------->
* 1 byte 20 bytes 20 bytes
* 4 bits | 4 bits source id random token
* version type
*
* ```
*/
struct Header final {
/// Protocol version
enum class Version : std::uint8_t {
V1 = 1,
} version_{Version::V1};
/// Message body type
enum class MessageType : std::uint8_t {
PING_REQUEST,
PING_RESPONSE,
STORE_REQUEST,
FIND_NODE_REQUEST,
FIND_NODE_RESPONSE,
FIND_VALUE_REQUEST,
FIND_VALUE_RESPONSE,
} type_{MessageType::PING_REQUEST};
/// ID of the source node (Hash 160)
Node::IdType source_id_;
/// A random token (Hash 160)
blocxxi::crypto::Hash160 random_token_;
};
/*!
* @brief Generalized function that can take any scoped enumerator and return
* a compile time constant of the underlying type.
*
* Used specifically for the serialization and deserialization of headers. For
* more details on the rational see Scott Meyers, Effective Modern C++ Item 10.
*
* @tparam TEnum the scoped enum class type.
* @param [in] e_value any value of the scoped enum class.
* @return a compile time constant of the underlying type corresponding to
* e_value.
*/
template <typename TEnum>
constexpr std::underlying_type_t<TEnum> ToUnderlying(TEnum e_value) noexcept {
return static_cast<std::underlying_type_t<TEnum>>(e_value);
}
/*!
* @brief A template trait class used to carry extra information about the
* messages types in use.
*
* The traits class T<M> lets us record such extra information about a message
* class M, without requiring any change at all to M. Such extra information is
* used to generically serialize and deserialize messages.
*
* @tparam TMessageBody the type of the message body described by this traits
* class.
*/
template <typename TMessageBody>
struct MessageTraits;
/*!
* @brief Serialize the header into the given buffer, which is expected to be
* able to accomodate the header binary size (41 bytes) or expand as needed.
*
* @param [in] header header object to be serialized.
* @param [out] buffer destination buffer for the header serialized binary form.
*/
void Serialize(Header const &header, Buffer &buffer);
/*!
* @brief Deserialize the contents of the buffer into a Header object.
*
* @param [in] buffer a span over a range of bytes (std::uint8_t) representing
* the header binary data.
* @param [out] header the deserialized resulting header object.
* @return an error code indicating success or failure of the deserialization.
*/
std::size_t Deserialize(BufferReader const &buffer, Header &header);
/// FIND_NODE request message body.
struct FindNodeRequestBody final {
/// The hash 160 id of the node to find.
Node::IdType node_id_;
};
/// Message traits template specialization for the FIND_NODE request message.
template <>
struct MessageTraits<FindNodeRequestBody> {
static constexpr Header::MessageType TYPE_ID =
Header::MessageType::FIND_NODE_REQUEST;
};
/*!
* @brief Serialize a FIND_NODE request body into the given buffer.
*
* @param [in] body the request body.
* @param [out] buffer the destination buffer.
*/
void Serialize(FindNodeRequestBody const &body, Buffer &buffer);
/*!
* @brief Deserialize a FIND_NODE request body from the given buffer.
*
* @param [in] buffer the input buffer.
* @param [out] body the resulting request body.
* @return the number of consumed bytes from the input buffer. Subsequent
* deserialization from the buffer need to start after the consumed bytes.
*/
std::size_t Deserialize(BufferReader const &buffer, FindNodeRequestBody &body);
/// FIND_NODE response message body.
struct FindNodeResponseBody final {
/// The list of nodes in the response.
std::vector<Node> peers_;
};
/// Message traits template specialization for the FIND_NODE response message.
template <>
struct MessageTraits<FindNodeResponseBody> {
static constexpr Header::MessageType TYPE_ID =
Header::MessageType::FIND_NODE_RESPONSE;
};
/*!
* @brief Serialize a FIND_NODE response body into the given buffer.
*
* @param [in] body the response body.
* @param [out] buffer the destination buffer.
*/
void Serialize(FindNodeResponseBody const &body, Buffer &buffer);
/*!
* @brief Deserialize a FIND_NODE response body from the given buffer.
*
* @param [in] buffer the input buffer.
* @param [out] body the resulting response body.
* @return the number of consumed bytes from the input buffer. Subsequent
* deserialization from the buffer need to start after the consumed bytes.
*/
std::size_t Deserialize(BufferReader const &buffer, FindNodeResponseBody &body);
/// FIND_VALUE request message body.
struct FindValueRequestBody final {
/// The hash 160 key of the value to find.
blocxxi::crypto::Hash160 value_key_;
};
/// Message traits template specialization for the FIND_VALUE request message.
template <>
struct MessageTraits<FindValueRequestBody> {
static constexpr Header::MessageType TYPE_ID =
Header::MessageType::FIND_VALUE_REQUEST;
};
/*!
* @brief Serialize a FIND_VALUE request body into the given buffer.
*
* @param [in] body the request body.
* @param [out] buffer the destination buffer.
*/
void Serialize(FindValueRequestBody const &body, Buffer &buffer);
/*!
* @brief Deserialize a FIND_VALUE request body from the given buffer.
*
* @param [in] buffer the input buffer.
* @param [out] body the resulting request body.
* @return the number of consumed bytes from the input buffer. Subsequent
* deserialization from the buffer need to start after the consumed bytes.
*/
std::size_t Deserialize(BufferReader const &buffer, FindValueRequestBody &body);
/// FIND_VALUE response message body.
struct FindValueResponseBody final {
/// The value data as a vector of bytes.
std::vector<std::uint8_t> data_;
};
/// Message traits template specialization for the FIND_VALUE response message.
template <>
struct MessageTraits<FindValueResponseBody> {
static constexpr Header::MessageType TYPE_ID =
Header::MessageType::FIND_VALUE_RESPONSE;
};
/*!
* @brief Serialize a FIND_VALUE response body into the given buffer.
*
* @param [in] body the response body.
* @param [out] buffer the destination buffer.
*/
void Serialize(FindValueResponseBody const &body, Buffer &buffer);
/*!
* @brief Deserialize a FIND_VALUE response body from the given buffer.
*
* @param [in] buffer the input buffer.
* @param [out] body the resulting response body.
* @return the number of consumed bytes from the input buffer. Subsequent
* deserialization from the buffer need to start after the consumed bytes.
*/
std::size_t Deserialize(BufferReader const &buffer,
FindValueResponseBody &body);
/// STORE_VALUE request message body.
struct StoreValueRequestBody final {
/// The hash 160 of the data key.
blocxxi::crypto::Hash160 data_key_;
/// The data value as a vector of bytes.
std::vector<std::uint8_t> data_value_;
};
/// Message traits template specialization for the STORE_VALUE request message.
template <>
struct MessageTraits<StoreValueRequestBody> {
static constexpr Header::MessageType TYPE_ID =
Header::MessageType::STORE_REQUEST;
};
/*!
* @brief Serialize a STORE_VALUE request body into the given buffer.
*
* @param [in] body the request body.
* @param [out] buffer the destination buffer.
*/
void Serialize(StoreValueRequestBody const &body, Buffer &buffer);
/*!
* @brief Deserialize a STORE_VALUE request body from the given buffer.
*
* @param [in] buffer the input buffer.
* @param [out] body the resulting request body.
* @return the number of consumed bytes from the input buffer. Subsequent
* deserialization from the buffer need to start after the consumed bytes.
*/
std::size_t Deserialize(BufferReader const &buffer,
StoreValueRequestBody &body);
} // namespace kademlia
} // namespace p2p
} // namespace blocxxi
| {
"alphanum_fraction": 0.723773842,
"avg_line_length": 32.3823529412,
"ext": "h",
"hexsha": "417dcb82aaf2aab11c2c506ff7b7d72e687a32ec",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z",
"max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "canhld94/blocxxi",
"max_forks_repo_path": "p2p/include/p2p/kademlia/message.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "canhld94/blocxxi",
"max_issues_repo_path": "p2p/include/p2p/kademlia/message.h",
"max_line_length": 80,
"max_stars_count": 24,
"max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "canhld94/blocxxi",
"max_stars_repo_path": "p2p/include/p2p/kademlia/message.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z",
"num_tokens": 1972,
"size": 8808
} |
// mathematical routines
#include "../include/bjutils.h"
double integrate_qag(double (*func)(double, void*),void *par,double low,double up,double *error)
{
const int lim=2000;
const int key=5;
const double eabs=0.0;
const double erel=1.e-4;
double res,err;
gsl_integration_workspace *work=gsl_integration_workspace_alloc(lim);
gsl_function F;
F.function=func;
F.params=par;
gsl_integration_qag(&F,low,up,eabs,erel,lim,key,work,&res,&err);
gsl_integration_workspace_free(work);
if (error!=NULL) *error=err;
return(res);
}
double findroot(double (*func)(double, void*),void *par,double low,double hig,double tol,double *error)
{
#include <gsl/gsl_errno.h>
int status,iter=0;
double root,rnext;
const int max_iter=1000; // maximum no. of iterations
gsl_function F;
F.function=func;
F.params=par;
const gsl_root_fsolver_type *T=gsl_root_fsolver_brent;
gsl_root_fsolver *solv=gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(solv,&F,low,hig);
do {
iter++;
status=gsl_root_fsolver_iterate(solv);
root=gsl_root_fsolver_root(solv);
low=gsl_root_fsolver_x_lower(solv);
hig=gsl_root_fsolver_x_upper(solv);
status=gsl_root_test_interval(low,hig,0.0,tol);
if (status==GSL_SUCCESS) printf ("Root finder converged after %i iterations\n",iter);
} while (status==GSL_CONTINUE && iter<max_iter);
gsl_root_fsolver_iterate(solv);
rnext=gsl_root_fsolver_root(solv);
*error=fabs(root-rnext);
gsl_root_fsolver_free(solv);
return(root);
}
// index search via bisection (log N process)
// array, dimension of array, value to be found, returned: index of array lower than x
void bisect_interpol(double *a,int dim,double x,int *erg)
{
int l=0,u=dim-1,m;
if ((x<a[l]) || (x>a[u])) {
printf("Error: index out of range: %g not in %g-%g\n",x,a[l],a[u]);
exit(-1);
}
while (u-l>1) {
m=(u+l)/2;
if (x>a[m]) l=m;
else u=m;
}
*erg=l;
}
// 1D linear interpolation + extrapolation
double interpol_linear_extra_1D(double *ax,int NX,double *z,double x)
{
if (NX==1) return(z[0]); // assume z constant if only one data point
if (x<=ax[0]) return((z[1]-z[0])/(ax[1]-ax[0])*(x-ax[0])+z[0]);
else if (x>=ax[NX-1]) return((z[NX-1]-z[NX-2])/(ax[NX-1]-ax[NX-2])*(x-ax[NX-1])+z[NX-1]);
else {
int ix;
bisect_interpol(ax,NX,x,&ix);
double t=(x-ax[ix])/(ax[ix+1]-ax[ix]);
return((1-t)*z[ix]+t*z[ix+1]);
}
}
// 2D linear interpolation + extrapolation
double interpol_linear_extra_2D(double *ax,int NX,double *ay,int NY,double **z,double x,double y)
{
if ((x<=ax[0])&&(y>ay[0])&&(y<ay[NY-1])) {
double int1=interpol_linear_extra_1D(ay,NY,z[0],y);
double int2=interpol_linear_extra_1D(ay,NY,z[1],y);
return(int1+(int2-int1)/(ax[1]-ax[0])*(x-ax[0]));
}
else if ((x>=ax[NX-1])&&(y>ay[0])&&(y<ay[NY-1])) {
double int1=interpol_linear_extra_1D(ay,NY,z[NX-2],y);
double int2=interpol_linear_extra_1D(ay,NY,z[NX-1],y);
return(int1+(int2-int1)/(ax[NX-1]-ax[NX-2])*(x-ax[NX-2]));
}
else if ((y<=ay[0])&&(x>ax[0])&&(x<ax[NX-1])) {
int i;
double tmp1[NX],tmp2[NX];
for(i=0;i<NX;i++) {
tmp1[i]=z[i][0];
tmp2[i]=z[i][1];
}
double int1=interpol_linear_extra_1D(ax,NX,tmp1,x);
double int2=interpol_linear_extra_1D(ax,NX,tmp2,x);
return(int1+(int2-int1)/(ay[1]-ay[0])*(y-ay[0]));
}
else if ((y>=ay[NY-1])&&(x>ax[0])&&(x<ax[NX-1])) {
int i;
double tmp1[NX],tmp2[NX];
for(i=0;i<NX;i++) {
tmp1[i]=z[i][NY-2];
tmp2[i]=z[i][NY-1];
}
double int1=interpol_linear_extra_1D(ax,NX,tmp1,x);
double int2=interpol_linear_extra_1D(ax,NX,tmp2,x);
return(int1+(int2-int1)/(ay[NY-1]-ay[NY-2])*(y-ay[NY-2]));
}
else { // produces error via 'bisect' if both dimensions outside range
int ix,iy;
bisect_interpol(ax,NX,x,&ix);
bisect_interpol(ay,NY,y,&iy);
double t=(x-ax[ix])/(ax[ix+1]-ax[ix]);
double u=(y-ay[iy])/(ay[iy+1]-ay[iy]);
return((1-t)*(1-u)*z[ix][iy]+t*(1-u)*z[ix+1][iy]+(1-t)*u*z[ix][iy+1]+t*u*z[ix+1][iy+1]);
}
}
// 3D linear interpolation + extrapolation
double interpol_linear_extra_3D(double *ax,int NX,double *ay,int NY,double *az,int NZ,double ***f,double x,double y,double z)
{
if ((x<=ax[0])&&(y>ay[0])&&(y<ay[NY-1])&&(z>az[0])&&(z<az[NZ-1])) { // x out of range, low
double int1=interpol_linear_extra_2D(ay,NY,az,NZ,f[0],y,z);
double int2=interpol_linear_extra_2D(ay,NY,az,NZ,f[1],y,z);
return(int1+(int2-int1)/(ax[1]-ax[0])*(x-ax[0]));
}
else if ((x>=ax[NX-1])&&(y>ay[0])&&(y<ay[NY-1])&&(z>az[0])&&(z<az[NZ-1])) { // x out of range, high
double int1=interpol_linear_extra_2D(ay,NY,az,NZ,f[NX-2],y,z);
double int2=interpol_linear_extra_2D(ay,NY,az,NZ,f[NX-1],y,z);
return(int1+(int2-int1)/(ax[NX-1]-ax[NX-2])*(x-ax[NX-2]));
}
else if ((y<=ay[0])&&(x>ax[0])&&(x<ax[NX-1])&&(z>az[0])&&(z<az[NZ-1])) { // y out of range, low
int i,j;
double **tmp1=malloc(NX*sizeof(double *));
double **tmp2=malloc(NX*sizeof(double *));
for(i=0;i<NX;i++) {
tmp1[i]=malloc(NZ*sizeof(double));
tmp2[i]=malloc(NZ*sizeof(double));
}
for(i=0;i<NX;i++) {
for(j=0;j<NZ;j++) {
tmp1[i][j]=f[i][0][j];
tmp2[i][j]=f[i][1][j];
}
}
double int1=interpol_linear_extra_2D(ax,NX,az,NZ,tmp1,x,z);
double int2=interpol_linear_extra_2D(ax,NX,az,NZ,tmp2,x,z);
for(i=0;i<NX;i++) {
free(tmp1[i]);
free(tmp2[i]);
}
free(tmp1);
free(tmp2);
return(int1+(int2-int1)/(ay[1]-ay[0])*(y-ay[0]));
}
else if ((y>=ay[NY-1])&&(x>ax[0])&&(x<ax[NX-1])&&(z>az[0])&&(z<az[NZ-1])) { // y out of range, high
int i,j;
double **tmp1=malloc(NX*sizeof(double *));
double **tmp2=malloc(NX*sizeof(double *));
for(i=0;i<NX;i++) {
tmp1[i]=malloc(NZ*sizeof(double));
tmp2[i]=malloc(NZ*sizeof(double));
}
for(i=0;i<NX;i++) {
for(j=0;j<NZ;j++) {
tmp1[i][j]=f[i][NY-2][j];
tmp2[i][j]=f[i][NY-1][j];
}
}
double int1=interpol_linear_extra_2D(ax,NX,az,NZ,tmp1,x,z);
double int2=interpol_linear_extra_2D(ax,NX,az,NZ,tmp2,x,z);
for(i=0;i<NX;i++) {
free(tmp1[i]);
free(tmp2[i]);
}
free(tmp1);
free(tmp2);
return(int1+(int2-int1)/(ay[NY-1]-ay[NY-2])*(y-ay[NY-2]));
}
else if ((z<=az[0])&&(x>ax[0])&&(x<ax[NX-1])&&(y>ay[0])&&(y<ay[NY-1])) { // z out of range, low
int i,j;
double **tmp1=malloc(NX*sizeof(double *));
double **tmp2=malloc(NX*sizeof(double *));
for(i=0;i<NX;i++) {
tmp1[i]=malloc(NY*sizeof(double));
tmp2[i]=malloc(NY*sizeof(double));
}
for(i=0;i<NX;i++) {
for(j=0;j<NY;j++) {
tmp1[i][j]=f[i][j][0];
tmp2[i][j]=f[i][j][1];
}
}
double int1=interpol_linear_extra_2D(ax,NX,ay,NY,tmp1,x,y);
double int2=interpol_linear_extra_2D(ax,NX,ay,NY,tmp2,x,y);
for(i=0;i<NX;i++) {
free(tmp1[i]);
free(tmp2[i]);
}
free(tmp1);
free(tmp2);
return(int1+(int2-int1)/(az[1]-az[0])*(z-az[0]));
}
else if ((z>=az[NZ-1])&&(x>ax[0])&&(x<ax[NX-1])&&(y>ay[0])&&(y<ay[NY-1])) { // z out of range, high
int i,j;
double **tmp1=malloc(NX*sizeof(double *));
double **tmp2=malloc(NX*sizeof(double *));
for(i=0;i<NX;i++) {
tmp1[i]=malloc(NY*sizeof(double));
tmp2[i]=malloc(NY*sizeof(double));
}
for(i=0;i<NX;i++) {
for(j=0;j<NY;j++) {
tmp1[i][j]=f[i][j][NZ-2];
tmp2[i][j]=f[i][j][NZ-1];
}
}
double int1=interpol_linear_extra_2D(ax,NX,ay,NY,tmp1,x,y);
double int2=interpol_linear_extra_2D(ax,NX,ay,NY,tmp2,x,y);
for(i=0;i<NX;i++) {
free(tmp1[i]);
free(tmp2[i]);
}
free(tmp1);
free(tmp2);
return(int1+(int2-int1)/(az[NZ-1]-az[NZ-2])*(z-az[NZ-2]));
}
else { // produces error via 'bisect' if more than 1 dimension outside range
int ix,iy,iz;
double f1a,f1b,f2a,f2b;
bisect_interpol(ax,NX,x,&ix);
bisect_interpol(ay,NY,y,&iy);
bisect_interpol(az,NZ,z,&iz);
double q1=(x-ax[ix])/(ax[ix+1]-ax[ix]);
double q2=(y-ay[iy])/(ay[iy+1]-ay[iy]);
double q3=(z-az[iz])/(az[iz+1]-az[iz]);
double p1=1-q1;
double p2=1-q2;
f1a=p1*f[ix][iy][iz]+q1*f[ix+1][iy][iz];
f1b=p1*f[ix][iy+1][iz]+q1*f[ix+1][iy+1][iz];
f2a=p2*f1a+q2*f1b;
f1a=p1*f[ix][iy][iz+1]+q1*f[ix+1][iy][iz+1];
f1b=p1*f[ix][iy+1][iz+1]+q1*f[ix+1][iy+1][iz+1];
f2b=p2*f1a+q2*f1b;
return((1-q3)*f2a+q3*f2b);
}
}
// 4D linear interpolation + extrapolation
double interpol_linear_extra_4D(double *ax,int NX,double *ay,int NY,double *az,int NZ,double *aw,int NW,double ****f,double x,double y,double z,double w)
{
int ix;
double f1,f2,t;
if (((x<ax[0])||(x>ax[NX-1]))&&((y<ay[0])||(y>ay[NY-1])||(z<az[0])||(z>az[NZ-1])||(w<aw[0])||(w>aw[NW-1]))) {
printf("Error in routine 'interpol_linear_extra_4D': attempt extrapolation in more than one dimension.\n");
exit(-1);
}
if (x<=ax[0]) {
f1=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[0],y,z,w);
f2=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[1],y,z,w);
return((f2-f1)/(ax[1]-ax[0])*(x-ax[0])+f1);
}
else if (x>=ax[NX-1]) {
f1=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[NX-2],y,z,w);
f2=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[NX-1],y,z,w);
return((f2-f1)/(ax[NX-1]-ax[NX-2])*(x-ax[NX-1])+f2);
}
else {
bisect_interpol(ax,NX,x,&ix);
f1=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[ix],y,z,w);
f2=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[ix+1],y,z,w);
t=(x-ax[ix])/(ax[ix+1]-ax[ix]);
return((1-t)*f1+t*f2);
}
}
void mattimesmat_gen(gsl_matrix *a,gsl_matrix *b,gsl_matrix *erg,int dim1,int dim2,int dim3)
{
int i,j,k;
double sum;
for (i=0;i<dim1;i++) {
for (j=0;j<dim3;j++) {
sum=0.0;
for (k=0;k<dim2;k++) {
sum+=gsl_matrix_get(a,i,k)*gsl_matrix_get(b,k,j);
}
gsl_matrix_set(erg,i,j,sum);
}
}
}
void mattimesmat(gsl_matrix *a,gsl_matrix *b,gsl_matrix *erg,int N)
{
int i,j,k;
double sum;
for (i=0;i<N;i++) {
for (j=0;j<N;j++) {
sum=0.0;
for (k=0;k<N;k++) {
sum+=gsl_matrix_get(a,i,k)*gsl_matrix_get(b,k,j);
}
gsl_matrix_set(erg,i,j,sum);
}
}
}
void mattimesvec_gen(gsl_matrix *a,gsl_vector *b,gsl_vector *erg,int dim1,int dim2)
{
int i,j;
double sum;
for (i=0;i<dim1;i++) {
sum=0.0;
for (j=0;j<dim2;j++) {
sum+=gsl_matrix_get(a,i,j)*gsl_vector_get(b,j);
}
gsl_vector_set(erg,i,sum);
}
}
void mattimesvec(gsl_matrix *a,gsl_vector *b,gsl_vector *erg,int N)
{
int i,j;
double sum;
for (i=0;i<N;i++) {
sum=0.0;
for (j=0;j<N;j++) {
sum+=gsl_matrix_get(a,i,j)*gsl_vector_get(b,j);
}
gsl_vector_set(erg,i,sum);
}
}
int matrixinvers(gsl_matrix *m,gsl_matrix *inv,int DIM)
{
int i,j,k,flag=0;
double elem,sum;
const int DOCHECK=1;
gsl_matrix *v=gsl_matrix_alloc(DIM,DIM);
gsl_matrix *id=gsl_matrix_alloc(DIM,DIM);
gsl_matrix *u=gsl_matrix_alloc(DIM,DIM);
gsl_vector *work=gsl_vector_alloc(DIM);
gsl_vector *s=gsl_vector_alloc(DIM);
gsl_matrix_memcpy(u,m);
gsl_linalg_SV_decomp(u,v,s,work);
for (i=0;i<DIM;i++) {
elem=gsl_vector_get(s,i);
if (fabs(elem)==0) {
printf("Error: zero singular value!\n");
exit(-1);
}
if (fabs(elem)<1.e-35) {
printf("Possible singular value: %g\n",elem);
flag=1;
}
//printf("eigenvalue: %g\n",elem);
}
for (i=0;i<DIM;i++) {
for (j=0;j<DIM;j++) {
sum=0.0;
for (k=0;k<DIM;k++) {
sum+=gsl_matrix_get(v,i,k)/gsl_vector_get(s,k)*gsl_matrix_get(u,j,k);
}
gsl_matrix_set(inv,i,j,sum);
}
}
if (DOCHECK) {
mattimesmat(m,inv,v,DIM); //v reused
gsl_matrix_set_identity(id);
gsl_matrix_sub(v,id); //result in v
for (i=0;i<DIM;i++) {
for (j=0;j<DIM;j++) {
elem=gsl_matrix_get(v,i,j);
if (fabs(elem)>1.e-2) {
printf("Problematic matrix inversion: %g\n",elem);
flag=2;
break;
}
}
}
}
gsl_matrix_free(u);
gsl_matrix_free(v);
gsl_matrix_free(id);
gsl_vector_free(work);
gsl_vector_free(s);
return(flag);
}
gsl_matrix *pseudoinvers(gsl_matrix *m,double thresh,double *eigen)
{
int i,j,k;
double sum;
const int dim=(int)m->size1;
if (m->size1!=m->size2) {
printf("Error in 'pseudoinvers': non-square matrix - not implemented yet.\n");
exit(-1);
}
gsl_matrix *res=gsl_matrix_alloc(dim,dim);
gsl_matrix *v=gsl_matrix_alloc(dim,dim);
gsl_matrix *cov=gsl_matrix_alloc(dim,dim);
gsl_vector *work=gsl_vector_alloc(dim);
gsl_vector *s=gsl_vector_alloc(dim);
gsl_vector *invs=gsl_vector_alloc(dim);
gsl_matrix_memcpy(cov,m);
gsl_linalg_SV_decomp(cov,v,s,work);
for (i=0;i<dim;i++) {
eigen[i]=gsl_vector_get(s,i);
if (eigen[i]<=thresh) gsl_vector_set(invs,i,0.0);
else gsl_vector_set(invs,i,1./eigen[i]);
}
for (i=0;i<dim;i++) {
for (j=0;j<dim;j++) {
sum=0.0;
for (k=0;k<dim;k++) {
sum+=gsl_matrix_get(v,i,k)*gsl_vector_get(invs,k)*gsl_matrix_get(cov,j,k);
}
gsl_matrix_set(res,i,j,sum);
}
}
gsl_matrix_free(cov);
gsl_matrix_free(v);
gsl_vector_free(work);
gsl_vector_free(s);
gsl_vector_free(invs);
return(res);
}
int covinvers(gsl_matrix *m,gsl_matrix *inv,int DIM)
{
#include<gsl/gsl_errno.h>
gsl_set_error_handler_off();
const int DOCHECK=1;
int i,flag=0;
gsl_matrix *check=gsl_matrix_alloc(DIM,DIM);
gsl_vector *b=gsl_vector_alloc(DIM);
gsl_matrix_memcpy(check,m);
flag=gsl_linalg_cholesky_decomp(check);
if (!flag) {
for (i=0;i<DIM;i++) {
gsl_vector_set_basis(b,i);
gsl_linalg_cholesky_svx(check,b);
gsl_matrix_set_col(inv,i,b);
}
if (DOCHECK) {
gsl_matrix *id=gsl_matrix_alloc(DIM,DIM);
gsl_matrix_set_identity(id);
int j;
double elem;
mattimesmat(m,inv,check,DIM); //check reused
gsl_matrix_sub(check,id); //result in check
for (i=0;i<DIM;i++) {
for (j=0;j<DIM;j++) {
elem=gsl_matrix_get(check,i,j);
if (fabs(elem)>1.e-6) {
printf("Problematic matrix inversion: %g\n",elem);
flag=2;
break;
}
}
}
gsl_matrix_free(id);
}
}
gsl_matrix_free(check);
gsl_vector_free(b);
return(flag);
}
double matrix_trace(gsl_matrix *a,int N)
{
int i;
double sum=0.0;
for (i=0;i<N;i++) {
sum+=gsl_matrix_get(a,i,i);
}
return(sum);
}
double matrix_det(gsl_matrix *a,int N)
{
int sign;
gsl_permutation *perm=gsl_permutation_alloc(N);
gsl_matrix *LU=gsl_matrix_alloc(N,N);
gsl_matrix_memcpy(LU,a);
gsl_linalg_LU_decomp(LU,perm,&sign);
gsl_permutation_free(perm);
return(gsl_linalg_LU_det(LU,sign));
}
void matrix_transpose(gsl_matrix *a,gsl_matrix *t,int dim1,int dim2)
{
int i,j;
for (i=0;i<dim1;i++) {
for (j=0;j<dim2;j++) {
gsl_matrix_set(t,j,i,gsl_matrix_get(a,i,j));
}
}
return;
}
void matrix_print(gsl_matrix *a,char *file)
{
int i,j;
FILE *dat;
if ((dat=fopen(file,"w"))==NULL) {
printf("Error in routine 'matrix_print': could not open file %s\n",file);
exit(-1);
}
for (i=0;i<a->size1;i++) {
for (j=0;j<a->size2;j++) {
fprintf(dat,"%15.10g\t",gsl_matrix_get(a,i,j));
}
fprintf(dat,"\n");
}
fclose(dat);
return;
}
void vector_print(gsl_vector *v,char *file)
{
int i;
FILE *dat;
if ((dat=fopen(file,"w"))==NULL) {
printf("Error in routine 'vector_print': could not open file %s\n",file);
exit(-1);
}
for (i=0;i<v->size;i++) {
fprintf(dat,"%15.10g\n",gsl_vector_get(v,i));
}
fclose(dat);
return;
}
void solve_lse(gsl_matrix *m,gsl_vector *in,gsl_vector *res)
{
if (m->size1!=res->size) {
printf("Error in routine 'solve_lse': matrix row dimension does not match dimension of solution vector: %zu - %zu\n",m->size1,res->size);
exit(-1);
}
if (m->size2!=in->size) {
printf("Error in routine 'solve_lse': matrix column dimension does not match dimension of input vector: %zu - %zu\n",m->size2,in->size);
exit(-1);
}
gsl_matrix *v=gsl_matrix_alloc(m->size2,m->size2);
gsl_matrix *u=gsl_matrix_alloc(m->size1,m->size2);
gsl_vector *work=gsl_vector_alloc(m->size2);
gsl_vector *s=gsl_vector_alloc(m->size2);
gsl_matrix_memcpy(u,m);
gsl_linalg_SV_decomp(u,v,s,work);
gsl_linalg_SV_solve(u,v,s,in,res);
gsl_matrix_free(u);
gsl_matrix_free(v);
gsl_vector_free(work);
gsl_vector_free(s);
return;
}
// inverse of symmetric matrix via Cholesky decomposition
int inverse_symm(gsl_matrix *in,gsl_matrix *out)
{
#include<gsl/gsl_errno.h>
gsl_set_error_handler_off();
int i,flag=0;
const int dim=(int)in->size1;
gsl_matrix *check=gsl_matrix_alloc(dim,dim);
gsl_vector *b=gsl_vector_alloc(dim);
gsl_matrix_memcpy(check,in); // do not overwrite 'in'
flag=gsl_linalg_cholesky_decomp(check);
if (!flag) {
for (i=0;i<dim;i++) {
gsl_vector_set_basis(b,i);
gsl_linalg_cholesky_svx(check,b);
gsl_matrix_set_col(out,i,b);
}
}
gsl_matrix_free(check);
gsl_vector_free(b);
return(flag);
}
int fisher_ellipse(gsl_matrix *fisher,int index1,int index2,double *semi_major,double *semi_minor,double *angle)
{
int flag;
// setup
if (index1==index2) return(2); // can only make ellipse for two different indices
const int dim=fisher->size1;
gsl_matrix *inv=gsl_matrix_alloc(dim,dim);
gsl_matrix *sub=gsl_matrix_alloc(2,2);
gsl_matrix *v=gsl_matrix_alloc(2,2);
gsl_vector *work=gsl_vector_alloc(2);
gsl_vector *s=gsl_vector_alloc(2);
// invert Fisher matrix
flag=inverse_symm(fisher,inv);
// get ellipse plotting parameters
gsl_matrix_set(sub,0,0,gsl_matrix_get(inv,index1,index1));
gsl_matrix_set(sub,0,1,gsl_matrix_get(inv,index1,index2));
gsl_matrix_set(sub,1,0,gsl_matrix_get(inv,index2,index1));
gsl_matrix_set(sub,1,1,gsl_matrix_get(inv,index2,index2));
gsl_linalg_SV_decomp(sub,v,s,work);
*semi_major=sqrt(gsl_vector_get(s,0));
*semi_minor=sqrt(gsl_vector_get(s,1));
*angle=atan(gsl_matrix_get(v,1,0)/gsl_matrix_get(v,0,0));
// clean up
gsl_vector_free(work);
gsl_matrix_free(v);
gsl_matrix_free(inv);
gsl_matrix_free(sub);
gsl_vector_free(s);
return(flag);
}
// provides KDE in 1D with Gaussians, using Silverman's rule if width<=0 on call
void kde_1D(double *dp,int nd,int nstep,double step_min,double step_max,double h,double *steps,double *func)
{
int i,j;
double width=1.;
const double gauss_norm=1./sqrt(2.*PI);
// set binning
for (i=0;i<nstep;i++) {
steps[i]=step_min+i*(step_max-step_min)/(1.*nstep-1.);
}
// get width of Gaussian
if (h<=0.0) { // apply Silverman's rule
width=1.06*gsl_stats_sd(dp,1,nd)*pow(nd,-0.2);
}
else width=h;
// perform KDE
for (i=0;i<nstep;i++) {
func[i]=0.0;
for (j=0;j<nd;j++) {
func[i]+=exp(-0.5*(steps[i]-dp[j])*(steps[i]-dp[j])/(width*width))/width;
}
func[i]*=gauss_norm; // normalised to nd if integrated
}
return;
}
| {
"alphanum_fraction": 0.6121933242,
"avg_line_length": 26.1986206897,
"ext": "c",
"hexsha": "afb69ce5f525235dc8d5d2b040b98569f7db220e",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-03-02T01:40:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-09T13:30:22.000Z",
"max_forks_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1",
"max_forks_repo_path": "src/bjutils/source/math.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d",
"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": "KiDS-WL/Cat_to_Obs_K1000_P1",
"max_issues_repo_path": "src/bjutils/source/math.c",
"max_line_length": 153,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1",
"max_stars_repo_path": "src/bjutils/source/math.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-01T08:54:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-18T12:58:03.000Z",
"num_tokens": 6793,
"size": 18994
} |
/* -----------------------------------------------------------------------------
* Copyright 2021 Jonathan Haigh
* SPDX-License-Identifier: MIT
* ---------------------------------------------------------------------------*/
#ifndef SQ_INCLUDE_GUARD_system_linux_SqPrimitiveTypeSchemaImpl_h_
#define SQ_INCLUDE_GUARD_system_linux_SqPrimitiveTypeSchemaImpl_h_
#include "core/typeutil.h"
#include "system/SqPrimitiveTypeSchema.gen.h"
#include "system/schema.h"
#include <gsl/gsl>
namespace sq::system::linux {
class SqPrimitiveTypeSchemaImpl
: public SqPrimitiveTypeSchema<SqPrimitiveTypeSchemaImpl> {
public:
explicit SqPrimitiveTypeSchemaImpl(
const PrimitiveTypeSchema &primitive_type_schema);
SQ_ND Result get_name() const;
SQ_ND Result get_doc() const;
SQ_ND Primitive to_primitive() const override;
private:
gsl::not_null<const PrimitiveTypeSchema *> primitive_type_schema_;
};
} // namespace sq::system::linux
#endif // SQ_INCLUDE_GUARD_system_linux_SqPrimitiveTypeSchemaImpl_h_
| {
"alphanum_fraction": 0.6811023622,
"avg_line_length": 29.0285714286,
"ext": "h",
"hexsha": "3928ecc5e879f588423f27cfcf3f6604770f20ae",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jonathanhaigh/sq",
"max_forks_repo_path": "src/system/include/system/linux/SqPrimitiveTypeSchemaImpl.h",
"max_issues_count": 44,
"max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jonathanhaigh/sq",
"max_issues_repo_path": "src/system/include/system/linux/SqPrimitiveTypeSchemaImpl.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jonathanhaigh/sq",
"max_stars_repo_path": "src/system/include/system/linux/SqPrimitiveTypeSchemaImpl.h",
"max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z",
"num_tokens": 205,
"size": 1016
} |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Contains collection of low-level routines for handling lists,
one-hot matrices, evaluation metrics (f1-scores), and other.
Dimitris Berberidis
University of Minnesota 2017-2018
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <inttypes.h>
#include <cblas.h>
#include <sys/stat.h>
#include <stdbool.h>
#include "my_utils.h"
#include "my_defs.h"
void assert_all_nodes_present(csr_graph graph, const sz_long* seed_indices, sz_med num_seeds){
for(sz_med i=0;i<num_seeds;i++){
if(seed_indices[i]>graph.num_nodes){
printf("ERROR: Seed node index does not appear in edgelist (probably an isolated node)\n");
exit(EXIT_FAILURE);
}
}
}
sz_long rand_lim(sz_long limit) {
/* return a random number between 0 and limit inclusive.
*/
int divisor = RAND_MAX/((int)limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
//Draw random samples with replacement from 0 to N-1
void random_sample( sz_long* seeds, abstract_labels labels, abstract_labels all_labels, sz_med num_seeds, sz_long N){
sz_long temp;
sz_short flag;
//Draw seed indexes
seeds[0]=rand_lim(N-1);
for(sz_med i=1;i<num_seeds;i++){
do{
temp=rand_lim(N-1);
flag=0;
for(sz_med j=0;j<i;j++){
if(temp==seeds[j])
flag=1;
}
}while(flag==1);
seeds[i]=temp;
}
//Draw corresponding labels
if(all_labels.is_multilabel){
for(sz_med i=0;i<num_seeds;i++){
for(sz_short j=0; j<all_labels.mlabel.num_class;j++)
labels.mlabel.bin[j][i] = all_labels.mlabel.bin[j][seeds[i]];
}
}else{
for(sz_med i=0;i<num_seeds;i++){
labels.mclass[i]=all_labels.mclass[seeds[i]];
//printf("%d\n",seeds[i]);
}
}
// +1 seed indexes !
for(sz_med i=0;i<num_seeds;i++){seeds[i]+=1;}
}
//My comparator for two collumn array. Sorts second col according to first
int compare ( const void *pa, const void *pb )
{
const sz_long *a = *(const sz_long **)pa;
const sz_long *b = *(const sz_long **)pb;
if(a[0] == b[0])
return a[1] - b[1];
else
return a[0] - b[0];
}
//My comparator for a struct with double and index
int compare2 ( const void *pa, const void *pb )
{
val_and_ind *a1 = (val_and_ind*)pa;
val_and_ind *a2 = (val_and_ind*)pb;
if((*a1).val>(*a2).val)return -1;
else if((*a1).val<(*a2).val)return 1;
else return 0;
}
//frobenious norm of double-valued square matrix
double frob_norm(double* A, sz_med dim){
double norm=0.0f;
for(sz_med i=0;i<dim*dim;i++){
norm+=pow(A[i],2.0f);
}
return sqrt(norm);
}
//mean of double array
double mean(double* a, int len){
double sum=0;
for(int i=0;i<len;i++) sum+=a[i];
return sum/(double)len;
}
//Simple linear system solver using the LU decomposition
/* INPUT: A,P filled in LUPDecompose; b - rhs vector; N - dimension
* OUTPUT: x - solution vector of A*x=b
*/
void LUPSolve(double **A, int *P, double *b, int N, double *x){
for (int i = 0; i < N; i++) {
x[i] = b[P[i]];
for (int k = 0; k < i; k++)
x[i] -= A[i][k] * x[k];
}
for (int i = N - 1; i >= 0; i--) {
for (int k = i + 1; k < N; k++)
x[i] -= A[i][k] * x[k];
x[i] = x[i] / A[i][i];
}
}
//Simple LU decomposition routine
/* INPUT: A - array of pointers to rows of a square matrix having dimension N
* Tol - small tolerance number to detect failure when the matrix is near degenerate
* OUTPUT: Matrix A is changed, it contains both matrices L-E and U as A=(L-E)+U such that P*A=L*U.
* The permutation matrix is not stored as a matrix, but in an integer vector P of size N+1
* containing column indexes where the permutation matrix has "1". The last element P[N]=S+N,
* where S is the number of row exchanges needed for determinant computation, det(P)=(-1)^S
*/
int LUPDecompose(double **A, int N, double Tol, int *P) {
int i, j, k, imax;
double maxA, *ptr, absA;
for (i = 0; i <= N; i++)
P[i] = i; //Unit permutation matrix, P[N] initialized with N
for (i = 0; i < N; i++) {
maxA = 0.0;
imax = i;
for (k = i; k < N; k++)
if ((absA = fabs(A[k][i])) > maxA) {
maxA = absA;
imax = k;
}
if (maxA < Tol) return 0; //failure, matrix is degenerate
if (imax != i) {
//pivoting P
j = P[i];
P[i] = P[imax];
P[imax] = j;
//pivoting rows of A
ptr = A[i];
A[i] = A[imax];
A[imax] = ptr;
//counting pivots starting from N (for determinant)
P[N]++;
}
for (j = i + 1; j < N; j++) {
A[j][i] /= A[i][i];
for (k = i + 1; k < N; k++)
A[j][k] -= A[j][i] * A[i][k];
}
}
return 1; //decomposition done
}
//Interface for CBLAS matrix vector product
void matvec(double*y, double* A, double* x, sz_med M, sz_med N ){
for(int i=0;i<M;i++){y[i]=0.0f;}
cblas_dgemv( CblasRowMajor , CblasNoTrans , (int)M , (int)N, 1.0f, A, (int)M, x, 1, 0.0f, y, 1);
}
//Interface for CBLAS matrix vector product
void matvec_trans(double*y, double* A, double* x, sz_med M, sz_med N ){
for(sz_med i=0;i<M;i++){y[i]=0.0f;}
cblas_dgemv( CblasRowMajor , CblasTrans , (int)M , (int)N, 1.0f, A, (int)M, x, 1, 0.0f, y, 1);
}
//Interface for CBLAS trnaspose-matrix vector product
void matvec_trans_long( double* y , double* A, double* x, sz_long N, sz_med p ){
cblas_dgemv (CblasRowMajor, CblasTrans, (int) p, (int)N , 1.0f, A, (int) N , x, 1 , 0.0f, y, 1);
}
//Interface for CBLAS mutrix matrix product
void matrix_matrix_product(double*C, double* A, double* B, sz_long m, sz_med k , sz_short n){
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, (int)m,
(int)n, (int)k, 1.0f, A, (int)k, B, (int)n, 0.0f, C, (int)n);
}
//Project vector onto simplex by alternating projections onto line and positive quadrant
//Operation happens in place
void project_to_simplex( double* x, sz_med N ){
double sum,a;
sz_short flag;
do{
flag=0;
sum=0.0f;
for(sz_med i=0; i<N; i++) sum+=x[i];
a=(sum - 1.0f)/(double)N;
for(sz_med i=0; i<N; i++){
x[i]-=a;
if(x[i]<= - PROJ_TOL){
x[i]=0.0f;
flag=1;}
}
}while(flag==1);
}
//find l_max norm between vecors of known length
double max_diff(double* x, double* y , sz_med L){
double dif;
double max_dif=0.0f;
for(sz_med i=0;i<L;i++){
dif=fabs( x[i] - y[i] );
max_dif = ( dif > max_dif ) ? dif : max_dif ;
}
return max_dif;
}
//Print array (double)
void print_array_1D(double* arr, sz_long N, sz_long M){
sz_long i,j;
printf("Array: \n");
for(i=0;i<N;i++){
printf("\n");
for(j=0;j<M;j++) printf("%lf ",arr[i*M + j]);
}
printf("\n");
}
//Pradict labels from largest soft label
void predict_labels( class_t* label_out, double* soft_labels, class_t* class,
sz_long graph_size, sz_short num_class ){
sz_short max_ind;
double max_val;
for(sz_long i=0;i<graph_size;i++){
max_val=-100.0f;
for(sz_short j=0;j<num_class;j++){
if(max_val<soft_labels[i*num_class + j]){
max_val=soft_labels[i*num_class + j];
max_ind=j;}
}
label_out[i]=class[max_ind];
}
}
//Pradict labels from largest soft label (Soft labels are transposed array)
void predict_labels_type2( class_t* label_out, double* soft_labels, class_t* class,
sz_long graph_size, sz_short num_class ){
sz_short max_ind;
double max_val;
for(sz_long j=0;j<graph_size;j++){
max_val=-100.0f;
for(sz_short i=0;i<num_class;i++){
if(max_val<soft_labels[i*graph_size + j]){
max_val=soft_labels[i*graph_size + j];
max_ind=i;}
}
label_out[j]=class[max_ind];
}
}
//Print the two collumn array of edges
void print_edge_list(const sz_long** edge_list, sz_long len){
printf("EDGE LIST: \n");
for(sz_long i=0;i<len;i++)
printf("%"PRIu64" %"PRIu64"\n", (uint64_t) edge_list[i][0], (uint64_t) edge_list[i][1]);
}
//Print array (double)
void print_predictions(class_t* arr, sz_long N){
printf("Predicted labels: \n");
for(sz_long i=0;i<N;i++) printf("%"PRIi16"\n", (int16_t) arr[i]);
}
//Check if file is valid
int file_isreg(char *path) {
struct stat st;
if (stat(path, &st) < 0)
return -1;
return S_ISREG(st.st_mode);
}
//Elementwise subtract b from a and store in c
void my_array_sub(double* c, double* a, double* b, sz_long N ){
for(sz_long i=0;i<N;i++) c[i] = a[i] -b[i];
}
//Max of array
sz_short max_u8( sz_short* a, sz_long N ){
sz_short max= 0;
for(sz_long i=0; i<N ; i++) max = ( a[i]>max ) ? a[i] : max ;
return max;
}
sz_long max_u64( sz_long* a, sz_long N ){
sz_long max= 0;
for(sz_long i=0; i<N ; i++) max = ( a[i]>max ) ? a[i] : max ;
return max;
}
//Return edge list and count to main
sz_long** give_edge_list( char* file_name, sz_long* count ){
sz_long** buffer= (sz_long **)malloc(EDGE_BUFF_SIZE * sizeof(sz_long *));
for(sz_long i=0;i<EDGE_BUFF_SIZE;i++)
buffer[i]= (sz_long*) malloc(2*sizeof(sz_long));
FILE* file= fopen(file_name, "r");
if(!file) printf("ERROR: Cannot open graph file");
// Read adjacency into buffer into buffer and return length count=edges
*count= read_adjacency_to_buffer(buffer,file);
printf("Number of edges: %"PRIu64"\n", (uint64_t) *count);
//print_edge_list( buffer, *count);
//Free excess memory
for(sz_long i=*count+1;i<EDGE_BUFF_SIZE;i++)
{free(buffer[i]);}
buffer=realloc(buffer,(*count)*sizeof(sz_long*));
return buffer;
}
//Read .txt file into buffer
sz_long read_adjacency_to_buffer(sz_long** buffer, FILE* file){
sz_long count = 0;
for (; count < EDGE_BUFF_SIZE; ++count)
{
int got = fscanf(file, "%"SCNu64"\t%"SCNu64"\n", &buffer[count][0] , &buffer[count][1]);
if ((got != 2)||( (buffer[count][0]==0) && (buffer[count][1]==0))) break;
// Stop scanning if wrong number of tokens (maybe end of file) or zero input
}
fclose(file);
return count;
}
//Read class.txt file into buffer (ignore first collumn here)
class_t* read_labels(char* filename, sz_long* label_count){
sz_long count = 0;
sz_long* indexes = (sz_long*) malloc(sizeof(sz_long)*CLASS_BUFF_SIZE);
class_t* buffer = (class_t*) malloc(sizeof(class_t)*CLASS_BUFF_SIZE);
FILE* file= fopen(filename, "r");
if(!file) printf("ERROR: Cannot open label file");
for (; count < CLASS_BUFF_SIZE; ++count)
{
int got = fscanf(file, "%"SCNu64"%"SCNu8"", &indexes[count] , &buffer[count]);
if (got != 2) break; // wrong number of tokens - maybe end of file
}
fclose(file);
*label_count = count;
buffer = realloc(buffer,sizeof(class_t)*count);
indexes = realloc(indexes,sizeof(sz_long)*count);
my_relative_sorting( indexes, buffer, count );
free(indexes);
return buffer;
}
//Read seed and label file when in operation mode
sz_long* read_seed_file( char* filename, sz_med* num_seeds, sz_short* num_class, abstract_labels* label_in ){
//First read file into buffers
sz_long count = 0;
sz_long* index_buffer = (sz_long*) malloc(sizeof(sz_long)*CLASS_BUFF_SIZE);
class_t* label_buffer = (class_t*) malloc(sizeof(class_t)*CLASS_BUFF_SIZE);
FILE* file= fopen(filename, "r");
if(!file) printf("ERROR: Cannot open seed file");
for (; count < CLASS_BUFF_SIZE; ++count)
{
int got = fscanf(file, "%"SCNu64"%"SCNd8"", &index_buffer[count] , &label_buffer[count]);
if (got != 2) break; // wrong number of tokens - maybe end of file
}
fclose(file);
label_buffer = realloc(label_buffer,sizeof(class_t)*count);
index_buffer = realloc(index_buffer,sizeof(sz_long)*count);
//prepare input labels and seeds for is_multilabel or multi_class
sz_long* seed_indices;
if(label_in->is_multilabel){
*num_class = max_u8( (sz_short*) label_buffer, count);
my_relative_sorting( index_buffer, label_buffer, count );
seed_indices = find_unique_from_sorted( index_buffer, count , num_seeds );
label_in->mlabel = init_one_hot(*num_class , *num_seeds);
sz_long j=0;
for(sz_long i=0;i<count;i++){
if(i>0) j = (index_buffer[i] == index_buffer[i-1] ) ? j : j+1;
label_in->mlabel.bin[label_buffer[i]-1][j]=1;
}
free(index_buffer);
free(label_buffer);
}else{
seed_indices = index_buffer;
label_in->mclass = label_buffer;
*num_seeds = (sz_med) count;
}
return seed_indices;
}
//write predicted labels (or ranking in multilabel case) to output file
void save_predictions(char* filename, abstract_label_output label_out, sz_long len, sz_short num_class){
FILE* file = fopen(filename, "w");
if(!file) printf("ERROR: Cannot open outfile");
if(label_out.is_multilabel){
val_and_ind line_of_out[num_class];
for(sz_long i=0; i<len; i++){
for(sz_short j=0; j<num_class; j++)
line_of_out[j] = (val_and_ind) {.val = label_out.mlabel[j*len + i], .ind=(int)j};
qsort( line_of_out, num_class, sizeof(line_of_out[0]), compare2);
fprintf(file, "%"SCNu64":\t", (uint64_t) i+1 );
for(sz_short j=0; j<num_class; j++)
fprintf(file, "%"PRIu16" ", (uint16_t) line_of_out[j].ind +1 );
fprintf(file, "\n");
}
}else{
for(sz_long i=0; i<len; i++)
fprintf(file, "%"SCNu64"\t%"SCNd16"\n", (uint64_t) i+1 , (int16_t) label_out.mclass[i]);
}
fclose(file);
}
//Read class.txt file into one_hot_matrix (ignore first collumn here)
one_hot_mat read_one_hot_mat(char* filename, sz_long* label_count){
sz_long count = 0;
sz_long* indexes = (sz_long*) malloc(sizeof(sz_long)*CLASS_BUFF_SIZE);
sz_short* buffer = (sz_short*) malloc(sizeof(sz_short)*CLASS_BUFF_SIZE);
FILE* file = fopen(filename, "r");
if(!file) printf("ERROR: Cannot open label file");
for (; count < CLASS_BUFF_SIZE; ++count)
{
int got = fscanf(file, "%"SCNu64"\t%"SCNu8"", &indexes[count] , &buffer[count]);
if (got != 2) break; // wrong number of tokens - maybe end of file
}
fclose(file);
buffer = realloc(buffer,sizeof(sz_short)*count);
indexes = realloc(indexes,sizeof(sz_long)*count);
sz_short num_class = max_u8( buffer, count);
sz_long length = max_u64( indexes, count);
// printf("LENGTH %"PRIu64"\n",length);
one_hot_mat all_labels = init_one_hot(num_class , length);
for(sz_long i=0;i<count;i++) all_labels.bin[buffer[i]-1][indexes[i]-1]=1;
*label_count = length;
free(indexes);
free(buffer);
return all_labels;
}
// Sort A and ind with respect to indexes in ind
void my_relative_sorting( sz_long* ind, class_t* A, sz_long len ){
sz_long* temp = (sz_long*)malloc(len*sizeof(sz_long));
sz_long* sorted_inds = (sz_long*)malloc(len*sizeof(sz_long));
for(sz_long i=0;i<len;i++){ temp[i] = i ;}
sz_long** zipped_arrays = zip_arrays(ind,temp,len);
qsort( zipped_arrays , len, sizeof(zipped_arrays[0]), compare);
unzip_array(zipped_arrays, temp, sorted_inds, len );
rearange(sorted_inds, (void*) A, "class_t" , len );
free(temp);
free(sorted_inds);
}
//Zip two arrays into a list of length-2 lists
sz_long** zip_arrays(sz_long* A, sz_long* B, sz_long len){
sz_long** zipped = (sz_long**)malloc(len*sizeof(sz_long*));
for(sz_long i=0;i<len;i++){
zipped[i] = (sz_long*)malloc(2*sizeof(sz_long));
** (zipped +i) = A[i];
*(* (zipped +i)+1) = B[i];
}
return zipped;
}
//Unzip two arrays into input pointers and destroy zipped array
void unzip_array(sz_long** zipped, sz_long* unzip_1, sz_long* unzip_2, sz_long len ){
for(sz_long i=0;i<len;i++){
unzip_1[i] = zipped[i][0];
unzip_2[i] = zipped[i][1];
free(*(zipped+i));
}
free(zipped);
}
//Rearange elements of array A accortding to given indexes
//Works for any type of array as long as the type is provided
void rearange(sz_long* ind, void* A, char* type , sz_long len ){
if(strcmp(type,"double")==0){
double A_temp[len];
memcpy(A_temp, A, len*sizeof(double));
for(sz_long i=0;i<len;i++){ *((double*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"sz_long")==0){
sz_long A_temp[len];
memcpy(A_temp, A, len*sizeof(sz_long));
for(sz_long i=0;i<len;i++){ *((sz_long*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"uint32_t")==0){
uint32_t A_temp[len];
memcpy(A_temp, A, len*sizeof(uint32_t));
for(sz_long i=0;i<len;i++){ *((uint32_t*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"sz_med")==0){
sz_med A_temp[len];
memcpy(A_temp, A, len*sizeof(sz_med));
for(sz_long i=0;i<len;i++){ *((sz_med*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"sz_short")==0){
sz_short A_temp[len];
memcpy(A_temp, A, len*sizeof(sz_short));
for(sz_long i=0;i<len;i++){ *((sz_short*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"int32_t")==0){
int32_t A_temp[len];
memcpy(A_temp, A, len*sizeof(int32_t));
for(sz_long i=0;i<len;i++){ *((int32_t*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"int16_t")==0){
int16_t A_temp[len];
memcpy(A_temp, A, len*sizeof(int16_t));
for(sz_long i=0;i<len;i++){ *((int16_t*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"class_t")==0){
class_t A_temp[len];
memcpy(A_temp, A, len*sizeof(class_t));
for(sz_long i=0;i<len;i++){ *((class_t*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"long double")==0){
long double A_temp[len];
memcpy(A_temp, A, len*sizeof(long double));
for(sz_long i=0;i<len;i++){ *((long double*)A + i) = A_temp[ind[i]];}
}else if(strcmp(type,"int")==0){
int A_temp[len];
memcpy(A_temp, A, len*sizeof(int));
for(sz_long i=0;i<len;i++){ *((int*)A + i) = A_temp[ind[i]];}
}else{
printf("Unknown rearange type\n");
exit(EXIT_FAILURE);
}
}
//Remove items of given indexes from array (list)
// Return result in NEW list
sz_long* remove_from_list(const sz_long* list, const sz_long* indexes_to_be_removed,
sz_long len, sz_long num_removed ){
sz_long* new_list = (sz_long*) malloc((len-num_removed)*sizeof(sz_long));
int mask[len];
memset(mask, 0, len*sizeof(int));
for(sz_long i =0; i<num_removed; i++){ mask[indexes_to_be_removed[i]] =1 ;}
sz_long k=0;
for(sz_long i =0; i<len; i++){
if(mask[i]==0){
new_list[k++] = list[i];
}
}
return new_list;
}
//Find unique elements among known number of entries in buffer
//Also eturn number of unique entries
sz_short find_unique(class_t* unique_elements, const class_t* buffer,sz_med N){
sz_short new,end=1;
unique_elements[0]=buffer[0];
for(sz_med i=0;i<N;i++){
new=1;
for(sz_short j=0;j<end;j++)
{if(unique_elements[j]==buffer[i])
new=0;}
if(new)
unique_elements[end++]=buffer[i];
}
return end;
}
//Find unique entries from list of sorted (unisgned indexes)
sz_long* find_unique_from_sorted( sz_long* sorted_buffer, sz_long len , sz_med* num_unique ){
sz_long* unique = (sz_long*) malloc(len*sizeof(sz_long));
*num_unique = 1;
unique[0] = sorted_buffer[0];
for(sz_long i=1;i<len;i++){
if(!(sorted_buffer[i] == sorted_buffer[i-1] )){
*num_unique += 1;
unique[*num_unique-1] = sorted_buffer[i];
}
}
unique = realloc(unique,*num_unique*sizeof(sz_long));
return unique;
}
// Converts list to one hot binary matrix of one_hot_mat type
// Label count is number of indexes with known labels
// label_count<=length
// If label_count<=length, then rows of the one_hot matrix
// without a coresponding labeled index will be [0...0]
one_hot_mat list_to_one_hot( sz_long* ind , class_t* labels, sz_short num_class ,
class_t* class , sz_long label_count ,sz_long length){
one_hot_mat one_hot = init_one_hot( num_class , length);
for(sz_long i=0;i<label_count;i++){
for(sz_short j=0;j<num_class;j++){
if( labels[i] == class[j] ){
one_hot.bin[j][ind[i]]=1;
break;
}
}
}
return one_hot;
}
//Allocate one_hot_mat
one_hot_mat init_one_hot(sz_short num_class ,sz_long length){
one_hot_mat one_hot;
one_hot.bin = (sz_short**) malloc(num_class*sizeof(sz_short*));
for(sz_short i=0;i<num_class;i++){
one_hot.bin[i] = (sz_short*) malloc(length*sizeof(sz_short));
for(sz_long j=0;j<length;j++){
one_hot.bin[i][j] =0 ;
}
}
one_hot.num_class = num_class;
one_hot.length = length;
return one_hot;
}
// Destroy (free) one_hot matrix
void destroy_one_hot(one_hot_mat one_hot){
for(sz_short i=0;i<one_hot.num_class;i++) free(one_hot.bin[i]);
free(one_hot.bin);
}
// Return array with number of non-zero entries in each row of one-hot-matrix
sz_short* return_num_labels_per_node( one_hot_mat one_hot ){
sz_short* num_labels = (sz_short*)malloc(one_hot.length*sizeof(sz_short));
for(sz_long i=0;i<one_hot.length;i++){
num_labels[i]=0;
for(sz_short j=0;j<one_hot.num_class;j++) num_labels[i]+= one_hot.bin[j][i];
}
return num_labels;
}
// Return a one_hot_mat with non-zeros for each row given to
// the k-largest (specified by num_lpn) corresponding soft labels
// Does not do sorting and has O(kC) complexity per node instead
// of O(C logC). Will be slow if C and k large
one_hot_mat top_k_mlabel( double* soft_labels , sz_short* num_lpn, sz_long length, sz_short num_class ){
double max_max,max,val;
sz_short max_ind;
one_hot_mat label_out = init_one_hot(num_class ,length);
for(sz_long i=0; i<length;i++ ){
max_max =1.1f;
for(sz_short k = 0; k<num_lpn[i];k++){
max = 0.0f;
for(sz_short j=0; j<num_class ;j++ ){
val = soft_labels[j*length +i];
if( ( val < max_max) && (val > max) ){
max = val;
max_ind = j;
}
}
max_max = max;
label_out.bin[max_ind][i]=1;
}
}
return label_out;
}
// Computes rate of true positive, False positive and false negative
// A binary mask determines which values I am interested in (usually unlabeled entries..)
detector_stats get_detector_stats( sz_short* true_val, sz_short* pred_val, sz_long len, int* mask ){
detector_stats stats = {.true_pos = 0.0,
.true_neg =0.0,
.false_pos = 0.0,
.false_neg = 0.0};
sz_long k=0;
for(sz_long i=0;i<len;i++){
if(mask[i]!=0){
k++;
if(true_val[i]==1){
if(pred_val[i]==1){
stats.true_pos+=1.0;
}else{
stats.false_neg+=1.0;
}
}else{
if(pred_val[i]==1){
stats.false_pos+=1.0;
}else{
stats.true_neg+=1.0;
}
}
}
}
stats.true_pos/=(double) k;
stats.true_neg/=(double) k;
stats.false_pos/=(double) k;
stats.false_neg/=(double) k;
return stats;
}
// Harmonic mean of 2 real numbers
double harmonic_mean( double x, double y ){
if(x+y == 0.0f){
printf("ERROR: Harmonic mean evaluated at 0\n ");
exit(EXIT_FAILURE);
}
return (2.0f*(x*y))/(x+y);
}
// Produce micro and macro averaged precision and recall
// Input is the more simple detector_stats for different classes
classifier_stats get_class_stats(detector_stats* all_stats , sz_short num_class ){
classifier_stats stats = {.micro_precision=0.0f,
.macro_precision=0.0f,
.micro_recall=0.0f,
.macro_recall=0.0f };
double sum_of_true_pos = 0.0f, micro_prec_denom = 0.0f, micro_recall_denom = 0.0f ;
for(sz_short i=0; i<num_class;i++){
sum_of_true_pos += all_stats[i].true_pos;
micro_prec_denom += all_stats[i].true_pos + all_stats[i].false_pos;
micro_recall_denom += all_stats[i].true_pos + all_stats[i].false_neg;
stats.macro_precision += all_stats[i].true_pos/( all_stats[i].true_pos + all_stats[i].false_pos );
stats.macro_recall += all_stats[i].true_pos/( all_stats[i].true_pos + all_stats[i].false_neg );
}
stats.micro_precision = sum_of_true_pos/micro_prec_denom;
stats.micro_recall = sum_of_true_pos/micro_recall_denom;
stats.macro_precision /= (double) num_class;
stats.macro_recall /= (double) num_class;
return stats;
}
// Takes array of detector statistics as input and returns array with f-1 scores for every class
void get_per_class_f1_scores(double* f1_per_class, detector_stats* all_stats, sz_short num_class ){
for(sz_short i=0;i<num_class;i++){
double TP = all_stats[i].true_pos;
double FN = all_stats[i].false_neg;
double FP = all_stats[i].false_pos;
f1_per_class[i] = 2.0*TP / ( 2.0*TP + FN + FP );
}
}
// Computes Micro and Macro f1-score
// Inputs must be one_hot structs
// f1_scores are only evaluated on the indexes denoted by unlabeled
f1_scores get_averaged_f1_scores( one_hot_mat true_labels, one_hot_mat pred_labels,
sz_long* unlabeled , sz_long num_unlabeled ){
if( (true_labels.num_class != pred_labels.num_class) || (true_labels.length != pred_labels.length) ){
printf("Classifier stats ERROR: One-hot matrixes dimensions dont match\n");
exit(EXIT_FAILURE);
}
int mask[true_labels.length];
memset(mask, 0 , true_labels.length*sizeof(int));
for(sz_long i=0;i< num_unlabeled; i++ ){ mask[unlabeled[i]]=1; }
// Start by gathering detection statistics per each class
detector_stats all_stats[true_labels.num_class];
for(sz_short i=0;i<true_labels.num_class;i++){
all_stats[i] = get_detector_stats( true_labels.bin[i] , pred_labels.bin[i] , true_labels.length , mask );
}
// Use detection stats to get Micro and Macro averaged F1 scores
f1_scores scores = {.micro = 0.0f,
.macro = 0.0f };
classifier_stats class_stats = get_class_stats(all_stats , true_labels.num_class );
double f1_per_class[true_labels.num_class];
get_per_class_f1_scores(f1_per_class, all_stats, true_labels.num_class);
scores.micro = harmonic_mean(class_stats.micro_precision, class_stats.micro_recall );
scores.macro = mean( f1_per_class, (int)true_labels.num_class );
/*
This definition of Macro F1 (using macro averaged precision and recall) does not seem to work well
scores.macro = harmonic_mean(class_stats.macro_precision, class_stats.macro_recall ); //
*/
return scores;
}
//Compute error rate
double accuracy(class_t* true_label, class_t* pred, sz_long* unlabeled, sz_long num_unlabeled){
double sum=0.0;
for(sz_long i=0;i<num_unlabeled;i++){
if(true_label[unlabeled[i]]==pred[unlabeled[i]])
sum+=1.0;
}
return sum/(double)num_unlabeled;
}
| {
"alphanum_fraction": 0.6447718126,
"avg_line_length": 27.0133333333,
"ext": "c",
"hexsha": "b37971f90182c8b293ba329799567964eb51b95f",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2019-05-16T08:23:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-24T03:55:53.000Z",
"max_forks_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "nikolakopoulos/Adaptive-Diffusions-for-SSL",
"max_forks_repo_path": "src/my_utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5",
"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": "nikolakopoulos/Adaptive-Diffusions-for-SSL",
"max_issues_repo_path": "src/my_utils.c",
"max_line_length": 117,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "8ca9ca6f595a5da718850f3dcf3607c9ebf51c92",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "DimBer/SSL_lib",
"max_stars_repo_path": "src/my_utils.c",
"max_stars_repo_stars_event_max_datetime": "2019-07-31T15:11:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-24T03:57:57.000Z",
"num_tokens": 7919,
"size": 26338
} |
//#include "readArray.h"
//#include "tensor_train.h"
#include "matrix.h"
#include "tensor.h"
#include "sketch.h"
#include "tt.h"
#include "VTime.h"
#include "readArray_MPI.h"
#include "PSTT.h"
#include "my_io.h"
#include "SSTT.h"
#include <omp.h>
#include <stdio.h>
#include <cblas.h>
#include <lapacke.h>
#include <math.h>
#include <string.h>
#include <gperftools/heap-profiler.h>
#ifndef HEAD
#define HEAD ((int) 0)
#endif
#ifndef FILE_BUF
#define FILE_BUF ((int) 256)
#endif
VTime_gathered* get_TT(tensor_train* tt, MPI_tensor* ten, int mid, int solvetype, int *heap_profile, char* path, long* total_alloc_ptr);
void MyHeapProfilerStart(int heap_profile, char* path, char* prefix, int rank)
{
if (heap_profile){
char* profile_path = (char*) calloc(FILE_BUF, sizeof(char));
snprintf(profile_path, FILE_BUF, "%s%s%d", path, prefix, rank);
HeapProfilerStart(profile_path);
}
}
void MyHeapProfilerStop(int* heap_profile, char* path, char* prefix, int rank, long* total_alloc_ptr)
{
if (*heap_profile){
HeapProfilerDump("");
HeapProfilerStop();
char file_name[256];
sprintf(file_name, "%s%s%d.000%d.heap", path, prefix, rank, *heap_profile);
FILE *f = fopen(file_name, "r");
while(f){
*heap_profile = *heap_profile + 1;
sprintf(file_name, "%s%s%d.000%d.heap", path, prefix, rank, *heap_profile);
f = fopen(file_name, "r");
}
sprintf(file_name, "%s%s%d.000%d.heap", path, prefix, rank, *heap_profile - 1);
f = fopen(file_name, "r");
char total_alloc_str[256];
char c = fgetc(f);
while( c != '['){
c = fgetc(f);
}
while( c != ':'){
c = fgetc(f);
}
c = fgetc(f);
int ii = 0;
while( c != ']'){
if (c != ' '){
total_alloc_str[ii] = c;
ii = ii+1;
}
c = fgetc(f);
}
total_alloc_str[ii] = '\0';
int info = sscanf(total_alloc_str, "%ld", total_alloc_ptr);
// printf("total_alloc_str = %s, total_alloc = %ld\n", total_alloc_str, *total_alloc_ptr);
// long MB = 1;
// for (int ii = 0; ii < 20; ++ii){
// MB = MB * 2;
// }
// printf("size = %f MB\n ", (double) *total_alloc_ptr / MB);
}
}
long* gather_heap_data(int heap_profile, long* total_allocs, int size, int rank, MPI_Comm comm)
{
int head = 0;
long* total_allocs_matrix = NULL;
if (heap_profile){
if (rank == head){
total_allocs_matrix = (long*) calloc((size + 1)*3, sizeof(long));
}
MPI_Gather(total_allocs, 3, MPI_LONG, total_allocs_matrix + 3, 3, MPI_LONG, head, comm);
for (int ii = 0; ii < size; ++ii){
for (int jj = 0; jj < 3; ++jj){
total_allocs[jj + ii*3];
}
}
if (rank == head){
for (int jj = 1; jj < size + 1; ++jj){
for (int ii = 0; ii < 3; ++ii){
total_allocs_matrix[ii] += total_allocs_matrix[ii + jj*3];
}
}
long MB = 1;
for (int ii = 0; ii < 20; ++ii){
MB = MB*2;
}
printf("TOTAL ALGORITHM SIZE = %f\n", (double) total_allocs_matrix[2]/MB);
}
}
return total_allocs_matrix;
}
//Input:
// argv[1] = solvetype
// argv[2] = tensortype
// -d = dimension
// -n = sizes
// -r = ranks
// -p = path
// -e = nps
// -m = mid (optional)
// -h = heap_profile
// -M = M for gaussian bumps (only for tensortype == 2)
// -g = gamma for gaussian bumps (only for tensortype == 2)
int main (int argc, char *argv[])
{
MPI_Init(&argc, &argv);
int world_rank;
int world_size;
MPI_Comm comm_world = MPI_COMM_WORLD;
MPI_Comm_rank(comm_world, &world_rank);
MPI_Comm_size(comm_world, &world_size);
if (world_rank == HEAD){ printf("Starting MPI_timing\n");}
int solvetype = atoi(argv[1]);
int tensortype = atoi(argv[2]);
int* dvec = NULL;
int d = 0;
int* midvec = NULL;
int mid = -1;
int* heap_profile_vec = NULL;
int heap_profile = 0;
int* nps = NULL;
int* n = NULL;
int* r = NULL;
void (*f_ten)(double* restrict, int*, int*, const void*);
void* parameters = NULL;
long* total_allocs = NULL;
double acc = 1e-10;
// Taken chars: 'd', 'm', 'n', 'r', 'p', 'e', 'g'
dvec = get_int_star_input('d', 1, argc, argv);
if (dvec == NULL){
printf("No input d for Hilbert Tensor\n");
MPI_Finalize();
return 0;
}
else{
d = dvec[0];
}
midvec = get_int_star_input('m', 1, argc, argv);
if (midvec != NULL){
mid = midvec[0];
}
// 'e' is for 'eeeeeeeeh-nps'
nps = get_int_star_input('e', d, argc, argv);
if (nps == NULL){
printf("No input nps\n");
MPI_Finalize();
return 0;
}
n = get_int_star_input('n', d, argc, argv);
if (n == NULL){
printf("No input n\n");
MPI_Finalize();
return 0;
}
r = get_int_star_input('r', d+1, argc, argv);
if (r == NULL){
printf("No input r\n");
MPI_Finalize();
return 0;
}
char* path = get_string_input ('p', argc, argv);
if (path == NULL){
printf("Must input path with -p\n");
MPI_Finalize();
return 0;
}
heap_profile_vec = get_int_star_input('h', 1, argc, argv);
if (heap_profile_vec != NULL){
heap_profile = *heap_profile_vec;
total_allocs = (long*) calloc(3, sizeof(long));
}
// Get the tensor pointer (I have _no_ idea how to make a function for this anymore)
if (tensortype == 1){
f_ten = &f_hilbert;
parameters = p_hilbert_init(d, n);
}
else if (tensortype == 2){
int* Mvec = NULL;
int M;
Mvec = get_int_star_input('M', 1, argc, argv);
if (Mvec != NULL){
M = Mvec[0];
}
else{
printf("Must input M with -M when tensortype == 2\n");
MPI_Finalize();
return 0;
}
double* gammavec = NULL;
double gamma;
gammavec = get_double_star_input('g', 1, argc, argv);
if (gammavec != NULL){
gamma = gammavec[0];
}
else{
printf("Must input gamma with -g when tensortype == 2\n");
MPI_Finalize();
return 0;
}
int seed = 168234591; // Arbitrary number
parameters = unit_random_p_gaussian_bumps_init(d, n, M, gamma, seed);
f_ten = &f_gaussian_bumps;
free(gammavec); gammavec = NULL;
free(Mvec); Mvec = NULL;
}
MyHeapProfilerStart(heap_profile, path, ".tt", world_rank);
tensor_train* tt = TT_init_rank(d, n, r);
MyHeapProfilerStop(&heap_profile, path, ".tt", world_rank, total_allocs);
MyHeapProfilerStart(heap_profile, path, ".ten", world_rank);
MPI_tensor* ten = MPI_tensor_init(d, n, nps, MPI_COMM_WORLD, f_ten, parameters);
MyHeapProfilerStop(&heap_profile, path, ".ten", world_rank, total_allocs + 1);
VTime_gathered* tms = get_TT(tt, ten, mid, solvetype, &heap_profile, path, total_allocs + 2);
if (world_rank == HEAD){ printf("Got the tensor train\n");}
if (solvetype == 1){
ten = MPI_tensor_init(d, n, nps, MPI_COMM_WORLD, f_ten, parameters);
}
double err = tt_error(tt, ten);
if (world_rank == HEAD){
printf("ERROR = %e\n", err);
printf("TIME = %f\n", tms->t[0]);
}
MPI_tensor_free(ten);
long* total_allocs_matrix = gather_heap_data(heap_profile, total_allocs, world_size, world_rank, comm_world);
if (world_rank == HEAD){
my_tt_write(tt, tms, err, nps, tensortype, solvetype, path, total_allocs_matrix);
}
if (tms != NULL){;
VTime_gathered_free(tms); tms = NULL;
}
TT_free(tt); tt = NULL;
if (tensortype == 1){
p_hilbert_free(parameters); parameters = NULL;
}
else if (tensortype == 2){
p_gaussian_bumps_free(parameters); parameters = NULL;
}
free(r); r = NULL;
free(n); n = NULL;
free(nps); nps = NULL;
free(midvec); midvec = NULL;
free(dvec); dvec = NULL;
free(total_allocs); total_allocs = NULL;
free(heap_profile_vec); heap_profile_vec = NULL;
MPI_Finalize();
return 0;
}
/* Key for argv[1]
* 1 : streaming_SSTT
* 2 : streaming_PSTT2
* 3 : streaming_PSTT2_onepass
*/
VTime_gathered* get_TT(tensor_train* tt, MPI_tensor* ten, int mid, int solvetype, int *heap_profile, char* path, long* total_alloc_ptr)
{
VTime* tm;
int world_rank = ten->rank;
MPI_Comm comm = ten->comm;
if (world_rank==HEAD){ printf("Getting the tensor train ("); }
if (solvetype == 1){
if (world_rank==HEAD){ printf("SSTT)\n"); }
MyHeapProfilerStart(*heap_profile, path, ".SSTT", world_rank);
tm = SSTT(tt, ten);
MyHeapProfilerStop(heap_profile, path, ".SSTT", world_rank, total_alloc_ptr);
}
if (solvetype == 2){
if (world_rank==HEAD){ printf("PSTT2)\n"); }
MyHeapProfilerStart(*heap_profile, path, ".PSTT", world_rank);
tm = PSTT2(tt, ten, mid);
MyHeapProfilerStop(heap_profile, path, ".PSTT", world_rank, total_alloc_ptr);
}
if (solvetype == 3){
if (world_rank==HEAD){ printf("PSTT2_onepass)\n"); }
MyHeapProfilerStart(*heap_profile, path, ".PSTT_onepass", world_rank);
tm = PSTT2_onepass(tt, ten, mid);
MyHeapProfilerStop(heap_profile, path, ".PSTT_onepass", world_rank, total_alloc_ptr);
}
if (world_rank==HEAD){ printf("Got tensor train\n");}
VTime_gathered* tms = VTime_gather(tm, comm);
if (tm != NULL){
VTime_free(tm); tm = NULL;
}
return tms;
} | {
"alphanum_fraction": 0.5611402095,
"avg_line_length": 27.5013850416,
"ext": "c",
"hexsha": "4758cfe08a6c6c0140505ffef86bf10eb6c0f9cb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SidShi/Parallel_TT_sketching",
"max_forks_repo_path": "test/MPI_timing.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SidShi/Parallel_TT_sketching",
"max_issues_repo_path": "test/MPI_timing.c",
"max_line_length": 136,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SidShi/Parallel_TT_sketching",
"max_stars_repo_path": "test/MPI_timing.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2875,
"size": 9928
} |
#include <assert.h>
#include <gsl/gsl_sf_gamma.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include "index.h"
#include "parse_mmaps.h"
#include "probability.h"
double reference_probability(const struct mmap_info* mmap_info,
struct revision_assignment* parent,
struct revision_assignment* child,
int disagrees,
const struct index_patch* index_patch) {
double action_prob = 1.0;
if (parent != NULL && parent->topic >= 0 && parent->pov >= 0
&& child->topic >= 0 && child->pov >= 0) {
struct revision_assignment_header* revision_assignment_header
= (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;
struct topic_summary* topic_summary;
struct pov_summary* pov_dist;
get_topic_summary(mmap_info, child->topic, &topic_summary, &pov_dist, NULL);
if (parent->topic == child->topic) {
if (parent->pov != child->pov) {
// POV reference
struct pov_summary* pov_summary = get_ant_pov(mmap_info, pov_dist,
child->pov, parent->pov);
double denom = (double)(pov_summary->norevert_count
+ pov_summary->revert_count)
+ revision_assignment_header->psi_alpha
+ revision_assignment_header->psi_beta;
int correction = 0;
if (index_patch != NULL
&& index_patch->topic == child->topic
&& index_patch->pov == child->pov
&& index_patch->parent_pov == parent->pov
&& index_patch->parent_topic == index_patch->topic) {
assert(denom -= 1.0 >= 0.0);
if (!disagrees == !(index_patch->disagrees)) {
correction += 1;
}
}
if (index_patch != NULL
&& index_patch->child_topic == child->topic
&& index_patch->child_pov == child->pov
&& index_patch->pov == parent->pov
&& index_patch->topic == index_patch->child_topic) {
assert(denom -= 1.0 >= 0.0);
if (!disagrees == !(index_patch->child_disagrees)) {
correction += 1;
}
}
if (disagrees) {
action_prob *= ((double)(pov_summary->revert_count
- correction)
+ revision_assignment_header->psi_alpha) / denom;
} else {
action_prob *= ((double)(pov_summary->norevert_count
- correction)
+ revision_assignment_header->psi_beta) / denom;
}
} else {
// topic reference
double denom = (double)(topic_summary->revert_topic_count
+ topic_summary->norevert_topic_count
+ revision_assignment_header->gamma_alpha
+ revision_assignment_header->gamma_beta);
int correction = 0;
if (index_patch != NULL
&& index_patch->topic == child->topic
&& index_patch->parent_pov == index_patch->pov
&& index_patch->parent_topic == index_patch->topic) {
assert(denom -= 1.0 >= 0.0);
if (!disagrees == !(index_patch->disagrees)) {
correction += 1;
}
}
if (index_patch != NULL
&& index_patch->child_topic == child->topic
&& index_patch->pov == index_patch->child_pov
&& index_patch->topic == index_patch->child_topic) {
assert(denom -= 1.0 >= 0.0);
if (!disagrees == !(index_patch->child_disagrees)) {
correction += 1;
}
}
if (disagrees) {
action_prob *= ((double)(topic_summary->revert_topic_count
- correction)
+ revision_assignment_header->gamma_alpha) / denom;
} else {
action_prob *= ((double)(topic_summary->norevert_topic_count
- correction)
+ revision_assignment_header->gamma_beta) / denom;
}
}
} else {
// general reference
double denom = (double)(topic_summary->revert_general_count
+ topic_summary->norevert_general_count)
+ revision_assignment_header->gamma_alpha
+ revision_assignment_header->gamma_beta;
int correction = 0;
if (index_patch != NULL
&& index_patch->parent_topic >= 0
&& index_patch->topic == child->topic
&& index_patch->parent_topic != index_patch->topic) {
assert(denom -= 1.0 >= 0.0);
if (!disagrees == !(index_patch->disagrees)) {
correction += 1;
}
}
if (index_patch != NULL
&& index_patch->topic >= 0
&& index_patch->child_topic == child->topic
&& index_patch->topic != index_patch->child_topic) {
assert(denom -= 1.0 >= 0.0);
if (!disagrees == !(index_patch->child_disagrees)) {
correction = 1;
}
}
if (disagrees) {
action_prob *= ((double)(topic_summary->revert_general_count
- correction)
+ revision_assignment_header->gamma_alpha) / denom;
} else {
action_prob *= ((double)(topic_summary->norevert_general_count
- correction)
+ revision_assignment_header->gamma_beta) / denom;
}
}
} // Else, a constant not dependant on POV or topic
assert(action_prob > 0.0);
return action_prob;
}
double revision_probability(const struct mmap_info* mmap_info, int64_t revision_id,
int32_t topic, int32_t pov,
int include_child,
int include_user_topic_pov,
const struct index_patch* index_patch) {
const struct revision* revision = get_revision(mmap_info, revision_id);
struct revision_assignment current_assignment;
current_assignment.topic = topic;
current_assignment.pov = pov;
double ret = 1.0;
// Revert probability
if (revision->parent >= 0) {
ret *= reference_probability(mmap_info,
get_revision_assignment(mmap_info, revision->parent),
¤t_assignment, revision->disagrees,
index_patch);
}
if (revision->child >= 0 && include_child) {
ret *= reference_probability(mmap_info, ¤t_assignment,
get_revision_assignment(mmap_info, revision->child),
get_revision(mmap_info, revision->child)->disagrees,
index_patch);
}
// Topic, pov probability
struct revision_assignment_header* revision_assignment_header
= (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;
if (include_user_topic_pov) {
int pov_correction = 0;
if (index_patch
&& index_patch->user == revision->user
&& pov == index_patch->pov
&& topic == index_patch->topic) {
pov_correction = 1;
}
double* user_pov_dist;
get_user_topics(mmap_info, revision->user, &user_pov_dist);
// Alpha is already added to this array. The normalizing constant is
// independant of topic/pov, so we exclude it here.
ret *= (user_pov_dist[topic * revision_assignment_header->pov_per_topic + pov]
- pov_correction);
}
// Page probability
struct topic_summary_header* topic_summary_header
= (struct topic_summary_header*)mmap_info->topic_index_mmap;
int64_t* page_dist;
struct topic_summary* topic_summary;
get_topic_summary(mmap_info, topic, &topic_summary, NULL, &page_dist);
int64_t topic_page_revisions = page_dist[revision->article];
int64_t topic_revisions = topic_summary->total_revisions;
if (index_patch && index_patch->topic == topic) {
topic_revisions -= 1;
if (index_patch->page == revision->article) {
topic_page_revisions -= 1;
}
}
ret *= ((double)(topic_page_revisions) + revision_assignment_header->beta)
/ ((double)(topic_revisions)
+ revision_assignment_header->beta * topic_summary_header->num_pages);
assert(ret > 0.0);
return ret;
}
void fill_index_patch(const struct mmap_info* mmap_info,
int64_t revision_id,
struct index_patch* index_patch) {
const struct revision* revision = get_revision(mmap_info, revision_id);
index_patch->user = revision->user;
index_patch->page = revision->article;
const struct revision_assignment* revision_assignment
= get_revision_assignment(mmap_info, revision_id);
index_patch->topic = revision_assignment->topic;
index_patch->pov = revision_assignment->pov;
index_patch->disagrees = revision->disagrees;
if (revision->parent >= 0) {
const struct revision_assignment* parent_assignment
= get_revision_assignment(mmap_info, revision->parent);
index_patch->parent_topic = parent_assignment->topic;
index_patch->parent_pov = parent_assignment->pov;
} else {
index_patch->parent_topic = -1;
index_patch->parent_pov = -1;
}
if (revision->child >= 0) {
const struct revision_assignment* child_assignment
= get_revision_assignment(mmap_info, revision->child);
index_patch->child_topic = child_assignment->topic;
index_patch->child_pov = child_assignment->pov;
index_patch->child_disagrees = get_revision(mmap_info,
revision->child)->disagrees;
} else {
index_patch->child_topic = -1;
index_patch->child_pov = -1;
index_patch->child_disagrees = -1;
}
}
double users_pages_probability_modn(const struct mmap_info* mmap_info, int sample, int modn) {
struct revision_assignment_header* revision_assignment_header
= (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;
struct user_topic_header* user_topic_header = (struct user_topic_header*)mmap_info->user_topic_mmap;
double log_likelihood = 0.0;
int64_t user_edits;
double* user_topic_pov_dist;
int topic_pov_count
= revision_assignment_header->num_topics * revision_assignment_header->pov_per_topic;
for (int64_t user_num = sample; user_num < user_topic_header->num_users; user_num += modn) {
get_user(mmap_info, user_num, &user_edits, NULL);
get_user_topics(mmap_info, user_num, &user_topic_pov_dist);
if (user_edits <= 0) {
// This user does not actually exist
continue;
}
log_likelihood -= gsl_sf_lngamma(user_edits + revision_assignment_header->alpha * topic_pov_count);
for (int topic = 0; topic < revision_assignment_header->num_topics; ++topic) {
for (int pov = 0; pov < revision_assignment_header->pov_per_topic; ++pov) {
log_likelihood += gsl_sf_lngamma(user_topic_pov_dist[topic * revision_assignment_header->pov_per_topic
+ pov]);
}
}
}
struct topic_summary_header* topic_summary_header
= (struct topic_summary_header*)mmap_info->topic_index_mmap;
int64_t* page_dist;
for (int topic = 0; topic < revision_assignment_header->num_topics; ++topic) {
get_topic_summary(mmap_info, topic, NULL, NULL, &page_dist);
for (int64_t page = sample; page < topic_summary_header->num_pages; page += modn) {
log_likelihood += gsl_sf_lngamma(page_dist[page] + revision_assignment_header->beta);
}
}
return log_likelihood;
}
double log_likelihood(const struct mmap_info* mmap_info) {
return log_likelihood_gamma(mmap_info, 1);
}
double log_likelihood_gamma(const struct mmap_info* mmap_info, int include_users_pages) {
struct user_topic_header* user_topic_header = (struct user_topic_header*)mmap_info->user_topic_mmap;
struct revision_assignment_header* revision_assignment_header
= (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;
int topic_pov_count
= revision_assignment_header->num_topics * revision_assignment_header->pov_per_topic;
double log_likelihood = 0.0;
log_likelihood += user_topic_header->num_users
* gsl_sf_lngamma(revision_assignment_header->alpha * topic_pov_count);
log_likelihood -= user_topic_header->num_users * topic_pov_count
* gsl_sf_lngamma(revision_assignment_header->alpha);
if (include_users_pages) {
log_likelihood += users_pages_probability_modn(mmap_info, 0, 1);
}
struct topic_summary_header* topic_summary_header
= (struct topic_summary_header*)mmap_info->topic_index_mmap;
struct topic_summary* topic_summary;
struct pov_summary* pov_dist;
struct pov_summary* pov_summary;
log_likelihood += revision_assignment_header->num_topics
* gsl_sf_lngamma(revision_assignment_header->beta * topic_summary_header->num_pages);
log_likelihood -= revision_assignment_header->num_topics * topic_summary_header->num_pages
* gsl_sf_lngamma(revision_assignment_header->beta);
for (int topic = 0; topic < revision_assignment_header->num_topics; ++topic) {
get_topic_summary(mmap_info, topic, &topic_summary, &pov_dist, NULL);
log_likelihood -= gsl_sf_lngamma(topic_summary->total_revisions + revision_assignment_header->beta
* topic_summary_header->num_pages);
// General reverts
log_likelihood += gsl_sf_lngamma(topic_summary->revert_general_count
+ revision_assignment_header->gamma_alpha);
log_likelihood += gsl_sf_lngamma(topic_summary->norevert_general_count
+ revision_assignment_header->gamma_beta);
log_likelihood -= gsl_sf_lngamma(topic_summary->revert_general_count
+ topic_summary->norevert_general_count
+ revision_assignment_header->gamma_alpha
+ revision_assignment_header->gamma_beta);
// Topic reverts
log_likelihood += gsl_sf_lngamma(topic_summary->revert_topic_count
+ revision_assignment_header->gamma_alpha);
log_likelihood += gsl_sf_lngamma(topic_summary->norevert_topic_count
+ revision_assignment_header->gamma_beta);
log_likelihood -= gsl_sf_lngamma(topic_summary->revert_topic_count
+ topic_summary->norevert_topic_count
+ revision_assignment_header->gamma_alpha
+ revision_assignment_header->gamma_beta);
// POV reverts
for (int pov = 0; pov < revision_assignment_header->pov_per_topic; ++pov) {
for (int ant_pov = 0; ant_pov < revision_assignment_header->pov_per_topic - 1; ++ant_pov) {
pov_summary = pov_dist + pov * (revision_assignment_header->pov_per_topic - 1) + ant_pov;
log_likelihood += gsl_sf_lngamma(pov_summary->revert_count
+ revision_assignment_header->psi_alpha);
log_likelihood += gsl_sf_lngamma(pov_summary->norevert_count
+ revision_assignment_header->psi_beta);
log_likelihood -= gsl_sf_lngamma(pov_summary->revert_count
+ pov_summary->norevert_count
+ revision_assignment_header->psi_alpha
+ revision_assignment_header->psi_beta);
}
}
}
log_likelihood += 2 * revision_assignment_header->num_topics
* gsl_sf_lngamma(revision_assignment_header->gamma_alpha + revision_assignment_header->gamma_beta);
log_likelihood -= 2 * revision_assignment_header->num_topics
* gsl_sf_lngamma(revision_assignment_header->gamma_alpha);
log_likelihood -= 2 * revision_assignment_header->num_topics
* gsl_sf_lngamma(revision_assignment_header->gamma_beta);
log_likelihood += revision_assignment_header->pov_per_topic
* (revision_assignment_header->pov_per_topic - 1)
* revision_assignment_header->num_topics
* gsl_sf_lngamma(revision_assignment_header->psi_alpha + revision_assignment_header->psi_beta);
log_likelihood -= revision_assignment_header->pov_per_topic
* (revision_assignment_header->pov_per_topic - 1)
* revision_assignment_header->num_topics
* gsl_sf_lngamma(revision_assignment_header->psi_alpha);
log_likelihood -= revision_assignment_header->pov_per_topic
* (revision_assignment_header->pov_per_topic - 1)
* revision_assignment_header->num_topics
* gsl_sf_lngamma(revision_assignment_header->psi_beta);
return log_likelihood;
}
| {
"alphanum_fraction": 0.7252465217,
"avg_line_length": 41.0138504155,
"ext": "c",
"hexsha": "1fc1561359513e0248373b6283e2b662604383db",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "allenlavoie/topic-pov",
"max_forks_repo_path": "src/probability.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "allenlavoie/topic-pov",
"max_issues_repo_path": "src/probability.c",
"max_line_length": 103,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "allenlavoie/topic-pov",
"max_stars_repo_path": "src/probability.c",
"max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z",
"num_tokens": 3687,
"size": 14806
} |
/* 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 <gsl/gsl-lite.hpp>
#include <type_traits>
#if defined(_MSC_VER)
#ifdef NNCASE_DLL
#define NNCASE_API __declspec(dllexport)
#elif defined(NNCASE_SHARED_LIBS)
#define NNCASE_API __declspec(dllimport)
#else
#define NNCASE_API
#endif
#else
#define NNCASE_API
#endif
#if defined(_MSC_VER)
#define NNCASE_UNREACHABLE() __assume(0)
#else
#define NNCASE_UNREACHABLE() __builtin_unreachable()
#endif
#if gsl_CPP17_OR_GREATER
#define NNCASE_INLINE_VAR inline
#define NNCASE_UNUSED [[maybe_unused]]
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::invoke_result_t<Callable, Args...>;
}
#else
#define NNCASE_INLINE_VAR
#if defined(_MSC_VER)
#define NNCASE_UNUSED
#else
#define NNCASE_UNUSED __attribute__((unused))
#endif
namespace nncase
{
template <class Callable, class... Args>
using invoke_result_t = std::result_of_t<Callable(Args...)>;
}
#endif
#define NNCASE_LITTLE_ENDIAN 1
#define NNCASE_HAVE_STD_BYTE gsl_CPP17_OR_GREATER
#define NNCASE_NODISCARD gsl_NODISCARD
#define NNCASE_NORETURN gsl_NORETURN
#define BEGIN_NS_NNCASE_RUNTIME \
namespace nncase \
{ \
namespace runtime \
{
#define END_NS_NNCASE_RUNTIME \
} \
}
#define BEGIN_NS_NNCASE_RT_STACKVM \
namespace nncase \
{ \
namespace runtime \
{ \
namespace stackvm \
{
#define END_NS_NNCASE_RT_STACKVM \
} \
} \
}
#define BEGIN_NS_NNCASE_KERNELS \
namespace nncase \
{ \
namespace kernels \
{
#define END_NS_NNCASE_KERNELS \
} \
}
#ifndef DEFINE_ENUM_BITMASK_OPERATORS
#define DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE) gsl_DEFINE_ENUM_BITMASK_OPERATORS(ENUMTYPE)
#endif
namespace nncase
{
struct default_init_t
{
};
NNCASE_INLINE_VAR constexpr default_init_t default_init {};
}
| {
"alphanum_fraction": 0.6405859235,
"avg_line_length": 25.9166666667,
"ext": "h",
"hexsha": "af41d971b190a08c9b46960b5c224837806a6b2f",
"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": "d740f558940aefd2eaa8f358f1a81041f93155dc",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "HelloDavid2020/kendryte-standalone-sdk",
"max_forks_repo_path": "lib/nncase/v1/include/nncase/runtime/compiler_defs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d740f558940aefd2eaa8f358f1a81041f93155dc",
"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": "HelloDavid2020/kendryte-standalone-sdk",
"max_issues_repo_path": "lib/nncase/v1/include/nncase/runtime/compiler_defs.h",
"max_line_length": 92,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "d740f558940aefd2eaa8f358f1a81041f93155dc",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "HelloDavid2020/kendryte-standalone-sdk",
"max_stars_repo_path": "lib/nncase/v1/include/nncase/runtime/compiler_defs.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-11T08:32:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-11T08:32:10.000Z",
"num_tokens": 623,
"size": 2799
} |
#include <math.h>
#include <stdlib.h>
#include <drfftw_mpi.h>
#include <mpi.h>
#include <gsl/gsl_rng.h>
#include "allvars.h"
#include "proto.h"
int main(int argc, char **argv)
{
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask);
MPI_Comm_size(MPI_COMM_WORLD, &NTask);
if(argc < 2)
{
if(ThisTask == 0)
{
fprintf(stdout, "\nParameters are missing.\n");
fprintf(stdout, "Call with <ParameterFile>\n\n");
}
MPI_Finalize();
exit(0);
}
read_parameterfile(argv[1]);
set_units();
initialize_powerspectrum();
initialize_ffts();
read_glass(GlassFile);
displacement_fields();
write_particle_data();
if(NumPart)
free(P);
free_ffts();
if(ThisTask == 0)
{
printf("\nIC's generated.\n\n");
printf("Initial scale factor = %g\n", InitTime);
printf("\n");
}
MPI_Barrier(MPI_COMM_WORLD);
print_spec();
MPI_Finalize(); /* clean up & finalize MPI */
exit(0);
}
void displacement_fields(void)
{
MPI_Request request;
MPI_Status status;
gsl_rng *random_generator;
int i, j, k, ii, jj, kk, axes;
int n;
int sendTask, recvTask;
double fac, vel_prefac;
double kvec[3], kmag, kmag2, p_of_k;
double delta, phase, ampl, hubble_a;
double u, v, w;
double f1, f2, f3, f4, f5, f6, f7, f8;
double dis, maxdisp, max_disp_glob;
unsigned int *seedtable;
#ifdef CORRECT_CIC
double fx, fy, fz, ff, smth;
#endif
if(ThisTask == 0)
{
printf("\nstart computing displacement fields...\n");
fflush(stdout);
}
hubble_a =
Hubble * sqrt(Omega / pow(InitTime, 3) + (1 - Omega - OmegaLambda) / pow(InitTime, 2) + OmegaLambda);
vel_prefac = InitTime * hubble_a * F_Omega(InitTime);
vel_prefac /= sqrt(InitTime); /* converts to Gadget velocity */
if(ThisTask == 0)
printf("vel_prefac= %g hubble_a=%g fom=%g \n", vel_prefac, hubble_a, F_Omega(InitTime));
fac = pow(2 * PI / Box, 1.5);
maxdisp = 0;
random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
gsl_rng_set(random_generator, Seed);
if(!(seedtable = malloc(Nmesh * Nmesh * sizeof(unsigned int))))
FatalError(4);
for(i = 0; i < Nmesh / 2; i++)
{
for(j = 0; j < i; j++)
seedtable[i * Nmesh + j] = 0x7fffffff * gsl_rng_uniform(random_generator);
for(j = 0; j < i + 1; j++)
seedtable[j * Nmesh + i] = 0x7fffffff * gsl_rng_uniform(random_generator);
for(j = 0; j < i; j++)
seedtable[(Nmesh - 1 - i) * Nmesh + j] = 0x7fffffff * gsl_rng_uniform(random_generator);
for(j = 0; j < i + 1; j++)
seedtable[(Nmesh - 1 - j) * Nmesh + i] = 0x7fffffff * gsl_rng_uniform(random_generator);
for(j = 0; j < i; j++)
seedtable[i * Nmesh + (Nmesh - 1 - j)] = 0x7fffffff * gsl_rng_uniform(random_generator);
for(j = 0; j < i + 1; j++)
seedtable[j * Nmesh + (Nmesh - 1 - i)] = 0x7fffffff * gsl_rng_uniform(random_generator);
for(j = 0; j < i; j++)
seedtable[(Nmesh - 1 - i) * Nmesh + (Nmesh - 1 - j)] = 0x7fffffff * gsl_rng_uniform(random_generator);
for(j = 0; j < i + 1; j++)
seedtable[(Nmesh - 1 - j) * Nmesh + (Nmesh - 1 - i)] = 0x7fffffff * gsl_rng_uniform(random_generator);
}
for(axes = 0; axes < 3; axes++)
{
if(ThisTask == 0)
{
printf("\nstarting axes=%d...\n", axes);
fflush(stdout);
}
/* first, clean the array */
for(i = 0; i < Local_nx; i++)
for(j = 0; j < Nmesh; j++)
for(k = 0; k <= Nmesh / 2; k++)
{
Cdata[(i * Nmesh + j) * (Nmesh / 2 + 1) + k].re = 0;
Cdata[(i * Nmesh + j) * (Nmesh / 2 + 1) + k].im = 0;
}
for(i = 0; i < Nmesh; i++)
{
ii = Nmesh - i;
if(ii == Nmesh)
ii = 0;
if((i >= Local_x_start && i < (Local_x_start + Local_nx)) ||
(ii >= Local_x_start && ii < (Local_x_start + Local_nx)))
{
for(j = 0; j < Nmesh; j++)
{
gsl_rng_set(random_generator, seedtable[i * Nmesh + j]);
for(k = 0; k < Nmesh / 2; k++)
{
phase = gsl_rng_uniform(random_generator) * 2 * PI;
do
ampl = gsl_rng_uniform(random_generator);
while(ampl == 0);
if(i == Nmesh / 2 || j == Nmesh / 2 || k == Nmesh / 2)
continue;
if(i == 0 && j == 0 && k == 0)
continue;
if(i < Nmesh / 2)
kvec[0] = i * 2 * PI / Box;
else
kvec[0] = -(Nmesh - i) * 2 * PI / Box;
if(j < Nmesh / 2)
kvec[1] = j * 2 * PI / Box;
else
kvec[1] = -(Nmesh - j) * 2 * PI / Box;
if(k < Nmesh / 2)
kvec[2] = k * 2 * PI / Box;
else
kvec[2] = -(Nmesh - k) * 2 * PI / Box;
kmag2 = kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2];
kmag = sqrt(kmag2);
if(SphereMode == 1)
{
if(kmag * Box / (2 * PI) > Nsample / 2) /* select a sphere in k-space */
continue;
}
else
{
if(fabs(kvec[0]) * Box / (2 * PI) > Nsample / 2)
continue;
if(fabs(kvec[1]) * Box / (2 * PI) > Nsample / 2)
continue;
if(fabs(kvec[2]) * Box / (2 * PI) > Nsample / 2)
continue;
}
p_of_k = PowerSpec(kmag);
p_of_k *= -log(ampl);
delta = fac * sqrt(p_of_k) / Dplus; /* scale back to starting redshift */
#ifdef CORRECT_CIC
/* do deconvolution of CIC interpolation */
fx = fy = fz = 1;
if(kvec[0] != 0)
{
fx = (kvec[0] * Box / 2) / Nmesh;
fx = sin(fx) / fx;
}
if(kvec[1] != 0)
{
fy = (kvec[1] * Box / 2) / Nmesh;
fy = sin(fy) / fy;
}
if(kvec[2] != 0)
{
fz = (kvec[2] * Box / 2) / Nmesh;
fz = sin(fz) / fz;
}
ff = 1 / (fx * fy * fz);
smth = ff * ff;
delta *= smth;
/* end deconvolution */
#endif
if(k > 0)
{
if(i >= Local_x_start && i < (Local_x_start + Local_nx))
{
Cdata[((i - Local_x_start) * Nmesh + j) * (Nmesh / 2 + 1) + k].re =
-kvec[axes] / kmag2 * delta * sin(phase);
Cdata[((i - Local_x_start) * Nmesh + j) * (Nmesh / 2 + 1) + k].im =
kvec[axes] / kmag2 * delta * cos(phase);
}
}
else /* k=0 plane needs special treatment */
{
if(i == 0)
{
if(j >= Nmesh / 2)
continue;
else
{
if(i >= Local_x_start && i < (Local_x_start + Local_nx))
{
jj = Nmesh - j; /* note: j!=0 surely holds at this point */
Cdata[((i - Local_x_start) * Nmesh + j) * (Nmesh / 2 + 1) + k].re =
-kvec[axes] / kmag2 * delta * sin(phase);
Cdata[((i - Local_x_start) * Nmesh + j) * (Nmesh / 2 + 1) + k].im =
kvec[axes] / kmag2 * delta * cos(phase);
Cdata[((i - Local_x_start) * Nmesh + jj) * (Nmesh / 2 + 1) + k].re =
-kvec[axes] / kmag2 * delta * sin(phase);
Cdata[((i - Local_x_start) * Nmesh + jj) * (Nmesh / 2 + 1) + k].im =
-kvec[axes] / kmag2 * delta * cos(phase);
}
}
}
else /* here comes i!=0 : conjugate can be on other processor! */
{
if(i >= Nmesh / 2)
continue;
else
{
ii = Nmesh - i;
if(ii == Nmesh)
ii = 0;
jj = Nmesh - j;
if(jj == Nmesh)
jj = 0;
if(i >= Local_x_start && i < (Local_x_start + Local_nx))
{
Cdata[((i - Local_x_start) * Nmesh + j) * (Nmesh / 2 + 1) + k].re =
-kvec[axes] / kmag2 * delta * sin(phase);
Cdata[((i - Local_x_start) * Nmesh + j) * (Nmesh / 2 + 1) + k].im =
kvec[axes] / kmag2 * delta * cos(phase);
}
if(ii >= Local_x_start && ii < (Local_x_start + Local_nx))
{
Cdata[((ii - Local_x_start) * Nmesh + jj) * (Nmesh / 2 + 1) +
k].re = -kvec[axes] / kmag2 * delta * sin(phase);
Cdata[((ii - Local_x_start) * Nmesh + jj) * (Nmesh / 2 + 1) +
k].im = -kvec[axes] / kmag2 * delta * cos(phase);
}
}
}
}
}
}
}
}
rfftwnd_mpi(Inverse_plan, 1, Disp, Workspace, FFTW_NORMAL_ORDER); /** FFT **/
/* now get the plane on the right side from neighbour on the right,
and send the left plane */
recvTask = ThisTask;
do
{
recvTask--;
if(recvTask < 0)
recvTask = NTask - 1;
}
while(Local_nx_table[recvTask] == 0);
sendTask = ThisTask;
do
{
sendTask++;
if(sendTask >= NTask)
sendTask = 0;
}
while(Local_nx_table[sendTask] == 0);
/* use non-blocking send */
if(Local_nx > 0)
{
MPI_Isend(&Disp[0],
sizeof(fftw_real) * Nmesh * (2 * (Nmesh / 2 + 1)),
MPI_BYTE, recvTask, 10, MPI_COMM_WORLD, &request);
MPI_Recv(&Disp[(Local_nx * Nmesh) * (2 * (Nmesh / 2 + 1))],
sizeof(fftw_real) * Nmesh * (2 * (Nmesh / 2 + 1)),
MPI_BYTE, sendTask, 10, MPI_COMM_WORLD, &status);
MPI_Wait(&request, &status);
}
/* read-out displacements */
for(n = 0; n < NumPart; n++)
{
{
u = P[n].Pos[0] / Box * Nmesh;
v = P[n].Pos[1] / Box * Nmesh;
w = P[n].Pos[2] / Box * Nmesh;
i = (int) u;
j = (int) v;
k = (int) w;
if(i == (Local_x_start + Local_nx))
i = (Local_x_start + Local_nx) - 1;
if(i < Local_x_start)
i = Local_x_start;
if(j == Nmesh)
j = Nmesh - 1;
if(k == Nmesh)
k = Nmesh - 1;
u -= i;
v -= j;
w -= k;
i -= Local_x_start;
ii = i + 1;
jj = j + 1;
kk = k + 1;
if(jj >= Nmesh)
jj -= Nmesh;
if(kk >= Nmesh)
kk -= Nmesh;
f1 = (1 - u) * (1 - v) * (1 - w);
f2 = (1 - u) * (1 - v) * (w);
f3 = (1 - u) * (v) * (1 - w);
f4 = (1 - u) * (v) * (w);
f5 = (u) * (1 - v) * (1 - w);
f6 = (u) * (1 - v) * (w);
f7 = (u) * (v) * (1 - w);
f8 = (u) * (v) * (w);
dis = Disp[(i * Nmesh + j) * (2 * (Nmesh / 2 + 1)) + k] * f1 +
Disp[(i * Nmesh + j) * (2 * (Nmesh / 2 + 1)) + kk] * f2 +
Disp[(i * Nmesh + jj) * (2 * (Nmesh / 2 + 1)) + k] * f3 +
Disp[(i * Nmesh + jj) * (2 * (Nmesh / 2 + 1)) + kk] * f4 +
Disp[(ii * Nmesh + j) * (2 * (Nmesh / 2 + 1)) + k] * f5 +
Disp[(ii * Nmesh + j) * (2 * (Nmesh / 2 + 1)) + kk] * f6 +
Disp[(ii * Nmesh + jj) * (2 * (Nmesh / 2 + 1)) + k] * f7 +
Disp[(ii * Nmesh + jj) * (2 * (Nmesh / 2 + 1)) + kk] * f8;
P[n].Vel[axes] = dis;
if(dis > maxdisp)
maxdisp = dis;
}
}
}
/* now add displacement to Lagrangian coordinates, and multiply velocities by correct factor */
for(n = 0; n < NumPart; n++)
{
for(axes = 0; axes < 3; axes++)
{
P[n].Pos[axes] += P[n].Vel[axes];
P[n].Vel[axes] *= vel_prefac;
P[n].Pos[axes] = periodic_wrap(P[n].Pos[axes]);
}
}
gsl_rng_free(random_generator);
MPI_Reduce(&maxdisp, &max_disp_glob, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if(ThisTask == 0)
{
printf("\nMaximum displacement: %g kpc/h, in units of the part-spacing= %g\n",
max_disp_glob, max_disp_glob / (Box / Nmesh));
}
}
double periodic_wrap(double x)
{
while(x >= Box)
x -= Box;
while(x < 0)
x += Box;
return x;
}
void set_units(void) /* ... set some units */
{
UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
G = GRAVITY / pow(UnitLength_in_cm, 3) * UnitMass_in_g * pow(UnitTime_in_s, 2);
Hubble = HUBBLE * UnitTime_in_s;
}
void initialize_ffts(void)
{
int total_size, i, additional;
int local_ny_after_transpose, local_y_start_after_transpose;
int *slab_to_task_local;
size_t bytes;
Inverse_plan = rfftw3d_mpi_create_plan(MPI_COMM_WORLD,
Nmesh, Nmesh, Nmesh, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE);
rfftwnd_mpi_local_sizes(Inverse_plan, &Local_nx, &Local_x_start,
&local_ny_after_transpose, &local_y_start_after_transpose, &total_size);
Local_nx_table = malloc(sizeof(int) * NTask);
MPI_Allgather(&Local_nx, 1, MPI_INT, Local_nx_table, 1, MPI_INT, MPI_COMM_WORLD);
if(ThisTask == 0)
{
for(i = 0; i < NTask; i++)
printf("Task=%d Local_nx=%d\n", i, Local_nx_table[i]);
fflush(stdout);
}
Slab_to_task = malloc(sizeof(int) * Nmesh);
slab_to_task_local = malloc(sizeof(int) * Nmesh);
for(i = 0; i < Nmesh; i++)
slab_to_task_local[i] = 0;
for(i = 0; i < Local_nx; i++)
slab_to_task_local[Local_x_start + i] = ThisTask;
MPI_Allreduce(slab_to_task_local, Slab_to_task, Nmesh, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
free(slab_to_task_local);
additional = (Nmesh) * (2 * (Nmesh / 2 + 1)); /* additional plane on the right side */
Disp = (fftw_real *) malloc(bytes = sizeof(fftw_real) * (total_size + additional));
Workspace = (fftw_real *) malloc(bytes += sizeof(fftw_real) * total_size);
if(Disp && Workspace)
{
if(ThisTask == 0)
printf("\nallocated %g Mbyte on Task %d for FFT's\n", bytes / (1024.0 * 1024.0), ThisTask);
}
else
{
printf("failed to allocate %g Mbyte on Task %d\n", bytes / (1024.0 * 1024.0), ThisTask);
printf("bailing out.\n");
FatalError(1);
}
Cdata = (fftw_complex *) Disp; /* transformed array */
}
void free_ffts(void)
{
free(Workspace);
free(Disp);
free(Slab_to_task);
rfftwnd_mpi_destroy_plan(Inverse_plan);
}
int FatalError(int errnum)
{
printf("FatalError called with number=%d\n", errnum);
fflush(stdout);
MPI_Abort(MPI_COMM_WORLD, errnum);
exit(0);
}
static double A, B, alpha, beta, V, gf;
double fnl(double x) /* Peacock & Dodds formula */
{
return x * pow((1 + B * beta * x + pow(A * x, alpha * beta)) /
(1 + pow(pow(A * x, alpha) * gf * gf * gf / (V * sqrt(x)), beta)), 1 / beta);
}
void print_spec(void)
{
double k, knl, po, dl, dnl, neff, kf, kstart, kend, po2, po1, DDD;
char buf[1000];
FILE *fd;
if(ThisTask == 0)
{
sprintf(buf, "%s/inputspec_%s.txt", OutputDir, FileBase);
fd = fopen(buf, "w");
gf = GrowthFactor(0.001, 1.0) / (1.0 / 0.001);
DDD = GrowthFactor(1.0 / (Redshift + 1), 1.0);
fprintf(fd, "%12g %12g\n", Redshift, DDD); /* print actual starting redshift and
linear growth factor for this cosmology */
kstart = 2 * PI / (1000.0 * (3.085678e24 / UnitLength_in_cm)); /* 1000 Mpc/h */
kend = 2 * PI / (0.001 * (3.085678e24 / UnitLength_in_cm)); /* 0.001 Mpc/h */
for(k = kstart; k < kend; k *= 1.025)
{
po = PowerSpec(k);
dl = 4.0 * PI * k * k * k * po;
kf = 0.5;
po2 = PowerSpec(1.001 * k * kf);
po1 = PowerSpec(k * kf);
if(po != 0 && po1 != 0 && po2 != 0)
{
neff = (log(po2) - log(po1)) / (log(1.001 * k * kf) - log(k * kf));
if(1 + neff / 3 > 0)
{
A = 0.482 * pow(1 + neff / 3, -0.947);
B = 0.226 * pow(1 + neff / 3, -1.778);
alpha = 3.310 * pow(1 + neff / 3, -0.244);
beta = 0.862 * pow(1 + neff / 3, -0.287);
V = 11.55 * pow(1 + neff / 3, -0.423) * 1.2;
dnl = fnl(dl);
knl = k * pow(1 + dnl, 1.0 / 3);
}
else
{
dnl = 0;
knl = 0;
}
}
else
{
dnl = 0;
knl = 0;
}
fprintf(fd, "%12g %12g %12g %12g\n", k, dl, knl, dnl);
}
fclose(fd);
}
}
| {
"alphanum_fraction": 0.5248847618,
"avg_line_length": 24.3398373984,
"ext": "c",
"hexsha": "4807e3b72dcb381d0b78aecd26a34813e7d1b018",
"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/N-GenIC/main.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/N-GenIC/main.c",
"max_line_length": 105,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/N-GenIC/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5364,
"size": 14969
} |
/* specfunc/bessel.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 */
/* Miscellaneous support functions for Bessel function evaluations.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_airy.h"
#include "gsl_sf_elementary.h"
#include "gsl_sf_exp.h"
#include "gsl_sf_gamma.h"
#include "gsl_sf_trig.h"
#include "error.h"
#include "bessel_amp_phase.h"
#include "bessel_temme.h"
#include "bessel.h"
#define CubeRoot2_ 1.25992104989487316476721060728
/* Debye functions [Abramowitz+Stegun, 9.3.9-10] */
inline static double
debye_u1(const double * tpow)
{
return (3.0*tpow[1] - 5.0*tpow[3])/24.0;
}
inline static double
debye_u2(const double * tpow)
{
return (81.0*tpow[2] - 462.0*tpow[4] + 385.0*tpow[6])/1152.0;
}
inline
static double debye_u3(const double * tpow)
{
return (30375.0*tpow[3] - 369603.0*tpow[5] + 765765.0*tpow[7] - 425425.0*tpow[9])/414720.0;
}
inline
static double debye_u4(const double * tpow)
{
return (4465125.0*tpow[4] - 94121676.0*tpow[6] + 349922430.0*tpow[8] -
446185740.0*tpow[10] + 185910725.0*tpow[12])/39813120.0;
}
inline
static double debye_u5(const double * tpow)
{
return (1519035525.0*tpow[5] - 49286948607.0*tpow[7] +
284499769554.0*tpow[9] - 614135872350.0*tpow[11] +
566098157625.0*tpow[13] - 188699385875.0*tpow[15])/6688604160.0;
}
#if 0
inline
static double debye_u6(const double * tpow)
{
return (2757049477875.0*tpow[6] - 127577298354750.0*tpow[8] +
1050760774457901.0*tpow[10] - 3369032068261860.0*tpow[12] +
5104696716244125.0*tpow[14] - 3685299006138750.0*tpow[16] +
1023694168371875.0*tpow[18])/4815794995200.0;
}
#endif
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_bessel_IJ_taylor_e(const double nu, const double x,
const int sign,
const int kmax,
const double threshold,
gsl_sf_result * result
)
{
/* CHECK_POINTER(result) */
if(nu < 0.0 || x < 0.0) {
DOMAIN_ERROR(result);
}
else if(x == 0.0) {
if(nu == 0.0) {
result->val = 1.0;
result->err = 0.0;
}
else {
result->val = 0.0;
result->err = 0.0;
}
return GSL_SUCCESS;
}
else {
gsl_sf_result prefactor; /* (x/2)^nu / Gamma(nu+1) */
gsl_sf_result sum;
int stat_pre;
int stat_sum;
int stat_mul;
if(nu == 0.0) {
prefactor.val = 1.0;
prefactor.err = 0.0;
stat_pre = GSL_SUCCESS;
}
else if(nu < INT_MAX-1) {
/* Separate the integer part and use
* y^nu / Gamma(nu+1) = y^N /N! y^f / (N+1)_f,
* to control the error.
*/
const int N = (int)floor(nu + 0.5);
const double f = nu - N;
gsl_sf_result poch_factor;
gsl_sf_result tc_factor;
const int stat_poch = gsl_sf_poch_e(N+1.0, f, &poch_factor);
const int stat_tc = gsl_sf_taylorcoeff_e(N, 0.5*x, &tc_factor);
const double p = pow(0.5*x,f);
prefactor.val = tc_factor.val * p / poch_factor.val;
prefactor.err = tc_factor.err * p / poch_factor.val;
prefactor.err += fabs(prefactor.val) / poch_factor.val * poch_factor.err;
prefactor.err += 2.0 * GSL_DBL_EPSILON * fabs(prefactor.val);
stat_pre = GSL_ERROR_SELECT_2(stat_tc, stat_poch);
}
else {
gsl_sf_result lg;
const int stat_lg = gsl_sf_lngamma_e(nu+1.0, &lg);
const double term1 = nu*log(0.5*x);
const double term2 = lg.val;
const double ln_pre = term1 - term2;
const double ln_pre_err = GSL_DBL_EPSILON * (fabs(term1)+fabs(term2)) + lg.err;
const int stat_ex = gsl_sf_exp_err_e(ln_pre, ln_pre_err, &prefactor);
stat_pre = GSL_ERROR_SELECT_2(stat_ex, stat_lg);
}
/* Evaluate the sum.
* [Abramowitz+Stegun, 9.1.10]
* [Abramowitz+Stegun, 9.6.7]
*/
{
const double y = sign * 0.25 * x*x;
double sumk = 1.0;
double term = 1.0;
int k;
for(k=1; k<=kmax; k++) {
term *= y/((nu+k)*k);
sumk += term;
if(fabs(term/sumk) < threshold) break;
}
sum.val = sumk;
sum.err = threshold * fabs(sumk);
stat_sum = ( k >= kmax ? GSL_EMAXITER : GSL_SUCCESS );
}
stat_mul = gsl_sf_multiply_err_e(prefactor.val, prefactor.err,
sum.val, sum.err,
result);
return GSL_ERROR_SELECT_3(stat_mul, stat_pre, stat_sum);
}
}
/* x >> nu*nu+1
* error ~ O( ((nu*nu+1)/x)^3 )
*
* empirical error analysis:
* choose GSL_ROOT3_MACH_EPS * x > (nu*nu + 1)
*
* This is not especially useful. When the argument gets
* large enough for this to apply, the cos() and sin()
* start loosing digits. However, this seems inevitable
* for this particular method.
*/
int
gsl_sf_bessel_Jnu_asympx_e(const double nu, const double x, gsl_sf_result * result)
{
double mu = 4.0*nu*nu;
double mum1 = mu-1.0;
double mum9 = mu-9.0;
double chi = x - (0.5*nu + 0.25)*M_PI;
double P = 1.0 - mum1*mum9/(128.0*x*x);
double Q = mum1/(8.0*x);
double pre = sqrt(2.0/(M_PI*x));
double c = cos(chi);
double s = sin(chi);
double r = mu/x;
result->val = pre * (c*P - s*Q);
result->err = pre * GSL_DBL_EPSILON * (fabs(c*P) + fabs(s*Q));
result->err += pre * fabs(0.1*r*r*r);
return GSL_SUCCESS;
}
/* x >> nu*nu+1
*/
int
gsl_sf_bessel_Ynu_asympx_e(const double nu, const double x, gsl_sf_result * result)
{
double ampl;
double theta;
double alpha = x;
double beta = -0.5*nu*M_PI;
int stat_a = gsl_sf_bessel_asymp_Mnu_e(nu, x, &l);
int stat_t = gsl_sf_bessel_asymp_thetanu_corr_e(nu, x, &theta);
double sin_alpha = sin(alpha);
double cos_alpha = cos(alpha);
double sin_chi = sin(beta + theta);
double cos_chi = cos(beta + theta);
double sin_term = sin_alpha * cos_chi + sin_chi * cos_alpha;
double sin_term_mag = fabs(sin_alpha * cos_chi) + fabs(sin_chi * cos_alpha);
result->val = ampl * sin_term;
result->err = fabs(ampl) * GSL_DBL_EPSILON * sin_term_mag;
result->err += fabs(result->val) * 2.0 * GSL_DBL_EPSILON;
if(fabs(alpha) > 1.0/GSL_DBL_EPSILON) {
result->err *= 0.5 * fabs(alpha);
}
else if(fabs(alpha) > 1.0/GSL_SQRT_DBL_EPSILON) {
result->err *= 256.0 * fabs(alpha) * GSL_SQRT_DBL_EPSILON;
}
return GSL_ERROR_SELECT_2(stat_t, stat_a);
}
/* x >> nu*nu+1
*/
int
gsl_sf_bessel_Inu_scaled_asympx_e(const double nu, const double x, gsl_sf_result * result)
{
double mu = 4.0*nu*nu;
double mum1 = mu-1.0;
double mum9 = mu-9.0;
double pre = 1.0/sqrt(2.0*M_PI*x);
double r = mu/x;
result->val = pre * (1.0 - mum1/(8.0*x) + mum1*mum9/(128.0*x*x));
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val) + pre * fabs(0.1*r*r*r);
return GSL_SUCCESS;
}
/* x >> nu*nu+1
*/
int
gsl_sf_bessel_Knu_scaled_asympx_e(const double nu, const double x, gsl_sf_result * result)
{
double mu = 4.0*nu*nu;
double mum1 = mu-1.0;
double mum9 = mu-9.0;
double pre = sqrt(M_PI/(2.0*x));
double r = nu/x;
result->val = pre * (1.0 + mum1/(8.0*x) + mum1*mum9/(128.0*x*x));
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val) + pre * fabs(0.1*r*r*r);
return GSL_SUCCESS;
}
/* nu -> Inf; uniform in x > 0 [Abramowitz+Stegun, 9.7.7]
*
* error:
* The error has the form u_N(t)/nu^N where 0 <= t <= 1.
* It is not hard to show that |u_N(t)| is small for such t.
* We have N=6 here, and |u_6(t)| < 0.025, so the error is clearly
* bounded by 0.025/nu^6. This gives the asymptotic bound on nu
* seen below as nu ~ 100. For general MACH_EPS it will be
* nu > 0.5 / MACH_EPS^(1/6)
* When t is small, the bound is even better because |u_N(t)| vanishes
* as t->0. In fact u_N(t) ~ C t^N as t->0, with C ~= 0.1.
* We write
* err_N <= min(0.025, C(1/(1+(x/nu)^2))^3) / nu^6
* therefore
* min(0.29/nu^2, 0.5/(nu^2+x^2)) < MACH_EPS^{1/3}
* and this is the general form.
*
* empirical error analysis, assuming 14 digit requirement:
* choose x > 50.000 nu ==> nu > 3
* choose x > 10.000 nu ==> nu > 15
* choose x > 2.000 nu ==> nu > 50
* choose x > 1.000 nu ==> nu > 75
* choose x > 0.500 nu ==> nu > 80
* choose x > 0.100 nu ==> nu > 83
*
* This makes sense. For x << nu, the error will be of the form u_N(1)/nu^N,
* since the polynomial term will be evaluated near t=1, so the bound
* on nu will become constant for small x. Furthermore, increasing x with
* nu fixed will decrease the error.
*/
int
gsl_sf_bessel_Inu_scaled_asymp_unif_e(const double nu, const double x, gsl_sf_result * result)
{
int i;
double z = x/nu;
double root_term = sqrt(1.0 + z*z);
double pre = 1.0/sqrt(2.0*M_PI*nu * root_term);
double eta = root_term + log(z/(1.0+root_term));
double ex_arg = ( z < 1.0/GSL_ROOT3_DBL_EPSILON ? nu*(-z + eta) : -0.5*nu/z*(1.0 - 1.0/(12.0*z*z)) );
gsl_sf_result ex_result;
int stat_ex = gsl_sf_exp_e(ex_arg, &ex_result);
if(stat_ex == GSL_SUCCESS) {
double t = 1.0/root_term;
double sum;
double tpow[16];
tpow[0] = 1.0;
for(i=1; i<16; i++) tpow[i] = t * tpow[i-1];
sum = 1.0 + debye_u1(tpow)/nu + debye_u2(tpow)/(nu*nu) + debye_u3(tpow)/(nu*nu*nu)
+ debye_u4(tpow)/(nu*nu*nu*nu) + debye_u5(tpow)/(nu*nu*nu*nu*nu);
result->val = pre * ex_result.val * sum;
result->err = pre * ex_result.val / (nu*nu*nu*nu*nu*nu);
result->err += pre * ex_result.err * fabs(sum);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
result->val = 0.0;
result->err = 0.0;
return stat_ex;
}
}
/* nu -> Inf; uniform in x > 0 [Abramowitz+Stegun, 9.7.8]
*
* error:
* identical to that above for Inu_scaled
*/
int
gsl_sf_bessel_Knu_scaled_asymp_unif_e(const double nu, const double x, gsl_sf_result * result)
{
int i;
double z = x/nu;
double root_term = sqrt(1.0 + z*z);
double pre = sqrt(M_PI/(2.0*nu*root_term));
double eta = root_term + log(z/(1.0+root_term));
double ex_arg = ( z < 1.0/GSL_ROOT3_DBL_EPSILON ? nu*(z - eta) : 0.5*nu/z*(1.0 + 1.0/(12.0*z*z)) );
gsl_sf_result ex_result;
int stat_ex = gsl_sf_exp_e(ex_arg, &ex_result);
if(stat_ex == GSL_SUCCESS) {
double t = 1.0/root_term;
double sum;
double tpow[16];
tpow[0] = 1.0;
for(i=1; i<16; i++) tpow[i] = t * tpow[i-1];
sum = 1.0 - debye_u1(tpow)/nu + debye_u2(tpow)/(nu*nu) - debye_u3(tpow)/(nu*nu*nu)
+ debye_u4(tpow)/(nu*nu*nu*nu) - debye_u5(tpow)/(nu*nu*nu*nu*nu);
result->val = pre * ex_result.val * sum;
result->err = pre * ex_result.err * fabs(sum);
result->err += pre * ex_result.val / (nu*nu*nu*nu*nu*nu);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
result->val = 0.0;
result->err = 0.0;
return stat_ex;
}
}
/* Evaluate J_mu(x),J_{mu+1}(x) and Y_mu(x),Y_{mu+1}(x) for |mu| < 1/2
*/
int
gsl_sf_bessel_JY_mu_restricted(const double mu, const double x,
gsl_sf_result * Jmu, gsl_sf_result * Jmup1,
gsl_sf_result * Ymu, gsl_sf_result * Ymup1)
{
/* CHECK_POINTER(Jmu) */
/* CHECK_POINTER(Jmup1) */
/* CHECK_POINTER(Ymu) */
/* CHECK_POINTER(Ymup1) */
if(x < 0.0 || fabs(mu) > 0.5) {
Jmu->val = 0.0;
Jmu->err = 0.0;
Jmup1->val = 0.0;
Jmup1->err = 0.0;
Ymu->val = 0.0;
Ymu->err = 0.0;
Ymup1->val = 0.0;
Ymup1->err = 0.0;
GSL_ERROR ("error", GSL_EDOM);
}
else if(x == 0.0) {
if(mu == 0.0) {
Jmu->val = 1.0;
Jmu->err = 0.0;
}
else {
Jmu->val = 0.0;
Jmu->err = 0.0;
}
Jmup1->val = 0.0;
Jmup1->err = 0.0;
Ymu->val = 0.0;
Ymu->err = 0.0;
Ymup1->val = 0.0;
Ymup1->err = 0.0;
GSL_ERROR ("error", GSL_EDOM);
}
else {
int stat_Y;
int stat_J;
if(x < 2.0) {
/* Use Taylor series for J and the Temme series for Y.
* The Taylor series for J requires nu > 0, so we shift
* up one and use the recursion relation to get Jmu, in
* case mu < 0.
*/
gsl_sf_result Jmup2;
int stat_J1 = gsl_sf_bessel_IJ_taylor_e(mu+1.0, x, -1, 100, GSL_DBL_EPSILON, Jmup1);
int stat_J2 = gsl_sf_bessel_IJ_taylor_e(mu+2.0, x, -1, 100, GSL_DBL_EPSILON, &Jmup2);
double c = 2.0*(mu+1.0)/x;
Jmu->val = c * Jmup1->val - Jmup2.val;
Jmu->err = c * Jmup1->err + Jmup2.err;
Jmu->err += 2.0 * GSL_DBL_EPSILON * fabs(Jmu->val);
stat_J = GSL_ERROR_SELECT_2(stat_J1, stat_J2);
stat_Y = gsl_sf_bessel_Y_temme(mu, x, Ymu, Ymup1);
return GSL_ERROR_SELECT_2(stat_J, stat_Y);
}
else if(x < 1000.0) {
double P, Q;
double J_ratio;
double J_sgn;
const int stat_CF1 = gsl_sf_bessel_J_CF1(mu, x, &J_ratio, &J_sgn);
const int stat_CF2 = gsl_sf_bessel_JY_steed_CF2(mu, x, &P, &Q);
double Jprime_J_ratio = mu/x - J_ratio;
double gamma = (P - Jprime_J_ratio)/Q;
Jmu->val = J_sgn * sqrt(2.0/(M_PI*x) / (Q + gamma*(P-Jprime_J_ratio)));
Jmu->err = 4.0 * GSL_DBL_EPSILON * fabs(Jmu->val);
Jmup1->val = J_ratio * Jmu->val;
Jmup1->err = fabs(J_ratio) * Jmu->err;
Ymu->val = gamma * Jmu->val;
Ymu->err = fabs(gamma) * Jmu->err;
Ymup1->val = Ymu->val * (mu/x - P - Q/gamma);
Ymup1->err = Ymu->err * fabs(mu/x - P - Q/gamma) + 4.0*GSL_DBL_EPSILON*fabs(Ymup1->val);
return GSL_ERROR_SELECT_2(stat_CF1, stat_CF2);
}
else {
/* Use asymptotics for large argument.
*/
const int stat_J0 = gsl_sf_bessel_Jnu_asympx_e(mu, x, Jmu);
const int stat_J1 = gsl_sf_bessel_Jnu_asympx_e(mu+1.0, x, Jmup1);
const int stat_Y0 = gsl_sf_bessel_Ynu_asympx_e(mu, x, Ymu);
const int stat_Y1 = gsl_sf_bessel_Ynu_asympx_e(mu+1.0, x, Ymup1);
stat_J = GSL_ERROR_SELECT_2(stat_J0, stat_J1);
stat_Y = GSL_ERROR_SELECT_2(stat_Y0, stat_Y1);
return GSL_ERROR_SELECT_2(stat_J, stat_Y);
}
}
}
int
gsl_sf_bessel_J_CF1(const double nu, const double x,
double * ratio, double * sgn)
{
const double RECUR_BIG = GSL_SQRT_DBL_MAX;
const int maxiter = 10000;
int n = 1;
double Anm2 = 1.0;
double Bnm2 = 0.0;
double Anm1 = 0.0;
double Bnm1 = 1.0;
double a1 = x/(2.0*(nu+1.0));
double An = Anm1 + a1*Anm2;
double Bn = Bnm1 + a1*Bnm2;
double an;
double fn = An/Bn;
double dn = a1;
double s = 1.0;
while(n < maxiter) {
double old_fn;
double del;
n++;
Anm2 = Anm1;
Bnm2 = Bnm1;
Anm1 = An;
Bnm1 = Bn;
an = -x*x/(4.0*(nu+n-1.0)*(nu+n));
An = Anm1 + an*Anm2;
Bn = Bnm1 + an*Bnm2;
if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {
An /= RECUR_BIG;
Bn /= RECUR_BIG;
Anm1 /= RECUR_BIG;
Bnm1 /= RECUR_BIG;
Anm2 /= RECUR_BIG;
Bnm2 /= RECUR_BIG;
}
old_fn = fn;
fn = An/Bn;
del = old_fn/fn;
dn = 1.0 / (2.0*(nu+n)/x - dn);
if(dn < 0.0) s = -s;
if(fabs(del - 1.0) < 2.0*GSL_DBL_EPSILON) break;
}
*ratio = fn;
*sgn = s;
if(n >= maxiter)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
/* Evaluate the continued fraction CF1 for J_{nu+1}/J_nu
* using Gautschi (Euler) equivalent series.
* This exhibits an annoying problem because the
* a_k are not positive definite (in fact they are all negative).
* There are cases when rho_k blows up. Example: nu=1,x=4.
*/
#if 0
int
gsl_sf_bessel_J_CF1_ser(const double nu, const double x,
double * ratio, double * sgn)
{
const int maxk = 20000;
double tk = 1.0;
double sum = 1.0;
double rhok = 0.0;
double dk = 0.0;
double s = 1.0;
int k;
for(k=1; k<maxk; k++) {
double ak = -0.25 * (x/(nu+k)) * x/(nu+k+1.0);
rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok));
tk *= rhok;
sum += tk;
dk = 1.0 / (2.0/x - (nu+k-1.0)/(nu+k) * dk);
if(dk < 0.0) s = -s;
if(fabs(tk/sum) < GSL_DBL_EPSILON) break;
}
*ratio = x/(2.0*(nu+1.0)) * sum;
*sgn = s;
if(k == maxk)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
#endif
/* Evaluate the continued fraction CF1 for I_{nu+1}/I_nu
* using Gautschi (Euler) equivalent series.
*/
int
gsl_sf_bessel_I_CF1_ser(const double nu, const double x, double * ratio)
{
const int maxk = 20000;
double tk = 1.0;
double sum = 1.0;
double rhok = 0.0;
int k;
for(k=1; k<maxk; k++) {
double ak = 0.25 * (x/(nu+k)) * x/(nu+k+1.0);
rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok));
tk *= rhok;
sum += tk;
if(fabs(tk/sum) < GSL_DBL_EPSILON) break;
}
*ratio = x/(2.0*(nu+1.0)) * sum;
if(k == maxk)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
int
gsl_sf_bessel_JY_steed_CF2(const double nu, const double x,
double * P, double * Q)
{
const int max_iter = 10000;
const double SMALL = 1.0e-100;
int i = 1;
double x_inv = 1.0/x;
double a = 0.25 - nu*nu;
double p = -0.5*x_inv;
double q = 1.0;
double br = 2.0*x;
double bi = 2.0;
double fact = a*x_inv/(p*p + q*q);
double cr = br + q*fact;
double ci = bi + p*fact;
double den = br*br + bi*bi;
double dr = br/den;
double di = -bi/den;
double dlr = cr*dr - ci*di;
double dli = cr*di + ci*dr;
double temp = p*dlr - q*dli;
q = p*dli + q*dlr;
p = temp;
for (i=2; i<=max_iter; i++) {
a += 2*(i-1);
bi += 2.0;
dr = a*dr + br;
di = a*di + bi;
if(fabs(dr)+fabs(di) < SMALL) dr = SMALL;
fact = a/(cr*cr+ci*ci);
cr = br + cr*fact;
ci = bi - ci*fact;
if(fabs(cr)+fabs(ci) < SMALL) cr = SMALL;
den = dr*dr + di*di;
dr /= den;
di /= -den;
dlr = cr*dr - ci*di;
dli = cr*di + ci*dr;
temp = p*dlr - q*dli;
q = p*dli + q*dlr;
p = temp;
if(fabs(dlr-1.0)+fabs(dli) < GSL_DBL_EPSILON) break;
}
*P = p;
*Q = q;
if(i == max_iter)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
/* Evaluate continued fraction CF2, using Thompson-Barnett-Temme method,
* to obtain values of exp(x)*K_nu and exp(x)*K_{nu+1}.
*
* This is unstable for small x; x > 2 is a good cutoff.
* Also requires |nu| < 1/2.
*/
int
gsl_sf_bessel_K_scaled_steed_temme_CF2(const double nu, const double x,
double * K_nu, double * K_nup1,
double * Kp_nu)
{
const int maxiter = 10000;
int i = 1;
double bi = 2.0*(1.0 + x);
double di = 1.0/bi;
double delhi = di;
double hi = di;
double qi = 0.0;
double qip1 = 1.0;
double ai = -(0.25 - nu*nu);
double a1 = ai;
double ci = -ai;
double Qi = -ai;
double s = 1.0 + Qi*delhi;
for(i=2; i<=maxiter; i++) {
double dels;
double tmp;
ai -= 2.0*(i-1);
ci = -ai*ci/i;
tmp = (qi - bi*qip1)/ai;
qi = qip1;
qip1 = tmp;
Qi += ci*qip1;
bi += 2.0;
di = 1.0/(bi + ai*di);
delhi = (bi*di - 1.0) * delhi;
hi += delhi;
dels = Qi*delhi;
s += dels;
if(fabs(dels/s) < GSL_DBL_EPSILON) break;
}
hi *= -a1;
*K_nu = sqrt(M_PI/(2.0*x)) / s;
*K_nup1 = *K_nu * (nu + x + 0.5 - hi)/x;
*Kp_nu = - *K_nup1 + nu/x * *K_nu;
if(i == maxiter)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
int gsl_sf_bessel_cos_pi4_e(double y, double eps, gsl_sf_result * result)
{
const double sy = sin(y);
const double cy = cos(y);
const double s = sy + cy;
const double d = sy - cy;
const double abs_sum = fabs(cy) + fabs(sy);
double seps;
double ceps;
if(fabs(eps) < GSL_ROOT5_DBL_EPSILON) {
const double e2 = eps*eps;
seps = eps * (1.0 - e2/6.0 * (1.0 - e2/20.0));
ceps = 1.0 - e2/2.0 * (1.0 - e2/12.0);
}
else {
seps = sin(eps);
ceps = cos(eps);
}
result->val = (ceps * s - seps * d)/ M_SQRT2;
result->err = 2.0 * GSL_DBL_EPSILON * (fabs(ceps) + fabs(seps)) * abs_sum / M_SQRT2;
/* Try to account for error in evaluation of sin(y), cos(y).
* This is a little sticky because we don't really know
* how the library routines are doing their argument reduction.
* However, we will make a reasonable guess.
* FIXME ?
*/
if(y > 1.0/GSL_DBL_EPSILON) {
result->err *= 0.5 * y;
}
else if(y > 1.0/GSL_SQRT_DBL_EPSILON) {
result->err *= 256.0 * y * GSL_SQRT_DBL_EPSILON;
}
return GSL_SUCCESS;
}
int gsl_sf_bessel_sin_pi4_e(double y, double eps, gsl_sf_result * result)
{
const double sy = sin(y);
const double cy = cos(y);
const double s = sy + cy;
const double d = sy - cy;
const double abs_sum = fabs(cy) + fabs(sy);
double seps;
double ceps;
if(fabs(eps) < GSL_ROOT5_DBL_EPSILON) {
const double e2 = eps*eps;
seps = eps * (1.0 - e2/6.0 * (1.0 - e2/20.0));
ceps = 1.0 - e2/2.0 * (1.0 - e2/12.0);
}
else {
seps = sin(eps);
ceps = cos(eps);
}
result->val = (ceps * d + seps * s)/ M_SQRT2;
result->err = 2.0 * GSL_DBL_EPSILON * (fabs(ceps) + fabs(seps)) * abs_sum / M_SQRT2;
/* Try to account for error in evaluation of sin(y), cos(y).
* See above.
* FIXME ?
*/
if(y > 1.0/GSL_DBL_EPSILON) {
result->err *= 0.5 * y;
}
else if(y > 1.0/GSL_SQRT_DBL_EPSILON) {
result->err *= 256.0 * y * GSL_SQRT_DBL_EPSILON;
}
return GSL_SUCCESS;
}
/************************************************************************
* *
Asymptotic approximations 8.11.5, 8.12.5, and 8.42.7 from
G.N.Watson, A Treatise on the Theory of Bessel Functions,
2nd Edition (Cambridge University Press, 1944).
Higher terms in expansion for x near l given by
Airey in Phil. Mag. 31, 520 (1916).
This approximation is accurate to near 0.1% at the boundaries
between the asymptotic regions; well away from the boundaries
the accuracy is better than 10^{-5}.
* *
************************************************************************/
#if 0
double besselJ_meissel(double nu, double x)
{
double beta = pow(nu, 0.325);
double result;
/* Fitted matching points. */
double llimit = 1.1 * beta;
double ulimit = 1.3 * beta;
double nu2 = nu * nu;
if (nu < 5. && x < 1.)
{
/* Small argument and order. Use a Taylor expansion. */
int k;
double xo2 = 0.5 * x;
double gamfactor = pow(nu,nu) * exp(-nu) * sqrt(nu * 2. * M_PI)
* (1. + 1./(12.*nu) + 1./(288.*nu*nu));
double prefactor = pow(xo2, nu) / gamfactor;
double C[5];
C[0] = 1.;
C[1] = -C[0] / (nu+1.);
C[2] = -C[1] / (2.*(nu+2.));
C[3] = -C[2] / (3.*(nu+3.));
C[4] = -C[3] / (4.*(nu+4.));
result = 0.;
for(k=0; k<5; k++)
result += C[k] * pow(xo2, 2.*k);
result *= prefactor;
}
else if(x < nu - llimit)
{
/* Small x region: x << l. */
double z = x / nu;
double z2 = z*z;
double rtomz2 = sqrt(1.-z2);
double omz2_2 = (1.-z2)*(1.-z2);
/* Calculate Meissel exponent. */
double term1 = 1./(24.*nu) * ((2.+3.*z2)/((1.-z2)*rtomz2) -2.);
double term2 = - z2*(4. + z2)/(16.*nu2*(1.-z2)*omz2_2);
double V_nu = term1 + term2;
/* Calculate the harmless prefactor. */
double sterlingsum = 1. + 1./(12.*nu) + 1./(288*nu2);
double harmless = 1. / (sqrt(rtomz2*2.*M_PI*nu) * sterlingsum);
/* Calculate the logarithm of the nu dependent prefactor. */
double ln_nupre = rtomz2 + log(z) - log(1. + rtomz2);
result = harmless * exp(nu*ln_nupre - V_nu);
}
else if(x < nu + ulimit)
{
/* Intermediate region 1: x near nu. */
double eps = 1.-nu/x;
double eps_x = eps * x;
double eps_x_2 = eps_x * eps_x;
double xo6 = x/6.;
double B[6];
static double gam[6] = {2.67894, 1.35412, 1., 0.89298, 0.902745, 1.};
static double sf[6] = {0.866025, 0.866025, 0., -0.866025, -0.866025, 0.};
/* Some terms are identically zero, because sf[] can be zero.
* Some terms do not appear in the result.
*/
B[0] = 1.;
B[1] = eps_x;
/* B[2] = 0.5 * eps_x_2 - 1./20.; */
B[3] = eps_x * (eps_x_2/6. - 1./15.);
B[4] = eps_x_2 * (eps_x_2 - 1.)/24. + 1./280.;
/* B[5] = eps_x * (eps_x_2*(0.5*eps_x_2 - 1.)/60. + 43./8400.); */
result = B[0] * gam[0] * sf[0] / pow(xo6, 1./3.);
result += B[1] * gam[1] * sf[1] / pow(xo6, 2./3.);
result += B[3] * gam[3] * sf[3] / pow(xo6, 4./3.);
result += B[4] * gam[4] * sf[4] / pow(xo6, 5./3.);
result /= (3.*M_PI);
}
else
{
/* Region of very large argument. Use expansion
* for x>>l, and we need not be very exacting.
*/
double secb = x/nu;
double sec2b= secb*secb;
double cotb = 1./sqrt(sec2b-1.); /* cotb=cot(beta) */
double beta = acos(nu/x);
double trigarg = nu/cotb - nu*beta - 0.25 * M_PI;
double cot3b = cotb * cotb * cotb;
double cot6b = cot3b * cot3b;
double sum1, sum2, expterm, prefactor, trigcos;
sum1 = 2.0 + 3.0 * sec2b;
trigarg -= sum1 * cot3b / (24.0 * nu);
trigcos = cos(trigarg);
sum2 = 4.0 + sec2b;
expterm = sum2 * sec2b * cot6b / (16.0 * nu2);
expterm = exp(-expterm);
prefactor = sqrt(2. * cotb / (nu * M_PI));
result = prefactor * expterm * trigcos;
}
return result;
}
#endif
| {
"alphanum_fraction": 0.5676032933,
"avg_line_length": 28.440386681,
"ext": "c",
"hexsha": "c46f5630923a8144ca9138d87a1933bb0663e501",
"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/bessel.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/bessel.c",
"max_line_length": 103,
"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/bessel.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": 9694,
"size": 26478
} |
/*
* Gsl_blas_dgemm: test gsl_blas_dgemm (matrix . matrix)
*
* Copyright (c) 2012 Jérémie Decock
*
* Required: GSL library (libgsl0-dev)
* Usage: gcc gsl_blas_dgemm.c -lgsl -lgslcblas -lm
* or: gcc gsl_blas_dgemm.c $(pkg-config --libs gsl)
*/
#include <stdio.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
int main (void)
{
gsl_matrix * m1 = gsl_matrix_alloc(3, 3);
gsl_matrix * m2 = gsl_matrix_alloc(3, 3);
gsl_matrix * m3 = gsl_matrix_alloc(3, 3);
gsl_matrix_set_all(m1, 3.0);
gsl_matrix_set_all(m2, 2.0);
/* Compute m3 = m1.m2 */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,
1.0, m1, m2,
0.0, m3);
int i, j;
for(i=0 ; i<3 ; i++) {
printf("[");
for(j=0 ; j<3 ; j++) {
printf(" %f ", gsl_matrix_get(m3, i, j));
}
printf("]\n");
}
gsl_matrix_free(m1);
gsl_matrix_free(m2);
gsl_matrix_free(m3);
return 0;
}
| {
"alphanum_fraction": 0.5630769231,
"avg_line_length": 21.1956521739,
"ext": "c",
"hexsha": "2450d841660dbf213800ebb918e765554911e4ce",
"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/blas/gsl_blas_dgemm.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/blas/gsl_blas_dgemm.c",
"max_line_length": 56,
"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/blas/gsl_blas_dgemm.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": 337,
"size": 975
} |
/*
* -----------------------------------------------------------------
* ODE Solver Library --- ode_lib.h
* Version: 1.6180
* Date: Feb 19, 2010
* -----------------------------------------------------------------
* Programmer: Americo Barbosa da Cunha Junior
* americo.cunhajr@gmail.com
* -----------------------------------------------------------------
* Copyright (c) 2010 by Americo Barbosa da Cunha Junior
*
* 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.
*
* A copy of the GNU General Public License is available in
* LICENSE.txt or http://www.gnu.org/licenses/.
* -----------------------------------------------------------------
* This is the header file for a library
* with the ODE solution tools.
* -----------------------------------------------------------------
*/
#ifndef __ODESOLVER_LIB_H__
#define __ODESOLVER_LIB_H__
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <cvode/cvode.h>
#undef RTOL
#define RTOL 1.0e-6
#undef ATOL
#define ATOL 1.0e-15
/*
*------------------------------------------------------------
* function prototypes
*------------------------------------------------------------
*/
double uround(void);
double wnorm(int n,
double *v1,
double *v2);
void ewtset(int n,
double *v,
double atol,
double rtol,
double *ewt);
int jacobian(CVRhsFn f,
void *f_data,
gsl_vector *Fx,
gsl_vector *x,
double t,
double atol,
double rtol,
gsl_matrix *J);
int gradient(CVRhsFn f,
void *f_data,
void *cvode_mem,
double t0,
double delta_t,
double atol,
double rtol,
gsl_vector *phi,
gsl_vector *Rphi,
gsl_matrix *A);
void linear_approx(gsl_vector *x,
gsl_vector *x0,
gsl_vector *Fx0,
gsl_matrix *DFx0,
gsl_vector *Fx);
int odesolver_init(CVRhsFn f,
void *data,
double t0,
int mxsteps,
double atol,
double rtol,
gsl_vector *x,
void *cvode_mem);
int odesolver_reinit(CVRhsFn f,
void *f_data,
double t0,
double atol,
double rtol,
gsl_vector *x,
void *cvode_mem);
int odesolver(void *cvode_mem,
double tf,
gsl_vector *Fx);
#endif /* __ODESOLVER_LIB_H__ */
| {
"alphanum_fraction": 0.4749839641,
"avg_line_length": 26.4237288136,
"ext": "h",
"hexsha": "8c122e981c9a357ea57dccd3d3ccf5b17c8811a4",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z",
"max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "americocunhajr/CRFlowLib",
"max_forks_repo_path": "CRFlowLib-1.0/include/ode_lib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"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": "americocunhajr/CRFlowLib",
"max_issues_repo_path": "CRFlowLib-1.0/include/ode_lib.h",
"max_line_length": 68,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "americocunhajr/CRFlowLib",
"max_stars_repo_path": "CRFlowLib-1.0/include/ode_lib.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z",
"num_tokens": 668,
"size": 3118
} |
#if !defined(PETIGAPART_H)
#define PETIGAPART_H
#include <petsc.h>
PETSC_EXTERN PetscErrorCode IGA_Partition(PetscInt,PetscInt,
PetscInt,const PetscInt[],
PetscInt[],PetscInt[]);
PETSC_EXTERN PetscErrorCode IGA_Distribute(PetscInt,
const PetscInt[],const PetscInt[],
const PetscInt[],PetscInt[],PetscInt[]);
#endif/*PETIGAPART_H*/
| {
"alphanum_fraction": 0.5238095238,
"avg_line_length": 36,
"ext": "h",
"hexsha": "9083cb2e3368c5162612e98c8c3651e46c541b0a",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2021-06-14T10:40:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-11-08T12:55:17.000Z",
"max_forks_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "otherlab/petiga",
"max_forks_repo_path": "src/petigapart.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"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": "otherlab/petiga",
"max_issues_repo_path": "src/petigapart.h",
"max_line_length": 83,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "otherlab/petiga",
"max_stars_repo_path": "src/petigapart.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T10:40:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-31T21:20:27.000Z",
"num_tokens": 101,
"size": 504
} |
#ifndef DEINOS_ALGORITHM_H
#define DEINOS_ALGORITHM_H
#include "chess.h"
#include <vector>
#include <array>
#include <gsl/pointers>
#include <mutex>
#include <variant>
#include <functional>
#include <string>
#include <thread>
#include <future>
#include <condition_variable>
//memory consmption ideas:
//can halve Move size by removing piece type tracking and putting boold inside promotion piece
//can reduce AnalysedPosition size by doubling up control inside one byte
//perhaps dynamically delete parts of the tree e.g. only positions and regenerate if necessary
//deletion thread?
//Other
//use gsl::index in for loops?
namespace algorithm {
class AnalysedPosition{
public:
constexpr AnalysedPosition() = default;
explicit AnalysedPosition(const chess::Position&); //generate from scratch
void advance_by(chess::MoveRecord);
struct occlusion_info {
std::array<std::array<chess::Square, 16>, 2> squares;
std::array<int, 2> counts = {0};
};
AnalysedPosition::occlusion_info get_occlusion(chess::MoveRecord);
inline const chess::Position& pos() const {return m_position;}
inline uint8_t ctrl(chess::Almnt a, chess::Square s) const {return m_control[chess::as_index(a)].get(s.file(), s.rank());}
inline const std::vector<chess::MoveRecord>& moves(chess::Almnt a) const {return m_moves[chess::as_index(a)];}
inline const std::vector<chess::MoveRecord>& moves() const {return moves(pos().to_move());}
inline chess::Move get_move(int index) const {return chess::Move(pos(), moves().at(index));}
inline const chess::Square king_sq(chess::Almnt a) const {return m_king_sq[chess::as_index(a)];}
inline bool in_check(chess::Almnt a) const {return ctrl(!a, king_sq(a)) > 0;}
inline bool legal_check() const {return in_check(pos().to_move());}
inline bool illegal_check() const {return in_check(!pos().to_move());}
std::optional<chess::Move> find_record(const std::string& name) const;
friend std::ostream& operator<<(std::ostream& os, const AnalysedPosition& ap);
private:
void append_calculation(chess::Square start); //calculate data associated with this square and append to state (for initialisation)
void append_castling();
std::array<chess::Square, 2> m_king_sq;
chess::Position m_position;
std::array<chess::HalfByteBoard, 2> m_control;
std::array<std::vector<chess::MoveRecord>, 2> m_moves = {};
};
std::ostream& operator<<(std::ostream& os, const AnalysedPosition& ap);
class Node;
struct Edge {
//std::mutex ptr_mutex;
float total_value;
int visits = 0;
//bool legal = true;
inline bool legal() const {return visits != -1;}
std::unique_ptr<Node> node = nullptr;
};
struct EdgeDatum {
float total_value = 0.0;
int visits = 0;
bool legal = true;
};
struct EdgeData {
EdgeData(int moves_num) : edges(std::vector<EdgeDatum>(moves_num)) {}
int total_n = 1;
std::vector<EdgeDatum> edges;
};
class Node { //TODO
public:
explicit Node(std::unique_ptr<const AnalysedPosition> t_apos);
explicit Node(const AnalysedPosition& t_apos);
int preferred_index();
std::unique_ptr<Node>* find_child(const std::string& fen);
std::unique_ptr<Node>* find_child(const chess::Move& mv);
inline Node* child(int index) const {return edges[index].node.get();}
const chess::Move best_move() {return chess::Move(apos->pos(), apos->moves()[preferred_index()]);}
inline std::optional<chess::GameResult> result() const {return m_result;}
//inline int res_dist() const {return m_res_dist;} //TODO
std::string display() const;
inline int total_n() const {return m_total_n;} //synchronise?
const std::unique_ptr<const AnalysedPosition> apos;
const bool white_to_play;
private:
void update(int index, float t_value);
void increment_n();
void set_illegal(int index);
std::optional<chess::GameResult> m_result = std::nullopt;
//int m_res_dist = 0; //TODO
//std::mutex data_mutex2;
//EdgeData data;
int m_total_n = 1;
std::vector<Edge> edges;
//std::vector<Edge> edges2;
std::mutex data_mutex; //40B
std::array<uint8_t, 3> node_prefetch = {0};
friend class Tree;
};
class Tree {
public:
Tree(const AnalysedPosition& base_apos, std::function<float(const AnalysedPosition&)> t_value_fn,
std::function<float(const AnalysedPosition&, const chess::Move&)> t_prior_fn, float t_expl_c = 0.2)
: base(std::make_unique<Node>(base_apos)), value_fn(t_value_fn), prior_fn(t_prior_fn), expl_c(t_expl_c) {}
void search(bool update_prefetch = false);
std::unique_ptr<Node> base;
std::function<float(const AnalysedPosition&)> value_fn;
std::function<float(const AnalysedPosition&, const chess::Move&)> prior_fn;
float expl_c = 0.2; //exploration coefficient
private:
float evaluate_node(Node& node); //used in search() for recursion
void update_node(int index, float t_value);
std::optional<int> edge_to_search(Node& node);
void update_prefetch(Node& node);
};
class TreeEngine {
public:
TreeEngine(
const AnalysedPosition& initial_position,
std::function<float(const AnalysedPosition&)> t_value_fn,
std::function<float(const AnalysedPosition&, const chess::Move&)> t_prior_fn,
float exploration_coefficient);
~TreeEngine() {
halt_promise.set_value();
for (auto& t : m_threads) t.join();
}
TreeEngine(const TreeEngine&) = delete;
TreeEngine& operator=(const TreeEngine&) = delete;
TreeEngine(TreeEngine&&) = delete;
TreeEngine& operator=(TreeEngine&&) = delete;
//void start();
const chess::Move choose_move(); //maybe add exploration?
bool advance_to(const std::string& fen);
bool advance_by(const chess::Move& mv); //TODO
std::string display() const; //TODO
inline int total_n() const {return m_tree.base->total_n();};
private:
bool should_pause();
void pause(); //blocks until all threads are paused
void resume(); //blocks until all threads are resumed
Tree m_tree;
std::promise<void> halt_promise;
std::mutex pause_mx;
std::condition_variable pause_cv;
bool pause_bool = false;
int pause_count = 0;
std::vector<std::thread> m_threads;
};
}
#endif | {
"alphanum_fraction": 0.7180921053,
"avg_line_length": 34.3502824859,
"ext": "h",
"hexsha": "39b310a3cd8acf6cbfaaa560661fc6366e2a1e36",
"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": "940f60f4c4907c3484217c082db6b66b3c39a373",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Ayals4/deinos",
"max_forks_repo_path": "deinos/algorithm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373",
"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": "Ayals4/deinos",
"max_issues_repo_path": "deinos/algorithm.h",
"max_line_length": 133,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "940f60f4c4907c3484217c082db6b66b3c39a373",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Ayals4/deinos",
"max_stars_repo_path": "deinos/algorithm.h",
"max_stars_repo_stars_event_max_datetime": "2020-01-05T00:44:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-05T00:44:30.000Z",
"num_tokens": 1665,
"size": 6080
} |
/*
* Gsl_vector: test gsl_vector
*
* Copyright (c) 2012 Jérémie Decock
*
* Required: GSL library (libgsl0-dev)
* Usage: gcc gsl_vector.c -lgsl -lgslcblas -lm
* or: gcc gsl_vector.c $(pkg-config --libs gsl)
*/
#include <stdio.h>
#include <gsl/gsl_vector.h>
static double v2;
int main(int argc, char * argv[]) {
gsl_vector * v = gsl_vector_calloc(3);
gsl_vector_set_all(v, 84.0);
gsl_vector_fprintf(stdout, v, "%f");
gsl_vector_free(v);
return 0;
}
| {
"alphanum_fraction": 0.6454918033,
"avg_line_length": 16.8275862069,
"ext": "c",
"hexsha": "4c6ad92bf7e7c3d4fb2fab268e19a634b3bae779",
"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_vector.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_vector.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_vector.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": 152,
"size": 488
} |
//==============================================
//---------- by Dmitry R. Gulevich -------------
//--------- drgulevich@corp.ifmo.ru ------------
//--- ITMO University, St Petersburg, Russia ---
//==============================================
// Translation to C++ and augmentation
// S. R. Whiteley, wrcad.com, Synopsys, Inc
//==============================================
//
// License: GNU General Public License Version 3, 29 June 2007.
#ifndef MMJCO_H
#define MMJCO_H
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <complex>
#include <cmath>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
// Uncomment this to use the cminpack library for the least-squares
// fitting, otherwise we will use the cmpfit library provided.
//#define WITH_CMINPACK
#define MM_ECHG 1.602176634e-19 // Electron charge (SI units).
#define MM_BOLTZ 1.3806226e-23 // Boltzmann constant (SI units).
using namespace std;
class mmjco
{
public:
// Constructor/destructor.
mmjco(double, double, double, double);
~mmjco();
// Functions return values for arbitrary x (values x<0 obtained by
// symmetry), not smoothed.
complex<double> Jpair(double x)
{
double absx = maximum(fabs(x), 1e-5);
return (Repair(absx) + sign(x)*1j*Impair(absx));
}
complex<double> Jqp(double x)
{
double absx = maximum(fabs(x), 1e-5);
return (Reqp(absx) + sign(x)*1j*Imqp(absx));
}
// As above, but smoothed.
complex<double> Jpair_smooth(double x)
{
return (Jpair(x) + Jpair_correction(x));
}
complex<double> Jqp_smooth(double x)
{
return (Jqp(x) + Jqp_correction(x));
}
// Utilities.
static double sign(double x)
{
if (x > 0.0)
return (1.0);
if (x == 0.0)
return (0.0);
return (-1.0);
}
static double minimum(double x, double y) { return (x < y ? x : y); }
static double maximum(double x, double y) { return (x > y ? x : y); }
static void save_data(const char*, const double*, const complex<double>*,
const complex<double>*, int);
static const char *version() { return (mm_version); }
private:
double Repair(double);
double Impair(double);
double Reqp(double);
double Imqp(double);
double Repair_integrand_part1(double y, double x)
{
return (tanh(mm_b*fabs(y))/
( sqrt(mm_dd1-(y-x)*(y-x)) * sqrt(y*y-mm_dd2) ));
}
double Repair_integrand_part2(double y, double x)
{
return (tanh(mm_b*fabs(y))/
( sqrt(y*y-mm_dd1) * sqrt(mm_dd2-(y+x)*(y+x)) ));
}
double Impair_integrand(double y, double x)
{
return (( tanh(mm_b*(y+x)) - tanh(mm_b*y) )*sign(y)*sign(y+x)/(
sqrt(y*y-mm_dd1) * sqrt((y+x)*(y+x)-mm_dd2) ));
}
double Reqp_integrand_part1(double y, double x)
{
return (fabs(y)*tanh(mm_b*y)*(y-x)/( sqrt(y*y-mm_dd1) *
sqrt(mm_dd2-(y-x)*(y-x)) ));
}
double Reqp_integrand_part1b_d1_xd2(double y, double x)
{
return (fabs(y)*tanh(mm_b*y)*(y-x)/sqrt((y+mm_d1)*(mm_d2+y-x)));
}
double Reqp_integrand_part1b_xd2_xd2(double y, double x)
{
return (fabs(y)*tanh(mm_b*y)*(y-x)/sqrt(y*y-mm_dd1));
}
double Reqp_integrand_part2_xd1_d2(double y, double x)
{
return (fabs(y)*tanh(mm_b*y)*(y+x)/sqrt((mm_d1-y-x)*(mm_d2-y)));
}
double Reqp_integrand_part2_xd1_xd1(double y, double x)
{
return (fabs(y)*tanh(mm_b*y)*(y+x)/sqrt(y*y-mm_dd2));
}
double Imqp_integrand(double y, double x)
{
return (( tanh(mm_b*(y+x))-tanh(mm_b*y) )*fabs(y)*fabs(y+x)/
( sqrt((y+x)*(y+x)-mm_dd1) * sqrt(y*y-mm_dd2) ));
}
// Passed to integration functions.
static double re_p_i1(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Repair_integrand_part1(x, m->mm_arg));
}
static double re_p_i2(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Repair_integrand_part2(x, m->mm_arg));
}
static double im_p_i(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Impair_integrand(x, m->mm_arg));
}
static double re_q_i1(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Reqp_integrand_part1(x, m->mm_arg));
}
static double re_q_i1b1x2(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Reqp_integrand_part1b_d1_xd2(x, m->mm_arg));
}
static double re_q_i1bx2x2(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Reqp_integrand_part1b_xd2_xd2(x, m->mm_arg));
}
static double re_q_i2x12(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Reqp_integrand_part2_xd1_d2(x, m->mm_arg));
}
static double re_q_i2x1x1(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Reqp_integrand_part2_xd1_xd1(x, m->mm_arg));
}
static double im_q_i(double x, void *ptr)
{
mmjco *m = (mmjco*)ptr;
return (m->Imqp_integrand(x, m->mm_arg));
}
// Smoothing.
complex<double> Jpair_correction(double x)
{
if (mm_symj) {
double absx = maximum(fabs(x),1.e-5);
return (dRe(absx) + sign(x)*1j*(dIm(absx) + dIm_at_0(absx)));
}
else {
double absx = maximum(fabs(x),1.e-5);
return (dRe(absx) + dRe_minus(absx) + sign(x)*1j*(dIm(absx) +
dIm_minus(absx)));
}
}
complex<double> Jqp_correction(double x)
{
if (mm_symj) {
double absx = maximum(fabs(x),1.e-5);
return (dRe(absx) + sign(x)*1j*(-dIm(absx) + dIm_at_0(absx)));
}
else {
double absx = maximum(fabs(x),1.e-5);
return (dRe(absx) - dRe_minus(absx) + sign(x)*1j*(-dIm(absx) +
dIm_minus(absx)));
}
}
// Smoothing for Repair, Reqp.
double dRe(double x)
{
double sqpos = (x-1.0)*(x-1.0);
double sqneg = (x+1.0)*(x+1.0);
return (-x*(1.0/M_PI)*mm_ip0*0.5*log(
((sqpos+mm_dsm*mm_dsm)/sqpos)*(sqneg/(sqneg+mm_dsm*mm_dsm)) ));
}
// Smoothing for Repair, -Reqp at x=mm_d2-mm_d1.
double dRe_minus(double x)
{
return (M_PI*x*sqrt(mm_d1*mm_d2)*
(tanh(mm_b*mm_d2)-tanh(mm_b*mm_d1)) *
0.5*( (2.0/M_PI)*atan((x-mm_d21)/mm_dsm)
- sign(x-mm_d21) + (2.0/M_PI)*atan((x+mm_d21)/mm_dsm) -
sign(x+mm_d21) ) / (4.0*mm_d21));
}
// Smoothing for Impair, Imqp at x=mm_d2-mm_d1.
double dIm_minus(double x)
{
double square1 = (x-mm_d21)*(x-mm_d21);
double square2 = (x+mm_d21)*(x+mm_d21);
return (-x*sqrt(mm_d1*mm_d2)*(tanh(mm_b*mm_d2)-tanh(mm_b*mm_d1))*
0.5*log((square1+mm_dsm*mm_dsm)*(square2+mm_dsm*mm_dsm)/
(square1*square2)) / (4.0*mm_d21));
}
// Smoothing for Impair, -Imqp.
double dIm(double x)
{
return (x*0.5*mm_ip0*((2.0/M_PI)*atan((1.0-x)/mm_dsm) -
sign(1.0-x) + (2.0/M_PI)*atan((1.0+x)/mm_dsm) - sign(1.0+x)));
}
// Smoothing for Impair, Imqp at mm_d2-mm_d1=0.
double dIm_at_0(double x)
{
double x2=x*x;
return (-mm_b*x*mm_expb*0.5*log(
(x2+mm_dsm*mm_dsm)/x2)/((mm_expb+1.0)*(mm_expb+1.0)));
}
static const char *mm_version;
double mm_d1, mm_d2;
double mm_d21;
double mm_dd1, mm_dd2;
double mm_b;
double mm_arg;
int mm_limit;
int mm_key;
double mm_epsabs;
double mm_epsrel;
gsl_integration_workspace *mm_ws;
gsl_integration_qaws_table *mm_tbl;
// Smoothing.
double mm_expb;
double mm_ip0;
double mm_dsm;
bool mm_symj;;
};
//
// Class to compute optimized TCA fitting parameters.
//
// Largest acceptable fitting table.
#define MAX_NTERMS 20
class mmjco_fit
{
public:
struct mm_adata
{
const double *x;
double thr;
const complex<double> *Jpair_data;
const complex<double> *Jqp_data;
};
mmjco_fit()
{
mmf_pAB = 0;
mmf_nterms = 0;
}
~mmjco_fit()
{
delete [] mmf_pAB;
}
void new_fit_parameters(const double*, const complex<double>*,
const complex<double>*, int, int, double);
void save_fit_parameters(const char*);
void load_fit_parameters(const char*);
void tca_fit(const double*, int, complex<double>**, complex<double>**);
double residual(const complex<double>*, const complex<double>*,
const complex<double>*, const complex<double>*, int, double);
const complex<double> *params() const { return (mmf_pAB); }
int numterms() const { return (mmf_nterms); }
private:
static complex<double> *modelJpair(const complex<double>*, int,
const double*, int);
static complex<double> *modelJqp(const complex<double>*, int,
const double*, int);
static double rep(double zeta) { return (-fabs(zeta)); }
static double invrep(double xi) { return (-xi); }
// Relative difference with threshold thr.
static double Drel(double X, double Xref, double thr)
{
double axref = fabs(Xref);
if (thr > axref)
axref = thr;
return (fabs(X-Xref)/axref);
}
// Flatten complex array.
static double *realimag(complex<double> *carray, int sz)
{
double *param_list = new double[2*sz];
for (int i = 0; i < sz; i++) {
param_list[i*2] = carray[i].real();
param_list[i*2+1] = carray[i].imag();
}
return (param_list);
}
// Form complex array.
static complex<double> *ccombine(const double *param_list, int plsz)
{
complex<double> *cpars = new complex<double>[plsz/2];
for (int i = 0; i < plsz; i++) {
int n = i/2;
if (i & 1)
cpars[n].imag(param_list[i]);
else
cpars[n].real(param_list[i]);
}
return (cpars);
}
#ifdef WITH_CMINPACK
static int func(void*, int, int, const double*, double*, int);
#else
static int func(int, int, double*, double*, double**, void*);
#endif
complex<double> *mmf_pAB;
int mmf_nterms;
};
#endif // MMJCO_H
| {
"alphanum_fraction": 0.5249011147,
"avg_line_length": 28.6701030928,
"ext": "h",
"hexsha": "39f8292bb4bda46806a0b67e46867f89e78a1d0c",
"lang": "C",
"max_forks_count": 34,
"max_forks_repo_forks_event_max_datetime": "2022-02-18T16:22:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-06T17:04:21.000Z",
"max_forks_repo_head_hexsha": "5d32ad130cfd13f4e5ecaae7701f2863b4558f4e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "markvolkmann/xictools",
"max_forks_repo_path": "wrspice/mmjco/mmjco.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "5d32ad130cfd13f4e5ecaae7701f2863b4558f4e",
"max_issues_repo_issues_event_max_datetime": "2022-03-20T19:35:36.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-01T10:18:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "markvolkmann/xictools",
"max_issues_repo_path": "wrspice/mmjco/mmjco.h",
"max_line_length": 79,
"max_stars_count": 73,
"max_stars_repo_head_hexsha": "f46ba6d42801426739cc8b2940a809b74f1641e2",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "wrcad/xictools",
"max_stars_repo_path": "wrspice/mmjco/mmjco.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-02T16:59:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-26T12:40:24.000Z",
"num_tokens": 3214,
"size": 11124
} |
/**
*
* @file qwrapper_zlansy.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Julien Langou
* @author Henricus Bouwmeester
* @author Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_zlansy(Quark *quark, Quark_Task_Flags *task_flags,
int norm, PLASMA_enum uplo, int N,
const PLASMA_Complex64_t *A, int LDA, int szeA,
int szeW, double *result)
{
szeW = max(1, szeW);
DAG_CORE_LANSY;
QUARK_Insert_Task(quark, CORE_zlansy_quark, task_flags,
sizeof(PLASMA_enum), &norm, VALUE,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex64_t)*szeA, A, INPUT,
sizeof(int), &LDA, VALUE,
sizeof(double)*szeW, NULL, SCRATCH,
sizeof(double), result, OUTPUT,
0);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlansy_f1(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum norm, PLASMA_enum uplo, int N,
const PLASMA_Complex64_t *A, int LDA, int szeA,
int szeW, double *result,
double *fake, int szeF)
{
szeW = max(1, szeW);
DAG_CORE_LANSY;
if ( result == fake ) {
QUARK_Insert_Task(quark, CORE_zlansy_quark, task_flags,
sizeof(PLASMA_enum), &norm, VALUE,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex64_t)*szeA, A, INPUT,
sizeof(int), &LDA, VALUE,
sizeof(double)*szeW, NULL, SCRATCH,
sizeof(double)*szeF, result, OUTPUT | GATHERV,
0);
} else {
QUARK_Insert_Task(quark, CORE_zlansy_f1_quark, task_flags,
sizeof(PLASMA_enum), &norm, VALUE,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex64_t)*szeA, A, INPUT,
sizeof(int), &LDA, VALUE,
sizeof(double)*szeW, NULL, SCRATCH,
sizeof(double), result, OUTPUT,
sizeof(double)*szeF, fake, OUTPUT | GATHERV,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlansy_quark = PCORE_zlansy_quark
#define CORE_zlansy_quark PCORE_zlansy_quark
#endif
void CORE_zlansy_quark(Quark *quark)
{
double *normA;
int norm;
PLASMA_enum uplo;
int N;
PLASMA_Complex64_t *A;
int LDA;
double *work;
quark_unpack_args_7(quark, norm, uplo, N, A, LDA, work, normA);
*normA = LAPACKE_zlansy_work(
LAPACK_COL_MAJOR,
lapack_const(norm), lapack_const(uplo),
N, A, LDA, work);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlansy_f1_quark = PCORE_zlansy_f1_quark
#define CORE_zlansy_f1_quark PCORE_zlansy_f1_quark
#endif
void CORE_zlansy_f1_quark(Quark *quark)
{
double *normA;
int norm;
PLASMA_enum uplo;
int N;
PLASMA_Complex64_t *A;
int LDA;
double *work;
double *fake;
quark_unpack_args_8(quark, norm, uplo, N, A, LDA, work, normA, fake);
*normA = LAPACKE_zlansy_work(
LAPACK_COL_MAJOR,
lapack_const(norm),
lapack_const(uplo),
N, A, LDA, work);
}
| {
"alphanum_fraction": 0.4912446758,
"avg_line_length": 33.5396825397,
"ext": "c",
"hexsha": "8f9356168cfb447f4ebc46a6d7ca75f3c5eb2627",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_zlansy.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_zlansy.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_zlansy.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1130,
"size": 4226
} |
#pragma once
#include "gl_helpers.h"
#include "GL_Loader.h"
#include "MappedGL.h"
#include "Range.h"
#include <handy/Guard.h>
#include <gsl/span>
#include <type_traits>
#include <vector>
namespace ad {
namespace graphics {
struct [[nodiscard]] VertexArrayObject : public ResourceGuard<GLuint>
{
/// \note Deleting a bound VAO reverts the binding to zero
VertexArrayObject() :
ResourceGuard<GLuint>{reserve(glGenVertexArrays),
[](GLuint aIndex){glDeleteVertexArrays(1, &aIndex);}}
{}
};
inline void bind(const VertexArrayObject & aVertexArray)
{
glBindVertexArray(aVertexArray);
}
// TODO Ad 2022/02/02: Is it a good idea to "expect" the object to unbind
// when the underlying unbinding mechanism does not use it (just reset a default)?
inline void unbind(const VertexArrayObject & aVertexArray)
{
glBindVertexArray(0);
}
/// \TODO understand when glDisableVertexAttribArray should actually be called
/// (likely not specially before destruction, but more when rendering other objects
/// since it is a current(i.e. global) VAO state)
/// \Note Well note even that: Activated vertex attribute array are per VAO, so changing VAO
/// Already correctly handles that.
struct [[nodiscard]] VertexBufferObject : public ResourceGuard<GLuint>
{
VertexBufferObject() :
ResourceGuard<GLuint>{reserve(glGenBuffers),
[](GLuint aIndex){glDeleteBuffers(1, &aIndex);}}
{}
};
inline void bind(const VertexBufferObject & aVertexBuffer)
{
glBindBuffer(GL_ARRAY_BUFFER, aVertexBuffer);
}
inline void unbind(const VertexBufferObject &)
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
struct [[nodiscard]] IndexBufferObject : public ResourceGuard<GLuint>
{
IndexBufferObject() :
ResourceGuard<GLuint>{reserve(glGenBuffers),
[](GLuint aIndex){glDeleteBuffers(1, &aIndex);}}
{}
};
inline void bind(const IndexBufferObject & aIndexBuffer)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, aIndexBuffer);
}
inline void unbind(const IndexBufferObject &)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
/// \brief A VertexArray with a vector of VertexBuffers
struct [[nodiscard]] VertexSpecification
{
VertexSpecification(VertexArrayObject aVertexArray={},
std::vector<VertexBufferObject> aVertexBuffers={}) :
mVertexArray{std::move(aVertexArray)},
mVertexBuffers{std::move(aVertexBuffers)}
{}
VertexArrayObject mVertexArray;
std::vector<VertexBufferObject> mVertexBuffers;
};
inline void bind(const VertexSpecification & aVertexSpecification)
{
bind(aVertexSpecification.mVertexArray);
}
inline void unbind(const VertexSpecification & aVertexSpecification)
{
unbind(aVertexSpecification.mVertexArray);
}
/// \brief Describes the attribute access from the shader (layout id, value type, normalization)
struct Attribute
{
enum class Access
{
Float,
Integer,
};
constexpr Attribute(GLuint aValue) :
mIndex(aValue)
{}
constexpr Attribute(GLuint aValue, Access aAccess, bool aNormalize=false) :
mIndex(aValue),
mTypeInShader(aAccess),
mNormalize(aNormalize)
{}
GLuint mIndex; // index to match in vertex shader.
Access mTypeInShader{Access::Float}; // destination data type
bool mNormalize{false}; // if destination is float and source is integral, should it be normalized (value/type_max_value)
};
/// \brief The complete description of an attribute expected by OpenGL
struct AttributeDescription : public Attribute
{
GLuint mDimension; // from 1 to 4 (explicit distinct attributes must be used for matrix data)
size_t mOffset; // offset for the attribute within the vertex data structure (interleaved)
GLenum mDataType; // attribute source data type
};
std::ostream & operator<<(std::ostream &aOut, const AttributeDescription & aDescription);
typedef std::initializer_list<AttributeDescription> AttributeDescriptionList;
/***
*
* Vertex Buffer
*
***/
/// \brief Attach an existing VertexBuffer to an exisiting VertexArray,
/// without providing initial data.
void attachVertexBuffer(const VertexBufferObject & aVertexBuffer,
const VertexArrayObject & aVertexArray,
AttributeDescriptionList aAttributes,
GLsizei aStride,
GLuint aAttributeDivisor = 0);
/// \brief This overload deduces the stride from T_vertex.
template <class T_vertex>
void attachVertexBuffer(const VertexBufferObject & aVertexBuffer,
const VertexArrayObject & aVertexArray,
AttributeDescriptionList aAttributes,
GLuint aAttributeDivisor = 0)
{
return attachVertexBuffer(aVertexBuffer, aVertexArray, aAttributes, sizeof(T_vertex), aAttributeDivisor);
}
/// \brief Intialize a VertexBufferObject, without providing initial data.
///
/// This is an extension of `attachVertexBuffer()`, which constructs the vertex buffer it attaches,
/// instead of expecting it as argument.
VertexBufferObject initVertexBuffer(const VertexArrayObject & aVertexArray,
AttributeDescriptionList aAttributes,
GLsizei aStride,
GLuint aAttributeDivisor = 0);
/// \brief This overload deduces the stride from T_vertex.
template <class T_vertex>
VertexBufferObject initVertexBuffer(const VertexArrayObject & aVertexArray,
AttributeDescriptionList aAttributes,
GLuint aAttributeDivisor = 0)
{
return initVertexBuffer(aVertexArray, aAttributes, sizeof(T_vertex), aAttributeDivisor);
}
/// \brief Create a VertexBufferObject with provided attributes, load it with data,
/// and associate the data to attributes of `aVertexArray`.
///
/// This is an extension of `initVertexBuffer()`, which loads data into the initialized vertex buffer.
///
/// \param aAttribute describes the associaiton.
///
/// \note This is the lowest level overload, with explicit attribute description and raw data pointer.
/// Other overloads end-up calling it.
VertexBufferObject loadVertexBuffer(const VertexArrayObject & aVertexArray,
AttributeDescriptionList aAttributes,
GLsizei aStride,
size_t aSize,
const GLvoid * aData,
GLuint aAttributeDivisor = 0);
/// \brief This overload deduces the stride and size from T_vertex,
/// which could itself be deduced from the provided span.
template <class T_vertex>
VertexBufferObject loadVertexBuffer(const VertexArrayObject & aVertexArray,
const AttributeDescriptionList & aAttributes,
const gsl::span<T_vertex> aVertices,
GLuint aAttributeDivisor = 0)
{
return loadVertexBuffer(aVertexArray,
aAttributes,
sizeof(T_vertex),
aVertices.size_bytes(),
aVertices.data(),
aAttributeDivisor);
}
/// \brief Create a VertexBufferObject and load it with provided data.
/// But do **not** attach it to a VertexArrayObject / do **not** associate the vertex data to attributes.
///
/// \note Attachment to a VertexArrayObject as well as attributes association might be done later with
/// `attachVertexBuffer()`.
template <class T_vertex>
VertexBufferObject loadUnattachedVertexBuffer(gsl::span<const T_vertex> aVertices,
GLenum aHint = GL_STATIC_DRAW)
{
VertexBufferObject vbo;
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, aVertices.size_bytes(), aVertices.data(), aHint);
return vbo;
}
/// \brief High-level function directly appending a loaded VertexBuffer to a VertexSpecification.
///
/// This is an extension to `loadVertexBuffer()`, which appends the loaded vertex buffer to `aSpecification`.
template <class T_vertex>
void appendToVertexSpecification(VertexSpecification & aSpecification,
const AttributeDescriptionList & aAttributes,
const gsl::span<T_vertex> aVertices,
GLuint aAttributeDivisor = 0)
{
aSpecification.mVertexBuffers.push_back(
loadVertexBuffer(aSpecification.mVertexArray,
aAttributes,
std::move(aVertices),
aAttributeDivisor));
}
/***
*
* Index Buffer
*
***/
/// \brief Attach an existing IndexBuffer to an exisiting VertexArray,
/// without providing initial data.
inline void attachIndexBuffer(const IndexBufferObject & aIndexBuffer,
const VertexArrayObject & aVertexArray)
{
glBindVertexArray(aVertexArray);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, aIndexBuffer);
}
/// \brief Intialize and attach an IndexBufferObject, without providing initial data.
///
/// This is an extension of `attachIndexBuffer()`, which constructs the index buffer it attaches,
/// instead of expecting it as argument.
inline IndexBufferObject initIndexBuffer(const VertexArrayObject & aVertexArray)
{
IndexBufferObject ibo;
attachIndexBuffer(ibo, aVertexArray);
return ibo;
}
/// \brief Initialize, attach and load data into an IndexBufferObject.
///
/// This is an extension of `initIndexBuffer()`, which loads data into the initialized vertex buffer.
template <class T_index>
IndexBufferObject loadIndexBuffer(const VertexArrayObject & aVertexArray,
const gsl::span<T_index> aIndices,
const BufferHint aHint)
{
IndexBufferObject ibo = initIndexBuffer(aVertexArray);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, aIndices.size_bytes(), aIndices.data(), getGLBufferHint(aHint));
return ibo;
}
/***
* Buffer re-specification
*
* see: https://www.khronos.org/opengl/wiki/Buffer_Object_Streaming#Buffer_re-specification
***/
/// \brief Respecify content of a vertex buffer.
inline void respecifyBuffer(const VertexBufferObject & aVBO, const GLvoid * aData, GLsizei aSize)
{
glBindBuffer(GL_ARRAY_BUFFER, aVBO);
// Orphan the previous buffer
glBufferData(GL_ARRAY_BUFFER, aSize, NULL, GL_STATIC_DRAW);
// Copy value to new buffer
glBufferSubData(GL_ARRAY_BUFFER, 0, aSize, aData);
}
/// \brief Respecify content of an index buffer.
inline void respecifyBuffer(const IndexBufferObject & aIBO, const GLvoid * aData, GLsizei aSize)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, aIBO);
// Orphan the previous buffer
glBufferData(GL_ELEMENT_ARRAY_BUFFER, aSize, NULL, GL_STATIC_DRAW);
// Copy value to new buffer
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, aSize, aData);
}
/// \brief Overload accepting a span of generic values, instead of low-level void pointer.
/// It works with both vertex and index buffers.
template <class T_values, class T_buffer>
void respecifyBuffer(const T_buffer & aBufferObject, const gsl::span<T_values> aValues)
{
respecifyBuffer(aBufferObject,
aValues.data(),
static_cast<GLsizei>(aValues.size_bytes()));
}
/// \brief Respecify a vertex buffer with the exactly same size (allowing potential optimizations).
///
/// \attention This is undefined behaviour is aData does not point to at least the same amount
/// of data that was present before in the re-specified vertex buffer.
inline void respecifyBufferSameSize(const VertexBufferObject & aVBO, const GLvoid * aData)
{
GLint size;
glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
respecifyBuffer(aVBO, aData, size);
}
} // namespace graphics
} // namespace ad
| {
"alphanum_fraction": 0.6794999172,
"avg_line_length": 33.364640884,
"ext": "h",
"hexsha": "9600657d0ee6899ec9f923fed1d37ade2df50556",
"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": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Adnn/Graphics",
"max_forks_repo_path": "src/lib/renderer/renderer/VertexSpecification.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8",
"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": "Adnn/Graphics",
"max_issues_repo_path": "src/lib/renderer/renderer/VertexSpecification.h",
"max_line_length": 125,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Adnn/Graphics",
"max_stars_repo_path": "src/lib/renderer/renderer/VertexSpecification.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2432,
"size": 12078
} |
#ifndef __INC_MODELSTRUCT__
#define __INC_MODELSTRUCT__
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
/**
* @file modelstruct.h
* \brief defines modelstruct which contains the raw data to be worked on by emulator and estimator
*/
struct optstruct;
//! holds the main data structures for a single model emulator run
/**
* \struct modelstruct
* this structure is everything you need to do run the estimation and the
* emulation
*
* it contains:
* training vector
* model points
* theta vector (hyperparameters)
* the options used to define this model
* \note: the options used to be kept separately, they are now always contained in the modelstruct
*/
typedef struct modelstruct{
/**
* \brief x_values (nmodel_points * nparams)
*
* the points at which the model (that which is to be emulated) was evaluated,
* each row is a new model point, the columns are the dimensions
*/
gsl_matrix* xmodel;
/**
* \brief y_values (nmodel_points)
*
* the values of the model evaluated at each model point
* this is what we aim to interpolate
*/
gsl_vector* training_vector;
/**
* \brief hyperparameters (nthetas)
*
* working and eventually best values of the covariance fns (hyper)parameters which
* should force the emulated model to pass through all of the training points
*/
gsl_vector* thetas;
/**
* the average distances between samples in the design in each dimension
* this sets soft minima on the correlation function length
*/
gsl_vector* sample_scales;
/**
* the options struct used to init this structure
*/
struct optstruct* options;
/**
* fnptrs which define various aspects of the regression etc
* should these be in optstruct?
*/
/**
* setup the regression H vector, depends upon the regression order
*
* (needed in regression.h)
*/
void (*makeHVector)(gsl_vector *h_vector, gsl_vector *x_location, int nparams);
/**
* points to the covariance function,
*
* (needed in emulator.h)
*/
double (*covariance_fn)(gsl_vector*, gsl_vector*, gsl_vector*, int, int);
/**
* compute the gradient matrix for the length setting theta values
* dC/dTheta = (C-nugget) * (1/2)*(x_i - x_j)^(alpha) * alpha / (thetaLength)
*
* this is a fn-ptr which will be set when the cov function is setup
* the different target fns are in emulator.c called derivative_l_<covfnname>
*
* @param covsub the covariance matrix with the nugget term subtracted
* @param thetaLength the current value of the length scale we're differentiating wrt
* @param index, the direction we're looking in
* @return dCdTheta the matrix of the derivative of C wrt index
*
* (needed in maxmultimin.h)
*/
void (*makeGradMatLength)(gsl_matrix *dCdTheta, gsl_matrix* xmodel,
double thetaLength, int index, int nmodel_points, int nparams);
} modelstruct;
#include "optstruct.h"
void alloc_modelstruct(modelstruct* the_model, optstruct* options);
void free_modelstruct(modelstruct* the_model);
void fill_modelstruct(modelstruct* the_model, optstruct* options, char** input_data);
void load_modelstruct(FILE* fptr, modelstruct* the_model, optstruct* opts);
void dump_modelstruct(FILE* fptr, modelstruct* the_model, optstruct* opts);
void copy_modelstruct(modelstruct* dst, modelstruct* src);
modelstruct * alloc_modelstruct_2(gsl_matrix* xmodel, gsl_vector* training_vector, int cov_fn_index, int regression_order);
void free_modelstruct_2(modelstruct * model);
void dump_modelstruct_2(FILE *fptr, modelstruct* the_model);
modelstruct* load_modelstruct_2(FILE *fptr);
void set_global_ptrs(modelstruct * model);
gsl_vector * fill_sample_scales_vec(gsl_matrix* xmodel);
#endif
| {
"alphanum_fraction": 0.7325424643,
"avg_line_length": 29.9112903226,
"ext": "h",
"hexsha": "82507837b2518f8291d3a676b83b83a97fe31f68",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MADAI/MADAIEmulator",
"max_forks_repo_path": "src/modelstruct.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"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": "MADAI/MADAIEmulator",
"max_issues_repo_path": "src/modelstruct.h",
"max_line_length": 123,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/modelstruct.h",
"max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z",
"num_tokens": 946,
"size": 3709
} |
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpRNG.h>
#include <gbpMCMC.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_interp.h>
void free_MCMC_covariance(MCMC_info *MCMC) {
int i_DS;
MCMC_DS_info *current_DS;
MCMC_DS_info *next_DS;
if(MCMC->n_M != NULL) {
SID_log("Freeing MCMC covariance matrix...", SID_LOG_OPEN);
SID_free(SID_FARG MCMC->V);
if(MCMC->m != NULL) {
gsl_matrix_free(MCMC->m);
MCMC->m = NULL;
}
if(MCMC->b != NULL) {
gsl_vector_free(MCMC->b);
MCMC->b = NULL;
}
SID_log("Done.", SID_LOG_CLOSE);
}
}
| {
"alphanum_fraction": 0.5727762803,
"avg_line_length": 22.4848484848,
"ext": "c",
"hexsha": "82cd405f583b650f2e03497b5c41b193aaa27a08",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_covariance.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_covariance.c",
"max_line_length": 67,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_covariance.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": 233,
"size": 742
} |
#ifndef _GDRDGEMM_H
#define _GDRDGEMM_H
#ifndef MKL
#include <cblas.h>
#else
#include <mkl_cblas.h>
#endif
#define NMAT 2048
void gdr_check_and_restart(double a[][NMAT],
double b[][NMAT],
double c[][NMAT]);
void gdrblas_dgemm
(
#ifndef MKL
const enum CBLAS_ORDER ORDER,
const enum CBLAS_TRANSPOSE TRANSA,
const enum CBLAS_TRANSPOSE TRANSB,
#else
const CBLAS_ORDER ORDER,
const CBLAS_TRANSPOSE TRANSA,
const CBLAS_TRANSPOSE TRANSB,
#endif
const int M,
const int N,
const int K,
const double ALPHA,
const double * A,
const int LDA,
const double * B,
const int LDB,
const double BETA,
double * C,
const int LDC
);
void mygdrdgemm(int m,
int n,
int k,
double alpha,
double * a,
int na,
double * b,
int nb,
double beta,
double * c,
int nc);
#endif
| {
"alphanum_fraction": 0.4847693647,
"avg_line_length": 22.0961538462,
"ext": "h",
"hexsha": "d38e25d0d43d1e0588799a36dbcf0d4e6d745d7f",
"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": "gdrdgemm.h",
"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": "gdrdgemm.h",
"max_line_length": 49,
"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": "gdrdgemm.h",
"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": 285,
"size": 1149
} |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include "hdf5.h"
#include <math.h>
#include <time.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf_bessel.h>
#include "mclib_3d.h"
//#include "mclib.h"
#include <omp.h>
#define R_DIM 1260
#define THETA_DIM 280
#define PHI_DIM 280
void read_hydro(char hydro_prefix[200], int frame, double r_inj, double **x, double **y, double **z, double **szx, double **szy, double **r, double **theta, double **phi,\
double **velx, double **vely, double **velz, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj, double min_r, double max_r, double fps, FILE *fPtr)
{
FILE *hydroPtr=NULL;
char hydrofile[200]="", file_num[200]="", full_file[200]="" ;
char buf[10]="";
int i=0, j=0, k=0, elem=0;
float buffer=0;
float *dens_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);
float *vel_r_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);
float *vel_theta_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);
float *vel_phi_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);
float *pres_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);
double ph_rmin=0, ph_rmax=0;
double r_in=1e10, r_ref=2e13;
double *r_edge=malloc(sizeof(double)*(R_DIM+1));
double *dr=malloc(sizeof(double)*(R_DIM));
double *r_unprc=malloc(sizeof(double)*R_DIM);
double *theta_unprc=malloc(sizeof(double)*THETA_DIM);
double *phi_unprc=malloc(sizeof(double)*PHI_DIM);
if (ph_inj==0)
{
ph_rmin=min_r;
ph_rmax=max_r;
}
//density
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 1,"-" );
modifyFlashName(file_num, hydrofile, frame, 1);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, ".data");
fprintf(fPtr,"Reading Density: %s\n", full_file);
fflush(fPtr);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(dens_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr); //data
fclose(hydroPtr);
for (i=0;i<R_DIM*THETA_DIM*PHI_DIM;i++)
{
if ((i>98784000-5) || (i<5))
{
fprintf(fPtr,"Density %d: %0.7e\n", i, *(dens_unprc+i));
fflush(fPtr);
}
}
//velocities divided by c
//v_r
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 2,"-" );
modifyFlashName(file_num, hydrofile, frame, 1);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, ".data");
fprintf(fPtr,"Reading v_r: %s\n", full_file);
fflush(fPtr);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(vel_r_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);
fclose(hydroPtr);
for (i=0;i<5;i++)
{
fprintf(fPtr,"V_r %d: %e\n", i, *(vel_r_unprc+i));
fflush(fPtr);
}
//v_theta
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 3,"-" );
modifyFlashName(file_num, hydrofile, frame, 1);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, ".data");
fprintf(fPtr,"Reading v_theta: %s\n", full_file);
fflush(fPtr);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(vel_theta_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);
fclose(hydroPtr);
for (i=0;i<5;i++)
{
fprintf(fPtr,"V_theta %d: %e\n", i, *(vel_theta_unprc+i));
fflush(fPtr);
}
//v_phi
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 4,"-" );
modifyFlashName(file_num, hydrofile, frame, 1);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, ".data");
fprintf(fPtr,"Reading v_phi: %s\n", full_file);
fflush(fPtr);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(vel_phi_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);
fclose(hydroPtr);
for (i=0;i<5;i++)
{
fprintf(fPtr,"V_phi %d: %e\n", i, *(vel_phi_unprc+i));
fflush(fPtr);
}
//pressure (divided by c^2)
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 8,"-" );
modifyFlashName(file_num, hydrofile, frame, 1);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, ".data");
fprintf(fPtr,"Reading pres: %s\n", full_file);
fflush(fPtr);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(pres_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);
fclose(hydroPtr);
for (i=PHI_DIM-1;i<PHI_DIM;i++)
{
for (j=THETA_DIM-1;j<THETA_DIM;j++)
{
for (k=R_DIM-5;k<R_DIM;k++)
{
fprintf(fPtr,"Pres %d: %e\n", (i*R_DIM*THETA_DIM + j*R_DIM + k ), *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )));
fflush(fPtr);
}
}
}
// see how many elements there are to test if reading correctly
/*
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
while (1 == fread(&buffer,sizeof(float),1,hydroPtr))
{
elem++;
}
//fread(pres_unprc, sizeof(double)*HYDRO_DIM,HYDRO_DIM, hydroPtr);
fclose(hydroPtr);
fprintf(fPtr,"Elem %d\n", elem);
*/
//R
if (frame<=1300)
{
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 0,"-x1.data" );
}
else if (frame<=2000)
{
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 1,"-x1.data" );
}
else
{
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"grid0", 2,"-x1.data" );
}
fprintf(fPtr,"Reading Radius: %s\n", hydrofile);
fflush(fPtr);
hydroPtr=fopen(hydrofile, "r");
i=0;
while (i<R_DIM)
{
fscanf(hydroPtr, "%lf", (r_unprc+i)); //read value
fgets(buf, 3,hydroPtr); //read comma
if (i<5)
{
fprintf(fPtr,"R %d: %e\n", i, *(r_unprc+i));
fflush(fPtr);
}
i++;
}
fclose(hydroPtr);
//calculate radial grid edges
*(r_edge+0)=r_in;
i=0;
for (i=1;i<R_DIM;i++)
{
*(r_edge+i)=(*(r_edge+i-1))+((*(r_edge+i-1))*(M_PI/560)/(1+((*(r_edge+i-1))/r_ref))); //r_i = r_(i-1) + Dq r_(i-1) [1 + r_(i-1)/r0]-1
*(dr+i-1)=(*(r_edge+i))-(*(r_edge+i-1));
if (i<5)
{
fprintf(fPtr,"R Edge: %d: %e Dr: %e\n", i, *(r_edge+i), *(dr+i-1));
fflush(fPtr);
}
}
free(r_edge);
//Theta
snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x2.data" );
fprintf(fPtr,"Reading Theta: %s\n", hydrofile);
fflush(fPtr);
hydroPtr=fopen(hydrofile, "r");
i=0;
while (i<THETA_DIM)
{
fscanf(hydroPtr, "%lf", (theta_unprc+i)); //read value
fgets(buf, 3,hydroPtr); //read comma
if (i<5)
{
fprintf(fPtr,"R %d: %e\n", i, *(theta_unprc+i));
fflush(fPtr);
}
i++;
}
fclose(hydroPtr);
//Phi
snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x3.data" );
fprintf(fPtr,"Reading Phi: %s\n", hydrofile);
fflush(fPtr);
hydroPtr=fopen(hydrofile, "r");
i=0;
while (i<PHI_DIM)
{
fscanf(hydroPtr, "%lf", (phi_unprc+i)); //read value
fgets(buf, 3,hydroPtr); //read comma
if (i<5)
{
fprintf(fPtr,"R %d: %e\n", i, *(phi_unprc+i));
fflush(fPtr);
}
i++;
}
fclose(hydroPtr);
//limit number of array elements
elem=0;
for (i=0;i<PHI_DIM;i++)
{
for (j=0;j<THETA_DIM;j++)
{
for (k=0;k<R_DIM;k++)
{
//if I have photons do selection differently than if injecting photons
if (ph_inj==0)
{
//if calling this function when propagating photons, choose blocks based on where the photons are
if (((ph_rmin - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k) < (ph_rmax + C_LIGHT/fps) ))
{
// *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )
elem++;
}
}
else
{
//if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient
if (((r_inj - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k) < (r_inj + C_LIGHT/fps) ))
{
// *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )
elem++;
}
}
}
}
}
fprintf(fPtr,"Number of post restricted Elems: %d %e\n", elem, r_inj);
//allocate space for new set of data
(*pres)=malloc (elem * sizeof (double ));
(*velx)=malloc (elem * sizeof (double ));
(*vely)=malloc (elem * sizeof (double ));
(*velz)=malloc (elem * sizeof (double ));
(*dens)=malloc (elem * sizeof (double ));
(*x)=malloc (elem * sizeof (double ));
(*y)=malloc (elem * sizeof (double ));
(*z)=malloc (elem * sizeof (double ));
(*r)=malloc (elem * sizeof (double ));
(*theta)=malloc (elem * sizeof (double ));
(*phi)=malloc (elem * sizeof (double ));
(*gamma)=malloc (elem * sizeof (double ));
(*dens_lab)=malloc (elem * sizeof (double ));
(*szx)=malloc (elem * sizeof (double )); //theta and phi resolution
(*szy)=malloc (elem * sizeof (double )); //r resolution
(*temp)=malloc (elem * sizeof (double ));
//limit number of array elements
elem=0;
for (i=0;i<PHI_DIM;i++)
{
for (j=0;j<THETA_DIM;j++)
{
for (k=0;k<R_DIM;k++)
{
//if I have photons do selection differently than if injecting photons
if (ph_inj==0)
{
//if calling this function when propagating photons, choose blocks based on where the photons are
if (((ph_rmin - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k) < (ph_rmax + C_LIGHT/fps) ))
{
(*pres)[elem] = *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ));
(*dens)[elem] = *(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ));
(*temp)[elem] = pow(3*(*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
//fprintf(fPtr, "Selected Values: pres, %e, temp, %e\n",*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),pow(3*(*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0) );
(*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);
(*dens_lab)[elem] = (*(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);
(*r)[elem] = *(r_unprc+k);
(*theta)[elem] = *(theta_unprc+j);
(*phi)[elem] = *(phi_unprc+i);
(*x)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i));
(*y)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i));
(*z)[elem] = (*(r_unprc+k))*cos(*(theta_unprc+j));
(*szx)[elem] = M_PI/560;
(*szy)[elem] = *(dr+k);
(*velx)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*cos(*(phi_unprc+i))) - ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(phi_unprc+i)));
(*vely)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(phi_unprc+i)));
(*velz)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))) - ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j)));
elem++;
}
}
else
{
//if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient
if (((r_inj - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k) < (r_inj + C_LIGHT/fps) ))
{
(*pres)[elem] = *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ));
(*dens)[elem] = *(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ));
(*temp)[elem] = pow(3*(*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
(*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);
(*dens_lab)[elem] = (*(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);
(*r)[elem] = *(r_unprc+k);
(*theta)[elem] = *(theta_unprc+j);
(*phi)[elem] = *(phi_unprc+i);
(*x)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i));
(*y)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i));
(*z)[elem] = (*(r_unprc+k))*cos(*(theta_unprc+j));
(*szx)[elem] = M_PI/560;
(*szy)[elem] = *(dr+k);
(*velx)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*cos(*(phi_unprc+i))) - ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(phi_unprc+i)));
(*vely)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(phi_unprc+i)));
(*velz)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))) - ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j)));
elem++;
}
}
}
}
}
*number=elem;
free(pres_unprc); free(dens_unprc); free(r_unprc); free(theta_unprc); free(phi_unprc);free(dr);free(vel_r_unprc); free(vel_theta_unprc); free(vel_phi_unprc);
}
void photonInjection3D( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\
double *x, double *y, double *z, double *szx, double *szy, double *r, double *theta, double *phi, double *temps, double *vx, double *vy, double *vz, gsl_rng * rand)
{
int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0;
double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, theta_prime=0;
double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame)
double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values
float num_dens_coeff;
if (spect=='w') //from MCRAT paper, w for wien spectrum
{
num_dens_coeff=8.44;
printf("in wien spectrum\n");
}
else
{
num_dens_coeff=20.29; //this is for black body spectrum
printf("in BB spectrum");
}
//find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for
//and then rcord which blocks have to have "x" amount of photons injected there
printf("%e, %e\n",*(phi+i), theta_max);
for(i=0;i<array_length;i++)
{
//look at all boxes in width delta r=c/fps and within angles we are interested in NEED TO modify for RIKEN data- dont need r anymore, just theta and phi? (didnt work), just look at pojection on x-z plane
theta_prime=acos(*(y+i)/(*(r+i))); //jet axis here is the y axis
if ( (theta_prime< theta_max) && (theta_prime > theta_min) ) //(*(r+i) > (r_inj - C_LIGHT/fps)) && (*(r+i) < (r_inj + C_LIGHT/fps) ) &&
{
//printf("%e\n", theta_prime );
block_cnt++;
}
}
printf("Blocks: %d\n", block_cnt);
ph_dens=malloc(block_cnt * sizeof(int));
//calculate the photon density for each block and save it to the array
j=0;
ph_tot=0;
ph_weight_adjusted=ph_weight;
//printf("%d %d\n", max_photons, min_photons);
while ((ph_tot>max_photons) || (ph_tot<min_photons) )
{
j=0;
ph_tot=0;
//allocate memory to record density of photons for each block
//ph_dens=malloc(block_cnt * sizeof(int));
for (i=0;i<array_length;i++)
{
//printf("%d\n",i);
//printf("%e, %e, %e, %e, %e, %e\n", *(r+i),(r_inj - C_LIGHT/fps), (r_inj + C_LIGHT/fps), *(theta+i) , theta_max, theta_min);
//NEED TO modify for RIKEN data - modified
theta_prime=acos(*(y+i)/(*(r+i)));
if ( (theta_prime< theta_max) && (theta_prime > theta_min) )
{
//NEED TO modify for RIKEN data - modified
ph_dens_calc=(num_dens_coeff*pow(*(temps+i),3.0)*pow(*(r+i),2)*sin(*(theta+i))* pow(*(szx+i),2.0)*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2,
(*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc
//printf("%d, %lf \n",*(ph_dens+j), ph_dens_calc);
//sum up all the densities to get total number of photons
ph_tot+=(*(ph_dens+j));
j++;
}
}
if (ph_tot>max_photons)
{
//if the number of photons is too big make ph_weight larger
ph_weight_adjusted*=10;
//free(ph_dens);
}
else if (ph_tot<min_photons)
{
ph_weight_adjusted*=0.5;
//free(ph_dens);
}
//printf("dens: %d, photons: %d\n", *(ph_dens+(j-1)), ph_tot);
}
printf("%d\n", ph_tot);
//allocate memory for that many photons and also allocate memory to hold comoving 4 momentum of each photon and the velocity of the fluid
(*ph)=malloc (ph_tot * sizeof (struct photon ));
p_comv=malloc(4*sizeof(double));
boost=malloc(3*sizeof(double));
l_boost=malloc(4*sizeof(double));
//go through blocks and assign random energies/locations to proper number of photons
ph_tot=0;
k=0;
for (i=0;i<array_length;i++)
{
theta_prime=acos(*(y+i)/(*(r+i)));
if ( (theta_prime< theta_max) && (theta_prime > theta_min) ) //NEED TO modify for RIKEN data - modified
{
//*(temps+i)=0.76*(*(temps+i));
for(j=0;j<( *(ph_dens+k) ); j++ )
{
//have to get random frequency for the photon comoving frequency
y_dum=1; //initalize loop
yfr_dum=0;
while (y_dum>yfr_dum)
{
fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz
//printf("%lf, %lf ",gsl_rng_uniform_pos(rand), (*(temps+i)));
y_dum=gsl_rng_uniform_pos(rand);
//printf("%lf ",fr_dum);
if (spect=='w')
{
yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum
}
else
{
fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb
bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max
yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency
}
//printf("%lf, %lf,%lf,%e \n",(*(temps+i)),fr_dum, y_dum, yfr_dum);
}
//printf("%lf\n ",fr_dum);
//position_phi= gsl_rng_uniform(rand)*2*M_PI; //NEED TO modify for RIKEN data-modified, dont need anymore
com_v_phi=gsl_rng_uniform(rand)*2*M_PI;
com_v_theta=acos((gsl_rng_uniform(rand)*2)-1);
//printf("%lf, %lf, %lf\n", position_phi, com_v_phi, com_v_theta);
//populate 4 momentum comoving array
*(p_comv+0)=PL_CONST*fr_dum/C_LIGHT;
*(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi);
*(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi);
*(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta);
//populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code...
//NEED TO modify for RIKEN data - modified
*(boost+0)=-1*(*(vx+i));
*(boost+1)=-1*(*(vy+i));
*(boost+2)=-1*(*(vz+i));
//printf("%lf, %lf, %lf\n", *(boost+0), *(boost+1), *(boost+2));
//boost to lab frame
lorentzBoost(boost, p_comv, l_boost, 'p');
//printf("Assignemnt: %e, %e, %e, %e\n", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3));
(*ph)[ph_tot].p0=(*(l_boost+0));
(*ph)[ph_tot].p1=(*(l_boost+1));
(*ph)[ph_tot].p2=(*(l_boost+2));
(*ph)[ph_tot].p3=(*(l_boost+3));
//NEED TO modify for RIKEN data-modified
(*ph)[ph_tot].r0= (*(x+i)); //put photons @ center of box that they are supposed to be in with random phi
(*ph)[ph_tot].r1=(*(y+i)) ;
(*ph)[ph_tot].r2=(*(z+i)); //y coordinate in flash becomes z coordinate in MCRaT
(*ph)[ph_tot].num_scatt=0;
(*ph)[ph_tot].weight=ph_weight_adjusted;
//printf("%d\n",ph_tot);
ph_tot++;
}
k++;
}
}
*ph_num=ph_tot; //save number of photons
//printf(" %d: %d\n", *(ph_dens+(k-1)), *ph_num);
free(ph_dens); free(p_comv);free(boost); free(l_boost);
}
void phMinMax(struct photon *ph, int ph_num, double *min, double *max)
{
double temp_r_max=0, temp_r_min=-1;
int i=0;
double ph_r=0;
for (i=0;i<ph_num;i++)
{
ph_r=pow(pow( ((ph+i)->r0), 2.0) + pow(((ph+i)->r1),2.0 ) + pow(((ph+i)->r2) , 2.0),0.5);
if (ph_r > temp_r_max )
{
temp_r_max=ph_r;
printf("The new max is: %e\n", temp_r_max);
}
if ((i==0) || (ph_r<temp_r_min))
{
temp_r_min=ph_r;
printf("The new min is: %e\n", temp_r_min);
}
}
*max=temp_r_max;
*min=temp_r_min;
} | {
"alphanum_fraction": 0.5234012975,
"avg_line_length": 42.1073170732,
"ext": "c",
"hexsha": "0e4bd46ffa6b5526621a48eee13e0de5a40dcb16",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z",
"max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "outflows/MCRaT",
"max_forks_repo_path": "OLDER_MCRaT_VERSIONS/mclib_3d.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"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": "outflows/MCRaT",
"max_issues_repo_path": "OLDER_MCRaT_VERSIONS/mclib_3d.c",
"max_line_length": 314,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "outflows/MCRaT",
"max_stars_repo_path": "OLDER_MCRaT_VERSIONS/mclib_3d.c",
"max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z",
"num_tokens": 7749,
"size": 25896
} |
#include "gemm.h"
#include "utils.h"
#include "cuda.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <omp.h>
#ifdef OPENBLAS
#include <cblas.h>
#endif
#ifdef OPENGEMM
#include "gemm_kernels.h"
#endif
void gemm_bin(int M, int N, int K, real_t ALPHA, char *A, int lda, real_t *B,
int ldb, real_t *C, int ldc) {
int i, j, k;
for (i = 0; i < M; ++i) {
for (k = 0; k < K; ++k) {
char A_PART = A[i * lda + k];
if (A_PART) {
for (j = 0; j < N; ++j) {
C[i * ldc + j] += B[k * ldb + j];
}
} else {
for (j = 0; j < N; ++j) {
C[i * ldc + j] -= B[k * ldb + j];
}
}
}
}
}
real_t *random_matrix(int rows, int cols) {
int i;
real_t *m = calloc(rows * cols, sizeof(real_t));
for (i = 0; i < rows * cols; ++i) {
m[i] = (real_t) rand() / RAND_MAX;
}
return m;
}
void time_random_matrix(int TA, int TB, int m, int k, int n) {
real_t *a;
if (!TA)
a = random_matrix(m, k);
else
a = random_matrix(k, m);
int lda = (!TA) ? k : m;
real_t *b;
if (!TB)
b = random_matrix(k, n);
else
b = random_matrix(n, k);
int ldb = (!TB) ? n : k;
real_t *c = random_matrix(m, n);
int i;
clock_t start = clock(), end;
for (i = 0; i < 10; ++i) {
gemm_cpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c, n);
}
end = clock();
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf ms\n", m, k,
k, n, TA, TB, (real_t)(end - start) / CLOCKS_PER_SEC);
free(a);
free(b);
free(c);
}
void gemm(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A, int lda,
real_t *B, int ldb, real_t BETA, real_t *C, int ldc) {
gemm_cpu(TA, TB, M, N, K, ALPHA, A, lda, B, ldb, BETA, C, ldc);
}
void gemm_nn(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,
int ldb, real_t *C, int ldc) {
int i, j, k;
#pragma omp parallel for
for (i = 0; i < M; ++i) {
for (k = 0; k < K; ++k) {
register real_t A_PART = ALPHA * A[i * lda + k];
for (j = 0; j < N; ++j) {
C[i * ldc + j] += A_PART * B[k * ldb + j];
}
}
}
}
void gemm_nt(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,
int ldb, real_t *C, int ldc) {
int i, j, k;
#pragma omp parallel for
for (i = 0; i < M; ++i) {
for (j = 0; j < N; ++j) {
register real_t sum = 0;
for (k = 0; k < K; ++k) {
sum += ALPHA * A[i * lda + k] * B[j * ldb + k];
}
C[i * ldc + j] += sum;
}
}
}
void gemm_tn(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,
int ldb, real_t *C, int ldc) {
int i, j, k;
#pragma omp parallel for
for (i = 0; i < M; ++i) {
for (k = 0; k < K; ++k) {
register real_t A_PART = ALPHA * A[k * lda + i];
for (j = 0; j < N; ++j) {
C[i * ldc + j] += A_PART * B[k * ldb + j];
}
}
}
}
void gemm_tt(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,
int ldb, real_t *C, int ldc) {
int i, j, k;
#pragma omp parallel for
for (i = 0; i < M; ++i) {
for (j = 0; j < N; ++j) {
register real_t sum = 0;
for (k = 0; k < K; ++k) {
sum += ALPHA * A[i + k * lda] * B[k + j * ldb];
}
C[i * ldc + j] += sum;
}
}
}
void gemm_cpu(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A,
int lda, real_t *B, int ldb, real_t BETA, real_t *C, int ldc) {
//printf("cpu: %d %d %d %d %d %f %d %d %f %d\n",TA, TB, M, N, K, ALPHA, lda, ldb, BETA, ldc);
#ifdef OPENBLAS
/*
void cblas_sgemm ( const CBLAS_LAYOUT layout,
const CBLAS_TRANSPOSE TransA,
const CBLAS_TRANSPOSE TransB,
const int M,
const int N,
const int K,
const float alpha,
const float * A,
const int lda,
const float * B,
const int ldb,
const float beta,
float * C,
const int ldc
)
*/
CBLAS_TRANSPOSE transa, transb;
if (!TA && !TB){
transa = CblasNoTrans;
transb = CblasNoTrans;
}else if (TA && !TB){
transa = CblasTrans;
transb = CblasNoTrans;
}else if (!TA && TB){
transa = CblasNoTrans;
transb = CblasTrans;
}else{
transa = CblasTrans;
transb = CblasTrans;
}
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13
cblas_sgemm(CblasRowMajor, transa, transb, M, N, K, ALPHA, A, lda, B, ldb, BETA, C, ldc);
#else
int i, j;
for (i = 0; i < M; ++i) {
for (j = 0; j < N; ++j) {
C[i * ldc + j] *= BETA;
}
}
if (!TA && !TB)
gemm_nn(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);
else if (TA && !TB)
gemm_tn(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);
else if (!TA && TB)
gemm_nt(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);
else
gemm_tt(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);
#endif
}
#ifdef GPU
void gemm_gpu(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A_gpu,
int lda, real_t *B_gpu, int ldb, real_t BETA, real_t *C_gpu, int ldc,
unsigned char use_tensor_cores, cudaStream_t st) {
cublasHandle_t handle = blas_handle(use_tensor_cores);
cublasSetStream(handle, st);
// if(TB || TA)
// {
// printf("Matrix need to be transposed %d %d\n", TB, TA);
// }
#ifndef OPENGEMM
#if REAL_TYPE == HALF
//run_cuda_gemm_half(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A_gpu,
// int lda, real_t *B_gpu, int ldb, real_t BETA, real_t *C_gpu, int ldc)
run_cuda_gemm_half(handle, TA, TB, M, N, K, ALPHA, A_gpu, lda, B_gpu, ldb, BETA, C_gpu, ldc, st);
#elif REAL_TYPE == FLOAT
cudaError_t status = (cudaError_t) cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,
A_gpu, lda, &BETA, C_gpu, ldc);
check_error(status);
#elif REAL_TYPE == DOUBLE
cudaError_t status = (cudaError_t) cublasDgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,
A_gpu, lda, &BETA, C_gpu, ldc);
check_error(status);
#endif
#else
#if REAL_TYPE == HALF
run_cuda_gemm_half(handle, TA, TB, M, N, K, ALPHA, A_gpu, lda, B_gpu, ldb, BETA, C_gpu, ldc, st);
#elif REAL_TYPE == FLOAT
sgemm((TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,
A_gpu, lda, &BETA, C_gpu, ldc);
#elif REAL_TYPE == DOUBLE
dgemm((TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,
A_gpu, lda, &BETA, C_gpu, ldc);
#endif
#endif
// cublasHandle_t handle = blas_handle();
// cudaError_t status = cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),
// (TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,
// A_gpu, lda, &BETA, C_gpu, ldc);
}
void time_gpu_random_matrix(int TA, int TB, int m, int k, int n) {
real_t *a;
if (!TA)
a = random_matrix(m, k);
else
a = random_matrix(k, m);
int lda = (!TA) ? k : m;
real_t *b;
if (!TB)
b = random_matrix(k, n);
else
b = random_matrix(n, k);
int ldb = (!TB) ? n : k;
real_t *c = random_matrix(m, n);
int i;
clock_t start = clock(), end;
for (i = 0; i < 32; ++i) {
gemm_gpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c, n, 0, 0x0);
}
end = clock();
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s\n", m, k,
k, n, TA, TB, (real_t)(end - start) / CLOCKS_PER_SEC);
free(a);
free(b);
free(c);
}
void time_gpu(int TA, int TB, int m, int k, int n) {
int iter = 10;
real_t *a = random_matrix(m, k);
real_t *b = random_matrix(k, n);
int lda = (!TA) ? k : m;
int ldb = (!TB) ? n : k;
real_t *c = random_matrix(m, n);
real_t *a_cl = cuda_make_array(a, m * k);
real_t *b_cl = cuda_make_array(b, k * n);
real_t *c_cl = cuda_make_array(c, m * n);
int i;
clock_t start = clock(), end;
for (i = 0; i < iter; ++i) {
gemm_gpu(TA, TB, m, n, k, 1, a_cl, lda, b_cl, ldb, 1, c_cl, n, 0, 0x0);
cudaDeviceSynchronize();
}
double flop = ((double) m) * n * (2. * k + 2.) * iter;
double gflop = flop / pow(10., 9);
end = clock();
double seconds = sec(end - start);
printf(
"Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s, %lf GFLOPS\n",
m, k, k, n, TA, TB, seconds, gflop / seconds);
cuda_free(a_cl);
cuda_free(b_cl);
cuda_free(c_cl);
free(a);
free(b);
free(c);
}
void test_gpu_accuracy(int TA, int TB, int m, int k, int n) {
srand(0);
real_t *a;
if (!TA)
a = random_matrix(m, k);
else
a = random_matrix(k, m);
int lda = (!TA) ? k : m;
real_t *b;
if (!TB)
b = random_matrix(k, n);
else
b = random_matrix(n, k);
int ldb = (!TB) ? n : k;
real_t *c = random_matrix(m, n);
real_t *c_gpu = random_matrix(m, n);
memset(c, 0, m * n * sizeof(real_t));
memset(c_gpu, 0, m * n * sizeof(real_t));
int i;
//pm(m,k,b);
gemm_gpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c_gpu, n, 0, 0x0);
//printf("GPU\n");
//pm(m, n, c_gpu);
gemm_cpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c, n);
//printf("\n\nCPU\n");
//pm(m, n, c);
double sse = 0;
for (i = 0; i < m * n; ++i) {
//printf("%f %f\n", c[i], c_gpu[i]);
sse += pow(c[i] - c_gpu[i], 2);
}
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %g SSE\n", m, k,
k, n, TA, TB, sse / (m * n));
free(a);
free(b);
free(c);
free(c_gpu);
}
int test_gpu_blas() {
/*
test_gpu_accuracy(0,0,10,576,75);
test_gpu_accuracy(0,0,17,10,10);
test_gpu_accuracy(1,0,17,10,10);
test_gpu_accuracy(0,1,17,10,10);
test_gpu_accuracy(1,1,17,10,10);
test_gpu_accuracy(0,0,1000,10,100);
test_gpu_accuracy(1,0,1000,10,100);
test_gpu_accuracy(0,1,1000,10,100);
test_gpu_accuracy(1,1,1000,10,100);
test_gpu_accuracy(0,0,10,10,10);
time_gpu(0,0,64,2916,363);(cudaError_t) cublasDgemm
time_gpu(0,0,64,2916,363);
time_gpu(0,0,64,2916,363);
time_gpu(0,0,192,729,1600);
time_gpu(0,0,384,196,1728);
time_gpu(0,0,256,196,3456);
time_gpu(0,0,256,196,2304);
time_gpu(0,0,128,4096,12544);
time_gpu(0,0,128,4096,4096);
*/
time_gpu(0, 0, 64, 75, 12544);
time_gpu(0, 0, 64, 75, 12544);
time_gpu(0, 0, 64, 75, 12544);
time_gpu(0, 0, 64, 576, 12544);
time_gpu(0, 0, 256, 2304, 784);
time_gpu(1, 1, 2304, 256, 784);
time_gpu(0, 0, 512, 4608, 196);
time_gpu(1, 1, 4608, 512, 196);
return 0;
}
#endif
| {
"alphanum_fraction": 0.5750756811,
"avg_line_length": 25.0886075949,
"ext": "c",
"hexsha": "bd15bcab5210d8c558ae7aec7fa749f5f11dc34d",
"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": "8f7e48a4ffd3f8e819c5fc0891fb62422080aa15",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "divadnauj-GB/nvbitfi",
"max_forks_repo_path": "test-apps/darknet_v3/src/gemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8f7e48a4ffd3f8e819c5fc0891fb62422080aa15",
"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": "divadnauj-GB/nvbitfi",
"max_issues_repo_path": "test-apps/darknet_v3/src/gemm.c",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8f7e48a4ffd3f8e819c5fc0891fb62422080aa15",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "divadnauj-GB/nvbitfi",
"max_stars_repo_path": "test-apps/darknet_v3/src/gemm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3984,
"size": 9910
} |
/* Foundation and miscellenea for the statistics modules.
*
* Contents:
* 1. Summary statistics (means, variances)
* 2. Special functions
* 3. Standard statistical tests
* 4. Data fitting.
* 5. Unit tests.
* 6. Test driver.
* 7. Examples.
* - driver for linear regression
* - driver for G-test
*/
#include "esl_config.h"
#include <math.h>
#include "easel.h"
#include "esl_stats.h"
/*****************************************************************
* 1. Summary statistics calculations (means, variances)
*****************************************************************/
/* Function: esl_stats_DMean()
* Synopsis: Calculates mean and $\sigma^2$ for samples $x_i$.
*
* Purpose: Calculates the sample mean and $s^2$, the unbiased
* estimator of the population variance, for a
* sample of <n> numbers <x[0]..x[n-1]>, and optionally
* returns either or both through <ret_mean> and
* <ret_var>.
*
* <esl_stats_FMean()> and <esl_stats_IMean()> do the same,
* for float and integer vectors.
*
* Args: x - samples x[0]..x[n-1]
* n - number of samples
* opt_mean - optRETURN: mean
* opt_var - optRETURN: estimate of population variance
*
* Returns: <eslOK> on success.
*/
int
esl_stats_DMean(const double *x, int n, double *opt_mean, double *opt_var)
{
double sum = 0.;
double sqsum = 0.;
int i;
for (i = 0; i < n; i++)
{
sum += x[i];
sqsum += x[i]*x[i];
}
if (opt_mean != NULL) *opt_mean = sum / (double) n;
if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);
return eslOK;
}
int
esl_stats_FMean(const float *x, int n, double *opt_mean, double *opt_var)
{
double sum = 0.;
double sqsum = 0.;
int i;
for (i = 0; i < n; i++)
{
sum += x[i];
sqsum += x[i]*x[i];
}
if (opt_mean != NULL) *opt_mean = sum / (double) n;
if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);
return eslOK;
}
int
esl_stats_IMean(const int *x, int n, double *opt_mean, double *opt_var)
{
double sum = 0.;
double sqsum = 0.;
int i;
for (i = 0; i < n; i++)
{
sum += x[i];
sqsum += x[i]*x[i];
}
if (opt_mean != NULL) *opt_mean = sum / (double) n;
if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);
return eslOK;
}
/*--------------- end, summary statistics -----------------------*/
/*****************************************************************
* 2. Special functions.
*****************************************************************/
/* Function: esl_stats_LogGamma()
* Synopsis: Calculates $\log \Gamma(x)$.
*
* Purpose: Returns natural log of $\Gamma(x)$, for $x > 0$.
*
* Credit: Adapted from a public domain implementation in the
* NCBI core math library. Thanks to John Spouge and
* the NCBI. (According to NCBI, that's Dr. John
* "Gammas Galore" Spouge to you, pal.)
*
* Args: x : argument, x > 0.0
* ret_answer : RETURN: the answer
*
* Returns: Put the answer in <ret_answer>; returns <eslOK>.
*
* Throws: <eslERANGE> if $x <= 0$.
*/
int
esl_stats_LogGamma(double x, double *ret_answer)
{
int i;
double xx, tx;
double tmp, value;
static double cof[11] = {
4.694580336184385e+04,
-1.560605207784446e+05,
2.065049568014106e+05,
-1.388934775095388e+05,
5.031796415085709e+04,
-9.601592329182778e+03,
8.785855930895250e+02,
-3.155153906098611e+01,
2.908143421162229e-01,
-2.319827630494973e-04,
1.251639670050933e-10
};
/* Protect against invalid x<=0 */
if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_LogGamma()");
xx = x - 1.0;
tx = tmp = xx + 11.0;
value = 1.0;
for (i = 10; i >= 0; i--) /* sum least significant terms first */
{
value += cof[i] / tmp;
tmp -= 1.0;
}
value = log(value);
tx += 0.5;
value += 0.918938533 + (xx+0.5)*log(tx) - tx;
*ret_answer = value;
return eslOK;
}
/* Function: esl_stats_Psi()
* Synopsis: Calculates $\Psi(x)$ (the digamma function).
*
* Purpose: Computes $\Psi(x)$ (the "digamma" function), which is
* the derivative of log of the Gamma function:
* $d/dx \log \Gamma(x) = \frac{\Gamma'(x)}{\Gamma(x)} = \Psi(x)$.
* Argument $x$ is $> 0$.
*
* This is J.M. Bernardo's "Algorithm AS103",
* Appl. Stat. 25:315-317 (1976).
*/
int
esl_stats_Psi(double x, double *ret_answer)
{
double answer = 0.;
double x2;
if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_Psi()");
/* For small x, Psi(x) ~= -0.5772 - 1/x + O(x), we're done.
*/
if (x <= 1e-5) {
*ret_answer = -eslCONST_EULER - 1./x;
return eslOK;
}
/* For medium x, use Psi(1+x) = \Psi(x) + 1/x to c.o.v. x,
* big enough for Stirling approximation to work...
*/
while (x < 8.5) {
answer = answer - 1./x;
x += 1.;
}
/* For large X, use Stirling approximation
*/
x2 = 1./x;
answer += log(x) - 0.5 * x2;
x2 = x2*x2;
answer -= (1./12.)*x2;
answer += (1./120.)*x2*x2;
answer -= (1./252.)*x2*x2*x2;
*ret_answer = answer;
return eslOK;
}
/* Function: esl_stats_IncompleteGamma()
* Synopsis: Calculates the incomplete Gamma function.
*
* Purpose: Returns $P(a,x)$ and $Q(a,x)$ where:
*
* \begin{eqnarray*}
* P(a,x) & = & \frac{1}{\Gamma(a)} \int_{0}^{x} t^{a-1} e^{-t} dt \\
* & = & \frac{\gamma(a,x)}{\Gamma(a)} \\
* Q(a,x) & = & \frac{1}{\Gamma(a)} \int_{x}^{\infty} t^{a-1} e^{-t} dt\\
* & = & 1 - P(a,x) \\
* \end{eqnarray*}
*
* $P(a,x)$ is the CDF of a gamma density with $\lambda = 1$,
* and $Q(a,x)$ is the survival function.
*
* For $x \simeq 0$, $P(a,x) \simeq 0$ and $Q(a,x) \simeq 1$; and
* $P(a,x)$ is less prone to roundoff error.
*
* The opposite is the case for large $x >> a$, where
* $P(a,x) \simeq 1$ and $Q(a,x) \simeq 0$; there, $Q(a,x)$ is
* less prone to roundoff error.
*
* Method: Based on ideas from Numerical Recipes in C, Press et al.,
* Cambridge University Press, 1988.
*
* Args: a - for instance, degrees of freedom / 2 [a > 0]
* x - for instance, chi-squared statistic / 2 [x >= 0]
* ret_pax - RETURN: P(a,x)
* ret_qax - RETURN: Q(a,x)
*
* Return: <eslOK> on success.
*
* Throws: <eslERANGE> if <a> or <x> is out of accepted range.
* <eslENOHALT> if approximation fails to converge.
*/
int
esl_stats_IncompleteGamma(double a, double x, double *ret_pax, double *ret_qax)
{
int iter; /* iteration counter */
double pax; /* P(a,x) */
double qax; /* Q(a,x) */
int status;
if (a <= 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): a must be > 0");
if (x < 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): x must be >= 0");
/* For x > a + 1 the following gives rapid convergence;
* calculate Q(a,x) = \frac{\Gamma(a,x)}{\Gamma(a)},
* using a continued fraction development for \Gamma(a,x).
*/
if (x > a+1)
{
double oldp; /* previous value of p */
double nu0, nu1; /* numerators for continued fraction calc */
double de0, de1; /* denominators for continued fraction calc */
nu0 = 0.; /* A_0 = 0 */
de0 = 1.; /* B_0 = 1 */
nu1 = 1.; /* A_1 = 1 */
de1 = x; /* B_1 = x */
oldp = nu1;
for (iter = 1; iter < 100; iter++)
{
/* Continued fraction development:
* set A_j = b_j A_j-1 + a_j A_j-2
* B_j = b_j B_j-1 + a_j B_j-2
* We start with A_2, B_2.
*/
/* j = even: a_j = iter-a, b_j = 1 */
/* A,B_j-2 are in nu0, de0; A,B_j-1 are in nu1,de1 */
nu0 = nu1 + ((double)iter - a) * nu0;
de0 = de1 + ((double)iter - a) * de0;
/* j = odd: a_j = iter, b_j = x */
/* A,B_j-2 are in nu1, de1; A,B_j-1 in nu0,de0 */
nu1 = x * nu0 + (double) iter * nu1;
de1 = x * de0 + (double) iter * de1;
/* rescale */
if (de1 != 0.)
{
nu0 /= de1;
de0 /= de1;
nu1 /= de1;
de1 = 1.;
}
/* check for convergence */
if (fabs((nu1-oldp)/nu1) < 1.e-7)
{
if ((status = esl_stats_LogGamma(a, &qax)) != eslOK) return status;
qax = nu1 * exp(a * log(x) - x - qax);
if (ret_pax != NULL) *ret_pax = 1 - qax;
if (ret_qax != NULL) *ret_qax = qax;
return eslOK;
}
oldp = nu1;
}
ESL_EXCEPTION(eslENOHALT,
"esl_stats_IncompleteGamma(): fraction failed to converge");
}
else /* x <= a+1 */
{
double p; /* current sum */
double val; /* current value used in sum */
/* For x <= a+1 we use a convergent series instead:
* P(a,x) = \frac{\gamma(a,x)}{\Gamma(a)},
* where
* \gamma(a,x) = e^{-x}x^a \sum_{n=0}{\infty} \frac{\Gamma{a}}{\Gamma{a+1+n}} x^n
* which looks appalling but the sum is in fact rearrangeable to
* a simple series without the \Gamma functions:
* = \frac{1}{a} + \frac{x}{a(a+1)} + \frac{x^2}{a(a+1)(a+2)} ...
* and it's obvious that this should converge nicely for x <= a+1.
*/
p = val = 1. / a;
for (iter = 1; iter < 10000; iter++)
{
val *= x / (a+(double)iter);
p += val;
if (fabs(val/p) < 1.e-7)
{
if ((status = esl_stats_LogGamma(a, &pax)) != eslOK) return status;
pax = p * exp(a * log(x) - x - pax);
if (ret_pax != NULL) *ret_pax = pax;
if (ret_qax != NULL) *ret_qax = 1. - pax;
return eslOK;
}
}
ESL_EXCEPTION(eslENOHALT,
"esl_stats_IncompleteGamma(): series failed to converge");
}
/*NOTREACHED*/
return eslOK;
}
/* Function: esl_stats_erfc()
* Synopsis: Complementary error function.
*
* Purpose: Calculate and return the complementary error function,
* erfc(x).
*
* erfc(x) is mandated by the ANSI C99 standard but that
* doesn't mean it's available on supposedly modern systems
* (looking at you here, Microsoft).
*
* Used for cumulative distribution function calculations
* for the normal (Gaussian) distribution. See <esl_normal>
* module.
*
* erfc(-inf) = 2.0
* erfc(0) = 1.0
* erfc(inf) = 0.0
* erfc(NaN) = NaN
*
* Args: x : any real-numbered value -inf..inf
*
* Returns: erfc(x)
*
* Throws: (no abnormal error conditions)
*
* Source:
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this software is
* freely granted, provided that this notice is preserved.
* [as posted by eggcrook at stackexchange.com, 21 Dec 2012]
*
* Removed arcane incantations for runtime detection of endianness,
* and for treating IEEE754 doubles as two adjacent uint32_t;
* replaced with ANSI-compliant macros and compile-time detection
* of endianness. [Apr 2015]
*/
double
esl_stats_erfc(double x)
{
static const double tiny = 1e-300;
static const double half = 5.00000000000000000000e-01; /* 0x3FE00000, 0x00000000 */
static const double one = 1.00000000000000000000e+00; /* 0x3FF00000, 0x00000000 */
static const double two = 2.00000000000000000000e+00; /* 0x40000000, 0x00000000 */
static const double erx = 8.45062911510467529297e-01; /* 0x3FEB0AC1, 0x60000000 */
/*
* Coefficients for approximation to erf on [0,0.84375]
*/
static const double pp0 = 1.28379167095512558561e-01; /* 0x3FC06EBA, 0x8214DB68 */
static const double pp1 = -3.25042107247001499370e-01; /* 0xBFD4CD7D, 0x691CB913 */
static const double pp2 = -2.84817495755985104766e-02; /* 0xBF9D2A51, 0xDBD7194F */
static const double pp3 = -5.77027029648944159157e-03; /* 0xBF77A291, 0x236668E4 */
static const double pp4 = -2.37630166566501626084e-05; /* 0xBEF8EAD6, 0x120016AC */
static const double qq1 = 3.97917223959155352819e-01; /* 0x3FD97779, 0xCDDADC09 */
static const double qq2 = 6.50222499887672944485e-02; /* 0x3FB0A54C, 0x5536CEBA */
static const double qq3 = 5.08130628187576562776e-03; /* 0x3F74D022, 0xC4D36B0F */
static const double qq4 = 1.32494738004321644526e-04; /* 0x3F215DC9, 0x221C1A10 */
static const double qq5 = -3.96022827877536812320e-06; /* 0xBED09C43, 0x42A26120 */
/*
* Coefficients for approximation to erf in [0.84375,1.25]
*/
static const double pa0 = -2.36211856075265944077e-03; /* 0xBF6359B8, 0xBEF77538 */
static const double pa1 = 4.14856118683748331666e-01; /* 0x3FDA8D00, 0xAD92B34D */
static const double pa2 = -3.72207876035701323847e-01; /* 0xBFD7D240, 0xFBB8C3F1 */
static const double pa3 = 3.18346619901161753674e-01; /* 0x3FD45FCA, 0x805120E4 */
static const double pa4 = -1.10894694282396677476e-01; /* 0xBFBC6398, 0x3D3E28EC */
static const double pa5 = 3.54783043256182359371e-02; /* 0x3FA22A36, 0x599795EB */
static const double pa6 = -2.16637559486879084300e-03; /* 0xBF61BF38, 0x0A96073F */
static const double qa1 = 1.06420880400844228286e-01; /* 0x3FBB3E66, 0x18EEE323 */
static const double qa2 = 5.40397917702171048937e-01; /* 0x3FE14AF0, 0x92EB6F33 */
static const double qa3 = 7.18286544141962662868e-02; /* 0x3FB2635C, 0xD99FE9A7 */
static const double qa4 = 1.26171219808761642112e-01; /* 0x3FC02660, 0xE763351F */
static const double qa5 = 1.36370839120290507362e-02; /* 0x3F8BEDC2, 0x6B51DD1C */
static const double qa6 = 1.19844998467991074170e-02; /* 0x3F888B54, 0x5735151D */
/*
* Coefficients for approximation to erfc in [1.25,1/0.35]
*/
static const double ra0 = -9.86494403484714822705e-03; /* 0xBF843412, 0x600D6435 */
static const double ra1 = -6.93858572707181764372e-01; /* 0xBFE63416, 0xE4BA7360 */
static const double ra2 = -1.05586262253232909814e+01; /* 0xC0251E04, 0x41B0E726 */
static const double ra3 = -6.23753324503260060396e+01; /* 0xC04F300A, 0xE4CBA38D */
static const double ra4 = -1.62396669462573470355e+02; /* 0xC0644CB1, 0x84282266 */
static const double ra5 = -1.84605092906711035994e+02; /* 0xC067135C, 0xEBCCABB2 */
static const double ra6 = -8.12874355063065934246e+01; /* 0xC0545265, 0x57E4D2F2 */
static const double ra7 = -9.81432934416914548592e+00; /* 0xC023A0EF, 0xC69AC25C */
static const double sa1 = 1.96512716674392571292e+01; /* 0x4033A6B9, 0xBD707687 */
static const double sa2 = 1.37657754143519042600e+02; /* 0x4061350C, 0x526AE721 */
static const double sa3 = 4.34565877475229228821e+02; /* 0x407B290D, 0xD58A1A71 */
static const double sa4 = 6.45387271733267880336e+02; /* 0x40842B19, 0x21EC2868 */
static const double sa5 = 4.29008140027567833386e+02; /* 0x407AD021, 0x57700314 */
static const double sa6 = 1.08635005541779435134e+02; /* 0x405B28A3, 0xEE48AE2C */
static const double sa7 = 6.57024977031928170135e+00; /* 0x401A47EF, 0x8E484A93 */
static const double sa8 = -6.04244152148580987438e-02; /* 0xBFAEEFF2, 0xEE749A62 */
/*
* Coefficients for approximation to erfc in [1/.35,28]
*/
static const double rb0 = -9.86494292470009928597e-03; /* 0xBF843412, 0x39E86F4A */
static const double rb1 = -7.99283237680523006574e-01; /* 0xBFE993BA, 0x70C285DE */
static const double rb2 = -1.77579549177547519889e+01; /* 0xC031C209, 0x555F995A */
static const double rb3 = -1.60636384855821916062e+02; /* 0xC064145D, 0x43C5ED98 */
static const double rb4 = -6.37566443368389627722e+02; /* 0xC083EC88, 0x1375F228 */
static const double rb5 = -1.02509513161107724954e+03; /* 0xC0900461, 0x6A2E5992 */
static const double rb6 = -4.83519191608651397019e+02; /* 0xC07E384E, 0x9BDC383F */
static const double sb1 = 3.03380607434824582924e+01; /* 0x403E568B, 0x261D5190 */
static const double sb2 = 3.25792512996573918826e+02; /* 0x40745CAE, 0x221B9F0A */
static const double sb3 = 1.53672958608443695994e+03; /* 0x409802EB, 0x189D5118 */
static const double sb4 = 3.19985821950859553908e+03; /* 0x40A8FFB7, 0x688C246A */
static const double sb5 = 2.55305040643316442583e+03; /* 0x40A3F219, 0xCEDF3BE6 */
static const double sb6 = 4.74528541206955367215e+02; /* 0x407DA874, 0xE79FE763 */
static const double sb7 = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */
int hx,ix;
double R,S,P,Q,s,y,z,r;
ESL_GET_HIGHWORD(hx, x); // SRE: replaced original Sun incantation here.
ix = hx & 0x7fffffff;
if (ix>=0x7ff00000) /* erfc(nan)=nan; erfc(+-inf)=0,2 */
return (double)(((unsigned)hx>>31)<<1)+one/x;
if (ix < 0x3feb0000) /* |x|<0.84375 */
{
if (ix < 0x3c700000) return one-x; /* |x|<2**-56 */
z = x*x;
r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));
s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));
y = r/s;
if (hx < 0x3fd00000) /* x<1/4 */
{
return one-(x+x*y);
}
else
{
r = x*y;
r += (x-half);
return half - r ;
}
}
if (ix < 0x3ff40000) /* 0.84375 <= |x| < 1.25 */
{
s = fabs(x)-one;
P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));
Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));
if (hx>=0)
{
z = one-erx;
return z - P/Q;
}
else
{
z = erx+P/Q;
return one+z;
}
}
if (ix < 0x403c0000) /* |x|<28 */
{
x = fabs(x);
s = one/(x*x);
if (ix< 0x4006DB6D) /* |x| < 1/.35 ~ 2.857143*/
{
R = ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));
S = one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));
}
else /* |x| >= 1/.35 ~ 2.857143 */
{
if (hx < 0 && ix >= 0x40180000) return two-tiny; /* x < -6 */
R = rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));
S = one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));
}
z = x;
ESL_SET_LOWWORD(z, 0); // SRE: replaced original Sun incantation here.
r = exp(-z*z-0.5625) * exp((z-x)*(z+x)+R/S);
if (hx>0) return r/x;
else return two-r/x;
}
else
{
if (hx>0) return tiny*tiny;
else return two-tiny;
}
}
/*----------------- end, special functions ----------------------*/
/*****************************************************************
* 3. Standard statistical tests.
*****************************************************************/
/* Function: esl_stats_GTest()
* Synopsis: Calculates a G-test on 2 vs. 1 binomials.
*
* Purpose: In experiment a, we've drawn <ca> successes in <na> total
* trials; in experiment b, we've drawn <cb> successes in
* <nb> total trials. Are the counts different enough to
* conclude that the two experiments are different? The
* null hypothesis is that the successes in both experiments
* were drawn from the same binomial distribution with
* per-trial probability $p$. The tested hypothesis is that
* experiments a,b have different binomial probabilities
* $p_a,p_b$. The G-test is a log-likelihood-ratio statistic,
* assuming maximum likelihood values for $p,p_a,p_b$.
* $2G$ is distributed approximately as $X^2(1)$,
* %"X" is "Chi"
* which we use to calculate a P-value for the G statistic.
*
* Args: ca - number of positives in experiment a
* na - total number in experiment a
* cb - number of positives in experiment b
* nb - total number in experiment b
* ret_G - RETURN: G statistic, a log likelihood ratio, in nats
* ret_P - RETURN: P-value for the G-statistic
*
* Returns: <eslOK> on success.
*
* Throws: (no abnormal error conditions)
*
* Xref: Archive1999/0906-sagescore/sagescore.c
*/
int
esl_stats_GTest(int ca, int na, int cb, int nb, double *ret_G, double *ret_P)
{
double a,b,c,d,n;
double G = 0.;
a = (double) ca;
b = (double) (na - ca);
c = (double) cb;
d = (double) (nb - cb);
n = (double) na+nb;
/* Yes, the calculation here is correct; algebraic
* rearrangement of the log-likelihood-ratio with
* p_a = ca/na, p_b = cb/nb, and p = (ca+cb)/(na+nb).
* Guard against 0 probabilities; assume 0 log 0 => 0.
*/
if (a > 0.) G = a * log(a);
if (b > 0.) G += b * log(b);
if (c > 0.) G += c * log(c);
if (d > 0.) G += d * log(d);
if (n > 0.) G += n * log(n);
if (a+b > 0.) G -= (a+b) * log(a+b);
if (c+d > 0.) G -= (c+d) * log(c+d);
if (a+c > 0.) G -= (a+c) * log(a+c);
if (b+d > 0.) G -= (b+d) * log(b+d);
*ret_G = G;
return esl_stats_IncompleteGamma( 0.5, G, NULL, ret_P);
}
/* Function: esl_stats_ChiSquaredTest()
* Synopsis: Calculates a $\chi^2$ P-value.
* Incept: SRE, Tue Jul 19 11:39:32 2005 [St. Louis]
*
* Purpose: Calculate the probability that a chi-squared statistic
* with <v> degrees of freedom would exceed the observed
* chi-squared value <x>; return it in <ret_answer>. If
* this probability is less than some small threshold (say,
* 0.05 or 0.01), then we may reject the hypothesis we're
* testing.
*
* Args: v - degrees of freedom
* x - observed chi-squared value
* ret_answer - RETURN: P(\chi^2 > x)
*
* Returns: <eslOK> on success.
*
* Throws: <eslERANGE> if <v> or <x> are out of valid range.
* <eslENOHALT> if iterative calculation fails.
*/
int
esl_stats_ChiSquaredTest(int v, double x, double *ret_answer)
{
return esl_stats_IncompleteGamma((double)v/2., x/2., NULL, ret_answer);
}
/*----------------- end, statistical tests ---------------------*/
/*****************************************************************
* 4. Data fitting.
*****************************************************************/
/* Function: esl_stats_LinearRegression()
* Synopsis: Fit data to a straight line.
* Incept: SRE, Sat May 26 11:33:46 2007 [Janelia]
*
* Purpose: Fit <n> points <x[i]>, <y[i]> to a straight line
* $y = a + bx$ by linear regression.
*
* The $x_i$ are taken to be known, and the $y_i$ are taken
* to be observed quantities associated with a sampling
* error $\sigma_i$. If known, the standard deviations
* $\sigma_i$ for $y_i$ are provided in the <sigma> array.
* If they are unknown, pass <sigma = NULL>, and the
* routine will proceed with the assumption that $\sigma_i
* = 1$ for all $i$.
*
* The maximum likelihood estimates for $a$ and $b$ are
* optionally returned in <opt_a> and <opt_b>.
*
* The estimated standard deviations of $a$ and $b$ and
* their estimated covariance are optionally returned in
* <opt_sigma_a>, <opt_sigma_b>, and <opt_cov_ab>.
*
* The Pearson correlation coefficient is optionally
* returned in <opt_cc>.
*
* The $\chi^2$ P-value for the regression fit is
* optionally returned in <opt_Q>. This P-value may only be
* obtained when the $\sigma_i$ are known. If <sigma> is
* passed as <NULL> and <opt_Q> is requested, <*opt_Q> is
* set to 1.0.
*
* This routine follows the description and algorithm in
* \citep[pp.661-666]{Press93}.
*
* <n> must be greater than 2; at least two x[i] must
* differ; and if <sigma> is provided, all <sigma[i]> must
* be $>0$. If any of these conditions isn't met, the
* routine throws <eslEINVAL>.
*
* Args: x - x[0..n-1]
* y - y[0..n-1]
* sigma - sample error in observed y_i
* n - number of data points
* opt_a - optRETURN: intercept estimate
* opt_b - optRETURN: slope estimate
* opt_sigma_a - optRETURN: error in estimate of a
* opt_sigma_b - optRETURN: error in estimate of b
* opt_cov_ab - optRETURN: covariance of a,b estimates
* opt_cc - optRETURN: Pearson correlation coefficient for x,y
* opt_Q - optRETURN: X^2 P-value for linear fit
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation error;
* <eslEINVAL> if a contract condition isn't met;
* <eslENORESULT> if the chi-squared test fails.
* In these cases, all optional return values are set to 0.
*/
int
esl_stats_LinearRegression(const double *x, const double *y, const double *sigma, int n,
double *opt_a, double *opt_b,
double *opt_sigma_a, double *opt_sigma_b, double *opt_cov_ab,
double *opt_cc, double *opt_Q)
{
int status;
double *t = NULL;
double S, Sx, Sy, Stt;
double Sxy, Sxx, Syy;
double a, b, sigma_a, sigma_b, cov_ab, cc, X2, Q;
double xdev, ydev;
double tmp;
int i;
/* Contract checks. */
if (n <= 2) ESL_XEXCEPTION(eslEINVAL, "n must be > 2 for linear regression fitting");
if (sigma != NULL)
for (i = 0; i < n; i++) if (sigma[i] <= 0.) ESL_XEXCEPTION(eslEINVAL, "sigma[%d] <= 0", i);
status = eslEINVAL;
for (i = 0; i < n; i++) if (x[i] != 0.) { status = eslOK; break; }
if (status != eslOK) ESL_XEXCEPTION(eslEINVAL, "all x[i] are 0.");
/* Allocations */
ESL_ALLOC(t, sizeof(double) * n);
/* S = \sum_{i=1}{n} \frac{1}{\sigma_i^2}. (S > 0.) */
if (sigma != NULL) { for (S = 0., i = 0; i < n; i++) S += 1./ (sigma[i] * sigma[i]); }
else S = (double) n;
/* S_x = \sum_{i=1}{n} \frac{x[i]}{ \sigma_i^2} (Sx real.) */
for (Sx = 0., i = 0; i < n; i++) {
if (sigma == NULL) Sx += x[i];
else Sx += x[i] / (sigma[i] * sigma[i]);
}
/* S_y = \sum_{i=1}{n} \frac{y[i]}{\sigma_i^2} (Sy real.) */
for (Sy = 0., i = 0; i < n; i++) {
if (sigma == NULL) Sy += y[i];
else Sy += y[i] / (sigma[i] * sigma[i]);
}
/* t_i = \frac{1}{\sigma_i} \left( x_i - \frac{S_x}{S} \right) (t_i real) */
for (i = 0; i < n; i++) {
t[i] = x[i] - Sx/S;
if (sigma != NULL) t[i] /= sigma[i];
}
/* S_{tt} = \sum_{i=1}^n t_i^2 (if at least one x is != 0, Stt > 0) */
for (Stt = 0., i = 0; i < n; i++) { Stt += t[i] * t[i]; }
/* b = \frac{1}{S_{tt}} \sum_{i=1}^{N} \frac{t_i y_i}{\sigma_i} */
for (b = 0., i = 0; i < n; i++) {
if (sigma != NULL) { b += t[i]*y[i] / sigma[i]; }
else { b += t[i]*y[i]; }
}
b /= Stt;
/* a = \frac{ S_y - S_x b } {S} */
a = (Sy - Sx * b) / S;
/* \sigma_a^2 = \frac{1}{S} \left( 1 + \frac{ S_x^2 }{S S_{tt}} \right) */
sigma_a = sqrt ((1. + (Sx*Sx) / (S*Stt)) / S);
/* \sigma_b = \frac{1}{S_{tt}} */
sigma_b = sqrt (1. / Stt);
/* Cov(a,b) = - \frac{S_x}{S S_{tt}} */
cov_ab = -Sx / (S * Stt);
/* Pearson correlation coefficient */
Sxy = Sxx = Syy = 0.;
for (i = 0; i < n; i++) {
if (sigma != NULL) {
xdev = (x[i] / (sigma[i] * sigma[i])) - (Sx / n);
ydev = (y[i] / (sigma[i] * sigma[i])) - (Sy / n);
} else {
xdev = x[i] - (Sx / n);
ydev = y[i] - (Sy / n);
}
Sxy += xdev * ydev;
Sxx += xdev * xdev;
Syy += ydev * ydev;
}
cc = Sxy / (sqrt(Sxx) * sqrt(Syy));
/* \chi^2 */
for (X2 = 0., i = 0; i < n; i++) {
tmp = y[i] - a - b*x[i];
if (sigma != NULL) tmp /= sigma[i];
X2 += tmp*tmp;
}
/* We can calculate a goodness of fit if we know the \sigma_i */
if (sigma != NULL) {
if (esl_stats_ChiSquaredTest(n-2, X2, &Q) != eslOK) { status = eslENORESULT; goto ERROR; }
} else Q = 1.0;
/* If we didn't use \sigma_i, adjust the sigmas for a,b */
if (sigma == NULL) {
tmp = sqrt(X2 / (double)(n-2));
sigma_a *= tmp;
sigma_b *= tmp;
}
/* Done. Set up for normal return.
*/
free(t);
if (opt_a != NULL) *opt_a = a;
if (opt_b != NULL) *opt_b = b;
if (opt_sigma_a != NULL) *opt_sigma_a = sigma_a;
if (opt_sigma_b != NULL) *opt_sigma_b = sigma_b;
if (opt_cov_ab != NULL) *opt_cov_ab = cov_ab;
if (opt_cc != NULL) *opt_cc = cc;
if (opt_Q != NULL) *opt_Q = Q;
return eslOK;
ERROR:
if (t != NULL) free(t);
if (opt_a != NULL) *opt_a = 0.;
if (opt_b != NULL) *opt_b = 0.;
if (opt_sigma_a != NULL) *opt_sigma_a = 0.;
if (opt_sigma_b != NULL) *opt_sigma_b = 0.;
if (opt_cov_ab != NULL) *opt_cov_ab = 0.;
if (opt_cc != NULL) *opt_cc = 0.;
if (opt_Q != NULL) *opt_Q = 0.;
return status;
}
/*------------------- end, data fitting -------------------------*/
/*****************************************************************
* 5. Unit tests.
*****************************************************************/
#ifdef eslSTATS_TESTDRIVE
#include "esl_random.h"
#include "esl_stopwatch.h"
#ifdef HAVE_LIBGSL
#include <gsl/gsl_sf_gamma.h>
#endif
/* Macros for treating IEEE754 double as two uint32_t halves, with
* compile-time handling of endianness; see esl_stats.h.
*/
static void
utest_doublesplitting(ESL_RANDOMNESS *rng)
{
char msg[] = "esl_stats:: doublesplitting unit test failed";
uint32_t ix0, ix1;
double x;
double x2;
int iteration; // iteration 0 uses x = 2; iteration 1 uses random x = [0,1).
for (iteration = 0; iteration < 2; iteration++)
{
x = (iteration == 0 ? 2.0 : esl_random(rng));
ESL_GET_WORDS(ix0, ix1, x);
ESL_SET_WORDS(x2, ix0, ix1);
if (x2 != x) esl_fatal(msg);
ESL_GET_HIGHWORD(ix0, x);
ESL_SET_HIGHWORD(x2, ix0);
if (x2 != x) esl_fatal(msg);
ESL_GET_LOWWORD(ix0, x);
ESL_SET_LOWWORD(x2, ix0);
if (iteration == 0 && ix0 != 0) esl_fatal(msg);
if (x2 != x) esl_fatal(msg);
}
}
/* The LogGamma() function is rate-limiting in hmmbuild, because it is
* used so heavily in mixture Dirichlet calculations.
* ./configure --with-gsl; [compile test driver]
* ./stats_utest -v
* runs a comparison of time/precision against GSL.
* SRE, Sat May 23 10:04:41 2009, on home Mac:
* LogGamma = 1.29u / N=1e8 = 13 nsec/call
* gsl_sf_lngamma = 1.43u / N=1e8 = 14 nsec/call
*/
static void
utest_LogGamma(ESL_RANDOMNESS *r, int N, int be_verbose)
{
char *msg = "esl_stats_LogGamma() unit test failed";
ESL_STOPWATCH *w = esl_stopwatch_Create();
double *x = malloc(sizeof(double) * N);
double *lg = malloc(sizeof(double) * N);
double *lg2 = malloc(sizeof(double) * N);
int i;
for (i = 0; i < N; i++)
x[i] = esl_random(r) * 100.;
esl_stopwatch_Start(w);
for (i = 0; i < N; i++)
if (esl_stats_LogGamma(x[i], &(lg[i])) != eslOK) esl_fatal(msg);
esl_stopwatch_Stop(w);
if (be_verbose) esl_stopwatch_Display(stdout, w, "esl_stats_LogGamma() timing: ");
#ifdef HAVE_LIBGSL
esl_stopwatch_Start(w);
for (i = 0; i < N; i++) lg2[i] = gsl_sf_lngamma(x[i]);
esl_stopwatch_Stop(w);
if (be_verbose) esl_stopwatch_Display(stdout, w, "gsl_sf_lngamma() timing: ");
for (i = 0; i < N; i++)
if (esl_DCompare(lg[i], lg2[i], 1e-2) != eslOK) esl_fatal(msg);
#endif
free(lg2);
free(lg);
free(x);
esl_stopwatch_Destroy(w);
}
/* The test of esl_stats_LinearRegression() is a statistical test,
* so we can't be too aggressive about testing results.
*
* Args:
* r - a source of randomness
* use_sigma - TRUE to pass sigma to the regression fit.
* be_verbose - TRUE to print results (manual, not automated test mode)
*/
static void
utest_LinearRegression(ESL_RANDOMNESS *r, int use_sigma, int be_verbose)
{
char msg[] = "linear regression unit test failed";
double a = -3.;
double b = 1.;
int n = 100;
double xori = -20.;
double xstep = 1.0;
double setsigma = 1.0; /* sigma on all points */
int i;
double *x = NULL;
double *y = NULL;
double *sigma = NULL;
double ae, be, siga, sigb, cov_ab, cc, Q;
if ((x = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
if ((y = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
if ((sigma = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
/* Simulate some linear data */
for (i = 0; i < n; i++)
{
sigma[i] = setsigma;
x[i] = xori + i*xstep;
y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);
}
if (use_sigma) {
if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);
} else {
if (esl_stats_LinearRegression(x, y, NULL, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);
}
if (be_verbose) {
printf("Linear regression test:\n");
printf("estimated intercept a = %8.4f [true = %8.4f]\n", ae, a);
printf("estimated slope b = %8.4f [true = %8.4f]\n", be, b);
printf("estimated sigma on a = %8.4f\n", siga);
printf("estimated sigma on b = %8.4f\n", sigb);
printf("estimated cov(a,b) = %8.4f\n", cov_ab);
printf("correlation coeff = %8.4f\n", cc);
printf("P-value = %8.4f\n", Q);
}
/* The following tests are statistical.
*/
if ( fabs(ae-a) > 2*siga ) esl_fatal(msg);
if ( fabs(be-b) > 2*sigb ) esl_fatal(msg);
if ( cc < 0.95) esl_fatal(msg);
if (use_sigma) {
if (Q < 0.001) esl_fatal(msg);
} else {
if (Q != 1.0) esl_fatal(msg);
}
free(x);
free(y);
free(sigma);
}
static void
utest_erfc(ESL_RANDOMNESS *rng, int be_verbose)
{
char msg[] = "esl_stats:: erfc unit test failed";
double x;
double result;
int i;
if (be_verbose) {
printf("#--------------------------\n");
printf("# erfc unit testing...\n");
}
result = esl_stats_erfc( eslNaN);
if (! isnan(result)) esl_fatal(msg);
if (esl_stats_erfc(-eslINFINITY) != 2.0) esl_fatal(msg);
if (esl_stats_erfc( 0.0) != 1.0) esl_fatal(msg);
if (esl_stats_erfc( eslINFINITY) != 0.0) esl_fatal(msg);
for (i = 0; i < 42; i++)
{
x = esl_random(rng) * 10. - 5.;
result = esl_stats_erfc(x);
if (!isfinite(result)) esl_fatal(msg);
#ifdef HAVE_ERFC
if (esl_DCompare(result, erfc(x), 1e-6) != eslOK) esl_fatal(msg);
if (be_verbose)
printf("%15f %15f %15f\n", x, result, erfc(x));
#endif
}
if (be_verbose)
printf("#--------------------------\n");
return;
}
#endif /*eslSTATS_TESTDRIVE*/
/*-------------------- end of unit tests ------------------------*/
/*****************************************************************
* 6. Test driver.
*****************************************************************/
#ifdef eslSTATS_TESTDRIVE
/* gcc -g -Wall -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lm
* gcc -DHAVE_LIBGSL -O2 -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lgsl -lm
*/
#include <stdio.h>
#include "easel.h"
#include "esl_getopts.h"
#include "esl_random.h"
#include "esl_stats.h"
static ESL_OPTIONS options[] = {
/* name type default env range togs reqs incomp help docgrp */
{"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
{"-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
{"-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "verbose: show verbose output", 0},
{"-N", eslARG_INT,"10000000", NULL, NULL, NULL, NULL, NULL, "number of trials in LogGamma test", 0},
{ 0,0,0,0,0,0,0,0,0,0},
};
static char usage[] = "[-options]";
static char banner[] = "test driver for stats special functions";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
ESL_RANDOMNESS *r = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
int be_verbose = esl_opt_GetBoolean(go, "-v");
int N = esl_opt_GetInteger(go, "-N");
if (be_verbose) printf("seed = %" PRIu32 "\n", esl_randomness_GetSeed(r));
utest_doublesplitting(r);
utest_erfc(r, be_verbose);
utest_LogGamma(r, N, be_verbose);
utest_LinearRegression(r, TRUE, be_verbose);
utest_LinearRegression(r, FALSE, be_verbose);
esl_getopts_Destroy(go);
esl_randomness_Destroy(r);
exit(0);
}
#endif /*eslSTATS_TESTDRIVE*/
/*------------------- end of test driver ------------------------*/
/*****************************************************************
* 7. Examples.
*****************************************************************/
/* Compile: gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm
* or gcc -g -Wall -o example -I. -L. -DeslSTATS_EXAMPLE esl_stats.c -leasel -lm
*/
#ifdef eslSTATS_EXAMPLE
/*::cexcerpt::stats_example::begin::*/
/* gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm */
#include <stdio.h>
#include "easel.h"
#include "esl_random.h"
#include "esl_stats.h"
int main(void)
{
ESL_RANDOMNESS *r = esl_randomness_Create(0);
double a = -3.;
double b = 1.;
double xori = -20.;
double xstep = 1.0;
double setsigma = 1.0; /* sigma on all points */
int n = 100;
double *x = malloc(sizeof(double) * n);
double *y = malloc(sizeof(double) * n);
double *sigma = malloc(sizeof(double) * n);
int i;
double ae, be, siga, sigb, cov_ab, cc, Q;
/* Simulate some linear data, with Gaussian noise added to y_i */
for (i = 0; i < n; i++) {
sigma[i] = setsigma;
x[i] = xori + i*xstep;
y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);
}
if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK)
esl_fatal("linear regression failed");
printf("estimated intercept a = %8.4f [true = %8.4f]\n", ae, a);
printf("estimated slope b = %8.4f [true = %8.4f]\n", be, b);
printf("estimated sigma on a = %8.4f\n", siga);
printf("estimated sigma on b = %8.4f\n", sigb);
printf("estimated cov(a,b) = %8.4f\n", cov_ab);
printf("correlation coeff = %8.4f\n", cc);
printf("P-value = %8.4f\n", Q);
free(x); free(y); free(sigma);
esl_randomness_Destroy(r);
exit(0);
}
/*::cexcerpt::stats_example::end::*/
#endif /* eslSTATS_EXAMPLE */
#ifdef eslSTATS_EXAMPLE2
#include <stdlib.h>
#include "easel.h"
#include "esl_getopts.h"
#include "esl_stats.h"
static ESL_OPTIONS options[] = {
/* name type default env range toggles reqs incomp help docgroup*/
{ "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
static char usage[] = "[-options] <ca> <na> <cb> <nb>";
static char banner[] = "example from the stats module: using a G-test";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 4, argc, argv, banner, usage);
int ca = strtol(esl_opt_GetArg(go, 1), NULL, 10);
int na = strtol(esl_opt_GetArg(go, 2), NULL, 10);
int cb = strtol(esl_opt_GetArg(go, 3), NULL, 10);
int nb = strtol(esl_opt_GetArg(go, 4), NULL, 10);
double G, P;
int status;
if (ca > na || cb > nb) esl_fatal("argument order wrong? expect ca, na, cb, nb for ca/na, cb/nb");
if ( (status = esl_stats_GTest(ca, na, cb, nb, &G, &P)) != eslOK) esl_fatal("G-test failed?");
printf("%-10.3g %12.2f\n", P, G);
exit(0);
}
#endif /* eslSTATS_EXAMPLE2 */
/*--------------------- end of examples -------------------------*/
| {
"alphanum_fraction": 0.5533476152,
"avg_line_length": 34.9793281654,
"ext": "c",
"hexsha": "7fc7801b80674a19c7b6126676aa4c30dec601b9",
"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": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "WooMichael/Project_Mendel",
"max_forks_repo_path": "hmmer-3.3/easel/esl_stats.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8",
"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": "WooMichael/Project_Mendel",
"max_issues_repo_path": "hmmer-3.3/easel/esl_stats.c",
"max_line_length": 124,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "WooMichael/Project_Mendel",
"max_stars_repo_path": "hmmer-3.3/easel/esl_stats.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 13737,
"size": 40611
} |
// stdafx.h
// (c) 2008-2020, Charles Lechasseur
//
// 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
// Including this header allows us to suppress C++ Core Guideline warnings more easily
#include <CppCoreCheck\warnings.h>
// Disable C++ Core checks warnings in library headers since we don't control them
#pragma warning(push)
#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)
#ifndef STRICT
#define STRICT
#endif
#include "targetver.h"
#define _ATL_APARTMENT_THREADED
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
//#define PCC_NO_CONTEXT_MENU_EXT2 // For testing purposes only
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <atlstr.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <windows.h>
// Disable some warnings in GDI+ headers
#pragma warning( push )
#pragma warning( disable : 4458 )
#include <gdiplus.h>
#pragma warning( pop )
// Undef the Windows min and max macros, since they conflict with STL
// We can't define NOMINMAX because GDI actually needs those macros :(
#undef min
#undef max
#include <algorithm>
#include <cstdint>
#include <exception>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include <utility>
#include <assert.h>
#include <memory.h>
#include <resource.h>
#include <PathCopyCopyLocalization_en\rsrc\resource.h>
#include <gsl/gsl>
#include <coveo/linq.h>
#pragma warning(pop) // core checks in library headers
#include "PathCopyCopyPrivateTypes.h"
| {
"alphanum_fraction": 0.7619954303,
"avg_line_length": 29.8409090909,
"ext": "h",
"hexsha": "48d4cdd58b68cfde97f0271e3c8404cb58b43f4e",
"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": "27ab622b3d38e9db2e80837c4657d7e9f41d2316",
"max_forks_repo_licenses": [
"MIT",
"Apache-2.0",
"MS-PL"
],
"max_forks_repo_name": "subashnict/pathcopycopy",
"max_forks_repo_path": "PathCopyCopy/prihdr/stdafx.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "27ab622b3d38e9db2e80837c4657d7e9f41d2316",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT",
"Apache-2.0",
"MS-PL"
],
"max_issues_repo_name": "subashnict/pathcopycopy",
"max_issues_repo_path": "PathCopyCopy/prihdr/stdafx.h",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "27ab622b3d38e9db2e80837c4657d7e9f41d2316",
"max_stars_repo_licenses": [
"MIT",
"Apache-2.0",
"MS-PL"
],
"max_stars_repo_name": "subashnict/pathcopycopy",
"max_stars_repo_path": "PathCopyCopy/prihdr/stdafx.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 602,
"size": 2626
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <jni.h>
#include "netlib-jni.h"
#include <cblas.h>
#include "org_apache_ignite_ml_math_NativeBlasOffHeap.h"
JNIEXPORT jdouble JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dasum (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint incx) {
jdouble * jni_dx = (jdouble *)dx;
jdouble returnValue = cblas_dasum(n, jni_dx, incx);
return returnValue;
}
JNIEXPORT jdouble JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dasum_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint _dx_offset, jint incx) {
jdouble * jni_dx = (jdouble *)dx;
jdouble returnValue = cblas_dasum(n, jni_dx + _dx_offset, incx);
return returnValue;
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_daxpy (JNIEnv * env, jobject calling_obj, jint n, jdouble da, jlong dx, jint incx, jlong dy, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_daxpy(n, da, jni_dx, incx, jni_dy, incy);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_daxpy_1offsets (JNIEnv * env, jobject calling_obj, jint n, jdouble da, jlong dx, jint _dx_offset, jint incx, jlong dy, jint _dy_offset, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_daxpy(n, da, jni_dx + _dx_offset, incx, jni_dy + _dy_offset, incy);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dcopy (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint incx, jlong dy, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_dcopy(n, jni_dx, incx, jni_dy, incy);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dcopy_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint _dx_offset, jint incx, jlong dy, jint _dy_offset, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_dcopy(n, jni_dx + _dx_offset, incx, jni_dy + _dy_offset, incy);
}
JNIEXPORT jdouble JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ddot (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint incx, jlong dy, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
jdouble returnValue = cblas_ddot(n, jni_dx, incx, jni_dy, incy);
return returnValue;
}
JNIEXPORT jdouble JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ddot_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint _dx_offset, jint incx, jlong dy, jint _dy_offset, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
jdouble returnValue = cblas_ddot(n, jni_dx + _dx_offset, incx, jni_dy + _dy_offset, incy);
return returnValue;
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dgbmv (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jint kl, jint ku, jdouble alpha, jlong a, jint lda, jlong x, jint incx, jdouble beta, jlong y, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dgbmv(CblasColMajor, getCblasTrans(jni_trans), m, n, kl, ku, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dgbmv_1offsets (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jint kl, jint ku, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx, jdouble beta, jlong y, jint _y_offset, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dgbmv(CblasColMajor, getCblasTrans(jni_trans), m, n, kl, ku, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dgemm (JNIEnv * env, jobject calling_obj, jstring transa, jstring transb, jint m, jint n, jint k, jdouble alpha, jlong a, jint lda, jlong b, jint ldb, jdouble beta, jlong c, jint Ldc) {
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_transb = (char *)(*env)->GetStringUTFChars(env, transb, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
jdouble * jni_c = (jdouble *)c;
cblas_dgemm(CblasColMajor, getCblasTrans(jni_transa), getCblasTrans(jni_transb), m, n, k, alpha, jni_a, lda, jni_b, ldb, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, transb, jni_transb);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dgemm_1offsets (JNIEnv * env, jobject calling_obj, jstring transa, jstring transb, jint m, jint n, jint k, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong b, jint _b_offset, jint ldb, jdouble beta, jlong c, jint _c_offset, jint Ldc) {
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_transb = (char *)(*env)->GetStringUTFChars(env, transb, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
jdouble * jni_c = (jdouble *)c;
cblas_dgemm(CblasColMajor, getCblasTrans(jni_transa), getCblasTrans(jni_transb), m, n, k, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, transb, jni_transb);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dgemv (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jdouble alpha, jlong a, jint lda, jlong x, jint incx, jdouble beta, jlong y, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dgemv(CblasColMajor, getCblasTrans(jni_trans), m, n, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dgemv_1offsets (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx, jdouble beta, jlong y, jint _y_offset, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dgemv(CblasColMajor, getCblasTrans(jni_trans), m, n, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dger (JNIEnv * env, jobject calling_obj, jint m, jint n, jdouble alpha, jlong x, jint incx, jlong y, jint incy, jlong a, jint lda) {
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
jdouble * jni_a = (jdouble *)a;
cblas_dger(CblasColMajor, m, n, alpha, jni_x, incx, jni_y, incy, jni_a, lda);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dger_1offsets (JNIEnv * env, jobject calling_obj, jint m, jint n, jdouble alpha, jlong x, jint _x_offset, jint incx, jlong y, jint _y_offset, jint incy, jlong a, jint _a_offset, jint lda) {
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
jdouble * jni_a = (jdouble *)a;
cblas_dger(CblasColMajor, m, n, alpha, jni_x + _x_offset, incx, jni_y + _y_offset, incy, jni_a + _a_offset, lda);
}
JNIEXPORT jdouble JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dnrm2 (JNIEnv * env, jobject calling_obj, jint n, jlong x, jint incx) {
jdouble * jni_x = (jdouble *)x;
jdouble returnValue = cblas_dnrm2(n, jni_x, incx);
return returnValue;
}
JNIEXPORT jdouble JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dnrm2_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong x, jint _x_offset, jint incx) {
jdouble * jni_x = (jdouble *)x;
jdouble returnValue = cblas_dnrm2(n, jni_x + _x_offset, incx);
return returnValue;
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_drot (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint incx, jlong dy, jint incy, jdouble c, jdouble s) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_drot(n, jni_dx, incx, jni_dy, incy, c, s);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_drot_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint _dx_offset, jint incx, jlong dy, jint _dy_offset, jint incy, jdouble c, jdouble s) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_drot(n, jni_dx + _dx_offset, incx, jni_dy + _dy_offset, incy, c, s);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_drotg (JNIEnv * env, jobject calling_obj, jdoublew da, jdoublew db, jdoublew c, jdoublew s) {
jclass jni_daClass = (*env)->GetObjectClass(env, da);
jfieldID jni_daId = (*env)->GetFieldID(env, jni_daClass, "val", "D");
jdouble jni_da = (*env)->GetDoubleField(env, da, jni_daId);
jclass jni_dbClass = (*env)->GetObjectClass(env, db);
jfieldID jni_dbId = (*env)->GetFieldID(env, jni_dbClass, "val", "D");
jdouble jni_db = (*env)->GetDoubleField(env, db, jni_dbId);
jclass jni_cClass = (*env)->GetObjectClass(env, c);
jfieldID jni_cId = (*env)->GetFieldID(env, jni_cClass, "val", "D");
jdouble jni_c = (*env)->GetDoubleField(env, c, jni_cId);
jclass jni_sClass = (*env)->GetObjectClass(env, s);
jfieldID jni_sId = (*env)->GetFieldID(env, jni_sClass, "val", "D");
jdouble jni_s = (*env)->GetDoubleField(env, s, jni_sId);
cblas_drotg(&jni_da, &jni_db, &jni_c, &jni_s);
(*env)->SetDoubleField(env, s, jni_sId, jni_s);
(*env)->SetDoubleField(env, c, jni_cId, jni_c);
(*env)->SetDoubleField(env, db, jni_dbId, jni_db);
(*env)->SetDoubleField(env, da, jni_daId, jni_da);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_drotm (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint incx, jlong dy, jint incy, jlong dparam) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
jdouble * jni_dparam = (jdouble *)dparam;
cblas_drotm(n, jni_dx, incx, jni_dy, incy, jni_dparam);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_drotm_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint _dx_offset, jint incx, jlong dy, jint _dy_offset, jint incy, jlong dparam, jint _dparam_offset) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
jdouble * jni_dparam = (jdouble *)dparam;
cblas_drotm(n, jni_dx + _dx_offset, incx, jni_dy + _dy_offset, incy, jni_dparam + _dparam_offset);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_drotmg (JNIEnv * env, jobject calling_obj, jdoublew dd1, jdoublew dd2, jdoublew dx1, jdouble dy1, jlong dparam) {
jclass jni_dd1Class = (*env)->GetObjectClass(env, dd1);
jfieldID jni_dd1Id = (*env)->GetFieldID(env, jni_dd1Class, "val", "D");
jdouble jni_dd1 = (*env)->GetDoubleField(env, dd1, jni_dd1Id);
jclass jni_dd2Class = (*env)->GetObjectClass(env, dd2);
jfieldID jni_dd2Id = (*env)->GetFieldID(env, jni_dd2Class, "val", "D");
jdouble jni_dd2 = (*env)->GetDoubleField(env, dd2, jni_dd2Id);
jclass jni_dx1Class = (*env)->GetObjectClass(env, dx1);
jfieldID jni_dx1Id = (*env)->GetFieldID(env, jni_dx1Class, "val", "D");
jdouble jni_dx1 = (*env)->GetDoubleField(env, dx1, jni_dx1Id);
jdouble * jni_dparam = (jdouble *)dparam;
cblas_drotmg(&jni_dd1, &jni_dd2, &jni_dx1, dy1, jni_dparam);
(*env)->SetDoubleField(env, dx1, jni_dx1Id, jni_dx1);
(*env)->SetDoubleField(env, dd2, jni_dd2Id, jni_dd2);
(*env)->SetDoubleField(env, dd1, jni_dd1Id, jni_dd1);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_drotmg_1offsets (JNIEnv * env, jobject calling_obj, jdoublew dd1, jdoublew dd2, jdoublew dx1, jdouble dy1, jlong dparam, jint _dparam_offset) {
jclass jni_dd1Class = (*env)->GetObjectClass(env, dd1);
jfieldID jni_dd1Id = (*env)->GetFieldID(env, jni_dd1Class, "val", "D");
jdouble jni_dd1 = (*env)->GetDoubleField(env, dd1, jni_dd1Id);
jclass jni_dd2Class = (*env)->GetObjectClass(env, dd2);
jfieldID jni_dd2Id = (*env)->GetFieldID(env, jni_dd2Class, "val", "D");
jdouble jni_dd2 = (*env)->GetDoubleField(env, dd2, jni_dd2Id);
jclass jni_dx1Class = (*env)->GetObjectClass(env, dx1);
jfieldID jni_dx1Id = (*env)->GetFieldID(env, jni_dx1Class, "val", "D");
jdouble jni_dx1 = (*env)->GetDoubleField(env, dx1, jni_dx1Id);
jdouble * jni_dparam = (jdouble *)dparam;
cblas_drotmg(&jni_dd1, &jni_dd2, &jni_dx1, dy1, jni_dparam + _dparam_offset);
(*env)->SetDoubleField(env, dx1, jni_dx1Id, jni_dx1);
(*env)->SetDoubleField(env, dd2, jni_dd2Id, jni_dd2);
(*env)->SetDoubleField(env, dd1, jni_dd1Id, jni_dd1);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsbmv (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jint k, jdouble alpha, jlong a, jint lda, jlong x, jint incx, jdouble beta, jlong y, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dsbmv(CblasColMajor, getCblasUpLo(jni_uplo), n, k, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsbmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jint k, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx, jdouble beta, jlong y, jint _y_offset, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dsbmv(CblasColMajor, getCblasUpLo(jni_uplo), n, k, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dscal (JNIEnv * env, jobject calling_obj, jint n, jdouble da, jlong dx, jint incx) {
jdouble * jni_dx = (jdouble *)dx;
cblas_dscal(n, da, jni_dx, incx);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dscal_1offsets (JNIEnv * env, jobject calling_obj, jint n, jdouble da, jlong dx, jint _dx_offset, jint incx) {
jdouble * jni_dx = (jdouble *)dx;
cblas_dscal(n, da, jni_dx + _dx_offset, incx);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dspmv (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong ap, jlong x, jint incx, jdouble beta, jlong y, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_ap = (jdouble *)ap;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dspmv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_ap, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dspmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong ap, jint _ap_offset, jlong x, jint _x_offset, jint incx, jdouble beta, jlong y, jint _y_offset, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_ap = (jdouble *)ap;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dspmv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_ap + _ap_offset, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dspr (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint incx, jlong ap) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_ap = (jdouble *)ap;
cblas_dspr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_ap);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dspr_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint _x_offset, jint incx, jlong ap, jint _ap_offset) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_ap = (jdouble *)ap;
cblas_dspr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_ap + _ap_offset);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dspr2 (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint incx, jlong y, jint incy, jlong ap) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
jdouble * jni_ap = (jdouble *)ap;
cblas_dspr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_y, incy, jni_ap);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dspr2_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint _x_offset, jint incx, jlong y, jint _y_offset, jint incy, jlong ap, jint _ap_offset) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
jdouble * jni_ap = (jdouble *)ap;
cblas_dspr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_y + _y_offset, incy, jni_ap + _ap_offset);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dswap (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint incx, jlong dy, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_dswap(n, jni_dx, incx, jni_dy, incy);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dswap_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint _dx_offset, jint incx, jlong dy, jint _dy_offset, jint incy) {
jdouble * jni_dx = (jdouble *)dx;
jdouble * jni_dy = (jdouble *)dy;
cblas_dswap(n, jni_dx + _dx_offset, incx, jni_dy + _dy_offset, incy);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsymm (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jint m, jint n, jdouble alpha, jlong a, jint lda, jlong b, jint ldb, jdouble beta, jlong c, jint Ldc) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
jdouble * jni_c = (jdouble *)c;
cblas_dsymm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), m, n, alpha, jni_a, lda, jni_b, ldb, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsymm_1offsets (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jint m, jint n, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong b, jint _b_offset, jint ldb, jdouble beta, jlong c, jint _c_offset, jint Ldc) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
double * jni_c = (jdouble *)c;
cblas_dsymm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), m, n, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsymv (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong a, jint lda, jlong x, jint incx, jdouble beta, jlong y, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dsymv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsymv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx, jdouble beta, jlong y, jint _y_offset, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
cblas_dsymv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyr (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint incx, jlong a, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_a = (jdouble *)a;
cblas_dsyr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_a, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyr_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint _x_offset, jint incx, jlong a, jint _a_offset, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_a = (jdouble *)a;
cblas_dsyr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_a + _a_offset, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyr2 (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint incx, jlong y, jint incy, jlong a, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
jdouble * jni_a = (jdouble *)a;
cblas_dsyr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_y, incy, jni_a, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyr2_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jdouble alpha, jlong x, jint _x_offset, jint incx, jlong y, jint _y_offset, jint incy, jlong a, jint _a_offset, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jdouble * jni_x = (jdouble *)x;
jdouble * jni_y = (jdouble *)x;
jdouble * jni_a = (jdouble *)a;
cblas_dsyr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_y + _y_offset, incy, jni_a + _a_offset, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyr2k (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jdouble alpha, jlong a, jint lda, jlong b, jint ldb, jdouble beta, jlong c, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
double * jni_c = (jdouble *)c;
cblas_dsyr2k(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a, lda, jni_b, ldb, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyr2k_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong b, jint _b_offset, jint ldb, jdouble beta, jlong c, jint _c_offset, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
double * jni_c = (jdouble *)c;
cblas_dsyr2k(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyrk (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jdouble alpha, jlong a, jint lda, jdouble beta, jlong c, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
double * jni_c = (jdouble *)c;
cblas_dsyrk(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a, lda, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dsyrk_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jdouble alpha, jlong a, jint _a_offset, jint lda, jdouble beta, jlong c, jint _c_offset, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
double * jni_c = (jdouble *)c;
cblas_dsyrk(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a + _a_offset, lda, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtbmv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jlong a, jint lda, jlong x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtbmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtbmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtbmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtbsv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jlong a, jint lda, jlong x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtbsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtbsv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtbsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtpmv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong ap, jlong x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_ap = (jdouble *)ap;
jdouble * jni_x = (jdouble *)x;
cblas_dtpmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtpmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong ap, jint _ap_offset, jlong x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_ap = (jdouble *)ap;
jdouble * jni_x = (jdouble *)x;
cblas_dtpmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap + _ap_offset, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtpsv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong ap, jlong x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_ap = (jdouble *)ap;
jdouble * jni_x = (jdouble *)x;
cblas_dtpsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtpsv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong ap, jint _ap_offset, jlong x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_ap = (jdouble *)ap;
jdouble * jni_x = (jdouble *)x;
cblas_dtpsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap + _ap_offset, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrmm (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jdouble alpha, jlong a, jint lda, jlong b, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
cblas_dtrmm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a, lda, jni_b, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrmm_1offsets (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong b, jint _b_offset, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
cblas_dtrmm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrmv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong a, jint lda, jlong x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtrmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtrmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrsm (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jdouble alpha, jlong a, jint lda, jlong b, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
cblas_dtrsm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a, lda, jni_b, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrsm_1offsets (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jdouble alpha, jlong a, jint _a_offset, jint lda, jlong b, jint _b_offset, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_b = (jdouble *)b;
cblas_dtrsm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrsv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong a, jint lda, jlong x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtrsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_dtrsv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jlong a, jint _a_offset, jint lda, jlong x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jdouble * jni_a = (jdouble *)a;
jdouble * jni_x = (jdouble *)x;
cblas_dtrsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT jint JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_idamax (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint incx) {
jdouble * jni_dx = (jdouble *)dx;
jint returnValue = cblas_idamax(n, jni_dx, incx);
return returnValue;
}
JNIEXPORT jint JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_idamax_1offsets (JNIEnv * env, jobject calling_obj, jint n, jlong dx, jint _dx_offset, jint incx) {
jdouble * jni_dx = (jdouble *)dx;
jint returnValue = cblas_idamax(n, jni_dx + _dx_offset, incx);
return returnValue;
}
JNIEXPORT jint JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_isamax (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint incx) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jint returnValue = cblas_isamax(n, jni_sx, incx);
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT jint JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_isamax_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint _sx_offset, jint incx) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jint returnValue = cblas_isamax(n, jni_sx + _sx_offset, incx);
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sasum (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint incx) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat returnValue = cblas_sasum(n, jni_sx, incx);
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sasum_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint _sx_offset, jint incx) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat returnValue = cblas_sasum(n, jni_sx + _sx_offset, incx);
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_saxpy (JNIEnv * env, jobject calling_obj, jint n, jfloat sa, jfloatArray sx, jint incx, jfloatArray sy, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_saxpy(n, sa, jni_sx, incx, jni_sy, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_saxpy_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloat sa, jfloatArray sx, jint _sx_offset, jint incx, jfloatArray sy, jint _sy_offset, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_saxpy(n, sa, jni_sx + _sx_offset, incx, jni_sy + _sy_offset, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_scopy (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint incx, jfloatArray sy, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_scopy(n, jni_sx, incx, jni_sy, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_scopy_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint _sx_offset, jint incx, jfloatArray sy, jint _sy_offset, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_scopy(n, jni_sx + _sx_offset, incx, jni_sy + _sy_offset, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sdot (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint incx, jfloatArray sy, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
jfloat returnValue = cblas_sdot(n, jni_sx, incx, jni_sy, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sdot_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint _sx_offset, jint incx, jfloatArray sy, jint _sy_offset, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
jfloat returnValue = cblas_sdot(n, jni_sx + _sx_offset, incx, jni_sy + _sy_offset, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sdsdot (JNIEnv * env, jobject calling_obj, jint n, jfloat sb, jfloatArray sx, jint incx, jfloatArray sy, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
jfloat returnValue = cblas_sdsdot(n, sb, jni_sx, incx, jni_sy, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sdsdot_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloat sb, jfloatArray sx, jint _sx_offset, jint incx, jfloatArray sy, jint _sy_offset, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
jfloat returnValue = cblas_sdsdot(n, sb, jni_sx + _sx_offset, incx, jni_sy + _sy_offset, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
return returnValue;
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sgbmv (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jint kl, jint ku, jfloat alpha, jfloatArray a, jint lda, jfloatArray x, jint incx, jfloat beta, jfloatArray y, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_sgbmv(CblasColMajor, getCblasTrans(jni_trans), m, n, kl, ku, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sgbmv_1offsets (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jint kl, jint ku, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx, jfloat beta, jfloatArray y, jint _y_offset, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_sgbmv(CblasColMajor, getCblasTrans(jni_trans), m, n, kl, ku, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sgemm (JNIEnv * env, jobject calling_obj, jstring transa, jstring transb, jint m, jint n, jint k, jfloat alpha, jfloatArray a, jint lda, jfloatArray b, jint ldb, jfloat beta, jfloatArray c, jint Ldc) {
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_transb = (char *)(*env)->GetStringUTFChars(env, transb, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_sgemm(CblasColMajor, getCblasTrans(jni_transa), getCblasTrans(jni_transb), m, n, k, alpha, jni_a, lda, jni_b, ldb, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, transb, jni_transb);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sgemm_1offsets (JNIEnv * env, jobject calling_obj, jstring transa, jstring transb, jint m, jint n, jint k, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray b, jint _b_offset, jint ldb, jfloat beta, jfloatArray c, jint _c_offset, jint Ldc) {
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_transb = (char *)(*env)->GetStringUTFChars(env, transb, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_sgemm(CblasColMajor, getCblasTrans(jni_transa), getCblasTrans(jni_transb), m, n, k, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, transb, jni_transb);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sgemv (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jfloat alpha, jfloatArray a, jint lda, jfloatArray x, jint incx, jfloat beta, jfloatArray y, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_sgemv(CblasColMajor, getCblasTrans(jni_trans), m, n, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sgemv_1offsets (JNIEnv * env, jobject calling_obj, jstring trans, jint m, jint n, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx, jfloat beta, jfloatArray y, jint _y_offset, jint incy) {
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_sgemv(CblasColMajor, getCblasTrans(jni_trans), m, n, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sger (JNIEnv * env, jobject calling_obj, jint m, jint n, jfloat alpha, jfloatArray x, jint incx, jfloatArray y, jint incy, jfloatArray a, jint lda) {
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
cblas_sger(CblasColMajor, m, n, alpha, jni_x, incx, jni_y, incy, jni_a, lda);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sger_1offsets (JNIEnv * env, jobject calling_obj, jint m, jint n, jfloat alpha, jfloatArray x, jint _x_offset, jint incx, jfloatArray y, jint _y_offset, jint incy, jfloatArray a, jint _a_offset, jint lda) {
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
cblas_sger(CblasColMajor, m, n, alpha, jni_x + _x_offset, incx, jni_y + _y_offset, incy, jni_a + _a_offset, lda);
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_snrm2 (JNIEnv * env, jobject calling_obj, jint n, jfloatArray x, jint incx) {
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat returnValue = cblas_snrm2(n, jni_x, incx);
return returnValue;
}
JNIEXPORT jfloat JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_snrm2_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray x, jint _x_offset, jint incx) {
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat returnValue = cblas_snrm2(n, jni_x + _x_offset, incx);
return returnValue;
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_srot (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint incx, jfloatArray sy, jint incy, jfloat c, jfloat s) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_srot(n, jni_sx, incx, jni_sy, incy, c, s);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_srot_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint _sx_offset, jint incx, jfloatArray sy, jint _sy_offset, jint incy, jfloat c, jfloat s) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_srot(n, jni_sx + _sx_offset, incx, jni_sy + _sy_offset, incy, c, s);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_srotg (JNIEnv * env, jobject calling_obj, jfloatw sa, jfloatw sb, jfloatw c, jfloatw s) {
jclass jni_saClass = (*env)->GetObjectClass(env, sa);
jfieldID jni_saId = (*env)->GetFieldID(env, jni_saClass, "val", "F");
jfloat jni_sa = (*env)->GetFloatField(env, sa, jni_saId);
jclass jni_sbClass = (*env)->GetObjectClass(env, sb);
jfieldID jni_sbId = (*env)->GetFieldID(env, jni_sbClass, "val", "F");
jfloat jni_sb = (*env)->GetFloatField(env, sb, jni_sbId);
jclass jni_cClass = (*env)->GetObjectClass(env, c);
jfieldID jni_cId = (*env)->GetFieldID(env, jni_cClass, "val", "F");
jfloat jni_c = (*env)->GetFloatField(env, c, jni_cId);
jclass jni_sClass = (*env)->GetObjectClass(env, s);
jfieldID jni_sId = (*env)->GetFieldID(env, jni_sClass, "val", "F");
jfloat jni_s = (*env)->GetFloatField(env, s, jni_sId);
cblas_srotg(&jni_sa, &jni_sb, &jni_c, &jni_s);
(*env)->SetFloatField(env, s, jni_sId, jni_s);
(*env)->SetFloatField(env, c, jni_cId, jni_c);
(*env)->SetFloatField(env, sb, jni_sbId, jni_sb);
(*env)->SetFloatField(env, sa, jni_saId, jni_sa);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_srotm (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint incx, jfloatArray sy, jint incy, jfloatArray sparam) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
jfloat * jni_sparam = NULL;
if (sparam != NULL) {
jni_sparam = (*env)->GetPrimitiveArrayCritical(env, sparam, JNI_FALSE);
check_memory(env, jni_sparam);
}
cblas_srotm(n, jni_sx, incx, jni_sy, incy, jni_sparam);
if (sparam != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sparam, jni_sparam, 0);
}
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_srotm_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint _sx_offset, jint incx, jfloatArray sy, jint _sy_offset, jint incy, jfloatArray sparam, jint _sparam_offset) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
jfloat * jni_sparam = NULL;
if (sparam != NULL) {
jni_sparam = (*env)->GetPrimitiveArrayCritical(env, sparam, JNI_FALSE);
check_memory(env, jni_sparam);
}
cblas_srotm(n, jni_sx + _sx_offset, incx, jni_sy + _sy_offset, incy, jni_sparam + _sparam_offset);
if (sparam != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sparam, jni_sparam, 0);
}
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_srotmg (JNIEnv * env, jobject calling_obj, jfloatw sd1, jfloatw sd2, jfloatw sx1, jfloat sy1, jfloatArray sparam) {
jclass jni_sd1Class = (*env)->GetObjectClass(env, sd1);
jfieldID jni_sd1Id = (*env)->GetFieldID(env, jni_sd1Class, "val", "F");
jfloat jni_sd1 = (*env)->GetFloatField(env, sd1, jni_sd1Id);
jclass jni_sd2Class = (*env)->GetObjectClass(env, sd2);
jfieldID jni_sd2Id = (*env)->GetFieldID(env, jni_sd2Class, "val", "F");
jfloat jni_sd2 = (*env)->GetFloatField(env, sd2, jni_sd2Id);
jclass jni_sx1Class = (*env)->GetObjectClass(env, sx1);
jfieldID jni_sx1Id = (*env)->GetFieldID(env, jni_sx1Class, "val", "F");
jfloat jni_sx1 = (*env)->GetFloatField(env, sx1, jni_sx1Id);
jfloat * jni_sparam = NULL;
if (sparam != NULL) {
jni_sparam = (*env)->GetPrimitiveArrayCritical(env, sparam, JNI_FALSE);
check_memory(env, jni_sparam);
}
cblas_srotmg(&jni_sd1, &jni_sd2, &jni_sx1, sy1, jni_sparam);
if (sparam != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sparam, jni_sparam, 0);
}
(*env)->SetFloatField(env, sx1, jni_sx1Id, jni_sx1);
(*env)->SetFloatField(env, sd2, jni_sd2Id, jni_sd2);
(*env)->SetFloatField(env, sd1, jni_sd1Id, jni_sd1);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_srotmg_1offsets (JNIEnv * env, jobject calling_obj, jfloatw sd1, jfloatw sd2, jfloatw sx1, jfloat sy1, jfloatArray sparam, jint _sparam_offset) {
jclass jni_sd1Class = (*env)->GetObjectClass(env, sd1);
jfieldID jni_sd1Id = (*env)->GetFieldID(env, jni_sd1Class, "val", "F");
jfloat jni_sd1 = (*env)->GetFloatField(env, sd1, jni_sd1Id);
jclass jni_sd2Class = (*env)->GetObjectClass(env, sd2);
jfieldID jni_sd2Id = (*env)->GetFieldID(env, jni_sd2Class, "val", "F");
jfloat jni_sd2 = (*env)->GetFloatField(env, sd2, jni_sd2Id);
jclass jni_sx1Class = (*env)->GetObjectClass(env, sx1);
jfieldID jni_sx1Id = (*env)->GetFieldID(env, jni_sx1Class, "val", "F");
jfloat jni_sx1 = (*env)->GetFloatField(env, sx1, jni_sx1Id);
jfloat * jni_sparam = NULL;
if (sparam != NULL) {
jni_sparam = (*env)->GetPrimitiveArrayCritical(env, sparam, JNI_FALSE);
check_memory(env, jni_sparam);
}
cblas_srotmg(&jni_sd1, &jni_sd2, &jni_sx1, sy1, jni_sparam + _sparam_offset);
if (sparam != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sparam, jni_sparam, 0);
}
(*env)->SetFloatField(env, sx1, jni_sx1Id, jni_sx1);
(*env)->SetFloatField(env, sd2, jni_sd2Id, jni_sd2);
(*env)->SetFloatField(env, sd1, jni_sd1Id, jni_sd1);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssbmv (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jint k, jfloat alpha, jfloatArray a, jint lda, jfloatArray x, jint incx, jfloat beta, jfloatArray y, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_ssbmv(CblasColMajor, getCblasUpLo(jni_uplo), n, k, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssbmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jint k, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx, jfloat beta, jfloatArray y, jint _y_offset, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_ssbmv(CblasColMajor, getCblasUpLo(jni_uplo), n, k, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sscal (JNIEnv * env, jobject calling_obj, jint n, jfloat sa, jfloatArray sx, jint incx) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
cblas_sscal(n, sa, jni_sx, incx);
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sscal_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloat sa, jfloatArray sx, jint _sx_offset, jint incx) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
cblas_sscal(n, sa, jni_sx + _sx_offset, incx);
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sspmv (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray ap, jfloatArray x, jint incx, jfloat beta, jfloatArray y, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_sspmv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_ap, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sspmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray ap, jint _ap_offset, jfloatArray x, jint _x_offset, jint incx, jfloat beta, jfloatArray y, jint _y_offset, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_sspmv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_ap + _ap_offset, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sspr (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint incx, jfloatArray ap) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
cblas_sspr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_ap);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sspr_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint _x_offset, jint incx, jfloatArray ap, jint _ap_offset) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
cblas_sspr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_ap + _ap_offset);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sspr2 (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint incx, jfloatArray y, jint incy, jfloatArray ap) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
cblas_sspr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_y, incy, jni_ap);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sspr2_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint _x_offset, jint incx, jfloatArray y, jint _y_offset, jint incy, jfloatArray ap, jint _ap_offset) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
cblas_sspr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_y + _y_offset, incy, jni_ap + _ap_offset);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sswap (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint incx, jfloatArray sy, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_sswap(n, jni_sx, incx, jni_sy, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_sswap_1offsets (JNIEnv * env, jobject calling_obj, jint n, jfloatArray sx, jint _sx_offset, jint incx, jfloatArray sy, jint _sy_offset, jint incy) {
jfloat * jni_sx = NULL;
if (sx != NULL) {
jni_sx = (*env)->GetPrimitiveArrayCritical(env, sx, JNI_FALSE);
check_memory(env, jni_sx);
}
jfloat * jni_sy = NULL;
if (sy != NULL) {
jni_sy = (*env)->GetPrimitiveArrayCritical(env, sy, JNI_FALSE);
check_memory(env, jni_sy);
}
cblas_sswap(n, jni_sx + _sx_offset, incx, jni_sy + _sy_offset, incy);
if (sy != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sy, jni_sy, 0);
}
if (sx != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, sx, jni_sx, 0);
}
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssymm (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jint m, jint n, jfloat alpha, jfloatArray a, jint lda, jfloatArray b, jint ldb, jfloat beta, jfloatArray c, jint Ldc) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_ssymm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), m, n, alpha, jni_a, lda, jni_b, ldb, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssymm_1offsets (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jint m, jint n, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray b, jint _b_offset, jint ldb, jfloat beta, jfloatArray c, jint _c_offset, jint Ldc) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_ssymm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), m, n, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssymv (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray a, jint lda, jfloatArray x, jint incx, jfloat beta, jfloatArray y, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_ssymv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_a, lda, jni_x, incx, beta, jni_y, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssymv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx, jfloat beta, jfloatArray y, jint _y_offset, jint incy) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
cblas_ssymv(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_a + _a_offset, lda, jni_x + _x_offset, incx, beta, jni_y + _y_offset, incy);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyr (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint incx, jfloatArray a, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
cblas_ssyr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_a, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyr_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint _x_offset, jint incx, jfloatArray a, jint _a_offset, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
cblas_ssyr(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_a + _a_offset, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyr2 (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint incx, jfloatArray y, jint incy, jfloatArray a, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
cblas_ssyr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x, incx, jni_y, incy, jni_a, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyr2_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jint n, jfloat alpha, jfloatArray x, jint _x_offset, jint incx, jfloatArray y, jint _y_offset, jint incy, jfloatArray a, jint _a_offset, jint lda) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
jfloat * jni_y = NULL;
if (y != NULL) {
jni_y = (*env)->GetPrimitiveArrayCritical(env, y, JNI_FALSE);
check_memory(env, jni_y);
}
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
cblas_ssyr2(CblasColMajor, getCblasUpLo(jni_uplo), n, alpha, jni_x + _x_offset, incx, jni_y + _y_offset, incy, jni_a + _a_offset, lda);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyr2k (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jfloat alpha, jfloatArray a, jint lda, jfloatArray b, jint ldb, jfloat beta, jfloatArray c, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_ssyr2k(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a, lda, jni_b, ldb, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyr2k_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray b, jint _b_offset, jint ldb, jfloat beta, jfloatArray c, jint _c_offset, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_ssyr2k(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyrk (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jfloat alpha, jfloatArray a, jint lda, jfloat beta, jfloatArray c, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_ssyrk(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a, lda, beta, jni_c, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_ssyrk_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jint n, jint k, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloat beta, jfloatArray c, jint _c_offset, jint Ldc) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_c = NULL;
if (c != NULL) {
jni_c = (*env)->GetPrimitiveArrayCritical(env, c, JNI_FALSE);
check_memory(env, jni_c);
}
cblas_ssyrk(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), n, k, alpha, jni_a + _a_offset, lda, beta, jni_c + _c_offset, Ldc);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stbmv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jfloatArray a, jint lda, jfloatArray x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stbmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stbmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stbmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stbsv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jfloatArray a, jint lda, jfloatArray x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stbsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stbsv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jint k, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stbsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, k, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stpmv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray ap, jfloatArray x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stpmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stpmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray ap, jint _ap_offset, jfloatArray x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stpmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap + _ap_offset, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stpsv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray ap, jfloatArray x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stpsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_stpsv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray ap, jint _ap_offset, jfloatArray x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_ap = NULL;
if (ap != NULL) {
jni_ap = (*env)->GetPrimitiveArrayCritical(env, ap, JNI_FALSE);
check_memory(env, jni_ap);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_stpsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_ap + _ap_offset, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strmm (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jfloat alpha, jfloatArray a, jint lda, jfloatArray b, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
cblas_strmm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a, lda, jni_b, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strmm_1offsets (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray b, jint _b_offset, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
cblas_strmm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strmv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray a, jint lda, jfloatArray x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_strmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strmv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_strmv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strsm (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jfloat alpha, jfloatArray a, jint lda, jfloatArray b, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
cblas_strsm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a, lda, jni_b, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strsm_1offsets (JNIEnv * env, jobject calling_obj, jstring side, jstring uplo, jstring transa, jstring diag, jint m, jint n, jfloat alpha, jfloatArray a, jint _a_offset, jint lda, jfloatArray b, jint _b_offset, jint ldb) {
char * jni_side = (char *)(*env)->GetStringUTFChars(env, side, JNI_FALSE);
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_transa = (char *)(*env)->GetStringUTFChars(env, transa, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_b = NULL;
if (b != NULL) {
jni_b = (*env)->GetPrimitiveArrayCritical(env, b, JNI_FALSE);
check_memory(env, jni_b);
}
cblas_strsm(CblasColMajor, getCblasSide(jni_side), getCblasUpLo(jni_uplo), getCblasTrans(jni_transa), getCblasDiag(jni_diag), m, n, alpha, jni_a + _a_offset, lda, jni_b + _b_offset, ldb);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, transa, jni_transa);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
(*env)->ReleaseStringUTFChars(env, side, jni_side);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strsv (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray a, jint lda, jfloatArray x, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_strsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a, lda, jni_x, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
JNIEXPORT void JNICALL Java_org_apache_ignite_ml_math_NativeBlasOffHeap_strsv_1offsets (JNIEnv * env, jobject calling_obj, jstring uplo, jstring trans, jstring diag, jint n, jfloatArray a, jint _a_offset, jint lda, jfloatArray x, jint _x_offset, jint incx) {
char * jni_uplo = (char *)(*env)->GetStringUTFChars(env, uplo, JNI_FALSE);
char * jni_trans = (char *)(*env)->GetStringUTFChars(env, trans, JNI_FALSE);
char * jni_diag = (char *)(*env)->GetStringUTFChars(env, diag, JNI_FALSE);
jfloat * jni_a = NULL;
if (a != NULL) {
jni_a = (*env)->GetPrimitiveArrayCritical(env, a, JNI_FALSE);
check_memory(env, jni_a);
}
jfloat * jni_x = NULL;
if (x != NULL) {
jni_x = (*env)->GetPrimitiveArrayCritical(env, x, JNI_FALSE);
check_memory(env, jni_x);
}
cblas_strsv(CblasColMajor, getCblasUpLo(jni_uplo), getCblasTrans(jni_trans), getCblasDiag(jni_diag), n, jni_a + _a_offset, lda, jni_x + _x_offset, incx);
(*env)->ReleaseStringUTFChars(env, diag, jni_diag);
(*env)->ReleaseStringUTFChars(env, trans, jni_trans);
(*env)->ReleaseStringUTFChars(env, uplo, jni_uplo);
}
| {
"alphanum_fraction": 0.7155536252,
"avg_line_length": 52.4831516353,
"ext": "c",
"hexsha": "ddc707e0e2a541e8a85a9cf9c84049f0f31842ae",
"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": "7eff6a97e13f6d7a1fb2f790f0aa26950dc39b54",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "oignatenko2/ignite-5535-1",
"max_forks_repo_path": "modules/ml/src/main/c/org_apache_ignite_ml_math_NativeBlasOffHeap.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7eff6a97e13f6d7a1fb2f790f0aa26950dc39b54",
"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": "oignatenko2/ignite-5535-1",
"max_issues_repo_path": "modules/ml/src/main/c/org_apache_ignite_ml_math_NativeBlasOffHeap.c",
"max_line_length": 330,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7eff6a97e13f6d7a1fb2f790f0aa26950dc39b54",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "oignatenko2/ignite-5535-1",
"max_stars_repo_path": "modules/ml/src/main/c/org_apache_ignite_ml_math_NativeBlasOffHeap.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 34656,
"size": 105911
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include "timer.h"
void integral_recur (int nmin, int nmax, double vals[]);
void integral_gen (int nmin, int nmax, double vals[]);
double ff (double x, void *params);
int adjust_rep_count (int count, double time, double tmin, double tmax);
double ff (double x, void *params)
{
double n = *(double *) params;
double f = exp (-x) * pow (x, n);
return f;
}
void integral_recur (int nmin, int nmax, double vals[])
{
int i;
vals[nmax] = 0.;
for (i = nmax - 1; i >= nmin; i--)
{
vals[i] = vals[i + 1] / (i + 1) + 1. / ((i + 1) * M_E);
}
}
void integral_gen (int nmin, int nmax, double vals[])
{
int i;
double result, error;
double a = 0., b = 1.;
double abserr = 1.e-9, relerr = 1.e-9;
double n;
size_t np = 1000;
gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);
gsl_function F;
F.function = &ff;
for (i = nmax; i >= nmin; i--)
{
n = (double) i;
F.params = &n;
gsl_integration_qag (&F, a, b, abserr, relerr, np, GSL_INTEG_GAUSS15,
w, &result, &error);
vals[i] = result;
}
gsl_integration_workspace_free (w);
}
#define N 100
int main (void)
{
int i;
double integral1[N + 1], integral2[N + 1];
int nmax = N;
int nmin = 10;
integral_recur (nmin, nmax, integral1);
integral_gen (nmin, nmax, integral2);
for (i = nmin; i <= nmax; i++)
{
printf ("%5d % 14.6f % 14.6f %g\n", i, integral1[i],
integral2[i], fabs (integral1[i] - integral2[i]));
}
double time, time1, time2, tmin = 1., tmax = 2.;
int count = 1000;
do
{
timer_start ();
for (i = 0; i < count; i++)
{
integral_recur (nmin, nmax, integral1);
}
time = timer_stop ();
time1 = time / count;
printf ("Recur: %10.2f usec %10.6f sec %10d\n", time1 * 1.e6, time,
count);
/*
* adjust count such that cpu time is between
* tmin and tmax
*/
count = adjust_rep_count (count, time, tmin, tmax);
}
while ((time > tmax) || (time < tmin));
count = 1000;
do
{
timer_start ();
for (i = 0; i < count; i++)
{
integral_gen (nmin, nmax, integral2);
}
time = timer_stop ();
time2 = time / count;
printf ("Integ: %10.2f usec %10.6f sec %10d\n", time1 * 1.e6, time,
count);
/*
* adjust count such that cpu time is between
* tmin and tmax
*/
count = adjust_rep_count (count, time, tmin, tmax);
}
while ((time > tmax) || (time < tmin));
printf ("Speedup: %.2f\n", time2 / time1);
return 0;
}
| {
"alphanum_fraction": 0.522614841,
"avg_line_length": 21.7692307692,
"ext": "c",
"hexsha": "5452be17b35a0a77f91c5ca536862b2a0b8eadae",
"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": "ea1028946c812057d792cbb83ee7a29a14f9d57c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "matthewignal/hw07",
"max_forks_repo_path": "recur.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ea1028946c812057d792cbb83ee7a29a14f9d57c",
"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": "matthewignal/hw07",
"max_issues_repo_path": "recur.c",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ea1028946c812057d792cbb83ee7a29a14f9d57c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "matthewignal/hw07",
"max_stars_repo_path": "recur.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 890,
"size": 2830
} |
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multilarge_nlinear.h>
#include <gsl/gsl_spblas.h>
#include <gsl/gsl_spmatrix.h>
/* parameters for functions */
struct model_params
{
double alpha;
gsl_spmatrix *J;
};
/* penalty function */
int
penalty_f (const gsl_vector * x, void *params, gsl_vector * f)
{
struct model_params *par = (struct model_params *) params;
const double sqrt_alpha = sqrt(par->alpha);
const size_t p = x->size;
size_t i;
double sum = 0.0;
for (i = 0; i < p; ++i)
{
double xi = gsl_vector_get(x, i);
gsl_vector_set(f, i, sqrt_alpha*(xi - 1.0));
sum += xi * xi;
}
gsl_vector_set(f, p, sum - 0.25);
return GSL_SUCCESS;
}
int
penalty_df (CBLAS_TRANSPOSE_t TransJ, const gsl_vector * x,
const gsl_vector * u, void * params, gsl_vector * v,
gsl_matrix * JTJ)
{
struct model_params *par = (struct model_params *) params;
const size_t p = x->size;
size_t j;
/* store 2*x in last row of J */
for (j = 0; j < p; ++j)
{
double xj = gsl_vector_get(x, j);
gsl_spmatrix_set(par->J, p, j, 2.0 * xj);
}
/* compute v = op(J) u */
if (v)
gsl_spblas_dgemv(TransJ, 1.0, par->J, u, 0.0, v);
if (JTJ)
{
gsl_vector_view diag = gsl_matrix_diagonal(JTJ);
/* compute J^T J = [ alpha*I_p + 4 x x^T ] */
gsl_matrix_set_zero(JTJ);
/* store 4 x x^T in lower half of JTJ */
gsl_blas_dsyr(CblasLower, 4.0, x, JTJ);
/* add alpha to diag(JTJ) */
gsl_vector_add_constant(&diag.vector, par->alpha);
}
return GSL_SUCCESS;
}
int
penalty_fvv (const gsl_vector * x, const gsl_vector * v,
void *params, gsl_vector * fvv)
{
const size_t p = x->size;
double normv = gsl_blas_dnrm2(v);
gsl_vector_set_zero(fvv);
gsl_vector_set(fvv, p, 2.0 * normv * normv);
(void)params; /* avoid unused parameter warning */
return GSL_SUCCESS;
}
void
solve_system(const gsl_vector *x0, gsl_multilarge_nlinear_fdf *fdf,
gsl_multilarge_nlinear_parameters *params)
{
const gsl_multilarge_nlinear_type *T = gsl_multilarge_nlinear_trust;
const size_t max_iter = 200;
const double xtol = 1.0e-8;
const double gtol = 1.0e-8;
const double ftol = 1.0e-8;
const size_t n = fdf->n;
const size_t p = fdf->p;
gsl_multilarge_nlinear_workspace *work =
gsl_multilarge_nlinear_alloc(T, params, n, p);
gsl_vector * f = gsl_multilarge_nlinear_residual(work);
gsl_vector * x = gsl_multilarge_nlinear_position(work);
int info;
double chisq0, chisq, rcond, xsq;
struct timeval tv0, tv1;
gettimeofday(&tv0, NULL);
/* initialize solver */
gsl_multilarge_nlinear_init(x0, fdf, work);
/* store initial cost */
gsl_blas_ddot(f, f, &chisq0);
/* iterate until convergence */
gsl_multilarge_nlinear_driver(max_iter, xtol, gtol, ftol,
NULL, NULL, &info, work);
gettimeofday(&tv1, NULL);
/* store final cost */
gsl_blas_ddot(f, f, &chisq);
/* compute final ||x||^2 */
gsl_blas_ddot(x, x, &xsq);
/* store cond(J(x)) */
gsl_multilarge_nlinear_rcond(&rcond, work);
/* print summary */
fprintf(stderr, "%-25s %-5zu %-4zu %-5zu %-6zu %-4zu %-10.4e %-10.4e %-7.2f %-11.4e %.2f\n",
gsl_multilarge_nlinear_trs_name(work),
gsl_multilarge_nlinear_niter(work),
fdf->nevalf,
fdf->nevaldfu,
fdf->nevaldf2,
fdf->nevalfvv,
chisq0,
chisq,
1.0 / rcond,
xsq,
(tv1.tv_sec - tv0.tv_sec) + 1.0e-6 * (tv1.tv_usec - tv0.tv_usec));
gsl_multilarge_nlinear_free(work);
}
int
main (void)
{
const size_t p = 2000;
const size_t n = p + 1;
gsl_vector *f = gsl_vector_alloc(n);
gsl_vector *x = gsl_vector_alloc(p);
/* allocate sparse Jacobian matrix with 2*p non-zero elements in triplet format */
gsl_spmatrix *J = gsl_spmatrix_alloc_nzmax(n, p, 2 * p, GSL_SPMATRIX_TRIPLET);
gsl_multilarge_nlinear_fdf fdf;
gsl_multilarge_nlinear_parameters fdf_params =
gsl_multilarge_nlinear_default_parameters();
struct model_params params;
size_t i;
params.alpha = 1.0e-5;
params.J = J;
/* define function to be minimized */
fdf.f = penalty_f;
fdf.df = penalty_df;
fdf.fvv = penalty_fvv;
fdf.n = n;
fdf.p = p;
fdf.params = ¶ms;
for (i = 0; i < p; ++i)
{
/* starting point */
gsl_vector_set(x, i, i + 1.0);
/* store sqrt(alpha)*I_p in upper p-by-p block of J */
gsl_spmatrix_set(J, i, i, sqrt(params.alpha));
}
fprintf(stderr, "%-25s %-4s %-4s %-5s %-6s %-4s %-10s %-10s %-7s %-11s %-10s\n",
"Method", "NITER", "NFEV", "NJUEV", "NJTJEV", "NAEV", "Init Cost",
"Final cost", "cond(J)", "Final |x|^2", "Time (s)");
fdf_params.scale = gsl_multilarge_nlinear_scale_levenberg;
fdf_params.trs = gsl_multilarge_nlinear_trs_lm;
solve_system(x, &fdf, &fdf_params);
fdf_params.trs = gsl_multilarge_nlinear_trs_lmaccel;
solve_system(x, &fdf, &fdf_params);
fdf_params.trs = gsl_multilarge_nlinear_trs_dogleg;
solve_system(x, &fdf, &fdf_params);
fdf_params.trs = gsl_multilarge_nlinear_trs_ddogleg;
solve_system(x, &fdf, &fdf_params);
fdf_params.trs = gsl_multilarge_nlinear_trs_subspace2D;
solve_system(x, &fdf, &fdf_params);
fdf_params.trs = gsl_multilarge_nlinear_trs_cgst;
solve_system(x, &fdf, &fdf_params);
gsl_vector_free(f);
gsl_vector_free(x);
gsl_spmatrix_free(J);
return 0;
}
| {
"alphanum_fraction": 0.6441530447,
"avg_line_length": 25.3045454545,
"ext": "c",
"hexsha": "558c72f25d5488c8c4d4897c70ba9e7b93ad7d0a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/nlfit4.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/nlfit4.c",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/nlfit4.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": 1825,
"size": 5567
} |
/// @file Error.h
/// @author Braxton Salyer <braxtonsalyer@gmail.com>
/// @brief Basic high-level types for communicating recoverable errors
/// @version 0.1
/// @date 2021-11-03
///
/// 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/BasicTypes.h>
#include <Hyperion/HyperionDef.h>
#include <Hyperion/Ignore.h>
#include <Hyperion/Memory.h>
#include <Hyperion/error/SystemDomain.h>
#include <cstring>
#include <gsl/gsl>
#include <memory>
#include <string>
#include <system_error>
#include <type_traits>
/// @defgroup error Error
/// The Error module provides various error-handling facilities and types for
/// communicating and handling recoverable errors and for aborting on
/// irrecoverable errors in a communicable way
/// @headerfile "Hyperion/Error.h"
namespace hyperion::error {
using namespace std::literals::string_literals;
/// @brief Basic interface for recoverable errors. Error types may provide
/// additional functionality beyond this, but this much is required.
/// @ingroup error
/// @headerfile "Hyperion/Error.h"
IGNORE_WEAK_VTABLES_START
class [[nodiscard]] ErrorBase {
public:
constexpr ErrorBase() noexcept = default;
constexpr ErrorBase(const ErrorBase&) noexcept = default;
constexpr ErrorBase(ErrorBase&&) noexcept = default;
constexpr virtual ~ErrorBase() noexcept = default;
/// @brief Returns the value of the associated error code as an `i64`
/// @return The value of the associated error code
/// @ingroup error
[[nodiscard]] virtual constexpr auto value() const noexcept -> i64 = 0;
/// @brief Returns the message associated with the error as a `std::string`
/// @return The message associated with the error
/// @ingroup error
[[nodiscard]] virtual auto message() const noexcept -> std::string = 0;
/// @brief Converts this error into a `std::string`
/// @return This error as a `std::string`
/// @ingroup error
[[nodiscard]] virtual auto to_string() const noexcept -> std::string = 0;
constexpr auto operator=(const ErrorBase&) noexcept -> ErrorBase& = default;
constexpr auto operator=(ErrorBase&&) noexcept -> ErrorBase& = default;
};
IGNORE_WEAK_VTABLES_STOP
// class [[nodiscard]] AnyError;
/// @brief General purpose type for communicating recoverable errors.
///
/// Wraps an `error::ErrorCode<Domain>` in a type-safe manner.
/// Usually makes up the `E` variant of a `Result<T, E>`
///
/// @tparam Domain - The `StatusCodeDomain` associated with the this error
/// @ingroup error
template<StatusCodeDomain Domain = SystemDomain>
class [[nodiscard]] Error final : public ErrorBase {
public:
/// @brief The type used to represent the error (an enum, integer error code,
/// etc)
/// @ingroup error
using value_type = typename ErrorCode<Domain>::value_type;
friend class AnyError;
/// @brief Constructs a default `Error` with an error code representing an
/// unknown error
/// @ingroup error
constexpr Error() noexcept {
if constexpr(StatusCodeEnum<value_type>) {
m_error_code = make_error_code(static_cast<value_type>(-1));
}
else {
m_error_code = make_error_code<Domain>(static_cast<value_type>(-1));
}
}
/// @brief Constructs an `Error` from the given `ErrorCode<Domain>`
///
/// @param code - The error code
/// @ingroup error
constexpr Error(const ErrorCode<Domain>& code) noexcept // NOLINT
: m_error_code(code) {
}
/// @brief Constructs an `Error` from the given `ErrorCode<Domain>`
///
/// @param code - The error code
/// @ingroup error
constexpr Error(ErrorCode<Domain>&& code) noexcept // NOLINT
: m_error_code(std::move(code)) {
}
/// @brief Constructs an `Error` from the given error code
///
/// @param code - The error code
/// @ingroup error
constexpr Error(const value_type& code) noexcept // NOLINT
requires(!StatusCodeEnum<value_type>)
: m_error_code(make_error_code<Domain>(code)) {
}
/// @brief Constructs an `Error` from the given error code
///
/// @param code - The error code
/// @ingroup error
constexpr Error(const value_type& code) noexcept // NOLINT
requires StatusCodeEnum<value_type> : m_error_code(make_error_code(code)) {
}
/// @brief Copy-constructs an `Error`
/// @ingroup error
constexpr Error(const Error& error) = default;
/// @brief Move-constructs an `Error`
/// @ingroup error
constexpr Error(Error&& error) noexcept = default;
/// @brief Destroys this `Error`
/// @ingroup error
constexpr ~Error() noexcept final = default;
/// @brief Returns the `i64` value of the error code associated with this
/// `Error`
///
/// @return The associated error code as an `i64`
/// @ingroup error
[[nodiscard]] auto value() const noexcept -> i64 final {
return m_error_code.value();
}
/// @brief Returns the `ErrorCode` associated with this `Error`
///
/// @return The associated `ErrorCode`
/// @ingroup error
[[nodiscard]] auto code() const noexcept -> const ErrorCode<Domain>& {
return m_error_code;
}
/// @brief Returns the error message associated with this `Error`
///
/// @return The error message
/// @ingroup error
[[nodiscard]] inline auto message() const noexcept -> std::string final {
if constexpr(concepts::Same<error_code_message_type, std::string>) {
return m_error_code.message();
}
else {
return std::string(m_error_code.message());
}
}
/// @brief Returns the error message associated with this `Error`, as a cstring
///
/// @return The error message
/// @ingroup error
[[nodiscard]] auto message_as_cstr() const noexcept -> const char* {
return m_error_code.message().c_str();
}
/// @brief Gets the `std::string` representation of this `Error`
///
/// @return this `Error` formatted as a `std::string`
/// @ingroup error
[[nodiscard]] auto to_string() const noexcept -> std::string final {
return fmt::format("Error: {}", m_error_code.message());
}
/// @brief Converts this `Error` into its underlying `ErrorCode<Domain>`
/// @ingroup error
constexpr operator ErrorCode<Domain>() const noexcept { // NOLINT
return m_error_code;
}
/// @brief Converts this `Error` into its underlying `value_type`
/// @ingroup error
constexpr operator value_type() const noexcept { // NOLINT
return static_cast<value_type>(m_error_code);
}
/// @brief Equality comparison operator with another `Error` from a possibly different
/// `StatusCodeDomain`
/// @tparam Domain2 - The `StatusCodeDomain` of `error`
/// @ingroup error
template<StatusCodeDomain Domain2>
constexpr auto operator==(const Error<Domain2>& error) const noexcept -> bool {
return m_error_code == error.m_error_code;
}
/// @brief Inequality comparison operator with another `Error` from a possibly different
/// `StatusCodeDomain`
/// @tparam Domain2 - The `StatusCodeDomain` of `error`
/// @ingroup error
template<StatusCodeDomain Domain2>
constexpr auto operator!=(const Error<Domain2>& error) const noexcept -> bool {
return m_error_code != error.m_error_code;
}
/// @brief Equality comparison operator with an `ErrorCode` from a possibly different
/// `StatusCodeDomain`
/// @tparam Domain2 - The `StatusCodeDomain` of `code`
/// @ingroup error
template<StatusCodeDomain Domain2>
constexpr auto operator==(const ErrorCode<Domain2>& code) const noexcept -> bool {
return m_error_code == code;
}
/// @brief Inequality comparison operator with an `ErrorCode` from a possibly different
/// `StatusCodeDomain`
/// @tparam Domain2 - The `StatusCodeDomain` of `code`
/// @ingroup error
template<StatusCodeDomain Domain2>
constexpr auto operator!=(const ErrorCode<Domain2>& code) const noexcept -> bool {
return m_error_code != code;
}
/// @brief Copy-assigns the given `error` to this `Error`
/// @ingroup error
constexpr auto operator=(const Error& error) noexcept -> Error& = default;
/// @brief Move-assigns the given `error` to this `Error`
/// @ingroup error
constexpr auto operator=(Error&& error) noexcept -> Error& = default;
/// @brief Copy-assigns the given `ErrorCode<Domain>` to this `Error`
/// @ingroup error
constexpr auto operator=(const ErrorCode<Domain>& code) noexcept -> Error& {
m_error_code = code;
return *this;
}
/// @brief Move-assigns the given `ErrorCode<Domain>` to this `Error`
/// @ingroup error
constexpr auto operator=(ErrorCode<Domain>&& code) noexcept -> Error& {
m_error_code = std::move(code);
return *this;
}
/// @brief Provides `std::tuple`-like structured binding support.
///
/// `Index == 0` returns the error code value.
/// `Index == 1` returns the error message.
/// Other `Index` values ar invalid
///
/// @return The error code value (`Index == 0`), or the error message (`Index
/// == 1`)
/// @ingroup error
template<usize Index>
auto get() const&& noexcept {
return get_impl<Index>(*this);
}
/// @brief Provides `std::tuple`-like structured binding support.
///
/// `Index == 0` returns the error code value.
/// `Index == 1` returns the error message.
/// Other `Index` values ar invalid
///
/// @return The error code value (`Index == 0`), or the error message (`Index
/// == 1`)
/// @ingroup error
template<usize Index>
auto get() const& noexcept {
return get_impl<Index>(*this);
}
private:
template<usize Index, typename T>
auto get_impl(T&& t) const noexcept {
static_assert(Index < 2, "Index out of bounds for hyperion::error::Error::get");
if constexpr(Index == 0) {
return std::forward<T>(t).m_error_code.value();
}
else {
return std::forward<T>(t).m_error_code.message();
}
}
/// error code
ErrorCode<Domain> m_error_code;
using error_code_message_type = decltype(m_error_code.message());
};
} // namespace hyperion::error
/// @brief Specialize `std::tuple_size` for `error::Error<Domain>`
/// @ingroup error
template<hyperion::error::StatusCodeDomain Domain>
struct std::tuple_size<hyperion::error::Error<Domain>> {
static constexpr hyperion::usize value = 2;
};
/// @brief Specialize `std::tuple_element<0, T>` for `error::Error<Domain>`
/// @ingroup error
template<hyperion::error::StatusCodeDomain Domain>
struct std::tuple_element<0, hyperion::error::Error<Domain>> {
using type = typename hyperion::error::Error<Domain>::value_type;
};
/// @brief Specialize `std::tuple_element<1, T>` for `error::Error<Domain>`
/// @ingroup error
template<hyperion::error::StatusCodeDomain Domain>
struct std::tuple_element<1, hyperion::error::Error<Domain>> {
using type = std::string;
};
namespace hyperion::error {
/// @brief `SystemError` is an error representing the default platform/OS level
/// errors (eg POSIX or WIN32 error codes)
///
/// In practice, this will usually be an alias for one of `PosixError`,
/// `Win32Error`, or `NTError`, depending on platform and configuration
/// @ingroup error
using SystemError = Error<SystemDomain>;
/// @brief `PosixError` is an error representing a platform's implementation of
/// POSIX error codes (it includes support for additional platform specific
/// codes not required by POSIX)
/// @ingroup error
using PosixError = Error<PosixDomain>;
/// @brief `GenericError` represents the strict set of POSIX required error
/// codes.
///
/// In Hyperion's error system, `GenericError` fills a role similar to a
/// `std::error_code` of `std::generic_category`
/// @ingroup error
using GenericError = Error<GenericDomain>;
#if HYPERION_PLATFORM_WINDOWS
/// @brief `Win32Error` is an error representing the Win32 error codes
/// @ingroup error
using Win32Error = Error<Win32Domain>;
/// @brief `NTError` is an error representing the Windows NT error codes
/// @ingroup error
using NTError = Error<NTDomain>;
#endif // HYPERION_PLATFORM_WINDOWS
/// @brief Concept specifying the requirements of a type necessary to be
/// guaranteed compatible with Hyperion's error system.
///
/// Users are encouraged to fulfill this concept for their own error types,
/// particularly when using them with Hyperion's higher-level error-handling
/// facilities like `Result<T, E>`
/// @ingroup error
template<typename E>
concept ErrorType = std::derived_from<E, ErrorBase>;
/// @brief Concept useful for shorthanding `!ErrorType<E>`
/// @note Removes the need for extra parentheses and enables cleaner
/// auto-formatting (eg `SomeConcept &&(!ErrorType<E>)` vs `SomeConcept &&
/// NotErrorType<E>`)
/// @ingroup error
template<typename E>
concept NotErrorType = !ErrorType<E>;
/// @brief `AnyError` represents a type erased error from any
/// `error::StatusCodeDomain`
/// @ingroup error
class [[nodiscard]] AnyError final : public ErrorBase {
public:
/// @brief Constructs an `AnyError` as an unknown error
/// @ingroup error
HYPERION_CONSTEXPR_STRINGS AnyError() noexcept = default;
/// @brief Constructs an `AnyError` from the given `error::ErrorCode<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error
///
/// @param code - The error code this `AnyError` should represent
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS AnyError(const ErrorCode<Domain>& code) noexcept // NOLINT
: m_error_code(code.value()), m_message(code.message()) {
}
/// @brief Constructs an `AnyError` from the given `error::ErrorCode<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error
///
/// @param code - The error code this `AnyError` should represent
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS AnyError(ErrorCode<Domain>&& code) noexcept // NOLINT
: m_error_code(code.value()), m_message(code.message()) {
}
/// @brief Constructs an `AnyError` from the given `error::Error<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error
///
/// @param error - The error this `AnyError` should represent
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS AnyError(const Error<Domain>& error) noexcept // NOLINT
: m_error_code(error.code().value()), m_message(error.message()) {
}
/// @brief Constructs an `AnyError` from the given `error::Error<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error
///
/// @param error - The error this `AnyError` should represent
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS AnyError(Error<Domain>&& error) noexcept // NOLINT
: m_error_code(error.code().value()), m_message(error.message()) {
}
/// @brief Copy-constructs an `AnyError` from the given one
/// @ingroup error
HYPERION_CONSTEXPR_STRINGS AnyError(const AnyError&) noexcept = default;
/// @brief Move-constructs an `AnyError` from the given one
/// @ingroup error
HYPERION_CONSTEXPR_STRINGS AnyError(AnyError&&) noexcept = default;
/// @brief Destroys this `AnyError`
/// @ingroup error
HYPERION_CONSTEXPR_STRINGS ~AnyError() noexcept final = default;
/// @brief Returns the `i64` value corresponding with the error code this
/// represents
/// @return The error code as an `i64`
/// @ingroup error
[[nodiscard]] constexpr auto value() const noexcept -> i64 final {
return m_error_code;
}
/// @brief Returns the error message associated with the error code this
/// represents
/// @return The error code message
/// @ingroup error
[[nodiscard]] auto message() const noexcept -> std::string final {
return m_message;
}
/// @brief Returns the string representation of this `AnyError`
/// @return this `AnyError` as a `std::string`
/// @ingroup error
[[nodiscard]] HYPERION_CONSTEXPR_STRINGS auto
to_string() const noexcept -> std::string final {
return "Error: "s + m_message + "\n"s;
}
/// @brief Copy-assigns the given `AnyError` to this one
/// @ingroup error
HYPERION_CONSTEXPR_STRINGS auto operator=(const AnyError&) noexcept -> AnyError& = default;
/// @brief Move-assigns the given `AnyError` to this one
/// @ingroup error
HYPERION_CONSTEXPR_STRINGS auto operator=(AnyError&&) noexcept -> AnyError& = default;
/// @brief Copy-assigns this `AnyError` with the given
/// `error::ErrorCode<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error code
///
/// @param code - The error code to assign to this
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS auto
operator=(const ErrorCode<Domain>& code) noexcept -> AnyError& {
m_error_code = code.value();
m_message = code.message();
return *this;
}
/// @brief Move-assigns this `AnyError` with the given
/// `error::ErrorCode<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error code
///
/// @param code - The error code to assign to this
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS auto operator=(ErrorCode<Domain>&& code) noexcept -> AnyError& {
m_error_code = code.value();
m_message = code.message();
return *this;
}
/// @brief Copy-assigns this `AnyError` with the given `error::Error<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error
///
/// @param error - The error to assign to this
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS auto
operator=(const Error<Domain>& error) noexcept -> AnyError& {
m_error_code = error.value();
m_message = error.message();
return *this;
}
/// @brief Move-assigns this `AnyError` with the given `error::Error<Domain>`
///
/// @tparam Domain - The `error::StatusCodeDomain` of the error
///
/// @param error - The error to assign to this
/// @ingroup error
template<StatusCodeDomain Domain>
HYPERION_CONSTEXPR_STRINGS auto operator=(Error<Domain>&& error) noexcept -> AnyError& {
m_error_code = error.value();
m_message = error.message();
return *this;
}
/// @brief Provides `std::tuple`-like structured binding support.
///
/// `Index == 0` returns the error code value.
/// `Index == 1` returns the error message.
/// Other `Index` values ar invalid
///
/// @return The error code value (`Index == 0`), or the error message (`Index
/// == 1`)
/// @ingroup error
template<usize Index>
auto get() const&& noexcept {
return get_impl<Index>(*this);
}
/// @brief Provides `std::tuple`-like structured binding support.
///
/// `Index == 0` returns the error code value.
/// `Index == 1` returns the error message.
/// Other `Index` values ar invalid
///
/// @return The error code value (`Index == 0`), or the error message (`Index
/// == 1`)
/// @ingroup error
template<usize Index>
auto get() const& noexcept {
return get_impl<Index>(*this);
}
private:
template<usize Index, typename T>
auto get_impl(T&& t) const noexcept {
static_assert(Index < 2, "Index out of bounds for hyperion::error::AnyError::get");
if constexpr(Index == 0) {
return std::forward<T>(t).m_error_code;
}
else {
return std::forward<T>(t).m_message;
}
}
i64 m_error_code = -1;
std::string m_message;
};
} // namespace hyperion::error
/// @brief Specialize `std::tuple_size` for `error::AnyError`
/// @ingroup error
template<>
struct std::tuple_size<hyperion::error::AnyError> {
static constexpr hyperion::usize value = 2;
};
/// @brief Specialize `std::tuple_element<0, T>` for `error::AnyError`
/// @ingroup error
template<>
struct std::tuple_element<0, hyperion::error::AnyError> {
using type = hyperion::i64;
};
/// @brief Specialize `std::tuple_element<1, T>` for `error::AnyError`
/// @ingroup error
template<>
struct std::tuple_element<1, hyperion::error::AnyError> {
using type = std::string;
};
| {
"alphanum_fraction": 0.6919273557,
"avg_line_length": 32.917057903,
"ext": "h",
"hexsha": "fce65b7998e6640713833dc7d48761411181d892",
"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.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.h",
"max_line_length": 93,
"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.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5577,
"size": 21034
} |
#pragma once
#include <cstdint>
#include <gsl/gsl>
#include "utils.h"
#include "halley/text/halleystring.h"
struct XXH64_state_s;
typedef struct XXH64_state_s XXH64_state_t;
namespace Halley {
class Hash {
public:
static uint64_t hash(const Bytes& bytes);
static uint64_t hash(gsl::span<const gsl::byte> bytes);
template <typename T>
static uint64_t hashValue(const T& v)
{
return hash(gsl::as_bytes(gsl::span<const T>(&v, 1)));
}
static uint32_t compressTo32(uint64_t value);
class Hasher
{
public:
Hasher();
~Hasher();
void feed(const String& string)
{
feedBytes(gsl::as_bytes(gsl::span<const char>(string.c_str(), string.length())));
}
template<typename T>
void feed(const T& data)
{
feedBytes(gsl::as_bytes(gsl::span<const T>(&data, 1)));
}
void feedBytes(gsl::span<const gsl::byte> bytes);
[[nodiscard]] uint64_t digest();
private:
bool ready;
XXH64_state_t* data;
};
};
}
| {
"alphanum_fraction": 0.6407960199,
"avg_line_length": 18.9622641509,
"ext": "h",
"hexsha": "3b08669d4d1bc01064a996ef570cd66a7894a8e9",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "code-disaster/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/utils/hash.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "code-disaster/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/utils/hash.h",
"max_line_length": 85,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "code-disaster/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/utils/hash.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 293,
"size": 1005
} |
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
const gsl_interp_type *types[7];
const gsl_interp2d_type *types2d[2];
void init(void)
{
types[0] = gsl_interp_linear;
types[1] = gsl_interp_polynomial;
types[2] = gsl_interp_cspline;
types[3] = gsl_interp_cspline_periodic;
types[4] = gsl_interp_akima;
types[5] = gsl_interp_akima_periodic;
types[6] = gsl_interp_steffen;
types2d[0] = gsl_interp2d_bilinear;
types2d[1] = gsl_interp2d_bicubic;
}
/* 1D */
gsl_interp *mgsl_interp_alloc(int type, size_t size)
{
if(types[0] == NULL) init();
return gsl_interp_alloc(types[type], size);
}
unsigned int mgsl_interp_type_min_size(int type)
{
if(types[0] == NULL) init();
return gsl_interp_type_min_size(types[type]);
}
gsl_spline *mgsl_spline_alloc(int type, size_t size)
{
if(types[0] == NULL) init();
return gsl_spline_alloc(types[type], size);
}
/* 2D */
gsl_interp2d *mgsl_interp2d_alloc(int type, size_t xsize, size_t ysize)
{
if(types[0] == NULL) init();
return gsl_interp2d_alloc(types2d[type], xsize, ysize);
}
unsigned int mgsl_interp2d_type_min_size(int type)
{
if(types[0] == NULL) init();
return gsl_interp2d_type_min_size(types2d[type]);
}
gsl_spline2d *mgsl_spline2d_alloc(int type, size_t xsize, size_t ysize)
{
if(types[0] == NULL) init();
return gsl_spline2d_alloc(types2d[type], xsize, ysize);
}
| {
"alphanum_fraction": 0.7197496523,
"avg_line_length": 24.3728813559,
"ext": "c",
"hexsha": "56e90900cdc1528fd23ae8563fea18e6a6f51d47",
"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": "c38f16cde531bd811e8d01cb5e3f6b7a5582587c",
"max_forks_repo_licenses": [
"Artistic-2.0"
],
"max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Interpolation",
"max_forks_repo_path": "src/interpolation.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c38f16cde531bd811e8d01cb5e3f6b7a5582587c",
"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-Interpolation",
"max_issues_repo_path": "src/interpolation.c",
"max_line_length": 71,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c38f16cde531bd811e8d01cb5e3f6b7a5582587c",
"max_stars_repo_licenses": [
"Artistic-2.0"
],
"max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Interpolation",
"max_stars_repo_path": "src/interpolation.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 468,
"size": 1438
} |
#ifdef __LOCAL_SIMULATION_ENV__
#include "model.h"
#endif
//############# START DYNAMIC_CLAMP CODE ##################
/*!
Dynamic clamp model for a current generated by multiple clusters of cooperative ion channels:
I_{coop} = -g*N_{open}*(V-E)
where the number of open channels N_{open} changes due to the stochastic opening and closing events guided by rates
which depend on the external voltage and the number of open channels among the surrounding channels in a cluster i.e.
alpha(V, o) and beta(V,o)
\par Input/Output
- V: Measured membrane potential in mV
- \f$ I_{inj} \f$ : Injected current in nA
\par Parameter
- g : conductance of a single channel in nS
- E : reversal potential of the ionic current in mV
- cN: number of clusters of cooperative ion channels without units
- cS: number of cooperative ion channels in a cluster without units
- J : pairwise interaction strength in mV
- tau : peak reaction time scale of a single channel in ms
*/
#ifndef __KERNEL__
#include <gsl/gsl_rng.h>
#include <time.h>
#endif
#define POWER_2_EXP 28
unsigned long next = 1;
const int RAND_PERIOD = 1 << POWER_2_EXP;
// numerical recipes in c, p. 276, not recommended for usage as the period is 30k and other issues
float evil_rand(void) {
next = next * 1103515245 + 1234;
return (float) ((unsigned int) (next / 65536) % 32768) / 32768;
}
#if defined (__KERNEL__) || defined (DYNCLAMPMODEL)
/*! Name, by which this module is known inside Linux: */
const char *modelName;
/*! Variables used by the model */
#define MAX_CLUSTER_SIZE 8
#define DEFAULT_CLUSTER_NUMBER 100
#define DEFAULT_CLUSTER_INIT 0
int cluster_states[MAX_CLUSTER_SIZE + 1] = {DEFAULT_CLUSTER_NUMBER, 0, 0, 0, 0, 0, 0, 0, 0};
int cluster_size = MAX_CLUSTER_SIZE;
int cluster_number = DEFAULT_CLUSTER_NUMBER;
int cluster_init = DEFAULT_CLUSTER_INIT;
/*! The period length of the realtime periodic task in seconds. */
float loopInterval;
/*! One over the period length of the realtime periodic task in Hertz. */
float loopRate;
/*! Analog input that is read from the DAQ board. */
#define INPUT_N 1
/*! The \a inputNames are used to match the \a input variables with
analog input traces in Relacs. */
const char *inputNames[INPUT_N] = {"V-1"};
const char *inputUnits[INPUT_N] = {"mV"};
/*! The \a inputChannels are set automatically. */
int inputChannels[INPUT_N];
/*! \a input holds the current value that was read in from the DAQ board. */
float input[INPUT_N] = {0.0};
/*! Analog output that is written to the DAQ board. */
#define OUTPUT_N 1
const char *outputNames[OUTPUT_N] = {"Current-1"};
const char *outputUnits[OUTPUT_N] = {"nA"};
int outputChannels[OUTPUT_N];
float output[OUTPUT_N] = {0.0};
/*! Parameter that are provided by the model and can be read out. */
#define PARAMINPUT_N 2
const char *paramInputNames[PARAMINPUT_N] = {"Cooperative-Cluster-Current", "Open-Channels"};
const char *paramInputUnits[PARAMINPUT_N] = {"nA", ""};
float paramInput[PARAMINPUT_N] = {0.0, 0.0};
/*! Parameter that are read by the model and are written to the model. */
#define PARAMOUTPUT_N 8
const char *paramOutputNames[PARAMOUTPUT_N] = {"g", "E", "J", "tau", "Cluster size", "Number of clusters", "Vhalf", "Initial state"};
const char *paramOutputUnits[PARAMOUTPUT_N] = {"pS", "mV", "mV", "ms", "", "", "mV", ""};
float paramOutput[PARAMOUTPUT_N] = {0.0, 0.0, 0.0, 15, MAX_CLUSTER_SIZE, DEFAULT_CLUSTER_NUMBER, -1.0, 0};
/*! Functions used by the model */
double opening_rate(double voltage) {
double oR;
float vhalf = paramOutput[6];
if (paramOutput[3] != 0.0) {
oR = cosh((voltage - vhalf) / 30.0) * (1.0 + tanh((voltage - vhalf) / 15.0)) / paramOutput[3] / 2.0;
} else {
oR = 0;
}
return oR;
}
double closing_rate(double voltage) {
double cR;
float vhalf = paramOutput[6];
if (paramOutput[3] != 0.0) {
cR = cosh((voltage - vhalf) / 30.0) * (1.0 - tanh((voltage - vhalf) / 15.0)) / paramOutput[3] / 2.0;
} else {
cR = 0;
}
return cR;
}
double get_rand(void) {
double u;
#ifdef ENABLE_LOOKUPTABLES
// random number from lookuptable:
next = (next >= (RAND_PERIOD - 1)) ? 0 : (next + 1);
u = (double) lookupx[0][next];
#else
u = (double) evil_rand();
#endif
return u;
}
int get_number_of_open_channels(void) {
int sum = 0;
int size = cluster_size;
int i;
for (i = 0; i <= size; i++) {
sum += cluster_states[i] * i;
}
return sum;
}
/*
brute_force on cluster state basis: rates based, does not need any internal state
- needs 2*cluster_size random numbers per time step
- problem: as multiple reactions might take place in a single time step an opening and a closing reaction might take
place simultaneously leaving behind an inconsistent state e.g. [0 1 0] -> [1 -1 1]
*/
void evolve_cluster_states(void) {
double rand;
double dt = loopInterval * 1000;
double voltage = input[0];
int cS = cluster_size;
float cluster_interaction = paramOutput[2];
//helpers
int i;
double opening_rates[cS];
double closing_rates[cS];
// calculate opening and closing rates
for (i = 0; i < cS; i++) {
// opening_rate[i]: rate from (i channels open) to (i+1 channels open)
opening_rates[i] = cluster_states[i] * (cS - i) * opening_rate(voltage + i * cluster_interaction);
// closing_rate[i]: rate from (i+1 channels open) to (i channels open)
closing_rates[i] = cluster_states[i + 1] * (i + 1) * closing_rate(voltage + i * cluster_interaction);
}
// update cluster states
for (i = 0; i < cS; i++) {
//opening reaction from (i channels open) to (i+1 channels open)
rand = get_rand();
if (rand <= opening_rates[i] * dt) {
//DEBUG_MSG("C -> Likelihood %.16f, Threshold:%.16f\n", opening_rates[i]*dt, rand);
//DEBUG_MSG("Opening %d:%d\n", i, cluster_states[i]);
if (cluster_states[i] != 0) {
cluster_states[i] -= 1;
cluster_states[i + 1] += 1;
}
}
// closing reaction from (i+1 channels open) to (i channels open)
rand = get_rand();
if (rand <= closing_rates[i] * dt) {
//DEBUG_MSG("C -> Likelihood %.16f, Threshold:%.16f\n", closing_rates[i]*dt, rand);
//DEBUG_MSG("Closing %d:%d\n", i+1,cluster_states[i+1]);
if (cluster_states[i + 1] != 0) {
cluster_states[i + 1] -= 1;
cluster_states[i] += 1;
}
}
}
}
void populate_state(int state_idx) {
int idx;
cluster_states[state_idx] = cluster_number;
for (idx = 0; idx <= cluster_size; idx++) {
if(idx != state_idx) {
cluster_states[idx] = 0;
}
}
}
void process_cluster_property_changes(void) {
int cluster_size_idx = 4;
int cluster_number_idx = 5;
int cluster_init_idx = 7;
if (cluster_size != (int) paramOutput[cluster_size_idx] ||
cluster_number != (int) paramOutput[cluster_number_idx] || cluster_init != (int) paramOutput[cluster_init_idx]) {
if (paramOutput[cluster_size_idx] > MAX_CLUSTER_SIZE) {
cluster_size = MAX_CLUSTER_SIZE;
} else {
cluster_size = (paramOutput[cluster_size_idx] >= 1) ? (int) paramOutput[cluster_size_idx] : 1;
};
if (paramOutput[cluster_init_idx] > MAX_CLUSTER_SIZE) {
cluster_init = MAX_CLUSTER_SIZE;
} else {
cluster_init = (paramOutput[cluster_init_idx] >= 0) ? (int) paramOutput[cluster_init_idx] : 0;
};
cluster_number = (paramOutput[cluster_number_idx] > 0) ? (int) paramOutput[cluster_number_idx] : 0;
populate_state(cluster_init);
}
}
/*! Functions provided by the model for the dynamic clamp module */
void initModel(void) {
modelName = "cooperative_clusters";
process_cluster_property_changes();
}
#define CONDUCTANCE_IDX 0
#define MEMBRANE_POTENTIAL_IDX 0
#define REVERSAL_POTENTIAL_IDX 1
void computeModel(void) {
int number_of_open_channels = 0;
process_cluster_property_changes();
evolve_cluster_states();
// number of open channels
number_of_open_channels = get_number_of_open_channels();
paramInput[0] = (float) (-0.000001 * paramOutput[CONDUCTANCE_IDX] * number_of_open_channels *
(input[MEMBRANE_POTENTIAL_IDX] - paramOutput[REVERSAL_POTENTIAL_IDX]));
// current flowing through cooperative clusters :
paramInput[1] = number_of_open_channels;
// total injected current:
output[0] = paramInput[0];
}
#endif
#ifndef __KERNEL__
#ifdef ENABLE_LOOKUPTABLES
/*! This function is called from DynClampAnalogOutput in user
space/C++ context and can be used to create some lookuptables for
nonlinear functions to be used by computeModel(). The implementation of this
functions has to allocate an \a x and \a y array of floats of a sensible size \a n.
\param[in] \a k : the index for the lookup table to be generated.
\param[out] \a n : the size of the lookup table (the number of elements in \a x and \a y).
\param[out] \a x : the x-values.
\param[out] \a y : the corresponding y-values.
\return: 0 if a lookuptable was generated, -1 otherwise.
*/
gsl_rng *rng_state;
unsigned long get_seed_from_clock();
void initialize_random_number_generator() {
const gsl_rng_type *T;
unsigned long int seed = get_seed_from_clock();
gsl_rng_env_setup();
T = gsl_rng_default;
rng_state = gsl_rng_alloc(T);
gsl_rng_set(rng_state, seed);
}
unsigned long get_seed_from_clock() {
clock_t current;
current = clock();
return (unsigned long int) current;
}
int generateLookupTable(int k, float **x, float **y, int *n) {
initialize_random_number_generator();
if (k == 0) {
/* Lookup-table for the Random number generator: */
const int nn = RAND_PERIOD;
*n = nn;
#ifdef __LOCAL_SIMULATION_ENV__
*x = (float *) malloc(nn * sizeof(float));
#else
*x = new float[nn];
#endif
for (int j = 0; j < nn; j++) {
float xx = gsl_rng_uniform(rng_state);
(*x)[j] = xx;
}
return 0;
}
return -1;
}
#endif
#endif
//############# END DYNAMIC_CLAMP CODE ##################
#ifdef __LOCAL_SIMULATION_ENV__
void setVoltage(float voltage) {
input[0] = voltage;
}
void setConductance(float conductance) {
paramOutput[0] = conductance;
}
void setReversalPotential(float reversalPotential) {
paramOutput[1] = reversalPotential;
}
void setClusterInteraction(float clusterInteraction) {
paramOutput[2] = clusterInteraction;
}
void setTimeConstant(float timeConstant) {
paramOutput[3] = timeConstant;
}
void setClusterSize(float clusterSize) {
paramOutput[4] = clusterSize;
}
void setClusterNumber(float clusterNumber) {
paramOutput[5] = clusterNumber;
}
void setVhalf(float vhalf) {
paramOutput[6] = vhalf;
}
void setClusterInit(float clusterInit) {
paramOutput[7] = clusterInit;
}
void setLoopInterval(float interval) {
loopInterval = interval;
}
float getCurrentOutput(void) {
return output[0];
}
int getClusterSize(void) {
return cluster_size;
}
int getClusterState(int i) {
return cluster_states[i];
}
#endif
| {
"alphanum_fraction": 0.658853706,
"avg_line_length": 29.2144702842,
"ext": "c",
"hexsha": "9514abc613b2b0fac8c4a67bffb14c0f2d3f8f11",
"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": "a05557002ba36d1be32c5dd5aa601842091b3e09",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "elifesciences-publications/49974-dynamic_clamp_model",
"max_forks_repo_path": "src/dynclamp_models/model.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a05557002ba36d1be32c5dd5aa601842091b3e09",
"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": "elifesciences-publications/49974-dynamic_clamp_model",
"max_issues_repo_path": "src/dynclamp_models/model.c",
"max_line_length": 133,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a05557002ba36d1be32c5dd5aa601842091b3e09",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "elifesciences-publications/49974-dynamic_clamp_model",
"max_stars_repo_path": "src/dynclamp_models/model.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3030,
"size": 11306
} |
#pragma once
#include "Buffer.h"
#include "Enum.h"
#include "Error.h"
#include "detail/Defaulted.h"
#include <boost/hana/define_struct.hpp>
#include <gsl/span>
#include <json.hpp>
namespace gltfpp {
inline namespace v1 {
BETTER_ENUM(BufferViewTarget, int32_t, ARRAY_BUFFER = 34962, ELEMENT_ARRAY_BUFFER = 34963)
struct BufferView {
BufferView()
: byteStride{0} {
}
BOOST_HANA_DEFINE_STRUCT(BufferView,
(option<BufferViewTarget>, target),
(option<std::string>, name),
(defaulted<uint8_t>, byteStride),
(option<nlohmann::json>, extensions),
(option<nlohmann::json>, extras));
gsl::span<byte const> span;
Buffer const *buffer;
};
auto parse(BufferView &) noexcept;
} // namespace v1
} // namespace gltfpp
| {
"alphanum_fraction": 0.5950226244,
"avg_line_length": 27.625,
"ext": "h",
"hexsha": "8a4b8516451bb719037f95d352e79e3d1be9781c",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2019-09-18T07:04:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-06-01T14:38:11.000Z",
"max_forks_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "mmha/gltfpp",
"max_forks_repo_path": "gltfpp/include/BufferView.h",
"max_issues_count": 9,
"max_issues_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d",
"max_issues_repo_issues_event_max_datetime": "2017-06-02T18:05:45.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-06-02T16:53:11.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "mmha/gltfpp",
"max_issues_repo_path": "gltfpp/include/BufferView.h",
"max_line_length": 92,
"max_stars_count": 25,
"max_stars_repo_head_hexsha": "9e9e2fe5f8da374838a5b6b03d97963bed87956d",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "mmha/gltfpp",
"max_stars_repo_path": "gltfpp/include/BufferView.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-06T04:23:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-03T04:09:50.000Z",
"num_tokens": 214,
"size": 884
} |
/**
* @file batchv_zdotu_sub.c
*
* Part of API test for Batched BLAS routines.
*
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date
*
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include "bblas.h"
#define COMPLEX
void batchv_zdotu_sub(
const int *n,
BBLAS_Complex64_t const * const * x,
const int *incx,
BBLAS_Complex64_t const * const * y,
const int *incy,
BBLAS_Complex64_t *dotu,
const int batch_count, int* info)
{
/* Local variables */
int batch_iter = 0;
char func_name[15] = "batchv_zdotu";
/*initialize the result */
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
dotu[batch_iter] = (BBLAS_Complex64_t)0.0;
}
/* Check input arguments */
if (batch_count < 0)
{
xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);
}
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
if (n[batch_iter] < 0)
{
xerbla_batch(func_name, BBLAS_ERR_N, batch_iter);
info[batch_iter] = BBLAS_ERR_N;
}
if (incx[batch_iter] < 1)
{
xerbla_batch(func_name, BBLAS_ERR_INCX, batch_iter);
info[batch_iter] = BBLAS_ERR_INCX;
}
if (incy[batch_iter] < 1)
{
xerbla_batch(func_name, BBLAS_ERR_INCY, batch_iter);
info[batch_iter] = BBLAS_ERR_INCY;
}
cblas_zdotu_sub(
n[batch_iter],
(void *)x[batch_iter],
incx[batch_iter],
(void *)y[batch_iter],
incy[batch_iter],
&dotu[batch_iter]);
/* Successful */
info[batch_iter] = BBLAS_SUCCESS;
} /* End fixed size for loop */
}
#undef COMPLEX
| {
"alphanum_fraction": 0.6266747868,
"avg_line_length": 21.8933333333,
"ext": "c",
"hexsha": "43b310e7fdb1facbd21a9c1796d77da26d73277e",
"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": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "sdrelton/bblas_api_test",
"max_forks_repo_path": "src/batchv_zdotu.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"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": "sdrelton/bblas_api_test",
"max_issues_repo_path": "src/batchv_zdotu.c",
"max_line_length": 61,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "mawussi/BBLAS-group",
"max_stars_repo_path": "src/batchv_zdotu.c",
"max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z",
"num_tokens": 528,
"size": 1642
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C code for EOBNRv2HM reduced order model (non-spinning version).
* See CQG 31 195010, 2014, arXiv:1402.4146 for details on the reduced order method.
* See arXiv:1106.1021 for the EOBNRv2HM model.
*
* Borrows from the SEOBNR ROM LAL code written by Michael Puerrer and John Veitch.
*
* Put the untared data in the directory designated by the environment variable ROM_DATA_PATH.
*
* Parameter ranges:
* q = 1-12 (almost)
* No spin
* Mtot >= 10Msun for fstart=8Hz
*
*/
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#include "EOBNRv2HMROMstruct.h"
#include "EOBNRv2HMROM.h"
/*************************************************/
/********* Some general definitions **************/
/* Number and list of modes to generate - to be modified ultimately to allow for a selection of the desired mode(s) */
/* By convention the first mode of the list is used to set phiRef */
/* nbmodemax = 5 has been defined in the header */
const int listmode[nbmodemax][2] = { {2,2}, {2,1}, {3,3}, {4,4}, {5,5} };
/* Maximal mass ratio covered by the model - q=12 (almost) for now */
static const double q_max = 11.9894197212;
/* Minimal geometric frequency covered by the model - f=8Hz for M=10Msol for now */
static const double Mf_ROM_min = 0.0003940393857519091;
/* Maximal geometric frequency covered by the model - Mf=0.285 for the 55 mode - used as default */
static const double Mf_ROM_max = 0.285;
/* Total mass (in units of solar mass) used to generate the ROM - used to restore the correct amplitude (global factor M) when coming back to physical units */
static const double M_ROM = 10.;
/* Define the number of points in frequency used by the SVD, identical for all modes */
static const int nbfreq = 300;
/* Define the number of training waveforms used by the SVD, identical for all modes */
static const int nbwf = 301;
/******************************************************************/
/********* Definitions for the persistent structures **************/
/* SEOBNR-ROM structures are generalized to lists */
ListmodesEOBNRHMROMdata* __EOBNRv2HMROM_data_init = NULL; /* for initialization only */
ListmodesEOBNRHMROMdata** const __EOBNRv2HMROM_data = &__EOBNRv2HMROM_data_init;
ListmodesEOBNRHMROMdata_interp* __EOBNRv2HMROM_interp_init = NULL; /* for initialization only */
ListmodesEOBNRHMROMdata_interp** const __EOBNRv2HMROM_interp = &__EOBNRv2HMROM_interp_init;
/* Tag indicating whether the data has been loaded and interpolated */
int __EOBNRv2HMROM_setup = FAILURE; /* To be set to SUCCESS after initialization*/
/********************* Miscellaneous ********************/
/* Return the closest higher power of 2 */
static size_t NextPow2(const size_t n) {
return 1 << (size_t) ceil(log2(n));
}
/* Arbitrary tuned q-dependent functions by which the frequencies for the 44 and 55 modes have been multiplied (to put the ringdowns at the same Mf). The frequencies stored in the data for the 44 and 55 modes are the rescaled ones, not the original ones. */
static double Scaling44(const double q) {
return 1.-1./4.*exp(-(q-1.)/5.);
}
static double Scaling55(const double q) {
return 1.-1./3.*exp(-(q-1.)/5.);
}
/* Function evaluating eta as a function of q */
static double EtaOfq(const double q) {
return q/(1.+q)/(1.+q);
}
/* Function evaluating delta m/m = (m1-m2)/(m1+m2) as a function of q */
static double DeltaOfq(const double q) {
return( (q-1.)/(q+1.) );
}
/* Fit of the frequency of the 22 mode at the peak amplitude - from table III in the EOBNRv2HM paper, Pan&al 1106 */
static double omega22peakOfq(const double q) {
double eta = EtaOfq(q);
return 0.2733 + 0.2316*eta + 0.4463*eta*eta;
}
/* Amplitude factors scaled out for each mode; this does not include the global amplitude factor scaled out from all modes. */
static double ModeAmpFactor(const int l, const int m, const double q) {
double eta = EtaOfq(q);
if( l==2 && m==2 ) return(sqrt(eta));
else if( l==2 && m==1 ) return( sqrt(eta)*DeltaOfq(q) );
else if( l==3 && m==3 ) return( sqrt(eta)*DeltaOfq(q) );
else if( l==4 && m==4 ) return( sqrt(Scaling44(q))*sqrt(eta)*(1.-3.*eta) );
else if( l==5 && m==5 ) return( pow(Scaling55(q), 1./6)*sqrt(eta)*DeltaOfq(q)*(1.-2.*eta) );
else {
fprintf(stderr, "Unknown mode (%d,%d) for the amplitude factor.\n", l, m);
return(FAILURE);
}
}
/********************* Functions to initialize and cleanup contents of data structures ********************/
void EOBNRHMROMdata_Init(EOBNRHMROMdata **data) {
if(!data) exit(1);
/* Create storage for structures */
if(!*data) *data=malloc(sizeof(EOBNRHMROMdata));
else
{
EOBNRHMROMdata_Cleanup(*data);
}
gsl_set_error_handler(&Err_Handler);
(*data)->q = gsl_vector_alloc(nbwf);
(*data)->freq = gsl_vector_alloc(nbfreq);
(*data)->Camp = gsl_matrix_alloc(nk_amp,nbwf);
(*data)->Cphi = gsl_matrix_alloc(nk_phi,nbwf);
(*data)->Bamp = gsl_matrix_alloc(nbfreq,nk_amp);
(*data)->Bphi = gsl_matrix_alloc(nbfreq,nk_phi);
(*data)->shifttime = gsl_vector_alloc(nbwf);
(*data)->shiftphase = gsl_vector_alloc(nbwf);
}
void EOBNRHMROMdata_interp_Init(EOBNRHMROMdata_interp **data_interp) {
if(!data_interp) exit(1);
/* Create storage for structures */
if(!*data_interp) *data_interp=malloc(sizeof(EOBNRHMROMdata_interp));
else
{
EOBNRHMROMdata_interp_Cleanup(*data_interp);
}
(*data_interp)->Camp_interp = NULL;
(*data_interp)->Cphi_interp = NULL;
(*data_interp)->shifttime_interp = NULL;
(*data_interp)->shiftphase_interp = NULL;
}
void EOBNRHMROMdata_coeff_Init(EOBNRHMROMdata_coeff **data_coeff) {
if(!data_coeff) exit(1);
/* Create storage for structures */
if(!*data_coeff) *data_coeff=malloc(sizeof(EOBNRHMROMdata_coeff));
else
{
EOBNRHMROMdata_coeff_Cleanup(*data_coeff);
}
gsl_set_error_handler(&Err_Handler);
(*data_coeff)->Camp_coeff = gsl_vector_alloc(nk_amp);
(*data_coeff)->Cphi_coeff = gsl_vector_alloc(nk_phi);
(*data_coeff)->shifttime_coeff = malloc(sizeof(double));
(*data_coeff)->shiftphase_coeff = malloc(sizeof(double));
}
void EOBNRHMROMdata_Cleanup(EOBNRHMROMdata *data /* data to destroy */) {
if(data->q) gsl_vector_free(data->q);
if(data->freq) gsl_vector_free(data->freq);
if(data->Camp) gsl_matrix_free(data->Camp);
if(data->Cphi) gsl_matrix_free(data->Cphi);
if(data->Bamp) gsl_matrix_free(data->Bamp);
if(data->Bphi) gsl_matrix_free(data->Bphi);
if(data->shifttime) gsl_vector_free(data->shifttime);
if(data->shiftphase) gsl_vector_free(data->shiftphase);
free(data);
}
void EOBNRHMROMdata_coeff_Cleanup(EOBNRHMROMdata_coeff *data_coeff) {
if(data_coeff->Camp_coeff) gsl_vector_free(data_coeff->Camp_coeff);
if(data_coeff->Cphi_coeff) gsl_vector_free(data_coeff->Cphi_coeff);
if(data_coeff->shifttime_coeff) free(data_coeff->shifttime_coeff);
if(data_coeff->shiftphase_coeff) free(data_coeff->shiftphase_coeff);
free(data_coeff);
}
void EOBNRHMROMdata_interp_Cleanup(EOBNRHMROMdata_interp *data_interp) {
if(data_interp->Camp_interp) SplineList_Destroy(data_interp->Camp_interp);
if(data_interp->Cphi_interp) SplineList_Destroy(data_interp->Cphi_interp);
if(data_interp->shifttime_interp) SplineList_Destroy(data_interp->shifttime_interp);
if(data_interp->shiftphase_interp) SplineList_Destroy(data_interp->shiftphase_interp);
free(data_interp);
}
/* Read binary ROM data for frequency vectors, coefficients matrices, basis functions matrices, and shiftvectors in time and phase */
int Read_Data_Mode(const char dir[], const int mode[2], EOBNRHMROMdata *data) {
/* Load binary data for amplitude and phase spline coefficients as computed in Mathematica */
int ret = SUCCESS;
char* file_q = malloc(strlen(dir)+64);
char* file_freq = malloc(strlen(dir)+64);
char* file_Camp = malloc(strlen(dir)+64);
char* file_Cphi = malloc(strlen(dir)+64);
char* file_Bamp = malloc(strlen(dir)+64);
char* file_Bphi = malloc(strlen(dir)+64);
char* file_shifttime = malloc(strlen(dir)+64);
char* file_shiftphase = malloc(strlen(dir)+64);
sprintf(file_q, "%s", "EOBNRv2HMROM_q.dat"); /* The q vector is the same for all modes */
sprintf(file_freq, "%s%d%d%s", "EOBNRv2HMROM_freq_", mode[0], mode[1], ".dat");
sprintf(file_Camp, "%s%d%d%s", "EOBNRv2HMROM_Camp_", mode[0], mode[1], ".dat");
sprintf(file_Cphi, "%s%d%d%s", "EOBNRv2HMROM_Cphi_", mode[0], mode[1], ".dat");
sprintf(file_Bamp, "%s%d%d%s", "EOBNRv2HMROM_Bamp_", mode[0], mode[1], ".dat");
sprintf(file_Bphi, "%s%d%d%s", "EOBNRv2HMROM_Bphi_", mode[0], mode[1], ".dat");
sprintf(file_shifttime, "%s%d%d%s", "EOBNRv2HMROM_shifttime_", mode[0], mode[1], ".dat");
sprintf(file_shiftphase, "%s%d%d%s", "EOBNRv2HMROM_shiftphase_", mode[0], mode[1], ".dat");
ret |= Read_Vector(dir, file_q, data->q);
ret |= Read_Vector(dir, file_freq, data->freq);
ret |= Read_Matrix(dir, file_Camp, data->Camp);
ret |= Read_Matrix(dir, file_Cphi, data->Cphi);
ret |= Read_Matrix(dir, file_Bamp, data->Bamp);
ret |= Read_Matrix(dir, file_Bphi, data->Bphi);
ret |= Read_Vector(dir, file_shifttime, data->shifttime);
ret |= Read_Vector(dir, file_shiftphase, data->shiftphase);
free(file_q);
free(file_freq);
free(file_Camp);
free(file_Cphi);
free(file_Bamp);
free(file_Bphi);
free(file_shifttime);
free(file_shiftphase);
return(ret);
}
/* Function interpolating the data in matrix/vector form produces an interpolated data in the form of SplineLists */
int Interpolate_Spline_Data(const EOBNRHMROMdata *data, EOBNRHMROMdata_interp *data_interp) {
gsl_set_error_handler(&Err_Handler);
SplineList* splinelist;
gsl_spline* spline;
gsl_interp_accel* accel;
gsl_vector* matrixline;
gsl_vector* vector;
int j;
/* Interpolating Camp */
splinelist = data_interp->Camp_interp;
for (j = 0; j<nk_amp; j++) {
matrixline = gsl_vector_alloc(nbwf);
gsl_matrix_get_row(matrixline, data->Camp, j);
accel = gsl_interp_accel_alloc();
spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);
gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(matrixline, 0), nbwf);
splinelist = SplineList_AddElementNoCopy(splinelist, spline, accel, j);
gsl_vector_free(matrixline);
}
data_interp->Camp_interp = splinelist;
/* Interpolating Cphi */
splinelist = data_interp->Cphi_interp;
for (j = 0; j<nk_phi; j++) {
matrixline = gsl_vector_alloc(nbwf);
gsl_matrix_get_row(matrixline, data->Cphi, j);
accel = gsl_interp_accel_alloc();
spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);
gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(matrixline, 0), nbwf);
splinelist = SplineList_AddElementNoCopy(splinelist, spline, accel, j);
gsl_vector_free(matrixline);
}
data_interp->Cphi_interp = splinelist;
/* Interpolating shifttime */
splinelist = data_interp->shifttime_interp;
vector = data->shifttime;
accel = gsl_interp_accel_alloc();
spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);
gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(vector, 0), nbwf);
splinelist = SplineList_AddElementNoCopy(NULL, spline, accel, 0); /* This SplineList has only 1 element */
data_interp->shifttime_interp = splinelist;
/* Interpolating shiftphase */
splinelist = data_interp->shiftphase_interp;
vector = data->shiftphase;
accel = gsl_interp_accel_alloc();
spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);
gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(vector, 0), nbwf);
splinelist = SplineList_AddElementNoCopy(NULL, spline, accel, 0); /* This SplineList has only 1 element */
data_interp->shiftphase_interp = splinelist;
return SUCCESS;
}
/* Function taking as input interpolated data in the form of SplineLists
* evaluates for a given q the projection coefficients and shifts in time and phase
*/
int Evaluate_Spline_Data(const double q, const EOBNRHMROMdata_interp* data_interp, EOBNRHMROMdata_coeff* data_coeff){
SplineList* splinelist;
/* Evaluating the vector of projection coefficients for the amplitude */
for (int j=0; j<nk_amp; j++) {
splinelist = SplineList_GetElement(data_interp->Camp_interp, j);
gsl_vector_set(data_coeff->Camp_coeff, j, gsl_spline_eval(splinelist->spline, q, splinelist->accel));
}
/* Evaluating the vector of projection coefficients for the phase */
for (int j=0; j<nk_phi; j++) {
splinelist = SplineList_GetElement(data_interp->Cphi_interp, j);
gsl_vector_set(data_coeff->Cphi_coeff, j, gsl_spline_eval(splinelist->spline, q, splinelist->accel));
}
/* Evaluating the shift in time */
splinelist = SplineList_GetElement(data_interp->shifttime_interp, 0); /* This SplineList has only one element */
*(data_coeff->shifttime_coeff) = gsl_spline_eval(splinelist->spline, q, splinelist->accel);
/* Evaluating the shift in phase */
splinelist = SplineList_GetElement(data_interp->shiftphase_interp, 0); /* This SplineList has only one element */
*(data_coeff->shiftphase_coeff) = gsl_spline_eval(splinelist->spline, q, splinelist->accel);
return SUCCESS;
}
/*
* Core function for computing the ROM waveform.
* Evaluates projection coefficients and shifts in time and phase at desired q.
* Construct 1D splines for amplitude and phase.
* Compute strain waveform from amplitude and phase.
*/
int EOBNRv2HMROMCore(
struct tagListmodesCAmpPhaseFrequencySeries **listhlm,
int nbmode,
double deltatRef,
double phiRef,
double fRef,
double Mtot_sec,
double q,
double distance,
int setphiRefatfRef)
{
int ret = SUCCESS;
int j;
double tpeak22estimate = 0;
/* Check output arrays */
if(!listhlm) exit(1);
if(*listhlm)
{
printf("Error: (*listhlm) is supposed to be NULL, but got %p\n",(*listhlm));
exit(1);
}
/* Check number of modes */
if(nbmode<1 || nbmode>nbmodemax) {
printf("Error: incorrect number of modes: %d", nbmode);
exit(1);
}
/* Check if the data has been set up */
if(__EOBNRv2HMROM_setup) {
printf("Error: the ROM data has not been set up\n");
exit(1);
}
/* Set the global pointers to data */
ListmodesEOBNRHMROMdata* listdata = *__EOBNRv2HMROM_data;
ListmodesEOBNRHMROMdata_interp* listdata_interp = *__EOBNRv2HMROM_interp;
/* Global amplitude prefactor - includes total mass scaling, Fourier scaling, distance scaling, and undoing an additional arbitrary scaling */
double Mtot_msol = Mtot_sec / MTSUN_SI; /* Mtot_msol and M_ROM in units of solar mass */
double amp0 = (Mtot_msol/M_ROM) * Mtot_sec * 1.E-16 * 1.E6 * PC_SI / distance;
/* Highest allowed geometric frequency for the first mode of listmode in the ROM - used for fRef
* by convention, we use the first mode of listmode (presumably the 22) for phiref */
ListmodesEOBNRHMROMdata* listdata_ref = ListmodesEOBNRHMROMdata_GetMode(listdata, listmode[0][0], listmode[0][1]);
EOBNRHMROMdata* data_ref = listdata_ref->data;
double Mf_ROM_max_ref = gsl_vector_get(data_ref->freq, nbfreq-1);
/* Convert to geometric units the reference time and frequency */
double deltatRef_geom = deltatRef / Mtot_sec;
double fRef_geom = fRef * Mtot_sec;
/* Enforce allowed geometric frequency range for fRef */
/* In case the user asks for a reference frequency higher than covered by the ROM, we keep it that way as we will just 0-pad the waveform (and do it anyway for some modes) */
if (fRef_geom > Mf_ROM_max_ref || fRef_geom == 0)
fRef_geom = Mf_ROM_max_ref; /* If fRef > fhigh or 0 we reset fRef to default value of cutoff frequency for the first mode of the list (presumably the 22 mode) */
if (0 < fRef_geom && fRef_geom < Mf_ROM_min) {
//printf("WARNING: Reference frequency Mf_ref=%g is smaller than lowest frequency in ROM Mf=%g. Setting it to the lowest frequency in ROM.\n", fRef_geom, Mf_ROM_min);
fRef_geom = Mf_ROM_min;
}
/* Internal storage for the projection coefficients and shifts in time and phase */
/* Initialized only once, and reused for the different modes */
EOBNRHMROMdata_coeff *data_coeff = NULL;
EOBNRHMROMdata_coeff_Init(&data_coeff);
/* The phase change imposed by phiref, from the phase of the first mode in the list - to be set in the first step of the loop on the modes */
double phase_change_ref = 0;
/* Main loop over the modes */
for(int i=0; i<nbmode; i++ ){
int l = listmode[i][0];
int m = listmode[i][1];
/* Getting the relevant modes in the lists of data */
ListmodesEOBNRHMROMdata* listdata_mode = ListmodesEOBNRHMROMdata_GetMode(listdata, l, m);
ListmodesEOBNRHMROMdata_interp* listdata_interp_mode = ListmodesEOBNRHMROMdata_interp_GetMode(listdata_interp, l, m);
/* Evaluating the projection coefficients and shift in time and phase */
ret |= Evaluate_Spline_Data(q, listdata_interp_mode->data_interp, data_coeff);
/* Evaluating the unnormalized amplitude and unshifted phase vectors for the mode */
/* Notice a change in convention: B matrices are transposed with respect to the B matrices in SEOBNRROM */
/* amp_pts = Bamp . Camp_coeff */
/* phi_pts = Bphi . Cphi_coeff */
gsl_vector* amp_f = gsl_vector_alloc(nbfreq);
gsl_vector* phi_f = gsl_vector_alloc(nbfreq);
//clock_t begblas = clock();
gsl_blas_dgemv(CblasNoTrans, 1.0, listdata_mode->data->Bamp, data_coeff->Camp_coeff, 0.0, amp_f);
gsl_blas_dgemv(CblasNoTrans, 1.0, listdata_mode->data->Bphi, data_coeff->Cphi_coeff, 0.0, phi_f);
//clock_t endblas = clock();
//printf("Mode (%d,%d) Blas time: %g s\n", l, m, (double)(endblas - begblas) / CLOCKS_PER_SEC);
/* The downsampled frequencies for the mode - we undo the rescaling of the frequency for the 44 and 55 modes */
gsl_vector* freq_ds = gsl_vector_alloc(nbfreq);
gsl_vector_memcpy(freq_ds, listdata_mode->data->freq);
if ( l==4 && m==4) gsl_vector_scale( freq_ds, 1./Scaling44(q));
if ( l==5 && m==5) gsl_vector_scale( freq_ds, 1./Scaling55(q));
/* Evaluating the shifts in time and phase - conditional scaling for the 44 and 55 modes */
/* Note: the stored values of 'shifttime' correspond actually to 2pi*Deltat */
SplineList* shifttime_splinelist = listdata_interp_mode->data_interp->shifttime_interp;
SplineList* shiftphase_splinelist = listdata_interp_mode->data_interp->shiftphase_interp;
double twopishifttime;
if( l==4 && m==4) {
twopishifttime = gsl_spline_eval(shifttime_splinelist->spline, q, shifttime_splinelist->accel) * Scaling44(q);
}
else if( l==5 && m==5) {
twopishifttime = gsl_spline_eval(shifttime_splinelist->spline, q, shifttime_splinelist->accel) * Scaling55(q);
}
else {
twopishifttime = gsl_spline_eval(shifttime_splinelist->spline, q, shifttime_splinelist->accel);
}
double shiftphase = gsl_spline_eval(shiftphase_splinelist->spline, q, shiftphase_splinelist->accel);
/* If first mode in the list, assumed to be the 22 mode, set totalshifttime and phase_change_ref */
if( i==0 ) {
if(l==2 && m==2) {
/* Setup 1d cubic spline for the phase of the 22 mode */
gsl_interp_accel* accel_phi22 = gsl_interp_accel_alloc();
gsl_spline* spline_phi22 = gsl_spline_alloc(gsl_interp_cspline, nbfreq);
gsl_spline_init(spline_phi22, gsl_vector_const_ptr(freq_ds,0), gsl_vector_const_ptr(phi_f,0), nbfreq);
/* Compute the shift in time needed to set the peak of the 22 mode roughly at deltatRef */
/* We use the SPA formula tf = -(1/2pi)*dPsi/df to estimate the correspondence between frequency and time */
/* The frequency corresponding to the 22 peak is omega22peak/2pi, with omega22peak taken from the fit to NR in Pan&al 1106 EOBNRv2HM paper */
double f22peak = fmin(omega22peakOfq(q)/(2*PI), Mf_ROM_max_ref); /* We ensure we evaluate the spline within its range */
/* Note : twopishifttime is almost 0 (order 1e-8) by construction for the 22 mode, so it does not intervene here */
tpeak22estimate = -1./(2*PI) * gsl_spline_eval_deriv(spline_phi22, f22peak, accel_phi22);
/* Determine the change in phase (to be propagated to all modes) required to have phi22(fRef) = 2*phiRef */
if(setphiRefatfRef) {
phase_change_ref = 2*phiRef + (gsl_spline_eval(spline_phi22, fRef_geom, accel_phi22) - (twopishifttime - 2*PI*tpeak22estimate + 2*PI*deltatRef_geom) * fRef_geom - shiftphase);
}
else {
phase_change_ref = 2*phiRef;
}
gsl_spline_free(spline_phi22);
gsl_interp_accel_free(accel_phi22);
}
else {
printf("Error: the first mode in listmode must be the 22 mode to set the changes in phase and time \n");
return FAILURE;
}
}
/* Total shift in time, and total change in phase for this mode */
double totaltwopishifttime = twopishifttime - 2*PI*tpeak22estimate + 2*PI*deltatRef_geom;
double constphaseshift = m/2. * phase_change_ref + shiftphase;
//
//printf("deltatRef_geom: %g\n", deltatRef_geom);
//printf("freq_ds 0: %g\n", gsl_vector_get(freq_ds, 0));
//printf("2*PI*deltatRef_geom * gsl_vector_get(freq_ds, 0), phase_change_ref: %g, %g\n", 2*PI*deltatRef_geom * gsl_vector_get(freq_ds, 0), phase_change_ref);
/* Initialize the complex series for the mode */
CAmpPhaseFrequencySeries *modefreqseries = NULL;
int len = (int) freq_ds->size;
CAmpPhaseFrequencySeries_Init(&modefreqseries, len);
/* Mode-dependent complete amplitude prefactor */
double amp_pre = amp0 * ModeAmpFactor( l, m, q);
/* Final result for the mode */
/* Scale and set the amplitudes (amplitudes are real at this stage)*/
gsl_vector_scale(amp_f, amp_pre);
gsl_vector_memcpy(modefreqseries->amp_real, amp_f);
gsl_vector_set_zero(modefreqseries->amp_imag); /* Amplitudes are real at this stage */
/* Add the linear term and the constant (including the shift to phiRef), and set the phases */
gsl_vector_scale(phi_f, -1.); /* Change the sign of the phases: ROM convention Psi=-phase */
gsl_blas_daxpy(totaltwopishifttime, freq_ds, phi_f); /*Beware: here freq_ds must still be in geometric units*/
gsl_vector_add_constant(phi_f, constphaseshift);
gsl_vector_memcpy(modefreqseries->phase, phi_f);
//
//printf("first phi_f: %g\n", gsl_vector_get(phi_f, 0 ));
//printf("last phi_f: %g\n", gsl_vector_get(phi_f, phi_f->size -1 ));
/* Scale (to physical units) and set the frequencies */
gsl_vector_scale(freq_ds, 1./Mtot_sec);
gsl_vector_memcpy(modefreqseries->freq, freq_ds);
/* Append the computed mode to the ListmodesCAmpPhaseFrequencySeries structure */
*listhlm = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listhlm, modefreqseries, l, m);
//
//printf("Mode (%d,%d) generated:\n", l, m);
//for( int j=0; j<len; j++ ){
// printf("%g %g %g %g\n", gsl_vector_get(modefreqseries->freq, j), gsl_vector_get(modefreqseries->amp_real, j), gsl_vector_get(modefreqseries->amp_imag, j), gsl_vector_get(modefreqseries->phase, j));
//}
/* Cleanup for the mode */
gsl_vector_free(freq_ds);
gsl_vector_free(amp_f);
gsl_vector_free(phi_f);
}
/* Cleanup of the coefficients data structure */
EOBNRHMROMdata_coeff_Cleanup(data_coeff);
return(SUCCESS);
}
/* Compute waveform in downsampled frequency-amplitude-phase format */
int SimEOBNRv2HMROM(
struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */
int nbmode, /* Number of modes to generate (starting with the 22) */
double deltatRef, /* Time shift so that the peak of the 22 mode occurs at deltatRef */
double phiRef, /* Phase at reference frequency */
double fRef, /* Reference frequency (Hz); 0 defaults to fLow */
double m1SI, /* Mass of companion 1 (kg) */
double m2SI, /* Mass of companion 2 (kg) */
double distance, /* Distance of source (m) */
int setphiRefatfRef) /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) */
{
/* Get masses in terms of solar mass */
double mass1 = m1SI / MSUN_SI;
double mass2 = m2SI / MSUN_SI;
double Mtot = mass1 + mass2;
double q = fmax(mass1/mass2, mass2/mass1); /* Mass-ratio >1 by convention*/
double Mtot_sec = Mtot * MTSUN_SI; /* Total mass in seconds */
if ( q > q_max ) {
//printf( "Error - %s: q out of range!\nEOBNRv2HMROM is only available for a mass ratio in the range q <= %g.\n", __func__, q_max);
return FAILURE;
}
/* Set up (load and build interpolation) ROM data if not setup already */
//clock_t beg = clock();
EOBNRv2HMROM_Init_DATA();
//clock_t end = clock();
//printf("Initialization time: %g s\n", (double)(end - beg) / CLOCKS_PER_SEC);
//beg = clock();
int retcode = EOBNRv2HMROMCore(listhlm, nbmode, deltatRef, phiRef, fRef, Mtot_sec, q, distance, setphiRefatfRef);
//end = clock();
//printf("ROM evaluation time: %g s\n", (double)(end - beg) / CLOCKS_PER_SEC);
return(retcode);
}
/* Setup EOBNRv2HMROM model using data files installed in $ROM_DATA_PATH */
int EOBNRv2HMROM_Init_DATA(void) {
if (!__EOBNRv2HMROM_setup) return SUCCESS;
int ret=FAILURE;
char *envpath=NULL;
char path[32768];
char *brkt,*word;
envpath=getenv("ROM_DATA_PATH");
if(!envpath) {
printf("Error: the environment variable ROM_DATA_PATH, giving the path to the ROM data, seems undefined\n");
return(FAILURE);
}
strncpy(path,envpath,sizeof(path));
#pragma omp critical
{
for(word=strtok_r(path,":",&brkt); word; word=strtok_r(NULL,":",&brkt))
{
ret = EOBNRv2HMROM_Init(word);
if(ret == SUCCESS) break;
}
if(ret!=SUCCESS) {
printf("Error: unable to find EOBNRv2HMROM data files in $ROM_DATA_PATH\n");
exit(FAILURE);
}
__EOBNRv2HMROM_setup = ret;
}
return(ret);
}
/* Setup EOBNRv2HMROM model using data files installed in dir */
int EOBNRv2HMROM_Init(const char dir[]) {
if(!__EOBNRv2HMROM_setup) {
printf("Error: EOBNRHMROMdata was already set up!");
exit(1);
}
int ret = SUCCESS;
ListmodesEOBNRHMROMdata* listdata = *__EOBNRv2HMROM_data;
ListmodesEOBNRHMROMdata_interp* listdata_interp = *__EOBNRv2HMROM_interp;
for (int j=0; j<nbmodemax; j++) { /* At setup, we initialize all available modes anyway */
EOBNRHMROMdata* data = NULL;
EOBNRHMROMdata_Init(&data);
ret |= Read_Data_Mode( dir, listmode[j], data);
if (!ret) {
listdata = ListmodesEOBNRHMROMdata_AddModeNoCopy( listdata, data, listmode[j][0], listmode[j][1]);
EOBNRHMROMdata_interp* data_interp = NULL;
EOBNRHMROMdata_interp_Init(&data_interp);
ret |= Interpolate_Spline_Data(data, data_interp);
if (!ret) listdata_interp = ListmodesEOBNRHMROMdata_interp_AddModeNoCopy( listdata_interp, data_interp, listmode[j][0], listmode[j][1]);
}
}
__EOBNRv2HMROM_setup = ret;
if (!ret) {
*__EOBNRv2HMROM_data = listdata;
*__EOBNRv2HMROM_interp = listdata_interp;
}
return(ret);
}
/* Non-spinning merger TaylorF2 waveform, copied and condensed from LAL */
/* Used by SimEOBNRv2HMROMExtTF2 to extend the signal to arbitrarily low frequencies */
static void TaylorF2nonspin(
double *amp, /**< FD waveform amplitude (modulus)*/
double *phase, /**< FD waveform phase */
const double *freqs, /**< frequency points at which to evaluate the waveform (Hz) */
const int size, /** number of freq samples */
const double m1_SI, /**< mass of companion 1 (kg) */
const double m2_SI, /**< mass of companion 2 (kg) */
const double distance, /** distance (m) */
const double imatch /**< index at which to match phase;
assumes arrays are preloaded at imatch and imatch+1
with the required result */
)
{
//The meat of this computation is copied from LAL: XLALSimInspiralPNPhasing_F2
//We dont need the spin terms
double m1 = m1_SI / MSUN_SI;
double m2 = m2_SI / MSUN_SI;
double mtot = m1 + m2;
double d = (m1 - m2) / (m1 + m2);
double eta = m1*m2/mtot/mtot;
double m1M = m1/mtot;
double m2M = m2/mtot;
double m_sec = mtot * MTSUN_SI;
double piM = PI * m_sec;
double pfaN = 3.L/(128.L * eta);
/* Non-spin phasing terms - see arXiv:0907.0700, Eq. 3.18 */
double pfav0 = 1.L;
double pfav2 = 5.L*(743.L/84.L + 11.L * eta)/9.L;
double pfav3 = -16.L*PI;
double pfav4 = 5.L*(3058.673L/7.056L + 5429.L/7.L * eta
+ 617.L * eta*eta)/72.L;
double pfav5 = 5.L/9.L * (7729.L/84.L - 13.L * eta) * PI;
double pfalogv5 = 5.L/3.L * (7729.L/84.L - 13.L * eta) * PI;
double pfav6 = (11583.231236531L/4.694215680L
- 640.L/3.L * PI * PI - 6848.L/21.L*GAMMA)
+ eta * (-15737.765635L/3.048192L
+ 2255./12. * PI * PI)
+ eta*eta * 76055.L/1728.L
- eta*eta*eta * 127825.L/1296.L;
pfav6 += (-6848.L/21.L)*log(4.);
double pfalogv6 = -6848.L/21.L;
double pfav7 = PI * ( 77096675.L/254016.L
+ 378515.L/1512.L * eta - 74045.L/756.L * eta*eta);
/* Non-spin 2-2 amplitude terms (Blanchet LRR)*/
double a2 = ( -107 + 55*eta ) / 42.;
double a3 = 2*PI;
double a4 = ( ( 2047.*eta - 7483. ) * eta - 2173. ) / 1512.;
/* Blanchet has more terms, but there should diminishing returns:
expect v^5 ~ 1e-5 and the higher terms are more complicated and, indeed, complex */
//Lead coefficients
//double amp0 = -4. * m1 * m2 / distance * C_SI * MTSUN_SI * MTSUN_SI * sqrt(PI/12.L); //(from LAL)
double amp0B = 2. * m1 * m2 / distance * C_SI * MTSUN_SI * MTSUN_SI * sqrt(16*PI/5.L); //Based on Blanchet-LRR (327)
//Note: amp0B = -4 * sqrt( 3/5) * amp0;
double FTaN = 32.0 * eta*eta / 5.0;
//printf("eta=%g\n",eta);
//Compute raw TaylorF2
int i;
for (i = 0; i < size; i++) {
double f = freqs[i];
double v = cbrt(piM*f);
double logv = log(v);
double v2 = v*v;
double v5 = v2*v2*v;
double v10 = v5*v5;
//printf("taylorf2: f=%g v=%g\n",f,v);
double phasing=0;
phasing = pfav7 * v;
phasing = (phasing + pfav6 + pfalogv6 * logv) * v;
phasing = (phasing + pfav5 + pfalogv5 * logv) * v;
phasing = (phasing + pfav4) * v;
phasing = (phasing + pfav3) * v;
phasing = (phasing + pfav2) * v2;
phasing += 1;
phasing *=pfaN;
double amp22fac;
amp22fac = a4*v;
amp22fac = ( amp22fac + a3 ) * v;
amp22fac = ( amp22fac + a2 ) * v2;
amp22fac += 1.0;
phasing /= v5;
double flux = FTaN * v10;
double dEnergy = -eta * v;
phase[i]=phasing;
//Notes for amplitude: Blanchet at leading order:
/* mf=x^(3/2); fdot=3/2/m x^(1/2) xdot ~ 3/2/m x^(1/2) * (-1/16)*(4x)^5(-eta/5/m) = 96/5*eta/m^2 * x^(11/2) */
/*-flux/dEnergy = 32.0 * eta*eta / 5.0 / eta *v^9 */
/*--> -flux/dEnergy = fdot / (3*v^2) [using x=v^2]*/
//amp[i] = amp0 * sqrt(-dEnergy/flux) * v; (Based on LAL)
amp[i] = amp0B * amp22fac * v2 / sqrt(-flux/dEnergy * 3 * v2 );
//printf("v=%g: a=%g ph=%g; amp22fac=%g sqrt(v^-9)=%g\n",v,amp[i],phase[i],amp22fac,sqrt(v/v10));
//Note ampB = - amp * 4*sqrt(3/5) * / sqrt(3) + higher-order = -4/sqrt(5)*( 1 + higher-order )
// ...possibly related to sph-harm normalization
// HACK: Strangely it seems that an additional factor of 4/sqrt(5) is just right to nearly match the EOB wf FT
amp[i] *= 4/sqrt(5); //HACK
//Here we depart from LAL, referencing phase and time-shift to two neighboring freq points
//First we match the freq derivative
}
}
/*Wrapper for waveform generation with possibly a combination of EOBNRv2HMROM and TaylorF2*/
/* Note: GenerateWaveform accepts masses and distances in SI units, whereas LISA params is in solar masses and Mpc */
/* Note: the extended waveform will now a different number of frequency points for each mode */
/* Note: phiRef is readjusted after the extension -- for the case where fRef is below the band covered by ROM, in which case the core function defaults fRef to the max geometric freq of the ROM */
int SimEOBNRv2HMROMExtTF2(
ListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */
int nbmode, /* Number of modes to generate (starting with the 22) */
double Mf_match, /* Minimum frequency using EOBNRv2HMROM in inverse total mass units*/
double minf, /* Minimum frequency required */
int tagexthm, /* Tag to decide whether or not to extend the higher modes as well */
double deltatRef, /* Time shift so that the peak of the 22 mode occurs at deltatRef */
double phiRef, /* Phase at reference frequency */
double fRef, /* Reference frequency (Hz); 0 defaults to fLow */
double m1SI, /* Mass of companion 1 (kg) */
double m2SI, /* Mass of companion 2 (kg) */
double distance, /* Distance of source (m) */
int setphiRefatfRef) /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) */
{//
//printf("calling SimEOBNRv2HMROMExtTF2 with minf=%g\n", minf);
//printf("params: %d %g %g %g %g %g %g %g %g\n", nbmode, Mf_match, minf, deltatRef, phiRef, fRef, m1SI, m2SI, distance);
int ret,i;
ListmodesCAmpPhaseFrequencySeries* listROM = NULL;
//int lout=-1,mout=-1;
int lout=-1,mout=-1;
/* Generate the waveform with the ROM */
ret = SimEOBNRv2HMROM(&listROM, nbmode, deltatRef, phiRef, fRef, m1SI, m2SI, distance, setphiRefatfRef);
/* If the ROM waveform generation failed (e.g. parameters were out of bounds) return FAILURE */
//if(ret==FAILURE)printf("SimEOBNRv2HMROMExtTF2: Generation of ROM for injection failed!\n");
if(ret==FAILURE) return FAILURE;
/* Main loop over the modes (as linked list) to perform the extension */
/* The 2-2 mode will be extended by TaylorF2 model with the phase and time offset
determined by matching conditions. All other modes will be extended as some
sort of power-law fall-off in amplitude and power-law growth in phase. */
ListmodesCAmpPhaseFrequencySeries* listelement = listROM;
while(listelement) { // For each l-m (ie each listelement)
/* Definitions: l,m, frequency series and length */
int l = listelement->l;
int m = listelement->m;
//NOTE: temporary hack to allow avoiding power-law extension of higher modes which seems problematic
// if((l==2&&m==2) || tagexthm) {
/* First we must compute a new frequency grid including a possible extension to lower frequencies*/
gsl_vector *freq_new;
gsl_vector* freq = listelement->freqseries->freq;
int len = (int) freq->size;
// Construct frequency grid extension on the geometric mean of the lowest few ROM frequencies after the matching point
const int Navg=3;
int imatch=-1;
double f_match;
if(Mf_match<=0) {
f_match = Mf_ROM_min/(m1SI+m2SI)*MSUN_SI/MTSUN_SI;
}
else if(Mf_match>Mf_ROM_min) {
f_match = Mf_match/(m1SI+m2SI)*MSUN_SI/MTSUN_SI;
}
else {
printf("WARNING: Mf_match lower than the lowest geometric frequency of the ROM model - used instead\n");
f_match = Mf_ROM_min/(m1SI+m2SI)*MSUN_SI/MTSUN_SI;
}
f_match = f_match*m/2; //Shift the matching frequency for non-22 modes to correspond to a comparable orbital freq.
//printf("f_match=%g\n",f_match);
for(i=0;i<len-Navg;i++){
if(gsl_vector_get(freq,i)>f_match){
imatch=i;
break;
}
}
if(imatch<0){
printf("WARNING: f_match exceeds high-freq range of the ROM model\n");
imatch=len-Navg-1;
}
double lnfmatch=log(gsl_vector_get(freq,imatch));
double lnfmin=log(minf);
double dlnf=(log(gsl_vector_get(freq,imatch+Navg))-lnfmatch)/Navg;
double dffac=exp(dlnf);
//The new grid will include the old grid, from imatch and after, plus adequate lower-freq
int len_add = (lnfmatch-lnfmin)/dlnf;
if(len_add<0) len_add=0;
int len_new = len - imatch + len_add;
//printf("extending waveform: len_add + len - imatch = len_new: %i + %i - %i = %i\n",len_add,len,imatch,len_new);
/* construct the extended freq grid */
freq_new=gsl_vector_alloc(len_new);
for(i=len_add;i<len_new;i++)gsl_vector_set(freq_new,i,gsl_vector_get(freq,len-len_new+i));
for(i=len_add;i>0;i--)gsl_vector_set(freq_new,i-1,gsl_vector_get(freq_new,i)/dffac);
//for(i=0;i<len_new;i++)printf("%i: %g %g\n",i,(i>=len_new-len?freq->data[i-len_new+len]:0),freq_new->data[i]);
//copy the old freqseries data to a new one and extend with power-law
CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;
if(l==lout&&m==mout){ //write to file for debugging
printf("Writing waveform-before for (%i,%i)\n",l,m);
FILE *f = fopen("waveform-before.dat", "w");
for(i=0;i<freqseries->freq->size;i++){
fprintf(f,"%i %i %g %g %g %g %i\n",l,m,
gsl_vector_get(freqseries->freq,i),
gsl_vector_get(freqseries->amp_real,i),
gsl_vector_get(freqseries->amp_imag,i),
gsl_vector_get(freqseries->phase,i),
i);
}
fclose(f);
}
CAmpPhaseFrequencySeries* freqseries_new=0; //New result will be assembled here
CAmpPhaseFrequencySeries_Init(&freqseries_new,len_new);
//set the new freqs
for(i=0;i<len_new;i++){
gsl_vector_set(freqseries_new->freq,i,gsl_vector_get(freq_new,i));
}
//copy in the high-freq ROM-model data
//printf("l,m = %i,%i; lenghts=%i,%i\n",l,m,freqseries->freq->size, freqseries_new->freq->size);
for(i=len_add;i<len_new;i++){
//printf("i, len-len_new+i: %i, %i\n",i,len-len_new+i);
gsl_vector_set(freqseries_new->amp_real,i,gsl_vector_get(freqseries->amp_real,len-len_new+i));
gsl_vector_set(freqseries_new->amp_imag,i,gsl_vector_get(freqseries->amp_imag,len-len_new+i));
gsl_vector_set(freqseries_new->phase,i,gsl_vector_get(freqseries->phase,len-len_new+i));
//printf("%i: copying %g %g %g %g\n",i,freqseries_new->freq->data[i],freqseries_new->amp_real->data[i],freqseries_new->amp_imag->data[i],freqseries_new->phase->data[i]);
}
//extend
if(l==2&&m==2&&len_add>0) {//extend 2-2 with TaylorF2
//Assemble data for matching
double f0=freq_new->data[len_add],f1=freq_new->data[len_add+1];
double ph0=freqseries_new->phase->data[len_add],ph1=freqseries_new->phase->data[len_add+1];
double amp=sqrt(freqseries_new->amp_real->data[len_add]*freqseries_new->amp_real->data[len_add]
+freqseries_new->amp_imag->data[len_add]*freqseries_new->amp_imag->data[len_add]);
double amp1=sqrt(freqseries_new->amp_real->data[len_add+1]*freqseries_new->amp_real->data[len_add+1]
+freqseries_new->amp_imag->data[len_add+1]*freqseries_new->amp_imag->data[len_add+1]);
double amprfac=freqseries_new->amp_real->data[len_add]/amp,ampifac=freqseries_new->amp_imag->data[len_add]/amp;
//Compute raw TaylorF2
TaylorF2nonspin(freqseries_new->amp_real->data,freqseries_new->phase->data,freq_new->data,len_add+2,m1SI,m2SI,distance,imatch);
//Compute offsets in phase, first phase derivative, and amplitude argument
double dphase0tf2=(freqseries_new->phase->data[len_add+1]-freqseries_new->phase->data[len_add])/(f1-f0);
double phase0tf2=freqseries_new->phase->data[len_add];
double dphase0eob=(ph1-ph0)/(f1-f0);
double dphase0=dphase0eob-dphase0tf2;
double phase0=ph0 - phase0tf2 - f0*dphase0;
double amp0bcoeff = amp / freqseries_new->amp_real->data[len_add] - 1.0; //Compute correction for continuity matching.
double amp0ccoeff = ((amp1/freqseries_new->amp_real->data[len_add+1]-1.0)/amp0bcoeff/(f1*f1/f0/f0)-1.0)/(f1/f0-1.0);
//TESTING
//printf("%g, %g\n", amp0bcoeff, amp0ccoeff);
//Compute correction for continuity matching.
/*
printf("ph0eob,dph0eob= %g, %g\n",ph0,dphase0eob);
printf("ph0tf2,dph0tf2= %g, %g\n",phase0tf2,dphase0tf2);
printf("ph0,dph0= %g, %g\n",phase0,dphase0);
printf("f0,f0*dph0= %g, %g\n",f0,dphase0*f0);
printf("imatch=%i\n",imatch);
*/
//Apply offsets
for (i = 0; i < len_add+2; i++){
double f=freqseries_new->freq->data[i];
//printf("%i<%i,%g\n",i,len_add,len_add-i);
//printf("f,ph0+f*dph0= %g, %g\n",freqseries_new->freq->data[i],phase0 + dphase0*f);
freqseries_new->phase->data[i] += phase0 + dphase0*f;
//First apply continuity matching
// amp -> amp * ( 1 + b*f^2/f0^2 * ( 1 + c*(f/f0 -1) )
//(starts at order f^2 since we only keep 2PN order ampl corrections in TaylorF2 code below; could change to f^3 if higher order terms are used)
freqseries_new->amp_real->data[i] *= 1.0 + amp0bcoeff*f*f/f0/f0*(1+amp0ccoeff*(f/f0-1));
freqseries_new->amp_imag->data[i] = freqseries_new->amp_real->data[i]*ampifac;
freqseries_new->amp_real->data[i] *= amprfac;
//printf("%i: extending TF2 %g %g %g %g\n",i,freqseries_new->freq->data[i],freqseries_new->amp_real->data[i],freqseries_new->amp_imag->data[i],freqseries_new->phase->data[i]);
}
} else { //extend other modes with power-law
//The results are many cycles out of phase almost immediately, so this definitely is not an accurate
//waveform, but the results are reasonably smooth and of plausible structure.
//Alternatively, we could also extend these with TaylorF2, btu we are mostly assuming this part of the WF is small
double phref=freqseries->phase->data[len-1];//For phase we extend by a power-law referenced to zero phase at end of ROM
for(i=0;i<len;i++)if(phref>freqseries->phase->data[i])phref=freqseries->phase->data[i];//get the smallest value of phi to use as ref.
phref=phref+1.0;//add one more
double ldArfac = 0;
if(gsl_vector_get(freqseries->amp_real,imatch)>0) //avoid div0 in trivial cases
//dArfac=exp(-log( gsl_vector_get(freqseries->amp_real,imatch+Navg)
// /gsl_vector_get(freqseries->amp_real,imatch) ) / Navg);
ldArfac=(log( gsl_vector_get(freqseries->amp_real,imatch+Navg)
/gsl_vector_get(freqseries->amp_real,imatch) ) /
log( gsl_vector_get(freqseries->freq,imatch+Navg)
/gsl_vector_get(freqseries->freq,imatch) ) );
//double dphfac = exp(-log( (gsl_vector_get(freqseries->phase,imatch+Navg)-phref)
// /(gsl_vector_get(freqseries->phase,imatch) -phref)) / Navg);
double ldphfac = (log( (gsl_vector_get(freqseries->phase,imatch+Navg)-phref)
/(gsl_vector_get(freqseries->phase,imatch) -phref)) /
log( gsl_vector_get(freqseries->freq,imatch+Navg)
/gsl_vector_get(freqseries->freq,imatch) ) );
if(1&&l==lout&&m==mout)printf("ldphfac(%i,%i)=%g\n",l,m,ldphfac);
//double f0=gsl_vector_get(freqseries->freq,imatch);
for(i=len_add;i>0;i--){
double fratio=gsl_vector_get(freqseries_new->freq,i-1)/gsl_vector_get(freqseries_new->freq,i);
double dArfac=pow(fratio,ldArfac);
gsl_vector_set(freqseries_new->amp_real,i-1,gsl_vector_get(freqseries_new->amp_real,i)*dArfac);
gsl_vector_set(freqseries_new->amp_imag,i-1,gsl_vector_get(freqseries_new->amp_imag,i)*dArfac);
double dphfac=pow(fratio,ldphfac);
gsl_vector_set(freqseries_new->phase,i-1,(gsl_vector_get(freqseries_new->phase,i)-phref)*dphfac+phref);
//printf("%i: extending %g %g %g %g\n",i,freqseries_new->freq->data[i-1],freqseries_new->amp_real->data[i-1],freqseries_new->amp_imag->data[i-1],freqseries_new->phase->data[i-1]);
}
//printf("Extended (%i,%i) down to f=%g, ampR=%g, ampI=%g, phase=%g\n",l,m,freqseries_new->freq->data[0],freqseries_new->amp_real->data[0],freqseries_new->amp_imag->data[0],freqseries_new->phase->data[0]);
}
//delete the old content data and replace with the new
CAmpPhaseFrequencySeries_Cleanup(freqseries);
listelement->freqseries=freqseries_new;
//TESTING
//printf("In ext: len freqseries: %d\n", freqseries_new->freq->size);
//for(int i=0; i<freqseries_new->freq->size; i++) {
//printf("%g %g %g %g\n", gsl_vector_get(freqseries_new->freq, i), gsl_vector_get(freqseries_new->amp_real, i), gsl_vector_get(freqseries_new->amp_imag, i), gsl_vector_get(freqseries_new->phase, i));
//}
//debugging
// freqseries=listelement->freqseries;
// if(1&&l==lout&&m==mout){ //write to file for debugging
// FILE *f = fopen("waveform.dat", "w");
// for(i=0;i<freqseries->freq->size;i++){
// fprintf(f,"%i %i %g %g %g %g %i\n",l,m,
// freqseries->freq->data[i],
// freqseries->amp_real->data[i],
// freqseries->amp_imag->data[i],
// freqseries->phase->data[i],
// i);
// }
// fclose(f);
// }
gsl_vector_free(freq_new);
listelement=listelement->next;
}
/* Compute phase shift to set phiRef at fRef */
/* Covers the case where input fRef is outside the range of the ROM, in which case the Core function defaulted to Mfmax_ROM */
/* Not very clean and a bit redundant */
if (setphiRefatfRef) {
CAmpPhaseFrequencySeries* h22 = ListmodesCAmpPhaseFrequencySeries_GetMode(listROM, 2, 2)->freqseries;
gsl_vector* freq22 = h22->freq;
gsl_vector* phase22 = h22->phase;
int nbfreq = freq22->size;
gsl_interp_accel* accel_phi22 = gsl_interp_accel_alloc();
gsl_spline* spline_phi22 = gsl_spline_alloc(gsl_interp_cspline, nbfreq);
gsl_spline_init(spline_phi22, gsl_vector_const_ptr(freq22,0), gsl_vector_const_ptr(phase22,0), nbfreq);
/* If fRef was not set (fRef=0), use the last frequency generated for 22 mode -- as is done internally in Core */
if (fRef==0.) fRef = freq22->data[freq22->size - 1];
/* Compute 22 phase at fRef before adjustment, check the extended range */
if ( (fRef<freq22->data[0]) || (fRef>freq22->data[freq22->size - 1]) ) {
printf("Error: fRef is not covered by the frequency range of the waveform after extension.\n");
return FAILURE;
}
double phi22atfRef = gsl_spline_eval(spline_phi22, fRef, accel_phi22);
/* Phase shift, as an orbital or observer phase shift (change in 22 is 2*phaseshift) */
double phaseshift = (2*phiRef - phi22atfRef)/2.;
/* Propagate phase shift to full list of modes */
listelement = listROM;
while(listelement) {
int l = listelement->l;
int m = listelement->m;
double phaseshiftlm = m/2. * phaseshift;
gsl_vector* philm = listelement->freqseries->phase;
gsl_vector_add_constant(philm, phaseshiftlm);
listelement = listelement->next;
}
/* Cleanup */
gsl_spline_free(spline_phi22);
gsl_interp_accel_free(accel_phi22);
}
/* Output */
*listhlm = listROM;
/*
printf("generated listROM: n=%i l=%i m=%i\n",(*listhlm)->freqseries->amp_real->size,listROM->l,listROM->m);
for(i=0;i<(*listhlm)->freqseries->freq->size;i++){
printf("%i: %g %g %g %g\n",i,(*listhlm)->freqseries->freq->data[i],(*listhlm)->freqseries->amp_real->data[i],(*listhlm)->freqseries->amp_imag->data[i],(*listhlm)->freqseries->phase->data[i]);
}
printf("listlhm=%x\n",listhlm);
printf("*listlhm=%x\n",*listhlm);
*/
return SUCCESS;
}
| {
"alphanum_fraction": 0.677926532,
"avg_line_length": 46.8557599226,
"ext": "c",
"hexsha": "4a2ccdc80ec653068bfb72b7b9e2868ccebd036d",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "JohnGBaker/flare",
"max_forks_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "JohnGBaker/flare",
"max_issues_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.c",
"max_line_length": 257,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "JohnGBaker/flare",
"max_stars_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.c",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 14371,
"size": 48402
} |
/*! \file profile_coord_map.h
\brief Grid initialization, finding flux coordinates, and getting profile data
Called by all the top-level functions.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <Python.h>
#include <gsl/gsl_vector.h> // needed for 2-d root-finding
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_linalg.h>
#include "eq_quantity.h"
#ifndef REAL_TYPEDEF
#define REAL_TYPEDEF
#ifndef single // compiler option determines variable size
typedef double REAL;
#else
typedef float REAL;
#endif
#endif
#ifndef DEBUG // default debug level: no output to stderr
#define DEBUG 0
#endif
#ifndef DEVELOPMENT // default development level: use the best of what has been tested to work
#define DEVELOPMENT 0
#endif
#ifndef VERBOSE
#define VERBOSE 0
#endif
#define MAX_N_TRIES 4 // number of times to try to get the root-finder unstuck
// used by desiredrz: constants to choose the desired grid in R,Z space
// used by desiredxyz: constants for desired 3d grid in x,y,z
extern double Xmin,Xmax,Ymin,Ymax,Zmin,Zmax;
// used by getAllProfiles
#define NORM_TO_KEV 4.7894e4 // conversion constant from normalized units to keV (called Tem_00 in fortran files) Normalization in GTS: Length 100cm, Time Deuterium Cyclotron frequency in 1T B field -- OMEGA_D^-1,
// T normalized st. vth = sqrt(T). Temperature has the energy dimention.
#define INVCM3_TO_INVM3 1e6 // convert cm^{-3} to m^{-3}
// used by decayNToutsideLCFS and getBoundaryPoints
#define ABOUNDARY 0.9
#define AINSIDE 0.88
#define AZERO 1.2
//#define DECAY_SCALING 0.1*(ABOUNDARY-AINSIDE) // the 0.1 makes it drop off faster
#define MINIMUM(x,y) ((x) < (y) ? (x) : (y))
extern char* NTFileName;
// ---------- local function declarations
int cylToLargeAR(REAL R[],REAL Z[], REAL r[], REAL theta[],int n,REAL R0,REAL Z0);
int largeARtoCyl(REAL r[],REAL theta[], REAL R[], REAL Z[],int n,REAL R0,REAL Z0);
int desiredrz(REAL R[],REAL Z[],REAL R1d[],REAL Z1d[],int nr,int nz,REAL R0,REAL Z0);
int desiredxyz(int nx,int ny,int nz,REAL x1d[],REAL y1d[],REAL z1d[],REAL x[],REAL y[],REAL z[],REAL R0,REAL Z0);
int mesh2dGrid(REAL x2d[],REAL y2d[],REAL x1d[],REAL y1d[],int nx,int ny);
int mesh3dGrid(REAL x3d[],REAL y3d[],REAL z3d[],REAL x1d[],REAL y1d[],REAL z1d[],int nx,int ny,int nz);
int guessatheta(REAL a[],REAL theta[], REAL R[], REAL Z[],int n,REAL R0,REAL Z0);
REAL error_amt(REAL R,REAL Z,REAL a,REAL theta);
void print_state(size_t iter, gsl_multiroot_fsolver * s);
int findcorrectatheta(REAL a[],REAL theta[],REAL Ract[],REAL Zact[],REAL Bm[],REAL Rwant[], REAL Zwant[],int n,int flag[],int location[],int mismatch[]);
int coord_f(const gsl_vector *x,void *params,gsl_vector *f);
int getBoundaryPoints(double** R_bdy,double** Z_bdy,int n_bdy);
void free_BoundaryPoints(double* R_bdy,double* Z_bdy);
int get_mag_axis(REAL coords[]);
int decayNToutsideLCFS(int npts,REAL a[],REAL ne[],REAL Te[],REAL Ti[],int* flag);
int getFluxCoords(int npts,REAL a[],REAL theta[],REAL Bm[],REAL Ract[],REAL Zact[],REAL Rinitial[],REAL Zinitial[],REAL Rwant[],REAL Zwant[],REAL mag_axis_coords[],int flag[],int location[], int mismatch[]);
int getAllProfiles(int npts,REAL Bpol[],REAL BR[],REAL BZ[],REAL Ti[],REAL Te[],REAL P[],REAL ne[],REAL qprofile[],REAL a[],REAL theta[],REAL Rwant[],REAL Zwant[],REAL R_bdy[],REAL Z_bdy[],int InOutFlag[],int location[]);
int getProfile(REAL a,REAL* ne,REAL* Ti,REAL* Te,REAL* a_p,REAL* n_p,REAL* Ti_p,REAL* Te_p,int n_prof );
int adiabaticElectronResponse(int npts,int ntimesteps,REAL ne_tilde[],REAL ne0[],REAL phi[],REAL Te[],int flag[]);
//modified by Lei Shi adding function to find the outside points
//declaration
void inner_check(double R[],double Z[],double R_bdy[],double Z_bdy[],int flag[],int n,int n_bdy,double tol);
//R,Z contains grid point coordinates, R_bdy Z_bdy contains boundary points, flag show inside(with value 1) and outside(with value 0), n the number of grid points, n_bdy the number of boundary points.
//if (R[i],Z[i]) is inside or on the boundary of the contour specified by R_bdy and Z_bdy, flag[i] is set to 1, otherwise 0;
//definition
int horipos_check(double Rc,double Zc, double R1,double Z1,double R2,double Z2,double tol){
double R=R1+ (Zc-Z1)/(Z2-Z1)*(R2-R1);
if(fabs(R-Rc)<=tol)
return 2;
else if(R<Rc)
return 1;
else
return -1;
}
void inner_check(double R[],double Z[],double R_bdy[],double Z_bdy[],int flag[],int n,int n_bdy,double tol){
int i;
for(i=0;i<n;i++){
double Rc=R[i];
double Zc=Z[i];
flag[i]=0;
int vertpos=0;
int horipos1=0;
int horipos2=0;
int j;
for(j=0;j<n_bdy;j++){
if(Z_bdy[j]==Zc){
if (horipos1==0)
{
if(fabs(R_bdy[j]-Rc) < tol)
horipos1=2;
else if(R_bdy[j]<Rc)
horipos1=1;
else
horipos1=-1;
continue;
}
else{
{
if(fabs(R_bdy[j]-Rc) < tol)
horipos2=2;
else if(R_bdy[j]<Rc)
horipos2=1;
else
horipos2=-1;
flag[i]= (horipos1 != horipos2)?1:0;
break;
}
}
}
else if(Z_bdy[j]<Zc){
if(vertpos==0){
vertpos = -1;
continue;
}
else if(vertpos==-1)
continue;
else{
if(horipos1 == 0){
vertpos = -1;
horipos1 = horipos_check(Rc,Zc,R_bdy[j],Z_bdy[j],R_bdy[j-1],Z_bdy[j-1],tol);
continue;
}
else{
horipos2=horipos_check(Rc,Zc,R_bdy[j],Z_bdy[j],R_bdy[j-1],Z_bdy[j-1],tol);
flag[i]= (horipos1 != horipos2)?1:0;
break;
}
}
}
else{
if(vertpos==0){
vertpos = 1;
continue;
}
else if(vertpos == 1)
continue;
else{
if(horipos1 == 0){
vertpos = 1;
horipos1 = horipos_check(Rc,Zc,R_bdy[j],Z_bdy[j],R_bdy[j-1],Z_bdy[j-1],tol);
continue;
}
else{
horipos2=horipos_check(Rc,Zc,R_bdy[j],Z_bdy[j],R_bdy[j-1],Z_bdy[j-1],tol);
flag[i]= (horipos1 != horipos2)?1:0;
break;
}
}
}
}
}
}
//end modification
// ---------- data structures
struct coordparams{ // structure for 2D root finding
REAL Rwant;
REAL Zwant;
};
// ---------- function definitions
//! Convert cylindrical coords (R,Z) to a large aspect ratio approximation of (r,theta)
/*! For n points, where (R0,Z0) is the position of the magnetic axis */
int cylToLargeAR(REAL R[],REAL Z[], REAL r[], REAL theta[],int n,REAL R0,REAL Z0){
REAL x,z;
int i;
for(i=0;i<n;i++){ // here I use: R-R0 = a*cos(theta)
x = R[i]-R0; // and Z = a*sin(theta)
z = Z[i]-Z0;
theta[i]=-atan2(z,x); // poloidal angle (correct quadrant)
// r[i] = sqrt(x*x+z*z); // minor rad.
r[i] = hypot(x,z);
}
return 0;
}
//! Convert a large aspect ratio (r,theta) to cylindrical coords (R,Z)
/*! For n points, where (R0,Z0) is the position of the magnetic axis */
int largeARtoCyl(REAL r[],REAL theta[], REAL R[], REAL Z[],int n,REAL R0,REAL Z0){
int i;
for(i=0;i<n;i++){ // here I use: R-R0 = a*cos(theta)
R[i] = R0 + r[i]*cos(theta[i]);
Z[i] = Z0 - r[i]*sin(theta[i]);
}
return 0;
}
//! Generate a regular, 2D array meshes in (R,Z), and also 1D arrays for each dimension
/*! 2D arrays vary fastest along R (columns) and slowly along Z (rows).
Also generates 1D arrays R1d, Z1d.
nr: points in R, nz: # points in z; total # points = nr*nz
R0,Z0 are the coordinates for the magnetic axis, which is not currently used.
*/
int desiredrz(REAL X[],REAL Y[],REAL X1d[],REAL Y1d[],int nx,int ny,REAL X0,REAL Y0){
int i;
REAL dx = (Xmax-Xmin)/(nx-1);
REAL dy = (Ymax-Ymin)/(ny-1);
for(i=0;i<ny;i++) Y1d[i] = (REAL)Ymin + i*dy;
for(i=0;i<nx;i++) X1d[i] = (REAL)Xmin + i*dx;
mesh2dGrid(X,Y,X1d,Y1d,nx,ny);
// printf("desiredrz: dr:%g,dz:%g\n",dr,dz);
// for(i=0;i<nz;i++){
// Z1d[i] = (REAL)ZMIN + i*dz;
// for(j=0;j<nr;j++){
// R[i*nr+j] = (REAL)RMIN + j*dr;
// Z[i*nr+j] = (REAL)ZMIN + i*dz;
// }
// }
return 0;
}
//! Generate a regular, 3D array meshes in (x,y,z), and also 1D arrays for each dimension
/*! 3D arrays vary fastest along x (columns), then along y (rows), slowest along z (pages).
x is locally radially outward, y is vertically upward, z is locally toroidal to make a
right-hand coordinate system.
nx: points in x direction, ny: points in y direction, nz: points in z direction;
total # points = nx*ny*nz.
R0,Z0 are the coordinates for the magnetic axis, which is not currently used.
*/
int desiredxyz(int nx,int ny,int nz,REAL x1d[],REAL y1d[],REAL z1d[],REAL x[],REAL y[],REAL z[],REAL X0,REAL Y0){
int i,j,k;
REAL dx = (Xmax-Xmin)/(nx-1);
REAL dy = (Ymax-Ymin)/(ny-1);
REAL dz = (Zmax-Zmin)/(nz-1);
#if DEBUG > 1
fprintf(stderr,"desiredrz: dx:%g,dy:%g,dz:%g\n",dx,dy,dz);
#endif
for(i=0;i<nz;i++) z1d[i] = (REAL)Zmin + i*dz;
for(i=0;i<ny;i++) y1d[i] = (REAL)Ymin + i*dy;
for(i=0;i<nx;i++) x1d[i] = (REAL)Xmin + i*dx;
mesh3dGrid(x,y,z,x1d,y1d,z1d,nx,ny,nz);
// for(i=0;i<nz;i++){
// z1d[i] = (REAL)zMIN + i*dz;
// for(j=0;j<ny;j++){
// for(k=0;k<nx;k++){
// x[i*ny*nx+j*nx+k] = (REAL)xMIN + k*dx;
// y[i*ny*nx+j*nx+k] = (REAL)yMIN + j*dy;
// z[i*ny*nx+j*nx+k] = (REAL)zMIN + i*dz;
// }
// }
// }
return 0;
}
//! Generate 2d mesh grids from 1d grids in each dimension
/*! Takes 1d arrays of coordinates x1d,y1d and generates 2d arrays
x2d,y2d of nx columns and ny rows, corresponding to the x,y
coordinate of each point.
*/
int mesh2dGrid(REAL x2d[],REAL y2d[],REAL x1d[],REAL y1d[],int nx,int ny){
int i,j;
for(i=0;i<ny;i++){
for(j=0;j<nx;j++){
x2d[i*nx+j] = x1d[j];
y2d[i*nx+j] = y1d[i];
}
}
return 0;
}
//! Generate 3d mesh grids from 1d grids in each dimension
/*! Takes 1d arrays of coordinates x1d,y1d,z1d and generates 3d arrays
x3d,y3d,z3d of nx columns, ny rows, and nz pages corresponding to the x,y,z
coordinates of each point.
*/
int mesh3dGrid(REAL x3d[],REAL y3d[],REAL z3d[],REAL x1d[],REAL y1d[],REAL z1d[],int nx,int ny,int nz){
int i,j,k;
for(i=0;i<nz;i++){
for(j=0;j<ny;j++){
for(k=0;k<nx;k++){
x3d[i*ny*nx+j*nx+k] = x1d[k];
y3d[i*ny*nx+j*nx+k] = y1d[j];
z3d[i*ny*nx+j*nx+k] = z1d[i];
}
}
}
return 0;
}
//! Given cylindrical coords (R,Z) calculates the initial guess for the flux coords (a,theta)
// first guess as to what the correct a,theta values are for the desired R,Z points
// this is the "large aspect ratio, circ. xsection where I take a = minor radius and
// theta is simply poloidal angle
// then I modify the angle by doing an interpolation
// n is total # of points in 1d array
int guessatheta(REAL a[],REAL theta[], REAL R[], REAL Z[],int n,REAL R0,REAL Z0){
int i,k;
int n1dgrid = (int)sqrt(n);
int ngrid = n1dgrid*n1dgrid;//+10;
#if DEVELOPMENT >= 0
REAL rwant[n],polwant[n];
k = cylToLargeAR(R,Z,rwant,polwant,n,R0,Z0);// the minor radius and polodial angles of the R,Z we want
// --- current method: 2D interpolation for 2 variables:
// (rgrid,polgrid) -> a
// (rgrid,polgrid) -> theta
REAL agrid[ngrid],thetagrid[ngrid],Rgrid[ngrid],Zgrid[ngrid];
REAL rgrid[ngrid],polgrid[ngrid],Bgrid[ngrid];
// set up a grid to interpolate on
// use to get an even grid in a,theta
double da = 1.5/(n1dgrid-1);
double dtheta = 2.0*M_PI/n1dgrid;
for(i=0;i<n1dgrid;i++){
for(k=0;k<n1dgrid;k++){
agrid[i*n1dgrid+k] = 0.5*da + i*da;
thetagrid[i*n1dgrid+k] = -M_PI+k*dtheta;
}
}
k = esigetrzb_(Rgrid,Zgrid,Bgrid,agrid,thetagrid,&ngrid); // get Rgrid and Zgrid
k = cylToLargeAR(Rgrid,Zgrid,rgrid,polgrid,ngrid,R0,Z0); // get the grid minor radius and poloidal angle
// interpolate using (rgrid,polgrid) -> (agrid,thetagrid)
// to get (rwant,thetawant) -> (a,theta)
k = interp2d(n,ngrid,rwant,polwant,a,theta,rgrid,polgrid,agrid,thetagrid);
#if DEBUG > 0
fprintf(stderr,"point agrid thetagrid Rgrid Zgrid rgrid polgrid\n");
for(i=0;i<ngrid;i++)
fprintf(stderr,"%5d, %g, %g, %g, %g, %g, %g\n",i,agrid[i],thetagrid[i],
Rgrid[i],Zgrid[i],rgrid[i],polgrid[i]);
fprintf(stderr,"point a theta R Z rwant polwant\n");
for(i=0;i<n;i++){
fprintf(stderr,"%5d, %g, %g, %g, %g, %g, %g\n",i,a[i],theta[i],
R[i],Z[i],rwant[i],polwant[i]);
}
#endif
for(i=0;i<n;i++) if(a[i]>2.5) a[i]=2.5; // limit the maximum radial flux coord
#endif
// // --- previous method: 1D interpolation of both variables independently
// // polgrid -> (agrid=1,thetagrid)
// // rgrid -> (agrid,thetagrid=pi/6)
// REAL agrid[n1dgrid],thetagrid[n1dgrid],Rgrid[n1dgrid],Zgrid[n1dgrid];
// REAL rgrid[n1dgrid],polgrid[n1dgrid],Bgrid[n1dgrid];
// // first do the poloidal interpolation
// double dtheta = 2*M_PI/n1dgrid;
// for(i=0;i<n1dgrid;i++){
// agrid[i] = 1;
// thetagrid[i] = -M_PI+i*dtheta;
// }
// k = esigetrzb_(Rgrid,Zgrid,Bgrid,agrid,thetagrid,&n);
// k = cylToLargeAR(Rgrid,Zgrid,rgrid,polgrid,n,R0,Z0); // get the grid minor radius and poloidal angle
// k = interpgsl(polwant,theta,polgrid,thetagrid,n,n1dgrid); // interpolate in poloidal angle:
// // then do the radial interpolation
// double da = 1.5/(n1dgrid-1);
// for(i=0;i<n1dgrid;i++){
// agrid[i] = i*da;
// thetagrid[i] = M_PI/6;
// }
// k = esigetrzb_(Rgrid,Zgrid,Bgrid,agrid,thetagrid,&n1dgrid);
// k = cylToLargeAR(Rgrid,Zgrid,rgrid,polgrid,n1dgrid,R0,Z0); // get minor rad. and pol. angle
// k = interpgsl(rwant,a,rgrid,agrid,n,n1dgrid); // interpolate radially
// // // modification that I discarded
// // for(i=0;i<n;i++){
// // a[i] += 1.5*a[i]*exp(-400.0*theta[i]*theta[i]/(M_PI*M_PI));//a[i]*1.5*fabs(exp(-fabs(theta[i])/M_PI)-exp(-1.0/4.0));//0.5*a[i]*(1-2*fabs(theta[i])/M_PI)*(1-2*fabs(theta[i])/M_PI);
// // }
// // --- end method: 1D interpolation of both variables independently
// --- solution in use previously
#if DEVELOPMENT < 0
REAL dtheta=2*M_PI/(n-1);// divide flux-coord domain
REAL x,alarge[n],q[n],Rmap[n],Zmap[n],Bmap[n],qpol[n];//,stheta[n-1];
// guess a large-aspect ratio, circular cross section
cylToLargeAR(R,Z,a,theta,n,R0,Z0);
// for(i=0;i<n;i++){ // here I use: R-R0 = a*cos(theta)
// x = R[i]-R0; // and Z = a*sin(theta)
// theta[i]=-atan2(Z[i],x); // poloidal angle (correct quadrant)
// a[i] = sqrt(x*x+Z[i]*Z[i]); // minor rad.
// }
// set up interpolation
// modify large aspect ratio, circ. xsection by interpolating between angles
// for large minor radius, map theta to actual poloidal angle:
for(i=0;i<n;i++){//generate an array of evenly-spaced flux coords
q[i] = -M_PI + dtheta*i; // to interpolate what qpol (R,Z), q (a,theta)
alarge[i] = 1; // is mapped to
}
k = esigetrzb_(Rmap,Zmap,Bmap,alarge,q,&n);
// check to see the poloidal angle these evenly-spaced flux coords mapped to
for(i=0;i<n;i++){ // here I use: R-R0 = a*cos(theta), Z = a*sin(theta)
x = Rmap[i]-R0;
qpol[i]=-atan2(Zmap[i],x); // poloidal angle (correct quadrant)
// rmax[i]=sqrt(x*x+Z[i]*Z[i]);
//printf("%g,",qpol[i]);
}
// now interpolate theta
REAL thetatmp[n];
k = interpgsl(theta,thetatmp,qpol,q,n,n);
for(i=0;i<n;i++) theta[i]=thetatmp[i]; //uncomment to skip interpolation
// for(i=0;i<n;i++){
// a[i] += 1.5*a[i]*exp(-400.0*theta[i]*theta[i]/(M_PI*M_PI));//a[i]*1.5*fabs(exp(-fabs(theta[i])/M_PI)-exp(-1.0/4.0));//0.5*a[i]*(1-2*fabs(theta[i])/M_PI)*(1-2*fabs(theta[i])/M_PI);
// } //not worth it; only removed 12 total iterations
// --- end solution in use previously
#endif
return 0;
}
//! the 2D function solved by the root finder
int coord_f(const gsl_vector *x,void *params,gsl_vector *f){
REAL Rwant = ((struct coordparams *) params)->Rwant; // desired R,Z
REAL Zwant = ((struct coordparams *) params)->Zwant;
REAL a[1] = {gsl_vector_get (x, 0)}; // current a,theta
REAL theta[1] = {gsl_vector_get (x, 1)};
int n=1;
int k;
REAL Ract[1],Zact[1],Bm[1]; // actual R,Z at this value of a,theta
if(!finite(a[0])) a[0] = ABOUNDARY; // in portalr4 this was necessary to eliminate faults
if(!finite(theta[0])) theta[0] = 0.0;
k = esigetrzb_(Ract,Zact,Bm,a,theta,&n); // solve for the actual R,Z values
gsl_vector_set (f, 0, Rwant-Ract[0]); // the error
gsl_vector_set (f, 1, Zwant-Zact[0]);
return GSL_SUCCESS;
}
//! returns the distance between desired (R,Z) position and the position mapped to by flux coords (a,theta)
REAL error_amt(REAL R,REAL Z,REAL a,REAL theta){
REAL Ract,Zact,Bact;
int single=1;
esigetrzb_(&Ract,&Zact,&Bact,&a,&theta,&single);
// return sqrt((R-Ract)*(R-Ract)+(Z-Zact)*(Z-Zact));
return hypot(R-Ract,Z-Zact);
}
//! Print current status of the root-finder
void print_state(size_t iter, gsl_multiroot_fsolver * s){
fprintf (stderr,"iter = %3u x = % .3f % .3f "
"f(x) = % .3e % .3e\n",
iter,
gsl_vector_get (s->x, 0),
gsl_vector_get (s->x, 1),
gsl_vector_get (s->f, 0),
gsl_vector_get (s->f, 1));
}
//! performs 2D root finding to get the (a,theta) for an array of given (R,Z) values
/*! Uses the gsl mulidimensional hybrids root solver ``gsl_multiroot_fsolver_hybrids''. */
// Modified by Lei Shi
// use function esirz2agq to find (a,theta) for a given (R,Z) inside LCFS, and treat outside points seperately
//write CDF function show the flags
inline void ERR_CI(int e,const char* s)
{
fprintf(stderr,"error:%s in %s\n",nc_strerror(e),s);
exit(e);
}
void writeCDF(char* fname,int ntotal, double R[],double Z[],int n_bdy,double R_bdy[],double Z_bdy[],int flag[]){
int R_dim_id,Z_dim_id,R_bdy_dim_id,Z_bdy_dim_id,flag_dim_id;
int nr_id,nz_id,ntotal_id,n_bdy_id;
int R_id,Z_id,R_bdy_id,Z_bdy_id,flag_id;
int f_id;
int ecode;
if(ecode=nc_create(fname,NC_CLOBBER,&f_id))
ERR_CI(ecode,"create file");
if(ecode=nc_def_dim(f_id,"r_dim",ntotal,&R_dim_id))
ERR_CI(ecode,"def r dim");
if(ecode=nc_def_dim(f_id,"z_dim",ntotal,&Z_dim_id))
ERR_CI(ecode,"def z dim");
if(ecode=nc_def_dim(f_id,"r_bdy_dim",n_bdy,&R_bdy_dim_id))
ERR_CI(ecode,"def r_bdy dim");
if(ecode=nc_def_dim(f_id,"z__bdy_dim",n_bdy,&Z_bdy_dim_id))
ERR_CI(ecode,"def z_bdy dim");
if(ecode=nc_def_dim(f_id,"flag_dim",ntotal,&flag_dim_id))
ERR_CI(ecode,"def flag dim");
if(ecode=nc_def_var(f_id,"nr",NC_INT,0,NULL,&nr_id))
ERR_CI(ecode,"def nr var");
if(ecode=nc_def_var(f_id,"nz",NC_INT,0,NULL,&nz_id))
ERR_CI(ecode,"def nz var");
if(ecode=nc_def_var(f_id,"ntotal",NC_INT,0,NULL,&ntotal_id))
ERR_CI(ecode,"def ntotal var");
if(ecode=nc_def_var(f_id,"n_bdy",NC_INT,0,NULL,&n_bdy_id))
ERR_CI(ecode,"def n_bdy var");
if(ecode=nc_def_var(f_id,"r",NC_DOUBLE,1,&R_dim_id,&R_id))
ERR_CI(ecode,"def r var");
if(ecode=nc_def_var(f_id,"z",NC_DOUBLE,1,&Z_dim_id,&Z_id))
ERR_CI(ecode,"def z var");
if(ecode=nc_def_var(f_id,"r_bdy",NC_DOUBLE,1,&R_bdy_dim_id,&R_bdy_id))
ERR_CI(ecode,"def r_bdy var");
if(ecode=nc_def_var(f_id,"z_bdy",NC_DOUBLE,1,&Z_bdy_dim_id,&Z_bdy_id))
ERR_CI(ecode,"def z_bdy var");
if(ecode=nc_def_var(f_id,"flag",NC_INT,1,&flag_dim_id,&flag_id))
ERR_CI(ecode,"def flag var");
if(ecode=nc_enddef(f_id))
ERR_CI(ecode,"enddef");
if(ecode=nc_put_var_int(f_id,nr_id,&ntotal))
ERR_CI(ecode,"put nr var");
if(ecode=nc_put_var_int(f_id,nz_id,&ntotal))
ERR_CI(ecode,"put nz var");
if(ecode=nc_put_var_int(f_id,ntotal_id,&ntotal))
ERR_CI(ecode,"put ntotal var");
if(ecode=nc_put_var_int(f_id,n_bdy_id,&n_bdy))
ERR_CI(ecode,"put n_bdy var");
if(ecode=nc_put_var_double(f_id,R_id,R))
ERR_CI(ecode,"put R var");
if(ecode=nc_put_var_double(f_id,Z_id,Z))
ERR_CI(ecode,"put Z var");
if(ecode=nc_put_var_double(f_id,R_bdy_id,R_bdy))
ERR_CI(ecode,"put R_bdy var");
if(ecode=nc_put_var_double(f_id,Z_bdy_id,Z_bdy))
ERR_CI(ecode,"put Z_bdy var");
if(ecode=nc_put_var_int(f_id,flag_id,flag))
ERR_CI(ecode,"put flag var");
if(ecode=nc_close(f_id))
ERR_CI(ecode,"close file");
FILE* txtfile;
txtfile=fopen("./bdy_out.txt","w");
fprintf(txtfile,"%d\n",n_bdy);
int i;
for(i=0;i<n_bdy;i++)
{
fprintf(txtfile,"%lf\t%lf\t",R_bdy[i],Z_bdy[i]);
}
fclose(txtfile);
}
int findcorrectatheta(REAL a[],REAL theta[],REAL Ract[], REAL Zact[],REAL Bm[], REAL Rwant[], REAL Zwant[],int n,int flag[],int location[], int mismatch[]){
// find correct a theta coordinates, for inside LCFS points, a theta are obtained by ESIrz2agq function, for outside points, a is assumed to be proportional to the distance from the magnetic axis, and theta is chosen as the same value as the corresponding boundary point. The corresponding boundary point is chosen to be the boundary point closest to the connecting line of magnetic axis and the desired location.
// Note that in this function, magnetude of B, BR and BZ are also calculated. BR and BZ calculation is not trivial, look into the attached file "Calc_BR_BZ.txt" for more detailed discussion.
// new version starts
extern int NBOUNDARY;
extern double* R_bdy,*Z_bdy;
fprintf(stderr,"start findcorrecttheta.\n");
getBoundaryPoints(&R_bdy,&Z_bdy,NBOUNDARY);
fprintf(stderr,"after getBoundaryPoints.\n");
double b_axis;
int single_point=1;
double tol=1e-9; //used in inner_check,when given point is near the bdy within tol distance, it's considered on the bdy.
double dR,dZ;
double match_tol = 1e-2;
double theta_guess;
double theta_bdy;
double a_guess;
double a_bdy=ABOUNDARY;
double zero=0;
double Z_rel;//the relative Z respect to mag_axis
double R_rel;//the relative R respect to mag_axis
double mag_axis_coords[2];
int loc;
int sign_ini;
int sign_cur;
char CDFfname[20]="./InOutFlags.cdf";
char logfile[20]="./sl_log.txt";
FILE* errlog;
dR = fabs(Rwant[1]-Rwant[0]);
match_tol *= dR; // absolute tolerance is the percentage tolerance times the finest grid resolution
fprintf(stderr,"match_tol = %lf\n", match_tol);
errlog=fopen(logfile,"w+");
fprintf(errlog,"match_tol = %lf\n", match_tol);
esigetrzb_(&mag_axis_coords[0],&mag_axis_coords[1],&b_axis,&zero,&zero,&single_point);
fprintf(stderr,"before inner_check.\n");
inner_check(Rwant,Zwant,R_bdy,Z_bdy,flag,n,NBOUNDARY,tol);
fprintf(stderr,"after before write CDF.\n");
writeCDF(CDFfname,n,Rwant,Zwant,NBOUNDARY,R_bdy,Z_bdy,flag);
int i;
/* for(i=0;i<NBOUNDARY;i++){
fprintf(errlog,"%lf\t%lf\n",R_bdy[i],Z_bdy[i]);
}
fprintf(errlog,"Boundary ends.\n");
*/
int ierror;
double b_tmp;
fprintf(stderr,"Start getting locations.\n");
for(i=0;i<n;i++){
if(flag[i]==1){
//fprintf(stderr,"point %d mapping start,",i);
int k=ESIrz2agq(&a[i],&theta[i],&Rwant[i],&Zwant[i],&ierror,single_point);
if(k!=0){
fprintf(errlog,"Point %d (%lf,%lf) has encountered an error: %d in rz2agq.\n",i,Rwant[i],Zwant[i],ierror);
}
esigetrzb_(&Ract[i],&Zact[i],&Bm[i],&a[i],&theta[i],&single_point);
double err=hypot((Rwant[i]-Ract[i]),(Zwant[i]-Zact[i]));
double dis=hypot((Rwant[i]-mag_axis_coords[0]),(Zwant[i]-mag_axis_coords[1]));
// output err and dis for checking
//fprintf(errlog,"Point %d (%lf,%lf) %lf away from axis has been mapped %lf away\n",i,Rwant[i],Zwant[i],dis,err);
if( err > match_tol){
fprintf(errlog,"Point %d (%lf,%lf) %lf away from axis has been mapped %lf away\n",i,Rwant[i],Zwant[i],dis,err);
mismatch[i] = 1;
//fprintf(stderr,"Point %d (%lf,%lf) %lf away from axis has been mapped %lf away\n",i,Rwant[i],Zwant[i],dis,err);
if(fabs(Zwant[i])<0.1)
{
a[i]=0;
theta[i]=0;
}
}
location[i]=-1; // inside points do not need location information
}
else if(flag[i]==0){
// fprintf(stderr,"outter point.\n");
Bm[i]=b_axis*mag_axis_coords[0]/Rwant[i]; // let B inversely proportional to R, based on B on axis
Ract[i]=Rwant[i];
Zact[i]=Zwant[i];
Z_rel=Zwant[i]-mag_axis_coords[1];
R_rel=Rwant[i]-mag_axis_coords[0];
int quarter=0;
if(R_rel>=0){
if(Z_rel>=0) quarter=1;
else quarter =4;
}
else{
if(Z_rel>=0) quarter=2;
else quarter=3;
}
theta_guess=atan((Z_rel/R_rel));
if(quarter == 2 || quarter == 3)
theta_guess += M_PI;
if(quarter == 4)
theta_guess += 2*M_PI;
Z_rel=Z_bdy[0]-mag_axis_coords[1];
R_rel=R_bdy[0]-mag_axis_coords[0];
theta_bdy=atan((Z_rel/R_rel));
if(R_rel>=0){
if(Z_rel>0) quarter=1;
else quarter =4;
}
else{
if(Z_rel>0) quarter=2;
else quarter=3;
}
if(quarter == 2 || quarter == 3)
theta_bdy+=M_PI;
if(quarter == 4)
theta_bdy += 2*M_PI;
sign_ini=(theta_guess>=theta_bdy)?1:-1;
int j;
for(j=0;j<NBOUNDARY;j++)
{
Z_rel=Z_bdy[j]-mag_axis_coords[1];
R_rel=R_bdy[j]-mag_axis_coords[0];
theta_bdy=atan((Z_rel/R_rel));
if(R_rel>=0){
if(Z_rel>0) quarter=1;
else quarter =4;
}
else{
if(Z_rel>0) quarter=2;
else quarter=3;
}
if(quarter == 2 || quarter == 3)
theta_bdy+=M_PI;
if(quarter == 4)
theta_bdy += 2*M_PI;//set the theta into (0,2Pi]
sign_cur=theta_guess>=theta_bdy?1:-1;
if(sign_ini*sign_cur<0){ //if passes the theta we want and is not on the opposite side, then we find the right boundary point
location[i]=j;
break;
}
}
if(j==NBOUNDARY)
location[i]=0;
Z_rel=Zwant[i]-mag_axis_coords[1];
R_rel=Rwant[i]-mag_axis_coords[0];
// fprintf(stderr,"start guess a\n");
a_guess=sqrt((Z_rel*Z_rel+R_rel*R_rel)/((R_bdy[loc]-mag_axis_coords[0])*(R_bdy[loc]-mag_axis_coords[0])+(Z_bdy[loc]-mag_axis_coords[1])*(Z_bdy[loc]-mag_axis_coords[1])))*a_bdy;
a[i]=a_guess;
theta[i]=2*M_PI/NBOUNDARY*loc;
}
else{
fprintf(stderr,"flag error: point %d at (%lf,%lf) has flag %d.\n",i,Rwant[i],Zwant[i],flag[i]);
exit(5);
}
}
fprintf(stderr,"finish getting locations.\n");
fclose(errlog);
return 0;
/*old version by Erik
// declarations for root solver
const gsl_multiroot_fsolver_type *T;
gsl_multiroot_fsolver *s;
int status; // status of root-finder (notifies if stuck, etc)
size_t iter = 0;
int i;
int ntries; // num of times for this point that we get stuck
const size_t ndims = 2; // 2D coordinate
struct coordparams p; // parameters used by ea. instance of solver: Rwant,Zwant
gsl_multiroot_function f = {&coord_f, ndims, &p}; // root solver setup
gsl_vector *x = gsl_vector_alloc (ndims); // R,Z values used by root solver
T = gsl_multiroot_fsolver_hybrids; // solver type
s = gsl_multiroot_fsolver_alloc (T, 2);
// loop over all points
for(i=0;i<n;i++){
status = GSL_CONTINUE; // reset root finder status
// check to see if the nearest point provides a better initial estimate
if(i>0){
if(error_amt(Rwant[i],Zwant[i],a[i],theta[i]) > error_amt(Rwant[i],Zwant[i],a[i-1],theta[i-1])){ // if the nearest point is a better guess than the default initial guess, use the previous point
a[i] = a[i-1];
theta[i] = theta[i-1];
}
}
// set up this instance of the root finder
p.Rwant = Rwant[i]; // pass the desired coordinates as parameters
p.Zwant = Zwant[i];
gsl_vector_set (x, 0, a[i]);
gsl_vector_set (x, 1, theta[i]);
// try a few times with different initial conditions if the solver gets stuck
for(ntries=0;ntries<MAX_N_TRIES;ntries++){
if(status == GSL_SUCCESS) break; // in this case, the root-find was successful
// choose a new initial condition if the solver is stuck
if(ntries>0){
#if DEVELOPMENT <= 0
gsl_vector_set(x,0,0.2);
gsl_vector_set(x,1,0.25*M_PI+ 0.8*gsl_vector_get(x,1));
#else
// gsl_vector_set(x,0,0.2 + fmod(0.3+gsl_vector_get(x,0),1.2));
gsl_vector_set(x,0,0.2 + fmod(0.4+gsl_vector_get(x,0),2.0));
// gsl_vector_set(x,1,-M_PI + fmod(1.5*M_PI+gsl_vector_get(x,1),2.0*M_PI));
gsl_vector_set(x,1,-M_PI + fmod(1.25*M_PI+gsl_vector_get(x,1),2.0*M_PI));
#endif
}
gsl_multiroot_fsolver_set (s, &f, x); // initialize the root finder
iter = 0; // reset iteration counter
do{
iter++;
status = gsl_multiroot_fsolver_iterate (s);
#if DEBUG > 0
fprintf(stderr,"point:%d, ntries:%d, status:%d, ",i,ntries,status);
print_state (iter, s); // uncomment to give info at each iteration
#endif
if (status){ // check if solver is stuck
break;
}
status = gsl_multiroot_test_residual (s->f, 1e-7);
}while (status == GSL_CONTINUE && iter < 200);
}
a[i] = gsl_vector_get(s->x,0);
theta[i] = gsl_vector_get(s->x,1);
}
gsl_multiroot_fsolver_free (s);
gsl_vector_free (x);
// make sure all radial flux coords are positive (a>0)
for(i=0;i<n;i++) a[i]=copysign(a[i],1.0);
// get the actual R,Z coordinates we've mapped
status = esigetrzb_(Ract,Zact,Bm,a,theta,&n);
#if VERBOSE > 0
REAL err_dist;
//modified by Lei start
const int NBOUNDARY=4000;
double R_bdy[NBOUNDARY],Z_bdy[NBOUNDARY];
getBoundaryPoints(R_bdy,Z_bdy,NBOUNDARY);
// for(i=0;i<NBOUNDARY;i++){
// fprintf(stdout,"(%lf,%lf),",R_bdy[i],Z_bdy[i]);
// }
for(i=0;i<n;i++){
err_dist = hypot((Rwant[i]-Ract[i]),(Zwant[i]-Zact[i]));
if(err_dist > 1e-7)//if the error is unnormally large, try to find a reasonable a and theta for that point, and adjust the B value
{
// fprintf(stderr,"Warning, point %d is mapped %.4g [m] away from requested position.\n",i,err_dist);
int single_point=1;
double zero=0;
double b; // B field on the axis
double theta_guess;
double theta_bdy;
double a_guess;
double a_bdy=1;
double Z_rel;//the relative Z respect to mag_axis
double R_rel;//the relative R respect to mag_axis
double mag_axis_coords[2];
int loc;
int sign_ini;
int sign_cur;
esigetrzb_(&mag_axis_coords[0],&mag_axis_coords[1],&b,&zero,&zero,&single_point);
Bm[i]=b*mag_axis_coords[0]/Rwant[i]; // let B inversely proportional to R, based on B on axis
Z_rel=Zwant[i]-mag_axis_coords[1];
R_rel=Rwant[i]-mag_axis_coords[0];
theta_guess=atan((Z_rel/R_rel));
if(theta_guess<=0)
theta_guess += 2*M_PI;
theta_bdy=atan((Z_bdy[0]-mag_axis_coords[1])/(R_bdy[0]-mag_axis_coords[0]));
if(theta_bdy<=0)
theta_bdy+=2*M_PI;
sign_ini=(theta_guess>=theta_bdy)?1:-1;
// fprintf(stderr,"pt[%d]:\n sign_ini = %d\n",i,sign_ini);
int j;
for(j=0;j<NBOUNDARY;j++)
{
theta_bdy=atan((Z_bdy[j]-mag_axis_coords[1])/(R_bdy[j]-mag_axis_coords[0]));
if(theta_bdy<=0)
theta_bdy += 2*M_PI;//set the theta into [0,2Pi)
sign_cur=theta_guess>=theta_bdy?1:-1;
if(sign_ini*sign_cur<0 && Zwant[i]*Z_bdy[j]>=0){ //if passes the theta we want and is not on the opposite side, then we find the right boundary point
loc=j;
break;
}
}
a_guess=sqrt((Z_rel*Z_rel+R_rel*R_rel)/((R_bdy[loc]-mag_axis_coords[0])*(R_bdy[loc]-mag_axis_coords[0])+(Z_bdy[loc]-mag_axis_coords[1])*(Z_bdy[loc]-mag_axis_coords[1])))*a_bdy;
a[i]=a_guess;
theta[i]=2*M_PI/NBOUNDARY*loc;
// if(theta_bdy>M_PI)
// fprintf(stderr,"sign_cur=%d\n loc= %d,Rwant=%lf, Zwant=%lf, theta=%lf, Rbd=%lf, Zbd=%lf, thetabd=%lf, a=%lf",sign_cur,loc,Rwant[i],Zwant[i],theta_guess,R_bdy[loc],Z_bdy[loc],theta_bdy,a[i]);
}
}
//Modified by Lei End
#endif
old version ends*/
}
//! Calculates the (R,Z) coordinates of the boundary of the last-closed-flux-surface
/*! Assumes the LCFS is given by the macro ABOUNDARY (set to 1.0 by default) */
int getBoundaryPoints(double** R_bdy,double** Z_bdy,int n_bdy){
double dtheta = 2*M_PI/(n_bdy-1);
double a[n_bdy],theta[n_bdy],B_bdy[n_bdy];
*R_bdy = (double*)xmalloc(sizeof(double)*n_bdy);
*Z_bdy = (double*)xmalloc(sizeof(double)*n_bdy);
int i,k;
for(i=0;i<n_bdy;i++){
theta[i] = dtheta*i;
a[i] = ABOUNDARY;
}
k=esigetrzb_(*R_bdy,*Z_bdy,B_bdy,a,theta,&n_bdy);
}
void free_BoundaryPoints(double* R_bdy,double* Z_bdy){
xfree(R_bdy);
xfree(Z_bdy);
}
//! Find the (R,Z) coordinates of the magnetic axis
/*! Uses the esi functions.
*/
int get_mag_axis(REAL coords[]){
REAL bm;
REAL mag_axis = 0;
int single_point = 1;
// get the position of the magnetic axis
//printf("before esigetrzb_\n");
int k = esigetrzb_(&coords[0],&coords[1],&bm,&mag_axis,&mag_axis,&single_point);
//printf("after esigetrzb_\n");
return 0;
}
// modified by Lei Shi to get desired shape outside the LCFS
// The shape function is set to be
// shape1:exponential tan shape
// n(a)=n(1)*exp(-n'(1)/n(1)*tan(PI/2*(a-1)/(a0-1)));
// shape2:cubic shape
// n(a)=c3*a^3+c2*a^2+c1^a+c0
// so that n(1) and n'(1) are unchanged, and n(a0) and n'(a0) are 0;
inline double Shape1(double x, double xb,double x0,double yb,double ypb){
return yb*exp(ypb/yb*tan(M_PI/2*(x-xb)/(x0-xb)));
}
double Shape2(double x,double xb,double x0,double yb,double ypb){
double xb2=xb*xb;
double xb3=xb*xb2;
double x02=x0*x0;
double x03=x0*x02;
double a_data[]=
{
1,xb,xb2, xb3,
1,x0,x02, x03,
0,1, 2*xb,3*xb2,
0,1, 2*x0,3*x02
};
double b_data[]={yb,0,ypb,0};
gsl_matrix_view m= gsl_matrix_view_array(a_data,4,4);
gsl_vector_view b= gsl_vector_view_array(b_data,4);
gsl_vector *c = gsl_vector_alloc(4);
int s;
gsl_permutation *p=gsl_permutation_alloc(4);
gsl_linalg_LU_decomp(&m.matrix,p,&s);
gsl_linalg_LU_solve(&m.matrix,p,&b.vector,c);
double C[4];
int i;
for(i=0;i<4;i++)
C[i]=gsl_vector_get(c,i);
return C[0]+C[1]*x+C[2]*x*x+C[3]*x*x*x;
}
inline double Decay(int shape,double a,double a_bdy,double a0,double y_bdy,double yp_bdy){
switch(shape){
case 1:
return Shape1(a,a_bdy,a0,y_bdy,yp_bdy);
case 2:
return Shape2(a,a_bdy,a0,y_bdy,yp_bdy);
default:
fprintf(stderr,"Wrong decay shape number, check the notes in profile_coord_map.h before function decayNToutsideLCFS for more info.\n");
}
}
//! Cause density and temperature to exponentially decay outside the LCFS
/*! Use the value of density, Ti, and Te at the Last-Closed-Flux-Surface
and force these quantities to exponentially decay outside this surface.
This is done so there is no abrupt increase in these quantities that might
frustrate the paraxial solver in the reflectometry code.
*/
int decayNToutsideLCFS(int npts,REAL a[],REAL ne[],REAL Te[],REAL Ti[],int* flag){
REAL abound = ABOUNDARY; // (a,theta) on the boundary that we use
REAL ain = AINSIDE; // (a,theta) inside the LCFS we use
// (* to find the exponential drop off *) in our case, to find n'(1)
REAL a0 = AZERO; // the flux coord where we set n & T to be zero
//load the equilibrium profile
int** n_prof=(int**)PyMem_Malloc(sizeof(int*));
REAL **a_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
REAL **n_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
REAL **Ti_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
REAL **Te_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
int k;
k=loadNTProfiles(NTFileName,n_prof,a_p,n_p,Ti_p,Te_p);
if(k!=0){
fprintf(stderr,"Loading NTProfile error %d.\n",k);
exit(1);
}
// values of ne,te,ti at boundary and just inside LCFS
REAL nebound,tibound,tebound,nein,tin,tein;
getProfile(abound,&nebound,&tibound,&tebound,*a_p,*n_p,*Ti_p,*Te_p,**n_prof);
getProfile(ain,&nein,&tin,&tein,*a_p,*n_p,*Ti_p,*Te_p,**n_prof);
nebound *=INVCM3_TO_INVM3;
// tibound *=1;
// tebound *=1;
nein *=INVCM3_TO_INVM3;
// tin *=1;
// tein *=1;
// the 1/e distance in radial flux coord
// the scale factor is to make it drop off faster
// REAL lambda_ne = -fabs(DECAY_SCALING*nebound/(nein-nebound));
// REAL lambda_ti = -fabs(DECAY_SCALING*tibound/(tin-tibound));
// REAL lambda_te = -fabs(DECAY_SCALING*tebound/(tein-tebound));
// the direvitives are obtained based on linear estimation
REAL ne_prime = (nebound-nein)/(abound-ain);
REAL ti_prime = (tibound-tin)/(abound-ain);
REAL te_prime = (tebound-tein)/(abound-ain);
fprintf(stderr,"n'=%lf,t'=%lf",ne_prime,te_prime);
// update the values in the ne,te,ti arrays
// int i;
// for(i=0;i<npts;i++){
// if(a[i]>1.0){
// ne[i] = nebound*exp((a[i]-abound)/lambda_ne);
// Te[i] = tebound*exp((a[i]-abound)/lambda_te);
// Ti[i] = tibound*exp((a[i]-abound)/lambda_ti);
// }
int i;
for(i=0;i<npts;i++){
if(flag[i] == 0 ){
if(a[i] <= a0){
ne[i]=Decay(2,a[i],abound,a0,nebound,ne_prime);
Te[i]=Decay(2,a[i],abound,a0,tebound,te_prime);
Ti[i]=Decay(2,a[i],abound,a0,tibound,ti_prime);
// fprintf(stderr,"inside a[%d]=%lf, ne=%lf, Te=%lf , Ti=%lf\n",i,a[i],ne[i],Te[i],Ti[i]);
}
else{
ne[i]=Te[i]=Ti[i]=0; // if the point is outside a0, set all to be 0
// fprintf(stderr,"outside a[%d]=%lf, ne=%lf, Te=%lf , Ti=%lf\n",i,a[i],ne[i],Te[i],Ti[i]);
}
}
}
return 0;
}
//! Runs all the functions to map from cylindrical (R,Z) coords to flux coords
/*! Given the number of points npts, the desired cylindrical coords (Rwant,Zwant)
and the (R,Z) coordinate array of the magnetic axis position "mag_axis_coords",
gives the initial guess (Rinitial,Zinitial), the flux coords (a,theta), and
the actual (Ract,Zact) these flux coords map to.
*/
int getFluxCoords(int npts,REAL a[],REAL theta[],REAL Bm[],REAL Ract[],REAL Zact[],REAL Rinitial[],REAL Zinitial[],REAL Rwant[],REAL Zwant[],REAL mag_axis_coords[],int flag[],int location[], int mismatch[]){
// field-line coords: a: flux (radial), theta: angle (poloidal), Bm: |B|
// (Rwant,Zwant): the R,Z coordinatew we want to map to
// (Rinitial,Zinitial): the R,Z coords of our initial guess
// (Ract,Zact): actual R,Z coordinates we end up with
int k;
// k = guessatheta(a,theta,Rwant,Zwant,npts,mag_axis_coords[0],mag_axis_coords[1]); // initial guess for the flux coords
// k = esigetrzb_(Rinitial,Zinitial,Bm,a,theta,&npts); // map to cylindrical coords
fprintf(stderr, "before findcorrectatheta.\n");
k = findcorrectatheta(a,theta,Ract,Zact,Bm,Rwant,Zwant,npts,flag,location,mismatch); // use esi provided interpolation to get flux coords
return k;
}
//! Gets all the profile data at the specified flux coordinates
/*! Given the number of points npts, the flux coords (a,theta), gets the
values of: Bpol, Ti, Te, P, ne, and the q profile at these points.
*/
extern char* NTFileName;
int getProfile(REAL a,REAL* ne,REAL* Ti,REAL* Te,REAL* a_p,REAL* n_p,REAL* Ti_p,REAL* Te_p,int n_prof){ //get ne,Ti,Te for a specified flux surface psi=a, linear interpolation based on the loaded ne,Ti,Te profile
interpxy(&a,ne,a_p,n_p,1,n_prof);
interpxy(&a,Ti,a_p,Ti_p,1,n_prof);
interpxy(&a,Te,a_p,Te_p,1,n_prof);
return 0;
}
int getAllProfiles(int npts,REAL Bpol[], REAL BR[],REAL BZ[] ,REAL Ti[],REAL Te[],REAL P[],REAL ne[],REAL qprofile[],REAL a[],REAL theta[], REAL Rwant[], REAL Zwant[],REAL R_bdy[],REAL Z_bdy[],int InOutFlag[], int location[]){
// used by esilink2c and esiget2dfunctions
REAL *F = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *Fa = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *gFa = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *gFaa = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *gYa = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *gYaa = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *Ta = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *Pa = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *r = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *ra = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *rq = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *z = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *za = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *zq = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *B = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *Ba = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *Bq = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *gh = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *gha = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
REAL *ghq = (REAL *)PyMem_Malloc(npts*sizeof(REAL));
int k = esilink2c_(F,Fa,gFa,gFaa,gYa,gYaa,Ti,Ta,P,Pa,r,ra,rq,z,za,zq,B,Ba,Bq,gh,gha,ghq);
k = esiget2dfunctions_(a,theta,&npts);
// get q profile
int i;
for(i=0;i<npts;i++){// reverse of method documented in escZ_march03.c
if(a[i]==0.0){ // this method is used in setup_v2.F90
qprofile[i] = -gFaa[i]/gYaa[i]; // the magnetic axis is a special case
}else qprofile[i]=-gFa[i]/gYa[i];
}
int** n_prof=(int**)PyMem_Malloc(sizeof(int*));
REAL **a_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
REAL **n_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
REAL **Ti_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
REAL **Te_p=(REAL**)PyMem_Malloc(sizeof(REAL*));
printf("NTFileName before loadNTProfiles: %s\n",NTFileName);
k=loadNTProfiles(NTFileName,n_prof,a_p,n_p,Ti_p,Te_p);
if(k!=0){
fprintf(stderr,"Loading NTProfile error %d.\n",k);
exit(1);
}
// get density and temperature profiles
for(i=0;i<npts;i++){
if(InOutFlag[i]==1){
getProfile(a[i],&ne[i],&Ti[i],&Te[i],*a_p,*n_p,*Ti_p,*Te_p,**n_prof);
Ti[i] *= 100;
Te[i] *= 100;
ne[i] *= INVCM3_TO_INVM3;
}
else{
ne[i]=0;
Ti[i]=0;
Te[i]=0;
}
}
//get BR, BZ for new FWR3D
// the basic idea is using flux coordinates to express BR = B dot grad(R).
// look into attached pdf file for more details about calculating these two components.
fprintf(stderr,"before getting BR,BZ. \n");
//get magnetic axis coordinates
double mag_axis_coords[2];
get_mag_axis(mag_axis_coords);
for (i=0;i<npts;i++){
if(InOutFlag[i]==1){
// for inside points, all relavent quantites can be gotten from ESI equilibrium reading functions defined in eq_quantity.h
//fprintf(stderr,"inside point [%d].\n",i);
initialize_esi_out(&a[i],&theta[i],1);
//fprintf(stderr,"esi_out initialized.\n");
//fprintf(stderr,"a=%lf,theta=%lf,n=%d.\n",esi_output.aaa[0],esi_output.the[0],esi_output.n);
load_esi_quantities();
//fprintf(stderr,"esi_quantities loaded\n");
double** metric = get_metric_elements();
//fprintf(stderr,"metric_elements got.\n");
double gaa = metric[0][0];
double gtt = metric[1][0];
double gat = metric[3][0];
double* J = get_Jacobian();
//fprintf(stderr,"Jacobian got.\n");
double dpsi_da = -esi_output.gYaj[0];
double dr_dth = esi_output.rqj[0];
double dr_da = esi_output.raj[0];
double dz_dth = esi_output.zqj[0];
double dz_da = esi_output.zaj[0];
// now, define some intermediate quantities:
double mod_grad_R = sqrt(dr_da*dr_da*gaa + dr_dth*dr_dth*gtt + 2*dr_da*dr_dth*gat);
double mod_grad_Z = sqrt(dz_da*dz_da*gaa + dz_dth*dz_dth*gtt + 2*dz_da*dz_dth*gat);
// calculate BR, BZ at this point
//fprintf(stderr,"before assigning BR,BZ. \n");
BR[i] = -dpsi_da*dr_dth/(mod_grad_R*J[0]);
BZ[i] = -dpsi_da*dz_dth/(mod_grad_Z*J[0]);
// clean up
//fprintf(stderr,"before cleaning up.");
free_all(metric,J);
}
else{
//if the point is outside of the LCFS, we estimate the BR, BZ using the information gotten from the corresponding points ON the LCFS. Assume Bpol is decaying proportionally to the distance away from the magnetic axis.
//fprintf(stderr,"outside point[%d].\n",i);
extern double* R_bdy,*Z_bdy;
extern int NBOUNDARY;
int loc = location[i];
//fprintf(stderr,"location got.\n");
double theta_loc = 2*M_PI/(NBOUNDARY-1) * loc; //Note that the convention is that the first and last boundary points corresponds to the same location(theta =0 and 2*pi), so boundary points form a closed circle.
double a_loc = ABOUNDARY;
double Rb = R_bdy[loc];
double Zb = Z_bdy[loc];
//fprintf(stderr,"Rb,Zb got.\n");
// for the boundary point, do the same thing to obtain BR, BZ there.
initialize_esi_out(&a_loc,&theta_loc,1);
//fprintf(stderr,"esi_out initialized.\n");
load_esi_quantities();
//fprintf(stderr,"esi_quantities loaded. \n");
double** metric = get_metric_elements();
//fprintf(stderr,"metric elements got.\n");
double gaa = metric[0][0];
double gtt = metric[1][0];
double gat = metric[3][0];
double* J = get_Jacobian();
//fprintf(stderr,"Jacobian got.\n");
double dpsi_da = -esi_output.gYaj[0];
double dr_dth = esi_output.rqj[0];
double dr_da = esi_output.raj[0];
double dz_dth = esi_output.zqj[0];
double dz_da = esi_output.zaj[0];
// now, define some intermediate quantities:
double mod_grad_R = sqrt(dr_da*dr_da*gaa + dr_dth*dr_dth*gtt + 2*dr_da*dr_dth*gat);
double mod_grad_Z = sqrt(dz_da*dz_da*gaa + dz_dth*dz_dth*gtt + 2*dz_da*dz_dth*gat);
// calculate BR, BZ at this point
double BR_bdy = -dpsi_da*dr_dth/(mod_grad_R*J[0]);
double BZ_bdy = -dpsi_da*dz_dth/(mod_grad_Z*J[0]);
//fprintf(stderr,"BR,BZ bdy got.\n");
// clean up
free_all(metric,J);
// now calculate the BR, BZ at the outside point
double R = Rwant[i];
double Z = Zwant[i];
//calculate the distances between relavent points
double dis_want = hypot(R-mag_axis_coords[0],Z-mag_axis_coords[1]);
double dis_bdy = hypot(Rb-mag_axis_coords[0],Zb-mag_axis_coords[1]);
//get BR, BZ based on the ratio of distances to magnetic axis
BR[i] = BR_bdy * dis_bdy / dis_want;
BZ[i] = BZ_bdy * dis_bdy / dis_want;
}
}
//calculate Bpol
for(i=0;i<npts;i++){
Bpol[i] = sqrt(BR[i]*BR[i] + BZ[i]*BZ[i]);
}
fprintf(stderr,"after getting BR,BZ. \n");
// free arrays that are no longer needed:
clearNTProfiles(n_prof,a_p,n_p,Ti_p,Te_p);
PyMem_Free(F);
PyMem_Free(Fa);
PyMem_Free(gFa);
PyMem_Free(gFaa);
PyMem_Free(gYa);
PyMem_Free(gYaa);
PyMem_Free(Ta);
PyMem_Free(Pa);
PyMem_Free(r);
PyMem_Free(ra);
PyMem_Free(rq);
PyMem_Free(z);
PyMem_Free(za);
PyMem_Free(zq);
PyMem_Free(B);
PyMem_Free(Ba);
PyMem_Free(Bq);
PyMem_Free(gh);
PyMem_Free(gha);
PyMem_Free(ghq);
return 0;
}
//! Determine the density fluctuation assuming adiabatic electron response to potential fluctuations.
/*! Given the number of points npts, the background density (ne0), electron temperature (Te),
and potential fluctuation (phi), computes the density fluctuation (ne_tilde) and the total
density (ne), using: ne_tilde = ne0*phi/Te, and ne = ne0 + ne_tilde
*/
int adiabaticElectronResponse(int npts,int ntimesteps,REAL ne_tilde[],REAL ne0[],REAL phi[],REAL Te[],int flag[]){
int i,j;
for(i=0;i<ntimesteps;i++){
for(j=0;j<npts;j++){
if(flag[j]==1){
double* phi_this = &phi[i*npts+j];
*phi_this *= NORM_TO_KEV;
ne_tilde[i*npts+j] = (*phi_this)/Te[j];
}
else
ne_tilde[i*npts+j] = 0;
}
}
return 0;
}
| {
"alphanum_fraction": 0.6501252382,
"avg_line_length": 34.1704462326,
"ext": "h",
"hexsha": "9562952cb36ad57e5a65c755de34fa60f211dfd9",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2020-01-10T03:38:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-29T12:35:59.000Z",
"max_forks_repo_head_hexsha": "5f1cb5c29d182490acbd4f3c167f0e09ec211236",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "justthepython/Synthetic-Diagnostics-Platform",
"max_forks_repo_path": "src/python2/sdp/plasma/gts/C_src/profile_coord_map.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "5f1cb5c29d182490acbd4f3c167f0e09ec211236",
"max_issues_repo_issues_event_max_datetime": "2016-05-11T17:18:36.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-05-11T12:58:00.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "justthepython/Synthetic-Diagnostics-Platform",
"max_issues_repo_path": "src/python2/sdp/plasma/gts/C_src/profile_coord_map.h",
"max_line_length": 415,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "870120d3fd14b2a3c89c6e6e85625d1e9109a2de",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "LeiShi/Synthetic-Diagnostics-Platform",
"max_stars_repo_path": "src/python2/sdp/plasma/gts/C_src/profile_coord_map.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-24T02:47:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-16T22:08:19.000Z",
"num_tokens": 15646,
"size": 46711
} |
/*
* author: Pierre Schnizer
* created: March 2004
* file: pygsl/src/initmodule.c
* $Id: initmodule.c,v 1.14 2008/10/25 20:45:04 schnizer Exp $
*
* Changes:
* 7. October 2003:
* Removed the error handler from this file. It is now in
* Lib/error_helpers.c Each module must call init_pygsl()
* in its init routine. This is necessary to support platforms
* where the gsl library is statically linked to the various
* modules.
*/
#define _PyGSL_API_MODULE 1
#include <pygsl/intern.h>
#include <pygsl/utils.h>
#include <pygsl/error_helpers.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_version.h>
/* Taken from Modules/getbuildinfo */
#ifndef DATE
#ifdef __DATE__
#define DATE __DATE__
#else
#define DATE "xx/xx/xx"
#endif
#endif
#ifndef TIME
#ifdef __TIME__
#define TIME __TIME__
#else
#define TIME "xx:xx:xx"
#endif
#endif
/* End */
/*
* Used as a buffer to generate error messages.
*/
static char pygsl_error_str[512];
#include "profile.c"
#include "error_helpers.c"
#include "general_helpers.c"
#include "complex_helpers.c"
#include "block_helpers.c"
#include "function_helpers.c"
#include "rng_helpers.c"
static PyObject * debuglist = NULL;
static int
PyGSL_register_debug_flag(int * ptr, const char * module_name)
{
#if DEBUG == 1
PyObject * cobj;
FUNC_MESS_BEGIN();
if ((cobj = PyCObject_FromVoidPtr((void *) ptr, NULL)) == NULL){
fprintf(stderr, "Could not create PyCObject for ptr %p to debug flag for module %s\n",
(void * ) ptr, module_name);
return GSL_EFAILED;
}
DEBUG_MESS(2, "Registering ptr %p for module %s", (void *) ptr, module_name);
if(PyList_Append(debuglist, cobj) != 0){
return GSL_EFAILED;
}
*ptr = pygsl_debug_level;
FUNC_MESS_END();
return GSL_SUCCESS;
#endif
PyGSL_ERROR("Why does it try to register the debug level callback? Should"
" use the compile time value DEBUG!", GSL_ESANITY);
}
static PyObject *
PyGSL_set_debug_level(PyObject *self, PyObject *args)
{
FUNC_MESS_BEGIN();
#if DEBUG == 1
PyObject *o;
int tmp, i, max, *ptr;
if(!PyArg_ParseTuple(args, "i", &tmp))
return NULL;
if(tmp >= 0 && tmp <PyGSL_DEBUG_MAX)
;
else
PyGSL_ERROR_VAL("Only accept debug levels between 0 and PyGSL_DEBUG_MAX", GSL_EINVAL, NULL);
pygsl_debug_level = tmp;
max = PySequence_Size(debuglist);
DEBUG_MESS(3, "Setting debug level to %d for %d modules", pygsl_debug_level, max);
for(i = 0; i < max; ++i){
if((o = PySequence_GetItem(debuglist, i)) == NULL){
fprintf(stderr, "In file %s at line %d; Could not get element %d\n",
__FILE__, __LINE__, i);
continue;
}
ptr = (int *)PyCObject_AsVoidPtr(o);
DEBUG_MESS(2, "Setting info ptr %p", (void *) ptr);
*ptr = tmp;
}
Py_INCREF(Py_None);
FUNC_MESS_END();
return Py_None;
#else
PyGSL_ERROR_NULL("PyGSL was not compiled with DEBUG = 1; Can not set DEBUG level!", GSL_EUNIMPL);
#endif
}
static PyObject *
PyGSL_get_debug_level(PyObject *self, PyObject *args)
{
int tmp;
#if DEBUG == 1
tmp = (int) pygsl_debug_level;
#else
tmp = DEBUG;
#endif
return PyInt_FromLong(tmp);
}
static void * _PyGSL_API[PyGSL_NENTRIES_NUM];
static PyMethodDef initMethods[] = {
{"get_debug_level", PyGSL_get_debug_level, METH_NOARGS, NULL},
{"set_debug_level", PyGSL_set_debug_level, METH_VARARGS, NULL},
{"vector_transform_counter", PyGSL_get_vector_transform_counter ,METH_NOARGS, NULL},
{"matrix_transform_counter", PyGSL_get_matrix_transform_counter ,METH_NOARGS, NULL},
{"complex_transform_counter", PyGSL_get_complex_transform_counter,METH_NOARGS, NULL},
{"float_transform_counter", PyGSL_get_float_transform_counter ,METH_NOARGS, NULL},
{"register_exceptions", PyGSL_register_exceptions, METH_VARARGS,NULL},
{"register_warnings", PyGSL_register_warnings, METH_VARARGS,NULL},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static void
PyGSL_init_api(void)
{
int i;
for(i=0;i<PyGSL_NENTRIES_NUM; ++i){
_PyGSL_API[i] = NULL;
}
_PyGSL_API[PyGSL_api_version_NUM ] = (void *) PyGSL_API_VERSION;
_PyGSL_API[PyGSL_RNG_ObjectType_NUM ] = NULL;
_PyGSL_API[PyGSL_error_flag_NUM ] = (void *) &PyGSL_error_flag;
_PyGSL_API[PyGSL_error_flag_to_pyint_NUM ] = (void *) &PyGSL_error_flag_to_pyint;
_PyGSL_API[PyGSL_add_traceback_NUM ] = (void *) &PyGSL_add_traceback;
_PyGSL_API[PyGSL_module_error_handler_NUM ] = (void *) &PyGSL_module_error_handler;
_PyGSL_API[PyGSL_error_string_for_callback_NUM ] = (void *) & PyGSL_set_error_string_for_callback ;
_PyGSL_API[PyGSL_pyfloat_to_double_NUM ] = (void *) & PyGSL_pyfloat_to_double ;
_PyGSL_API[PyGSL_pylong_to_ulong_NUM ] = (void *) & PyGSL_pylong_to_ulong ;
_PyGSL_API[PyGSL_pylong_to_uint_NUM ] = (void *) & PyGSL_pylong_to_uint ;
_PyGSL_API[PyGSL_check_python_return_NUM ] = (void *) & PyGSL_check_python_return ;
_PyGSL_API[PyGSL_clear_name_NUM ] = (void *) & PyGSL_clear_name ;
_PyGSL_API[PyGSL_PyComplex_to_gsl_complex_NUM ] = (void *) & PyGSL_PyComplex_to_gsl_complex ;
_PyGSL_API[PyGSL_PyComplex_to_gsl_complex_float_NUM ] = (void *) & PyGSL_PyComplex_to_gsl_complex_float ;
_PyGSL_API[PyGSL_PyComplex_to_gsl_complex_long_double_NUM ] = (void *) & PyGSL_PyComplex_to_gsl_complex_long_double ;
_PyGSL_API[PyGSL_stride_recalc_NUM ] = (void *) & PyGSL_stride_recalc ;
_PyGSL_API[PyGSL_PyArray_new_NUM ] = (void *) & PyGSL_New_Array ;
_PyGSL_API[PyGSL_PyArray_copy_NUM ] = (void *) & PyGSL_Copy_Array ;
/*
_PyGSL_API[PyGSL_PyArray_prepare_gsl_vector_view_NUM ] = (void *) & PyGSL_PyArray_prepare_gsl_vector_view ;
_PyGSL_API[PyGSL_PyArray_prepare_gsl_matrix_view_NUM ] = (void *) & PyGSL_PyArray_prepare_gsl_matrix_view ;
*/
_PyGSL_API[PyGSL_PyArray_generate_gsl_vector_view_NUM ] = (void *) & PyGSL_PyArray_generate_gsl_vector_view ;
_PyGSL_API[PyGSL_PyArray_generate_gsl_matrix_view_NUM ] = (void *) & PyGSL_PyArray_generate_gsl_matrix_view ;
_PyGSL_API[PyGSL_copy_pyarray_to_gslvector_NUM ] = (void *) & PyGSL_copy_pyarray_to_gslvector ;
_PyGSL_API[PyGSL_copy_pyarray_to_gslmatrix_NUM ] = (void *) & PyGSL_copy_pyarray_to_gslmatrix ;
_PyGSL_API[PyGSL_copy_gslvector_to_pyarray_NUM ] = (void *) & PyGSL_copy_gslvector_to_pyarray ;
_PyGSL_API[PyGSL_copy_gslmatrix_to_pyarray_NUM ] = (void *) & PyGSL_copy_gslmatrix_to_pyarray ;
_PyGSL_API[PyGSL_gsl_rng_from_pyobject_NUM ] = (void *) & PyGSL_gsl_rng_from_pyobject ;
_PyGSL_API[PyGSL_function_wrap_helper_NUM ] = (void *) & PyGSL_function_wrap_helper ;
_PyGSL_API[PyGSL_register_debug_flag_NUM ] = (void *) & PyGSL_register_debug_flag ;
_PyGSL_API[PyGSL_vector_or_double_NUM ] = (void *) & PyGSL_vector_or_double ;
_PyGSL_API[PyGSL_warning_NUM ] = (void *) & PyGSL_warning ;
_PyGSL_API[PyGSL_pyint_to_int_NUM ] = (void *) & PyGSL_pyint_to_int ;
_PyGSL_API[PyGSL_vector_check_NUM ] = (void *) & PyGSL_vector_check ;
_PyGSL_API[PyGSL_matrix_check_NUM ] = (void *) & PyGSL_matrix_check ;
_PyGSL_API[PyGSL_array_check_NUM ] = (void *) & PyGSL_array_check ;
}
DL_EXPORT(void) initinit(void)
{
PyObject *m = NULL, *d = NULL, *version=NULL, *date=NULL, *api = NULL;
m = Py_InitModule("pygsl.init", initMethods);
import_array();
if(m == NULL){
fprintf(stderr, "I could not init pygsl.init!");
return;
}
d = PyModule_GetDict(m);
if(d == NULL){
fprintf(stderr, "I could not get the module dict for pygsl.init!");
return;
}
PyGSL_init_api();
if(PyGSL_init_errno() != 0){
PyErr_SetString(PyExc_ImportError, "Failed to init errno handling!");
}
PyGSL_API = _PyGSL_API;
PyGSL_SET_ERROR_HANDLER();
api = PyCObject_FromVoidPtr((void *) PyGSL_API, NULL);
assert(api);
if (PyDict_SetItemString(d, "_PYGSL_API", api) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not add _PYGSL_API!");
return;
}
version = PyString_FromString(GSL_VERSION);
if(version == NULL){
fprintf(stderr, "I could not create the version string for pygsl.init!");
return;
}
if(PyDict_SetItemString(d, "compiled_gsl_version", version) != 0){
fprintf(stderr, "I could not add the compile version string to the module dict of pygsl.init!");
return;
}
version = PyString_FromString(gsl_version);
if(version == NULL){
fprintf(stderr, "I could not create the version string for pygsl.init!");
return;
}
if(PyDict_SetItemString(d, "run_gsl_version", version) != 0){
fprintf(stderr, "I could not add the run version string to the module dict of pygsl.init!");
return;
}
date = PyString_FromString(DATE " " TIME);
if(version == NULL){
fprintf(stderr, "I could not create the date string for pygsl.init!");
return;
}
if(PyDict_SetItemString(d, "compile_date", date) != 0){
fprintf(stderr, "I could not add the date version string to the module dict of pygsl.init!");
return;
}
if((debuglist = PyList_New(0)) == NULL){
fprintf(stderr, "Failed to init Debug list!\n");
}
/*
* These functions will be moved to the approbriate modules and the user will
* have to call them explicitly when needed.
*/
return;
}
| {
"alphanum_fraction": 0.6267974479,
"avg_line_length": 38.6066176471,
"ext": "c",
"hexsha": "d8106275cd753188cab47de5b5b6b20cbdd0d349",
"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/src/init/initmodule.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/src/init/initmodule.c",
"max_line_length": 122,
"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/src/init/initmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2874,
"size": 10501
} |
/* stable/stable_pdf.c
*
* Functions wrappers of GSL routines for random sample generation of
* alpha-stable random variable.
*
* Copyright (C) 2013. Javier Royuela del Val
* Federico Simmross Wattenberg
*
* 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; version 3 of the License.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*
* Javier Royuela del Val.
* E.T.S.I. Telecomunicación
* Universidad de Valladolid
* Paseo de Belén 15, 47002 Valladolid, Spain.
* jroyval@lpi.tel.uva.es
*/
#include "stable.h"
#include <gsl/gsl_randist.h>
void
stable_rnd_seed(StableDist * dist, unsigned long int s)
{
gsl_rng_set(dist->gslrand, s);
}
inline double
stable_rnd_point(StableDist *dist)
{
return dist->mu_1 +
gsl_ran_levy_skew(dist->gslrand, dist->sigma, dist->alpha, dist->beta);
}
void
stable_rnd(StableDist *dist, double *rnd, unsigned int n)
{
//double *rnd;
int i;
//rnd = (double*)malloc(n*sizeof(double));
if (rnd ==NULL) {
perror("stable_rnd: NULL output pointer");
return;
}
for(i=0;i<n;i++)
{
rnd[i]=stable_rnd_point(dist);
}
return;
}
| {
"alphanum_fraction": 0.6899320568,
"avg_line_length": 25.6984126984,
"ext": "c",
"hexsha": "555393d74fc68e29f0eed56bca44eb889a8cff06",
"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": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "TantraLabs/gonum",
"max_forks_repo_path": "stat/distuv/libs/libstable/stable/src/stable_rnd.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50",
"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": "TantraLabs/gonum",
"max_issues_repo_path": "stat/distuv/libs/libstable/stable/src/stable_rnd.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "TantraLabs/gonum",
"max_stars_repo_path": "stat/distuv/libs/libstable/stable/src/stable_rnd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 442,
"size": 1619
} |
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
#pragma once
#include <intsafe.h>
#include <gsl/gsl>
namespace arcana
{
void set_thread_name(DWORD threadId, gsl::czstring<> threadName);
}
| {
"alphanum_fraction": 0.714953271,
"avg_line_length": 15.2857142857,
"ext": "h",
"hexsha": "a7f1bf67394b74eede48e93c888f615b749816e0",
"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/Windows/arcana/threading/set_thread_name.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/Windows/arcana/threading/set_thread_name.h",
"max_line_length": 69,
"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/Windows/arcana/threading/set_thread_name.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": 53,
"size": 214
} |
/* vector/gsl_vector_complex_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_COMPLEX_DOUBLE_H__
#define __GSL_VECTOR_COMPLEX_DOUBLE_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_vector_complex.h>
#include <gsl/gsl_block_complex_double.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
double *data;
gsl_block_complex *block;
int owner;
} gsl_vector_complex;
typedef struct
{
gsl_vector_complex vector;
} _gsl_vector_complex_view;
typedef _gsl_vector_complex_view gsl_vector_complex_view;
typedef struct
{
gsl_vector_complex vector;
} _gsl_vector_complex_const_view;
typedef const _gsl_vector_complex_const_view gsl_vector_complex_const_view;
/* Allocation */
GSL_FUN gsl_vector_complex *gsl_vector_complex_alloc (const size_t n);
GSL_FUN gsl_vector_complex *gsl_vector_complex_calloc (const size_t n);
GSL_FUN gsl_vector_complex *
gsl_vector_complex_alloc_from_block (gsl_block_complex * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_complex *
gsl_vector_complex_alloc_from_vector (gsl_vector_complex * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_complex_free (gsl_vector_complex * v);
/* Views */
GSL_FUN _gsl_vector_complex_view
gsl_vector_complex_view_array (double *base,
size_t n);
GSL_FUN _gsl_vector_complex_view
gsl_vector_complex_view_array_with_stride (double *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_complex_const_view
gsl_vector_complex_const_view_array (const double *base,
size_t n);
GSL_FUN _gsl_vector_complex_const_view
gsl_vector_complex_const_view_array_with_stride (const double *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_complex_view
gsl_vector_complex_subvector (gsl_vector_complex *base,
size_t i,
size_t n);
GSL_FUN _gsl_vector_complex_view
gsl_vector_complex_subvector_with_stride (gsl_vector_complex *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_complex_const_view
gsl_vector_complex_const_subvector (const gsl_vector_complex *base,
size_t i,
size_t n);
GSL_FUN _gsl_vector_complex_const_view
gsl_vector_complex_const_subvector_with_stride (const gsl_vector_complex *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_view
gsl_vector_complex_real (gsl_vector_complex *v);
GSL_FUN _gsl_vector_view
gsl_vector_complex_imag (gsl_vector_complex *v);
GSL_FUN _gsl_vector_const_view
gsl_vector_complex_const_real (const gsl_vector_complex *v);
GSL_FUN _gsl_vector_const_view
gsl_vector_complex_const_imag (const gsl_vector_complex *v);
/* Operations */
GSL_FUN void gsl_vector_complex_set_zero (gsl_vector_complex * v);
GSL_FUN void gsl_vector_complex_set_all (gsl_vector_complex * v,
gsl_complex z);
GSL_FUN int gsl_vector_complex_set_basis (gsl_vector_complex * v, size_t i);
GSL_FUN int gsl_vector_complex_fread (FILE * stream,
gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_fwrite (FILE * stream,
const gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_fscanf (FILE * stream,
gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_fprintf (FILE * stream,
const gsl_vector_complex * v,
const char *format);
GSL_FUN int gsl_vector_complex_memcpy (gsl_vector_complex * dest, const gsl_vector_complex * src);
GSL_FUN int gsl_vector_complex_reverse (gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_swap (gsl_vector_complex * v, gsl_vector_complex * w);
GSL_FUN int gsl_vector_complex_swap_elements (gsl_vector_complex * v, const size_t i, const size_t j);
GSL_FUN int gsl_vector_complex_equal (const gsl_vector_complex * u,
const gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_isnull (const gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_ispos (const gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_isneg (const gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_isnonneg (const gsl_vector_complex * v);
GSL_FUN int gsl_vector_complex_add (gsl_vector_complex * a, const gsl_vector_complex * b);
GSL_FUN int gsl_vector_complex_sub (gsl_vector_complex * a, const gsl_vector_complex * b);
GSL_FUN int gsl_vector_complex_mul (gsl_vector_complex * a, const gsl_vector_complex * b);
GSL_FUN int gsl_vector_complex_div (gsl_vector_complex * a, const gsl_vector_complex * b);
GSL_FUN int gsl_vector_complex_scale (gsl_vector_complex * a, const gsl_complex x);
GSL_FUN int gsl_vector_complex_add_constant (gsl_vector_complex * a, const gsl_complex x);
GSL_FUN INLINE_DECL gsl_complex gsl_vector_complex_get (const gsl_vector_complex * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_complex_set (gsl_vector_complex * v, const size_t i, gsl_complex z);
GSL_FUN INLINE_DECL gsl_complex *gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i);
GSL_FUN INLINE_DECL const gsl_complex *gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
gsl_complex
gsl_vector_complex_get (const gsl_vector_complex * v,
const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
gsl_complex zero = {{0, 0}};
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero);
}
#endif
return *GSL_COMPLEX_AT (v, i);
}
INLINE_FUN
void
gsl_vector_complex_set (gsl_vector_complex * v,
const size_t i, gsl_complex z)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
*GSL_COMPLEX_AT (v, i) = z;
}
INLINE_FUN
gsl_complex *
gsl_vector_complex_ptr (gsl_vector_complex * v,
const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return GSL_COMPLEX_AT (v, i);
}
INLINE_FUN
const gsl_complex *
gsl_vector_complex_const_ptr (const gsl_vector_complex * v,
const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return GSL_COMPLEX_AT (v, i);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_COMPLEX_DOUBLE_H__ */
| {
"alphanum_fraction": 0.6650084794,
"avg_line_length": 33.7595419847,
"ext": "h",
"hexsha": "4b84c426598cd20834348fcf906ee884ad86e5b5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mharding01/augmented-neuromuscular-RT-running",
"max_forks_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_vector_complex_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mharding01/augmented-neuromuscular-RT-running",
"max_issues_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_vector_complex_double.h",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mharding01/augmented-neuromuscular-RT-running",
"max_stars_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_vector_complex_double.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1973,
"size": 8845
} |
/*
* rw.c -- Loesung des Randwertproblems mit der GSL
*
* (c) 2016 Prof Dr Andreas Mueller, Hochschule Rapperswil
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
static double g = 9.81;
static long fcounter = 0;
static int f(double x, const double y[], double f[], void *params) {
fcounter++;
double g = *(double *)params;
f[0] = y[2];
f[1] = y[3];
f[2] = 0;
f[3] = -g;
return GSL_SUCCESS;
}
static long dfcounter = 0;
static int df(double x, const double y[], double *dfdy, double dfdx[],
void *params) {
dfcounter++;
dfdy[0 * 4 + 0] = 0;
dfdy[1 * 4 + 0] = 0;
dfdy[2 * 4 + 0] = 0;
dfdy[3 * 4 + 0] = 0;
dfdy[0 * 4 + 1] = 0;
dfdy[1 * 4 + 1] = 0;
dfdy[2 * 4 + 1] = 0;
dfdy[3 * 4 + 1] = 0;
dfdy[0 * 4 + 2] = 1;
dfdy[1 * 4 + 2] = 0;
dfdy[2 * 4 + 2] = 0;
dfdy[3 * 4 + 2] = 0;
dfdy[0 * 4 + 3] = 0;
dfdy[1 * 4 + 4] = 1;
dfdy[2 * 4 + 4] = 0;
dfdy[3 * 4 + 4] = 0;
dfdx[0] = 0;
dfdx[1] = 0;
dfdx[2] = 0;
dfdx[3] = 0;
return GSL_SUCCESS;
}
static long Fcounter = 0;
static int F(double x, const double J[], double F[], void *params) {
Fcounter++;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
F[i * 4 + j] = J[(i + 2) * 4 + j];
}
}
for (int i = 2; i < 4; i++) {
for (int j = 0; j < 4; j++) {
F[i * 4 + j] = 0;
}
}
return GSL_SUCCESS;
}
int main(int argc, char *argv[]) {
gsl_odeiv2_system system = { f, df, 4, &g };
gsl_odeiv2_system Jsystem = { F, NULL, 16, NULL };
gsl_odeiv2_driver *driver
= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,
1e-6, 1e-6, 0.0);
gsl_odeiv2_driver *Jdriver
= gsl_odeiv2_driver_alloc_y_new(&Jsystem, gsl_odeiv2_step_rk8pd,
1e-6, 1e-6, 0.0);
double t = 0.0;
double vx = 8;
double vy = 7;
double tnext = 20 / vx;
double delta;
int counter = 0;
printf(" n v_y t x y dy/dv_y vynew delta\n");
do {
// compute the solution up to x = 1.5
t = 0;
double y[4] = { 0.0, 0.0, vx, vy };
int status = gsl_odeiv2_driver_apply(driver, &t, tnext, y);
if (status != GSL_SUCCESS) {
fprintf(stderr, "error: return value = %d\n", status);
}
// compute the jacobi matrix up to x = 1.5
t = 0;
double J[16] = { 1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0 };
status = gsl_odeiv2_driver_apply(Jdriver, &t, tnext, J);
if (status != GSL_SUCCESS) {
fprintf(stderr, "error: return value = %d\n", status);
}
// the derivative is J_{24}
double derivative = J[1 * 4 + 3];
// compute the newton correction
double vynew = vy - y[1] / derivative;
delta = vy - vynew;
printf("%2d%8.4f %8.4f %8.4f %10.6f %12.8f %12.8f %14.10f\n",
counter, vy, t, y[0], y[1], derivative, vynew, delta);
vy = vynew;
counter++;
} while ((fabs(delta) > 1e-6) && (counter <= 50));
printf("calls to f: %ld, to df: %ld, to F: %ld\n",
fcounter, dfcounter, Fcounter);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.5527103425,
"avg_line_length": 22.7803030303,
"ext": "c",
"hexsha": "1b3585103e60fc84aaf354c6f3718b3511faa386",
"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": "a7c452c44097ca851c661d3bc1093204ddae7f67",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "MatthiasRubin/SeminarDGL",
"max_forks_repo_path": "skript/chapters/examples/rw.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67",
"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": "MatthiasRubin/SeminarDGL",
"max_issues_repo_path": "skript/chapters/examples/rw.c",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "MatthiasRubin/SeminarDGL",
"max_stars_repo_path": "skript/chapters/examples/rw.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-05T07:48:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-05T07:48:28.000Z",
"num_tokens": 1320,
"size": 3007
} |
#ifndef GSLUtility_h
#define GSLUtility_h
/** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <QString>
#include <tnt/tnt_array1d.h>
#include <tnt/tnt_array1d_utils.h>
#include <tnt/tnt_array2d.h>
#include <tnt/tnt_array2d_utils.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
// Some GSL optimization on by default, off if DEBUG or SAFE_GSL is defined
#ifndef DEBUG
#ifndef SAFE_GSL
#define GSL_RANGE_CHECK_OFF 1
#endif
#endif
#include "IException.h"
namespace Isis {
namespace GSL {
/**
* @brief GSLUtility Provides top level interface to the GNU GSL
*
* Provides GSL setup and interface utilities. This object is provided for
* convenience of GSL vector and matrix manipulation as well as better
* management of GSL error handling.
*
* Without setting up GSL error handling, the GSL will abort when certain
* errors occur. This singleton object, an object where there is never more
* than one instance, an error handler is established that captures GSL errors
* and formats them into ISIS exceptions.
*
* There are many convenience methods provided for manipulation of GSL vectors
* and matrixs. Motivation for this is to address element access and
* efficient parameter and copy mechanisms (provided by the TNT library).
*
* There are some compile options on by default that help optimize the GSL.
* When the compile time DEBUG macro is set, range checking is turned on.
* Inline functions are also turned on by default unless the DEBUG macro is
* set. In addition, an additional compile time macro called SAFE_GSL is
* provided to emulate the DEBUG behavior, but does not invoke additional
* DEBUG behavior/side effects.
*
* See http://www.gnu.org/software/gsl/ for additional details on the GNU
* Scientific Library.
*
* @ingroup Utility
* @author 2008-05-06 Kris Becker
* @internal
* @history 2009-08-20 Kris Becker Completed documentation
*/
class GSLUtility {
public:
typedef TNT::Array1D<double> GSLVector;
typedef TNT::Array2D<double> GSLMatrix;
static GSLUtility *getInstance();
/** Tests if status is success */
inline bool success(int status) const {
return (status == GSL_SUCCESS);
}
/**
* @brief Returns GSL specific error text
*
* @param gsl_errno GSL error number
* @return QString Textual context of GSL error
*/
inline QString status(int gsl_errno) const {
return (QString(gsl_strerror(gsl_errno)));
}
void check(int gsl_status, const char *src = __FILE__, int line = __LINE__)
const;
size_t Rows(const gsl_matrix *m) const;
size_t Columns(const gsl_matrix *m) const;
size_t Rows(const GSLMatrix &m) const;
size_t Columns(const GSLMatrix &m) const;
size_t size(const gsl_vector *v) const;
size_t size(const gsl_matrix *m) const;
gsl_vector *vector(size_t n, bool zero = false) const;
gsl_matrix *matrix(size_t n1, size_t n2, bool zero = false) const;
gsl_matrix *identity(size_t n1, size_t n2) const;
void setIdentity(gsl_matrix *m) const;
void free(gsl_vector *v) const;
void free(gsl_matrix *m) const;
GSLVector gslToGSL(const gsl_vector *v) const;
GSLMatrix gslToGSL(const gsl_matrix *m) const;
gsl_vector *GSLTogsl(const GSLVector &v, gsl_vector *gv = 0) const;
gsl_matrix *GSLTogsl(const GSLMatrix &m, gsl_matrix *gm = 0) const;
private:
// Private Constructor/Destructor makes this a singleton
GSLUtility();
~GSLUtility() { }
static GSLUtility *_instance; //!< Singleton self-reference pointer
static void handler(const char *reason, const char *file, int line,
int gsl_errno);
};
} // namespace GSL
} // namespace Isis
#endif
| {
"alphanum_fraction": 0.6706763504,
"avg_line_length": 32.637037037,
"ext": "h",
"hexsha": "3a69856878857e8e3873db45682b483242dfffd0",
"lang": "C",
"max_forks_count": 164,
"max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z",
"max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "jlaura/isis3",
"max_forks_repo_path": "isis/src/base/objs/GSLUtility/GSLUtility.h",
"max_issues_count": 3825,
"max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "kdl222/ISIS3",
"max_issues_repo_path": "isis/src/base/objs/GSLUtility/GSLUtility.h",
"max_line_length": 83,
"max_stars_count": 134,
"max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "kdl222/ISIS3",
"max_stars_repo_path": "isis/src/base/objs/GSLUtility/GSLUtility.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z",
"num_tokens": 1022,
"size": 4406
} |
#include <stdio.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
#include <time.h>
#define N_OF_RUNS 10
#define RUSAGE_DIFF(r1, r2) \
((double) ((r1).tv_sec - (r2).tv_sec) + (double) ((r1).tv_nsec - (r2).tv_nsec)/(double)1E9)
gsl_matrix* random_matrix(size_t);
inline gsl_matrix* zero_matrix(const size_t size);
double* naive_test(size_t);
double* better_test(size_t);
double* dgemm_test(size_t);
void test_suite(size_t, size_t, size_t, const char*);
int main() {
srand48((unsigned int)time(NULL));
const char filename[] = "results_unoptimized.csv";
test_suite(100, 1000, 100, filename);
return 0;
}
void test_suite(const size_t from, const size_t to, const size_t step, const char* filename){
FILE* file = fopen(filename, "w");
if(file == NULL){
printf("Error opening file, exiting \r\n");
exit(EXIT_FAILURE);
}
fprintf(file, "METHOD,SIZE,TIME\r\n");
double* naive_result, * dgemm_result, * better_result;
for(size_t i = from; i <= to; i += step){
for(int j = 0; j < N_OF_RUNS; j++) {
naive_result = naive_test(i);
better_result = better_test(i);
dgemm_result = dgemm_test(i);
fprintf(file, "Naive,%d,%lf\r\n", (int) i, *naive_result);
fprintf(file, "Better,%d,%lf\r\n", (int) i, *better_result);
fprintf(file, "BLAS,%d,%lf\r\n", (int) i, *dgemm_result);
free(naive_result);
free(better_result);
free(dgemm_result);
}
}
fclose(file);
}
gsl_matrix* random_matrix(const size_t size) {
gsl_matrix* a = gsl_matrix_calloc(size, size);
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
gsl_matrix_set(a, (size_t)i, (size_t)j, drand48()*10);
return a;
}
gsl_matrix* zero_matrix(const size_t size) {
gsl_matrix* a = gsl_matrix_calloc(size, size);
return a;
}
double** random_double_matrix(const size_t size) {
double** a = calloc(size, sizeof(double*));
for(int i = 0; i < size; i++)
a[i] = calloc(size, sizeof(double));
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
a[i][j] = drand48() * 10;
return a;
}
double** zero_double_matrix(const size_t size) {
double** a = calloc(size, sizeof(double*));
for(int i = 0; i < size; i++)
a[i] = calloc(size, sizeof(double));
return a;
}
void free_double_matrix(double** matrix, const size_t size){
for(int i = 0; i < size; i++)
free(matrix[i]);
free(matrix);
}
double* naive_test(const size_t size) {
double** m_1 = random_double_matrix(size);
double** m_2 = random_double_matrix(size);
double** m_3 = zero_double_matrix(size);
printf("Multiplying matrices of size %d using naive method\r\n", (int)size);
struct timespec real_start, real_end;
clock_gettime(CLOCK_REALTIME, &real_start);
for(int k = 0; k < size; k++)
for(int j = 0; j < size; j++)
for(int i = 0; i < size; i++)
m_3[i][j] += m_1[i][k] * m_2[k][j];
clock_gettime(CLOCK_REALTIME, &real_end);
double* time = malloc(sizeof(double));
*time = RUSAGE_DIFF(real_end, real_start);
printf("Real time = %lf \r\n", *time);
free_double_matrix(m_1, size); free_double_matrix(m_2, size); free_double_matrix(m_3, size);
return time;
}
double* better_test(const size_t size) {
double** m_1 = random_double_matrix(size);
double** m_2 = random_double_matrix(size);
double** m_3 = zero_double_matrix(size);
printf("Multiplying matrices of size %d using better method\r\n", (int)size);
struct timespec real_start, real_end;
clock_gettime(CLOCK_REALTIME, &real_start);
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
for(int k = 0; k < size; k++)
m_3[i][j] += m_1[i][k] * m_2[k][j];
clock_gettime(CLOCK_REALTIME, &real_end);
double* time = malloc(sizeof(double));
*time = RUSAGE_DIFF(real_end, real_start);
printf("Real time = %lf \r\n", *time);
free_double_matrix(m_1, size); free_double_matrix(m_2, size); free_double_matrix(m_3, size);
return time;
}
double* dgemm_test(const size_t size) {
gsl_matrix* m_1 = random_matrix(size);
gsl_matrix* m_2 = random_matrix(size);
gsl_matrix* m_3 = zero_matrix(size);
printf("Multiplying matrices of size %d using BLAS\r\n", (int)size);
struct timespec real_start, real_end;
clock_gettime(CLOCK_REALTIME, &real_start);
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, m_1, m_2, 0.0, m_3);
clock_gettime(CLOCK_REALTIME, &real_end);
double* time = malloc(sizeof(double));
*time = RUSAGE_DIFF(real_end, real_start);
printf("Real time = %lf \r\n", *time);
gsl_matrix_free(m_1); gsl_matrix_free(m_2); gsl_matrix_free(m_3);
return time;
} | {
"alphanum_fraction": 0.6220989936,
"avg_line_length": 30.43125,
"ext": "c",
"hexsha": "6d88989bbf2330eefacc8f28ee4764e288fe340f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-12-13T10:05:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-13T10:05:17.000Z",
"max_forks_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kamilok1965/CMfSaT",
"max_forks_repo_path": "lab_3/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695",
"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": "kamilok1965/CMfSaT",
"max_issues_repo_path": "lab_3/main.c",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0d63eea12291789800df29b23bda0772f6af6695",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kamilok1965/CMfSaT",
"max_stars_repo_path": "lab_3/main.c",
"max_stars_repo_stars_event_max_datetime": "2019-01-09T18:59:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-09T18:59:11.000Z",
"num_tokens": 1419,
"size": 4869
} |
/*
* -----------------------------------------------------------------
* ell_lib.h
* Ellipsoid Library
* Version: 2.0
* Last Update: July 22, 2020
*
* Programmer: Americo Barbosa da Cunha Junior
* americo.cunhajr@gmail.com
* -----------------------------------------------------------------
* Copyright (c) 2010-2019, Americo Barbosa da Cunha Junior
* All rights reserved.
* -----------------------------------------------------------------
* This is the header file for BST_LIB module, a computational
* library to work with n-dimensional ellipsoids.
* -----------------------------------------------------------------
*/
#ifndef __ELL_LIB_H__
#define __ELL_LIB_H__
#include <stdlib.h>
#include <gsl/gsl_linalg.h>
#undef ELL_TOL
#define ELL_TOL 1.0e-7
#undef ELL_TRUE
#define ELL_TRUE 1
#undef ELL_FALSE
#define ELL_FALSE 0
/*
*------------------------------------------------------------
* function prototypes
*------------------------------------------------------------
*/
void ell_psd2eig(gsl_matrix *B,
gsl_matrix *V,
gsl_vector *lam);
void ell_psd2chol(gsl_matrix *B,
gsl_matrix *L);
void ell_eig2chol(gsl_matrix *V,
gsl_vector *sig,
gsl_matrix *L);
unsigned int ell_pt_in(gsl_vector *x,
gsl_vector *c,
gsl_matrix *L);
void ell_map2uhs(gsl_vector *x,
gsl_vector *c,
gsl_matrix *L,
gsl_vector *y);
void ell_pt_modify(gsl_vector *p,
gsl_vector *c,
gsl_matrix *L);
#endif /* __ELL_LIB_H__ */
| {
"alphanum_fraction": 0.4555822329,
"avg_line_length": 23.1388888889,
"ext": "h",
"hexsha": "6823576e98ea245ec2a20313a4c3284070673390",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z",
"max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "americocunhajr/CRFlowLib",
"max_forks_repo_path": "CRFlowLib-2.0/include/ell_lib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"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": "americocunhajr/CRFlowLib",
"max_issues_repo_path": "CRFlowLib-2.0/include/ell_lib.h",
"max_line_length": 67,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "americocunhajr/CRFlowLib",
"max_stars_repo_path": "CRFlowLib-2.0/include/ell_lib.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z",
"num_tokens": 371,
"size": 1666
} |
#include <gsl/gsl_integration.h>
#include <pygsl/error_helpers.h>
#include <pygsl/function_helpers.h>
#include <setjmp.h>
PyObject *module = NULL;
typedef struct{
PyObject * callback;
PyObject * args;
jmp_buf buffer;
}pygsl_function_args;
static double
pygsl_function_callback(double x, void *p)
{
double value;
int flag;
pygsl_diff_args *pargs = NULL;
pargs = (pygsl_diff_args *) p;
assert(pargs->callback);
assert(pargs->args);
flag = PyGSL_function_wrap_helper(x, &value, NULL, pargs->callback,
pargs->args, (char *)__FUNCTION__);
if(GSL_SUCCESS != flag){
longjmp(pargs->buffer, flag);
return gsl_nan();
}
return value;
}
PyObject *
integrate(PyObject *self, PyObject *pyargs)
{
PyObject *callback = NULL, *args = NULL;
pygsl_function_args cb_args;
gsl_function f;
int flag;
double a, b, epsabs, epsrel, result, abserr;
size_t neval;
if(!PyArg_ParseTuple(args, "Odddd|O", &callback, &a, &b, &epsabs, &epsrel, &args))
goto fail;
if(!Py_Callable(callback)){
pygsl_error("First argument must be a callable object!", GSL_EINVAL);
goto fail;
}
if(args == NULL){
args = Py_NONE;
}
f.f = pygsl_function_callback;
f.params = &cb_args;
cb_args.args = args;
cb_args.callback = callback;
flag = gsl_integration_qng (const *F, a, b, epsabs, epsrel, &result, &abserr, &neval)
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS)
goto fail;
return Py_BuildValue("(ddi)", result, abserr, neval);
fail:
Py_XDECREF(callback);
Py_XDECREF(args);
return NULL;
}
void
initintegrate(void)
{
PyObject *m;
m=Py_InitModule("integrate", mMethods);
module = m;
assert(m);
}
| {
"alphanum_fraction": 0.659315148,
"avg_line_length": 20.5119047619,
"ext": "c",
"hexsha": "bc269007b6be4cf5edf283932406c598fd4ed421",
"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/integrate.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/integrate.c",
"max_line_length": 90,
"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/integrate.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 485,
"size": 1723
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <gsl/gsl_math.h>
#include <inttypes.h>
#include "allvars.h"
#include "proto.h"
#include "domain.h"
#ifdef HAVE_HDF5
#include <hdf5.h>
#endif
/*! \file fof.c
* \brief parallel FoF group finder
*/
#ifdef FOF
#include "fof.h"
#ifdef SUBFIND
#include "subfind.h"
#endif
int Ngroups, TotNgroups;
long long TotNids;
struct group_properties *Group;
static struct fofdata_in
{
MyDouble Pos[3];
MyFloat Hsml;
MyIDType MinID;
MyIDType MinIDTask;
int NodeList[NODELISTLENGTH];
}
*FoFDataIn, *FoFDataGet;
static struct fofdata_out
{
MyFloat Distance;
MyIDType MinID;
MyIDType MinIDTask;
}
*FoFDataResult, *FoFDataOut;
static struct fof_particle_list
{
MyIDType MinID;
MyIDType MinIDTask;
int Pindex;
}
*FOF_PList;
static struct fof_group_list
{
MyIDType MinID;
MyIDType MinIDTask;
int LocCount;
int ExtCount;
#ifdef DENSITY_SPLIT_BY_TYPE
int LocDMCount;
int ExtDMCount;
#endif
int GrNr;
}
*FOF_GList;
static struct id_list
{
MyIDType ID;
unsigned int GrNr;
}
*ID_list;
static double LinkL;
static int NgroupsExt, Nids;
static MyIDType *Head, *Len, *Next, *Tail, *MinID, *MinIDTask;
static char *NonlocalFlag;
static float *fof_nearest_distance;
static float *fof_nearest_hsml;
void fof_fof(int num)
{
int i, ndm, start, lenloc, largestgroup, imax1, imax2, n;
double mass, masstot, rhodm, t0, t1;
struct unbind_data *d;
long long ndmtot;
#ifdef SUBFIND_READ_FOF
read_fof(num);
#endif
#ifdef SUBFIND_RESHUFFLE_CATALOGUE
read_subfind_ids();
if(All.TotN_gas > 0)
{
if(ThisTask == 0)
printf
("\nThe option SUBFIND_RESHUFFLE_CATALOGUE does not work with gas particles yet\n");
endrun(0);
}
t0 = second();
parallel_sort(P, NumPart, sizeof(struct particle_data), io_compare_P_GrNr_ID);
t1 = second();
if(ThisTask == 0)
printf("Ordering of particle-data took = %g sec\n", timediff(t0, t1));
strcat(All.SnapshotFileBase, "_subidorder");
savepositions(RestartSnapNum);
endrun(0);
#endif
if(ThisTask == 0)
{
printf("\nBegin to compute FoF group catalogues... (presently allocated=%g MB)\n",
AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
CPU_Step[CPU_MISC] += measure_time();
All.NumForcesSinceLastDomainDecomp = (long long) (All.TotNumPart * All.TreeDomainUpdateFrequency + 1);
domain_Decomposition();
force_treefree();
#ifdef ONLY_PRODUCE_HSML_FILES
subfind(num);
endrun(0);
#endif
for(i = 0, ndm = 0, mass = 0; i < NumPart; i++)
#ifdef DENSITY_SPLIT_BY_TYPE
{
if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))
ndm++;
if(((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE)))
mass += P[i].Mass;
}
#else
if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))
{
ndm++;
mass += P[i].Mass;
}
#endif
sumup_large_ints(1, &ndm, &ndmtot);
MPI_Allreduce(&mass, &masstot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
#ifdef DENSITY_SPLIT_BY_TYPE
rhodm = All.Omega0 * 3 * All.Hubble * All.Hubble / (8 * M_PI * All.G);
#else
rhodm = (All.Omega0 - All.OmegaBaryon) * 3 * All.Hubble * All.Hubble / (8 * M_PI * All.G);
#endif
LinkL = LINKLENGTH * pow(masstot / ndmtot / rhodm, 1.0 / 3);
if(ThisTask == 0)
{
printf("\nComoving linking length: %g ", LinkL);
printf("(presently allocated=%g MB)\n", AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
FOF_PList =
(struct fof_particle_list *) mymalloc(NumPart *
sizemax(sizeof(struct fof_particle_list), 3 * sizeof(MyIDType)));
MinID = (MyIDType *) FOF_PList;
MinIDTask = MinID + NumPart;
Head = MinIDTask + NumPart;
Len = (MyIDType *) mymalloc(NumPart * sizeof(MyIDType));
Next = (MyIDType *) mymalloc(NumPart * sizeof(MyIDType));
Tail = (MyIDType *) mymalloc(NumPart * sizeof(MyIDType));
CPU_Step[CPU_FOF] += measure_time();
if(ThisTask == 0)
printf("Tree construction.\n");
force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart);
/* build index list of particles of selected primary species */
d = (struct unbind_data *) mymalloc(NumPart * sizeof(struct unbind_data));
for(i = 0, n = 0; i < NumPart; i++)
if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))
d[n++].index = i;
force_treebuild(n, d);
myfree(d);
for(i = 0; i < NumPart; i++)
{
Head[i] = Tail[i] = i;
Len[i] = 1;
Next[i] = -1;
MinID[i] = P[i].ID;
MinIDTask[i] = ThisTask;
}
t0 = second();
fof_find_groups();
t1 = second();
if(ThisTask == 0)
printf("group finding took = %g sec\n", timediff(t0, t1));
t0 = second();
fof_find_nearest_dmparticle();
t1 = second();
if(ThisTask == 0)
printf("attaching gas and star particles to nearest dm particles took = %g sec\n", timediff(t0, t1));
t0 = second();
for(i = 0; i < NumPart; i++)
{
Next[i] = MinID[Head[i]];
Tail[i] = MinIDTask[Head[i]];
if(Tail[i] >= NTask) /* it appears that the Intel C 9.1 on Itanium2 produces incorrect code if
this if-statemet is omitted. Apparently, the compiler then joins the two loops,
but this is here not permitted because storage for FOF_PList actually overlaps
(on purpose) with MinID/MinIDTask/Head */
{
printf("oh no: ThisTask=%d i=%d Head[i]=%d NumPart=%d MinIDTask[Head[i]]=%d\n",
ThisTask, i, (int) Head[i], NumPart, (int) MinIDTask[Head[i]]);
fflush(stdout);
endrun(8812);
}
}
for(i = 0; i < NumPart; i++)
{
FOF_PList[i].MinID = Next[i];
FOF_PList[i].MinIDTask = Tail[i];
FOF_PList[i].Pindex = i;
}
force_treefree();
myfree(Tail);
myfree(Next);
myfree(Len);
FOF_GList = (struct fof_group_list *) mymalloc(sizeof(struct fof_group_list) * NumPart);
fof_compile_catalogue();
t1 = second();
if(ThisTask == 0)
printf("compiling local group data and catalogue took = %g sec\n", timediff(t0, t1));
MPI_Allreduce(&Ngroups, &TotNgroups, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
sumup_large_ints(1, &Nids, &TotNids);
if(TotNgroups > 0)
{
int largestloc = 0;
for(i = 0; i < NgroupsExt; i++)
if(FOF_GList[i].LocCount + FOF_GList[i].ExtCount > largestloc)
largestloc = FOF_GList[i].LocCount + FOF_GList[i].ExtCount;
MPI_Allreduce(&largestloc, &largestgroup, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
}
else
largestgroup = 0;
if(ThisTask == 0)
{
printf("\nTotal number of groups with at least %d particles: %d\n", FOF_GROUP_MIN_LEN, TotNgroups);
if(TotNgroups > 0)
{
printf("Largest group has %d particles.\n", largestgroup);
printf("Total number of particles in groups: %d%09d\n\n",
(int) (TotNids / 1000000000), (int) (TotNids % 1000000000));
}
}
t0 = second();
Group =
(struct group_properties *) mymalloc(sizeof(struct group_properties) *
IMAX(NgroupsExt, TotNgroups / NTask + 1));
if(ThisTask == 0)
{
printf("group properties are now allocated.. (presently allocated=%g MB)\n",
AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
for(i = 0, start = 0; i < NgroupsExt; i++)
{
while(FOF_PList[start].MinID < FOF_GList[i].MinID)
{
start++;
if(start > NumPart)
endrun(78);
}
if(FOF_PList[start].MinID != FOF_GList[i].MinID)
endrun(123);
for(lenloc = 0; start + lenloc < NumPart;)
if(FOF_PList[start + lenloc].MinID == FOF_GList[i].MinID)
lenloc++;
else
break;
Group[i].MinID = FOF_GList[i].MinID;
Group[i].MinIDTask = FOF_GList[i].MinIDTask;
fof_compute_group_properties(i, start, lenloc);
start += lenloc;
}
fof_exchange_group_data();
fof_finish_group_properties();
t1 = second();
if(ThisTask == 0)
printf("computation of group properties took = %g sec\n", timediff(t0, t1));
#ifdef BLACK_HOLES
if(num < 0)
fof_make_black_holes();
#endif
#ifdef BUBBLES
if(num < 0)
find_CM_of_biggest_group();
#endif
#ifdef MULTI_BUBBLES
if(num < 0)
multi_bubbles();
#endif
CPU_Step[CPU_FOF] += measure_time();
if(num >= 0)
{
fof_save_groups(num);
#ifdef SUBFIND
subfind(num);
#endif
}
myfree(Group);
myfree(FOF_GList);
myfree(FOF_PList);
if(ThisTask == 0)
{
printf("Finished computing FoF groups. (presently allocated=%g MB)\n\n",
AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
CPU_Step[CPU_FOF] += measure_time();
#ifdef SUBFIND
All.NumForcesSinceLastDomainDecomp = (long long) (All.TotNumPart * All.TreeDomainUpdateFrequency + 1);
domain_Decomposition();
#else
force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart);
#endif
if(ThisTask == 0)
printf("Tree construction.\n");
force_treebuild(NumPart, NULL);
TreeReconstructFlag = 0;
}
void fof_find_groups(void)
{
int i, j, ndone_flag, link_count, dummy, nprocessed;
int ndone, ngrp, sendTask, recvTask, place, nexport, nimport, link_across;
int npart, marked;
long long totmarked, totnpart;
long long link_across_tot, ntot;
MyIDType *MinIDOld;
char *FoFDataOut, *FoFDataResult, *MarkedFlag, *ChangedFlag;
double t0, t1;
if(ThisTask == 0)
{
printf("\nStart linking particles (presently allocated=%g MB)\n", AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
/* allocate buffers to arrange communication */
Ngblist = (int *) mymalloc(NumPart * sizeof(int));
All.BunchSize =
(int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +
2 * sizeof(struct fofdata_in)));
DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));
DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));
NonlocalFlag = (char *) mymalloc(NumPart * sizeof(char));
MarkedFlag = (char *) mymalloc(NumPart * sizeof(char));
ChangedFlag = (char *) mymalloc(NumPart * sizeof(char));
MinIDOld = (MyIDType *) mymalloc(NumPart * sizeof(MyIDType));
t0 = second();
/* first, link only among local particles */
for(i = 0, marked = 0, npart = 0; i < NumPart; i++)
{
if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))
{
fof_find_dmparticles_evaluate(i, -1, &dummy, &dummy);
npart++;
if(NonlocalFlag[i])
marked++;
}
}
sumup_large_ints(1, &marked, &totmarked);
sumup_large_ints(1, &npart, &totnpart);
t1 = second();
if(ThisTask == 0)
{
printf
("links on local processor done (took %g sec).\nMarked=%d%09d out of the %d%09d primaries which are linked\n",
timediff(t0, t1),
(int) (totmarked / 1000000000), (int) (totmarked % 1000000000),
(int) (totnpart / 1000000000), (int) (totnpart % 1000000000));
printf("\nlinking across processors (presently allocated=%g MB) \n",
AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
for(i = 0; i < NumPart; i++)
{
MinIDOld[i] = MinID[Head[i]];
MarkedFlag[i] = 1;
}
do
{
t0 = second();
for(i = 0; i < NumPart; i++)
{
ChangedFlag[i] = MarkedFlag[i];
MarkedFlag[i] = 0;
}
i = 0; /* begin with this index */
link_across = 0;
nprocessed = 0;
do
{
for(j = 0; j < NTask; j++)
{
Send_count[j] = 0;
Exportflag[j] = -1;
}
/* do local particles and prepare export list */
for(nexport = 0; i < NumPart; i++)
{
if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))
{
if(NonlocalFlag[i] && ChangedFlag[i])
{
if(fof_find_dmparticles_evaluate(i, 0, &nexport, Send_count) < 0)
break;
nprocessed++;
}
}
}
#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
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
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];
}
}
FoFDataGet = (struct fofdata_in *) mymalloc(nimport * sizeof(struct fofdata_in));
FoFDataIn = (struct fofdata_in *) mymalloc(nexport * sizeof(struct fofdata_in));
/* prepare particle data for export */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
FoFDataIn[j].Pos[0] = P[place].Pos[0];
FoFDataIn[j].Pos[1] = P[place].Pos[1];
FoFDataIn[j].Pos[2] = P[place].Pos[2];
FoFDataIn[j].MinID = MinID[Head[place]];
FoFDataIn[j].MinIDTask = MinIDTask[Head[place]];
memcpy(FoFDataIn[j].NodeList,
DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));
}
/* exchange particle data */
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(&FoFDataIn[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct fofdata_in), MPI_BYTE,
recvTask, TAG_DENS_A,
&FoFDataGet[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct fofdata_in), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
myfree(FoFDataIn);
FoFDataResult = (char *) mymalloc(nimport * sizeof(char));
FoFDataOut = (char *) mymalloc(nexport * sizeof(char));
/* now do the particles that were sent to us */
for(j = 0; j < nimport; j++)
{
link_count = fof_find_dmparticles_evaluate(j, 1, &dummy, &dummy);
link_across += link_count;
if(link_count)
FoFDataResult[j] = 1;
else
FoFDataResult[j] = 0;
}
/* exchange data */
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(&FoFDataResult[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(char),
MPI_BYTE, recvTask, TAG_DENS_B,
&FoFDataOut[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(char),
MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
/* need to mark the particle if it induced a link */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
if(FoFDataOut[j])
MarkedFlag[place] = 1;
}
myfree(FoFDataOut);
myfree(FoFDataResult);
myfree(FoFDataGet);
if(i >= NumPart)
ndone_flag = 1;
else
ndone_flag = 0;
MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
}
while(ndone < NTask);
sumup_large_ints(1, &link_across, &link_across_tot);
sumup_large_ints(1, &nprocessed, &ntot);
t1 = second();
if(ThisTask == 0)
{
printf("have done %d%09d cross links (processed %d%09d, took %g sec)\n",
(int) (link_across_tot / 1000000000), (int) (link_across_tot % 1000000000),
(int) (ntot / 1000000000), (int) (ntot % 1000000000), timediff(t0, t1));
fflush(stdout);
}
/* let's check out which particles have changed their MinID */
for(i = 0; i < NumPart; i++)
if(NonlocalFlag[i])
{
if(MinID[Head[i]] != MinIDOld[i])
MarkedFlag[i] = 1;
MinIDOld[i] = MinID[Head[i]];
}
}
while(link_across_tot > 0);
myfree(MinIDOld);
myfree(ChangedFlag);
myfree(MarkedFlag);
myfree(NonlocalFlag);
myfree(DataNodeList);
myfree(DataIndexTable);
myfree(Ngblist);
if(ThisTask == 0)
{
printf("Local groups found.\n\n");
fflush(stdout);
}
}
int fof_find_dmparticles_evaluate(int target, int mode, int *nexport, int *nsend_local)
{
int j, n, links, p, s, ss, listindex = 0;
int startnode, numngb_inbox;
MyDouble *pos;
links = 0;
if(mode == 0 || mode == -1)
pos = P[target].Pos;
else
pos = FoFDataGet[target].Pos;
if(mode == 0 || mode == -1)
{
startnode = All.MaxPart; /* root node */
}
else
{
startnode = FoFDataGet[target].NodeList[0];
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
while(startnode >= 0)
{
while(startnode >= 0)
{
if(mode == -1)
*nexport = 0;
numngb_inbox = ngb_treefind_fof_primary(pos, LinkL, target, &startnode, mode, nexport, nsend_local);
if(numngb_inbox < 0)
return -1;
if(mode == -1)
{
if(*nexport == 0)
NonlocalFlag[target] = 0;
else
NonlocalFlag[target] = 1;
}
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
if(mode == 0 || mode == -1)
{
if(Head[target] != Head[j]) /* only if not yet linked */
{
if(mode == 0)
endrun(87654);
if(Len[Head[target]] > Len[Head[j]]) /* p group is longer */
{
p = target;
s = j;
}
else
{
p = j;
s = target;
}
Next[Tail[Head[p]]] = Head[s];
Tail[Head[p]] = Tail[Head[s]];
Len[Head[p]] += Len[Head[s]];
ss = Head[s];
do
Head[ss] = Head[p];
while((ss = Next[ss]) >= 0);
if(MinID[Head[s]] < MinID[Head[p]])
{
MinID[Head[p]] = MinID[Head[s]];
MinIDTask[Head[p]] = MinIDTask[Head[s]];
}
}
}
else /* mode is 1 */
{
if(MinID[Head[j]] > FoFDataGet[target].MinID)
{
MinID[Head[j]] = FoFDataGet[target].MinID;
MinIDTask[Head[j]] = FoFDataGet[target].MinIDTask;
links++;
}
}
}
}
if(mode == 1)
{
listindex++;
if(listindex < NODELISTLENGTH)
{
startnode = FoFDataGet[target].NodeList[listindex];
if(startnode >= 0)
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
}
}
return links;
}
void fof_compile_catalogue(void)
{
int i, j, start, nimport, ngrp, sendTask, recvTask;
struct fof_group_list *get_FOF_GList;
/* sort according to MinID */
qsort(FOF_PList, NumPart, sizeof(struct fof_particle_list), fof_compare_FOF_PList_MinID);
for(i = 0; i < NumPart; i++)
{
FOF_GList[i].MinID = FOF_PList[i].MinID;
FOF_GList[i].MinIDTask = FOF_PList[i].MinIDTask;
if(FOF_GList[i].MinIDTask == ThisTask)
{
FOF_GList[i].LocCount = 1;
FOF_GList[i].ExtCount = 0;
#ifdef DENSITY_SPLIT_BY_TYPE
if(((1 << P[FOF_PList[i].Pindex].Type) & (FOF_PRIMARY_LINK_TYPES)))
FOF_GList[i].LocDMCount = 1;
else
FOF_GList[i].LocDMCount = 0;
FOF_GList[i].ExtDMCount = 0;
#endif
}
else
{
FOF_GList[i].LocCount = 0;
FOF_GList[i].ExtCount = 1;
#ifdef DENSITY_SPLIT_BY_TYPE
FOF_GList[i].LocDMCount = 0;
if(((1 << P[FOF_PList[i].Pindex].Type) & (FOF_PRIMARY_LINK_TYPES)))
FOF_GList[i].ExtDMCount = 1;
else
FOF_GList[i].ExtDMCount = 0;
#endif
}
}
/* eliminate duplicates in FOF_GList with respect to MinID */
if(NumPart)
NgroupsExt = 1;
else
NgroupsExt = 0;
for(i = 1, start = 0; i < NumPart; i++)
{
if(FOF_GList[i].MinID == FOF_GList[start].MinID)
{
FOF_GList[start].LocCount += FOF_GList[i].LocCount;
FOF_GList[start].ExtCount += FOF_GList[i].ExtCount;
#ifdef DENSITY_SPLIT_BY_TYPE
FOF_GList[start].LocDMCount += FOF_GList[i].LocDMCount;
FOF_GList[start].ExtDMCount += FOF_GList[i].ExtDMCount;
#endif
}
else
{
start = NgroupsExt;
FOF_GList[start] = FOF_GList[i];
NgroupsExt++;
}
}
/* sort the remaining ones according to task */
qsort(FOF_GList, NgroupsExt, sizeof(struct fof_group_list), fof_compare_FOF_GList_MinIDTask);
/* count how many we have of each task */
for(i = 0; i < NTask; i++)
Send_count[i] = 0;
for(i = 0; i < NgroupsExt; i++)
Send_count[FOF_GList[i].MinIDTask]++;
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)
{
Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];
if(j == ThisTask) /* we will not exchange the ones that are local */
Recv_count[j] = 0;
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];
}
}
get_FOF_GList = (struct fof_group_list *) mymalloc(nimport * sizeof(struct fof_group_list));
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 group info */
MPI_Sendrecv(&FOF_GList[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct fof_group_list), MPI_BYTE,
recvTask, TAG_DENS_A,
&get_FOF_GList[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct fof_group_list), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
for(i = 0; i < nimport; i++)
get_FOF_GList[i].MinIDTask = i;
/* sort the groups according to MinID */
qsort(FOF_GList, NgroupsExt, sizeof(struct fof_group_list), fof_compare_FOF_GList_MinID);
qsort(get_FOF_GList, nimport, sizeof(struct fof_group_list), fof_compare_FOF_GList_MinID);
/* merge the imported ones with the local ones */
for(i = 0, start = 0; i < nimport; i++)
{
while(FOF_GList[start].MinID < get_FOF_GList[i].MinID)
{
start++;
if(start >= NgroupsExt)
endrun(7973);
}
if(get_FOF_GList[i].LocCount != 0)
endrun(123);
if(FOF_GList[start].MinIDTask != ThisTask)
endrun(124);
FOF_GList[start].ExtCount += get_FOF_GList[i].ExtCount;
#ifdef DENSITY_SPLIT_BY_TYPE
FOF_GList[start].ExtDMCount += get_FOF_GList[i].ExtDMCount;
#endif
}
/* copy the size information back into the list, to inform the others */
for(i = 0, start = 0; i < nimport; i++)
{
while(FOF_GList[start].MinID < get_FOF_GList[i].MinID)
{
start++;
if(start >= NgroupsExt)
endrun(797831);
}
get_FOF_GList[i].ExtCount = FOF_GList[start].ExtCount;
get_FOF_GList[i].LocCount = FOF_GList[start].LocCount;
#ifdef DENSITY_SPLIT_BY_TYPE
get_FOF_GList[i].ExtDMCount = FOF_GList[start].ExtDMCount;
get_FOF_GList[i].LocDMCount = FOF_GList[start].LocDMCount;
#endif
}
/* sort the imported/exported list according to MinIDTask */
qsort(get_FOF_GList, nimport, sizeof(struct fof_group_list), fof_compare_FOF_GList_MinIDTask);
qsort(FOF_GList, NgroupsExt, sizeof(struct fof_group_list), fof_compare_FOF_GList_MinIDTask);
for(i = 0; i < nimport; i++)
get_FOF_GList[i].MinIDTask = ThisTask;
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 group info */
MPI_Sendrecv(&get_FOF_GList[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct fof_group_list), MPI_BYTE,
recvTask, TAG_DENS_A,
&FOF_GList[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct fof_group_list), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
myfree(get_FOF_GList);
/* eliminate all groups that are too small, and count local groups */
for(i = 0, Ngroups = 0, Nids = 0; i < NgroupsExt; i++)
{
#ifdef DENSITY_SPLIT_BY_TYPE
if(FOF_GList[i].LocDMCount + FOF_GList[i].ExtDMCount < FOF_GROUP_MIN_LEN)
#else
if(FOF_GList[i].LocCount + FOF_GList[i].ExtCount < FOF_GROUP_MIN_LEN)
#endif
{
FOF_GList[i] = FOF_GList[NgroupsExt - 1];
NgroupsExt--;
i--;
}
else
{
if(FOF_GList[i].MinIDTask == ThisTask)
{
Ngroups++;
Nids += FOF_GList[i].LocCount + FOF_GList[i].ExtCount;
}
}
}
/* sort the group list according to MinID */
qsort(FOF_GList, NgroupsExt, sizeof(struct fof_group_list), fof_compare_FOF_GList_MinID);
}
void fof_compute_group_properties(int gr, int start, int len)
{
int j, k, index;
double xyz[3];
Group[gr].Len = 0;
Group[gr].Mass = 0;
#ifdef SFR
Group[gr].Sfr = 0;
#endif
#ifdef BLACK_HOLES
Group[gr].BH_Mass = 0;
Group[gr].BH_Mdot = 0;
Group[gr].index_maxdens = Group[gr].task_maxdens = -1;
Group[gr].MaxDens = 0;
#endif
for(k = 0; k < 3; k++)
{
Group[gr].CM[k] = 0;
Group[gr].Vel[k] = 0;
Group[gr].FirstPos[k] = P[start].Pos[k];
}
for(k = 0; k < 6; k++)
{
Group[gr].LenType[k] = 0;
Group[gr].MassType[k] = 0;
}
for(k = 0; k < len; k++)
{
index = FOF_PList[start + k].Pindex;
Group[gr].Len++;
Group[gr].Mass += P[index].Mass;
Group[gr].LenType[P[index].Type]++;
Group[gr].MassType[P[index].Type] += P[index].Mass;
#ifdef SFR
if(P[index].Type == 0)
Group[gr].Sfr += SphP[index].Sfr;
#endif
#ifdef BLACK_HOLES
if(P[index].Type == 5)
{
Group[gr].BH_Mdot += P[index].BH_Mdot;
Group[gr].BH_Mass += P[index].BH_Mass;
}
if(P[index].Type == 0)
{
#ifdef WINDS
if(SphP[index].DelayTime == 0)
#endif
if(SphP[index].d.Density > Group[gr].MaxDens)
{
Group[gr].MaxDens = SphP[index].d.Density;
Group[gr].index_maxdens = index;
Group[gr].task_maxdens = ThisTask;
}
}
#endif
for(j = 0; j < 3; j++)
{
xyz[j] = P[index].Pos[j];
#ifdef PERIODIC
xyz[j] = fof_periodic(xyz[j] - P[start].Pos[j]);
#endif
Group[gr].CM[j] += P[index].Mass * xyz[j];
Group[gr].Vel[j] += P[index].Mass * P[index].Vel[j];
}
}
}
void fof_exchange_group_data(void)
{
struct group_properties *get_Group;
int i, j, ngrp, sendTask, recvTask, nimport, start;
double xyz[3];
/* sort the groups according to task */
qsort(Group, NgroupsExt, sizeof(struct group_properties), fof_compare_Group_MinIDTask);
/* count how many we have of each task */
for(i = 0; i < NTask; i++)
Send_count[i] = 0;
for(i = 0; i < NgroupsExt; i++)
Send_count[FOF_GList[i].MinIDTask]++;
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)
{
Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];
if(j == ThisTask) /* we will not exchange the ones that are local */
Recv_count[j] = 0;
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];
}
}
get_Group = (struct group_properties *) mymalloc(sizeof(struct group_properties) * nimport);
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 group data */
MPI_Sendrecv(&Group[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct group_properties), MPI_BYTE,
recvTask, TAG_DENS_A,
&get_Group[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct group_properties), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
/* sort the groups again according to MinID */
qsort(Group, NgroupsExt, sizeof(struct group_properties), fof_compare_Group_MinID);
qsort(get_Group, nimport, sizeof(struct group_properties), fof_compare_Group_MinID);
/* now add in the partial imported group data to the main ones */
for(i = 0, start = 0; i < nimport; i++)
{
while(Group[start].MinID < get_Group[i].MinID)
{
start++;
if(start >= NgroupsExt)
endrun(797890);
}
Group[start].Len += get_Group[i].Len;
Group[start].Mass += get_Group[i].Mass;
for(j = 0; j < 6; j++)
{
Group[start].LenType[j] += get_Group[i].LenType[j];
Group[start].MassType[j] += get_Group[i].MassType[j];
}
#ifdef SFR
Group[start].Sfr += get_Group[i].Sfr;
#endif
#ifdef BLACK_HOLES
Group[start].BH_Mdot += get_Group[i].BH_Mdot;
Group[start].BH_Mass += get_Group[i].BH_Mass;
if(get_Group[i].MaxDens > Group[start].MaxDens)
{
Group[start].MaxDens = get_Group[i].MaxDens;
Group[start].index_maxdens = get_Group[i].index_maxdens;
Group[start].task_maxdens = get_Group[i].task_maxdens;
}
#endif
for(j = 0; j < 3; j++)
{
xyz[j] = get_Group[i].CM[j] / get_Group[i].Mass + get_Group[i].FirstPos[j];
#ifdef PERIODIC
xyz[j] = fof_periodic(xyz[j] - Group[start].FirstPos[j]);
#endif
Group[start].CM[j] += get_Group[i].Mass * xyz[j];
Group[start].Vel[j] += get_Group[i].Vel[j];
}
}
myfree(get_Group);
}
void fof_finish_group_properties(void)
{
double cm[3];
int i, j, ngr;
for(i = 0; i < NgroupsExt; i++)
{
if(Group[i].MinIDTask == ThisTask)
{
for(j = 0; j < 3; j++)
{
Group[i].Vel[j] /= Group[i].Mass;
cm[j] = Group[i].CM[j] / Group[i].Mass;
#ifdef PERIODIC
cm[j] = fof_periodic_wrap(cm[j] + Group[i].FirstPos[j]);
#endif
Group[i].CM[j] = cm[j];
}
}
}
/* eliminate the non-local groups */
for(i = 0, ngr = NgroupsExt; i < ngr; i++)
{
if(Group[i].MinIDTask != ThisTask)
{
Group[i] = Group[ngr - 1];
i--;
ngr--;
}
}
if(ngr != Ngroups)
endrun(876889);
qsort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_MinID);
}
void fof_save_groups(int num)
{
int i, j, start, lenloc, nprocgroup, masterTask, groupTask, ngr, totlen;
long long totNids;
char buf[500];
double t0, t1;
if(ThisTask == 0)
{
printf("start global sorting of group catalogues\n");
fflush(stdout);
}
t0 = second();
/* assign group numbers (at this point, both Group and FOF_GList are sorted by MinID) */
for(i = 0; i < NgroupsExt; i++)
{
FOF_GList[i].LocCount += FOF_GList[i].ExtCount; /* total length */
FOF_GList[i].ExtCount = ThisTask; /* original task */
#ifdef DENSITY_SPLIT_BY_TYPE
FOF_GList[i].LocDMCount += FOF_GList[i].ExtDMCount; /* total length */
FOF_GList[i].ExtDMCount = ThisTask; /* not longer needed/used (hopefully) */
#endif
}
parallel_sort(FOF_GList, NgroupsExt, sizeof(struct fof_group_list),
fof_compare_FOF_GList_LocCountTaskDiffMinID);
for(i = 0, ngr = 0; i < NgroupsExt; i++)
{
if(FOF_GList[i].ExtCount == FOF_GList[i].MinIDTask)
ngr++;
FOF_GList[i].GrNr = ngr;
}
MPI_Allgather(&ngr, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD);
for(j = 1, Send_offset[0] = 0; j < NTask; j++)
Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];
for(i = 0; i < NgroupsExt; i++)
FOF_GList[i].GrNr += Send_offset[ThisTask];
MPI_Allreduce(&ngr, &i, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if(i != TotNgroups)
{
printf("i=%d\n", i);
endrun(123123);
}
/* bring the group list back into the original order */
parallel_sort(FOF_GList, NgroupsExt, sizeof(struct fof_group_list), fof_compare_FOF_GList_ExtCountMinID);
/* Assign the group numbers to the group properties array */
for(i = 0, start = 0; i < Ngroups; i++)
{
while(FOF_GList[start].MinID < Group[i].MinID)
{
start++;
if(start >= NgroupsExt)
endrun(7297890);
}
Group[i].GrNr = FOF_GList[start].GrNr;
}
/* sort the groups according to group-number */
parallel_sort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_GrNr);
/* fill in the offset-values */
for(i = 0, totlen = 0; i < Ngroups; i++)
{
if(i > 0)
Group[i].Offset = Group[i - 1].Offset + Group[i - 1].Len;
else
Group[i].Offset = 0;
totlen += Group[i].Len;
}
MPI_Allgather(&totlen, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD);
unsigned int *uoffset = mymalloc(NTask * sizeof(unsigned int));
for(j = 1, uoffset[0] = 0; j < NTask; j++)
uoffset[j] = uoffset[j - 1] + Send_count[j - 1];
for(i = 0; i < Ngroups; i++)
Group[i].Offset += uoffset[ThisTask];
myfree(uoffset);
/* prepare list of ids with assigned group numbers */
ID_list = mymalloc(sizeof(struct id_list) * NumPart);
#ifdef SUBFIND
for(i = 0; i < NumPart; i++)
P[i].GrNr = TotNgroups + 1; /* will mark particles that are not in any group */
#endif
for(i = 0, start = 0, Nids = 0; i < NgroupsExt; i++)
{
while(FOF_PList[start].MinID < FOF_GList[i].MinID)
{
start++;
if(start > NumPart)
endrun(78);
}
if(FOF_PList[start].MinID != FOF_GList[i].MinID)
endrun(1313);
for(lenloc = 0; start + lenloc < NumPart;)
if(FOF_PList[start + lenloc].MinID == FOF_GList[i].MinID)
{
ID_list[Nids].GrNr = FOF_GList[i].GrNr;
ID_list[Nids].ID = P[FOF_PList[start + lenloc].Pindex].ID;
#ifdef SUBFIND
P[FOF_PList[start + lenloc].Pindex].GrNr = FOF_GList[i].GrNr;
#endif
Nids++;
lenloc++;
}
else
break;
start += lenloc;
}
sumup_large_ints(1, &Nids, &totNids);
MPI_Allgather(&Nids, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD);
for(j = 1, Send_offset[0] = 0; j < NTask; j++)
Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];
if(totNids != TotNids)
{
printf("Task=%d Nids=%d totNids=%d TotNids=%d\n", ThisTask, Nids, (int) totNids, (int) TotNids);
endrun(12);
}
/* sort the particle IDs according to group-number */
parallel_sort(ID_list, Nids, sizeof(struct id_list), fof_compare_ID_list_GrNrID);
t1 = second();
if(ThisTask == 0)
{
printf("Group catalogues globally sorted. took = %g sec\n", timediff(t0, t1));
printf("starting saving of group catalogue\n");
fflush(stdout);
}
t0 = second();
if(ThisTask == 0)
{
sprintf(buf, "%s/groups_%03d", All.OutputDir, num);
mkdir(buf, 02755);
}
MPI_Barrier(MPI_COMM_WORLD);
if(NTask < All.NumFilesWrittenInParallel)
{
printf
("Fatal error.\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\n");
endrun(241931);
}
nprocgroup = NTask / All.NumFilesWrittenInParallel;
if((NTask % All.NumFilesWrittenInParallel))
nprocgroup++;
masterTask = (ThisTask / nprocgroup) * nprocgroup;
for(groupTask = 0; groupTask < nprocgroup; groupTask++)
{
if(ThisTask == (masterTask + groupTask)) /* ok, it's this processor's turn */
fof_save_local_catalogue(num);
MPI_Barrier(MPI_COMM_WORLD); /* wait inside the group */
}
myfree(ID_list);
t1 = second();
if(ThisTask == 0)
{
printf("Group catalogues saved. took = %g sec\n", timediff(t0, t1));
fflush(stdout);
}
}
void fof_save_local_catalogue(int num)
{
FILE *fd;
float *mass, *cm, *vel;
char fname[500];
int i, j, *len;
MyIDType *ids;
sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "group_tab", num, ThisTask);
if(!(fd = fopen(fname, "w")))
{
printf("can't open file `%s`\n", fname);
endrun(1183);
}
my_fwrite(&Ngroups, sizeof(int), 1, fd);
my_fwrite(&TotNgroups, sizeof(int), 1, fd);
my_fwrite(&Nids, sizeof(int), 1, fd);
my_fwrite(&TotNids, sizeof(long long), 1, fd);
my_fwrite(&NTask, sizeof(int), 1, fd);
/* group len */
len = mymalloc(Ngroups * sizeof(int));
for(i = 0; i < Ngroups; i++)
len[i] = Group[i].Len;
my_fwrite(len, Ngroups, sizeof(int), fd);
myfree(len);
/* offset into id-list */
len = mymalloc(Ngroups * sizeof(int));
for(i = 0; i < Ngroups; i++)
len[i] = Group[i].Offset;
my_fwrite(len, Ngroups, sizeof(int), fd);
myfree(len);
/* mass */
mass = mymalloc(Ngroups * sizeof(float));
for(i = 0; i < Ngroups; i++)
mass[i] = Group[i].Mass;
my_fwrite(mass, Ngroups, sizeof(float), fd);
myfree(mass);
/* CM */
cm = mymalloc(Ngroups * 3 * sizeof(float));
for(i = 0; i < Ngroups; i++)
for(j = 0; j < 3; j++)
cm[i * 3 + j] = Group[i].CM[j];
my_fwrite(cm, Ngroups, 3 * sizeof(float), fd);
myfree(cm);
/* vel */
vel = mymalloc(Ngroups * 3 * sizeof(float));
for(i = 0; i < Ngroups; i++)
for(j = 0; j < 3; j++)
vel[i * 3 + j] = Group[i].Vel[j];
my_fwrite(vel, Ngroups, 3 * sizeof(float), fd);
myfree(vel);
/* group len for each type */
len = mymalloc(Ngroups * 6 * sizeof(int));
for(i = 0; i < Ngroups; i++)
for(j = 0; j < 6; j++)
len[i * 6 + j] = Group[i].LenType[j];
my_fwrite(len, Ngroups, 6 * sizeof(int), fd);
myfree(len);
/* group mass for each type */
mass = mymalloc(Ngroups * 6 * sizeof(int));
for(i = 0; i < Ngroups; i++)
for(j = 0; j < 6; j++)
mass[i * 6 + j] = Group[i].MassType[j];
my_fwrite(mass, Ngroups, 6 * sizeof(float), fd);
myfree(mass);
#ifdef SFR
/* sfr */
mass = mymalloc(Ngroups * sizeof(float));
for(i = 0; i < Ngroups; i++)
mass[i] = Group[i].Sfr;
my_fwrite(mass, Ngroups, sizeof(float), fd);
myfree(mass);
#endif
#ifdef BLACK_HOLES
/* BH_Mass */
mass = mymalloc(Ngroups * sizeof(float));
for(i = 0; i < Ngroups; i++)
mass[i] = Group[i].BH_Mass;
my_fwrite(mass, Ngroups, sizeof(float), fd);
myfree(mass);
/* BH_Mdot */
mass = mymalloc(Ngroups * sizeof(float));
for(i = 0; i < Ngroups; i++)
mass[i] = Group[i].BH_Mdot;
my_fwrite(mass, Ngroups, sizeof(float), fd);
myfree(mass);
#endif
fclose(fd);
ids = (MyIDType *) ID_list;
for(i = 0; i < Nids; i++)
ids[i] = ID_list[i].ID;
sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "group_ids", num, ThisTask);
if(!(fd = fopen(fname, "w")))
{
printf("can't open file `%s`\n", fname);
endrun(1184);
}
my_fwrite(&Ngroups, sizeof(int), 1, fd);
my_fwrite(&TotNgroups, sizeof(int), 1, fd);
my_fwrite(&Nids, sizeof(int), 1, fd);
my_fwrite(&TotNids, sizeof(long long), 1, fd);
my_fwrite(&NTask, sizeof(int), 1, fd);
my_fwrite(&Send_offset[ThisTask], sizeof(int), 1, fd); /* this is the number of IDs in previous files */
my_fwrite(ids, sizeof(MyIDType), Nids, fd);
fclose(fd);
}
void fof_find_nearest_dmparticle(void)
{
int i, j, n, ntot, dummy;
int ndone, ndone_flag, ngrp, sendTask, recvTask, place, nexport, nimport, npleft, iter;
if(ThisTask == 0)
{
printf("Start finding nearest dm-particle (presently allocated=%g MB)\n",
AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
fof_nearest_distance = (float *) mymalloc(sizeof(float) * NumPart);
fof_nearest_hsml = (float *) mymalloc(sizeof(float) * NumPart);
for(n = 0; n < NumPart; n++)
{
if(((1 << P[n].Type) & (FOF_SECONDARY_LINK_TYPES)))
{
fof_nearest_distance[n] = 1.0e30;
fof_nearest_hsml[n] = 0.1 * LinkL;
}
}
/* allocate buffers to arrange communication */
Ngblist = (int *) mymalloc(NumPart * sizeof(int));
All.BunchSize =
(int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +
sizeof(struct fofdata_in) + sizeof(struct fofdata_out) +
sizemax(sizeof(struct fofdata_in), sizeof(struct fofdata_out))));
DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));
DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));
iter = 0;
/* we will repeat the whole thing for those particles where we didn't find enough neighbours */
do
{
i = 0; /* beginn with this index */
do
{
for(j = 0; j < NTask; j++)
{
Send_count[j] = 0;
Exportflag[j] = -1;
}
/* do local particles and prepare export list */
for(nexport = 0; i < NumPart; i++)
if(((1 << P[i].Type) & (FOF_SECONDARY_LINK_TYPES)))
{
if(fof_nearest_distance[i] > 1.0e29)
{
if(fof_find_nearest_dmparticle_evaluate(i, 0, &nexport, Send_count) < 0)
break;
}
}
#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
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
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];
}
}
FoFDataGet = (struct fofdata_in *) mymalloc(nimport * sizeof(struct fofdata_in));
FoFDataIn = (struct fofdata_in *) mymalloc(nexport * sizeof(struct fofdata_in));
if(ThisTask == 0)
{
printf("still finding nearest... (presently allocated=%g MB)\n",
AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
FoFDataIn[j].Pos[0] = P[place].Pos[0];
FoFDataIn[j].Pos[1] = P[place].Pos[1];
FoFDataIn[j].Pos[2] = P[place].Pos[2];
FoFDataIn[j].Hsml = fof_nearest_hsml[place];
memcpy(FoFDataIn[j].NodeList,
DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));
}
/* exchange particle data */
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(&FoFDataIn[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct fofdata_in), MPI_BYTE,
recvTask, TAG_DENS_A,
&FoFDataGet[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct fofdata_in), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
myfree(FoFDataIn);
FoFDataResult = (struct fofdata_out *) mymalloc(nimport * sizeof(struct fofdata_out));
FoFDataOut = (struct fofdata_out *) mymalloc(nexport * sizeof(struct fofdata_out));
for(j = 0; j < nimport; j++)
{
fof_find_nearest_dmparticle_evaluate(j, 1, &dummy, &dummy);
}
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(&FoFDataResult[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct fofdata_out),
MPI_BYTE, recvTask, TAG_DENS_B,
&FoFDataOut[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct fofdata_out),
MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
if(FoFDataOut[j].Distance < fof_nearest_distance[place])
{
fof_nearest_distance[place] = FoFDataOut[j].Distance;
MinID[place] = FoFDataOut[j].MinID;
MinIDTask[place] = FoFDataOut[j].MinIDTask;
}
}
if(i >= NumPart)
ndone_flag = 1;
else
ndone_flag = 0;
MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
myfree(FoFDataOut);
myfree(FoFDataResult);
myfree(FoFDataGet);
}
while(ndone < NTask);
/* do final operations on results */
for(i = 0, npleft = 0; i < NumPart; i++)
{
if(((1 << P[i].Type) & (FOF_SECONDARY_LINK_TYPES)))
{
if(fof_nearest_distance[i] > 1.0e29)
{
/* need to redo this particle */
npleft++;
fof_nearest_hsml[i] *= 2.0;
if(iter >= MAXITER - 10)
{
printf("i=%d task=%d ID=%d Hsml=%g pos=(%g|%g|%g)\n",
i, ThisTask, (int) P[i].ID, fof_nearest_hsml[i],
P[i].Pos[0], P[i].Pos[1], P[i].Pos[2]);
fflush(stdout);
}
}
}
}
MPI_Allreduce(&npleft, &ntot, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if(ntot > 0)
{
iter++;
if(iter > 0 && ThisTask == 0)
{
printf("fof-nearest iteration %d: need to repeat for %d particles.\n", iter, ntot);
fflush(stdout);
}
if(iter > MAXITER)
{
printf("failed to converge in fof-nearest\n");
fflush(stdout);
endrun(1159);
}
}
}
while(ntot > 0);
myfree(DataNodeList);
myfree(DataIndexTable);
myfree(Ngblist);
myfree(fof_nearest_hsml);
myfree(fof_nearest_distance);
if(ThisTask == 0)
{
printf("done finding nearest dm-particle\n");
fflush(stdout);
}
}
int fof_find_nearest_dmparticle_evaluate(int target, int mode, int *nexport, int *nsend_local)
{
int j, n, index, listindex = 0;
int startnode, numngb_inbox;
double h, r2max;
double dx, dy, dz, r2;
MyDouble *pos;
if(mode == 0)
{
pos = P[target].Pos;
h = fof_nearest_hsml[target];
}
else
{
pos = FoFDataGet[target].Pos;
h = FoFDataGet[target].Hsml;
}
index = -1;
r2max = 1.0e30;
if(mode == 0)
{
startnode = All.MaxPart; /* root node */
}
else
{
startnode = FoFDataGet[target].NodeList[0];
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
while(startnode >= 0)
{
while(startnode >= 0)
{
numngb_inbox = ngb_treefind_fof_primary(pos, 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 < r2max && r2 < h * h)
{
index = j;
r2max = r2;
}
}
}
if(mode == 1)
{
listindex++;
if(listindex < NODELISTLENGTH)
{
startnode = FoFDataGet[target].NodeList[listindex];
if(startnode >= 0)
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
}
}
if(mode == 0)
{
if(index >= 0)
{
fof_nearest_distance[target] = sqrt(r2max);
MinID[target] = MinID[Head[index]];
MinIDTask[target] = MinIDTask[Head[index]];
}
}
else
{
if(index >= 0)
{
FoFDataResult[target].Distance = sqrt(r2max);
FoFDataResult[target].MinID = MinID[Head[index]];
FoFDataResult[target].MinIDTask = MinIDTask[Head[index]];
}
else
FoFDataResult[target].Distance = 2.0e30;
}
return 0;
}
#ifdef BLACK_HOLES
void fof_make_black_holes(void)
{
int i, j, n, ntot;
int nexport, nimport, sendTask, recvTask, level;
int *import_indices, *export_indices;
double massDMpart;
if(All.MassTable[1] > 0)
massDMpart = All.MassTable[1];
else
massDMpart = All.massDMpart;
for(n = 0; n < NTask; n++)
Send_count[n] = 0;
for(i = 0; i < Ngroups; i++)
{
if(Group[i].LenType[1] * massDMpart >=
(All.Omega0 - All.OmegaBaryon) / All.Omega0 * All.MinFoFMassForNewSeed)
if(Group[i].LenType[5] == 0)
{
if(Group[i].index_maxdens >= 0)
Send_count[Group[i].task_maxdens]++;
}
}
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
for(j = 0, nimport = nexport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)
{
Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];
nexport += Send_count[j];
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];
}
}
import_indices = mymalloc(nimport * sizeof(int));
export_indices = mymalloc(nexport * sizeof(int));
for(n = 0; n < NTask; n++)
Send_count[n] = 0;
for(i = 0; i < Ngroups; i++)
{
if(Group[i].LenType[1] * massDMpart >=
(All.Omega0 - All.OmegaBaryon) / All.Omega0 * All.MinFoFMassForNewSeed)
if(Group[i].LenType[5] == 0)
{
if(Group[i].index_maxdens >= 0)
export_indices[Send_offset[Group[i].task_maxdens] +
Send_count[Group[i].task_maxdens]++] = Group[i].index_maxdens;
}
}
memcpy(&import_indices[Recv_offset[ThisTask]], &export_indices[Send_offset[ThisTask]],
Send_count[ThisTask] * sizeof(int));
for(level = 1; level < (1 << PTask); level++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ level;
if(recvTask < NTask)
MPI_Sendrecv(&export_indices[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(int),
MPI_BYTE, recvTask, TAG_FOF_E,
&import_indices[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(int),
MPI_BYTE, recvTask, TAG_FOF_E, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
MPI_Allreduce(&nimport, &ntot, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if(ThisTask == 0)
{
printf("\nMaking %d new black hole particles\n\n", ntot);
fflush(stdout);
}
All.TotBHs += ntot;
for(n = 0; n < nimport; n++)
{
if(P[import_indices[n]].Type != 0)
endrun(7772);
P[import_indices[n]].Type = 5; /* make it a black hole particle */
#ifdef STELLARAGE
P[import_indices[n]].StellarAge = All.Time;
#endif
P[import_indices[n]].BH_Mass = All.SeedBlackHoleMass;
P[import_indices[n]].BH_Mdot = 0;
#ifdef BH_COUNTPROGS
P[import_indices[n]].BH_CountProgs = 1;
#endif
#ifdef BH_BUBBLES
P[import_indices[n]].BH_Mass_bubbles = All.SeedBlackHoleMass;
P[import_indices[n]].BH_Mass_ini = All.SeedBlackHoleMass;
#ifdef UNIFIED_FEEDBACK
P[import_indices[n]].BH_Mass_radio = All.SeedBlackHoleMass;
#endif
#endif
Stars_converted++;
TimeBinCountSph[P[import_indices[n]].TimeBin]--;
}
All.TotN_gas -= ntot;
myfree(export_indices);
myfree(import_indices);
}
#endif
#ifdef BUBBLES
void find_CM_of_biggest_group(void)
{
int i, rootcpu;
struct group_properties BiggestGroup;
parallel_sort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_Len);
/* the biggest group will now be the first group on the first cpu that has any groups */
MPI_Allgather(&Ngroups, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD);
for(rootcpu = 0; Send_count[rootcpu] == 0 && rootcpu < NTask - 1; rootcpu++);
if(rootcpu == ThisTask)
BiggestGroup = Group[0];
/* bring groups back into original order */
parallel_sort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_MinIDTask_MinID);
MPI_Bcast(&BiggestGroup, sizeof(struct group_properties), MPI_BYTE, rootcpu, MPI_COMM_WORLD);
All.BiggestGroupLen = BiggestGroup.Len;
for(i = 0; i < 3; i++)
All.BiggestGroupCM[i] = BiggestGroup.CM[i];
All.BiggestGroupMass = BiggestGroup.Mass;
if(ThisTask == 0)
{
printf("Biggest group length has %d particles.\n", All.BiggestGroupLen);
printf("CM of biggest group is: (%g|%g|%g)\n", All.BiggestGroupCM[0], All.BiggestGroupCM[1],
All.BiggestGroupCM[2]);
printf("Mass of biggest group is: %g\n", All.BiggestGroupMass);
}
}
#endif
#ifdef MULTI_BUBBLES
void multi_bubbles(void)
{
double phi, theta;
double dx, dy, dz, rr, r2, dE;
double E_bubble, totE_bubble, hubble_a = 0.0;
double BubbleDistance, BubbleRadius, BubbleEnergy;
MyFloat Mass_bubble, totMass_bubble;
MyFloat pos[3];
int numngb, tot_numngb, startnode, numngb_inbox;
int n, i, j, k, l, dummy;
int nheat, tot_nheat;
int eff_nheat, tot_eff_nheat;
double *GroupMassType_common, *GroupMassType_dum;
float *GroupCM_common_x, *GroupCM_dum_x;
float *GroupCM_common_y, *GroupCM_dum_y;
float *GroupCM_common_z, *GroupCM_dum_z;
int logical;
int *nn_heat, *disp;
double massDMpart;
if(All.MassTable[1] > 0)
massDMpart = All.MassTable[1];
else
massDMpart = All.massDMpart;
if(All.ComovingIntegrationOn)
{
hubble_a = hubble_function(All.Time) / All.Hubble;
}
nheat = tot_nheat = 0;
eff_nheat = tot_eff_nheat = 0;
logical = 0;
for(k = 0; k < Ngroups; k++)
{
if(massDMpart > 0)
{
if(Group[k].LenType[1] * massDMpart >=
(All.Omega0 - All.OmegaBaryon) / All.Omega0 * All.MinFoFMassForNewSeed)
nheat++;
}
else
{
printf("The DM particles mass is zero! I will stop.\n");
endrun(0);
}
}
MPI_Allreduce(&nheat, &tot_nheat, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if(ThisTask == 0)
printf("The total number of clusters to heat is: %d\n", tot_nheat);
nn_heat = mymalloc(NTask * sizeof(int));
disp = mymalloc(NTask * sizeof(int));
MPI_Allgather(&nheat, 1, MPI_INT, nn_heat, 1, MPI_INT, MPI_COMM_WORLD);
for(k = 1, disp[0] = 0; k < NTask; k++)
disp[k] = disp[k - 1] + nn_heat[k - 1];
if(tot_nheat > 0)
{
GroupMassType_common = mymalloc(tot_nheat * sizeof(double));
GroupMassType_dum = mymalloc(nheat * sizeof(double));
GroupCM_common_x = mymalloc(tot_nheat * sizeof(float));
GroupCM_dum_x = mymalloc(nheat * sizeof(float));
GroupCM_common_y = mymalloc(tot_nheat * sizeof(float));
GroupCM_dum_y = mymalloc(nheat * sizeof(float));
GroupCM_common_z = mymalloc(tot_nheat * sizeof(float));
GroupCM_dum_z = mymalloc(nheat * sizeof(float));
for(k = 0, i = 0; k < Ngroups; k++)
{
if(massDMpart > 0)
{
if(Group[k].LenType[1] * massDMpart >=
(All.Omega0 - All.OmegaBaryon) / All.Omega0 * All.MinFoFMassForNewSeed)
{
GroupCM_dum_x[i] = Group[k].CM[0];
GroupCM_dum_y[i] = Group[k].CM[1];
GroupCM_dum_z[i] = Group[k].CM[2];
GroupMassType_dum[i] = Group[k].Mass;
i++;
}
}
else
{
printf("The DM particles mass is zero! I will stop.\n");
endrun(0);
}
}
MPI_Allgatherv(GroupMassType_dum, nheat, MPI_DOUBLE, GroupMassType_common, nn_heat, disp, MPI_DOUBLE,
MPI_COMM_WORLD);
MPI_Allgatherv(GroupCM_dum_x, nheat, MPI_FLOAT, GroupCM_common_x, nn_heat, disp, MPI_FLOAT,
MPI_COMM_WORLD);
MPI_Allgatherv(GroupCM_dum_y, nheat, MPI_FLOAT, GroupCM_common_y, nn_heat, disp, MPI_FLOAT,
MPI_COMM_WORLD);
MPI_Allgatherv(GroupCM_dum_z, nheat, MPI_FLOAT, GroupCM_common_z, nn_heat, disp, MPI_FLOAT,
MPI_COMM_WORLD);
for(l = 0; l < tot_nheat; l++)
{
if(All.ComovingIntegrationOn > 0)
{
BubbleDistance =
All.BubbleDistance * 1. / All.Time * pow(GroupMassType_common[l] / All.ClusterMass200,
1. / 3.) / pow(hubble_a, 2. / 3.);
BubbleRadius =
All.BubbleRadius * 1. / All.Time * pow(GroupMassType_common[l] / All.ClusterMass200,
1. / 3.) / pow(hubble_a, 2. / 3.);
BubbleEnergy =
All.BubbleEnergy * pow(GroupMassType_common[l] / All.ClusterMass200, 5. / 3.) * pow(hubble_a,
2. / 3.);
phi = theta = rr = 0.0;
phi = 2 * M_PI * get_random_number(0);
theta = acos(2 * get_random_number(0) - 1);
rr = pow(get_random_number(0), 1. / 3.) * BubbleDistance;
pos[0] = pos[1] = pos[2] = 0.0;
pos[0] = sin(theta) * cos(phi);
pos[1] = sin(theta) * sin(phi);
pos[2] = cos(theta);
for(k = 0; k < 3; k++)
pos[k] *= rr;
pos[0] += GroupCM_common_x[l];
pos[1] += GroupCM_common_y[l];
pos[2] += GroupCM_common_z[l];
/* First, let's see how many particles are in the bubble */
Ngblist = (int *) mymalloc(NumPart * sizeof(int));
numngb = 0;
E_bubble = 0.;
Mass_bubble = 0.;
startnode = All.MaxPart;
do
{
numngb_inbox = ngb_treefind_variable(pos, BubbleRadius, -1, &startnode, 0, &dummy, &dummy);
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 < BubbleRadius * BubbleRadius)
{
numngb++;
if(All.ComovingIntegrationOn)
E_bubble +=
SphP[j].Entropy * P[j].Mass * pow(SphP[j].d.Density / pow(All.Time, 3),
GAMMA_MINUS1) / GAMMA_MINUS1;
else
E_bubble +=
SphP[j].Entropy * P[j].Mass * pow(SphP[j].d.Density,
GAMMA_MINUS1) / GAMMA_MINUS1;
Mass_bubble += P[j].Mass;
}
}
}
while(startnode >= 0);
tot_numngb = totE_bubble = totMass_bubble = 0.0;
MPI_Allreduce(&numngb, &tot_numngb, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&E_bubble, &totE_bubble, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&Mass_bubble, &totMass_bubble, 1, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD);
if(tot_numngb == 0)
{
tot_numngb = 1;
totMass_bubble = 1;
totE_bubble = 1;
logical = 0;
}
else
{
logical = 1;
eff_nheat++;
}
totE_bubble *= All.UnitEnergy_in_cgs;
if(ThisTask == 0)
{
if(logical == 1)
{
printf("%g, %g, %g, %g, %d, %g, %g, %g\n", GroupMassType_common[l], GroupCM_common_x[l],
GroupCM_common_y[l], GroupCM_common_z[l], tot_numngb, BubbleRadius, BubbleEnergy,
(BubbleEnergy + totE_bubble) / totE_bubble);
}
fflush(stdout);
}
/* now find particles in Bubble again, and inject energy */
startnode = All.MaxPart;
do
{
numngb_inbox = ngb_treefind_variable(pos, BubbleRadius, -1, &startnode, 0, &dummy, &dummy);
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 < BubbleRadius * BubbleRadius)
{
/* with sf on gas particles have mass that is not fixed */
/* energy we want to inject in this particle */
if(logical == 1)
dE = ((BubbleEnergy / All.UnitEnergy_in_cgs) / totMass_bubble) * P[j].Mass;
else
dE = 0;
if(All.ComovingIntegrationOn)
SphP[j].Entropy +=
GAMMA_MINUS1 * dE / P[j].Mass / pow(SphP[j].d.Density / pow(All.Time, 3),
GAMMA_MINUS1);
else
SphP[j].Entropy +=
GAMMA_MINUS1 * dE / P[j].Mass / pow(SphP[j].d.Density, GAMMA_MINUS1);
if(dE > 0 && P[j].ID > 0)
P[j].ID = -P[j].ID;
}
}
}
while(startnode >= 0);
myfree(Ngblist);
}
}
myfree(GroupCM_dum_z);
myfree(GroupCM_common_z);
myfree(GroupCM_dum_y);
myfree(GroupCM_common_y);
myfree(GroupCM_dum_x);
myfree(GroupCM_common_x);
myfree(GroupMassType_dum);
myfree(GroupMassType_common);
MPI_Allreduce(&eff_nheat, &tot_eff_nheat, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if(ThisTask == 0)
printf("The total effective! number of clusters to heat is: %d\n", eff_nheat);
}
else
{
printf("There are no clusters to heat. I will stop.\n");
endrun(0);
}
myfree(disp);
myfree(nn_heat);
}
#endif
double fof_periodic(double x)
{
if(x >= 0.5 * All.BoxSize)
x -= All.BoxSize;
if(x < -0.5 * All.BoxSize)
x += All.BoxSize;
return x;
}
double fof_periodic_wrap(double x)
{
while(x >= All.BoxSize)
x -= All.BoxSize;
while(x < 0)
x += All.BoxSize;
return x;
}
int fof_compare_FOF_PList_MinID(const void *a, const void *b)
{
if(((struct fof_particle_list *) a)->MinID < ((struct fof_particle_list *) b)->MinID)
return -1;
if(((struct fof_particle_list *) a)->MinID > ((struct fof_particle_list *) b)->MinID)
return +1;
return 0;
}
int fof_compare_FOF_GList_MinID(const void *a, const void *b)
{
if(((struct fof_group_list *) a)->MinID < ((struct fof_group_list *) b)->MinID)
return -1;
if(((struct fof_group_list *) a)->MinID > ((struct fof_group_list *) b)->MinID)
return +1;
return 0;
}
int fof_compare_FOF_GList_MinIDTask(const void *a, const void *b)
{
if(((struct fof_group_list *) a)->MinIDTask < ((struct fof_group_list *) b)->MinIDTask)
return -1;
if(((struct fof_group_list *) a)->MinIDTask > ((struct fof_group_list *) b)->MinIDTask)
return +1;
return 0;
}
int fof_compare_FOF_GList_LocCountTaskDiffMinID(const void *a, const void *b)
{
if(((struct fof_group_list *) a)->LocCount > ((struct fof_group_list *) b)->LocCount)
return -1;
if(((struct fof_group_list *) a)->LocCount < ((struct fof_group_list *) b)->LocCount)
return +1;
if(((struct fof_group_list *) a)->MinID < ((struct fof_group_list *) b)->MinID)
return -1;
if(((struct fof_group_list *) a)->MinID > ((struct fof_group_list *) b)->MinID)
return +1;
if(labs(((struct fof_group_list *) a)->ExtCount - ((struct fof_group_list *) a)->MinIDTask) <
labs(((struct fof_group_list *) b)->ExtCount - ((struct fof_group_list *) b)->MinIDTask))
return -1;
if(labs(((struct fof_group_list *) a)->ExtCount - ((struct fof_group_list *) a)->MinIDTask) >
labs(((struct fof_group_list *) b)->ExtCount - ((struct fof_group_list *) b)->MinIDTask))
return +1;
return 0;
}
int fof_compare_FOF_GList_ExtCountMinID(const void *a, const void *b)
{
if(((struct fof_group_list *) a)->ExtCount < ((struct fof_group_list *) b)->ExtCount)
return -1;
if(((struct fof_group_list *) a)->ExtCount > ((struct fof_group_list *) b)->ExtCount)
return +1;
if(((struct fof_group_list *) a)->MinID < ((struct fof_group_list *) b)->MinID)
return -1;
if(((struct fof_group_list *) a)->MinID > ((struct fof_group_list *) b)->MinID)
return +1;
return 0;
}
int fof_compare_Group_MinID(const void *a, const void *b)
{
if(((struct group_properties *) a)->MinID < ((struct group_properties *) b)->MinID)
return -1;
if(((struct group_properties *) a)->MinID > ((struct group_properties *) b)->MinID)
return +1;
return 0;
}
int fof_compare_Group_GrNr(const void *a, const void *b)
{
if(((struct group_properties *) a)->GrNr < ((struct group_properties *) b)->GrNr)
return -1;
if(((struct group_properties *) a)->GrNr > ((struct group_properties *) b)->GrNr)
return +1;
return 0;
}
int fof_compare_Group_MinIDTask(const void *a, const void *b)
{
if(((struct group_properties *) a)->MinIDTask < ((struct group_properties *) b)->MinIDTask)
return -1;
if(((struct group_properties *) a)->MinIDTask > ((struct group_properties *) b)->MinIDTask)
return +1;
return 0;
}
int fof_compare_Group_MinIDTask_MinID(const void *a, const void *b)
{
if(((struct group_properties *) a)->MinIDTask < ((struct group_properties *) b)->MinIDTask)
return -1;
if(((struct group_properties *) a)->MinIDTask > ((struct group_properties *) b)->MinIDTask)
return +1;
if(((struct group_properties *) a)->MinID < ((struct group_properties *) b)->MinID)
return -1;
if(((struct group_properties *) a)->MinID > ((struct group_properties *) b)->MinID)
return +1;
return 0;
}
int fof_compare_Group_Len(const void *a, const void *b)
{
if(((struct group_properties *) a)->Len > ((struct group_properties *) b)->Len)
return -1;
if(((struct group_properties *) a)->Len < ((struct group_properties *) b)->Len)
return +1;
return 0;
}
int fof_compare_ID_list_GrNrID(const void *a, const void *b)
{
if(((struct id_list *) a)->GrNr < ((struct id_list *) b)->GrNr)
return -1;
if(((struct id_list *) a)->GrNr > ((struct id_list *) b)->GrNr)
return +1;
if(((struct id_list *) a)->ID < ((struct id_list *) b)->ID)
return -1;
if(((struct id_list *) a)->ID > ((struct id_list *) b)->ID)
return +1;
return 0;
}
#ifdef SUBFIND_READ_FOF /* read already existing FOF instead of recomputing it */
void read_fof(int num)
{
FILE *fd;
double t0, t1;
char fname[500];
float *mass, *cm;
int i, j, ntask, *len, count;
MyIDType *ids;
int *list_of_ngroups, *list_of_nids, *list_of_allgrouplen;
int *recvoffset;
int grnr, ngrp, sendTask, recvTask, imax1, imax2;
int nprocgroup, masterTask, groupTask, nid_previous;
int fof_compare_P_SubNr(const void *a, const void *b);
if(ThisTask == 0)
{
printf("\nTrying to read preexisting FoF group catalogues... (presently allocated=%g MB)\n",
AllocatedBytes / (1024.0 * 1024.0));
fflush(stdout);
}
All.NumForcesSinceLastDomainDecomp = (long long) (All.TotNumPart * All.TreeDomainUpdateFrequency + 1);
domain_Decomposition();
force_treefree();
/* start reading of group catalogue */
if(ThisTask == 0)
{
sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "group_tab", num, 0);
if(!(fd = fopen(fname, "r")))
{
printf("can't read file `%s`\n", fname);
endrun(11831);
}
my_fread(&Ngroups, sizeof(int), 1, fd);
my_fread(&TotNgroups, sizeof(int), 1, fd);
my_fread(&Nids, sizeof(int), 1, fd);
my_fread(&TotNids, sizeof(long long), 1, fd);
my_fread(&ntask, sizeof(int), 1, fd);
fclose(fd);
}
MPI_Bcast(&ntask, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&TotNgroups, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&TotNids, sizeof(long long), MPI_BYTE, 0, MPI_COMM_WORLD);
t0 = second();
if(NTask != ntask)
{
if(ThisTask == 0)
printf
("number of files (%d) in group catalogues does not match MPI-Tasks, I'm working around this.\n",
ntask);
Group =
(struct group_properties *) mymalloc(sizeof(struct group_properties) * (TotNgroups / NTask + NTask));
ID_list = mymalloc((TotNids / NTask + NTask) * sizeof(struct id_list));
int filenr, target, ngroups, nids, nsend, stored;
int *ngroup_to_get = mymalloc(NTask * sizeof(NTask));
int *nids_to_get = mymalloc(NTask * sizeof(NTask));
int *ngroup_obtained = mymalloc(NTask * sizeof(NTask));
int *nids_obtained = mymalloc(NTask * sizeof(NTask));
for(i = 0; i < NTask; i++)
ngroup_obtained[i] = nids_obtained[i] = 0;
for(i = 0; i < NTask - 1; i++)
ngroup_to_get[i] = TotNgroups / NTask;
ngroup_to_get[NTask - 1] = TotNgroups - (NTask - 1) * (TotNgroups / NTask);
for(i = 0; i < NTask - 1; i++)
nids_to_get[i] = (int) (TotNids / NTask);
nids_to_get[NTask - 1] = (int) (TotNids - (NTask - 1) * (TotNids / NTask));
Ngroups = ngroup_to_get[ThisTask];
Nids = nids_to_get[ThisTask];
if(ThisTask == 0)
{
for(filenr = 0; filenr < ntask; filenr++)
{
sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "group_tab", num, filenr);
if(!(fd = fopen(fname, "r")))
{
printf("can't read file `%s`\n", fname);
endrun(11831);
}
printf("reading '%s'\n", fname);
fflush(stdout);
my_fread(&ngroups, sizeof(int), 1, fd);
my_fread(&TotNgroups, sizeof(int), 1, fd);
my_fread(&nids, sizeof(int), 1, fd);
my_fread(&TotNids, sizeof(long long), 1, fd);
my_fread(&ntask, sizeof(int), 1, fd);
struct group_properties *tmpGroup =
(struct group_properties *) mymalloc(sizeof(struct group_properties) * ngroups);
/* group len */
len = mymalloc(ngroups * sizeof(int));
my_fread(len, ngroups, sizeof(int), fd);
for(i = 0; i < ngroups; i++)
tmpGroup[i].Len = len[i];
myfree(len);
/* offset into id-list */
len = mymalloc(ngroups * sizeof(int));
my_fread(len, ngroups, sizeof(int), fd);
for(i = 0; i < ngroups; i++)
tmpGroup[i].Offset = len[i];
myfree(len);
/* mass */
mass = mymalloc(ngroups * sizeof(float));
my_fread(mass, ngroups, sizeof(float), fd);
for(i = 0; i < ngroups; i++)
tmpGroup[i].Mass = mass[i];
myfree(mass);
/* CM */
cm = mymalloc(ngroups * 3 * sizeof(float));
my_fread(cm, ngroups, 3 * sizeof(float), fd);
for(i = 0; i < ngroups; i++)
for(j = 0; j < 3; j++)
tmpGroup[i].CM[j] = cm[i * 3 + j];
myfree(cm);
fclose(fd);
target = 0;
stored = 0;
while(ngroups > 0)
{
while(ngroup_to_get[target] == 0)
target++;
if(ngroups > ngroup_to_get[target])
nsend = ngroup_to_get[target];
else
nsend = ngroups;
if(target == 0)
memcpy(&Group[ngroup_obtained[target]], &tmpGroup[stored],
nsend * sizeof(struct group_properties));
else
{
MPI_Send(&nsend, 1, MPI_INT, target, TAG_N, MPI_COMM_WORLD);
MPI_Send(&tmpGroup[stored], nsend * sizeof(struct group_properties), MPI_BYTE,
target, TAG_PDATA, MPI_COMM_WORLD);
}
ngroup_to_get[target] -= nsend;
ngroup_obtained[target] += nsend;
ngroups -= nsend;
stored += nsend;
}
myfree(tmpGroup);
}
/**** now ids ****/
for(filenr = 0; filenr < ntask; filenr++)
{
sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "group_ids", num, filenr);
if(!(fd = fopen(fname, "r")))
{
printf("can't read file `%s`\n", fname);
endrun(1184132);
}
printf("reading '%s'\n", fname);
fflush(stdout);
my_fread(&ngroups, sizeof(int), 1, fd);
my_fread(&TotNgroups, sizeof(int), 1, fd);
my_fread(&nids, sizeof(int), 1, fd);
my_fread(&TotNids, sizeof(long long), 1, fd);
my_fread(&ntask, sizeof(int), 1, fd);
my_fread(&nid_previous, sizeof(int), 1, fd); /* this is the number of IDs in previous files */
struct id_list *tmpID_list = mymalloc(nids * sizeof(struct id_list));
ids = mymalloc(nids * sizeof(MyIDType));
my_fread(ids, sizeof(MyIDType), nids, fd);
for(i = 0; i < nids; i++)
tmpID_list[i].ID = ids[i];
myfree(ids);
fclose(fd);
target = 0;
stored = 0;
while(nids > 0)
{
while(nids_to_get[target] == 0)
target++;
if(nids > nids_to_get[target])
nsend = nids_to_get[target];
else
nsend = nids;
if(target == 0)
memcpy(&ID_list[nids_obtained[target]], &tmpID_list[stored],
nsend * sizeof(struct id_list));
else
{
MPI_Send(&nsend, 1, MPI_INT, target, TAG_HEADER, MPI_COMM_WORLD);
MPI_Send(&tmpID_list[stored], nsend * sizeof(struct id_list), MPI_BYTE,
target, TAG_SPHDATA, MPI_COMM_WORLD);
}
nids_to_get[target] -= nsend;
nids_obtained[target] += nsend;
nids -= nsend;
stored += nsend;
}
myfree(tmpID_list);
}
}
else
{
while(ngroup_to_get[ThisTask])
{
MPI_Recv(&nsend, 1, MPI_INT, 0, TAG_N, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&Group[ngroup_obtained[ThisTask]], nsend * sizeof(struct group_properties), MPI_BYTE,
0, TAG_PDATA, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
ngroup_to_get[ThisTask] -= nsend;
ngroup_obtained[ThisTask] += nsend;
}
while(nids_to_get[ThisTask])
{
MPI_Recv(&nsend, 1, MPI_INT, 0, TAG_HEADER, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&ID_list[nids_obtained[ThisTask]], nsend * sizeof(struct id_list), MPI_BYTE,
0, TAG_SPHDATA, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
nids_to_get[ThisTask] -= nsend;
nids_obtained[ThisTask] += nsend;
}
}
myfree_msg(nids_obtained, "nids_obtained");
myfree(ngroup_obtained);
myfree(nids_to_get);
myfree_msg(ngroup_to_get, "ngroup_to_get");
}
else
{
/* read routine can constinue in parallel */
nprocgroup = NTask / All.NumFilesWrittenInParallel;
if((NTask % All.NumFilesWrittenInParallel))
nprocgroup++;
masterTask = (ThisTask / nprocgroup) * nprocgroup;
for(groupTask = 0; groupTask < nprocgroup; groupTask++)
{
if(ThisTask == (masterTask + groupTask)) /* ok, it's this processor's turn */
{
sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "group_tab", num, ThisTask);
if(!(fd = fopen(fname, "r")))
{
printf("can't read file `%s`\n", fname);
endrun(11831);
}
printf("reading '%s'\n", fname);
fflush(stdout);
my_fread(&Ngroups, sizeof(int), 1, fd);
my_fread(&TotNgroups, sizeof(int), 1, fd);
my_fread(&Nids, sizeof(int), 1, fd);
my_fread(&TotNids, sizeof(long long), 1, fd);
my_fread(&ntask, sizeof(int), 1, fd);
if(NTask != ntask)
{
if(ThisTask == 0)
printf("number of files in group catalogues needs to match MPI-Tasks\n");
endrun(0);
}
if(ThisTask == 0)
printf("TotNgroups=%d\n", TotNgroups);
Group = (struct group_properties *) mymalloc(sizeof(struct group_properties) *
IMAX(Ngroups, TotNgroups / NTask + 1));
/* group len */
len = mymalloc(Ngroups * sizeof(int));
my_fread(len, Ngroups, sizeof(int), fd);
for(i = 0; i < Ngroups; i++)
Group[i].Len = len[i];
myfree(len);
/* offset into id-list */
len = mymalloc(Ngroups * sizeof(int));
my_fread(len, Ngroups, sizeof(int), fd);
for(i = 0; i < Ngroups; i++)
Group[i].Offset = len[i];
myfree(len);
/* mass */
mass = mymalloc(Ngroups * sizeof(float));
my_fread(mass, Ngroups, sizeof(float), fd);
for(i = 0; i < Ngroups; i++)
Group[i].Mass = mass[i];
myfree(mass);
/* CM */
cm = mymalloc(Ngroups * 3 * sizeof(float));
my_fread(cm, Ngroups, 3 * sizeof(float), fd);
for(i = 0; i < Ngroups; i++)
for(j = 0; j < 3; j++)
Group[i].CM[j] = cm[i * 3 + j];
myfree(cm);
fclose(fd);
printf("reading '%s'\n", fname);
fflush(stdout);
sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "group_ids", num, ThisTask);
if(!(fd = fopen(fname, "r")))
{
printf("can't read file `%s`\n", fname);
endrun(1184132);
}
printf("reading '%s'\n", fname);
fflush(stdout);
my_fread(&Ngroups, sizeof(int), 1, fd);
my_fread(&TotNgroups, sizeof(int), 1, fd);
my_fread(&Nids, sizeof(int), 1, fd);
my_fread(&TotNids, sizeof(long long), 1, fd);
my_fread(&ntask, sizeof(int), 1, fd);
my_fread(&nid_previous, sizeof(int), 1, fd); /* this is the number of IDs in previous files */
ID_list = mymalloc(Nids * sizeof(struct id_list));
ids = mymalloc(Nids * sizeof(MyIDType));
my_fread(ids, sizeof(MyIDType), Nids, fd);
for(i = 0; i < Nids; i++)
ID_list[i].ID = ids[i];
myfree(ids);
fclose(fd);
}
MPI_Barrier(MPI_COMM_WORLD); /* wait inside the group */
}
}
t1 = second();
if(ThisTask == 0)
printf("reading took %g sec\n", timediff(t0, t1));
t0 = second();
/* now need to assign group numbers */
list_of_ngroups = mymalloc(NTask * sizeof(int));
list_of_nids = mymalloc(NTask * sizeof(int));
MPI_Allgather(&Ngroups, 1, MPI_INT, list_of_ngroups, 1, MPI_INT, MPI_COMM_WORLD);
MPI_Allgather(&Nids, 1, MPI_INT, list_of_nids, 1, MPI_INT, MPI_COMM_WORLD);
list_of_allgrouplen = mymalloc(TotNgroups * sizeof(int));
recvoffset = mymalloc(NTask * sizeof(int));
for(i = 1, recvoffset[0] = 0; i < NTask; i++)
recvoffset[i] = recvoffset[i - 1] + list_of_ngroups[i - 1];
len = mymalloc(Ngroups * sizeof(int));
for(i = 0; i < Ngroups; i++)
len[i] = Group[i].Len;
MPI_Allgatherv(len, Ngroups, MPI_INT, list_of_allgrouplen, list_of_ngroups, recvoffset, MPI_INT,
MPI_COMM_WORLD);
myfree(len);
myfree(recvoffset);
/* do a check */
long long totlen;
for(i = 0, totlen = 0; i < TotNgroups; i++)
totlen += list_of_allgrouplen[i];
if(totlen != TotNids)
endrun(8881);
for(i = 0, count = 0; i < ThisTask; i++)
count += list_of_ngroups[i];
for(i = 0; i < Ngroups; i++)
Group[i].GrNr = 1 + count + i;
/* fix Group.Offset (may have overflown) */
if(Ngroups > 0)
for(i = 0, count = 0, Group[0].Offset = 0; i < ThisTask; i++)
for(j = 0; j < list_of_ngroups[i]; j++)
Group[0].Offset += list_of_allgrouplen[count++];
for(i = 1; i < Ngroups; i++)
Group[i].Offset = Group[i - 1].Offset + Group[i - 1].Len;
long long *idoffset = mymalloc(NTask * sizeof(long long));
for(i = 1, idoffset[0] = 0; i < NTask; i++)
idoffset[i] = idoffset[i - 1] + list_of_nids[i - 1];
count = 0;
for(i = 0, grnr = 1, totlen = 0; i < TotNgroups; totlen += list_of_allgrouplen[i++], grnr++)
{
if(totlen + list_of_allgrouplen[i] - 1 >= idoffset[ThisTask] && totlen < idoffset[ThisTask] + Nids)
{
for(j = 0; j < list_of_allgrouplen[i]; j++)
{
if((totlen + j) >= idoffset[ThisTask] && (totlen + j) < (idoffset[ThisTask] + Nids))
{
ID_list[(totlen + j) - idoffset[ThisTask]].GrNr = grnr;
count++;
}
}
}
}
if(count != Nids)
endrun(1231);
myfree(idoffset);
t1 = second();
if(ThisTask == 0)
printf("assigning took %g sec\n", timediff(t0, t1));
t0 = second();
for(i = 0; i < NumPart; i++)
P[i].SubNr = i;
qsort(P, NumPart, sizeof(struct particle_data), io_compare_P_ID);
qsort(ID_list, Nids, sizeof(struct id_list), fof_compare_ID_list_ID);
for(i = 0; i < NumPart; i++)
P[i].GrNr = TotNgroups + 1; /* will mark particles that are not in any group */
t1 = second();
if(ThisTask == 0)
printf("sorting took %g sec\n", timediff(t0, t1));
static struct id_list *recv_ID_list;
t0 = second();
int matches = 0;
/* exchange data */
for(ngrp = 0; ngrp < (1 << PTask); ngrp++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(list_of_nids[sendTask] > 0 || list_of_nids[recvTask] > 0)
{
if(ngrp == 0)
{
recv_ID_list = ID_list;
}
else
{
recv_ID_list = mymalloc(list_of_nids[recvTask] * sizeof(struct id_list));
/* get the particles */
MPI_Sendrecv(ID_list, Nids * sizeof(struct id_list), MPI_BYTE, recvTask, TAG_DENS_A,
recv_ID_list, list_of_nids[recvTask] * sizeof(struct id_list), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
for(i = 0, j = 0; i < list_of_nids[recvTask]; i++)
{
while(j < NumPart - 1 && P[j].ID < recv_ID_list[i].ID)
j++;
if(recv_ID_list[i].ID == P[j].ID)
{
P[j].GrNr = recv_ID_list[i].GrNr;
matches++;
}
}
if(ngrp != 0)
myfree(recv_ID_list);
}
}
}
sumup_large_ints(1, &matches, &totlen);
if(totlen != TotNids)
endrun(543);
t1 = second();
if(ThisTask == 0)
printf("assigning GrNr to P[] took %g sec\n", timediff(t0, t1));
MPI_Barrier(MPI_COMM_WORLD);
myfree(list_of_allgrouplen);
myfree(list_of_nids);
myfree(list_of_ngroups);
/* restore peano-hilbert order */
qsort(P, NumPart, sizeof(struct particle_data), fof_compare_P_SubNr);
subfind(num);
endrun(0);
}
int fof_compare_ID_list_ID(const void *a, const void *b)
{
if(((struct id_list *) a)->ID < ((struct id_list *) b)->ID)
return -1;
if(((struct id_list *) a)->ID > ((struct id_list *) b)->ID)
return +1;
return 0;
}
int fof_compare_P_SubNr(const void *a, const void *b)
{
if(((struct particle_data *) a)->SubNr < (((struct particle_data *) b)->SubNr))
return -1;
if(((struct particle_data *) a)->SubNr > (((struct particle_data *) b)->SubNr))
return +1;
return 0;
}
#endif /* of SUBFIND_READ_FOF */
#endif /* of FOF */
| {
"alphanum_fraction": 0.6115144583,
"avg_line_length": 25.3029254483,
"ext": "c",
"hexsha": "214355d9685bbbdf2023bab919754e07b0f0d9c4",
"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/fof.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/fof.c",
"max_line_length": 111,
"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/fof.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 26072,
"size": 80438
} |
/*
Ballistic: a software to benchmark ballistic models.
AUTHORS: Javier Burguete Tolosa.
Copyright 2018, AUTHORS.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
/**
* \file utils.c
* \brief Source file with the useful data and functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2018.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <libxml/parser.h>
#include <glib.h>
#include "config.h"
#include "equation.h"
#define DEBUG_UTILS 0 ///< macro to debug the useful functions.
char *error_message = NULL; ///< error message string.
/**
* Function to add an error message.
*/
void
error_add (const char *message) ///< error message.
{
char *buffer;
buffer = error_message;
error_message = (char *) g_strconcat (message, "\n", buffer, NULL);
g_free (buffer);
}
/**
* Function to calculate the distance between two vectors.
*
* \return vectors distance.
*/
long double
distance (long double *r1, ///< 1st vector.
long double *r2) ///< 2nd vector.
{
long double d, dr[3];
#if DEBUG_EQUATION
fprintf (stderr, "distance: start\n");
fprintf (stderr, "distance: x1=%Lg y1=%Lg z1=%Lg\n", r1[0], r1[1], r1[2]);
fprintf (stderr, "distance: x2=%Lg y2=%Lg z2=%Lg\n", r2[0], r2[1], r2[2]);
#endif
dr[0] = r1[0] - r2[0];
dr[1] = r1[1] - r2[1];
dr[2] = r1[2] - r2[2];
d = sqrtl (dr[0] * dr[0] + dr[1] * dr[1] + dr[2] * dr[2]);
#if DEBUG_EQUATION
fprintf (stderr, "distance: d=%Lg\n", d);
fprintf (stderr, "distance: end\n");
#endif
return d;
}
/**
* Function to calculate the solution of a reduced 2nd order equation.
*
* This function calculates the solution of a reduced 2nd order equation in the
* form:
* \f[x^2+a\,x+b=0\f]
* in the interval \f$x\in\left[x_1,\;x_2\right]\f$.
*
* \return solution value. If the equation can not be solved or the solution is
* not in the interval the value is undetermined.
*/
long double
solve_quadratic_reduced (long double a, ///< a equation coefficient.
long double b, ///< b equation coefficient.
long double x1, ///< lower solution limit.
long double x2) ///< higher solution limit.
{
long double a2, k, x;
#if DEBUG_EQUATION
fprintf (stderr, "solve_quadratic_reduced: start\n");
fprintf (stderr, "solve_quadratic_reduced: a=%Lg b=%Lg\n", a, b);
fprintf (stderr, "solve_quadratic_reduced: x1=%Lg x2=%Lg\n", x1, x2);
#endif
a2 = -0.5L * a;
k = sqrtl (a2 * a2 - b);
x = a2 + k;
if (x < x1 || x > x2)
x = a2 - k;
#if DEBUG_EQUATION
fprintf (stderr, "solve_quadratic_reduced: x=%Lg\n", x);
fprintf (stderr, "solve_quadratic_reduced: end\n");
#endif
return x;
}
/**
* Function to calculate the solution of a 2nd order equation.
*
* This function calculates the solution of a 2nd order equation in the
* form:
* \f[a\,x^2+b\,x+c=0\f]
* in the interval \f$x\in\left[x_1,\;x_2\right]\f$.
*
* \return solution value. If the equation can not be solved or the solution is
* not in the interval the value is undetermined.
*/
long double
solve_quadratic (long double a, ///< a equation coefficient.
long double b, ///< b equation coefficient.
long double c, ///< c equation coefficient.
long double x1, ///< lower solution limit.
long double x2) ///< higher solution limit.
{
long double x;
#if DEBUG_EQUATION
fprintf (stderr, "solve_quadratic: start\n");
fprintf (stderr, "solve_quadratic: a=%Lg b=%Lg c=%Lg\n", a, b, c);
fprintf (stderr, "solve_quadratic: x1=%Lg x2=%Lg\n", x1, x2);
#endif
if (a == 0.L)
x = -c / b;
else
x = solve_quadratic_reduced (b / a, c / a, x1, x2);
#if DEBUG_EQUATION
fprintf (stderr, "solve_quadratic: x=%Lg\n", x);
fprintf (stderr, "solve_quadratic: end\n");
#endif
return x;
}
/**
* Function to calculate the solution of a reduced 3rd order equation.
*
* This function calculates the solution of a reduced 3rd order equation in the
* form:
* \f[x^3+a\,x^2+b\,x+c=0\f]
* in the interval \f$x\in\left[x_1,\;x_2\right]\f$.
*
* \return solution value. If the equation can not be solved or the solution is
* not in the interval the value is undetermined.
*/
long double
solve_cubic_reduced (long double a, ///< a equation coefficient.
long double b, ///< b equation coefficient.
long double c, ///< c equation coefficient.
long double x1, ///< lower solution limit.
long double x2) ///< higher solution limit.
{
long double k0, k1, k2;
#if DEBUG_EQUATION
fprintf (stderr, "solve_cubic_reduced: start\n");
fprintf (stderr, "solve_cubic_reduced: a=%Lg b=%Lg c=%Lg\n", a, b, c);
fprintf (stderr, "solve_cubic_reduced: x1=%Lg x2=%Lg\n", x1, x2);
#endif
a /= 3.L;
k0 = a * a;
k1 = b / 3.L - k0;
k0 = (b * a - c) / 2.L - a * k0;
k2 = k1 * k1 * k1 + k0 * k0;
if (k2 < 0.L)
{
k1 = sqrtl (-k1);
k0 = acosl (k0 / (k1 * k1 * k1)) / 3.L;
k1 *= 2.L;
k2 = k1 * cosl (k0) - a;
if (k2 < x1 || k2 > x2)
{
k2 = k1 * cosl (k0 + 2.L * M_PIl / 3.L) - a;
if (k2 < x1 || k2 > x2)
k2 = k1 * cosl (k0 - 2.L * M_PIl / 3.L) - a;
}
}
else
{
k1 = sqrtl (k2);
k2 = k0 + k1;
k2 = cbrtl (k2);
k0 -= k1;
k2 += cbrtl (k0);
k2 -= a;
}
#if DEBUG_EQUATION
fprintf (stderr, "solve_cubic_reduced: x=%Lg\n", k2);
fprintf (stderr, "solve_cubic_reduced: end\n");
#endif
return k2;
}
/**
* Function to calculate the solution of a 3rd order equation.
*
* This function calculates the solution of a 3rd order equation in the
* form:
* \f[a\,x^3+b\,x^2+c\,x+d=0\f]
* in the interval \f$x\in\left[x_1,\;x_2\right]\f$.
*
* \return solution value. If the equation can not be solved or the solution is
* not in the interval the value is undetermined.
*/
long double
solve_cubic (long double a, ///< a equation coefficient.
long double b, ///< b equation coefficient.
long double c, ///< c equation coefficient.
long double d, ///< d equation coefficient.
long double x1, ///< lower solution limit.
long double x2) ///< higher solution limit.
{
long double x;
#if DEBUG_EQUATION
fprintf (stderr, "solve_cubic: start\n");
fprintf (stderr, "solve_cubic: a=%Lg b=%Lg c=%Lg d=%Lg\n", a, b, c, d);
fprintf (stderr, "solve_cubic: x1=%Lg x2=%Lg\n", x1, x2);
#endif
if (a == 0.L)
x = solve_quadratic (b, c, d, x1, x2);
else
x = solve_cubic_reduced (b / a, c / a, d / a, x1, x2);
#if DEBUG_EQUATION
fprintf (stderr, "solve_cubic: x=%Lg\n", x);
fprintf (stderr, "solve_cubic: end\n");
#endif
return x;
}
/**
* Function to get an integer number of a XML node property.
*
* \return Integer number value.
*/
int
xml_node_get_int (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
int *error_code) ///< Error code.
{
int i = 0;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
if (!buffer)
*error_code = 1;
else
{
if (sscanf ((char *) buffer, "%d", &i) != 1)
*error_code = 2;
else
*error_code = 0;
xmlFree (buffer);
}
return i;
}
/**
* Function to get an unsigned integer number of a XML node property.
*
* \return Unsigned integer number value.
*/
unsigned int
xml_node_get_uint (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
int *error_code) ///< Error code.
{
unsigned int i = 0;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
if (!buffer)
*error_code = 1;
else
{
if (sscanf ((char *) buffer, "%u", &i) != 1)
*error_code = 2;
else
*error_code = 0;
xmlFree (buffer);
}
return i;
}
/**
* Function to get an unsigned integer number of a XML node property with a
* default value.
*
* \return Unsigned integer number value.
*/
unsigned int
xml_node_get_uint_with_default (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
unsigned int default_value,
///< default value.
int *error_code) ///< Error code.
{
unsigned int i;
if (xmlHasProp (node, prop))
i = xml_node_get_uint (node, prop, error_code);
else
{
i = default_value;
*error_code = 0;
}
return i;
}
/**
* Function to get a floating point number of a XML node property.
*
* \return Floating point number value.
*/
long double
xml_node_get_float (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
int *error_code) ///< Error code.
{
long double x = 0.L;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
if (!buffer)
*error_code = 1;
else
{
if (sscanf ((char *) buffer, "%Lf", &x) != 1)
*error_code = 2;
else
*error_code = 0;
xmlFree (buffer);
}
return x;
}
/**
* Function to get a floating point number of a XML node property with a
* default value.
*
* \return Floating point number value.
*/
long double
xml_node_get_float_with_default (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
long double default_value,
///< default value.
int *error_code) ///< Error code.
{
long double x;
if (xmlHasProp (node, prop))
x = xml_node_get_float (node, prop, error_code);
else
{
x = default_value;
*error_code = 0;
}
return x;
}
| {
"alphanum_fraction": 0.5987975592,
"avg_line_length": 29.5596816976,
"ext": "c",
"hexsha": "90ec7774bb2f40bedf6db0f0f2b8dbab8028b5e8",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-06-24T07:19:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-24T07:19:47.000Z",
"max_forks_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ballistic",
"max_forks_repo_path": "1.1.0/utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f",
"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/ballistic",
"max_issues_repo_path": "1.1.0/utils.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ballistic",
"max_stars_repo_path": "1.1.0/utils.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-02T14:03:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-02T14:03:09.000Z",
"num_tokens": 3198,
"size": 11144
} |
#pragma once
#include "halley/plugin/iasset_importer.h"
#include <gsl/gsl>
namespace Halley
{
class Animation;
class AnimationImporter : public IAssetImporter
{
public:
ImportAssetType getType() const override { return ImportAssetType::Animation; }
void import(const ImportingAsset& asset, IAssetCollector& collector) override;
static void parseAnimation(Animation& animation, gsl::span<const gsl::byte> data);
};
}
| {
"alphanum_fraction": 0.7679814385,
"avg_line_length": 22.6842105263,
"ext": "h",
"hexsha": "24b8b0a40e6e2de606ee8376fdb96004a33efaab",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/tools/tools/src/assets/importers/animation_importer.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/tools/tools/src/assets/importers/animation_importer.h",
"max_line_length": 84,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/tools/tools/src/assets/importers/animation_importer.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 101,
"size": 431
} |
/* multifit/fdfsolver.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multifit_nlin.h>
gsl_multifit_fdfsolver *
gsl_multifit_fdfsolver_alloc (const gsl_multifit_fdfsolver_type * T,
size_t n, size_t p)
{
int status;
gsl_multifit_fdfsolver * s;
if (n < p)
{
GSL_ERROR_VAL ("insufficient data points, n < p", GSL_EINVAL, 0);
}
s = (gsl_multifit_fdfsolver *) calloc (1, sizeof (gsl_multifit_fdfsolver));
if (s == 0)
{
GSL_ERROR_VAL ("failed to allocate space for multifit solver struct",
GSL_ENOMEM, 0);
}
s->x = gsl_vector_calloc (p);
if (s->x == 0)
{
gsl_multifit_fdfsolver_free (s);
GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
}
s->f = gsl_vector_calloc (n);
if (s->f == 0)
{
gsl_multifit_fdfsolver_free (s);
GSL_ERROR_VAL ("failed to allocate space for f", GSL_ENOMEM, 0);
}
s->dx = gsl_vector_calloc (p);
if (s->dx == 0)
{
gsl_multifit_fdfsolver_free (s);
GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0);
}
s->g = gsl_vector_alloc (p);
if (s->g == 0)
{
gsl_multifit_fdfsolver_free (s);
GSL_ERROR_VAL ("failed to allocate space for g", GSL_ENOMEM, 0);
}
s->sqrt_wts = gsl_vector_calloc (n);
if (s->sqrt_wts == 0)
{
gsl_multifit_fdfsolver_free (s);
GSL_ERROR_VAL ("failed to allocate space for sqrt_wts", GSL_ENOMEM, 0);
}
s->state = calloc (1, T->size);
if (s->state == 0)
{
gsl_multifit_fdfsolver_free (s);
GSL_ERROR_VAL ("failed to allocate space for multifit solver state",
GSL_ENOMEM, 0);
}
s->type = T ;
status = (s->type->alloc)(s->state, n, p);
if (status != GSL_SUCCESS)
{
gsl_multifit_fdfsolver_free (s);
GSL_ERROR_VAL ("failed to set solver", status, 0);
}
s->fdf = NULL;
s->niter = 0;
return s;
}
int
gsl_multifit_fdfsolver_set (gsl_multifit_fdfsolver * s,
gsl_multifit_function_fdf * f,
const gsl_vector * x)
{
return gsl_multifit_fdfsolver_wset(s, f, x, NULL);
}
int
gsl_multifit_fdfsolver_wset (gsl_multifit_fdfsolver * s,
gsl_multifit_function_fdf * f,
const gsl_vector * x,
const gsl_vector * wts)
{
const size_t n = s->f->size;
if (n != f->n)
{
GSL_ERROR ("function size does not match solver", GSL_EBADLEN);
}
else if (s->x->size != x->size)
{
GSL_ERROR ("vector length does not match solver", GSL_EBADLEN);
}
else if (wts != NULL && n != wts->size)
{
GSL_ERROR ("weight vector length does not match solver", GSL_EBADLEN);
}
else
{
size_t i;
s->fdf = f;
gsl_vector_memcpy(s->x, x);
s->niter = 0;
if (wts)
{
for (i = 0; i < n; ++i)
{
double wi = gsl_vector_get(wts, i);
gsl_vector_set(s->sqrt_wts, i, sqrt(wi));
}
}
else
gsl_vector_set_all(s->sqrt_wts, 1.0);
return (s->type->set) (s->state, s->sqrt_wts, s->fdf, s->x, s->f, s->dx);
}
}
int
gsl_multifit_fdfsolver_iterate (gsl_multifit_fdfsolver * s)
{
int status =
(s->type->iterate) (s->state, s->sqrt_wts, s->fdf, s->x, s->f, s->dx);
s->niter++;
return status;
}
/*
gsl_multifit_fdfsolver_driver()
Iterate the nonlinear least squares solver until completion
Inputs: s - fdfsolver
maxiter - maximum iterations to allow
xtol - tolerance in step x
gtol - tolerance in gradient
ftol - tolerance in ||f||
info - (output) info flag on why iteration terminated
1 = stopped due to small step size ||dx|
2 = stopped due to small gradient
3 = stopped due to small change in f
GSL_ETOLX = ||dx|| has converged to within machine
precision (and xtol is too small)
GSL_ETOLG = ||g||_inf is smaller than machine
precision (gtol is too small)
GSL_ETOLF = change in ||f|| is smaller than machine
precision (ftol is too small)
Return: GSL_SUCCESS if converged, GSL_MAXITER if maxiter exceeded without
converging
*/
int
gsl_multifit_fdfsolver_driver (gsl_multifit_fdfsolver * s,
const size_t maxiter,
const double xtol,
const double gtol,
const double ftol,
int *info)
{
int status;
size_t iter = 0;
do
{
status = gsl_multifit_fdfsolver_iterate (s);
/*
* if status is GSL_ENOPROG or GSL_SUCCESS, continue iterating,
* otherwise the method has converged with a GSL_ETOLx flag
*/
if (status != GSL_SUCCESS && status != GSL_ENOPROG)
break;
/* test for convergence */
status = gsl_multifit_fdfsolver_test(s, xtol, gtol, ftol, info);
}
while (status == GSL_CONTINUE && ++iter < maxiter);
/*
* the following error codes mean that the solution has converged
* to within machine precision, so record the error code in info
* and return success
*/
if (status == GSL_ETOLF || status == GSL_ETOLX || status == GSL_ETOLG)
{
*info = status;
status = GSL_SUCCESS;
}
/* check if max iterations reached */
if (iter >= maxiter && status != GSL_SUCCESS)
status = GSL_EMAXITER;
return status;
} /* gsl_multifit_fdfsolver_driver() */
int
gsl_multifit_fdfsolver_jac (gsl_multifit_fdfsolver * s, gsl_matrix * J)
{
const size_t n = s->f->size;
const size_t p = s->x->size;
if (n != J->size1 || p != J->size2)
{
GSL_ERROR ("Jacobian dimensions do not match solver", GSL_EBADLEN);
}
else
{
return (s->type->jac) (s->state, J);
}
} /* gsl_multifit_fdfsolver_jac() */
void
gsl_multifit_fdfsolver_free (gsl_multifit_fdfsolver * s)
{
RETURN_IF_NULL (s);
if (s->state)
{
(s->type->free) (s->state);
free (s->state);
}
if (s->dx)
gsl_vector_free (s->dx);
if (s->x)
gsl_vector_free (s->x);
if (s->f)
gsl_vector_free (s->f);
if (s->sqrt_wts)
gsl_vector_free (s->sqrt_wts);
if (s->g)
gsl_vector_free (s->g);
free (s);
}
const char *
gsl_multifit_fdfsolver_name (const gsl_multifit_fdfsolver * s)
{
return s->type->name;
}
gsl_vector *
gsl_multifit_fdfsolver_position (const gsl_multifit_fdfsolver * s)
{
return s->x;
}
gsl_vector *
gsl_multifit_fdfsolver_residual (const gsl_multifit_fdfsolver * s)
{
return s->f;
}
size_t
gsl_multifit_fdfsolver_niter (const gsl_multifit_fdfsolver * s)
{
return s->niter;
}
/*
gsl_multifit_eval_wf()
Compute residual vector y with user callback function, and apply
weighting transform if given:
y~ = sqrt(W) y
Inputs: fdf - callback function
x - model parameters
swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn))
set to NULL for unweighted fit
y - (output) (weighted) residual vector
y_i = sqrt(w_i) f_i where f_i is unweighted residual
*/
int
gsl_multifit_eval_wf(gsl_multifit_function_fdf *fdf, const gsl_vector *x,
const gsl_vector *swts, gsl_vector *y)
{
int s = ((*((fdf)->f)) (x, fdf->params, y));
++(fdf->nevalf);
/* y <- sqrt(W) y */
if (swts)
gsl_vector_mul(y, swts);
return s;
}
/*
gsl_multifit_eval_wdf()
Compute Jacobian matrix J with user callback function, and apply
weighting transform if given:
J~ = sqrt(W) J
Inputs: fdf - callback function
x - model parameters
swts - weight matrix W = diag(w1,w2,...,wn)
set to NULL for unweighted fit
dy - (output) (weighted) Jacobian matrix
dy = sqrt(W) dy where dy is unweighted Jacobian
*/
int
gsl_multifit_eval_wdf(gsl_multifit_function_fdf *fdf, const gsl_vector *x,
const gsl_vector *swts, gsl_matrix *dy)
{
int status = ((*((fdf)->df)) (x, fdf->params, dy));
++(fdf->nevaldf);
/* J <- sqrt(W) J */
if (swts)
{
const size_t n = swts->size;
size_t i;
for (i = 0; i < n; ++i)
{
double swi = gsl_vector_get(swts, i);
gsl_vector_view v = gsl_matrix_row(dy, i);
gsl_vector_scale(&v.vector, swi);
}
}
return status;
}
| {
"alphanum_fraction": 0.5956411342,
"avg_line_length": 24.8083989501,
"ext": "c",
"hexsha": "88136e9e4659519d67bb53698c15f656f403d295",
"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/fdfsolver.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/fdfsolver.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multifit/fdfsolver.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": 2728,
"size": 9452
} |
#ifndef CONTROLLERS_IMAGEOPERATIONTOGGLECONTROLLER_H
#define CONTROLLERS_IMAGEOPERATIONTOGGLECONTROLLER_H
#include "imageoperationactioncontroller.h"
#include "s3d/cv/image_operation/image_operation.h"
#include <QAction>
#include <gsl/gsl>
class ImageOperationToggleController : public ImageOperationActionController {
Q_OBJECT
public:
ImageOperationToggleController(gsl::not_null<QAction*> action,
gsl::not_null<s3d::image_operation::ImageOperation*> imageOperation);
void onActionTriggered() override;
};
#endif //CONTROLLERS_IMAGEOPERATIONTOGGLECONTROLLER_H
| {
"alphanum_fraction": 0.7927631579,
"avg_line_length": 26.4347826087,
"ext": "h",
"hexsha": "4bdbe13ac04c507a2596c026eea936f500f2896f",
"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/imageoperationtogglecontroller.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/imageoperationtogglecontroller.h",
"max_line_length": 102,
"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/imageoperationtogglecontroller.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": 134,
"size": 608
} |
/*
* particle_filters.c
*
* Created on: 18 Sep 2020
* Author: heine
*/
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_eigen.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "particle_filters.h"
void MLbootstrapfilter(double* y, double sig_std, double obs_std, int data_length,
double x0, int Nobs, short N_levels, long* sample_sizes, double* x_hats,
double *filtering_time, double *Rinv0, double *Rinv1, double *worst_case_sign_ratio) {
const char prog_bar[51] = "-------------------------------------------------";
clock_t start;
int bar_segment_count = 0;
long N = 0;
for (short i = 0; i < N_levels; i++) {
N += sample_sizes[i];
// printf("N%i = %lu, ", i, sample_sizes[i]);
}
// printf("N = %lu\n", N);
double *X = (double*) malloc(N * sizeof(double));
double *X_res = (double*) malloc(N * sizeof(double));
double *W = (double*) malloc(N * sizeof(double));
double *absW = (double*) malloc(N * sizeof(double));
short *signs = (short*) malloc(N * sizeof(short));
short *signs_res = (short*) malloc(N * sizeof(short));
long *ind = (long*) malloc(N * sizeof(long));
short *level_indicator = (short*) malloc(N * sizeof(short));
double x_hat = 0;
double p_hat = 0;
printf(
"%s\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
prog_bar);
fflush(stdout);
start = clock();
/*
* Initial sample and level indicator
*/
long sample_counter = 0;
short current_level = 0;
gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);
gsl_rng_set(rng, clock());
for (long i = 0; i < N; i++) {
X[i] = gsl_ran_gaussian(rng, sig_std) + x0; // init sample
W[i] = (double) 1.0 / (double) N; // init weights
/* Construct level indicator array */
signs_res[i] = 1;
if (sample_counter >= sample_sizes[current_level]) {
current_level++;
sample_counter = 0;
} else {
sample_counter++;
}
level_indicator[i] = current_level;
}
double normaliser = 0;
double abs_normaliser = 0;
double diff;
double ESS, ESSABS;
double tmp_x_hat;
double positive_mass, negative_mass;
FILE* bpf_out = fopen("bpf_out.txt", "w");
double* raw_like = (double*) malloc(2 * N * sizeof(double));
long *permutation = (long*) malloc(N * sizeof(long));
double lap1 = 0, lap2 = 0, lap3 = 0, lap4 = 0;
clock_t iteration_timer;
clock_t resampling_timer;
clock_t level_timer_start;
double level_0_particle_cost = 0;
double level_1_particle_cost = 0;
double rsamp_time_per_prcl = 0;
double time_increment;
double scaler;
double num, den;
worst_case_sign_ratio[0] = 100;
double sign_balance;
/* FILTER MAIN LOOP */
for (int n = 0; n < data_length; n++) {
iteration_timer = clock(); // start the stopwatch
level_timer_start = clock();
/*
* Weight calculation
*/
normaliser = 0;
abs_normaliser = 0;
for (long i = 0; i < N; i++) {
if (level_indicator[i] == 0) {
/* Use the diagonal observation covariance */
raw_like[i] = likelihood(n, X[i], y, 0, Rinv0, Nobs, 1);
raw_like[N + i] = 0;
} else {
/* Calculate both, the diagonal and full covariance to get level 1
* differences */
raw_like[i] = full_likelihood(n, X[i], y, Rinv1, Nobs, 1);
raw_like[N + i] = likelihood(n, X[i], y, 0, Rinv0, Nobs, 1);
}
if (i == sample_sizes[0]) {
/* When level indicator changes take the time per particle for level 0 */
time_increment = (double) (clock() - level_timer_start) / CLOCKS_PER_SEC
/ (double) sample_sizes[0];
level_0_particle_cost += time_increment;
level_timer_start = clock();
}
}
/* Time per particle for level 1 */
time_increment = (double) (clock() - level_timer_start) / CLOCKS_PER_SEC
/ (double) sample_sizes[1];
level_1_particle_cost += time_increment;
lap1 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;
/*
* Find scaler for the level 0 likelihood
* */
if (N_levels == 2) { // Do this only for non-unilevel
num = 0;
den = 0;
for (int i = (int)sample_sizes[0]; i < N; i++) {
num += raw_like[i] * raw_like[N + i];
den += raw_like[N + i] * raw_like[N + i];
}
scaler = num / den;
scaler = isnan(scaler) ? 1 : scaler;
/*
* Scale all level 0 weights by 'scaler'
* */
for (long i = 0; i < sample_sizes[0]; i++) // level 0
raw_like[i] *= scaler;
for (long i = sample_sizes[0]; i < N; i++) // Level 1
raw_like[N + i] *= scaler;
}
/* Actual weight calculation */
for (long i = 0; i < N; i++) {
W[i] = (raw_like[i] - raw_like[N + i]) / (double) sample_sizes[level_indicator[i]]
* (double) signs_res[i];
absW[i] = fabs(W[i]);
signs[i] = W[i] > 0 ? 1 : -1;
normaliser += W[i];
abs_normaliser += absW[i];
}
/* Normalise */
tmp_x_hat = 0;
positive_mass = 0;
negative_mass = 0;
for (long i = 0; i < N; i++) {
W[i] /= normaliser;
if (W[i] > 0) {
positive_mass += W[i];
} else {
negative_mass += fabs(W[i]);
}
absW[i] /= abs_normaliser;
tmp_x_hat += X[i] * W[i];
}
sign_balance = positive_mass / negative_mass;
if (sign_balance < worst_case_sign_ratio[0]) {
worst_case_sign_ratio[0] = sign_balance;
}
ESS = 0;
ESSABS = 0;
for (long i = 0; i < N; i++) {
ESS += W[i] * W[i];
ESSABS += absW[i] * absW[i];
}
ESS = (double) 1.0 / ESS;
ESSABS = (double) 1.0 / ESSABS;
lap2 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;
/* Resample */
resampling_timer = clock();
resample(N, absW, ind, rng);
random_permuter(permutation, N, rng);
rsamp_time_per_prcl += (double) (clock() - resampling_timer) / CLOCKS_PER_SEC / (double) N;
lap3 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;
normaliser = 0;
for (long i = 0; i < N; i++) {
X_res[permutation[i]] = X[ind[i]];
signs_res[permutation[i]] = signs[ind[i]];
normaliser += signs[ind[i]];
}
for (long i = 0; i < N; i++) {
W[i] = (double) signs_res[i] / normaliser;
}
/* Calculate the output: posterior mean */
x_hat = 0;
for (long i = 0; i < N; i++) {
x_hat += X_res[i] * W[i];
}
x_hats[n] = x_hat;
/* Calculate the output: posterior variance */
p_hat = 0;
for (long i = 0; i < N; i++) {
diff = X_res[i] - x_hat;
p_hat += diff * diff * W[i];
}
/* Mutate */
for (long i = 0; i < N; i++)
X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std);
if (floor(n * (double) 50 / data_length) > bar_segment_count) {
printf("█");
fflush(stdout);
bar_segment_count++;
}
lap4 += (double) (clock() - iteration_timer) / CLOCKS_PER_SEC;
}
filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length;
filtering_time[1] = level_0_particle_cost / (double) data_length;
filtering_time[2] = level_1_particle_cost / (double) data_length;
filtering_time[3] = rsamp_time_per_prcl / (double) data_length;
printf(" %5.2f sec\n", filtering_time[0]);
printf(" %5.2f %5.2f %5.2f %5.2f\n", lap1, lap2, lap3, lap4);
fclose(bpf_out);
free(X);
free(X_res);
free(W);
free(absW);
free(signs);
free(signs_res);
free(ind);
free(level_indicator);
free(raw_like);
free(permutation);
gsl_rng_free(rng);
}
void bootstrapfilter(double* y, double sig_std, double obs_std, int data_length, double x0,
int Nobs, long N, double* x_hats, double *filtering_time, double *Rinv, short full) {
const char prog_bar[51] = "-------------------------------------------------";
clock_t start;
int bar_segment_count = 0;
printf("Basic BPF with N = %lu\n", N);
double *X = (double*) malloc(N * sizeof(double));
double *X_res = (double*) malloc(N * sizeof(double));
double *W = (double*) malloc(N * sizeof(double));
long *ind = (long*) malloc(N * sizeof(long));
double x_hat = 0;
double p_hat = 0;
printf(
"%s\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
prog_bar);
fflush(stdout);
start = clock();
/*
* Initial sample and level indicator
*/
gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);
gsl_rng_set(rng, clock());
for (long i = 0; i < N; i++) {
X[i] = gsl_ran_gaussian(rng, sig_std) + x0;
W[i] = (double) 1.0 / (double) N;
}
double normaliser = 0;
double diff;
double ESS;
FILE* bpf_out = fopen("classicbpf_out.txt", "w");
/* Classic BPF main loop */
for (int n = 0; n < data_length; n++) {
/* Weight calculation */
normaliser = 0;
/*
* Weight calculation
*/
for (long i = 0; i < N; i++) {
if (full > 0) {
W[i] = full_likelihood(n, X[i], y, Rinv, Nobs, 1);
} else {
W[i] = likelihood(n, X[i], y, 0, Rinv, Nobs, 1);
}
normaliser += W[i];
}
for (long i = 0; i < N; i++) {
W[i] /= normaliser;
}
ESS = 0;
for (long i = 0; i < N; i++) {
ESS += W[i] * W[i];
}
ESS = (double) 1.0 / ESS;
/* Resample */
resample(N, W, ind, rng);
for (long i = 0; i < N; i++) {
X_res[i] = X[ind[i]];
}
/* Calculate the output: posterior mean */
x_hat = 0;
for (long i = 0; i < N; i++) {
x_hat += X_res[i] / (double) N;
}
x_hats[n] = x_hat;
/* Calculate the output: posterior variance */
p_hat = 0;
for (long i = 0; i < N; i++) {
diff = X_res[i] - x_hat;
p_hat += diff * diff / (double) N;
}
/* Mutate */
for (long i = 0; i < N; i++)
X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std);
fprintf(bpf_out, "%i %f %f %f\n", n, x_hat, p_hat, ESS);
fflush(bpf_out);
if (floor(n * (double) 50 / data_length) > bar_segment_count) {
printf("█");
fflush(stdout);
bar_segment_count++;
}
}
filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length;
filtering_time[1] = 0;
filtering_time[2] = 0;
filtering_time[3] = 0;
printf(" %5.2f sec\n", filtering_time[0]);
fclose(bpf_out);
free(X);
free(X_res);
free(W);
free(ind);
gsl_rng_free(rng);
}
double likelihood(int n, double x, double *y, int band, double *Rinv, int Nobs, double det) {
double diff;
double log_likelihood = 0;
for (int j = 0; j < Nobs; j++) {
diff = y[n * Nobs + j] - x;
log_likelihood += (y[n * Nobs + j] - x) * Rinv[j * Nobs + j] * diff;
}
log_likelihood /= -(double) 2.0;
return exp(log_likelihood) / det; // / sqrt(pow((2 * M_PI), Nobs) * det);
}
double full_likelihood(int n, double x, double *y, double *Rinv, int Nobs, double det) {
double diff;
double log_likelihood = 0;
for (int j = 0; j < Nobs; j++) {
diff = y[n * Nobs + j] - x;
for (int i = 0; i < Nobs; i++) {
log_likelihood += (y[n * Nobs + i] - x) * Rinv[j * Nobs + i] * diff;
}
}
log_likelihood /= -(double) 2.0;
return exp(log_likelihood); // / sqrt(pow((2 * M_PI), Nobs) * det);
}
void random_permuter(long *permutation, long N, gsl_rng *r) {
for (long i = 0; i < N; i++)
permutation[i] = i;
long j;
long tmp;
for (long i = N - 1; i > 0; i--) {
j = gsl_rng_uniform_int(r, i + 1);
tmp = permutation[j];
permutation[j] = permutation[i];
permutation[i] = tmp;
}
}
void resample(long size, double *w, long *ind, gsl_rng *r) {
/* Generate the exponentials */
double *e = (double*) malloc((size + 1) * sizeof(double));
double g = 0;
for (long i = 0; i <= size; i++) {
e[i] = gsl_ran_exponential(r, 1.0);
g += e[i];
}
/* Generate the uniform order statistics */
double *u = (double *) malloc((size + 1) * sizeof(double));
u[0] = 0;
for (long i = 1; i <= size; i++)
u[i] = u[i - 1] + e[i - 1] / g;
/* Do the actual sampling with inverse cdf */
double cdf = w[0];
long j = 0;
for (long i = 0; i < size; i++) {
while (cdf < u[i + 1]) {
j++;
cdf += w[j];
}
ind[i] = j;
}
free(e);
free(u);
}
| {
"alphanum_fraction": 0.5587492875,
"avg_line_length": 27.1703539823,
"ext": "c",
"hexsha": "2827859bebc3751ef8cc25f89f7b4a5a4292c34a",
"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": "92805b7ba34496271628f745e44eb4984329fb4a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "heinekmp/MLBPF",
"max_forks_repo_path": "BIG_DATA/particle_filters.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a",
"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": "heinekmp/MLBPF",
"max_issues_repo_path": "BIG_DATA/particle_filters.c",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "heinekmp/MLBPF",
"max_stars_repo_path": "BIG_DATA/particle_filters.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3950,
"size": 12281
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_spmatrix.h>
#include <gsl/gsl_splinalg.h>
int
main()
{
const size_t N = 100; /* number of grid points */
const size_t n = N - 2; /* subtract 2 to exclude boundaries */
const double h = 1.0 / (N - 1.0); /* grid spacing */
gsl_spmatrix *A = gsl_spmatrix_alloc(n ,n); /* triplet format */
gsl_spmatrix *C; /* compressed format */
gsl_vector *f = gsl_vector_alloc(n); /* right hand side vector */
gsl_vector *u = gsl_vector_alloc(n); /* solution vector */
size_t i;
/* construct the sparse matrix for the finite difference equation */
/* construct first row */
gsl_spmatrix_set(A, 0, 0, -2.0);
gsl_spmatrix_set(A, 0, 1, 1.0);
/* construct rows [1:n-2] */
for (i = 1; i < n - 1; ++i)
{
gsl_spmatrix_set(A, i, i + 1, 1.0);
gsl_spmatrix_set(A, i, i, -2.0);
gsl_spmatrix_set(A, i, i - 1, 1.0);
}
/* construct last row */
gsl_spmatrix_set(A, n - 1, n - 1, -2.0);
gsl_spmatrix_set(A, n - 1, n - 2, 1.0);
/* scale by h^2 */
gsl_spmatrix_scale(A, 1.0 / (h * h));
/* construct right hand side vector */
for (i = 0; i < n; ++i)
{
double xi = (i + 1) * h;
double fi = -M_PI * M_PI * sin(M_PI * xi);
gsl_vector_set(f, i, fi);
}
/* convert to compressed column format */
C = gsl_spmatrix_ccs(A);
/* now solve the system with the GMRES iterative solver */
{
const double tol = 1.0e-6; /* solution relative tolerance */
const size_t max_iter = 10; /* maximum iterations */
const gsl_splinalg_itersolve_type *T = gsl_splinalg_itersolve_gmres;
gsl_splinalg_itersolve *work =
gsl_splinalg_itersolve_alloc(T, n, 0);
size_t iter = 0;
double residual;
int status;
/* initial guess u = 0 */
gsl_vector_set_zero(u);
/* solve the system A u = f */
do
{
status = gsl_splinalg_itersolve_iterate(C, f, tol, u, work);
/* print out residual norm ||A*u - f|| */
residual = gsl_splinalg_itersolve_normr(work);
fprintf(stderr, "iter %zu residual = %.12e\n", iter, residual);
if (status == GSL_SUCCESS)
fprintf(stderr, "Converged\n");
}
while (status == GSL_CONTINUE && ++iter < max_iter);
/* output solution */
for (i = 0; i < n; ++i)
{
double xi = (i + 1) * h;
double u_exact = sin(M_PI * xi);
double u_gsl = gsl_vector_get(u, i);
printf("%f %.12e %.12e\n", xi, u_gsl, u_exact);
}
gsl_splinalg_itersolve_free(work);
}
gsl_spmatrix_free(A);
gsl_spmatrix_free(C);
gsl_vector_free(f);
gsl_vector_free(u);
return 0;
} /* main() */
| {
"alphanum_fraction": 0.574822695,
"avg_line_length": 27.6470588235,
"ext": "c",
"hexsha": "5d9ba81827f0f25a57bb2b453645c0514d97eaa2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/poisson.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/poisson.c",
"max_line_length": 84,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/poisson.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": 876,
"size": 2820
} |
/**
* @file ica.h
* @brief PCA and ICA
* @author Kenichi Kumatani and John McDonough
*/
#ifndef ICA_H
#define ICA_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/refcount.h"
#include "common/jexception.h"
// ----- definition for class `PCA' -----
//
class PCA {
public:
PCA(unsigned dimN);
~PCA();
void pca_svd(gsl_matrix* input, gsl_matrix* basis, gsl_vector* eigenVal, gsl_vector* whiten);
void pca_eigen(gsl_matrix* input, gsl_matrix* basis, gsl_vector* eigenVal, gsl_vector* whiten);
private:
const unsigned _dimN;
gsl_vector* _work;
};
typedef refcount_ptr<PCA> PCAPtr;
// ----- definition for class `FastICA' -----
//
class FastICA {
public:
FastICA(unsigned dimN, unsigned maxIterN);
~FastICA();
void deflation(gsl_matrix* data, gsl_matrix* B, gsl_matrix* A, gsl_matrix* W, gsl_matrix* M,
gsl_matrix* neg, double eps, int maxIterN);
private:
const unsigned _dimN;
const unsigned _maxIterN;
gsl_matrix* _w;
gsl_matrix* _a;
gsl_matrix* _wr;
gsl_matrix* _BTw;
gsl_matrix* _BBTw;
gsl_matrix* _wOld;
gsl_matrix* _wOld2;
gsl_matrix* _wSum;
gsl_matrix* _wDiff;
gsl_matrix* _hypTan;
gsl_matrix* _dHypTan;
gsl_matrix* _dHypTanT;
gsl_matrix* _wDHypTanT;
gsl_matrix* _XHypTan;
};
typedef refcount_ptr<FastICA> FastICAPtr;
#endif
| {
"alphanum_fraction": 0.7039106145,
"avg_line_length": 20.1690140845,
"ext": "h",
"hexsha": "3159da06f62a1b16941b2c6d03880f29547ffed4",
"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/sad/ica.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/sad/ica.h",
"max_line_length": 97,
"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/sad/ica.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": 457,
"size": 1432
} |
// Implementation of the interface described in viewer_window.h.
#include <fcntl.h>
#include <math.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <gtk/gtkgl.h>
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <gsl/gsl_math.h>
#include "space_2d.h"
#include "utilities.h"
#include "viewer_window.h"
#ifdef G_LOG_DOMAIN
# undef G_LOG_DOMAIN
#endif
#define G_LOG_DOMAIN "ViewerWindow"
// Flag true iff initialize_libraries has been run.
static gboolean initialized = FALSE;
// OpenGL configuration we use.
static GdkGLConfig *glconfig = NULL;
// Throw a fatal exception if an OpenGL error is found.
static void
trap_opengl_errors (void)
{
GLenum gl_error_code = glGetError ();
if ( gl_error_code != GL_NO_ERROR ) {
g_error (__FILE__ " line %d: OpenGL error detected: %s", __LINE__,
gluErrorString (gl_error_code));
}
}
// Get a pointer to a blob of floating point data using fair means or
// foul. We want a blob st the region defined by start_x, start_y and
// extending min (ceil (win_w / zoom), image->size_x) in the x
// direction and min (ceil (win_h / zoom), image->size_y) in the y
// direction (all in base image coordinates) is fully represented at
// zoom factor zoom (as defined in ViewerWindow class) or better
// (better meaning more detailed). We return a pointer to the region,
// the position of the upper left corner of the region with respect to
// the base, the width and height of the returned data region in
// pixels (actual pixels, not base pixels), the actual zoom factor of
// the data retrieved, and a flag indicating if the returned memory is
// otherwise unowned (if it is, then the caller is responsible for
// freeing it, otherwise the caller must not).
static void
get_data_pointer (ViewerImage *image, size_t start_x, size_t start_y,
gfloat zoom, gint win_w, gint win_h, float **dp,
size_t *dp_start_x, size_t *dp_start_y,
size_t *dp_w, size_t *dp_h, gfloat *actual_zoom,
gboolean *unowned_memory)
{
// Insist that (start_x, start_y) refers to an image pixel.
g_assert (start_x >= 0);
g_assert (start_x < image->size_x + image->x_offset);
g_assert (start_y >= 0);
g_assert (start_y < image->size_y + image->y_offset);
// With a few small tweaks we might be able to make things work when
// zoomed in to the point of pixelation, but I haven't thought about
// it.
if ( zoom > 1.0 ) {
g_error ("zoom factor %f is greater than 1.0", zoom);
}
guint layer_zoom = lrint (pow (2.0, floor (log2 (1.0 / zoom))));
ssize_t desired_width = GSL_MIN (ceil (win_w / zoom),
image->size_x - start_x);
ssize_t desired_height = GSL_MIN (ceil (win_h / zoom),
image->size_y - start_y);
if ( viewer_image_pyramid (image) != NULL ) {
*actual_zoom = 1.0 / layer_zoom;
// Ensure that floating point math has worked as expected since we
// validated the zoom input parameter.
g_assert (*actual_zoom <= 1.0);
pyramid_get_region (image->pyramid, start_x, start_y, desired_width,
desired_height, layer_zoom, dp, dp_start_x,
dp_start_y, dp_w, dp_h, unowned_memory);
}
else {
// The image pyramids aren't ready yet, so in the meantime we show
// the user some data from the quickview image, or if that isn't
// sufficiently high resolution, we form a new region.
if ( zoom <= 1.0 / image->quick_view_stride ) {
*dp = image->quick_view;
*dp_start_x = 0;
*dp_start_y = 0;
*dp_w = image->qvw;
*dp_h = image->qvh;
*actual_zoom = 1.0 / image->quick_view_stride;
*unowned_memory = FALSE;
}
else {
// We don't try to center our sample pixels in the middle of the
// areas they represent or anything, after all we are only doing
// this while the pyramid is prepared.
const size_t pixel_stride = layer_zoom;
*dp_start_x = start_x;
*dp_start_y = start_y;
*dp_w = desired_width / pixel_stride;
*dp_h = desired_height / pixel_stride;
size_t dp_area = *dp_w * *dp_h;
g_assert (dp_area > 0);
*dp = g_new (float, dp_area);
size_t ii, jj;
size_t cr = 0;
GString *data_name
= my_g_string_new_printf ("%s.img", image->base_name->str);
int data_fd = open (data_name->str, O_RDONLY);
g_assert (data_fd != -1);
float *row_buffer = g_new (float, desired_width);
g_assert (row_buffer != NULL);
for ( jj = start_y ; jj <= desired_height - pixel_stride + start_y ;
jj += pixel_stride, cr++ ) {
size_t cc = 0;
off_t row_offset = sizeof (float) * (jj * image->size_x + start_x);
off_t lseek_result = lseek (data_fd, row_offset, SEEK_SET);
g_assert (lseek_result == row_offset);
// We don't bother trying to seek between samples in a row:
// its highly unlikely to be any faster, even if the stride is
// large.
size_t bytes_to_read = sizeof (float) * desired_width;
g_assert (bytes_to_read <= SSIZE_MAX);
ssize_t bytes_read = read (data_fd, row_buffer, bytes_to_read);
g_assert (bytes_read != -1);
if ( bytes_read != bytes_to_read ) {
g_error ("bytes_read (%llu) != bytes_to_read (%lld) while "
"attempting to read from file %s",
(long long unsigned) bytes_read,
(long long int) bytes_to_read, data_name->str);
}
g_assert (bytes_read == bytes_to_read);
for ( ii = start_x ; ii <= desired_width - pixel_stride + start_x ;
ii += pixel_stride, cc++ ) {
float pv = row_buffer[ii - start_x];
if ( G_BYTE_ORDER == G_LITTLE_ENDIAN ) {
swap_bytes_32 ((unsigned char *) &pv);
}
if ( cr * *dp_w + cc >= dp_area ) {
g_error ("internal memory allocation or reference error");
}
(*dp)[cr * *dp_w + cc] = pv;
}
}
int return_code = close (data_fd);
g_assert (return_code != -1);
my_g_string_free (data_name);
g_assert (row_buffer != NULL);
g_free (row_buffer);
*actual_zoom = 1.0 / pixel_stride;
*unowned_memory = TRUE;
}
}
return;
}
// Use the Space2d class to translate between big picture and OpenGL
// orthographic view coordinates (implicit in this is an understanding
// of the OpenGL projection in use -- see elsewhere).
static void
coord_translate_big_picture_to_opengl (ViewerWindow *self,
gdouble *x, gdouble *y)
{
GtkWidget *da = self->da;
Space2D *space = space_2d_new ();
// Register the big picture coordinate system.
CoordinateSystem2D *big_picture
= coordinate_system_2d_new (0.0, 0.0, 1.0, -1.0, 0.0, 0.0,
self->max_x, self->max_y);
space_2d_add_system (space, NULL, big_picture);
// Register the virtual window coordinate system (which covers the
// entire big picture coordinate system, but at reduced resolution).
CoordinateSystem2D *virtual_window
= coordinate_system_2d_new (0.0, 0.0, 1.0 / self->zoom, 1.0 / self->zoom,
0.0, 0.0, self->max_x * self->zoom,
self->max_y * self->zoom);
space_2d_add_system (space, big_picture, virtual_window);
// Register the drawing area coordinates as Gdk/Gtk knows them.
CoordinateSystem2D *screen
= coordinate_system_2d_new (self->hadj->value, self->vadj->value, 1.0, 1.0,
0.0, 0.0,
da->allocation.width,
da->allocation.height);
space_2d_add_system (space, virtual_window, screen);
CoordinateSystem2D *opengl_orthographic
= coordinate_system_2d_new (0.0, da->allocation.height, 1.0, -1.0,
0.0, 0.0,
da->allocation.width, da->allocation.height);
space_2d_add_system (space, screen, opengl_orthographic);
space_2d_translate (space, big_picture, opengl_orthographic, x, y);
space_2d_unref (space);
}
// Draw on the current gldrawable using the current glcontext in the
// current viewport and projection (i.e. gdk_gl_drawable_gl_begin must
// be in effect and the appropriate viewport and transformation
// matricies set).
static void
draw (ViewerWindow *viewer_window)
{
ViewerWindow *self = viewer_window; // Convenience alias.
glClear (GL_COLOR_BUFFER_BIT);
gint win_w = self->da->allocation.width;
gint win_h = self->da->allocation.height;
if ( self->dp_to_free != NULL ) {
g_free (self->dp_to_free);
self->dp_to_free = NULL;
}
// Pointer to data to draw for current frame.
float *dp = NULL;
// Position of upper left corner of data pointed to by dp relative
// to base image.
size_t dp_start_x, dp_start_y;
// Width and height of memory region pointed to by dp.
size_t dp_w, dp_h;
// dp pixels per image pixel.
gfloat dp_zoom;
// Upper left pixel image coordinates to fetch.
size_t ulp_x = GSL_MAX (0, (self->hadj->value / self->zoom
- self->image->x_offset));
size_t ulp_y = GSL_MAX (0, (self->vadj->value / self->zoom
- self->image->y_offset));
gboolean must_free_dp;
// If we have anything to draw (once we get trimming set up we
// should always have).
if ( !(ulp_x >= self->image->size_x || ulp_y >= self->image->size_y) ) {
get_data_pointer (self->image, ulp_x, ulp_y, self->zoom,
win_w, win_h, &dp, &dp_start_x, &dp_start_y,
&dp_w, &dp_h, &dp_zoom, &must_free_dp);
// If we don't own the memory, we will need to free it before the
// next redraw, so save a pointer to it.
if ( must_free_dp ) {
self->dp_to_free = dp;
}
else {
self->dp_to_free = NULL;
}
// We may have to let OpenGL do a bit more zooming out for us,
// since the pixels in our data region dp may still be higher
// resolution than we need.
GLfloat residual_zoom = self->zoom / dp_zoom;
g_assert (sizeof (int32_t) == sizeof (GLint));
g_assert (dp_w <= INT32_MAX);
glPixelStorei (GL_UNPACK_ROW_LENGTH, dp_w);
// Now we need to determine the actual region of interest in the
// returned data. Here we determine the offsets in get_data
// coordinates of the point we want to put in the top left corner
// of the window. // FIIXME: obviously the exact positioning of
// the raster image on screen is questionable after all the
// shenanegans we go through. All that is really gauranteed is
// that the cursor cross hair rendering is right for a zoom factor
// of 1.0 on the OpenGL implementation I developed on (though I
// think it should be ok for other sane implementations as well).
// It would be lovely to fix this for other zoom factors (i.e. so
// when the cursor steps visibly off the edge of the image, the
// info command reports it as off), but I think this is actually
// pretty hard: it would need an special single interface through
// which all positioning command and queries could go, plus a
// detailed knowledge of what OpenGL actually specifies. I'm not
// sure if it is even possible to use OpenGL commands to, say,
// draw the lines for the cursor and have things work out. One
// might have to set pixel values in the image itself. This way
// you only have to know precisly where the image is rendered,
// instead of precicely where the image is rendered, plus
// precisely where the drawing commands render, plus gaurantee
// that the two correspond perfectly. Another possibility is to
// find a library like cairo and/or glitz that has already
// addressed these formidible issues, and use it.
GLint roi_offset_x
= GSL_MAX ((round (self->hadj->value / self->zoom) - dp_start_x
- self->image->x_offset) * dp_zoom, 0.0);
g_assert (roi_offset_x >= 0);
GLint roi_offset_y
= GSL_MAX ((round (self->vadj->value / self->zoom) - dp_start_y
- self->image->y_offset) * dp_zoom, 0.0);
g_assert (roi_offset_y >= 0);
glPixelStorei (GL_UNPACK_SKIP_ROWS, roi_offset_y);
glPixelStorei (GL_UNPACK_SKIP_PIXELS, roi_offset_x);
// Here we do a bit of defensive programming to avoid problems
// with floating point inexactness. I'm not sure these assertions
// will always pass, it may be necessary to explicitly clamp the
// region of interest to be no wider than the remaining portion of
// the data region retrieved.
// One dimension of the data is probably smaller than the other,
// so we have these GSL_MIN calls to just use all the available
// data in a given direction if there isn't enough to fill the
// window.
GLint roi_w = GSL_MIN (dp_w - roi_offset_x,
ceil (win_w / residual_zoom));
g_assert (roi_offset_x + roi_w <= dp_w);
GLint roi_h = GSL_MIN (dp_h - roi_offset_y,
ceil (win_h / residual_zoom));
g_assert (roi_offset_y + roi_h <= dp_h);
glPixelZoom (residual_zoom, -residual_zoom);
// Raster position to pass to glRasterPos.
GLdouble x_raster_pos
= GSL_MAX (round (self->image->x_offset * self->zoom)
- self->hadj->value, 0);
GLdouble y_raster_pos
= (win_h - GSL_MAX (round (self->image->y_offset * self->zoom)
- self->vadj->value, 0));
// Sometimes floating point inexactness in the above expression
// may lead cause the entire image to get clipped (since OpenGL
// weirdly insists on clipping the entire image if the raster
// point is clipped). Instead of going to the trouble of texture
// mapping the image onto a polygon (OpenGL doesn't clip the
// entire polygon), we just have a small check to ensure that we
// haven't slipped below zero. But if we have slipped by very
// much, we need to rethink our algorithm.
GLdouble allowable_slop = 0.001;
if ( y_raster_pos > win_h ) {
g_assert (y_raster_pos < win_h + allowable_slop);
y_raster_pos = win_h;
}
// We would like the raster position to be exactly at the top of
// the window. But some sort of floating point comparison
// problems seem to occur even when we ensure that this is the
// case with the above code, and then use a glRasterPos2i call.
// The only thing that seems to work is to use glRasterPos2f and
// then nudge the value down just slightly. This gets us an image
// placed at the very top pixel of the window (no black line at
// the top) and doesn't seem to get the entire image clipped. But
// I wouldn't be shocked to see other OpenGL implementation behave
// differently, possibly clipping the image out of existence.
GLdouble downward_nudge = 0.0001;
GLdouble rightward_nudge = downward_nudge;
glRasterPos2d (x_raster_pos + rightward_nudge,
y_raster_pos - downward_nudge);
// The range for which we will perform linear mapping.
gdouble linear_bottom, linear_top;
ViewerImage *ci = self->image;
if ( ci->sigmas <= 0.0 ) {
linear_bottom = ci->min;
linear_top = ci->max;
}
else {
linear_bottom = ci->mean - ci->sigmas * ci->sdev;
linear_top = ci->mean + ci->sigmas * ci->sdev;
}
float bias = linear_bottom;
float scale = linear_top - linear_bottom;
// FIIXME: should bias be negated here? It works this way but seems
// strange.
glPixelTransferf (GL_RED_BIAS, bias / scale);
glPixelTransferf (GL_GREEN_BIAS, bias / scale);
glPixelTransferf (GL_BLUE_BIAS, bias / scale);
glPixelTransferf (GL_RED_SCALE, 1.0 / scale);
glPixelTransferf (GL_GREEN_SCALE, 1.0 / scale);
glPixelTransferf (GL_BLUE_SCALE, 1.0 / scale);
// OpenGL will clamp the results of the above scale and bias
// operations into the range [0, 1] for us, so at this point we
// have effectively implemented the advertised sigma clamping.
glDrawPixels (roi_w, roi_h, GL_LUMINANCE, GL_FLOAT, dp);
}
// If the cursor has been placed, draw it (it may get clipped, which
// is fine).
if ( self->cursor_x != -1 ) {
g_assert (self->cursor_y != -1);
const int cursor_size = 19; // Cursor size, in pixels.
g_assert (cursor_size % 2 == 1);
gdouble x_ogl = self->cursor_x, y_ogl = self->cursor_y;
coord_translate_big_picture_to_opengl (self, &x_ogl, &y_ogl);
// Deal with translation inexactness.
x_ogl = round (x_ogl);
y_ogl = round (y_ogl);
// The same trick we have to pull with the raster position for the
// image itself to keep the image from sometimes getting clipped,
// we have to pull here. I'm not exactly sure why.
GLdouble downward_nudge = 0.1;
y_ogl -= downward_nudge;
// Looks like we also have to pull this trick in the x direction.
// GLdouble rightward_nudge = downward_nudge;
//x_ogl += rightward_nudge;
glColor3d (1.0, 0.0, 0.0); // A pretty red cursor.
glBegin (GL_LINES);
{
glVertex2d (x_ogl - cursor_size / 2, y_ogl);
glVertex2d (x_ogl + cursor_size / 2, y_ogl);
}
glEnd ();
glBegin (GL_LINES);
{
glVertex2d (x_ogl, y_ogl - cursor_size / 2);
glVertex2d (x_ogl, y_ogl + cursor_size / 2);
}
glEnd ();
// Sigh... OpenGL is pixel-inexact. The implementation I'm on
// seems to omit the pixel at the end of the line segment, others
// might do it differently. So we explicitly add the end points
// as dots. IMPROVEME: we're assuming dot size of 1 pixel here,
// this is a piece of OpenGL state that should be queried and
// asserted.
glBegin (GL_POINTS);
{
glVertex2d (x_ogl - cursor_size / 2, y_ogl);
glVertex2d (x_ogl + cursor_size / 2, y_ogl);
glVertex2d (x_ogl, y_ogl - cursor_size / 2);
glVertex2d (x_ogl, y_ogl + cursor_size / 2);
}
glEnd ();
}
// This code draws a little red X near the lower left corner of the
// window (maybe useful for sorting out flipping and clipping
// issues).
/*
glColor3d (1.0, 0.0, 0.0);
glBegin (GL_LINES);
glVertex2d (20, 20);
glVertex2d (80, 80);
glEnd ();
glBegin (GL_LINES);
glVertex2d (20, 80);
glVertex2d (80, 20);
glEnd ();
*/
trap_opengl_errors ();
}
// This is currently a no-op handler. Its difficult to say exactly
// when we want to prevent the user from making the window large (they
// may be planning to zoom in as the next thing they do, so that
// displayed space that is outside the big picture coordinate system
// will then immediately get used). And making the window big doesn't
// happen by accident or cause a lot of confusion, so we don't worry
// about it.
static void
reset_window_max_dimensions (ViewerWindow *self)
{
// GdkGeometry hints;
// hints.max_width = self->max_x - self->hadj->value / self->zoom;
// hints.max_height = self->max_y - self->vadj->value / self->zoom;
// gtk_window_set_geometry_hints (GTK_WINDOW (self->w), self->da, &hints,
// GDK_HINT_MAX_SIZE);
}
// Fetch the GdkGLContext and GdkGLDrawable associated with
// drawing_area, call the draw routing to perform OpenGL rendering
// according to the current state of self, and swap or flush buffer
// (depending on double buffered status of the drawable).
static void
redraw_drawing_area (ViewerWindow *self, GtkWidget *drawing_area)
{
GdkGLContext *glcontext = gtk_widget_get_gl_context (drawing_area);
GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (drawing_area);
gboolean return_code = gdk_gl_drawable_gl_begin (gldrawable, glcontext);
g_assert (return_code);
{
draw (self);
if ( gdk_gl_drawable_is_double_buffered (gldrawable) ) {
gdk_gl_drawable_swap_buffers (gldrawable);
}
else {
// This code path is simple, but untested.
g_assert_not_reached ();
glFlush ();
}
}
gdk_gl_drawable_gl_end (gldrawable);
}
// Recompute the maximum window dimensions given self->zoom and the
// current adjustment positions, and hint gtk appropriately, then
// redraw the drawing area.
static void
on_adjustment_changed (GtkAdjustment *adj, ViewerWindow *self)
{
reset_window_max_dimensions (self);
redraw_drawing_area (self, self->da);
// FIIXME: I assume since the signature for this signal in the
// GtkAdjustment docs says this handler returns void, that either
// the default handler always runs and updates the rendering of the
// sliders themselves. Confirm this.
}
static void
after_realize (GtkWidget *widget, gpointer data)
{
ViewerWindow *self = data;
// It seems that only after we realize the drawing window do we
// really finally find out how big it really is.
GtkAdjustment *va = self->vadj, *ha = self->hadj;
va->page_size = self->da->allocation.height;
va->upper = ceil (GSL_MAX (self->max_y * self->zoom, va->page_size));
ha->page_size = self->da->allocation.width;
ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));
// In case Gtk needs to know to redraw its scrollbars (maybe the
// scrollbars get drawn before the drawing area is realized, I'm not
// sure). We disable our handler since the drawing area will get
// redrawn anyway.
g_signal_handlers_block_by_func (va, on_adjustment_changed, self);
g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);
g_signal_emit_by_name (va, "changed::");
g_signal_emit_by_name (ha, "changed::");
g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);
g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);
GdkGLContext *glcontext = gtk_widget_get_gl_context (widget);
GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (widget);
gboolean return_code = gdk_gl_drawable_gl_begin (gldrawable, glcontext);
g_assert (return_code);
{
draw (self);
}
gdk_gl_drawable_gl_end (gldrawable);
}
typedef struct {
GtkAdjustment *vertical;
GtkAdjustment *horizontal;
} marshaled_adjustments;
static gboolean
on_drawing_area_configure_event (GtkWidget *widget, GdkEventConfigure *event,
gpointer data)
{
GdkGLContext *glcontext = gtk_widget_get_gl_context (widget);
GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (widget);
gint w = widget->allocation.width, h = widget->allocation.height;
gboolean return_code = gdk_gl_drawable_gl_begin (gldrawable, glcontext);
g_assert (return_code);
{
glViewport (0, 0, w, h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D (0.0, (GLfloat) w, 0.0, (GLfloat) h);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
}
gdk_gl_drawable_gl_end (gldrawable);
ViewerWindow *self = data;
// Convenience aliases.
GtkAdjustment *ha = self->hadj, *va = self->vadj;
// We want the increments to be whole numbers, hence floor().
ha->step_increment = floor (w / 4.0);
ha->page_increment = floor (w / 2.0);
ha->page_size = w;
va->step_increment = floor (h / 4.0);
va->page_increment = floor (h / 2.0);
va->page_size = h;
// If the window is now bigger the the portion of the big picture
// domain with upper left corner at the same position it was before
// the resize, as rendered at this zoom level, go ahead and zoom in
// (leaving the upper left corner in the same position in big
// picture coordinates).
// Bottom right of big picture in current virtual window
// coordinates. IMPROVEME: this way of handling resizing
// unfortunately pulls us off power-of-two zoom levels, which
// creates aliasing. When power-of-two zoom level locking is
// implemented, probably what will need to happen is to make the big
// picture domain bigger by a precomputed amount so that we only
// need to zoom on resize if we can do it as a power of two.
// Bottom right of big picture coordinate domain in viewer window
// coordinates.
double brvw_x = self->max_x * self->zoom, brvw_y = self->max_y * self->zoom;
gfloat old_zoom = self->zoom;
if ( brvw_x - ha->value < w && brvw_y - va->value < h ) {
if ( (brvw_x - ha->value) / w > (brvw_y - va->value) / h ) {
self->zoom = (w + ha->value) / self->max_x;
}
else {
self->zoom = (w + va->value) / self->max_y;
}
// Since we don't zooming to the point of pixelation at the
// moment, floating inexactness in the above code can trip us up
// elsewhere. It would also be nice to clamp to power of two or
// using antialiasing convolution filtering in OpenGL, as
// mentioned elsewhere.
if ( self->zoom > 1.0 ) {
gdouble max_slop = 0.01;
// If this isn't a small correction, we probably have a genuine
// problem somewhere.
if ( self->zoom - 1.0 > max_slop ) {
g_error ("floating point slop too large: self->zoom - 1.0 = %lf\n",
self->zoom - 1.0);
}
self->zoom = 1.0;
}
ha->value = round (ha->value * self->zoom / old_zoom);
va->value = round (va->value * self->zoom / old_zoom);
ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));
va->upper = ceil (GSL_MAX (self->max_x * self->zoom, va->page_size));
}
// FIIXME: confirm: I don't think we need or want to emit any changed
// signals for the adjustments here, since if we get a configure
// event we should also get an expose event or the like which should
// redraw the scroll bars and image area correctly anyway. It seems
// to work.
// g_signal_emit_by_name (self->hadj, "changed::");
// g_signal_emit_by_name (self->vadj, "changed::");
return TRUE;
}
static gboolean
on_expose_event (GtkWidget *widget, GdkEventExpose *event, ViewerWindow *self)
{
redraw_drawing_area (self, widget);
return TRUE;
}
static gboolean
on_button_press_event (GtkWidget *widget, GdkEventButton *event,
ViewerWindow *self)
{
// Here I test out the mental economy of my Space2D class. Indulge
// me. It would of course be more economical to keep the coordinate
// systems around more permanently somewhere else.
Space2D *space = space_2d_new ();
// Register the big picture coordinate system.
CoordinateSystem2D *big_picture
= coordinate_system_2d_new (0.0, 0.0, 1.0, -1.0, 0.0, 0.0,
self->max_x, self->max_y);
space_2d_add_system (space, NULL, big_picture);
// Register the virtual window coordinate system (which covers the
// entire big picture coordinate system, but at reduced resolution).
CoordinateSystem2D *virtual_window
= coordinate_system_2d_new (0.0, 0.0, 1.0 / self->zoom, 1.0 / self->zoom,
0.0, 0.0, self->max_x * self->zoom,
self->max_y * self->zoom);
space_2d_add_system (space, big_picture, virtual_window);
// Register the drawing area coordinates as Gdk/Gtk knows them.
CoordinateSystem2D *screen
= coordinate_system_2d_new (self->hadj->value, self->vadj->value, 1.0, 1.0,
0.0, 0.0,
widget->allocation.width,
widget->allocation.height);
space_2d_add_system (space, virtual_window, screen);
// Register the current image under the big picture system.
ViewerImage *ci = self->image; // Convenience alias.
CoordinateSystem2D *current_image
= coordinate_system_2d_new (ci->x_offset, ci->y_offset, 1.0, 1.0,
0.0, 0.0, ci->size_x - 1, ci->size_y - 1);
space_2d_add_system (space, big_picture, current_image);
// Now we should be able to effortlessly translate the window
// coordinates given to us in the GdkEventButton structure into
// coordinates in (or not in, as the case may be) the current image.
gdouble xc = event->x, yc = event->y;
space_2d_translate (space, screen, big_picture, &xc, &yc);
space_2d_unref (space);
if ( event->button == 1 ) {
self->cursor_x = xc;
self->cursor_y = yc;
}
redraw_drawing_area (self, self->da);
return FALSE; // Return FALSE tell Gtk to go ahead and propagate event.
}
// Convert a GDK state, keyval pair to a single representative
// character.
static gchar
find_key_op (guint state, guint keyval)
{
if ( keyval == GDK_minus ) {
return '-';
}
if ( state | GDK_SHIFT_MASK && keyval == GDK_plus ) {
return '+';
}
if ( keyval == GDK_N ) {
return 'N';
}
if ( keyval == GDK_n ) {
return 'n';
}
if ( keyval == GDK_P ) {
return 'P';
}
if ( keyval == GDK_p ) {
return 'p';
}
if ( keyval == GDK_I ) {
return 'I';
}
if ( keyval == GDK_i ) {
return 'i';
}
if ( keyval == GDK_a ) {
return 'a';
}
if ( keyval == GDK_A ) {
return 'a';
}
// When Escape is pressed this routing returns... 'e'. Pretty silly
// but oh well, we didn't envision wanting Esc and our caller knows
// what 'e' means.
if ( keyval == GDK_Escape ) {
return 'e';
}
// We use this magic to mean "otherwise unrecognized key press".
return '~';
}
// Print to standard output some information about the pixel at the
// current cursor position.
static void
print_point_info_for_cursor (ViewerWindow *self)
{
// Convert cursor coordinates to current image coordinates.
size_t img_x = self->cursor_x - self->image->x_offset;
size_t img_y = self->cursor_y - self->image->y_offset;
g_print ("\n");
if ( self->cursor_x == -1 ) {
g_assert (self->cursor_y == -1); // By definition.
g_print ("Pixel info requested, but the cursor hasn't been placed yet.\n"
"Left click on the image to place it.\n");
}
else if ( img_x >= 0 && img_x < self->image->size_x
&& img_y >= 0 && img_y < self->image->size_y ) {
// Look up the value of the current pixel in the data file.
GString *data_file = g_string_new (self->image->base_name->str);
g_string_append (data_file, ".img");
// IMPROVEME: it would be nice to through in a check to make sure
// the file size is what we expect, to help catch file changes
// while the viewer is running.
FILE *df = fopen (data_file->str, "r");
g_assert (df != NULL);
off_t offset = (img_y * self->image->size_x + img_x) * sizeof (float);
int return_code = fseeko (df, offset, SEEK_SET);
g_assert (return_code == 0);
float pixel_value;
size_t read_count = fread (&pixel_value, sizeof(float), 1, df);
g_assert (read_count == 1);
return_code = fclose (df);
g_assert (return_code == 0);
if ( G_BYTE_ORDER == G_LITTLE_ENDIAN ) {
swap_bytes_32 ((unsigned char *) &pixel_value);
}
g_print ("Pixel information:\n");
g_print ("------------------------------------------------------------\n");
g_print ("File base name: %s\n", self->image->base_name->str);
g_print ("Image pixel (row, column): (%d, %d)\n", img_x, img_y);
g_print ("Pixel value: %f\n", pixel_value);
}
else {
g_print ("Current cursor position is outside current image. Left click\n"
"on the image to reposition the cursor inside the image.\n");
}
g_print ("\n");
}
// Run the analysis program on the tile surrounding the current cursor
// position using the analysis-program related data members.
static void
run_analysis (ViewerWindow *self)
{
g_assert (self->cursor_x != -1);
g_assert (self->cursor_y != -1);
g_assert (self->analysis_program != NULL);
GString *command_line = g_string_new (self->analysis_program->str);
g_string_append_c (command_line, ' ');
g_string_append_printf (command_line, "%u ", self->images->len);
// We will end up creating a bunch of temporary files that we'll
// need to remove.
GPtrArray *tmp_files = g_ptr_array_new ();
guint ii;
for ( ii = 0 ; ii < self->images->len ; ii++ ) {
ViewerImage *ci = g_ptr_array_index (self->images, ii); // Current image.
g_string_append_printf (command_line, "%s ", ci->base_name->str);
ssize_t image_x = self->cursor_x - ci->x_offset;
ssize_t image_y = self->cursor_y - ci->y_offset;
// Start x and start y of tile in image.
size_t start_x = image_x - self->analysis_tile_size / 2;
size_t start_y = image_y - self->analysis_tile_size / 2;
// Tile width and height.
ssize_t tw = self->analysis_tile_size;
ssize_t th = self->analysis_tile_size;
// Adjust dimensions and/or starting point if near image edges.
if ( image_x - self->analysis_tile_size / 2 < 0 ) {
start_x = 0;
tw += image_x - self->analysis_tile_size / 2;
}
if ( image_x + self->analysis_tile_size / 2 >= ci->size_x ) {
size_t overhang
= image_x + self->analysis_tile_size / 2 - ci->size_x + 1;
// start_x -= overhang;
tw -= overhang;
}
if ( tw < 0 ) {
tw = 0;
}
if ( image_y - self->analysis_tile_size / 2 < 0 ) {
start_y = 0;
th += image_y - self->analysis_tile_size / 2;
}
if ( image_y + self->analysis_tile_size / 2 >= ci->size_y ) {
size_t overhang
= image_y + self->analysis_tile_size / 2 - ci->size_y + 1;
// start_y -= overhang;
th -= overhang;
}
if ( th < 0 ) {
th = 0;
}
g_string_append_printf (command_line, "%lld %lld ",
(long long int) tw, (long long int) th);
// Read the actual tile data.
GString *data_name = g_string_new (ci->base_name->str);
g_string_append (data_name, ".img");
float *tile_data = my_read_data_rectangle (data_name->str, sizeof (float),
ci->size_x, start_x, start_y,
tw, th);
swap_array_bytes_32 (tile_data, tw * th);
// Store tile data in temporary file for use by analysis program.
// For uniqueness :)
GString *tile_tmp_file_name
= make_unique_tmp_file_name ("/tmp", "blagLEweird");
g_ptr_array_add (tmp_files, tile_tmp_file_name);
if ( tw > 0 && th > 0 ) {
g_assert (tw <= SSIZE_MAX);
g_assert (th <= SSIZE_MAX);
FloatImage *tile_fi = float_image_new_from_memory (tw, th, tile_data);
// FIIXME: verify: works for zero width or height tiles?
int return_code = float_image_store (tile_fi, tile_tmp_file_name->str,
FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);
g_assert (return_code == 0);
}
else {
// We have a tile file of size zero, which the float_image
// interface doesn't contend with, so we just use touch to
// create an empty file.
GString *touch_command = g_string_new ("touch ");
g_string_append (touch_command, tile_tmp_file_name->str);
int exit_code = system (touch_command->str);
g_assert (exit_code == 0);
g_string_free (touch_command, TRUE);
}
g_string_append_printf (command_line, "%s ", tile_tmp_file_name->str);
}
if ( self->async_analysis ) {
// IMPROVEME: in an ideal world we might document somehow for the
// user the fact that when analysis commands are run
// asynchronously, the temporary tile files that are created need
// to be removed by the analysis program itself.
GError *err = NULL;
gboolean exit_code = g_spawn_command_line_async (command_line->str, &err);
if ( ! exit_code ) {
g_printerr ("\nasynchronous analysis command execution failed: %s\n",
err->message);
}
}
else {
// FIIXME: confirm: I'm guess glib allocates these for us.
gchar *standard_output = NULL, *standard_error = NULL;
gint exit_status;
GError *err = NULL;
gboolean exit_code
= g_spawn_command_line_sync (command_line->str, &standard_output,
&standard_error, &exit_status, &err);
if ( standard_output != NULL ) {
g_print ("%s", standard_output);
}
if ( standard_error != NULL ) {
g_printerr ("%s", standard_error);
}
if ( ! exit_code ) {
g_printerr ("\nanalysis command execution failed: %s\n", err->message);
}
}
}
// Zoom in one step (power of two). We have to do a lot of special
// stuff at minimum or maximum zoom, around image edges, etc.
static void
step_zoom_in (ViewerWindow *self)
{
// At most one screen pixel per image pixel.
const gfloat max_zoom = 1.0;
// Remember old values so we can adjust the adjustments correctly.
GtkAdjustment *va = self->vadj, *ha = self->hadj;
gdouble v_old_upper = va->upper, h_old_upper = ha->upper;
gdouble v_old_middle = va->value + va->page_size / 2.0;
gdouble h_old_middle = ha->value + ha->page_size / 2.0;
gfloat old_zoom = self->zoom;
// Zoom, but only up to the maximum. IMPROVEME: it would be best to
// only zoom by factors of 2.0, even when the window is resized.
// The pyramids are of these powers naturally, so no additional
// OpenGL scaling needs to be done. The additional scaling probably
// introduces aliasing, which is kind of a shame since the whole
// point of building the pyramids is to produce good looking results
// at different resolutions. For now, we just clamp to powers ot
// two here in the zoom in/out code, not in the code that handles
// window resizing. This is somewhat reasonable, since doing this
// gives the user our best available rendering when they try to look
// at something in detail, which is when it counts. It isn't really
// the ideal arrangement though. Another potential option is to use
// an antialiasing OpenGL convolution filter. But I'm not sure
// exactly how to do that, or even what the tradeoffs are exactly.
self->zoom *= 2.0;
// Clamp to a power of 2.0.
gdouble power = round (log2 (self->zoom));
self->zoom = pow (2.0, power);
if ( self->zoom > max_zoom ) {
self->zoom = max_zoom;
}
// Compute the new upper value and current value of the adjustments,
// given the new virtual window size.
gfloat zoom_ratio = self->zoom / old_zoom;
// Update the vertical adjustment.
va->upper = ceil (va->upper * zoom_ratio);
gfloat v_new_middle = v_old_middle * va->upper / v_old_upper;
// When we zoom, we may end up with a different part of the image in
// the center, since we try to avoid showing areas not in the big
// picture coordinate system, and configure events may have changed
// the window size.
if ( v_new_middle < va->page_size / 2.0 ) {
v_new_middle = va->page_size / 2.0;
}
if ( v_new_middle > va->upper - va->page_size / 2.0 ) {
v_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,
va->page_size / 2.0);
}
va->value = round (v_new_middle - va->page_size / 2.0);
// Floating point math might put us off by a tiny bit, so we check
// for this and clamp if needed.
const gfloat max_slop = 0.4;
if ( va->value < 0.0) {
// We should only be dealing with slight floating point
// inexactness here.
g_assert (va->value >= -0.4);
va->value = 0.0;
}
if ( va->value > va->upper - va->page_size ) {
g_assert (va->value - (va->upper - va->page_size) <= max_slop);
va->value = va->upper - va->page_size;
}
// Update the horizontal adjustment.
ha->upper = ceil (ha->upper * zoom_ratio);
gfloat h_new_middle = h_old_middle * ha->upper / h_old_upper;
// When we zoom, we may end up with a different part of the image in
// the center, since we try to avoid showing areas not in the big
// picture coordinate system, and configure events may have changed
// the window size.
if ( h_new_middle < ha->page_size / 2.0 ) {
h_new_middle = ha->page_size / 2.0;
}
if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {
h_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,
ha->page_size / 2.0);
}
ha->value = round (h_new_middle - ha->page_size / 2.0);
if ( ha->value < 0.0 ) {
// We should only be dealing with slight floating point
// inexactness here.
g_assert (ha->value >= -max_slop);
ha->value = 0.0;
}
if ( ha->value > ha->upper - ha->page_size ) {
gdouble slop = ha->value - (ha->upper - ha->page_size);
// FIIXME: I swear I got this condition to trip once at this slop
// threshold. So it might be necessary to change this into a
// warning, or loosen the tolerance a bit.
if ( slop > max_slop ) {
g_error ("too much slop (%lf) in floating point calculation in "
"file " __FILE__ " function %s, line %d", slop, __func__,
__LINE__);
}
ha->value = round (ha->upper - ha->page_size);
}
// We unblock our own handler for three of the next four
// adjustment-related emissions, since all it does it recompute
// and rehint the max window dimensions and redraw the drawing
// area. Doing this once is enough. But we do want gtk to have
// a chance to run any code it needs to run to redraw the
// scrollbars and such.
gint block_count
= g_signal_handlers_block_by_func (va, on_adjustment_changed, self);
g_assert (block_count == 2);
block_count
= g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);
g_assert (block_count == 2);
{
g_signal_emit_by_name (va, "changed::");
g_signal_emit_by_name (ha, "changed::");
// IMPROVEME: Do we need both changed and value-changed
// emmisions? Gtk docs seem to suggest we do as of this
// writing, but this seems like a pretty silly requirement.
g_signal_emit_by_name (va, "value-changed::");
}
gint unblock_count
= g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);
g_assert (unblock_count == 2);
unblock_count
= g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);
g_assert (unblock_count == 2);
g_signal_emit_by_name (ha, "value-changed::");
}
static void
step_zoom_out (ViewerWindow *self) {
// Remember old values so we can adjust the adjustments correctly.
GtkAdjustment *va = self->vadj, *ha = self->hadj;
gdouble v_old_middle = va->value + va->page_size / 2.0;
gdouble h_old_middle = ha->value + ha->page_size / 2.0;
gfloat old_zoom = self->zoom;
// The maximum zoom out we will allow is one that displays the
// entire big picture coordinate systme in the current window.
const gfloat min_zoom = GSL_MIN (ha->page_size / self->max_x,
va->page_size / self->max_y);
// Zoom, but only out to the maximum.
self->zoom /= 2.0;
if ( self->zoom < min_zoom ) {
self->zoom = min_zoom;
}
// Compute the new upper value and current value of the adjustments,
// given the new virtual window size.
gfloat zoom_ratio = self->zoom / old_zoom;
// Update the vertical adjustment.
va->upper = ceil (GSL_MAX (self->max_y * self->zoom, va->page_size));
gfloat v_new_middle = v_old_middle * zoom_ratio;
// When we zoom out, we may end up with a different part of the
// image in the center, since we try to avoid showing areas not in
// the big picture coordinate system.
if ( v_new_middle < va->page_size / 2.0 ) {
v_new_middle = va->page_size / 2.0;
}
if ( v_new_middle > va->upper - va->page_size / 2.0 ) {
v_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,
va->page_size / 2.0);
}
va->value = round (v_new_middle - va->page_size / 2.0);
// Floating point math might put us off by a tiny bit, so we check
// for this and clamp if needed.
const gfloat max_slop = 0.4;
if ( va->value < 0.0 ) {
// We should only be dealing with slight floating point
// inexactness here.
if ( va->value < -max_slop ) {
g_error ("Current vertical page position too negative: %lf\n",
va->value);
}
g_assert (va->value >= -max_slop);
va->value = 0.0;
}
if ( va->value > va->upper - va->page_size ) {
g_assert (va->value - (va->upper - va->page_size) <= max_slop);
va->value = va->upper - va->page_size;
}
// Update the horizontal adjustment.
ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));
gfloat h_new_middle = h_old_middle * zoom_ratio;
if ( h_new_middle < ha->page_size / 2.0 ) {
h_new_middle = ha->page_size / 2.0;
}
if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {
h_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,
ha->page_size / 2.0);
}
ha->value = round (h_new_middle - ha->page_size / 2.0);
if ( ha->value < 0.0 ) {
// We should only be dealing with slight floating point
// inexactness here.
g_assert (ha->value > -max_slop);
ha->value = 0.0;
}
if ( ha->value > ha->upper - ha->page_size ) {
gdouble margin = ha->value - (ha->upper - ha->page_size);
if ( margin > max_slop ) {
g_error ("Current hosizontal page position too much too large: %lf",
margin);
}
g_assert (ha->value - (ha->upper - ha->page_size) <= max_slop);
ha->value = ha->upper - ha->page_size;
}
// We unblock our own handler for three of the next four
// adjustment-related emissions, since all it does it recompute and
// rehint the max window dimensions and redraw the drawing area.
// Doing this once is enough. But we do want gtk to have a chance
// to run any code it needs to run to redraw the scrollbars and
// such.
gint block_count
= g_signal_handlers_block_by_func (va, on_adjustment_changed, self);
g_assert (block_count == 2);
block_count
= g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);
g_assert (block_count == 2);
{
g_signal_emit_by_name (va, "changed::");
g_signal_emit_by_name (ha, "changed::");
// IMPROVEME: Do we need both changed and value-changed emmisions?
// Gtk does seem to suggest yes as of this writing, but this seems
// like a pretty silly requirement.
g_signal_emit_by_name (va, "value-changed::");
}
gint unblock_count
= g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);
g_assert (unblock_count == 2);
unblock_count
= g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);
g_assert (unblock_count == 2);
g_signal_emit_by_name (ha, "value-changed::");
}
static gboolean
on_key_press_event (GtkWidget *win, GdkEventKey *event, gpointer user_data)
{
ViewerWindow *self = user_data;
gchar key_op = find_key_op (event->state, event->keyval);
switch ( key_op ) {
case 'I':
case 'i':
print_point_info_for_cursor (self);
break;
case '+':
{
// FIIXME: all this code should be replaced with a step_zoom_in call.
// At most one screen pixel per image pixel.
const gfloat max_zoom = 1.0;
// Remember old values so we can adjust the adjustments
// correctly.
GtkAdjustment *va = self->vadj, *ha = self->hadj;
gdouble v_old_upper = va->upper, h_old_upper = ha->upper;
gdouble v_old_middle = va->value + va->page_size / 2.0;
gdouble h_old_middle = ha->value + ha->page_size / 2.0;
gfloat old_zoom = self->zoom;
// Zoom, but only up to the maximum. IMPROVEME: it would be
// best to only zoom by factors of 2.0, even when the window is
// resized. The pyramids are of these powers naturally, so no
// additional OpenGL scaling needs to be done. The additional
// scaling probably introduces aliasing, which is kind of a
// shame since the whole point of building the pyramids is to
// produce good looking results at different resolutions. For
// now, we just clamp to powers ot two here in the zoom in/out
// code, not in the code that handles window resizing. This is
// somewhat reasonable, since doing this gives the user our best
// available rendering when they try to look at something in
// detail, which is when it counts. It isn't really the ideal
// arrangement though. Another potential option is to use an
// antialiasing OpenGL convolution filter. But I'm not sure
// exactly how to do that, or even what the tradeoffs are
// exactly.
self->zoom *= 2.0;
// Clamp to a power of 2.0.
gdouble power = round (log2 (self->zoom));
self->zoom = pow (2.0, power);
if ( self->zoom > max_zoom ) {
self->zoom = max_zoom;
}
// Compute the new upper value and current value of the
// adjustments, given the new virtual window size.
gfloat zoom_ratio = self->zoom / old_zoom;
// Update the vertical adjustment.
va->upper = ceil (va->upper * zoom_ratio);
gfloat v_new_middle = v_old_middle * va->upper / v_old_upper;
// When we zoom, we may end up with a different part of the
// image in the center, since we try to avoid showing areas not
// in the big picture coordinate system, and configure events
// may have changed the window size.
if ( v_new_middle < va->page_size / 2.0 ) {
v_new_middle = va->page_size / 2.0;
}
if ( v_new_middle > va->upper - va->page_size / 2.0 ) {
v_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,
va->page_size / 2.0);
}
va->value = round (v_new_middle - va->page_size / 2.0);
// Floating point math might put us off by a tiny bit, so we
// check for this and clamp if needed.
const gfloat max_slop = 0.4;
if ( va->value < 0.0) {
// We should only be dealing with slight floating point
// inexactness here.
g_assert (va->value >= -0.4);
va->value = 0.0;
}
if ( va->value > va->upper - va->page_size ) {
g_assert (va->value - (va->upper - va->page_size) <= max_slop);
va->value = va->upper - va->page_size;
}
// Update the horizontal adjustment.
ha->upper = ceil (ha->upper * zoom_ratio);
gfloat h_new_middle = h_old_middle * ha->upper / h_old_upper;
// When we zoom, we may end up with a different part of the
// image in the center, since we try to avoid showing areas not
// in the big picture coordinate system, and configure events
// may have changed the window size.
if ( h_new_middle < ha->page_size / 2.0 ) {
h_new_middle = ha->page_size / 2.0;
}
if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {
h_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,
ha->page_size / 2.0);
}
ha->value = round (h_new_middle - ha->page_size / 2.0);
if ( ha->value < 0.0 ) {
// We should only be dealing with slight floating point
// inexactness here.
g_assert (ha->value >= -max_slop);
ha->value = 0.0;
}
if ( ha->value > ha->upper - ha->page_size ) {
gdouble slop = ha->value - (ha->upper - ha->page_size);
// FIIXME: I swear I got this condition to trip once at this
// slop threshold. So it might be necessary to change this
// into a warning, or loosen the tolerance a bit.
if ( slop > max_slop ) {
g_error ("too much slop (%lf) in floating point calculation in "
"file " __FILE__ " function %s, line %d", slop, __func__,
__LINE__);
}
ha->value = round (ha->upper - ha->page_size);
}
// We unblock our own handler for three of the next four
// adjustment-related emissions, since all it does it recompute
// and rehint the max window dimensions and redraw the drawing
// area. Doing this once is enough. But we do want gtk to have
// a chance to run any code it needs to run to redraw the
// scrollbars and such.
gint block_count
= g_signal_handlers_block_by_func (va, on_adjustment_changed, self);
g_assert (block_count == 2);
block_count
= g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);
g_assert (block_count == 2);
{
g_signal_emit_by_name (va, "changed::");
g_signal_emit_by_name (ha, "changed::");
// IMPROVEME: Do we need both changed and value-changed
// emmisions? Gtk docs seem to suggest we do as of this
// writing, but this seems like a pretty silly requirement.
g_signal_emit_by_name (va, "value-changed::");
}
gint unblock_count
= g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);
g_assert (unblock_count == 2);
unblock_count
= g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);
g_assert (unblock_count == 2);
g_signal_emit_by_name (ha, "value-changed::");
break;
}
case '-':
{
// FIIXME: all this code should be replaced with a step_zoom_out call.
// Remember old values so we can adjust the adjustments
// correctly.
GtkAdjustment *va = self->vadj, *ha = self->hadj;
gdouble v_old_middle = va->value + va->page_size / 2.0;
gdouble h_old_middle = ha->value + ha->page_size / 2.0;
gfloat old_zoom = self->zoom;
// The maximum zoom out we will allow is one that displays the
// entire big picture coordinate systme in the current window.
const gfloat min_zoom = GSL_MIN (ha->page_size / self->max_x,
va->page_size / self->max_y);
// Zoom, but only out to the maximum.
self->zoom /= 2.0;
if ( self->zoom < min_zoom ) {
self->zoom = min_zoom;
}
// Compute the new upper value and current value of the
// adjustments, given the new virtual window size.
gfloat zoom_ratio = self->zoom / old_zoom;
// Update the vertical adjustment.
va->upper = ceil (GSL_MAX (self->max_y * self->zoom, va->page_size));
gfloat v_new_middle = v_old_middle * zoom_ratio;
// When we zoom out, we may end up with a different part of the
// image in the center, since we try to avoid showing areas not
// in the big picture coordinate system.
if ( v_new_middle < va->page_size / 2.0 ) {
v_new_middle = va->page_size / 2.0;
}
if ( v_new_middle > va->upper - va->page_size / 2.0 ) {
v_new_middle = GSL_MAX (va->upper - va->page_size / 2.0,
va->page_size / 2.0);
}
va->value = round (v_new_middle - va->page_size / 2.0);
// Floating point math might put us off by a tiny bit, so we
// check for this and clamp if needed.
const gfloat max_slop = 0.4;
if ( va->value < 0.0 ) {
// We should only be dealing with slight floating point
// inexactness here.
if ( va->value < -max_slop ) {
g_error ("Current vertical page position too negative: %lf\n",
va->value);
}
g_assert (va->value >= -max_slop);
va->value = 0.0;
}
if ( va->value > va->upper - va->page_size ) {
g_assert (va->value - (va->upper - va->page_size) <= max_slop);
va->value = va->upper - va->page_size;
}
// Update the horizontal adjustment.
ha->upper = ceil (GSL_MAX (self->max_x * self->zoom, ha->page_size));
gfloat h_new_middle = h_old_middle * zoom_ratio;
if ( h_new_middle < ha->page_size / 2.0 ) {
h_new_middle = ha->page_size / 2.0;
}
if ( h_new_middle > ha->upper - ha->page_size / 2.0 ) {
h_new_middle = GSL_MAX (ha->upper - ha->page_size / 2.0,
ha->page_size / 2.0);
}
ha->value = round (h_new_middle - ha->page_size / 2.0);
if ( ha->value < 0.0 ) {
// We should only be dealing with slight floating point
// inexactness here.
g_assert (ha->value > -max_slop);
ha->value = 0.0;
}
if ( ha->value > ha->upper - ha->page_size ) {
gdouble margin = ha->value - (ha->upper - ha->page_size);
if ( margin > max_slop ) {
g_error ("Current hosizontal page position too much too large: %lf",
margin);
}
g_assert (ha->value - (ha->upper - ha->page_size) <= max_slop);
ha->value = ha->upper - ha->page_size;
}
// We unblock our own handler for three of the next four
// adjustment-related emissions, since all it does it recompute
// and rehint the max window dimensions and redraw the drawing
// area. Doing this once is enough. But we do want gtk to have
// a chance to run any code it needs to run to redraw the
// scrollbars and such.
gint block_count
= g_signal_handlers_block_by_func (va, on_adjustment_changed, self);
g_assert (block_count == 2);
block_count
= g_signal_handlers_block_by_func (ha, on_adjustment_changed, self);
g_assert (block_count == 2);
{
g_signal_emit_by_name (va, "changed::");
g_signal_emit_by_name (ha, "changed::");
// IMPROVEME: Do we need both changed and value-changed
// emmisions? Gtk does seem to suggest yes as of this
// writing, but this seems like a pretty silly requirement.
g_signal_emit_by_name (va, "value-changed::");
}
gint unblock_count
= g_signal_handlers_unblock_by_func (ha, on_adjustment_changed, self);
g_assert (unblock_count == 2);
unblock_count
= g_signal_handlers_unblock_by_func (va, on_adjustment_changed, self);
g_assert (unblock_count == 2);
g_signal_emit_by_name (ha, "value-changed::");
break;
}
case 'N':
case 'n':
{
// Find the current image.
gboolean found = FALSE;
guint ii;
for ( ii = 0 ; ii < self->images->len ; ii++ ) {
ViewerImage *ci = g_ptr_array_index ( self->images, ii);
if ( ci == self->image ) {
found = TRUE;
break;
}
}
g_assert (found);
if ( self->images->len > 1 ) {
ii = (ii + 1) % self->images->len;
}
else {
g_print ("Only 1 image is loaded (i.e. there is no next image).");
}
self->image = g_ptr_array_index (self->images, ii);
redraw_drawing_area (self, self->da);
break;
}
case 'P':
case 'p':
{
// Find the current image.
gboolean found = FALSE;
guint ii;
for ( ii = 0 ; ii < self->images->len ; ii++ ) {
if ( g_ptr_array_index (self->images, ii) == self->image ) {
found = TRUE;
break;
}
}
g_assert (found);
if ( self->images->len > 1 ) {
if ( ii == 0 ) {
ii = self->images->len - 1;
}
else {
ii--;
}
}
else {
g_print ("Only 1 image is loaded (i.e. there is no previous image).");
}
self->image = g_ptr_array_index (self->images, ii);
redraw_drawing_area (self, self->da);
break;
}
case 'a':
{
// Analyze a tile around the current cursor location.
if ( self->analysis_program == NULL ) {
g_print ("\n");
g_print ("Analysis requested, but no analysis program was specified\n"
"with the --analysis-program command line option.\n");
}
else if ( self->cursor_x == -1 ) {
g_assert (self->cursor_y == -1);
g_print ("\n");
g_print ("Analysis requested, but the cursor has not been placed.\n"
"(left click to place the cursor)\n");
}
else {
run_analysis (self);
}
}
break;
case 'e':
{
g_signal_emit_by_name (self->w, "delete_event::");
}
case '~':
{
// An key not obviously convertible to a single letter, or an
// key the simple conversion routine hasn't been taught about.
switch ( event->keyval ) {
case GDK_Up:
self->cursor_y--;
if ( self->cursor_y < 0 ) {
self->cursor_y = 0;
}
break;
case GDK_Down:
self->cursor_y++;
// The cursor can be on max_y (instead of max_y - 1) because
// we have defined max_y as the largest addressable index.
if ( self->cursor_y > self->max_y ) {
self->cursor_y = self->max_y;
}
break;
case GDK_Left:
self->cursor_x--;
if ( self->cursor_x < 0 ) {
self->cursor_x = 0;
}
break;
case GDK_Right:
self->cursor_x++;
// The cursor can be on max_x (instead of max_x - 1) because
// we have defined max_y as the largest addressable index.
if ( self->cursor_x > self->max_x ) {
self->cursor_x = self->max_x;
}
break;
default:
break;
}
redraw_drawing_area (self, self->da);
break;
}
default:
break;
}
return FALSE;
}
static gboolean
on_scroll_event (GtkDrawingArea *da, GdkEventScroll *event, ViewerWindow *self)
{
if ( event->direction == GDK_SCROLL_UP ) {
step_zoom_in (self);
}
else if ( event->direction == GDK_SCROLL_DOWN ) {
step_zoom_out (self);
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////
//
// Click and Drag Scrolling
//
// Together these handlers implement click-and-drag-to-scroll.
//
static gboolean
also_on_button_press_event (GtkDrawingArea *da, GdkEventButton *event,
ViewerWindow *self)
{
if ( event->type == GDK_BUTTON_PRESS && event->button == 2 ) {
// FIXME: initialize these to magic and reset between to magic.
self->drag_start_x = event->x;
self->drag_start_y = event->y;
self->drag_start_hadj_value = gtk_adjustment_get_value (self->hadj);
self->drag_start_vadj_value = gtk_adjustment_get_value (self->vadj);
}
return FALSE;
}
static void
drag_scroll (ViewerWindow *self, gdouble x, gdouble y)
{
gdouble delta_x = x - self->drag_start_x, delta_y = y - self->drag_start_y;
// Determine the new horizontal adjustment value.
gdouble new_hval = self->drag_start_hadj_value - delta_x;
gdouble drag_hmax = self->hadj->upper - self->hadj->page_size;
if ( new_hval > drag_hmax ) {
new_hval = drag_hmax;
}
gtk_adjustment_set_value (self->hadj, new_hval);
// Determine the new vertical adjustment value.
gdouble new_vval = self->drag_start_vadj_value - delta_y;
gdouble drag_vmax = self->vadj->upper - self->vadj->page_size;
if ( new_vval > drag_vmax ) {
new_vval = drag_vmax;
}
gtk_adjustment_set_value (self->vadj, new_vval);
// We only want to end up redrawing once, so we block our handler
// for one of the two adjustment changed emissions. But we still
// emit both so internal Gtk handlers can update the scroll bars or
// whatever they do.
gint block_count
= g_signal_handlers_block_by_func (self->hadj, on_adjustment_changed,
self);
g_assert (block_count == 2);
{
gtk_adjustment_value_changed (self->hadj);
}
gint unblock_count
= g_signal_handlers_unblock_by_func (self->hadj, on_adjustment_changed,
self);
g_assert (unblock_count == 2);
gtk_adjustment_value_changed (self->vadj);
}
static gboolean
on_motion_notify_event (GtkDrawingArea *da, GdkEventMotion *event,
ViewerWindow *self)
{
if ( event->state & GDK_BUTTON2_MASK ) {
if ( self->drag_start_x != -1 ) {
drag_scroll (self, event->x, event->y);
}
else {
g_assert (self->drag_start_y == -1);
}
// We don't really care what this call returns, since we have
// already redrawn according to the motion_notify_event we just
// received, but we make it in order to let GDK know we're ready
// for the next motion event (seek GdkEventMask documentation, in
// particular the discussion of GDK_POINTER_MOTION_HINT_MASK).
gint junk_x, junk_y;
GdkModifierType mask;
gdk_window_get_pointer ((GTK_WIDGET (da))->window, &junk_x, &junk_y,
&mask);
}
return FALSE;
}
static gboolean
on_button_release_event (GtkDrawingArea *da, GdkEventButton *event,
ViewerWindow *self)
{
if ( event->type == GDK_BUTTON_RELEASE && event->button == 2 ) {
if ( self->drag_start_x != -1 ) {
drag_scroll (self, event->x, event->y);
}
self->drag_start_x = -1;
self->drag_start_y = -1;
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// Initialize the gtk and gtkglext libraries, and create the
// GdkGLConfig we will be usein.
static void
initialize_libraries (void)
{
// FIIXME: verify that passing NULL is really ok. It sure seems to work.
gtk_init (NULL, NULL);
gtk_gl_init (NULL, NULL);
// Check OpenGL version.
gint major, minor;
gdk_gl_query_version (&major, &minor);
g_assert (major >= 1 && minor >= 2);
glconfig = gdk_gl_config_new_by_mode ( GDK_GL_MODE_RGB
| GDK_GL_MODE_DEPTH
| GDK_GL_MODE_DOUBLE);
g_assert (glconfig != NULL);
}
ViewerWindow *
viewer_window_new (ViewerImage *image, GPtrArray *images,
size_t max_x, size_t max_y,
size_t start_x, size_t start_y, size_t w, size_t h,
GString *analysis_program, gboolean async_analysis,
gint analysis_tile_size)
{
if ( ! initialized ) {
initialize_libraries ();
}
ViewerWindow *self = g_new0 (ViewerWindow, 1);
self->image = viewer_image_ref (image);
// Note this is a pointer to a list owned by main(), so we must not
// change or free it.
self->images = images;
self->max_x = max_x;
self->max_y = max_y;
self->start_x = start_x;
self->start_y = start_y;
// The cursor begins life unplaced.
self->cursor_x = -1;
self->cursor_y = -1;
// Store the analysis-related arguments.
if ( analysis_program == NULL ) {
self->analysis_program = NULL;
}
else {
self->analysis_program = g_string_new (analysis_program->str);
self->async_analysis = async_analysis;
self->analysis_tile_size = analysis_tile_size;
}
// Haven't gotten any data to draw before, so there isn't going to
// be anything to free the first time we draw.
self->dp_to_free = NULL;
// Set up the Gtk window.
GtkWidget *window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
// Top level GtkObject instances have only a floating reference
// which gets claimed by the GTK library itself, so we have to ref
// the window.
gtk_widget_ref (window);
GString *title = g_string_new (image->base_name->str);
g_string_prepend (title, "ssv: ");
gtk_window_set_title (GTK_WINDOW (window), title->str);
gtk_container_set_reallocate_redraws (GTK_CONTAINER (window), TRUE);
self->w = window;
// Set up table to hold the drawing area and scrollbars.
GtkTable *table = GTK_TABLE (gtk_table_new (2, 2, FALSE));
GtkWidget *hbar = gtk_hscrollbar_new (NULL);
// IMPROVEME: we may want to use UPDATE_DELAYED until we find that
// the pyramids are done.
gtk_range_set_update_policy (GTK_RANGE (hbar), GTK_UPDATE_CONTINUOUS);
GtkAdjustment *hadj = gtk_range_get_adjustment (GTK_RANGE (hbar));
hadj->lower = 0;
hadj->value = 0;
self->hadj = hadj;
GtkWidget *vbar = gtk_vscrollbar_new (NULL);
// IMPROVEME: we may want to use UPDATE_DELAYED until we find that
// the pyramids are done.
gtk_range_set_update_policy (GTK_RANGE (vbar), GTK_UPDATE_CONTINUOUS);
GtkAdjustment *vadj = gtk_range_get_adjustment (GTK_RANGE (vbar));
vadj->lower = 0;
vadj->value = 0;
self->vadj = vadj;
gtk_table_attach (table, vbar, 1, 2, 0, 1, GTK_FILL, GTK_FILL | GTK_EXPAND,
0, 0);
gtk_table_attach (table, hbar, 0, 1, 1, 2, GTK_FILL | GTK_EXPAND, GTK_FILL,
0, 0);
// When the GtkAdjustment instances associated with the scrollbars
// change, we need to redraw things.
g_signal_connect (vadj, "changed::", G_CALLBACK (on_adjustment_changed),
self);
g_signal_connect (vadj, "value-changed::",
G_CALLBACK (on_adjustment_changed), self);
g_signal_connect (hadj, "changed::", G_CALLBACK (on_adjustment_changed),
self);
g_signal_connect (hadj, "value-changed::",
G_CALLBACK (on_adjustment_changed), self);
// Set up the drawing area.
GtkWidget *da = gtk_drawing_area_new ();
gboolean return_code = gtk_widget_set_gl_capability (da, glconfig, NULL,
TRUE, GDK_GL_RGBA_TYPE);
g_assert (return_code);
g_signal_connect_after (G_OBJECT (da), "realize", G_CALLBACK (after_realize),
self);
g_signal_connect (G_OBJECT (da), "configure_event",
G_CALLBACK (on_drawing_area_configure_event), self);
g_signal_connect (G_OBJECT (da), "expose_event",
G_CALLBACK (on_expose_event), self);
gtk_widget_add_events (da, GDK_BUTTON_PRESS_MASK);
g_signal_connect (G_OBJECT (da), "button_press_event",
G_CALLBACK (on_button_press_event), self);
self->da = da;
// Path the drawing area into the table.
gtk_table_attach_defaults (table, self->da, 0, 1, 0, 1);
// Pack the table into the window.
gtk_container_add (GTK_CONTAINER (self->w), GTK_WIDGET (table));
// True iff the entire image should fit in a drawing area of the
// default dimensions without any zooming.
size_t def_w = VIEWER_WINDOW_DRAWING_AREA_DEFAULT_WIDTH;
size_t def_h = VIEWER_WINDOW_DRAWING_AREA_DEFAULT_HEIGHT;
gboolean image_fits = (w <= def_w && h <= def_h);
if ( image_fits ) {
self->zoom = 1.0;
// The entire image should ift in the drawing area, so we can just
// use a smaller drawing area. IMPROVEME: but maybe using small
// windows sometimes is just confusing and irritating to the user,
// and causes window managers to place things inconsistently?
gtk_widget_set_size_request (self->da, w, h);
}
else {
// We try to make the drawing area have the standard default size.
// The window manager may thwart us, of course. IMPROVEME: here
// is another point where work might be needed to implement
// power-of-two zoom level locking (see IMPROVEME elsewhere).
gtk_widget_set_size_request (self->da, def_w, def_h);
if ( (double) w / def_w > (double) h / def_h ) {
self->zoom = (double) def_w / w;
}
else {
self->zoom = (double) def_h / h;
}
}
vadj->page_size = self->da->allocation.height;
vadj->upper = GSL_MAX (self->max_y * self->zoom, vadj->page_size);
hadj->page_size = self->da->allocation.width;
hadj->upper = GSL_MAX (self->max_x * self->zoom, hadj->page_size);
// FIIXME: Presumably don't need to emit a changed signal or
// anything on the adjustments here since everything is yet to be
// drawn (confirm)?
g_signal_connect (G_OBJECT (self->w), "key_press_event",
G_CALLBACK (on_key_press_event), self);
g_signal_connect (G_OBJECT (self->da), "scroll_event",
G_CALLBACK (on_scroll_event), self);
// Connect to the click-and-drag scrolling handlers.
g_signal_connect (G_OBJECT (self->da), "button_press_event",
G_CALLBACK (also_on_button_press_event), self);
g_signal_connect (G_OBJECT (self->da), "motion_notify_event",
G_CALLBACK (on_motion_notify_event), self);
g_signal_connect (G_OBJECT (self->da), "button_release_event",
G_CALLBACK (on_button_release_event), self);
GdkEventMask da_events;
g_object_get (G_OBJECT (self->da), "events", &da_events, NULL);
if ( ! (da_events
& (GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON2_MOTION_MASK)) ) {
da_events |= (GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON2_MOTION_MASK);
g_object_set (G_OBJECT (self->da), "events", da_events, NULL);
}
// Set the maximum dimensions of the window commensurate with the
// available data.
reset_window_max_dimensions (self);
// Here lies an attempt to figure out why sometimes the window comes
// out only the height of the layer for a roughly square layer. Who
// knows. Put it down to window manager evilness, though I think it
// might be a concurrency issue of some sort at the Gtk level.
/*
GtkResizeMode rm = gtk_container_get_resize_mode (GTK_CONTAINER (table));
switch ( rm ) {
case GTK_RESIZE_PARENT:
g_print ("table in PARENT mode\n");
break;
case GTK_RESIZE_QUEUE:
g_print ("table in QUEUE mode\n");
break;
case GTK_RESIZE_IMMEDIATE:
g_print ("table in IMMEDIATE mode\n");
break;
default:
g_assert_not_reached ();
break;
}
*/
// Display the new window and everything it contains (triggering the
// signals that do the OpenGL drawing).
gtk_widget_show_all (self->w);
gtk_widget_set_size_request (self->da, -1, -1);
self->reference_count = 1;
return self;
}
void
viewer_window_unref (ViewerWindow *self)
{
self->reference_count--;
if ( self->reference_count == 0 ) {
g_assert (self->w != NULL);
gtk_widget_unref (self->w);
viewer_image_unref (self->image);
g_free (self);
}
}
| {
"alphanum_fraction": 0.6645742706,
"avg_line_length": 35.6970156803,
"ext": "c",
"hexsha": "fe4490c23159b9cb222f603fb8e3a0c51be06ff2",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/ssv/viewer_window.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/ssv/viewer_window.c",
"max_line_length": 79,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/ssv/viewer_window.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 19667,
"size": 70573
} |
#pragma once
#include <type_traits>
#include <cuda/define_specifiers.hpp>
#include <cuda/runtime_api.hpp>
#include <gsl-lite/gsl-lite.hpp>
#include <thrustshift/fill.h>
namespace thrustshift {
namespace kernel {
template <typename SrcT, typename DstT>
__global__ void copy(gsl_lite::span<const SrcT> src, gsl_lite::span<DstT> dst) {
const auto gtid = threadIdx.x + blockIdx.x * blockDim.x;
if (gtid < src.size()) {
dst[gtid] = src[gtid];
}
}
template <typename SrcT, typename DstT, typename T, typename I>
__global__ void copy_find(gsl_lite::span<const SrcT> src,
gsl_lite::span<DstT> dst,
T value,
I* pos) {
const auto gtid = threadIdx.x + blockIdx.x * blockDim.x;
if (gtid < src.size()) {
const auto src_value = src[gtid];
dst[gtid] = src_value;
if (src_value == value) {
*pos = gtid;
}
}
}
} // namespace kernel
namespace async {
//! thrust uses sometimes a cudaMemcpyAsync instead of a copy kernel
template <class SrcRange, class DstRange>
void copy(cuda::stream_t& stream, SrcRange&& src, DstRange&& dst) {
gsl_Expects(src.size() == dst.size());
if (src.empty()) {
return;
}
using src_value_type =
typename std::remove_reference<SrcRange>::type::value_type;
using dst_value_type =
typename std::remove_reference<DstRange>::type::value_type;
constexpr cuda::grid::block_dimension_t block_dim = 128;
const cuda::grid::dimension_t grid_dim =
(src.size() + block_dim - 1) / block_dim;
auto c = cuda::make_launch_config(grid_dim, block_dim);
auto k = kernel::copy<src_value_type, dst_value_type>;
cuda::enqueue_launch(k, stream, c, src, dst);
}
//! Copy and search for an element. If the element occurs more than once, it
//! is undefined which of the valid positions is returned. If the element does
//! not occur `pos` is unchanged.
template <class SrcRange, class DstRange, typename T, typename I>
void copy_find(cuda::stream_t& stream,
SrcRange&& src,
DstRange&& dst,
const T& value,
I* pos) {
gsl_Expects(src.size() == dst.size());
gsl_Expects(pos != nullptr);
if (src.empty()) {
return;
}
using src_value_type =
typename std::remove_reference<SrcRange>::type::value_type;
using dst_value_type =
typename std::remove_reference<DstRange>::type::value_type;
constexpr cuda::grid::block_dimension_t block_dim = 128;
const cuda::grid::dimension_t grid_dim =
(src.size() + block_dim - 1) / block_dim;
auto c = cuda::make_launch_config(grid_dim, block_dim);
auto k = kernel::copy_find<src_value_type, dst_value_type, T, I>;
cuda::enqueue_launch(k, stream, c, src, dst, value, pos);
}
} // namespace async
namespace detail {
template <int BLOCK_DIM,
int NUM_ELEMENTS,
int LD_FIRST = NUM_ELEMENTS,
int LD_RESULT = NUM_ELEMENTS,
int NUM_PER_ROW_FIRST = NUM_ELEMENTS,
int NUM_PER_ROW_RESULT = NUM_ELEMENTS>
struct helper_t {
template <class iteratorA_t, class iteratorB_t, class F>
CUDA_FHD static void block_copy_even(iteratorA_t first,
iteratorB_t result,
int tid,
F f) {
if (BLOCK_DIM < NUM_ELEMENTS) {
// pragma unroll is device code specific
#ifdef __CUDA_ARCH__
#pragma unroll
#endif
for (int i = 0; i < NUM_ELEMENTS - BLOCK_DIM; i += BLOCK_DIM) {
f(first,
result,
i + ((i + tid) / NUM_PER_ROW_FIRST) *
(LD_FIRST - NUM_PER_ROW_FIRST) + tid,
i + ((i + tid) / NUM_PER_ROW_RESULT) *
(LD_RESULT - NUM_PER_ROW_RESULT) + tid);
}
}
}
template <class iteratorA_t, class iteratorB_t, class F>
CUDA_FHD static void block_copy_tail(iteratorA_t first,
iteratorB_t result,
int tid,
F f) {
if (NUM_ELEMENTS % BLOCK_DIM == 0) {
f(first,
result,
(NUM_ELEMENTS - BLOCK_DIM) +
(((NUM_ELEMENTS - BLOCK_DIM) + tid) / NUM_PER_ROW_FIRST) *
(LD_FIRST - NUM_PER_ROW_FIRST) + tid,
(NUM_ELEMENTS - BLOCK_DIM) +
(((NUM_ELEMENTS - BLOCK_DIM) + tid) / NUM_PER_ROW_RESULT) *
(LD_RESULT - NUM_PER_ROW_RESULT) + tid);
}
else if (tid + (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM < NUM_ELEMENTS) {
constexpr int j = (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM;
f(first,
result,
j + ((j + tid) / NUM_PER_ROW_FIRST) *
(LD_FIRST - NUM_PER_ROW_FIRST) + tid,
j + ((j + tid) / NUM_PER_ROW_RESULT) *
(LD_RESULT - NUM_PER_ROW_RESULT) + tid);
}
}
}; // helper
template <int BLOCK_DIM, int NUM_ELEMENTS>
struct helper_t<BLOCK_DIM,
NUM_ELEMENTS,
NUM_ELEMENTS,
NUM_ELEMENTS,
NUM_ELEMENTS,
NUM_ELEMENTS> {
template <class iteratorA_t, class iteratorB_t, class F>
CUDA_FHD static void block_copy_even(iteratorA_t first,
iteratorB_t result,
int tid,
F f) {
if (BLOCK_DIM < NUM_ELEMENTS) {
// pragma unroll is device code specific
#ifdef __CUDA_ARCH__
#pragma unroll
#endif
for (int i = 0; i < NUM_ELEMENTS - BLOCK_DIM; i += BLOCK_DIM) {
const int j = i + tid;
f(first, result, j, j);
}
}
}
template <class iteratorA_t, class iteratorB_t, class F>
CUDA_FHD static void block_copy_tail(iteratorA_t first,
iteratorB_t result,
int tid,
F f) {
if (NUM_ELEMENTS % BLOCK_DIM == 0) {
const int j = NUM_ELEMENTS - BLOCK_DIM + tid;
f(first,
result,
j,
j);
}
else if (tid + (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM < NUM_ELEMENTS) {
const int j = (NUM_ELEMENTS / BLOCK_DIM) * BLOCK_DIM + tid;
f(first, result, j, j);
}
}
}; // struct helper_t
//! Specialization for equal block dimension and number of elements
template <int BD_AND_NE>
struct helper_t<BD_AND_NE,
BD_AND_NE,
BD_AND_NE,
BD_AND_NE,
BD_AND_NE,
BD_AND_NE> {
template <class iteratorA_t, class iteratorB_t, class F>
CUDA_FHD static void block_copy_even(iteratorA_t first,
iteratorB_t result,
int tid,
F f) {
}
template <class iteratorA_t, class iteratorB_t, class F>
CUDA_FHD static void block_copy_tail(iteratorA_t first,
iteratorB_t result,
int tid,
F f) {
f(first, result, tid, tid);
}
}; // struct helper_t
}; // namespace detail
/* \brief Copy data blockwise with efficient loop unrolling.
*
* This function implements an efficient memory copy. This is in particular
* useful if you use only a few threads to copy data, since this is limited
* by register dependencies if trivially implemented. The algorithm is
* implemented in two steps. First we copy elements subsequently and
* block wise with the whole thread block:
*
* N = 11, bdim = 4: x x x x | x x x x | o o o
* N = 12, bdim = 4: x x x x | x x x x | o o o o
* N = 13, bdim = 4: x x x x | x x x x | x x x x | o
*
* Thus the last elements are not copied (denoted by `o`).
* Afterwards we must copy the remaining elements, which is
* trivial if N % bdim == 0.
*
* \param BLOCK_DIM Current thread block dimension
* \param NUM_ELEMENTS total amount of elements to copy
* \param LD_RESULT Leading dimension on result. Only used in case of two dimensional
* arranged data. This is equal to the number of elements, which
* must be skipped to get an element in the next row. This is
* useful if you want to skip some of the columns of the 2D data:
*
* | ld |
* x x x x o o
* x x x x o o
* x x x x o o
* x x x x o o
* | nepr |
*
* `nepr` = num elements per row
* `ld` = leading dimension
* If you want to copy only the `x` elements.
*
* \param NUM_PER_ROW Only used in case of two dimensional data copies
* \param first iterator to first read element
* \param result iterator to first result element
* \param f A functor to write the data, e.g.
* ```
* auto default_f = [](iteratorA_t first,
* iteratorB_t result,
* int i_first,
* int i_result) {
* result[i_result] = first[i_first];
* };
* ```
* `i_first` and `i_result` are the global indices on iterator `first` and `result`. With such
* a functor it is possible to modify the read and write process. E.g. you can read
* the data in a permuted way.
*
*/
template <int BLOCK_DIM,
int NUM_ELEMENTS,
class iteratorA_t,
class iteratorB_t,
int LD_FIRST = NUM_ELEMENTS,
int LD_RESULT = NUM_ELEMENTS,
int NUM_PER_ROW_FIRST = NUM_ELEMENTS,
int NUM_PER_ROW_RESULT = NUM_ELEMENTS,
class F>
CUDA_FHD void block_copy(iteratorA_t first,
iteratorB_t result,
int tid,
F f) {
detail::helper_t<BLOCK_DIM,
NUM_ELEMENTS,
LD_FIRST,
LD_RESULT,
NUM_PER_ROW_FIRST,
NUM_PER_ROW_RESULT>::block_copy_even(first,
result,
tid,
f);
detail::helper_t<BLOCK_DIM,
NUM_ELEMENTS,
LD_FIRST,
LD_RESULT,
NUM_PER_ROW_FIRST,
NUM_PER_ROW_RESULT>::block_copy_tail(first,
result,
tid,
f);
}
template <int BLOCK_DIM,
int NUM_ELEMENTS,
int LD_FIRST = NUM_ELEMENTS,
int LD_RESULT = NUM_ELEMENTS,
int NUM_PER_ROW_FIRST = NUM_ELEMENTS,
int NUM_PER_ROW_RESULT = NUM_ELEMENTS,
class iteratorA_t,
class iteratorB_t>
CUDA_FHD void block_copy(iteratorA_t first,
iteratorB_t result,
int tid = threadIdx.x) {
auto default_f = [](iteratorA_t first,
iteratorB_t result,
int i_first,
int i_result) {
result[i_result] = first[i_first];
};
block_copy<BLOCK_DIM,
NUM_ELEMENTS,
iteratorA_t,
iteratorB_t,
LD_FIRST,
LD_RESULT,
NUM_PER_ROW_FIRST,
NUM_PER_ROW_RESULT>(first, result, tid, default_f);
}
//! copy data without loops unrolled
template <class iteratorA_t, class iteratorB_t>
CUDA_FHD void block_copy(iteratorA_t first,
int num_elements,
iteratorB_t result,
int group_dim,
int ld_first,
int ld_result,
int num_per_row_first,
int num_per_row_result,
int tid) {
auto f = [](iteratorA_t first,
iteratorB_t result,
int i_first,
int i_result) { result[i_result] = first[i_first]; };
//////////
// HEAD //
//////////
if (group_dim < num_elements) {
for (int i = 0; i < num_elements - group_dim; i += group_dim) {
f(first,
result,
i + ((i + tid) / num_per_row_first) *
(ld_first - num_per_row_first) + tid,
i + ((i + tid) / num_per_row_result) *
(ld_result - num_per_row_result) + tid);
}
}
//////////
// TAIL //
//////////
if (num_elements % group_dim == 0) {
f(first,
result,
(num_elements - group_dim) +
(((num_elements - group_dim) + tid) / num_per_row_first) *
(ld_first - num_per_row_first) + tid,
(num_elements - group_dim) +
(((num_elements - group_dim) + tid) / num_per_row_result) *
(ld_result - num_per_row_result) + tid);
}
else if (tid + (num_elements / group_dim) * group_dim < num_elements) {
const int j = (num_elements / group_dim) * group_dim;
f(first,
result,
j + ((j + tid) / num_per_row_first) * (ld_first - num_per_row_first) + tid,
j + ((j + tid) / num_per_row_result) *
(ld_result - num_per_row_result) + tid);
}
}
} // namespace thrustshift
| {
"alphanum_fraction": 0.5613518332,
"avg_line_length": 32.9948849105,
"ext": "h",
"hexsha": "844663e3f8b7a21b27248c516b7ba6dee4e1ac8c",
"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/copy.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pauleonix/thrustshift",
"max_issues_repo_path": "include/thrustshift/copy.h",
"max_line_length": 98,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pauleonix/thrustshift",
"max_stars_repo_path": "include/thrustshift/copy.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z",
"num_tokens": 3041,
"size": 12901
} |
#include "cones.h"
#ifdef LAPACK_LIB_FOUND
#include <cblas.h>
#include <lapacke.h>
#endif
void projectsdc(double * X, int n, Work * w);
/* in place projection (with branches) */
void projCone(double *x, Cone * k, Work * w, int iter)
{
int i;
int count;
/* project onto positive orthant */
for(i = k->f; i < k->f+k->l; ++i)
{
if(x[i] < 0.0) x[i] = 0.0;
//x[i] = (x[i] < 0.0) ? 0.0 : x[i];
}
count = k->l+k->f;
/* project onto SOC */
for(i = 0; i < k->qsize; ++i)
{
double v1 = x[count];
double s = calcNorm(&(x[count+1]),k->q[i]-1);
double alpha = (s + v1)/2.0;
if(s <= v1) { /* do nothing */ }
else if (s <= - v1) {
memset(&(x[count]), 0, k->q[i]*sizeof(double));
} else {
x[count] = alpha;
scaleArray(&(x[count+1]), alpha/s, k->q[i]-1);
//cblas_dscal(k->q[i]-1, alpha/s, &(x[count+1]),1);
}
count += k->q[i];
}
#ifdef LAPACK_LIB_FOUND
/* project onto PSD cone */
for (i=0; i < k->ssize; ++i){
projectsdc(&(x[count]),k->s[i],w);
count += (k->s[i])*(k->s[i]);
}
#else
if(k->ssize > 0){
coneOS_printf("WARNING: solving SDP, no lapack library specified in makefile!\n");
coneOS_printf("ConeOS will return a wrong answer!\n");
}
#endif
/*
* exponential cone is not self dual, if s \in K
* then y \in K^* and so if K is the primal cone
* here we project onto K^*, via Moreau
*/
scaleArray(&(x[count]), -1, 3*k->ep); // x = -x;
double r,s,t;
int idx;
#pragma omp parallel for private(r,s,t,idx)
for (i=0; i < k->ep; ++i) {
idx = count + 3*i;
r = x[idx];
s = x[idx+1];
t = x[idx+2];
projExpCone(&(x[idx]));
x[idx] -= r;
x[idx+1] -= s;
x[idx+2] -= t;
}
count += 3*k->ep;
// exponential cone:
#pragma omp parallel for
for (i=0; i < k->ed; ++i) {
projExpCone(&(x[count + 3*i]));
}
count += 3*k->ed;
/* project onto OTHER cones */
}
double expNewtonOneD(double rho, double y_hat, double z_hat) {
double t = fmax( -z_hat , 1e-6);
double f, fp;
for (int i=0; i<100; ++i){
f = t * (t + z_hat) / rho / rho - y_hat/rho + log(t/rho) + 1;
fp = (2 * t + z_hat) / rho / rho + 1/t;
t = t - f/fp;
if (t <= -z_hat) {
return 0;
} else if (t <= 0) {
return z_hat;
} else if ( fabs(f) < 1e-9 ) {
break;
}
}
return t + z_hat;
}
void expSolveForXWithRho(double * v, double * x, double rho) {
x[2] = expNewtonOneD(rho, v[1], v[2]);
x[1] = (x[2] - v[2]) * x[2] / rho;
x[0] = v[0] - rho;
}
double expCalcGrad(double * v, double * x, double rho) {
expSolveForXWithRho(v, x, rho);
if (x[1] <= 1e-12) {
return x[0];
} else {
return x[0] + x[1] * log( x[1] / x[2] );
}
}
void expGetRhoUb(double * v, double * x, double * ub, double * lb) {
*lb = 0;
*ub = 0.125;
while(expCalcGrad(v, x, *ub) > 0) {
*lb = *ub;
(*ub) *= 2;
}
}
// project onto the exponential cone, v has dimension *exactly* 3
void projExpCone(double * v) {
double r = v[0], s = v[1], t = v[2];
// v in cl(Kexp)
if( (s*exp(r/s) <= t && s > 0) || (r <= 0 && s == 0 && t >= 0) ) {
return;
}
// -v in Kexp^*
if ( (-r < 0 && r*exp(s/r) <= -exp(1)*t) || (-r == 0 && -s >= 0 && -t >= 0) ) {
memset(v, 0, 3*sizeof(double));
return;
}
// special case with analytical solution
if(r < 0 && s < 0) {
v[1] = 0.0;
v[2] = fmax(v[2],0);
return;
}
double ub, lb, rho, g, x[3];
expGetRhoUb(v, x, &ub, &lb);
for(int i = 0; i < 100; ++i){
rho = (ub + lb)/2;
g = expCalcGrad(v, x, rho);
if (g > 0) {
lb = rho;
} else{
ub = rho;
}
if (ub - lb < 1e-9) {
break;
}
}
v[0] = x[0];
v[1] = x[1];
v[2] = x[2];
}
#ifdef LAPACK_LIB_FOUND
void projectsdc(double *X, int n, Work * w)
{ /* project onto the positive semi-definite cone */
if (n == 1) {
if(X[0] < 0.0) X[0] = 0.0;
return;
}
int i, j, m=0;
double * Xs = w->Xs;
double * Z = w->Z;
double * e = w->e;
memcpy(Xs,X,n*n*sizeof(double));
// Xs = X + X', save div by 2 for eigen-recomp
for (i = 0; i < n; ++i){
cblas_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1);
//b_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1);
}
double EIG_TOL = 1e-8;
double vupper = calcNorm(Xs,n*n);
LAPACKE_dsyevr( LAPACK_COL_MAJOR, 'V', 'V', 'U', n, Xs, n, 0.0, vupper, -1, -1, EIG_TOL, &m, e, Z, n , NULL);
//printf("m is %i, n is %i\n", m ,n);
//printf("vupper is %f, max eig is %f\n",vupper, e[m>0 ? m-1:0]/2);
memset(X, 0, n*n*sizeof(double));
for (i = 0; i < m; ++i) {
cblas_dsyr(CblasColMajor, CblasLower, n, e[i]/2, &(Z[i*n]), 1, X, n);
//b_dsyr('L', n, -e[i]/2, &(Z[i*n]), 1, Xs, n);
}
// fill in upper half
for (i = 0; i < n; ++i){
for (j = i+1; j < n; ++j){
X[i + j*n] = X[j + i*n];
}
}
}
#endif
| {
"alphanum_fraction": 0.4504780115,
"avg_line_length": 25.1442307692,
"ext": "c",
"hexsha": "8e8e6015542f63aed6bd3d53c0f3ed36edec3374",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-12-20T19:38:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-26T23:10:34.000Z",
"max_forks_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "cvxgrp/coneos",
"max_forks_repo_path": "coneOSsparse/cones.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "cvxgrp/coneos",
"max_issues_repo_path": "coneOSsparse/cones.c",
"max_line_length": 111,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "cvxgrp/coneos",
"max_stars_repo_path": "coneOSsparse/cones.c",
"max_stars_repo_stars_event_max_datetime": "2015-08-29T07:42:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-08-29T07:42:29.000Z",
"num_tokens": 1975,
"size": 5230
} |
/* siman/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi
*
* 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 <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_siman.h>
#include <gsl/gsl_ieee_utils.h>
#include <stdio.h>
/* set up parameters for this simulated annealing run */
#define N_TRIES 200 /* how many points do we try before stepping */
#define ITERS_FIXED_T 1000 /* how many iterations for each T? */
#define STEP_SIZE 1.0 /* max step size in random walk */
#define K 1.0 /* Boltzmann constant */
#define T_INITIAL 0.008 /* initial temperature */
#define MU_T 1.003 /* damping factor for temperature */
#define T_MIN 2.0e-6
gsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE,
K, T_INITIAL, MU_T, T_MIN};
inline double square (double x) ;
inline double square (double x) { return x * x ; }
double test_E_1D(Element x);
void test_step_1D(const gsl_rng * r, Element *x_p, gsl_siman_params_t p);
void print_pos_1D(Element x);
double distance_1D(Element x, Element y);
double test_E_1D(Element x)
{
double val = x.D1;
double u = val - 1 ;
return exp(-u * u)*sin(8*val);
/* return sin(sin(val*val) - cos(val)) + cos(sin(val) + sin(val)*sin(val));*/
/* return 1.0/(square(x-1.0) + 1.0)*sin(8.0*x); */
/* return 1.0/(square(x-1.0) + 1.0)*sin(8.0*x) + x*x/100.0; */
}
/* takes a step for the test function; max distance: step_size.
* the new point is put in x_p and returned.
*/
void test_step_1D(const gsl_rng * r, Element *x_p, gsl_siman_params_t p)
{
double old_x = x_p->D1;
double new_x;
new_x = gsl_rng_uniform(r);
new_x = new_x*2*p.step_size;
new_x = new_x - p.step_size + old_x;
x_p->D1 = new_x;
}
/* simple routine to print out a position value */
void print_pos_1D(Element x)
{
printf("%12g", x.D1);
}
void debug_pos_1D(void * x)
{
printf("%12g", ((Element *)x)->D1);
}
/* a metric for the 2D space */
double distance_1D(Element x, Element y)
{
return fabs(y.D1 - x.D1);
}
double test_E_2D(Element x);
void test_step_2D(const gsl_rng * r, Element *x_p, gsl_siman_params_t p);
void print_pos_2D(Element x);
double distance_2D(Element x, Element y);
/* a 2-D function to be minimized */
double test_E_2D(Element x)
{
double old_x = x.D2[0], old_y = x.D2[1];
double u = old_x-1 ;
double v = old_y - 0.8 ;
return exp(-u * u - v * v)*sin(8*old_x + 8 * old_y);
}
/* takes a step for the test function; max distance: step_size. the
new point is put in x_p and returned. */
void test_step_2D(const gsl_rng * r, Element *x_p, gsl_siman_params_t p)
{
double old_x = x_p->D2[0], old_y = x_p->D2[1], new_x, new_y;
new_x = gsl_rng_uniform(r);
new_x = new_x*2*p.step_size;
new_x = new_x - p.step_size + old_x;
new_y = gsl_rng_uniform(r);
new_y = new_y*2*p.step_size;
new_y = new_y - p.step_size + old_y;
x_p->D2[0] = new_x;
x_p->D2[1] = new_y;
}
/* simple routine to print out a position value */
void print_pos_2D(Element x)
{
printf("%g::%g", x.D2[0], x.D2[1]);
}
/* a metric for the 2D space */
double distance_2D(Element x, Element y)
{
double u = y.D2[0]-x.D2[0] ;
double v = y.D2[1]-x.D2[1] ;
return sqrt(u*u + v*v);
}
/**********************************************/
/************ 3-dimensional search ************/
/**********************************************/
double test_E_3D(Element x);
void test_step_3D(const gsl_rng * r, Element *x_p, gsl_siman_params_t p);
void print_pos_3D(Element x);
double distance_3D(Element x, Element y);
/* a 3-D function to be minimized */
double test_E_3D(Element x)
{
return exp(-square(x.D3[0]-1) - square(x.D3[1] - 0.8)
- square(x.D3[2] - 0.8)) * sin(8*x.D3[0] + 8*x.D3[1] + 8*x.D3[2])
+ (square(x.D3[0]) + square(x.D3[1]) + square(x.D3[2]))/10000.0;
}
/* takes a step for the test function; max distance: step_size.
* the new point is put in x_p and returned.
*/
void test_step_3D(const gsl_rng * r, Element *x_p, gsl_siman_params_t p)
{
double old_x = x_p->D3[0], old_y = x_p->D3[1], old_z = x_p->D3[2];
double new_x, new_y, new_z;
new_x = gsl_rng_uniform(r);
new_x = new_x*2*p.step_size;
new_x = new_x - p.step_size + old_x;
new_y = gsl_rng_uniform(r);
new_y = new_y*2*p.step_size;
new_y = new_y - p.step_size + old_y;
new_z = gsl_rng_uniform(r);
new_z = new_z*2*p.step_size;
new_z = new_z - p.step_size + old_z;
x_p->D3[0] = new_x;
x_p->D3[1] = new_y;
x_p->D3[2] = new_z;
}
/* simple routine to print out a position value */
void print_pos_3D(Element x)
{
printf("%g::%g::%g", x.D3[0], x.D3[1], x.D3[2]);
}
/* a metric for the 2D space */
double distance_3D(Element x, Element y)
{
return sqrt(square(y.D3[0]-x.D3[0]) + square(y.D3[1]-x.D3[1])
+ square(y.D3[2]-x.D3[2]));
}
double E1(void *xp);
double M1(void *xp, void *yp);
void S1(const gsl_rng * r, void *xp, double step_size);
void P1(void *xp);
/* now some functions to test in one dimension */
double E1(void *xp)
{
double x = * ((double *) xp);
/* return exp(-square(x-1))*sin(8*x); */
return exp(-square(x-1))*sin(8*x) - exp(-square(x-1000))*0.89;
}
double M1(void *xp, void *yp)
{
double x = *((double *) xp);
double y = *((double *) yp);
return fabs(x - y);
}
void S1(const gsl_rng * r, void *xp, double step_size)
{
double old_x = *((double *) xp);
double new_x;
new_x = gsl_rng_uniform(r)*2*step_size - step_size + old_x;
/* new_x = new_x*2*step_size; */
/* new_x = new_x - step_size + old_x; */
/* printf("test step from old_x = %g to new_x = %g\n", old_x, new_x); */
memcpy(xp, &new_x, sizeof(new_x));
}
void P1(void *xp)
{
printf(" %12g ", *((double *) xp));
}
int main(void)
{
double x_min = 1.36312999455315182 ;
double x ;
gsl_rng * r = gsl_rng_alloc (gsl_rng_env_setup()) ;
gsl_ieee_env_setup ();
/* The function tested here has multiple mimima.
The global minimum is at x = 1.36312999, (f = -0.87287)
There is a local minimum at x = 0.60146196, (f = -0.84893) */
gsl_ieee_env_setup ();
x = -10.0 ;
gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
sizeof(double), params);
gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=-10") ;
x = +10.0 ;
gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
sizeof(double), params);
gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=10") ;
/* Start at the false minimum */
x = +0.6 ;
gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
sizeof(double), params);
gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.6") ;
x = +0.5 ;
gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
sizeof(double), params);
gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.5") ;
x = +0.4 ;
gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
sizeof(double), params);
gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.4") ;
exit (gsl_test_summary ());
#ifdef JUNK
x0.D1 = 12.0;
printf("#one dimensional problem, x0 = %f\n", x0.D1);
gsl_siman_Usolve(r, &x0, test_E_1D, test_step_1D, distance_1D,
print_pos_1D, params);
x0.D2[0] = 12.0;
x0.D2[1] = 5.5;
printf("#two dimensional problem, (x0,y0) = (%f,%f)\n",
x0.D2[0], x0.D2[1]);
gsl_siman_Usolve(r, &x0, test_E_2D, test_step_2D, distance_2D,
print_pos_2D, params);
x0.D3[0] = 12.2;
x0.D3[1] = 5.5;
x0.D3[2] = -15.5;
printf("#three dimensional problem, (x0,y0,z0) = (%f,%f,%f)\n",
x0.D3[0], x0.D3[1], x0.D3[2]);
gsl_siman_Usolve(r, &x0, test_E_3D, test_step_3D, distance_3D,
print_pos_3D, params);
x0.D2[0] = 12.2;
x0.D2[1] = 5.5;
gsl_siman_solve(r, &x0, test_E_2D, test_step_2D, distance_2D, print_pos_2D, params);
x0.D3[0] = 12.2;
x0.D3[1] = 5.5;
x0.D3[2] = -15.5;
gsl_siman_solve(r, &x0, test_E_3D, test_step_3D, distance_3D, print_pos_3D, params);
return 0;
#endif
}
| {
"alphanum_fraction": 0.6331367788,
"avg_line_length": 27.1128526646,
"ext": "c",
"hexsha": "cd6d69efc24aa0ae67fb003eb655946f728c9bd2",
"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/siman/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/siman/test.c",
"max_line_length": 86,
"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/siman/test.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 3107,
"size": 8649
} |
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef UTILS_H_
#define UTILS_H_
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_randist.h>
#include <vector>
using namespace std;
namespace hlda {
// This class provides functionality for summing values,
// for reading data from files and also provides
// an interface to gsl specific methods.
// This class is not thread-safe (see private static gsl_rng* RANDNUMGEN).
class Utils {
public:
// Sum up the values in a vector.
static double Sum(const vector<double>& v);
// An approximation of the logarithm of a sum.
// Given log(a) denoted with log_a and log(b) denoted with log_b
// it approximates log(a + b) as:
// if log_a < log_b then log(a + b) = log_b + log(1 + exp(log_a - log_b))
// otherwise log(a + b) = log_a + log(1 + exp(log_b - log_a)).
static double LogSum(double log_a, double log_b);
// Sample log probabilities.
// The log_pr vector keeps for each level
// the current log probability of the word + the current
// log probability of the level in the tree.
// These values are used to sample the new level.
// The vector should contain at least one element.
static int SampleFromLogPr(const vector<double>& log_pr);
// Shuffle the values in a gsl_permutation.
static void Shuffle(gsl_permutation* permutation, int size);
// Initialize the random number generator.
// rng_seed is the random number generator seed.
static void InitRandomNumberGen(long rng_seed);
// Return a gsl Gaussian random variate with mean and stdev as parameters
static double RandGauss(double mean, double stdev);
// Return a random number using the gsl random number generator.
static double RandNo();
private:
static gsl_rng* RANDNUMGEN;
};
} // namespace hlda
#endif // UTILS_H_
| {
"alphanum_fraction": 0.7290870488,
"avg_line_length": 32.7083333333,
"ext": "h",
"hexsha": "b33370cb8e65de5231e13bdb299ec8b153d9fd0a",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2020-02-28T17:32:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-24T03:30:32.000Z",
"max_forks_repo_head_hexsha": "6aea5bb42f8c1777434303411d3fd4a422caf050",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "samuel2015/hlda-cpp",
"max_forks_repo_path": "src/utils.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "6aea5bb42f8c1777434303411d3fd4a422caf050",
"max_issues_repo_issues_event_max_datetime": "2016-04-11T13:03:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-02-08T18:29:51.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "samuel2015/hlda-cpp",
"max_issues_repo_path": "src/utils.h",
"max_line_length": 75,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "6aea5bb42f8c1777434303411d3fd4a422caf050",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "samuel2015/hlda-cpp",
"max_stars_repo_path": "src/utils.h",
"max_stars_repo_stars_event_max_datetime": "2019-03-11T06:25:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-28T09:55:53.000Z",
"num_tokens": 563,
"size": 2355
} |
/**
* @file constants.h
* @brief Public header file defining constants
*/
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <petsc.h>
#define epsilon 1E-8 /**< epsilon value for finite differences */
#define MAXLINE 1000 /**< Max. number of characters in a line */
#define ISOLATED_BUS 4 /**< Isolated bus */
#define REF_BUS 3 /**< Reference bus (swing bus) */
#define PV_BUS 2 /**< PV (voltage-controlled) bus */
#define PQ_BUS 1 /**< PQ bus */
#define NGEN_AT_BUS_MAX 15 /**< Maximum number of generators allowed at a bus */
#define NLOAD_AT_BUS_MAX 10 /**< Maximum number of loads allowed at a bus */
#define NPHASE 1 /**< Per-phase analysis */
#endif
| {
"alphanum_fraction": 0.6984848485,
"avg_line_length": 31.4285714286,
"ext": "h",
"hexsha": "3a91e67b703e6ba3780dff218cf329e827d99eb3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-09-11T00:24:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-11T00:24:08.000Z",
"max_forks_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pflow-team/PFLOW",
"max_forks_repo_path": "include/constants.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95",
"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": "pflow-team/PFLOW",
"max_issues_repo_path": "include/constants.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "85b21a84514f438b6b956f024e4b753c0f3ccc95",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pflow-team/PFLOW",
"max_stars_repo_path": "include/constants.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 158,
"size": 660
} |
#ifndef OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
#define OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
#include <cstdint>
#include <unordered_map>
#include <gsl/gsl>
#include "openmc/cell.h"
#include "openmc/tallies/filter.h"
#include "openmc/vector.h"
namespace openmc {
//==============================================================================
//! Specifies cell instances that tally events reside in.
//==============================================================================
class CellInstanceFilter : public Filter {
public:
//----------------------------------------------------------------------------
// Constructors, destructors
CellInstanceFilter() = default;
CellInstanceFilter(gsl::span<CellInstance> instances);
~CellInstanceFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override { return "cellinstance"; }
void from_xml(pugi::xml_node node) override;
void get_all_bins(const Particle& p, TallyEstimator estimator,
FilterMatch& match) const override;
void to_statepoint(hid_t filter_group) const override;
std::string text_label(int bin) const override;
//----------------------------------------------------------------------------
// Accessors
const vector<CellInstance>& cell_instances() const { return cell_instances_; }
const std::unordered_set<int32_t>& cells() const { return cells_; }
void set_cell_instances(gsl::span<CellInstance> instances);
private:
//----------------------------------------------------------------------------
// Data members
//! The indices of the cells binned by this filter.
vector<CellInstance> cell_instances_;
//! The set of cells used in this filter
std::unordered_set<int32_t> cells_;
//! A map from cell/instance indices to filter bin indices.
std::unordered_map<CellInstance, gsl::index, CellInstanceHash> map_;
//! Indicates if filter uses only material-filled cells
bool material_cells_only_;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
| {
"alphanum_fraction": 0.5809069212,
"avg_line_length": 29.5070422535,
"ext": "h",
"hexsha": "d74850df757f86b713592394121a7772615d5e7b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "huak95/openmc",
"max_forks_repo_path": "include/openmc/tallies/filter_cell_instance.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "huak95/openmc",
"max_issues_repo_path": "include/openmc/tallies/filter_cell_instance.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2efe223404680099f9a77214e743ab78e37cd08c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stu314159/openmc",
"max_stars_repo_path": "include/openmc/tallies/filter_cell_instance.h",
"max_stars_repo_stars_event_max_datetime": "2021-10-09T17:55:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-09T17:55:14.000Z",
"num_tokens": 399,
"size": 2095
} |
#include <stdio.h>
#include <math.h>
#include <gbpLib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_min.h>
#include <gbpInterpolate.h>
double interpolate_maximum_function(double x, void *params);
double interpolate_maximum_function(double x, void *params) {
return (-interpolate((interp_info *)params, x));
}
void interpolate_maximum(interp_info *interp,
double x_lo_in,
double x_guess_in,
double x_hi_in,
double threshold,
double * x_maxima,
double * y_maxima) {
double x_lo;
double x_hi;
double x_guess;
double r_val;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer * s;
gsl_function F;
int status;
int iter = 0;
int max_iter;
x_lo = x_lo_in;
x_guess = x_guess_in;
x_hi = x_hi_in;
max_iter = GBP_MAX(100, interp->n);
F.function = interpolate_maximum_function;
F.params = (void *)interp;
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &F, x_guess, x_lo, x_hi);
do {
iter++;
status = gsl_min_fminimizer_iterate(s);
x_lo = gsl_min_fminimizer_x_lower(s);
x_guess = gsl_min_fminimizer_x_minimum(s);
x_hi = gsl_min_fminimizer_x_upper(s);
status = gsl_min_test_interval(x_lo, x_hi, 0., threshold);
} while(status == GSL_CONTINUE && iter < max_iter);
gsl_min_fminimizer_free(s);
(*x_maxima) = x_guess;
(*y_maxima) = interpolate(interp, x_guess);
}
| {
"alphanum_fraction": 0.536809816,
"avg_line_length": 34.9285714286,
"ext": "c",
"hexsha": "497710af990f089d6371f218f6e37365c4701f69",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpMath/gbpInterpolate/interpolate_maximum.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpMath/gbpInterpolate/interpolate_maximum.c",
"max_line_length": 67,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpMath/gbpInterpolate/interpolate_maximum.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": 458,
"size": 1956
} |
#define ORIGIN_DATE "2012.01.05"
#define ORIGIN_VERSION "2.1"
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>
#include <assert.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "common.h"
#include "ivector.h"
#include "species.h"
#include "specieslist.h"
#include "graph.h"
#include "utils.h"
#define MODEL_BDM_NEUTRAL 0
#define MODEL_BDM_SELECTION 1
// Parameters of the simulations.
typedef struct
{
int m; // Type of model.
int communities; // Number of communities.
int j_per_c; // Number of individuals per community.
int k_gen; // Number of generations (in thousands).
int init_species; // Initial number of species.
double mu; // Mutation rate.
double omega; // Weight of the links between communities.
double s; // Selection coefficient.
double r; // Radius (for random geometric graphs).
double w; // Width (for rectangle random geometric graphs).
char *ofilename; // Name of the output files.
char *shape; // Shape of the metacommunity.
}
Params;
// Prototype for the function used by the threads
void *sim(void *parameters);
// The function used to setup the cumulative jagged array from the graph.
double **setup_cumulative_list(const graph *g, double omega);
/////////////////////////////////////////////////////////////
// Main //
/////////////////////////////////////////////////////////////
int main(int argc, const char *argv[])
{
// Set default values;
Params p;
p.m = MODEL_BDM_SELECTION;
p.communities = 10;
p.j_per_c = 10000;
p.init_species = 20;
p.k_gen = 100;
p.mu = 1e-4;
p.omega = 5e-4;
p.s = 0.15;
p.r = 0.25;
p.w = 0.25;
p.ofilename = (char*)malloc(50);
p.shape = (char*)malloc(20);
// Number of simulations;
int n_threads = 1;
// Options;
if (argc > 1 && argv[1][0] == '-' && argv[1][1] == '-')
{
// --help
if (argv[1][2] == 'h')
{
printf("Usage: ./origin [options]\n");
printf("Example: ./origin -x=8 -shape=circle -model=1 -s=0.10\n");
printf("General options:\n");
printf(" --help How you got here...\n");
printf(" --version Display version.\n");
printf(" --ref Display reference.\n");
printf("Simulation parameters:\n");
printf(" -x\n");
printf(" description: Number of simulations to run. Each simulation\n");
printf(" will use a distinct POSIX thread. \n");
printf(" values: Any unsigned integer.\n");
printf(" default: 1\n");
printf(" -model\n");
printf(" description: Set the model used.\n");
printf(" values: 0, 1.\n");
printf(" details: 0 = Neutral BDM speciation.\n");
printf(" 1 = BDM speciation with selection.\n");
printf(" default: 1\n");
printf(" -shape\n");
printf(" description: Set the shape of the metacommunity.\n");
printf(" values: circle, complete, random, rectangle, star.\n");
printf(" default: random\n");
printf(" -r\n");
printf(" description: Threshold radius for random geometric\n");
printf(" graphs.\n");
printf(" values: Any double greater than 0.\n");
printf(" default: 0.25\n");
printf(" -w\n");
printf(" description: The width of a rectangle random geometric\n");
printf(" graph.\n");
printf(" values: 0 < w < 1\n");
printf(" default: 0.25\n");
printf(" -g\n");
printf(" description: Number of generations in thousands.\n");
printf(" values: Any positive integer.\n");
printf(" default: 100 (i.e.: 100 000 generations)\n");
printf(" -c\n");
printf(" description: Number of local communities.\n");
printf(" values: Any integer greater than 0.\n");
printf(" default: 10\n");
printf(" -jpc\n");
printf(" description: Number of individuals per communities.\n");
printf(" values: Any integer greater than 0.\n");
printf(" default: 10000\n");
printf(" -sp\n");
printf(" description: Initial number of species. Must be a factor\n");
printf(" of the number of individuals/community.\n");
printf(" values: Any positive integer greater than 0.\n");
printf(" default: 20\n");
printf(" -s\n");
printf(" description: Set the selection coefficient (model 1 only).\n");
printf(" values: Any double in the (-1.0, 1.0) interval.\n");
printf(" default: 0.15\n");
printf(" -mu\n");
printf(" description: Set the mutation rate.\n");
printf(" values: Any positive double.\n");
printf(" default: 1e-4\n");
printf(" -omega\n");
printf(" description: The weight of the proper edges.\n");
printf(" values: Any nonnegative double.\n");
printf(" default: 5e-4\n");
printf(" -o\n");
printf(" description: Name of the output files.\n");
printf(" values: Any string.\n");
return EXIT_SUCCESS;
}
else if (argv[1][2] == 'v') // --version
{
printf("origin v.%s (%s)\n", ORIGIN_VERSION, ORIGIN_DATE);
printf("Copyright (c) 2010-2011 Philippe Desjardins-Proulx <philippe.d.proulx@gmail.com>\n");
printf("GPLv2 license (see LICENSE)\n");
return EXIT_SUCCESS;
}
else if (argv[1][2] == 'r') // --ref
{
printf("P. Desjardins-Proul and D. Gravel. How likely is speciation in\n neutral ecology? The American Naturalist 179(1).\n");
return EXIT_SUCCESS;
}
} // end '--' options
// Read options
read_opt_i("g", argv, argc, &p.k_gen);
read_opt_i("jpc", argv, argc, &p.j_per_c);
read_opt_i("model", argv, argc, &p.m);
read_opt_i("c", argv, argc, &p.communities);
read_opt_i("sp", argv, argc, &p.init_species);
read_opt_i("x", argv, argc, &n_threads);
read_opt_d("mu", argv, argc, &p.mu);
read_opt_d("omega", argv, argc, &p.omega);
read_opt_d("r", argv, argc, &p.r);
read_opt_d("w", argv, argc, &p.w);
read_opt_d("s", argv, argc, &p.s);
if (read_opt_s("o", argv, argc, p.ofilename) == false)
{
sprintf(p.ofilename, "");
}
if (read_opt_s("shape", argv, argc, p.shape) == false)
{
sprintf(p.shape, "random");
}
printf("<?xml version=\"1.0\"?>\n");
printf("<origin_ssne>\n");
printf(" <model>");
if (p.m == MODEL_BDM_NEUTRAL)
{
printf("Neutral BDM speciation</model>\n");
}
else if (p.m == MODEL_BDM_SELECTION)
{
printf("BDM speciation with selection</model>\n");
}
printf(" <n>%d</n>\n", n_threads);
printf(" <shape_metacom>%s</shape_metacom>\n", p.shape);
printf(" <metacom_size>%d</metacom_size>\n", p.j_per_c * p.communities);
printf(" <k_gen>%d</k_gen>\n", p.k_gen);
printf(" <num_comm>%d</num_comm>\n", p.communities);
printf(" <individuals_per_comm>%d</individuals_per_comm>\n", p.j_per_c);
printf(" <initial_num_species>%d</initial_num_species>\n", p.init_species);
printf(" <mutation_rate>%.2e</mutation_rate>\n", p.mu);
printf(" <omega>%.2e</omega>\n", p.omega);
if (p.m == MODEL_BDM_SELECTION)
{
printf(" <selection>%.2e</selection>\n", p.s);
}
if (p.shape[0] == 'r')
{
printf(" <radius>%.4f</radius>\n", p.r);
}
if (p.shape[0] == 'r' && p.shape[1] == 'e')
{
printf(" <width>%.4f</width>\n", p.w);
}
printf(" <filename>%s</filename>\n", p.ofilename);
// The threads:
pthread_t threads[n_threads];
const time_t start = time(NULL);
// Create the threads:
for (int i = 0; i < n_threads; ++i)
{
pthread_create(&threads[i], NULL, sim, (void*)&p);
}
// Wait for the threads to end:
for (int i = 0; i < n_threads; ++i)
{
pthread_join(threads[i], NULL);
}
const time_t end_t = time(NULL);
printf(" <seconds>%lu</seconds>\n", (unsigned long)(end_t - start));
printf(" <time>%s</time>\n", sec_to_string(end_t - start));
printf("</origin_ssne>\n");
return EXIT_SUCCESS; // yeppie !
}
///////////////////////////////////////////
// The simulation //
///////////////////////////////////////////
void *sim(void *parameters)
{
const Params P = *((Params*)parameters);
char *shape = P.shape;
const int k_gen = P.k_gen;
const int communities = P.communities;
const int j_per_c = P.j_per_c;
const int init_species = P.init_species;
const int init_pop_size = j_per_c / init_species;
const double omega = P.omega;
const double mu = P.mu;
const double s = P.s;
const double radius = P.r;
const double width = P.w;
// GSL's Taus generator:
gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus2);
// Initialize the GSL generator with /dev/urandom:
const unsigned int seed = devurandom_get_uint();
gsl_rng_set(rng, seed); // Seed with time
printf(" <seed>%u</seed>\n", seed);
// Used to name the output file:
char *buffer = (char*)malloc(100);
// Nme of the file:
sprintf(buffer, "%s%u.xml", P.ofilename, seed);
// Open the output file:
FILE *restrict out = fopen(buffer, "w");
// Store the total num. of species/1000 generations:
int *restrict total_species = (int*)malloc(k_gen * sizeof(int));
// Number of speciation events/1000 generations:
int *restrict speciation_events = (int*)malloc(k_gen * sizeof(int));
// Number of extinctions/1000 generations:
int *restrict extinction_events = (int*)malloc(k_gen * sizeof(int));
// Number of speciation events/vertex:
int *restrict speciation_per_c = (int*)malloc(communities * sizeof(int));
// Number of local extinction events/vertex:
int *restrict extinction_per_c = (int*)malloc(communities * sizeof(int));
// Store the lifespan of the extinct species:
ivector lifespan;
ivector_init0(&lifespan);
// Store the population size at speciation event:
ivector pop_size;
ivector_init0(&pop_size);
// (x, y) coordinates for the spatial graph:
double *restrict x = (double*)malloc(communities * sizeof(double));
double *restrict y = (double*)malloc(communities * sizeof(double));
for (int i = 0; i < communities; ++i)
{
speciation_per_c[i] = 0;
extinction_per_c[i] = 0;
}
// Initialize an empty list of species:
species_list *restrict list = species_list_init();
// Initialize the metacommunity and fill them with the initial species evenly:
for (int i = 0; i < init_species; ++i)
{
// Intialize the species and add it to the list:
species_list_add(list, species_init(communities, 0, 3));
}
// To iterate the list;
slnode *it = list->head;
// Fill the communities:
while (it != NULL)
{
for (int i = 0; i < communities; ++i)
{
it->sp->n[i] = init_pop_size;
it->sp->genotypes[0][i] = init_pop_size;
}
it = it->next;
}
// To iterate the list;
const int remainder = j_per_c - (init_species * init_pop_size);
for (int i = 0; i < communities; ++i)
{
it = list->head;
for (int j = 0; j < remainder; ++j, it = it->next)
{
++(it->sp->n[i]);
++(it->sp->genotypes[0][i]);
}
}
// Test (will be removed for v2.0):
int sum = 0;
it = list->head;
while (it != NULL)
{
sum += species_total(it->sp);
it = it->next;
}
assert(sum == j_per_c * communities);
// Create the metacommunity;
graph g;
switch(shape[0])
{
case 's':
shape = "star";
graph_get_star(&g, communities);
break;
case 'c':
if (shape[1] == 'o')
{
shape = "complete";
graph_get_complete(&g, communities);
break;
}
else
{
shape = "circle";
graph_get_circle(&g, communities);
break;
}
case 'r':
if (shape[1] == 'e')
{
shape = "rectangle";
graph_get_rec_crgg(&g, communities, width, radius, x, y, rng);
break;
}
else
{
shape = "random";
graph_get_crgg(&g, communities, radius, x, y, rng);
break;
}
default:
shape = "random";
graph_get_crgg(&g, communities, radius, x, y, rng);
}
// Setup the cumulative jagged array for migration:
double **cumul = setup_cumulative_list(&g, omega);
fprintf(out, "<?xml version=\"1.0\"?>\n");
fprintf(out, "<simulation>\n");
fprintf(out, " <model>");
if (P.m == MODEL_BDM_NEUTRAL)
{
fprintf(out, "Neutral BDM speciation</model>\n");
}
else if (P.m == MODEL_BDM_SELECTION)
{
fprintf(out, "BDM speciation with selection</model>\n");
}
fprintf(out, " <seed>%u</seed>\n", seed);
fprintf(out, " <shape_metacom>%s</shape_metacom>\n", shape);
fprintf(out, " <metacom_size>%d</metacom_size>\n", j_per_c * communities);
fprintf(out, " <k_gen>%d</k_gen>\n", k_gen);
fprintf(out, " <num_comm>%d</num_comm>\n", communities);
fprintf(out, " <individuals_per_comm>%d</individuals_per_comm>\n", j_per_c);
fprintf(out, " <initial_num_species>%d</initial_num_species>\n", init_species);
fprintf(out, " <mutation_rate>%.2e</mutation_rate>\n", mu);
fprintf(out, " <omega>%.2e</omega>\n", omega);
if (P.m == MODEL_BDM_SELECTION)
{
fprintf(out, " <selection>%.2e</selection>\n", s);
}
if (shape[0] == 'r')
{
fprintf(out, " <radius>%.4f</radius>\n", radius);
}
if (shape[0] == 'r' && shape[1] == 'e')
{
fprintf(out, " <width>%.4f</width>\n", width);
}
// To select the species and genotypes to pick and replace:
slnode *s0 = list->head; // species0
slnode *s1 = list->head; // species1
int g0 = 0;
int g1 = 0;
int v1 = 0; // Vertex of the individual 1
/////////////////////////////////////////////
// Groups of 1 000 generations //
/////////////////////////////////////////////
for (int k = 0; k < k_gen; ++k)
{
extinction_events[k] = 0;
speciation_events[k] = 0;
/////////////////////////////////////////////
// 1 000 generations //
/////////////////////////////////////////////
for (int gen = 0; gen < 1000; ++gen)
{
const int current_date = (k * 1000) + gen;
/////////////////////////////////////////////
// A single generation //
/////////////////////////////////////////////
for (int t = 0; t < j_per_c; ++t)
{
/////////////////////////////////////////////
// A single time step (for each community) //
/////////////////////////////////////////////
for (int c = 0; c < communities; ++c)
{
// Select the species and genotype of the individual to be replaced
int position = (int)(gsl_rng_uniform(rng) * j_per_c);
s0 = list->head;
int index = s0->sp->n[c];
while (index <= position)
{
s0 = s0->next;
index += s0->sp->n[c];
}
position = (int)(gsl_rng_uniform(rng) * s0->sp->n[c]);
if (position < s0->sp->genotypes[0][c])
{
g0 = 0;
}
else if (position < (s0->sp->genotypes[0][c] + s0->sp->genotypes[1][c]))
{
g0 = 1;
}
else
{
g0 = 2;
}
// Choose the vertex for the individual
const double r_v1 = gsl_rng_uniform(rng);
v1 = 0;
while (r_v1 > cumul[c][v1])
{
++v1;
}
v1 = g.adj_list[c][v1];
// species of the new individual
position = (int)(gsl_rng_uniform(rng) * j_per_c);
s1 = list->head;
index = s1->sp->n[v1];
while (index <= position)
{
s1 = s1->next;
index += s1->sp->n[v1];
}
if (v1 == c) // local remplacement
{
const double r = gsl_rng_uniform(rng);
const int aa = s1->sp->genotypes[0][v1];
const int Ab = s1->sp->genotypes[1][v1];
const int AB = s1->sp->genotypes[2][v1];
// The total fitness of the population 'W':
const double w = aa + Ab * (1.0 + s) + AB * (1.0 + s) * (1.0 + s);
if (r < aa / w)
{
g1 = gsl_rng_uniform(rng) < mu ? 1 : 0;
}
else
{
if (AB == 0 || r < (aa + Ab * (1.0 + s)) / w)
{
g1 = gsl_rng_uniform(rng) < mu ? 2 : 1;
}
else
{
g1 = 2;
}
}
}
else
{ // Migration event
g1 = 0;
}
// Apply the changes
s0->sp->n[c]--;
s0->sp->genotypes[g0][c]--;
s1->sp->n[c]++;
s1->sp->genotypes[g1][c]++;
////////////////////////////////////////////
// Check for local extinction //
////////////////////////////////////////////
if (s0->sp->n[c] == 0)
{
extinction_per_c[c]++;
}
////////////////////////////////////////////
// Check for speciation //
////////////////////////////////////////////
else if (s0->sp->genotypes[2][c] > 0 && s0->sp->genotypes[0][c] == 0 && s0->sp->genotypes[1][c] == 0)
{
species_list_add(list, species_init(communities, current_date, 3)); // Add the new species
const int pop = s0->sp->n[c];
list->tail->sp->n[c] = pop;
list->tail->sp->genotypes[0][c] = pop;
s0->sp->n[c] = 0;
s0->sp->genotypes[2][c] = 0;
// To keep info on patterns of speciation...
ivector_add(&pop_size, pop);
++speciation_events[k];
++speciation_per_c[c];
}
} // End 'c'
} // End 't'
// Remove extinct species from the list and store the number of extinctions.
extinction_events[k] += species_list_rmv_extinct2(list, &lifespan, current_date);
} // End 'g'
total_species[k] = list->size;
} // End 'k'
//////////////////////////////////////////////////
// PRINT THE FINAL RESULTS //
//////////////////////////////////////////////////
fprintf(out, " <global>\n");
fprintf(out, " <proper_edges>%d</proper_edges>\n", graph_edges(&g));
fprintf(out, " <links_per_c>%.4f</links_per_c>\n", (double)graph_edges(&g) / communities);
fprintf(out, " <avr_lifespan>%.4f</avr_lifespan>\n", imean(lifespan.array, lifespan.size));
fprintf(out, " <median_lifespan>%.4f</median_lifespan>\n", imedian(lifespan.array, lifespan.size));
fprintf(out, " <avr_pop_size_speciation>%.4f</avr_pop_size_speciation>\n", imean(pop_size.array, pop_size.size));
fprintf(out, " <median_pop_size_speciation>%.4f</median_pop_size_speciation>\n", imedian(pop_size.array, pop_size.size));
fprintf(out, " <speciation_per_k_gen>");
int i = 0;
for (; i < k_gen - 1; ++i)
{
fprintf(out, "%d ", speciation_events[i]);
}
fprintf(out, "%d</speciation_per_k_gen>\n", speciation_events[i]);
fprintf(out, " <extinctions_per_k_gen>");
for (i = 0; i < k_gen - 1; ++i)
{
fprintf(out, "%d ", extinction_events[i]);
}
fprintf(out, "%d</extinctions_per_k_gen>\n", extinction_events[i]);
fprintf(out, " <extant_species_per_k_gen>");
for (i = 0; i < k_gen - 1; ++i)
{
fprintf(out, "%d ", total_species[i]);
}
fprintf(out, "%d</extant_species_per_k_gen>\n", total_species[i]);
// Print global distribution
fprintf(out, " <species_distribution>");
ivector species_distribution;
ivector_init1(&species_distribution, 128);
it = list->head;
while (it != NULL)
{
ivector_add(&species_distribution, species_total(it->sp));
it = it->next;
}
ivector_sort_asc(&species_distribution);
ivector_print(&species_distribution, out);
fprintf(out, "</species_distribution>\n");
double *octaves;
int oct_num = biodiversity_octaves(species_distribution.array, species_distribution.size, &octaves);
fprintf(out, " <octaves>");
for (i = 0; i < oct_num; ++i)
{
fprintf(out, "%.2f ", octaves[i]);
}
fprintf(out, "%.2f</octaves>\n", octaves[i]);
fprintf(out, " </global>\n");
// Print info on all vertices
double *restrict ric_per_c = (double*)malloc(communities * sizeof(double));
for (int c = 0; c < communities; ++c)
{
fprintf(out, " <vertex>\n");
fprintf(out, " <id>%d</id>\n", c);
if (shape[0] == 'r')
{
fprintf(out, " <xcoor>%.4f</xcoor>\n", x[c]);
fprintf(out, " <ycoor>%.4f</ycoor>\n", y[c]);
}
fprintf(out, " <degree>%d</degree>\n", g.num_e[c] + 1);
fprintf(out, " <speciation_events>%d</speciation_events>\n", speciation_per_c[c]);
fprintf(out, " <extinction_events>%d</extinction_events>\n", extinction_per_c[c]);
int vertex_richess = 0;
ivector_rmvall(&species_distribution);
it = list->head;
while (it != NULL)
{
ivector_add(&species_distribution, it->sp->n[c]);
it = it->next;
}
// Sort the species distribution and remove the 0s
ivector_sort_asc(&species_distribution);
ivector_trim_small(&species_distribution, 1);
ric_per_c[c] = (double)species_distribution.size;
fprintf(out, " <species_richess>%d</species_richess>\n", species_distribution.size);
fprintf(out, " <species_distribution>");
ivector_print(&species_distribution, out);
fprintf(out, "</species_distribution>\n");
// Print octaves
free(octaves);
oct_num = biodiversity_octaves(species_distribution.array, species_distribution.size, &octaves);
fprintf(out, " <octaves>");
for (i = 0; i < oct_num - 1; ++i)
{
fprintf(out, "%.2f ", octaves[i]);
}
fprintf(out, "%.2f</octaves>\n", octaves[i]);
fprintf(out, " </vertex>\n");
}
fprintf(out, "</simulation>\n");
// GraphML output:
sprintf(buffer, "%s%u.graphml", P.ofilename, seed);
FILE *outgml = fopen(buffer, "w");
graph_graphml(&g, outgml, seed);
// Print to SVG files.
sprintf(buffer, "%s%u.svg", P.ofilename, seed);
FILE *outsvg = fopen(buffer, "w");
graph_svg(&g, x, y, 400.0, 20.0, outsvg);
sprintf(buffer, "%s%u-speciation.svg", P.ofilename, seed);
FILE *outsvgspe = fopen(buffer, "w");
double *spe_per_c = (double*)malloc(communities * sizeof(double));
for (int c = 0; c < communities; ++c)
{
spe_per_c[c] = (double)speciation_per_c[c];
}
scale_0_1(spe_per_c, communities);
graph_svg_abun(&g, x, y, 400.0, 20.0, spe_per_c, 2, outsvgspe);
sprintf(buffer, "%s%u-richness.svg", P.ofilename, seed);
FILE *outsvgric = fopen(buffer, "w");
scale_0_1(ric_per_c, communities);
graph_svg_abun(&g, x, y, 400.0, 20.0, ric_per_c, 1, outsvgric);
//////////////////////////////////////////////////
// EPILOGUE... //
//////////////////////////////////////////////////
// Close files;
fclose(out);
fclose(outgml);
fclose(outsvg);
fclose(outsvgspe);
fclose(outsvgric);
// Free arrays;
free(x);
free(y);
free(ric_per_c);
free(spe_per_c);
free(buffer);
free(total_species);
free(octaves);
free(speciation_per_c);
free(extinction_per_c);
free(speciation_events);
free(extinction_events);
// Free structs;
species_list_free(list);
ivector_free(&species_distribution);
ivector_free(&lifespan);
ivector_free(&pop_size);
graph_free(&g);
gsl_rng_free(rng);
return NULL;
}
double **setup_cumulative_list(const graph *g, double omega)
{
const int num_v = g->num_v;
double **cumul = (double**)malloc(num_v * sizeof(double*));
for (int i = 0; i < num_v; ++i)
{
cumul[i] = (double*)malloc(g->num_e[i] * sizeof(double));
}
for (int i = 0; i < num_v; ++i)
{
for (int j = 0; j < g->num_e[i]; ++j)
{
cumul[i][j] = g->w_list[i][j];
}
}
for (int i = 0; i < num_v; ++i)
{
for (int j = 0; j < g->num_e[i]; ++j)
{
if (i != g->adj_list[i][j])
{
cumul[i][j] = omega;
}
else
{
cumul[i][j] = 1.0;
}
}
}
for (int i = 0; i < num_v; ++i)
{
double sum = 0.0;
const int num_e = g->num_e[i];
for (int j = 0; j < num_e; ++j)
{
sum += cumul[i][j];
}
for (int j = 0; j < num_e; ++j)
{
cumul[i][j] /= sum;
}
}
for (int i = 0; i < num_v; ++i)
{
const int num_e = g->num_e[i];
for (int j = 1; j < num_e - 1; ++j)
{
cumul[i][j] += cumul[i][j - 1];
}
cumul[i][num_e - 1] = 1.0;
}
/*
graph_print(g, stdout);
for (int i = 0; i < num_v; ++i)
{
const int num_e = g->num_e[i];
for (int j = 0; j < num_e; ++j)
{
printf("%.4f ", cumul[i][j]);
}
printf("\n");
}
*/
return cumul;
}
| {
"alphanum_fraction": 0.4811286973,
"avg_line_length": 35.9871134021,
"ext": "c",
"hexsha": "a172244958e240675fddc28f1c062fabcf327eec",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "PhDP/Origin",
"max_forks_repo_path": "src/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "PhDP/Origin",
"max_issues_repo_path": "src/main.c",
"max_line_length": 139,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "PhDP/Origin",
"max_stars_repo_path": "src/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7243,
"size": 27926
} |
#ifndef MOVE_H
#define MOVE_H
#include <cmath>
#include "param.h"
#include "mpiutils.h"
#include <gsl/gsl_rng.h>
namespace weakarg
{
extern gsl_rng * rng;
/**
@brief This virtual class represents a move of the MCMC
*/
class Move
{
protected:
std::string name;///<The moves name
std::string description;///<The moves description
Param*param;///<Parameter set on which the move is performed
double alpha;///<Weighting for this move (probability is alpha/sum_i(alpha_i) )
int intDist; //FMA_CHANGES: Number of intermediate distns for AISRJ
int numcalls;///<Number of attempts at the move
int numaccept;///<Number of acceptances of the move
public:
Move(Param*p,double a=1.0);///<Constructor specifying on which Parameter the move is to be performed
virtual Move * clone()=0;
virtual ~Move()=0;
virtual int move()=0;///<Performs the move once
virtual inline int getTopoCounts(){return(-1);};
virtual inline int getTopoAcc(){return(-1);};
virtual inline int move(vector<int> *samplespace){cout<<"Problem in Move!"<<endl;return(move());};///<Performs the move once
inline void setParam(Param * param)
{
this->param=param;
}///<Change the Parameter on which the move is to be performed
inline std::string desc()
{
return description;
}///<Returns a description of the move
inline std::string getName()
{
return name;
}///<Returns a description of the move
inline void setName(std::string newname)
{
name=newname;
}
inline void setAlpha(double a)
{
alpha=a;
}
;///<Sets alpha for the move
inline double getAlpha()
{
return(alpha);
}
inline int getCounts()
{
return(numcalls);
}
inline int getAcc()
{
return(numaccept);
}
;///<Returns alpha for the move
};
} // end namespace weakarg
#endif
| {
"alphanum_fraction": 0.644200627,
"avg_line_length": 26.5833333333,
"ext": "h",
"hexsha": "f7c128d59204c3ad4007d481edc427b0f21c1d6c",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "fmedina7/ClonOr_cpp",
"max_forks_repo_path": "ClonOr_cpp/move.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "fmedina7/ClonOr_cpp",
"max_issues_repo_path": "ClonOr_cpp/move.h",
"max_line_length": 128,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "fmedina7/ClonOr_cpp",
"max_stars_repo_path": "ClonOr_cpp/move.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 478,
"size": 1914
} |
#pragma once
#include <gsl/gsl>
#include <string>
#include <string_view>
#include <memory>
#include "aas/aas_math.h"
namespace aas {
/**
* Animations can either be advanced by time (automatic), distance moved, or object rotation.
*/
enum class SkelAnimDriver : uint8_t {
Time = 0,
Distance,
Rotation
};
struct SkelAnimStream {
uint16_t frames;
int16_t variationId; // This might actually be a uint8_t
float frameRate;
float dps;
// Offset to the start of the key-frame stream in relation to SkaAnimation start
uint32_t dataOffset;
};
struct SkelAnimStreamData;
struct SkelAnimEvent {
int16_t frame;
char type[48];
char action[128];
};
struct SkelAnim {
char name[64];
SkelAnimDriver driveType;
uint8_t loopable;
uint16_t eventCount; // seems to be uint8_t in reality...
uint32_t eventOffset;
uint16_t streamCount;
uint16_t unk;
SkelAnimStream streams[10];
const gsl::span<SkelAnimEvent> GetEventData() const {
if (eventCount == 0) {
return {};
} else {
auto data = (SkelAnimEvent*)(((char*)this) + eventOffset);
return gsl::span(data, eventCount);
}
}
const SkelAnimStreamData* GetStreamKeyframes(int streamIdx = 0) const {
return (SkelAnimStreamData*)(((char*)this) + streams[streamIdx].dataOffset);
}
};
struct SkelBoneState {
DX::XMFLOAT4 scale;
DX::XMFLOAT4 rotation;
DX::XMFLOAT4 translation;
static void Lerp(gsl::span<SkelBoneState> out,
const gsl::span<SkelBoneState> from,
const gsl::span<SkelBoneState> to,
int count,
float fraction);
};
struct SkelBone {
int16_t flags;
int16_t parentId;
char name[40];
int field_2C;
float field_30;
SkelBoneState initialState;
};
class Skeleton {
public:
Skeleton(std::string filename, std::vector<uint8_t> data);
gsl::span<SkelBone> GetBones() const {
return bones_;
}
gsl::span<SkelAnim> GetAnimations() const {
return animations_;
}
/**
* Searches for a bone in this skeleton by name (case-insensitive).
* Returns nullptr if no bone is found.
*/
const SkelBone* FindBoneByName(std::string_view name) const;
/**
* Searches for the index of a bone in this skeleton by name (case-insensitive).
* Returns -1 if no bone is found.
*/
int FindBoneIdxByName(std::string_view name) const;
/**
* Searches for an animation in this skeleton by it's name (case insensitive)
* and returns the index of the animation in the skeleton.
* If no animation is found, returns -1.
*/
int FindAnimIdxByName(std::string_view name) const;
const std::string &GetFilename() const {
return filename_;
}
private:
std::string filename_;
std::vector<uint8_t> data_;
// These are views into the data buffer
gsl::span<SkelBone> bones_;
gsl::span<SkelAnim> animations_;
};
std::unique_ptr<Skeleton> LoadSkeletonFile(std::string_view filename);
}
| {
"alphanum_fraction": 0.6967071057,
"avg_line_length": 21.8560606061,
"ext": "h",
"hexsha": "d6410b750401694cc8a3a3a11a9881013efee2c4",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z",
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/src/aas/aas_skeleton.h",
"max_issues_count": 457,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/src/aas/aas_skeleton.h",
"max_line_length": 94,
"max_stars_count": 69,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/src/aas/aas_skeleton.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z",
"num_tokens": 819,
"size": 2885
} |
/* ============================================================ *
* decomp_eb.h *
* Martin Kilbinger, Liping Fu 2008, 2009 *
* ============================================================ */
#ifndef __DECOMP_EB_H
#define __DECOMP_EB_H
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_combination.h>
#include "maths.h"
#include "io.h"
#include "errorlist.h"
/* Error codes */
#define mr_base -1500
#define mr_range -1 + mr_base
#define mr_poly -2 + mr_base
#define mr_func -3 + mr_base
#define mr_type -4 + mr_base
#define mr_incompatible -5 + mr_base
#define mr_null -6 + mr_base
#define mr_dimension -7 + mr_base
#define mr_file -8 + mr_base
/* Maximum COSEBI mode. The code is accurate up *
* to Nmax_cosebi = 13 */
#define NMAX_COSEBI 20
typedef enum {cheby, cheby2, legen, cosebi} poly_t;
#define spoly_t(i) ( \
i==cheby ? "cheby" : \
i==cheby2 ? "cheby2" : \
i==legen ? "legen" : \
i==cosebi ? "cosebi" : \
"")
#define Npoly_t 4
/*
typedef enum {cosebi} filter_t;
#define sfilter_t(i) ( \
i==cosebu ? "cosebi" : \
"")
#define Nfilter_t 1
*/
typedef enum {comb_none, all_sc} mring_combinef_t;
#define smring_combinef_t(i) ( \
i==comb_none ? "comb_none" : \
i==all_sc ? "all_sc" : \
"")
#define Nmring_combinef_t 2
typedef enum {inner, outer, fromZ} cov_mode_t;
/* === CFHTLS Wide 3rd data release, Fu&Kilbinger (2010) === */
#define N_FK10 6
#define eta_FK10_SN 0.02
#define eta_FK10_FoM_eta10 0.1
#define eta_FK10_FoM_eta50 0.02
double Cheby(double x, int n, error **err);
double Cheby2(double x, int n, error **err);
double Legen(double x, int n);
double C(double x, int n, poly_t poly, error **err);
double Tp(double x, const double *a, int N, poly_t poly, error **err);
double Fn0(double x, int n, poly_t poly, error **err);
void Fnnu(double x, int n, poly_t poly, double Fn[], error **err);
double alpha_explicit(double x, int n, double R, poly_t poly, error **err);
double Tm(double x, const double *a, int N, poly_t poly, double R, error **err);
double RR_data(const double *xip, const double *xim, const double *th, const int Nxi,
double THETA_MIN, double THETA_MAX, const double *a, int N,
poly_t poly, int pm, error **err);
double cov_RR(const double *THETA_MIN, const double *THETA_MAX, const double *a, int N, poly_t poly,
const double *theta, const double *cov_xi, int Ntheta,
cov_mode_t cov_mode, int n, int m, double fac, error **err);
double cov_RR_diag_xi(const double *THETA_MIN, const double *THETA_MAX, const double *a, int N, poly_t poly,
const double *theta, const double *var_xi, int Ntheta, int islog,
error **err);
double chi2_RB_null(const double *RB, const double *covRB, int NRB);
double *read_zeros_norm_cosebi_auto_check(double Psimin, double Psimax, const char *path, error **err);
double *read_zeros_norm_cosebi(const char *rname, double *psimin, double *psimax, error **err);
double Tplog(double x, const double *r, int n, error **err);
double Tplog_c(double z, const double *c, int n, error **err);
double Tmlog(double x, const double *c, int n, error **err);
double an2(int n, const double *c);
double an4(int n, const double *c);
double dnm(int n, const int m, const double *c);
double sum_combinations(int j, int n, const double *r, error **err);
void xipmEB(double theta, double THETA_MIN, double THETA_MAX, const double *c,
const double *E, const double *B, int N, double xi_pm_EB[4], error **err);
#endif
| {
"alphanum_fraction": 0.6573446328,
"avg_line_length": 32.1818181818,
"ext": "h",
"hexsha": "e8bf11de8630470371c59dedeba769aff9f7ecfe",
"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": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "danielgruen/ccv",
"max_forks_repo_path": "src/nicaea_2.5/Cosmo/include/decomp_eb.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"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": "danielgruen/ccv",
"max_issues_repo_path": "src/nicaea_2.5/Cosmo/include/decomp_eb.h",
"max_line_length": 108,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "danielgruen/ccv",
"max_stars_repo_path": "src/nicaea_2.5/Cosmo/include/decomp_eb.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z",
"num_tokens": 1092,
"size": 3540
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;
int i, n = 10;
double mu = 3.0;
/* create a generator chosen by the
environment variable GSL_RNG_TYPE */
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
/* print n random variates chosen from
the poisson distribution with mean
parameter mu */
for (i = 0; i < n; i++)
{
unsigned int k = gsl_ran_poisson (r, mu);
printf (" %u", k);
}
printf ("\n");
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.6,
"avg_line_length": 16.5277777778,
"ext": "c",
"hexsha": "ef69b72f1ad8a86549ef33df84567e83682fdc03",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/randpoisson.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/randpoisson.c",
"max_line_length": 47,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/randpoisson.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": 185,
"size": 595
} |
/* Utility functions for working with GSL data types. */
#include <math.h>
#include <stdio.h>
#include <unistd.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_spmatrix.h>
#include <gsl/gsl_statistics.h>
#include <hdf5.h>
#include <hdf5_hl.h>
#include <osqp/osqp.h>
#include "qdm.h"
gsl_vector *
qdm_vector_seq(double from, double to, double by)
{
size_t size = fabs(to - from) / by;
gsl_vector *s = gsl_vector_alloc(size + 1);
double value = from;
for (size_t i = 0; i < s->size; i++) {
gsl_vector_set(s, i, value);
value += by;
}
return s;
}
void
qdm_vector_set_seq(gsl_vector *v, double from, double to)
{
double by = (to - from) / (double)(v->size - 1);
double value = from;
for (size_t i = 0; i < v->size; i++) {
gsl_vector_set(v, i, value);
value += by;
}
}
size_t
qdm_vector_search(const gsl_vector *v, double needle)
{
double x = 0;
size_t i = v->size - 1;
for (; i > 0; i--) {
x = gsl_vector_get(v, i);
if (needle >= x) {
break;
}
}
return i;
}
void
qdm_vector_csv_fwrite(FILE *f, const gsl_vector *v)
{
for (size_t i = 0; i < v->size; i++) {
fprintf(f, "%.17g", gsl_vector_get(v, i));
if (i < v->size - 1) {
fprintf(f, ",");
}
}
fprintf(f, "\n");
}
void
qdm_matrix_csv_fwrite(FILE *f, const gsl_matrix *m)
{
if (m != NULL) {
for (size_t i = 0; i < m->size1; i++) {
gsl_vector_const_view row = gsl_matrix_const_row(m, i);
qdm_vector_csv_fwrite(f, &row.vector);
}
}
}
/* Compute M^T * M */
int
qdm_matrix_tmm(gsl_matrix *m, gsl_matrix *result)
{
return gsl_blas_dgemm(
CblasTrans , CblasNoTrans , 1.0 ,
m , m ,
0.0 , result
);
}
/* Compute det(M^T * M) */
int
qdm_matrix_det_tmm(gsl_matrix *m, double *det)
{
int status = 0;
gsl_matrix *c = gsl_matrix_alloc(m->size2, m->size2);
gsl_permutation *p = gsl_permutation_alloc(c->size1);
status = gsl_blas_dgemm(
CblasTrans , CblasNoTrans , 1.0 ,
m , m ,
0.0 , c
);
if (status != 0) {
goto cleanup;
}
int signum = 0;
status = gsl_linalg_LU_decomp(c, p, &signum);
if (status != 0) {
goto cleanup;
}
*det = gsl_linalg_LU_det(c, signum);
cleanup:
gsl_permutation_free(p);
gsl_matrix_free(c);
return status;
}
/* Create a sorted copy of the vector v. */
gsl_vector *
qdm_vector_sorted(const gsl_vector *v)
{
gsl_vector *s = gsl_vector_alloc(v->size);
gsl_vector_memcpy(s, v);
gsl_sort_vector(s);
return s;
}
gsl_vector *
qdm_vector_quantile(gsl_vector *data, gsl_vector *probs)
{
gsl_vector *sorted = qdm_vector_sorted(data);
gsl_vector *quantiles = gsl_vector_alloc(probs->size);
for (size_t i = 0; i < probs->size; i++) {
double q = gsl_stats_quantile_from_sorted_data(
sorted->data,
sorted->stride,
sorted->size,
gsl_vector_get(probs, i)
);
gsl_vector_set(quantiles, i, q);
}
free(sorted);
return quantiles;
}
/* Compute the residual sum of squares:
*
* sum((y[i] - f(x[i])) ^ 2)
*/
double
qdm_vector_rss(const gsl_vector *y, const gsl_vector *fx)
{
int status = 0;
double rss = 0.0;
gsl_vector *se = gsl_vector_alloc(y->size);
status = gsl_vector_memcpy(se, y);
if (status != 0) {
goto cleanup;
}
status = gsl_vector_sub(se, fx);
if (status != 0) {
goto cleanup;
}
status = gsl_vector_mul(se, se);
if (status != 0) {
goto cleanup;
}
rss = qdm_vector_sum(se);
cleanup:
gsl_vector_free(se);
return rss;
}
/* Compute the summation of the vector.
*
* This uses the "iterative Kahan-Babuska algorithm" (aka Klein summation) as
* outlined here:
*
* https://en.wikipedia.org/wiki/Kahan_summation_algorithm
*/
double
qdm_vector_sum(gsl_vector *v)
{
double s = 0.0;
double cs = 0.0;
double ccs = 0.0;
for (size_t i = 0; i < v->size; i++) {
double t = s + gsl_vector_get(v, i);
double c;
if (fabs(s) >= fabs(gsl_vector_get(v, i))) {
c = (s - t) + gsl_vector_get(v, i);
} else {
c = (gsl_vector_get(v, i) - t) + s;
}
s = t;
t = cs + c;
double cc;
if (fabs(cs) >= fabs(c)) {
cc = (cs - t) + c;
} else {
cc = (c - t) + cs;
}
cs = t;
ccs = ccs + cc;
}
return s + cs + ccs;
}
/* Return the first index with a value greater than the value. */
size_t
qdm_vector_greater_than(const gsl_vector *v, double value)
{
for (size_t i = 0; i < v->size; i++) {
if (gsl_vector_get(v, i) > value) {
return i;
}
}
return 0;
}
/* Select the elements in the upper triangle of the matrix. All other elements
* will be set to zero.
*/
void
qdm_matrix_select_upper_triangle(gsl_matrix *m)
{
for (size_t i = 0; i < m->size1; i++) {
for (size_t j = 0; j < m->size2; j++) {
if (j < i) {
gsl_matrix_set(m, i, j, 0);
}
}
}
}
int
qdm_matrix_to_csc_matrix(csc **result, gsl_matrix *input)
{
int status = 0;
gsl_spmatrix *sm = gsl_spmatrix_alloc(input->size1, input->size2);
status = gsl_spmatrix_d2sp(sm, input);
if (status != 0) {
goto cleanup_sm;
}
gsl_spmatrix *sm_csc = gsl_spmatrix_compress(sm, GSL_SPMATRIX_CSC);
int m = sm_csc->size1;
int n = sm_csc->size2;
int nzmax = gsl_spmatrix_nnz(sm_csc);
size_t x_size = sizeof(double) * nzmax;
double *x = malloc(x_size);
memcpy(x, sm_csc->data, x_size);
size_t i_size = sizeof(int) * nzmax;
int *i = malloc(i_size);
memcpy(i, sm_csc->i, i_size);
size_t p_size = sizeof(int) * (n + 1);
int *p = malloc(p_size);
memcpy(p, sm_csc->p, p_size);
*result = csc_matrix(
m, // m First dimension (rows)
n, // n Second dimension (columns)
nzmax, // nzmax Maximum number of nonzero elements
x, // x Vector of data (size nzmax)
i, // i Vector of row indices (size nzmax)
p // p Vector of column pointers (size n+1)
);
gsl_spmatrix_free(sm_csc);
cleanup_sm:
gsl_spmatrix_free(sm);
return status;
}
gsl_vector *
qdm_vector_copy(const gsl_vector *src)
{
gsl_vector *dst = gsl_vector_alloc(src->size);
gsl_vector_memcpy(dst, src);
return dst;
}
gsl_matrix *
qdm_matrix_copy(const gsl_matrix *src)
{
gsl_matrix *dst = gsl_matrix_alloc(src->size1, src->size2);
gsl_matrix_memcpy(dst, src);
return dst;
}
int create_hd5(
const char *file_path,
const char *group_path
)
{
int status = 0;
hid_t file = -1;
hid_t group = -1;
hid_t gcpl = -1;
/* Save old error handler */
herr_t (*old_func)(hid_t, void*) = NULL;
void *old_client_data = NULL;
H5Eget_auto(H5E_DEFAULT, &old_func, &old_client_data);
/* Turn off error handling */
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
file = H5Fopen(file_path, H5F_ACC_RDWR, H5P_DEFAULT);
if (file < 0) {
file = H5Fcreate(file_path, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
}
if (file < 0) {
status = file;
goto cleanup;
}
group = H5Gopen(file, group_path, H5P_DEFAULT);
if (group < 0) {
gcpl = H5Pcreate(H5P_LINK_CREATE);
if (gcpl < 0) {
status = gcpl;
goto cleanup;
}
status = H5Pset_create_intermediate_group(gcpl, 1);
if (status < 0) {
goto cleanup;
}
group = H5Gcreate(file, group_path, gcpl, H5P_DEFAULT, H5P_DEFAULT);
if (group < 0) {
status = group;
goto cleanup;
}
}
cleanup:
if (gcpl >= 0) {
H5Pclose(gcpl);
}
if (group >= 0) {
H5Gclose(group);
}
if (file >= 0) {
H5Fclose(file);
}
/* Restore previous error handler */
H5Eset_auto(H5E_DEFAULT, old_func, old_client_data);
if (status < 0) {
H5Eprint(H5E_DEFAULT, stderr);
}
return status;
}
int
qdm_vector_hd5_read(
hid_t id,
const char *name,
gsl_vector **v
)
{
int status = 0;
int rank = 0;
status = H5LTget_dataset_ndims(id, name, &rank);
if (status < 0) {
return status;
}
hsize_t dims[rank];
status = H5LTget_dataset_info(id, name, dims, NULL, NULL);
if (status < 0) {
return status;
}
size_t size = 1;
for (int i = 0; i < rank; i++) {
size *= dims[i];
}
gsl_vector *tmp = gsl_vector_alloc(size);
status = H5LTread_dataset_double(id, name, tmp->data);
if (status < 0) {
gsl_vector_free(tmp);
return status;
}
*v = tmp;
return status;
}
int
qdm_vector_hd5_write(
hid_t id,
const char *name,
const gsl_vector *v
)
{
int status = 0;
hid_t datatype = -1;
hid_t dataspace = -1;
hid_t dataset = -1;
hid_t dcpl = -1;
if (v == NULL) {
goto cleanup;
}
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
status = H5Tset_order(datatype, H5T_ORDER_LE);
if (status != 0) {
goto cleanup;
}
hsize_t dims[1] = {
v->size,
};
dataspace = H5Screate_simple(1, dims, NULL);
if (dataspace < 0) {
status = dataspace;
goto cleanup;
}
dcpl = H5Pcreate(H5P_DATASET_CREATE);
if (dcpl < 0) {
status = dcpl;
goto cleanup;
}
/* Only enable compression on larger vectors. */
/*
if (v->size > 1024) {
status = H5Pset_deflate(dcpl, 9);
if (status != 0) {
goto cleanup;
}
hsize_t chunk_dims[1] = {
v->size,
};
status = H5Pset_chunk(dcpl, 1, chunk_dims);
if (status != 0) {
goto cleanup;
}
}
*/
dataset = H5Dcreate(id, name, datatype, dataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT);
if (dataset < 0) {
status = dataset;
goto cleanup;
}
status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, v->data);
if (status != 0) {
goto cleanup;
}
cleanup:
if (dcpl >= 0) {
H5Pclose(dcpl);
}
if (dataset >= 0) {
H5Dclose(dataset);
}
if (dataspace >= 0) {
H5Sclose(dataspace);
}
if (datatype >= 0) {
H5Tclose(datatype);
}
H5Oflush(id);
return status;
}
int
qdm_matrix_hd5_read(
hid_t id,
const char *name,
gsl_matrix **m
)
{
int status = 0;
int rank = 0;
status = H5LTget_dataset_ndims(id, name, &rank);
if (status < 0) {
return status;
}
if (rank < 2) {
return -1;
}
hsize_t dims[rank];
status = H5LTget_dataset_info(id, name, dims, NULL, NULL);
if (status < 0) {
return status;
}
size_t size1 = dims[0];
size_t size2 = 1;
for (int i = 1; i < rank; i++) {
size2 *= dims[i];
}
gsl_matrix *tmp = gsl_matrix_alloc(size1, size2);
status = H5LTread_dataset_double(id, name, tmp->data);
if (status < 0) {
gsl_matrix_free(tmp);
return status;
}
*m = tmp;
return status;
}
int
qdm_matrix_hd5_write(
hid_t id,
const char *name,
const gsl_matrix *m
)
{
int status = 0;
hid_t datatype = -1;
hid_t dataspace = -1;
hid_t dataset = -1;
hid_t dcpl = -1;
if (m == NULL) {
goto cleanup;
}
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
status = H5Tset_order(datatype, H5T_ORDER_LE);
if (status != 0) {
goto cleanup;
}
hsize_t dims[2] = {
m->size1,
m->size2,
};
dataspace = H5Screate_simple(2, dims, NULL);
if (dataspace < 0) {
status = dataspace;
goto cleanup;
}
dcpl = H5Pcreate(H5P_DATASET_CREATE);
if (dcpl < 0) {
status = dcpl;
goto cleanup;
}
/* Only enable compression on larger matrices. */
/*
if (m->size1 * m->size2 > 1024) {
status = H5Pset_deflate(dcpl, 9);
if (status != 0) {
goto cleanup;
}
hsize_t chunk_dims[2] = {
m->size1,
m->size2
};
status = H5Pset_chunk(dcpl, 2, chunk_dims);
if (status != 0) {
goto cleanup;
}
}
*/
dataset = H5Dcreate(id, name, datatype, dataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT);
if (dataset < 0) {
status = dataset;
goto cleanup;
}
status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, m->data);
if (status != 0) {
goto cleanup;
}
cleanup:
if (dcpl >= 0) {
H5Pclose(dcpl);
}
if (dataset >= 0) {
H5Dclose(dataset);
}
if (dataspace >= 0) {
H5Sclose(dataspace);
}
if (datatype >= 0) {
H5Tclose(datatype);
}
H5Oflush(id);
return status;
}
gsl_vector *
qdm_matrix_filter(
const gsl_matrix *m,
size_t needle_column,
double needle_value,
size_t select_column
)
{
size_t size = 0;
for (size_t i = 0; i < m->size1; i++) {
if (gsl_matrix_get(m, i, needle_column) == needle_value) {
size++;
}
}
gsl_vector *v = gsl_vector_alloc(size);
size_t j = 0;
for (size_t i = 0; i < m->size1; i++) {
double select_value = gsl_matrix_get(m, i, select_column);
if (gsl_matrix_get(m, i, needle_column) == needle_value) {
gsl_vector_set(v, j, select_value);
j++;
}
}
return v;
}
| {
"alphanum_fraction": 0.5968980103,
"avg_line_length": 17.9802816901,
"ext": "c",
"hexsha": "9ca42ca63b8d10ff4b2a944c6de755acf3b9f36a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "src/gsl.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "src/gsl.c",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "src/gsl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4232,
"size": 12766
} |
// Copyright 2018-2019 TAP, Inc. All Rights Reserved.
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <corecrt_math_defines.h>
#include <array>
#include <vector>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <chrono>
#include <filesystem>
#include <thread>
#include <string>
using namespace std::literals::string_literals;
#pragma warning(disable : 4127)
#pragma warning(disable : 4201)
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#pragma warning(default : 4201)
#pragma warning(default : 4127)
#pragma warning(disable : 4100)
#pragma warning(disable : 4458)
#include <gli/gli.hpp>
#pragma warning(default : 4458)
#pragma warning(default : 4100)
#define VK_USE_PLATFORM_WIN32_KHR
#include <vulkan/vulkan.h>
#include <vulkan/vk_mem_alloc.h>
#include <entt/entt.hpp>
#include <gsl/gsl>
| {
"alphanum_fraction": 0.7595486111,
"avg_line_length": 20.9454545455,
"ext": "h",
"hexsha": "ec047ee08b5200476a76b3c3a1257d68428b91d8",
"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": "2252d14cbb502414de7b03d7daf659ce44a0116d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "noirhero/new_framework",
"max_forks_repo_path": "stdafx.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2252d14cbb502414de7b03d7daf659ce44a0116d",
"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": "noirhero/new_framework",
"max_issues_repo_path": "stdafx.h",
"max_line_length": 54,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2252d14cbb502414de7b03d7daf659ce44a0116d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "noirhero/new_framework",
"max_stars_repo_path": "stdafx.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 299,
"size": 1152
} |
#pragma once
#include "../configuration.h"
#include <chrono>
#include <gsl/gsl-lite.hpp>
#include <string_view>
#include <utility>
#include <yaml-cpp/yaml.h>
namespace angonoka {
/**
Load Configuration from a YAML string.
@param text Null-terminated string
@return An instance of Configuration
*/
Configuration load_text(gsl::czstring text);
/**
Load Configuration from a YAML file.
@param path YAML configuration location
@return An instance of Configuration
*/
Configuration load_file(std::string_view path);
} // namespace angonoka
namespace angonoka::detail {
/**
Finds or inserts a group into Configuration.groups.
@param groups An array of Groups
@param group Group name
@return The index of the group in Configuration.groups
and whether the insertion took place.
*/
std::pair<GroupIndex, bool>
find_or_insert_group(Groups& groups, std::string_view group);
/**
Parses human-readable durations.
Parses durations with resolution ranging from seconds
up to and including months. Examples:
1h 15min
3 weeks and 5 months
30 seconds
@param text A string containing a duration.
@return The duration in seconds.
*/
std::chrono::seconds parse_duration(std::string_view text);
/**
Parses agents blocks.
Parses blocks such as these:
agents:
agent 1:
agent 2:
@param node "agents" node
@param config An instance of Configuration
*/
void parse_agents(const YAML::Node& node, Configuration& config);
/**
Parses tasks blocks.
Parses blocks such as these:
tasks:
- name: task 1
duration:
min: 1 h
max: 3 h
- name: task 2
duration: 2h
@param node "tasks" node
@param config An instance of Configuration
*/
void parse_tasks(const YAML::Node& node, Configuration& config);
} // namespace angonoka::detail
| {
"alphanum_fraction": 0.6832721552,
"avg_line_length": 21.1888888889,
"ext": "h",
"hexsha": "e44866e3f215e024a96d3a314f055045e59d4175",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "coffee-lord/angonoka",
"max_forks_repo_path": "src/config/load.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "coffee-lord/angonoka",
"max_issues_repo_path": "src/config/load.h",
"max_line_length": 65,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "coffee-lord/angonoka",
"max_stars_repo_path": "src/config/load.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z",
"num_tokens": 443,
"size": 1907
} |
/*
* 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 math_870b373b_c3fb_4c7a_abc7_bc4bd4095aef_h
#define math_870b373b_c3fb_4c7a_abc7_bc4bd4095aef_h
#include <gslib/config.h>
#include <gslib/basetype.h>
#ifndef PI
#define PI (3.14159265358979323846f)
#endif
__gslib_begin__
struct _vec2 { float x, y; };
struct _vec3 { float x, y, z; };
struct _vec4 { float x, y, z, w; };
struct _mat2
{
union
{
struct
{
float _11, _12,
_21, _22;
};
float m[2][2];
};
};
struct _mat3
{
union
{
struct
{
float _11, _12, _13,
_21, _22, _23,
_31, _32, _33;
};
float m[3][3];
};
};
struct _mat4
{
union
{
struct
{
float _11, _12, _13, _14,
_21, _22, _23, _24,
_31, _32, _33, _34,
_41, _42, _43, _44;
};
float m[4][4];
};
};
struct _quat
{
union
{
struct { float x, y, z, w; };
float q[4];
};
};
struct _plane { float a, b, c, d; };
struct viewport
{
int left;
int top;
uint width;
uint height;
float min_depth;
float max_depth;
};
class vec2;
class vec3;
class vec4;
class mat3;
class mat4;
class quat;
class plane;
typedef vec2 point2;
typedef vec3 point3;
typedef mat4 matrix;
typedef mat3 matrix3;
typedef _mat2 matrix2;
/* inline */
float vec2length(const vec2* p);
float vec2lengthsq(const vec2* p);
float vec2dot(const vec2* p1, const vec2* p2);
float vec2ccw(const vec2* p1, const vec2* p2);
vec2* vec2add(vec2* out, const vec2* p1, const vec2* p2);
vec2* vec2sub(vec2* out, const vec2* p1, const vec2* p2);
vec2* vec2min(vec2* out, const vec2* p1, const vec2* p2);
vec2* vec2max(vec2* out, const vec2* p1, const vec2* p2);
vec2* vec2scale(vec2* out, const vec2* p, float s);
vec2* vec2lerp(vec2* out, const vec2* p1, const vec2* p2, float s);
float vec2lerp_x(const vec2* p1, const vec2* p2, float y);
float vec2lerp_y(const vec2* p1, const vec2* p2, float x);
vec2* vec2multiply(vec2* out, const vec2* p, const matrix2* m);
vec2* vec2transformcoord(vec2* out, const vec2* p, const mat3* m);
vec2* vec2transformnormal(vec2* out, const vec2* p, const mat3* m);
float vec3length(const vec3* v);
float vec3lengthsq(const vec3* v);
float vec3dot(const vec3* v1, const vec3* v2);
vec3* vec3cross(vec3* out, const vec3* v1, const vec3* v2);
vec3* vec3add(vec3* out, const vec3* v1, const vec3* v2);
vec3* vec3sub(vec3* out, const vec3* v1, const vec3* v2);
vec3* vec3min(vec3* out, const vec3* v1, const vec3* v2);
vec3* vec3max(vec3* out, const vec3* v1, const vec3* v2);
vec3* vec3scale(vec3* out, const vec3* v, float s);
vec3* vec3lerp(vec3* out, const vec3* v1, const vec3* v2, float s);
vec3* vec3multiply(vec3* out, const vec3* v, const mat3* m);
vec3* vec3project(vec3* out, const vec3* v, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world);
vec3* vec3unproject(vec3* out, const vec3* v, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world);
vec3* vec3projectarray(vec3* out, uint ostride, const vec3* v, uint vstride, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world, uint n);
vec3* vec3unprojectarray(vec3* out, uint ostride, const vec3* v, uint vstride, const viewport* vp, const matrix* prj, const matrix* view, const matrix* world, uint n);
float vec4length(const vec4* v);
float vec4lengthsq(const vec4* v);
float vec4dot(const vec4* v1, const vec4* v2);
vec4* vec4add(vec4* out, const vec4* v1, const vec4* v2);
vec4* vec4sub(vec4* out, const vec4* v1, const vec4* v2);
vec4* vec4min(vec4* out, const vec4* v1, const vec4* v2);
vec4* vec4max(vec4* out, const vec4* v1, const vec4* v2);
vec4* vec4scale(vec4* out, const vec4* v, float s);
vec4* vec4lerp(vec4* out, const vec4* v1, const vec4* v2, float s);
vec4* vec4multiply(vec4* out, const vec4* v, const matrix* m);
matrix3* mat3identity(matrix3* out);
bool mat3isidentity(const matrix3* m);
float mat3determinant(const matrix3* m);
matrix3* mat3inverse(matrix3* out, float* det, const matrix3* m);
matrix3* mat3multiply(matrix3* out, const matrix3* m1, const matrix3* m2);
matrix3* mat3transpose(matrix3* out, const matrix3* m);
matrix3* mat3scaling(matrix3* out, float sx, float sy);
matrix3* mat3translation(matrix3* out, float x, float y);
matrix3* mat3rotation(matrix3* out, float angle);
matrix3* mat3rotationpos(matrix3* out, const vec2* p, float angle);
matrix* matidentity(matrix* out);
bool matisidentity(const matrix* m);
bool matdecompose(vec3* scale, quat* rot, vec3* trans, const matrix* m);
matrix* mattranspose(matrix* out, const matrix* m);
matrix* matscaling(matrix* out, float sx, float sy, float sz);
matrix* mattranslation(matrix* out, float x, float y, float z);
matrix* matrotation_x(matrix* out, float angle);
matrix* matrotation_y(matrix* out, float angle);
matrix* matrotation_z(matrix* out, float angle);
matrix* matrotationaxis(matrix* out, const vec3* v, float angle);
matrix* matrotationquatern(matrix* out, const quat* q);
matrix* matrotationeuler(matrix* out, float yaw, float pitch, float roll);
matrix* matlookatlh(matrix* out, const vec3* eye, const vec3* at, const vec3* up);
matrix* matlookatrh(matrix* out, const vec3* eye, const vec3* at, const vec3* up);
matrix* matperspectivelh(matrix* out, float w, float h, float zn, float zf);
matrix* matperspectiverh(matrix* out, float w, float h, float zn, float zf);
matrix* matperspectivefovlh(matrix* out, float fovy, float aspect, float zn, float zf);
matrix* matperspectivefovrh(matrix* out, float fovy, float aspect, float zn, float zf);
matrix* matperspectiveoffcenterlh(matrix* out, float l, float r, float b, float t, float zn, float zf);
matrix* matperspectiveoffcenterrh(matrix* out, float l, float r, float b, float t, float zn, float zf);
matrix* matortholh(matrix* out, float w, float h, float zn, float zf);
matrix* matorthorh(matrix* out, float w, float h, float zn, float zf);
matrix* matorthooffcenterlh(matrix* out, float l, float r, float b, float t, float zn, float zf);
matrix* matorthooffcenterrh(matrix* out, float l, float r, float b, float t, float zn, float zf);
matrix* matviewportproject(matrix* out, const viewport* vp);
matrix* matviewportunproject(matrix* out, const viewport* vp);
matrix* mattransform(matrix* out, const vec3* scalecenter, const quat* scalerot, const vec3* scale, const vec3* rotcenter, const quat* rot, const vec3* trans);
matrix* mattransform2d(matrix* out, const vec2* scalecenter, float scalerot, const vec2* scale, const vec2* rotcenter, float rot, const vec2* trans);
matrix* mataffinetransform(matrix* out, float scale, const vec3* rotcenter, const quat* rot, const vec3* trans);
matrix* mataffinetransform2d(matrix* out, float scale, const vec2* rotcenter, float rot, const vec2* trans);
float quatlength(const quat* q);
float quatlengthsq(const quat* q);
float quatdot(const quat* q1, const quat* q2);
quat* quatidentity(quat* out);
bool quatisidenetity(const quat* q);
quat* quatconjugate(quat* out, const quat* q);
void quattoaxisangle(const quat* q, vec3* axis, float* angle);
quat* quatrotatematrix(quat* out, const matrix* m);
quat* quatrotateaxis(quat* out, const vec3* v, float angle);
quat* quatln(quat* out, const quat* q);
quat* quatexp(quat* out, const quat* q);
quat* quatslerp(quat* out, const quat* q1, const quat* q2, float t);
quat* quatsquad(quat* out, const quat* q, const quat* a, const quat* b, const quat* c, float t);
quat* quatbarycentric(quat* out, const quat* q1, const quat* q2, const quat* q3, float f, float g);
void quatsquadsetup(quat* a, quat* b, quat* c, const quat* q1, const quat* q2, const quat* q3, const quat* q4);
float planedot(const plane* p, const vec4* v);
float planedotcoord(const plane* p, const vec3* v);
float planedotnormal(const plane* p, const vec3* v);
plane* planescale(plane* out, const plane* p, float s);
plane* planefrompointnormal(plane* out, const vec3* p, const vec3* normal);
/* non-inline */
typedef vec2* (__stdcall *fnvec2normalize)(vec2* out, const vec2* v);
typedef vec2* (__stdcall *fnvec2hermite)(vec2* out, const vec2* p1, const vec2* t1, const vec2* p2, const vec2* t2, float s);
typedef vec2* (__stdcall *fnvec2catmullrom)(vec2* out, const vec2* p1, const vec2* p2, const vec2* p3, const vec2* p4, float s);
typedef vec2* (__stdcall *fnvec2barycentric)(vec2* out, const vec2* p1, const vec2* p2, const vec2* p3, float f, float g);
typedef vec4* (__stdcall *fnvec2transform)(vec4* out, const vec2* p, const matrix* m);
typedef vec2* (__stdcall *fnvec2transformcoord)(vec2* out, const vec2* p, const matrix* m);
typedef vec2* (__stdcall *fnvec2transformnormal)(vec2* out, const vec2* p, const matrix* m);
typedef vec4* (__stdcall *fnvec2transformarray)(vec4* out, uint ostride, const vec2* v, uint vstride, const matrix* m, uint n);
typedef vec2* (__stdcall *fnvec2transformcoordarray)(vec2* out, uint ostride, const vec2* v, uint vstride, const matrix* m, uint n);
typedef vec2* (__stdcall *fnvec2transformnormalarray)(vec2* out, uint ostride, const vec2* v, uint vstride, const matrix* m, uint n);
typedef vec3* (__stdcall *fnvec3normalize)(vec3* out, const vec3* v);
typedef vec3* (__stdcall *fnvec3hermite)(vec3* out, const vec3* v1, const vec3* t1, const vec3* v2, const vec3* t2, float s);
typedef vec3* (__stdcall *fnvec3catmullrom)(vec3* out, const vec3* v1, const vec3* v2, const vec3* v3, const vec3* v4, float s);
typedef vec3* (__stdcall *fnvec3barycentric)(vec3* out, const vec3* v1, const vec3* v2, const vec3* v3, float f, float g);
typedef vec4* (__stdcall *fnvec3transform)(vec4* out, const vec3* v, const matrix* m);
typedef vec3* (__stdcall *fnvec3transformcoord)(vec3* out, const vec3* v, const matrix* m);
typedef vec3* (__stdcall *fnvec3transformnormal)(vec3* out, const vec3* v, const matrix* m);
typedef vec4* (__stdcall *fnvec3transformarray)(vec4* out, uint ostride, const vec3* v, uint vstride, const matrix* m, uint n);
typedef vec3* (__stdcall *fnvec3transformcoordarray)(vec3* out, uint ostride, const vec3* v, uint vstride, const matrix* m, uint n);
typedef vec3* (__stdcall *fnvec3transformnormalarray)(vec3* out, uint ostride, const vec3* v, uint vstride, const matrix* m, uint n);
typedef vec4* (__stdcall *fnvec4cross)(vec4* out, const vec4* v1, const vec4* v2, const vec4* v3);
typedef vec4* (__stdcall *fnvec4normalize)(vec4* out, const vec4* v);
typedef vec4* (__stdcall *fnvec4hermite)(vec4* out, const vec4* v1, const vec4* t1, const vec4* v2, const vec4* t2, float s);
typedef vec4* (__stdcall *fnvec4catmullrom)(vec4* out, const vec4* v1, const vec4* v2, const vec4* v3, const vec4* v4, float s);
typedef vec4* (__stdcall *fnvec4barycentric)(vec4* out, const vec4* v1, const vec4* v2, const vec4* v3, float f, float g);
typedef vec4* (__stdcall *fnvec4transform)(vec4* out, const vec4* v, const matrix* m);
typedef vec4* (__stdcall *fnvec4transformarray)(vec4* out, uint ostride, const vec4* v, uint vstride, const matrix* m, uint n);
typedef float (__stdcall *fnmatdeterminant)(const matrix* m);
typedef matrix* (__stdcall *fnmatmultiply)(matrix* out, const matrix* m1, const matrix* m2);
typedef matrix* (__stdcall *fnmatmultiplytranspose)(matrix* out, const matrix* m1, const matrix* m2);
typedef matrix* (__stdcall *fnmatinverse)(matrix* out, float* determinant, const matrix* m);
typedef matrix* (__stdcall *fnmatshadow)(matrix* out, const vec4* plight, const plane* pln);
typedef matrix* (__stdcall *fnmatreflect)(matrix* out ,const plane* pln);
typedef quat* (__stdcall *fnquatrotateeuler)(quat* out, float yaw, float pitch, float roll);
typedef quat* (__stdcall *fnquatmultiply)(quat* out, const quat* q1, const quat* q2);
typedef quat* (__stdcall *fnquatnormalize)(quat* out, const quat* q);
typedef quat* (__stdcall *fnquatinverse)(quat* out, const quat* q);
typedef plane* (__stdcall *fnplanenormalize)(plane* out, const plane* p);
typedef vec3* (__stdcall *fnplaneintersectline)(vec3* out, const plane* p, const vec3* v1, const vec3* v2);
typedef plane* (__stdcall *fnplanefrompoints)(plane* out, const vec3* v1, const vec3* v2, const vec3* v3);
typedef plane* (__stdcall *fnplanetransform)(plane* out, const plane* p, const matrix* m);
typedef plane* (__stdcall *fnplanetransformarray)(plane* out, uint ostride, const plane* p, uint pstride, const matrix* m, uint n);
gs_export extern fnvec2normalize vec2normalize;
gs_export extern fnvec2hermite vec2hermite;
gs_export extern fnvec2catmullrom vec2catmullrom;
gs_export extern fnvec2barycentric vec2barycentric;
gs_export extern fnvec2transform vec2transform;
gs_export extern fnvec2transformarray vec2transformarray;
gs_export extern fnvec2transformcoordarray vec2transformcoordarray;
gs_export extern fnvec2transformnormalarray vec2transformnormalarray;
gs_export extern fnvec3normalize vec3normalize;
gs_export extern fnvec3hermite vec3hermite;
gs_export extern fnvec3catmullrom vec3catmullrom;
gs_export extern fnvec3barycentric vec3barycentric;
gs_export extern fnvec3transform vec3transform;
gs_export extern fnvec3transformcoord vec3transformcoord;
gs_export extern fnvec3transformnormal vec3transformnormal;
gs_export extern fnvec3transformarray vec3transformarray;
gs_export extern fnvec3transformcoordarray vec3transformcoordarray;
gs_export extern fnvec3transformnormalarray vec3transformnormalarray;
gs_export extern fnvec4cross vec4cross;
gs_export extern fnvec4normalize vec4normalize;
gs_export extern fnvec4hermite vec4hermite;
gs_export extern fnvec4catmullrom vec4catmullrom;
gs_export extern fnvec4barycentric vec4barycentric;
gs_export extern fnvec4transform vec4transform;
gs_export extern fnvec4transformarray vec4transformarray;
gs_export extern fnmatdeterminant matdeterminant;
gs_export extern fnmatmultiply matmultiply;
gs_export extern fnmatmultiplytranspose matmultiplytranspose;
gs_export extern fnmatinverse matinverse;
gs_export extern fnmatshadow matshadow;
gs_export extern fnmatreflect matreflect;
gs_export extern fnquatrotateeuler quatrotateeuler;
gs_export extern fnquatmultiply quatmultiply;
gs_export extern fnquatnormalize quatnormalize;
gs_export extern fnquatinverse quatinverse;
gs_export extern fnplanenormalize planenormalize;
gs_export extern fnplaneintersectline planeintersectline;
gs_export extern fnplanefrompoints planefrompoints;
gs_export extern fnplanetransform planetransform;
gs_export extern fnplanetransformarray planetransformarray;
class gs_export vec2:
public _vec2
{
public:
vec2() {}
vec2(const float*);
vec2(float x, float y);
public:
operator float*();
operator const float*() const;
public:
vec2& operator+=(const vec2&);
vec2& operator-=(const vec2&);
vec2& operator*=(float);
vec2& operator/=(float);
public:
vec2 operator+() const;
vec2 operator-() const;
public:
vec2 operator+(const vec2&) const;
vec2 operator-(const vec2&) const;
vec2 operator*(float) const;
vec2 operator/(float) const;
friend vec2 operator*(float, const vec2&);
public:
bool operator==(const vec2&) const;
bool operator!=(const vec2&) const;
public:
float length() const { return vec2length(this); }
float lengthsq() const { return vec2lengthsq(this); }
float dot(const vec2& v) const { return vec2dot(this, &v); }
float ccw(const vec2& v) const { return vec2ccw(this, &v); }
vec2& add(const vec2& p1, const vec2& p2) { return *vec2add(this, &p1, &p2); }
vec2& sub(const vec2& p1, const vec2& p2) { return *vec2sub(this, &p1, &p2); }
vec2& scale(float s) { return *vec2scale(this, this, s); }
vec2& scale(const vec2& v, float s) { return *vec2scale(this, &v, s); }
vec2& lerp(const vec2& p1, const vec2& p2, float s) { return *vec2lerp(this, &p1, &p2, s); }
vec2& multiply(const matrix2& m) { return *vec2multiply(this, this, &m); }
vec2& multiply(const vec2& p, const matrix2& m) { return *vec2multiply(this, &p, &m); }
vec2& normalize() { return *vec2normalize(this, this); }
vec2& normalize(const vec2& v) { return *vec2normalize(this, &v); }
vec2& hermite(const vec2& p1, const vec2& t1, const vec2& p2, const vec2& t2, float s) { return *vec2hermite(this, &p1, &t1, &p2, &t2, s); }
vec2& catmullrom(const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4, float s) { return *vec2catmullrom(this, &p1, &p2, &p3, &p4, s); }
vec2& barycentric(const vec2& p1, const vec2& p2, const vec2& p3, float f, float g) { return *vec2barycentric(this, &p1, &p2, &p3, f, g); }
vec4& transform(vec4& v, const matrix& m) const { return *vec2transform(&v, this, &m); }
vec2& transformcoord(const mat3& m) { return *vec2transformcoord(this, this, &m); }
vec2& transformcoord(const vec2& p, const mat3& m) { return *vec2transformcoord(this, &p, &m); }
vec2& transformnormal(const mat3& m) { return *vec2transformnormal(this, this, &m); }
vec2& transformnormal(const vec2& p, const mat3& m) { return *vec2transformnormal(this, &p, &m); }
};
class gs_export vec3:
public _vec3
{
public:
vec3() {}
vec3(const float*);
vec3(float x, float y, float z);
public:
operator float*();
operator const float*() const;
public:
vec3& operator+=(const vec3&);
vec3& operator-=(const vec3&);
vec3& operator*=(float);
vec3& operator/=(float);
public:
vec3 operator+() const;
vec3 operator-() const;
public:
vec3 operator+(const vec3&) const;
vec3 operator-(const vec3&) const;
vec3 operator*(float) const;
vec3 operator/(float) const;
friend vec3 operator*(float, const vec3&);
public:
bool operator==(const vec3&) const;
bool operator!=(const vec3&) const;
public:
float length() const { return vec3length(this); }
float lengthsq() const { return vec3lengthsq(this); }
float dot(const vec3& v) const { return vec3dot(this, &v); }
vec3& add(const vec3& v1, const vec3& v2) { return *vec3add(this, &v1, &v2); }
vec3& sub(const vec3& v1, const vec3& v2) { return *vec3sub(this, &v1, &v2); }
vec3& cross(const vec3& v) { return *vec3cross(this, &vec3(*this), &v); }
vec3& cross(const vec3& v1, const vec3& v2) { return *vec3cross(this, &v1, &v2); }
vec3& scale(float s) { return *vec3scale(this, this, s); }
vec3& scale(const vec3& v, float s) { return *vec3scale(this, &v, s); }
vec3& lerp(const vec3& p1, const vec3& p2, float s) { return *vec3lerp(this, &p1, &p2, s); }
vec3& multiply(const vec3& p, const mat3& m) { return *vec3multiply(this, &p, &m); }
vec3& project(const viewport& vp, const matrix& prj, const matrix& view, const matrix& world) { return *vec3project(this, this, &vp, &prj, &view, &world); }
vec3& unproject(const viewport& vp, const matrix& prj, const matrix& view, const matrix& world) { return *vec3unproject(this, this, &vp, &prj, &view, &world); }
vec3& normalize() { return *vec3normalize(this, this); }
vec3& normalize(const vec3& v) { return *vec3normalize(this, &v); }
vec3& hermite(const vec3& v1, const vec3& t1, const vec3& v2, const vec3& t2, float s) { return *vec3hermite(this, &v1, &t1, &v2, &t2, s); }
vec3& catmullrom(const vec3& v1, const vec3& v2, const vec3& v3, const vec3& v4, float s) { return *vec3catmullrom(this, &v1, &v2, &v3, &v4, s); }
vec3& barycentric(const vec3& v1, const vec3& v2, const vec3& v3, float f, float g) { return *vec3barycentric(this, &v1, &v2, &v3, f, g); }
vec4& transform(vec4& v, const matrix& m) const { return *vec3transform(&v, this, &m); }
vec3& transformcoord(const matrix& m) { return *vec3transformcoord(this, this, &m); }
vec3& transformcoord(const vec3& v, const matrix& m) { return *vec3transformcoord(this, &v, &m); }
vec3& transformnormal(const matrix& m) { return *vec3transformnormal(this, this, &m); }
vec3& transformnormal(const vec3& v, const matrix& m) { return *vec3transformnormal(this, &v, &m); }
};
class gs_export vec4:
public _vec4
{
public:
vec4() {}
vec4(const float*);
vec4(const _vec3& xyz, float w);
vec4(float x, float y, float z, float w);
public:
operator float*();
operator const float*() const;
public:
vec4& operator+=(const vec4&);
vec4& operator-=(const vec4&);
vec4& operator*=(float);
vec4& operator/=(float);
public:
vec4 operator+() const;
vec4 operator-() const;
public:
vec4 operator+(const vec4&) const;
vec4 operator-(const vec4&) const;
vec4 operator*(float) const;
vec4 operator/(float) const;
friend vec4 operator*(float, const vec4&);
public:
bool operator==(const vec4&) const;
bool operator!=(const vec4&) const;
public:
float length() const { return vec4length(this); }
float lengthsq() const { return vec4lengthsq(this); }
float dot(const vec4& v) const { return vec4dot(this, &v); }
vec4& add(const vec4& v1, const vec4& v2) { return *vec4add(this, &v1, &v2); }
vec4& sub(const vec4& v1, const vec4& v2) { return *vec4sub(this, &v1, &v2); }
vec4& scale(float s) { return *vec4scale(this, this, s); }
vec4& scale(const vec4& v, float s) { return *vec4scale(this, &v, s); }
vec4& lerp(const vec4& v1, const vec4& v2, float s) { return *vec4lerp(this, &v1, &v2, s); }
vec4& multiply(const matrix& m) { return *vec4multiply(this, this, &m); }
vec4& multiply(const vec4& v, const matrix& m) { return *vec4multiply(this, &v, &m); }
vec4& cross(const vec4& v1, const vec4& v2, const vec4& v3) { return *vec4cross(this, &v1, &v2, &v3); }
vec4& hermite(const vec4& v1, const vec4& t1, const vec4& v2, const vec4& t2, float s) { return *vec4hermite(this, &v1, &t1, &v2, &t2, s); }
vec4& catmullrom(const vec4& v1, const vec4& v2, const vec4& v3, const vec4& v4, float s) { return *vec4catmullrom(this, &v1, &v2, &v3, &v4, s); }
vec4& barycentric(const vec4& v1, const vec4& v2, const vec4& v3, float f, float g) { return *vec4barycentric(this, &v1, &v2, &v3, f, g); }
vec4& transform(const matrix& m) { return *vec4transform(this, this, &m); }
vec4& transform(const vec4& v, const matrix& m) { return *vec4transform(this, &v, &m); }
};
class gs_export mat3:
public _mat3
{
public:
mat3() {}
mat3(const float*);
mat3(const mat3&);
mat3(float f11, float f12, float f13,
float f21, float f22, float f23,
float f31, float f32, float f33
);
public:
float& operator()(uint row, uint col);
float operator()(uint row, uint col) const;
operator float*();
operator const float*() const;
public:
mat3& operator*=(const mat3&);
mat3& operator+=(const mat3&);
mat3& operator-=(const mat3&);
mat3& operator*=(float);
mat3& operator/=(float);
public:
mat3 operator+() const;
mat3 operator-() const;
public:
mat3 operator*(const mat3&) const;
mat3 operator+(const mat3&) const;
mat3 operator-(const mat3&) const;
mat3 operator*(float) const;
mat3 operator/(float) const;
friend mat3 operator*(float, const mat3&);
public:
bool operator==(const mat3&) const;
bool operator!=(const mat3&) const;
public:
mat3& identity() { return *mat3identity(this); }
bool isidentity() const { return mat3isidentity(this); }
mat3& transpose() { return *mat3transpose(this, this); }
mat3& transpose(const mat3& m) { return *mat3transpose(this, &m); }
mat3& scaling(float sx, float sy) { return *mat3scaling(this, sx, sy); }
mat3& translation(float x, float y) { return *mat3translation(this, x, y); }
mat3& rotation(float angle) { return *mat3rotation(this, angle); }
mat3& rotationpos(const vec2& p, float angle) { return *mat3rotationpos(this, &p, angle); }
mat3& multiply(const mat3& m) { return *mat3multiply(this, this, &m); }
mat3& multiply(const mat3& m1, const mat3& m2) { return *mat3multiply(this, &m1, &m2); }
float determinant() const { return mat3determinant(this); }
mat3& inverse(float* det, const mat3& m) { return *mat3inverse(this, det, &m); }
};
class gs_export mat4:
public _mat4
{
public:
mat4() {}
mat4(const float*);
mat4(const mat4&);
mat4(float f11, float f12, float f13, float f14,
float f21, float f22, float f23, float f24,
float f31, float f32, float f33, float f34,
float f41, float f42, float f43, float f44);
public:
float& operator()(uint row, uint col);
float operator()(uint row, uint col) const;
operator float*();
operator const float*() const;
public:
mat4& operator*=(const mat4&);
mat4& operator+=(const mat4&);
mat4& operator-=(const mat4&);
mat4& operator*=(float);
mat4& operator/=(float);
public:
mat4 operator+() const;
mat4 operator-() const;
public:
mat4 operator*(const mat4&) const;
mat4 operator+(const mat4&) const;
mat4 operator-(const mat4&) const;
mat4 operator*(float) const;
mat4 operator/(float) const;
friend mat4 operator*(float, const mat4&);
public:
bool operator==(const mat4&) const;
bool operator!=(const mat4&) const;
public:
mat4& identity() { return *matidentity(this); }
bool isidentity() const { return matisidentity(this); }
bool decompose(vec3& scale, quat& rot, vec3& trans) { return matdecompose(&scale, &rot, &trans, this); }
mat4& transpose() { return *mattranspose(this, this); }
mat4& transpose(const mat4& m) { return *mattranspose(this, &m); }
mat4& scaling(float sx, float sy, float sz) { return *matscaling(this, sx, sy, sz); }
mat4& translation(float x, float y, float z) { return *mattranslation(this, x, y, z); }
mat4& rotation_x(float angle) { return *matrotation_x(this, angle); }
mat4& rotation_y(float angle) { return *matrotation_y(this, angle); }
mat4& rotation_z(float angle) { return *matrotation_z(this, angle); }
mat4& rotation(const vec3& v, float angle) { return *matrotationaxis(this, &v, angle); }
mat4& rotation(const quat& q) { return *matrotationquatern(this, &q); }
mat4& rotation(float yaw, float pitch, float roll) { return *matrotationeuler(this, yaw, pitch, roll); }
mat4& lookatlh(const vec3& eye, const vec3& at, const vec3& up) { return *matlookatlh(this, &eye, &at, &up); }
mat4& lookatrh(const vec3& eye, const vec3& at, const vec3& up) { return *matlookatrh(this, &eye, &at, &up); }
mat4& perspectivelh(float w, float h, float zn, float zf) { return *matperspectivelh(this, w, h, zn, zf); }
mat4& perspectiverh(float w, float h, float zn, float zf) { return *matperspectiverh(this, w, h, zn, zf); }
mat4& perspectivefovlh(float fovy, float aspect, float zn, float zf) { return *matperspectivefovlh(this, fovy, aspect, zn, zf); }
mat4& perspectivefovrh(float fovy, float aspect, float zn, float zf) { return *matperspectivefovrh(this, fovy, aspect, zn, zf); }
mat4& perspectiveoffcenterlh(float l, float r, float b, float t, float zn, float zf) { return *matperspectiveoffcenterlh(this, l ,r, b, t, zn, zf); }
mat4& perspectiveoffcenterrh(float l, float r, float b, float t, float zn, float zf) { return *matperspectiveoffcenterlh(this, l ,r, b, t, zn, zf); }
mat4& ortholh(float w, float h, float zn, float zf) { return *matortholh(this, w, h, zn, zf); }
mat4& orthorh(float w, float h, float zn, float zf) { return *matorthorh(this, w, h, zn, zf); }
mat4& orthooffcenterlh(float l, float r, float b, float t, float zn, float zf) { return *matorthooffcenterlh(this, l, r, b, t, zn, zf); }
mat4& orthooffcenterrh(float l, float r, float b, float t, float zn, float zf) { return *matorthooffcenterrh(this, l, r, b, t, zn, zf); }
mat4& viewportproject(const viewport& vp) { return *matviewportproject(this, &vp); }
mat4& viewportunproject(const viewport& vp) { return *matviewportunproject(this, &vp); }
mat4& transform(const vec3& scalecenter, const quat& scalerot, const vec3& scale, const vec3& rotcenter, const quat& rot, const vec3& trans) { return *mattransform(this, &scalecenter, &scalerot, &scale, &rotcenter, &rot, &trans); }
mat4& transform2d(const vec2& scalecenter, float scalerot, const vec2& scale, const vec2& rotcenter, float rot, const vec2& trans) { return *mattransform2d(this, &scalecenter, scalerot, &scale, &rotcenter, rot, &trans); }
mat4& affinetransform(float scale, const vec3& rotcenter, const quat& rot, const vec3& trans) { return *mataffinetransform(this, scale, &rotcenter, &rot, &trans); }
mat4& affinetransform2d(float scale, const vec2& rotcenter, float rot, const vec2& trans) { return *mataffinetransform2d(this, scale, &rotcenter, rot, &trans); }
float determinant() const { return matdeterminant(this); }
mat4& multiply(const mat4& m) { return *matmultiply(this, this, &m); }
mat4& multiply(const mat4& m1, const mat4& m2) { return *matmultiply(this, &m1, &m2); }
mat4& multiplytranspose(const mat4& m) { return *matmultiplytranspose(this, this, &m); }
mat4& multiplytranspose(const mat4& m1, const mat4& m2) { return *matmultiplytranspose(this, &m1, &m2); }
mat4& inverse(float* determinant, const mat4& m) { return *matinverse(this, determinant, &m); }
mat4& shadow(const vec4& plight, const plane& pln) { return *matshadow(this, &plight, &pln); }
mat4& reflect(const plane& pln) { return *matreflect(this, &pln); }
};
class gs_export quat:
public _quat
{
public:
quat() {}
quat(const float*);
quat(float x, float y, float z, float w);
public:
operator float*();
operator const float*() const;
public:
quat& operator+=(const quat&);
quat& operator-=(const quat&);
quat& operator*=(const quat&);
quat& operator*=(float);
quat& operator/=(float);
public:
quat operator+() const;
quat operator-() const;
public:
quat operator+(const quat&) const;
quat operator-(const quat&) const;
quat operator*(const quat&) const;
quat operator*(float) const;
quat operator/(float) const;
friend quat operator*(float, const quat&);
public:
bool operator==(const quat&) const;
bool operator!=(const quat&) const;
public:
float length() const { return quatlength(this); }
float lengthsq() const { return quatlengthsq(this); }
float dot(const quat& q) const { return quatdot(this, &q); }
quat& identity() { return *quatidentity(this); }
bool isidentity() const { return quatisidenetity(this); }
quat& conjugate() { return *quatconjugate(this, this); }
quat& conjugate(const quat& q) { return *quatconjugate(this, &q); }
float toaxisangle(vec3& axis) const
{
float f;
quattoaxisangle(this, &axis, &f);
return f;
}
quat& rotate(const matrix& m) { return *quatrotatematrix(this, &m); }
quat& rotate(const vec3& v, float angle) { return *quatrotateaxis(this, &v, angle); }
quat& ln() { return *quatln(this, this); }
quat& ln(const quat& q) { return *quatln(this, &q); }
quat& exp() { return *quatexp(this, this); }
quat& exp(const quat& q) { return *quatexp(this, &q); }
quat& slerp(const quat& q1, const quat& q2, float t) { return *quatslerp(this, &q1, &q2, t); }
quat& squad(const quat& q, const quat& a, const quat& b, const quat& c, float f) { return *quatsquad(this, &q, &a, &b, &c, f); }
quat& squad(const quat& a, const quat& b, const quat& c, float f) { return *quatsquad(this, this, &a, &b, &c, f); }
quat& barycentric(const quat& q1, const quat& q2, const quat& q3, float f, float g) { return *quatbarycentric(this, &q1, &q2, &q3, f, g); }
quat& rotate(float yaw, float pitch, float roll) { return *quatrotateeuler(this, yaw, pitch, roll); }
quat& multiply(const quat& q1, const quat& q2) { return *quatmultiply(this, &q1, &q2); }
quat& normalize() { return *quatnormalize(this, this); }
quat& normalize(const quat& q) { return *quatnormalize(this, &q); }
quat& inverse() { return *quatinverse(this, this); }
quat& inverse(const quat& q) { return *quatinverse(this, &q); }
};
class gs_export plane:
public _plane
{
public:
plane() {}
plane(const float*);
plane(float a, float b, float c, float d);
public:
operator float*();
operator const float*() const;
public:
plane& operator*=(float);
plane& operator/=(float);
plane operator+() const;
plane operator-() const;
plane operator*(float) const;
plane operator/(float) const;
friend plane operator*(float, const plane&);
public:
bool operator==(const plane&) const;
bool operator!=(const plane&) const;
public:
float dot(const vec4& v) const { return planedot(this, &v); }
float dotcoord(const vec3& v) const { return planedotcoord(this, &v); }
float dotnormal(const vec3& v) const { return planedotnormal(this, &v); }
plane& scale(float s) { return *planescale(this, this, s); }
plane& scale(const plane& p, float s) { return *planescale(this, &p, s); }
plane& frompointnormal(const vec3& p, const vec3& normal) { return *planefrompointnormal(this, &p, &normal); }
plane& normalize() { return *planenormalize(this, this); }
plane& normalize(const plane& p) { return *planenormalize(this, &p); }
vec3& intersectline(vec3& v, const vec3& v1, const vec3& v2) const { return *planeintersectline(&v, this, &v1, &v2); }
plane& frompoints(const vec3& v1, const vec3& v2, const vec3& v3) { return *planefrompoints(this, &v1, &v2, &v3); }
plane& transform(const matrix& m) { return *planetransform(this, this, &m); }
plane& transform(const plane& p, const matrix& m) { return *planetransform(this, &p, &m); }
};
__gslib_end__
#include <gslib/math.inl>
#endif
| {
"alphanum_fraction": 0.6766078255,
"avg_line_length": 49.2060857538,
"ext": "h",
"hexsha": "44d442cd7d0d597c7dc9753870ead1027c8310b0",
"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/math.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/math.h",
"max_line_length": 236,
"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/math.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": 10973,
"size": 35576
} |
#pragma once
#include "ui/detail/nki_image.h"
#include "ui/detail/nk_essential.h"
#include <gsl/gsl>
#include <nuklear.h>
namespace cws80 {
class UIController;
struct FontRequest;
enum class GraphicsType {
Other,
OpenGL,
Cairo,
Gdiplus,
};
//
class GraphicsDevice {
public:
explicit GraphicsDevice(UIController &ctl)
: ctl_(ctl)
{
}
virtual ~GraphicsDevice() {}
virtual GraphicsType type() const = 0;
virtual void setup_context() {}
virtual void initialize(gsl::span<const FontRequest> fontreqs) = 0;
virtual void cleanup() = 0;
im_texture load_texture(const im_image &img);
virtual im_texture load_texture(const u8 *data, uint w, uint h, uint channels) = 0;
virtual void unload_texture(nk_handle handle) = 0;
virtual void render(void *draw_context) = 0;
virtual nk_user_font *get_font(uint id) = 0;
protected:
UIController &ctl_;
};
//------------------------------------------------------------------------------
struct FontRequest {
static FontRequest Default(f32 height, const nk_rune *range);
static FontRequest File(f32 height, const char *path, const nk_rune *range);
static FontRequest Memory(f32 height, const void *data, size_t size, const nk_rune *range);
enum class Type { Default, File, Memory } type;
f32 height;
const nk_rune *range;
union {
struct {
const char *path;
} file;
struct {
const void *data;
size_t size;
} memory;
} un;
};
inline auto FontRequest::Default(f32 height, const nk_rune *range) -> FontRequest
{
FontRequest req;
req.type = FontRequest::Type::Default;
req.height = height;
req.range = range;
return req;
}
inline auto FontRequest::File(f32 height, const char *path, const nk_rune *range) -> FontRequest
{
FontRequest req;
req.type = FontRequest::Type::File;
req.height = height;
req.range = range;
req.un.file.path = path;
return req;
}
inline auto FontRequest::Memory(f32 height, const void *data, size_t size, const nk_rune *range) -> FontRequest
{
FontRequest req;
req.type = FontRequest::Type::Memory;
req.height = height;
req.range = range;
req.un.memory.data = data;
req.un.memory.size = size;
return req;
}
} // namespace cws80
| {
"alphanum_fraction": 0.6352389078,
"avg_line_length": 23.9183673469,
"ext": "h",
"hexsha": "230b50aa5efb5312ce78517ccbaba0d945e50ca8",
"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": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "jpcima/cws80",
"max_forks_repo_path": "sources/ui/detail/device/dev_graphics.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "jpcima/cws80",
"max_issues_repo_path": "sources/ui/detail/device/dev_graphics.h",
"max_line_length": 111,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "jpcima/cws80",
"max_stars_repo_path": "sources/ui/detail/device/dev_graphics.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z",
"num_tokens": 579,
"size": 2344
} |
#include <math.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gpc/gpc.h>
#include <egsl/egsl_macros.h>
#include "../csm_all.h"
#include "icp.h"
int icp_loop(struct sm_params*params, const double*q0, double*x_new,
double*total_error, int*valid, int*iterations) {
if(any_nan(q0,3)) {
sm_error("icp_loop: Initial pose contains nan: %s\n", friendly_pose(q0));
return 0;
}
LDP laser_sens = params->laser_sens;
double x_old[3], delta[3], delta_old[3] = {0,0,0};
copy_d(q0, 3, x_old);
unsigned int hashes[params->max_iterations];
int iteration;
sm_debug("icp: starting at q0 = %s \n", friendly_pose(x_old));
if(JJ) jj_loop_enter("iterations");
int all_is_okay = 1;
for(iteration=0; iteration<params->max_iterations;iteration++) {
if(JJ) jj_loop_iteration();
if(JJ) jj_add_double_array("x_old", x_old, 3);
egsl_push_named("icp_loop iteration");
sm_debug("== icp_loop: starting iteration. %d \n", iteration);
/** Compute laser_sens's points in laser_ref's coordinates
by roto-translating by x_old */
ld_compute_world_coords(laser_sens, x_old);
/** Find correspondences (the naif or smart way) */
if(params->use_corr_tricks)
find_correspondences_tricks(params);
else
find_correspondences(params);
/** If debug_verify_tricks, make sure that find_correspondences_tricks()
and find_correspondences() return the same answer */
if(params->debug_verify_tricks)
debug_correspondences(params);
/* If not many correspondences, bail out */
int num_corr = ld_num_valid_correspondences(laser_sens);
double fail_perc = 0.05;
if(num_corr < fail_perc * laser_sens->nrays) { /* TODO: arbitrary */
sm_error(" : before trimming, only %d correspondences.\n",num_corr);
all_is_okay = 0;
egsl_pop_named("icp_loop iteration"); /* loop context */
break;
}
if(JJ) jj_add("corr0", corr_to_json(laser_sens->corr, laser_sens->nrays));
/* Kill some correspondences (using dubious algorithm) */
if(params->outliers_remove_doubles)
kill_outliers_double(params);
int num_corr2 = ld_num_valid_correspondences(laser_sens);
if(JJ) jj_add("corr1", corr_to_json(laser_sens->corr, laser_sens->nrays));
double error=0;
/* Trim correspondences */
kill_outliers_trim(params, &error);
int num_corr_after = ld_num_valid_correspondences(laser_sens);
if(JJ) {
jj_add("corr2", corr_to_json(laser_sens->corr, laser_sens->nrays));
jj_add_int("num_corr0", num_corr);
jj_add_int("num_corr1", num_corr2);
jj_add_int("num_corr2", num_corr_after);
}
*total_error = error;
*valid = num_corr_after;
sm_debug(" icp_loop: total error: %f valid %d mean = %f\n", *total_error, *valid, *total_error/ *valid);
/* If not many correspondences, bail out */
if(num_corr_after < fail_perc * laser_sens->nrays){
sm_error(" icp_loop: failed: after trimming, only %d correspondences.\n",num_corr_after);
all_is_okay = 0;
egsl_pop_named("icp_loop iteration"); /* loop context */
break;
}
/* Compute next estimate based on the correspondences */
if(!compute_next_estimate(params, x_old, x_new)) {
sm_error(" icp_loop: Cannot compute next estimate.\n");
all_is_okay = 0;
egsl_pop_named("icp_loop iteration");
break;
}
pose_diff_d(x_new, x_old, delta);
{
sm_debug(" icp_loop: killing. laser_sens has %d/%d rays valid, %d corr found -> %d after double cut -> %d after adaptive cut \n", count_equal(laser_sens->valid, laser_sens->nrays, 1), laser_sens->nrays, num_corr, num_corr2, num_corr_after);
if(JJ) {
jj_add_double_array("x_new", x_new, 3);
jj_add_double_array("delta", delta, 3);
}
}
/** Checks for oscillations */
hashes[iteration] = ld_corr_hash(laser_sens);
{
sm_debug(" icp_loop: it. %d hash=%d nvalid=%d mean error = %f, x_new= %s\n",
iteration, hashes[iteration], *valid, *total_error/ *valid,
friendly_pose(x_new));
}
/** PLICP terminates in a finite number of steps! */
if(params->use_point_to_line_distance) {
int loop_detected = 0; /* TODO: make function */
int a; for(a=iteration-1;a>=0;a--) {
if(hashes[a]==hashes[iteration]) {
sm_debug("icpc: oscillation detected (cycle length = %d)\n", iteration-a);
loop_detected = 1;
break;
}
}
if(loop_detected) {
egsl_pop_named("icp_loop iteration");
break;
}
}
/* This termination criterium is useless when using
the point-to-line-distance; however, we put it here because
one can choose to use the point-to-point distance. */
if(termination_criterion(params, delta)) {
egsl_pop_named("icp_loop iteration");
break;
}
copy_d(x_new, 3, x_old);
copy_d(delta, 3, delta_old);
egsl_pop_named("icp_loop iteration");
}
if(JJ) jj_loop_exit();
*iterations = iteration+1;
return all_is_okay;
}
int termination_criterion(struct sm_params*params, const double*delta){
double a = norm_d(delta);
double b = fabs(delta[2]);
return (a<params->epsilon_xy) && (b<params->epsilon_theta);
}
int compute_next_estimate(struct sm_params*params,
const double x_old[3], double x_new[3])
{
LDP laser_ref = params->laser_ref;
LDP laser_sens = params->laser_sens;
struct gpc_corr c[laser_sens->nrays];
int i; int k=0;
for(i=0;i<laser_sens->nrays;i++) {
if(!laser_sens->valid[i])
continue;
if(!ld_valid_corr(laser_sens,i))
continue;
int j1 = laser_sens->corr[i].j1;
int j2 = laser_sens->corr[i].j2;
c[k].valid = 1;
if(laser_sens->corr[i].type == corr_pl) {
c[k].p[0] = laser_sens->points[i].p[0];
c[k].p[1] = laser_sens->points[i].p[1];
c[k].q[0] = laser_ref->points[j1].p[0];
c[k].q[1] = laser_ref->points[j1].p[1];
/** TODO: here we could use the estimated alpha */
double diff[2];
diff[0] = laser_ref->points[j1].p[0]-laser_ref->points[j2].p[0];
diff[1] = laser_ref->points[j1].p[1]-laser_ref->points[j2].p[1];
double one_on_norm = 1 / sqrt(diff[0]*diff[0]+diff[1]*diff[1]);
double normal[2];
normal[0] = +diff[1] * one_on_norm;
normal[1] = -diff[0] * one_on_norm;
double cos_alpha = normal[0];
double sin_alpha = normal[1];
c[k].C[0][0] = cos_alpha*cos_alpha;
c[k].C[1][0] =
c[k].C[0][1] = cos_alpha*sin_alpha;
c[k].C[1][1] = sin_alpha*sin_alpha;
/* sm_debug("k=%d, i=%d sens_phi: %fdeg, j1=%d j2=%d, alpha_seg=%f, cos=%f sin=%f \n", k,i,
rad2deg(laser_sens->theta[i]), j1,j2, atan2(sin_alpha,cos_alpha), cos_alpha,sin_alpha);*/
#if 0
/* Note: it seems that because of numerical errors this matrix might be
not semidef positive. */
double det = c[k].C[0][0] * c[k].C[1][1] - c[k].C[0][1] * c[k].C[1][0];
double trace = c[k].C[0][0] + c[k].C[1][1];
int semidef = (det >= 0) && (trace>0);
if(!semidef) {
/* printf("%d: Adjusting correspondence weights\n",i);*/
double eps = -det;
c[k].C[0][0] += 2*sqrt(eps);
c[k].C[1][1] += 2*sqrt(eps);
}
#endif
} else {
c[k].p[0] = laser_sens->points[i].p[0];
c[k].p[1] = laser_sens->points[i].p[1];
projection_on_segment_d(
laser_ref->points[j1].p,
laser_ref->points[j2].p,
laser_sens->points_w[i].p,
c[k].q);
/* Identity matrix */
c[k].C[0][0] = 1;
c[k].C[1][0] = 0;
c[k].C[0][1] = 0;
c[k].C[1][1] = 1;
}
double factor = 1;
/* Scale the correspondence weight by a factor concerning the
information in this reading. */
if(params->use_ml_weights) {
int have_alpha = 0;
double alpha = 0;
if(!is_nan(laser_ref->true_alpha[j1])) {
alpha = laser_ref->true_alpha[j1];
have_alpha = 1;
} else if(laser_ref->alpha_valid[j1]) {
alpha = laser_ref->alpha[j1];;
have_alpha = 1;
} else have_alpha = 0;
if(have_alpha) {
double pose_theta = x_old[2];
/** Incidence of the ray
Note that alpha is relative to the first scan (not the world)
and that pose_theta is the angle of the second scan with
respect to the first, hence it's ok. */
double beta = alpha - (pose_theta + laser_sens->theta[i]);
factor = 1 / square(cos(beta));
} else {
static int warned_before = 0;
if(!warned_before) {
sm_error("Param use_ml_weights was active, but not valid alpha[] or true_alpha[]."
"Perhaps, if this is a single ray not having alpha, you should mark it as inactive.\n");
sm_error("Writing laser_ref: \n");
ld_write_as_json(laser_ref, stderr);
warned_before = 1;
}
}
}
/* Weight the points by the sigma in laser_sens */
if(params->use_sigma_weights) {
if(!is_nan(laser_sens->readings_sigma[i])) {
factor *= 1 / square(laser_sens->readings_sigma[i]);
} else {
static int warned_before = 0;
if(!warned_before) {
sm_error("Param use_sigma_weights was active, but the field readings_sigma[] was not filled in.\n");
sm_error("Writing laser_sens: \n");
ld_write_as_json(laser_sens, stderr);
}
}
}
c[k].C[0][0] *= factor;
c[k].C[1][0] *= factor;
c[k].C[0][1] *= factor;
c[k].C[1][1] *= factor;
k++;
}
/* TODO: use prior for odometry */
double std = 0.11;
const double inv_cov_x0[9] =
{1/(std*std), 0, 0,
0, 1/(std*std), 0,
0, 0, 0};
int ok = gpc_solve(k, c, 0, inv_cov_x0, x_new);
if(!ok) {
sm_error("gpc_solve_valid failed\n");
return 0;
}
double old_error = gpc_total_error(c, k, x_old);
double new_error = gpc_total_error(c, k, x_new);
sm_debug("\tcompute_next_estimate: old error: %f x_old= %s \n", old_error, friendly_pose(x_old));
sm_debug("\tcompute_next_estimate: new error: %f x_new= %s \n", new_error, friendly_pose(x_new));
sm_debug("\tcompute_next_estimate: new error - old_error: %g \n", new_error-old_error);
double epsilon = 0.000001;
if(new_error > old_error + epsilon) {
sm_error("\tcompute_next_estimate: something's fishy here! Old error: %lf new error: %lf x_old %lf %lf %lf x_new %lf %lf %lf\n",old_error,new_error,x_old[0],x_old[1],x_old[2],x_new[0],x_new[1],x_new[2]);
}
return 1;
}
| {
"alphanum_fraction": 0.6490652347,
"avg_line_length": 29.6637168142,
"ext": "c",
"hexsha": "f64d17a9a321c76e90c47f6494f68967bd10161a",
"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": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alecone/ROS_project",
"max_forks_repo_path": "src/csm/sm/csm/icp/icp_loop.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"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": "alecone/ROS_project",
"max_issues_repo_path": "src/csm/sm/csm/icp/icp_loop.c",
"max_line_length": 245,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alecone/ROS_project",
"max_stars_repo_path": "src/csm/sm/csm/icp/icp_loop.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3303,
"size": 10056
} |
/******************************************************************************
CosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics
https://github.com/CosmoLike/CosmoCov
by CosmoLike developers
******************************************************************************/
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <time.h>
#include <stdio.h>
void cov_G_cl_cl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, double **cov_g_interp);
void cov_NG_cl_cl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, double **cov_ng_interp);
void cov_G_cl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int zl, int zs, double **cov_g_interp);
void cov_NG_cl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int zl, int zs, double **cov_ng_interp);
void cov_G_cl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm, double **cov_g_interp);
void cov_NG_cl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm, double **cov_ng_interp);
void cov_G_gl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl1, int zs1, int zl2, int zs2, double **cov_g_interp);
void cov_NG_gl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl1, int zs1, int zl2, int zs2, double **cov_ng_interp);
void cov_G_gl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl, int zs, int z3, int z4, int pm, double **cov_g_interp);
void cov_NG_gl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl, int zs, int z3, int z4, int pm, double **cov_ng_interp);
void cov_G_shear_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm1, int pm2, double **cov_g_interp);
void cov_NG_shear_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm1, int pm2, double **cov_ng_interp);
void cov_G_real_fft_bin_template(double *theta, int Ntheta, double **cov_g_interp, config my_config, double *N, int *array, double *task_type);
void cov_NG_real_fft_bin_template(double *theta, int Ntheta, double **cov_ng_interp, config my_config, int *array, double *task_type);
double func_for_cov_G_shear(double l, int *ar);
double func_for_cov_NG_shear(double l1, double l2, int *ar);
double func_for_cov_G_cl(double l, int *ar);
double func_for_cov_NG_cl(double l1, double l2, int *ar);
double func_for_cov_G_cl_gl(double l, int *ar);
double func_for_cov_NG_cl_gl(double l1, double l2, int *ar);
double func_for_cov_G_cl_shear(double l, int *ar);
double func_for_cov_NG_cl_shear(double l1, double l2, int *ar);
double func_for_cov_G_gl(double l, int *ar);
double func_for_cov_NG_gl(double l1, double l2, int *ar);
double func_for_cov_G_gl_shear(double l, int *ar);
double func_for_cov_NG_gl_shear(double l1, double l2, int *ar);
void cov_G_shear_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm1, int pm2, double **cov_g_interp) {
// pure noise term
double N[Ntheta],res = 0.;
int array[5];
array[1] = z1; array[2] = z2; array[3] = z3; array[4] = z4;
int i,j;
for(i=0;i<Ntheta;i++) {N[i] = 0.;}
if (z1 ==z3 && z2 ==z4 && pm1 == pm2){ //&& pm1 == pm2 required as C+- doesn't have the diagonal shot noise term
for(i=0;i<Ntheta;i++) {
N[i] += pow(survey.sigma_e,4.0)/(M_PI*(theta[i+1]*theta[i+1]-theta[i]*theta[i])*4.*nsource(z1)*nsource(z2)*pow(survey.n_gal_conversion_factor,2.0)*survey.area*survey.area_conversion_factor);
} //(number of galaxy pairs in the survey contributing to annulus of width Dtheta centered at theta1)^-1
}
if (z1 ==z4 && z2 ==z3 && pm1 == pm2){ //&& pm1 == pm2 required as C+- doesn't have the diagonal shot noise term
for(i=0;i<Ntheta;i++) {
N[i] += pow(survey.sigma_e,4.0)/(M_PI*(theta[i+1]*theta[i+1]-theta[i]*theta[i])*4.*nsource(z1)*nsource(z2)*pow(survey.n_gal_conversion_factor,2.0)*survey.area*survey.area_conversion_factor);
}
}
for(i=0;i<Ntheta;i++) {
if(N[i]) {N[i]/= w_mask(theta[i]); printf("N[i]: %lg\n", N[i]);}
}
// get big cov_G matrix
config my_config;
if (pm1 == 1){my_config.l1 = -0.5;}
else{my_config.l1 = 3.5;}
if (pm2 == 1){my_config.l2 = -0.5;}
else{my_config.l2 = 3.5;}
// my_config.nu1 = 1.01-my_config.l1/2.;
// my_config.nu2 = 1.01-my_config.l2/2.;
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {2,2};
cov_G_real_fft_bin_template(theta, Ntheta, cov_g_interp, my_config, N, array, task_type);
}
void cov_NG_shear_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm1, int pm2, double **cov_ng_interp) {
int array[5];
array[1] = z1; array[2] = z2; array[3] = z3; array[4] = z4;
int i,j;
// get big cov_NG matrix
config my_config;
if (pm1 == 1){my_config.l1 = -0.5;}
else{my_config.l1 = 3.5;}
if (pm2 == 1){my_config.l2 = -0.5;}
else{my_config.l2 = 3.5;}
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {2,2};
cov_NG_real_fft_bin_template(theta, Ntheta, cov_ng_interp, my_config, array, task_type);
}
void cov_G_cl_cl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, double **cov_g_interp) {
// pure noise term
double N[Ntheta],res = 0.;
int array[5];
array[1] = z1; array[2] = z2; array[3] = z3; array[4] = z4;
int i,j;
for(i=0;i<Ntheta;i++) {N[i] = 0.;}
if (z1 ==z3 && z2 ==z4){
for(i=0;i<Ntheta;i++) {
N[i] += 1./(M_PI*(theta[i+1]*theta[i+1]-theta[i]*theta[i])*nlens(z1)*nlens(z2)*pow(survey.n_gal_conversion_factor,2.0)*survey.area*survey.area_conversion_factor); //(number of galaxy pairs in the survey contributing to annulus of width Dtheta centered at theta1)^-1
}
}
if (z1 ==z4 && z2 ==z3){
for(i=0;i<Ntheta;i++) {
N[i] += 1./(M_PI*(theta[i+1]*theta[i+1]-theta[i]*theta[i])*nlens(z1)*nlens(z2)*pow(survey.n_gal_conversion_factor,2.0)*survey.area*survey.area_conversion_factor);
}
}
for(i=0;i<Ntheta;i++) {
if(N[i]) N[i]/= w_mask(theta[i]);
}
// get big cov_G matrix
config my_config;
my_config.l1 = -0.5;
my_config.l2 = -0.5;
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {0,0};
cov_G_real_fft_bin_template(theta, Ntheta, cov_g_interp, my_config, N, array, task_type);
}
void cov_NG_cl_cl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, double **cov_ng_interp) {
int array[5];
array[1] = z1; array[2] = z2; array[3] = z3; array[4] = z4;
int i,j;
// get big cov_NG matrix
config my_config;
my_config.l1 = -0.5;
my_config.l2 = -0.5;
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {0,0};
cov_NG_real_fft_bin_template(theta, Ntheta, cov_ng_interp, my_config, array, task_type);
}
void cov_G_cl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int zl, int zs, double **cov_g_interp) {
double N[Ntheta],res = 0.;
int array[5];
array[1] = z1; array[2] = z2; array[3] = zl; array[4] = zs;
int i,j;
// get big cov_G matrix
config my_config;
my_config.l1 = -0.5;
my_config.l2 = 1.5;
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {0,1};
cov_G_real_fft_bin_template(theta, Ntheta, cov_g_interp, my_config, N, array, task_type);
}
void cov_NG_cl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int zl, int zs, double **cov_ng_interp) {
int array[5];
array[1] = z1; array[2] = z2; array[3] = zl; array[4] = zs;
int i,j;
// get big cov_NG matrix
config my_config;
my_config.l1 = -0.5;
my_config.l2 = 1.5;
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {0,1};
cov_NG_real_fft_bin_template(theta, Ntheta, cov_ng_interp, my_config, array, task_type);
}
void cov_G_cl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm, double **cov_g_interp) {
double N[Ntheta],res = 0.;
int array[5];
array[1] = z1; array[2] = z2; array[3] = z3; array[4] = z4;
int i,j;
// get big cov_G matrix
config my_config;
my_config.l1 = -0.5;
if (pm == 1){my_config.l2 = -0.5;}
else{my_config.l2 = 3.5;}
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {0,2};
cov_G_real_fft_bin_template(theta, Ntheta, cov_g_interp, my_config, N, array, task_type);
}
void cov_NG_cl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int z1, int z2, int z3, int z4, int pm, double **cov_ng_interp) {
int array[5];
array[1] = z1; array[2] = z2; array[3] = z3; array[4] = z4;
int i,j;
// get big cov_NG matrix
config my_config;
my_config.l1 = -0.5;
if (pm == 1){my_config.l2 = -0.5;}
else{my_config.l2 = 3.5;}
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {0,2};
cov_NG_real_fft_bin_template(theta, Ntheta, cov_ng_interp, my_config, array, task_type);
}
void cov_G_gl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl1, int zs1, int zl2, int zs2, double **cov_g_interp) {
// pure noise term
double N[Ntheta],res = 0.;
int array[5];
array[1] = zl1; array[2] = zs1; array[3] = zl2; array[4] = zs2;
int i,j;
for(i=0;i<Ntheta;i++) {N[i] = 0.;}
if (zl1 ==zl2 && zs1 ==zs2){
for(i=0;i<Ntheta;i++) {
N[i] += pow(survey.sigma_e,2.0)/(2.0*M_PI*(theta[i+1]*theta[i+1]-theta[i]*theta[i])*nlens(zl1)*nsource(zs2)*pow(survey.n_gal_conversion_factor,2.0)*survey.area*survey.area_conversion_factor);
if(N[i]) N[i]/= w_mask(theta[i]);
}
}
// get big cov_G matrix
config my_config;
my_config.l1 = 1.5;
my_config.l2 = 1.5;
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {1,1};
cov_G_real_fft_bin_template(theta, Ntheta, cov_g_interp, my_config, N, array, task_type);
}
void cov_NG_gl_gl_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl1, int zs1, int zl2, int zs2, double **cov_ng_interp) {
int array[5];
array[1] = zl1; array[2] = zs1; array[3] = zl2; array[4] = zs2;
int i,j;
// get big cov_NG matrix
config my_config;
my_config.l1 = 1.5;
my_config.l2 = 1.5;
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {1,1};
cov_NG_real_fft_bin_template(theta, Ntheta, cov_ng_interp, my_config, array, task_type);
}
void cov_G_gl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl, int zs, int z3, int z4, int pm, double **cov_g_interp) {
double N[Ntheta],res = 0.;
int array[5];
array[1] = zl; array[2] = zs; array[3] = z3; array[4] = z4;
int i,j;
// get big cov_G matrix
config my_config;
my_config.l1 = 1.5;
if (pm == 1){my_config.l2 = -0.5;}
else{my_config.l2 = 3.5;}
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {1,2};
cov_G_real_fft_bin_template(theta, Ntheta, cov_g_interp, my_config, N, array, task_type);
}
void cov_NG_gl_shear_real_fft_binned(double *theta, int Ntheta, double *dtheta, int zl, int zs, int z3, int z4, int pm, double **cov_ng_interp) {
int array[5];
array[1] = zl; array[2] = zs; array[3] = z3; array[4] = z4;
int i,j;
// get big cov_NG matrix
config my_config;
my_config.l1 = 1.5;
if (pm == 1){my_config.l2 = -0.5;}
else{my_config.l2 = 3.5;}
my_config.nu1 = 1.01;
my_config.nu2 = 1.01;
double task_type[] = {1,2};
cov_NG_real_fft_bin_template(theta, Ntheta, cov_ng_interp, my_config, array, task_type);
}
/*********** Templates *************************************/
void cov_G_real_fft_bin_template(double *theta, int Ntheta, double **cov_g_interp, config my_config, double *N, int *array, double *task_type) {
my_config.sym_Flag = 0;
my_config.c_window_width = 0.25;
double res = 0.;
int i,j;
// get input func log-sampled in ell
const int Nsub = 20; // split each (theta[i],theta[i+1]) range into Nsub sub-ranges, i.e. fill in (Nsub-1) sampling points within the range
// clock_t start_t, end_t;
// start_t = clock();
double ellmax = 50000.;
double ell_first = 1./theta[Ntheta]; // include the last bin edge
double ell_last = 1./theta[0];
double dlnell = log(theta[1]/theta[0])/Nsub;
int ind_first = floor(log(ell_first)/dlnell); // index of ell_first in log-sampled array (from range [1,ellmax]) containing our orginal desired array (1/theta)
int Nell = floor(log(ellmax/ell_first)/dlnell) + ind_first + 1; // total sampling points in range [1,ellmax]
double ell[Nell], func[Nell];
// printf("ell_first:%lg\n", ell_first);
// printf("Nell:%d\n", Nell);
// end_t = clock();
// printf("Total time taken by CPU: %f\n", (double)(end_t - start_t) / CLOCKS_PER_SEC );
double noise_factor = 0.;
double (*func_for_cov_G)(double, int*);
if(task_type[0]==0) {
if(task_type[1]==0) {func_for_cov_G = &func_for_cov_G_cl; noise_factor=1.;}
else if(task_type[1]==1) {func_for_cov_G = &func_for_cov_G_cl_gl;}
else if(task_type[1]==2) {func_for_cov_G = &func_for_cov_G_cl_shear;}
}
else if(task_type[0]==1) {
if(task_type[1]==1) {func_for_cov_G = &func_for_cov_G_gl; noise_factor=1.;}
else if(task_type[1]==2) {func_for_cov_G = &func_for_cov_G_gl_shear;}
}
else {
if(task_type[1]==2) {func_for_cov_G = &func_for_cov_G_shear; noise_factor=2.;}
}
for(i=0; i<Nell; i++) {
ell[i] = exp(dlnell * (i-ind_first)) * ell_first;
func[i] = func_for_cov_G(ell[i], array);
}
// end_t = clock();
// printf("Total time taken by CPU: %f\n", (double)(end_t - start_t) / CLOCKS_PER_SEC );
// extrapolate
// const int N_extra = 800-246;
const int N_extra = 800;
int Ntot = N_extra*2+Nell;
double large_ell[Ntot], large_fl[Ntot];
extrap_log_linear_cfastcov(ell, Nell, N_extra, large_ell);
extrap_log_linear_cfastcov(func, Nell, N_extra, large_fl);
double **fk1k2;
fk1k2 = malloc(Ntot*sizeof(double *));
for(i=0;i<Ntot;i++) {
fk1k2[i] = malloc(Ntot*sizeof(double));
}
mk_diag_g_to_ng(large_fl, Ntot, dlnell, fk1k2);
// end_t = clock();
// printf("Total time taken by CPU: %f\n", (double)(end_t - start_t) / CLOCKS_PER_SEC );
// do integration
double theta_fine[Ntot];
double **result;
result = malloc(Ntot*sizeof(double *));
for(i=0;i<Ntot;i++) {
result[i] = malloc(Ntot*sizeof(double));
}
// twobessel(large_ell, large_ell, fk1k2, Ntot, Ntot, &my_config, theta_fine, theta_fine, result);
double smooth_dlnr = dlnell*Nsub;
printf("Ntot,%d\n",Ntot);
twobessel_binave(large_ell, large_ell, fk1k2, Ntot, Ntot, &my_config, smooth_dlnr, 2.5, theta_fine, theta_fine, result);
// printf("Ntot,%d\n",Ntot);
// end_t = clock();
// printf("Total time taken by CPU: %f\n", (double)(end_t - start_t) / CLOCKS_PER_SEC );
int ind_theta_first = Ntot - 1 - N_extra-ind_first - Nsub*(Ntheta); // different from nobin case because ind_first is set different!
for(i=0; i<Ntheta; i++) {
for(j=0; j<Ntheta; j++) {
cov_g_interp[i][j] = result[ind_theta_first+i*Nsub][ind_theta_first+j*Nsub];
cov_g_interp[i][j] /= ( (theta[i+1]*theta[i+1]-theta[i]*theta[i])*(theta[j+1]*theta[j+1]-theta[j]*theta[j]) *M_PI*M_PI*M_PI*survey.area/41253.);
}
// printf("theta[%d]=%lg, cov_g_interp[%d][%d]: %lg\n",i, theta[i], i,i, cov_g_interp[i][i]);
cov_g_interp[i][i] += noise_factor * N[i];
}
// end_t = clock();
// printf("Total time taken by CPU: %f\n", (double)(end_t - start_t) / CLOCKS_PER_SEC );
free(result);free(fk1k2);
}
void cov_NG_real_fft_bin_template(double *theta, int Ntheta, double **cov_ng_interp, config my_config, int *array, double *task_type) {
int i,j;
my_config.sym_Flag = 0;
my_config.c_window_width = 0.25;
// get input func log-sampled in ell
const int Nsub = 20; // split each (theta[i],theta[i+1]) range into Nsub sub-ranges, i.e. fill in (Nsub-1) sampling points within the range
// clock_t start_t, end_t;
// start_t = clock();
double ellmax = 50000.;
double ell_first = 1./theta[Ntheta]; // include the last bin edge
double ell_last = 1./theta[0];
double dlnell = log(theta[1]/theta[0])/Nsub;
int ind_first = floor(log(ell_first)/dlnell); // index of ell_first in log-sampled array (from range [1,ellmax]) containing our orginal desired array (1/theta)
int Nell = floor(log(ellmax/ell_first)/dlnell) + ind_first + 1; // total sampling points in range [1,ellmax]
double ell[Nell];
// printf("ell_first:%lg\n", ell_first);
// printf("Nell:%d\n", Nell);
for(i=0; i<Nell; i++) {
ell[i] = exp(dlnell * (i-ind_first)) * ell_first;
}
double (*func_for_cov_NG)(double, double, int*);
if(task_type[0]==0) {
if(task_type[1]==0) {func_for_cov_NG = &func_for_cov_NG_cl;}
else if(task_type[1]==1) {func_for_cov_NG = &func_for_cov_NG_cl_gl;}
else if(task_type[1]==2) {func_for_cov_NG = &func_for_cov_NG_cl_shear;}
}
else if(task_type[0]==1) {
if(task_type[1]==1) {func_for_cov_NG = &func_for_cov_NG_gl;}
else if(task_type[1]==2) {func_for_cov_NG = &func_for_cov_NG_gl_shear;}
}
else {
if(task_type[1]==2) {func_for_cov_NG = &func_for_cov_NG_shear;}
}
double **func;
func = malloc(Nell*sizeof(double *));
for(i=0; i<Nell; i++) {
func[i] = malloc(Nell * sizeof(double));
for(j=0; j<Nell; j++) {
func[i][j] = func_for_cov_NG(ell[i], ell[j], array);
}
}
// FILE * output = fopen("func_ng.txt", "w");
// for(i=0;i<Nell;i++){
// for(j=0;j<Nell;j++){
// fprintf(output, "%lg ", func[i][j]);
// }
// fprintf(output, "\n");
// }
// fclose(output);
// exit(0);
// extrapolate
const int N_extra = 800;
int Ntot = N_extra*2+Nell;
double large_ell[Ntot];
double **fk1k2;
fk1k2 = malloc(Ntot*sizeof(double *));
for(i=0;i<Ntot;i++) {
fk1k2[i] = malloc(Ntot*sizeof(double));
}
extrap_log_linear_cfastcov(ell, Nell, N_extra, large_ell);
extrap_2dzeros(func, Nell, N_extra, fk1k2);
// do integration
double theta_fine[Ntot];
double **result;
result = malloc(Ntot*sizeof(double *));
for(i=0;i<Ntot;i++) {
result[i] = malloc(Ntot*sizeof(double));
}
// twobessel(large_ell, large_ell, fk1k2, Ntot, Ntot, &my_config, theta_fine, theta_fine, result);
double smooth_dlnr = dlnell*Nsub;
twobessel_binave(large_ell, large_ell, fk1k2, Ntot, Ntot, &my_config, smooth_dlnr, 2.5, theta_fine, theta_fine, result);
printf("Ntot,%d\n",Ntot);
int ind_theta_first = Ntot - 1 - N_extra-ind_first - Nsub*(Ntheta); // different from nobin case because ind_first is set different!
for(i=0; i<Ntheta; i++) {
for(j=0; j<Ntheta; j++) {
cov_ng_interp[i][j] = result[ind_theta_first+i*Nsub][ind_theta_first+j*Nsub];
cov_ng_interp[i][j] /= ( (theta[i+1]*theta[i+1]-theta[i]*theta[i])*(theta[j+1]*theta[j+1]-theta[j]*theta[j]) /2. *M_PI*M_PI*M_PI);
}
}
free(result);free(fk1k2);free(func);
}
/********** Functions for differnt covariances ***************************************/
double func_for_cov_G_shear(double l, int *ar){
double C13, C14, C23, C24, N13=0.0, N14=0.0, N23=0.0, N24=0.0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
//printf("n1=%d n2=%d n3=%d n4=%d l=%le\n",n1,n2,n3,n4,l);
C13 = C_shear_shear_IA_tab(l,n1,n3);
C24 = C_shear_shear_IA_tab(l,n2,n4);
C14 = C_shear_shear_IA_tab(l,n1,n4);
C23 = C_shear_shear_IA_tab(l,n2,n3);
if (n1 == n3){N13= pow(survey.sigma_e,2.0)/(2.*nsource(n1)*survey.n_gal_conversion_factor);}
if (n1 == n4){N14= pow(survey.sigma_e,2.0)/(2.*nsource(n1)*survey.n_gal_conversion_factor);}
if (n2 == n3){N23= pow(survey.sigma_e,2.0)/(2.*nsource(n2)*survey.n_gal_conversion_factor);}
if (n2 == n4){N24= pow(survey.sigma_e,2.0)/(2.*nsource(n2)*survey.n_gal_conversion_factor);}
return (C13*C24+C13*N24+N13*C24 + C14*C23+C14*N23+N14*C23)*l*l*l;
}
double func_for_cov_NG_shear(double l1, double l2, int *ar){
double tri = 0.,res =0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
tri= bin_cov_NG_shear_shear_tomo(l1,l2,n1,n2,n3,n4);
// if(isnan(tri)) {tri=0.;}
return tri * pow(l1, 2.5) * pow(l2, 2.5);
}
double func_for_cov_G_cl(double l, int *ar){
double C13, C14, C23, C24, N13=0.0, N14=0.0, N23=0.0, N24=0.0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
//printf("n1=%d n2=%d n3=%d n4=%d l=%le\n",n1,n2,n3,n4,l);
C13 = C_cl_tomo(l,n1,n3);
C24 = C_cl_tomo(l,n2,n4);
C14 = C_cl_tomo(l,n1,n4);
C23 = C_cl_tomo(l,n2,n3);
N13= tomo.n_lens_ij[n1][n3]/(nlens(n1)*nlens(n3)*survey.n_gal_conversion_factor);
N14= tomo.n_lens_ij[n1][n4]/(nlens(n1)*nlens(n4)*survey.n_gal_conversion_factor);
N23= tomo.n_lens_ij[n2][n3]/(nlens(n2)*nlens(n3)*survey.n_gal_conversion_factor);
N24= tomo.n_lens_ij[n2][n4]/(nlens(n2)*nlens(n4)*survey.n_gal_conversion_factor);
return (C13*C24+C13*N24+N13*C24 + C14*C23+C14*N23+N14*C23)*l*l*l;
}
double func_for_cov_NG_cl(double l1, double l2, int *ar){
double tri = 0.,res =0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
tri= bin_cov_NG_cl_cl_tomo(l1,l2,n1,n2,n3,n4);
// if(isnan(tri)) {tri=0.;}
return tri * pow(l1, 2.5) * pow(l2, 2.5);
}
double func_for_cov_G_cl_gl(double l, int *ar){
double C13, C14, C23, C24, N13=0.0, N14=0.0, N23=0.0, N24=0.0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
//printf("n1=%d n2=%d n3=%d n4=%d l=%le\n",n1,n2,n3,n4,l);
C13 = C_cl_tomo(l,n1,n3);
C24 = C_ggl_IA_tab(l,n2,n4);
C14 = C_ggl_IA_tab(l,n1,n4);
C23 = C_cl_tomo(l,n2,n3);
N13= tomo.n_lens_ij[n1][n3]/(nlens(n1)*nlens(n3)*survey.n_gal_conversion_factor);
N23= tomo.n_lens_ij[n2][n3]/(nlens(n2)*nlens(n3)*survey.n_gal_conversion_factor);
//printf("%lg, %lg, %lg, %lg, %lg, %lg, %lg\n", l, C13, C24, C14, C23, N13, N23);
return (C13*C24+C13*N24+C24*N13+C14*C23+C14*N23+C23*N14)*l*l*l;
}
double func_for_cov_NG_cl_gl(double l1, double l2, int *ar){
double tri = 0.,res =0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
tri= bin_cov_NG_cl_gl_tomo(l1,l2,n1,n2,n3,n4);
// if(isnan(tri)) {tri=0.;}
return tri * pow(l1, 2.5) * pow(l2, 2.5);
}
double func_for_cov_G_cl_shear(double l, int *ar){
double C13, C14, C23, C24, N13=0.0, N14=0.0, N23=0.0, N24=0.0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
//printf("n1=%d n2=%d n3=%d n4=%d l=%le\n",n1,n2,n3,n4,l);
C13 = C_ggl_IA_tab(l,n1,n3);
C24 = C_ggl_IA_tab(l,n2,n4);
C14 = C_ggl_IA_tab(l,n1,n4);
C23 = C_ggl_IA_tab(l,n2,n3);
return (C13*C24+ C14*C23)*l*l*l;
}
double func_for_cov_NG_cl_shear(double l1, double l2, int *ar){
double tri = 0.,res =0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
tri= bin_cov_NG_cl_shear_tomo(l1,l2,n1,n2,n3,n4);
// if(isnan(tri)) {tri=0.;}
return tri * pow(l1, 2.5) * pow(l2, 2.5);
}
double func_for_cov_G_gl(double l, int *ar){
double C13, C14, C23, C24, N13=0.0, N14=0.0, N23=0.0, N24=0.0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
//printf("n1=%d n2=%d n3=%d n4=%d l=%le\n",n1,n2,n3,n4,l);
C13 = C_cl_tomo(l,n1,n3);
C24 = C_shear_shear_IA_tab(l,n2,n4);
C14 = C_ggl_IA_tab(l,n1,n4);
C23 = C_ggl_IA_tab(l,n3,n2);
N13= tomo.n_lens_ij[n1][n3]/(nlens(n1)*nlens(n3)*survey.n_gal_conversion_factor);
if (n2 == n4){N24= pow(survey.sigma_e,2.0)/(2.0*nsource(n2)*survey.n_gal_conversion_factor);}
// printf("%lg, %lg, %lg, %lg, %lg, %lg, %lg\n", l, C13, C24, C14, C23, N13, N24);
return (C13*C24+C13*N24+N13*C24 + C14*C23+C14*N23+N14*C23)*l*l*l;
}
double func_for_cov_NG_gl(double l1, double l2, int *ar){
double tri = 0.,res =0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
tri= bin_cov_NG_gl_gl_tomo(l1,l2,n1,n2,n3,n4);
// if(isnan(tri)) {tri=0.;}
return tri * pow(l1, 2.5) * pow(l2, 2.5);
}
double func_for_cov_G_gl_shear(double l, int *ar){
double C13, C14, C23, C24, N13=0.0, N14=0.0, N23=0.0, N24=0.0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
//printf("n1=%d n2=%d n3=%d n4=%d l=%le\n",n1,n2,n3,n4,l);
C13 = C_ggl_IA_tab(l,n1,n3);
C24 = C_shear_shear_IA_tab(l,n2,n4);
C14 = C_ggl_IA_tab(l,n1,n4);
C23 = C_shear_shear_IA_tab(l,n2,n3);
if (n2 == n4){N24= pow(survey.sigma_e,2.0)/(2.0*nsource(n2)*survey.n_gal_conversion_factor);}
if (n2 == n3){N23= pow(survey.sigma_e,2.0)/(2.0*nsource(n2)*survey.n_gal_conversion_factor);}
return (C13*C24+C13*N24+N13*C24 + C14*C23+C14*N23+N14*C23)*l*l*l;
}
double func_for_cov_NG_gl_shear(double l1, double l2, int *ar){
double tri = 0.,res =0;
int n1,n2,n3,n4;
n1 = ar[1]; n2 = ar[2]; n3 = ar[3]; n4 = ar[4];
tri= bin_cov_NG_gl_shear_tomo(l1,l2,n1,n2,n3,n4);
// if(isnan(tri)) {tri=0.;}
return tri * pow(l1, 2.5) * pow(l2, 2.5);
}
| {
"alphanum_fraction": 0.6512849296,
"avg_line_length": 36.8434268833,
"ext": "c",
"hexsha": "09d728e80952ca088e238b68c81fdad0455f68b4",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-01-27T11:30:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-04-21T20:17:05.000Z",
"max_forks_repo_head_hexsha": "afa02abe76ad1e7b0fc17f43d7f271cb466948c1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "robinupham/CosmoCov_ClCov",
"max_forks_repo_path": "CosmoCov/cosmolike_core/theory/covariances_real_bin_fft.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "afa02abe76ad1e7b0fc17f43d7f271cb466948c1",
"max_issues_repo_issues_event_max_datetime": "2021-06-29T16:27:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-12T19:43:54.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "robinupham/CosmoCov_ClCov",
"max_issues_repo_path": "CosmoCov/cosmolike_core/theory/covariances_real_bin_fft.c",
"max_line_length": 271,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "afa02abe76ad1e7b0fc17f43d7f271cb466948c1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "robinupham/CosmoCov_ClCov",
"max_stars_repo_path": "CosmoCov/cosmolike_core/theory/covariances_real_bin_fft.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-31T10:39:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-14T00:46:09.000Z",
"num_tokens": 9422,
"size": 24943
} |
#ifndef _SEARCHBEST_
#define _SEARCHBEST_
#include <assert.h>
#include <cmath>
#include <float.h>
#include <climits>
// use openblas
#include <cblas.h>
#include "cosine_similarity.h"
// Step 1, g++ main.cpp search_best.cpp cosine_similarity.cpp -std=c++11
// Step 2, g++ main.cpp search_best.cpp cosine_similarity.cpp -std=c++11 -O3
// Step 3, g++ main.cpp search_best.cpp cosine_similarity.cpp -std=c++11 -O3 -Ofast -ffast-math
template <typename T>
int SearchBest(const T* __restrict__ const pVecA, // 待搜索的单个特征向量首地址
const int lenA, // 待搜索特征向量长度(1 x 单个特征维数)
const T* __restrict__ const pVecDB, // 底库首地址
const int lenDB) // 底库长度(特征个数 x 单个特征维数)
{
assert(lenDB%lenA == 0);
const int featsize = lenA;
const int facenum = lenDB / lenA;
int best_index = - INT_MAX;
T best_similarity = - FLT_MAX;
#if 0
// Step 5, 加上OpenMP
//GCC很聪明,OpenMP默认线程数就是多核处理器的核心数量,不必显示指定
//OpenMP起线程,收回线程也是有开销的,所以要合理安排每个线程的任务量大小,不宜放入内层for循环(任务量太小划不来)
//#pragma omp parallel for num_threads(8)
#pragma omp parallel for
for(int i = 0; i < facenum; i++) {
// 普通C++代码实现的余弦相似度计算
T similarity = Cosine_similarity(pVecA, pVecDB + i*featsize, featsize);
// 使用向量化代码实现的余弦相似度计算
//T similarity = Cosine_similarity_avx(pVecA, pVecDB + i*featsize, featsize);
if(similarity > best_similarity) {
best_similarity = similarity;
best_index = i;
}
}
#else
// Step 12,使用OpenBLAS
T simAll[facenum] = {0.0f};
cblas_sgemv(CblasRowMajor, CblasNoTrans, facenum, featsize, 1, pVecDB, featsize, pVecA, 1, 0, simAll, 1);
// 寻找simAll里面最大的,它的序号就是要找的id
for(int i = 0; i < facenum; i++) {
if(simAll[i] > best_similarity) {
best_similarity = simAll[i];
best_index = i;
}
}
#endif
return best_index;
}
#endif //!_SEARCHBEST_
| {
"alphanum_fraction": 0.6494405967,
"avg_line_length": 30.7704918033,
"ext": "h",
"hexsha": "c44fcfc2c76173817807e1835f75e36b3fb3c9d2",
"lang": "C",
"max_forks_count": 171,
"max_forks_repo_forks_event_max_datetime": "2022-03-23T06:37:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-30T01:36:18.000Z",
"max_forks_repo_head_hexsha": "f0f6781f55cf24d2bcb28cb65ef124505d411e27",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zhangshaokun999/CaptainBlackboard",
"max_forks_repo_path": "D#0003-optimizing_cosine_distance_searching_in_a_million_feature-set/code/search_best.h",
"max_issues_count": 125,
"max_issues_repo_head_hexsha": "f0f6781f55cf24d2bcb28cb65ef124505d411e27",
"max_issues_repo_issues_event_max_datetime": "2021-04-22T12:33:08.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-02-20T14:24:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zhangshaokun999/CaptainBlackboard",
"max_issues_repo_path": "D#0003-optimizing_cosine_distance_searching_in_a_million_feature-set/code/search_best.h",
"max_line_length": 109,
"max_stars_count": 961,
"max_stars_repo_head_hexsha": "c8ec5f1adf2301724a3a864890df6c0bcb598505",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "awesome-archive/CaptainBlackboard",
"max_stars_repo_path": "D#0003-optimizing_cosine_distance_searching_in_a_million_feature-set/code/search_best.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T01:09:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-30T01:46:26.000Z",
"num_tokens": 698,
"size": 1877
} |
#include "linearwaves.h"
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#define FREAD_CHECK(i,j) ((i) >= (j)) ? (void) 0 : printf("fread returned read fewer items than expected (%zu < %zu) at line %d in %s of %s\n",i,j,__LINE__,__func__,__FILE__)
void interpolation(double *xd, double *yd, int nd, double *x, double *y, double *dy, double *d2y, int n) {
gsl_interp_accel *acc = gsl_interp_accel_alloc ();
gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, nd);
gsl_spline_init (spline, xd, yd, nd);
int i;
for(i=0;i<n;i++) {
y[i] = gsl_spline_eval(spline,x[i],acc);
dy[i] = gsl_spline_eval_deriv(spline,x[i],acc);
d2y[i] = gsl_spline_eval_deriv2(spline,x[i],acc);
}
gsl_spline_free (spline);
gsl_interp_accel_free (acc);
return;
}
void interpolate_onto_grid(double *xd, double *yd, int ndata, double *lr, double *ynew, double *dlydlr, double *d2lydlr, int n,int add_flag) {
int i;
int jstart = 0;
int jend = n-1;
for(i=0;i<n;i++) {
if (lr[i] >= xd[0]) {
jstart = i;
break;
}
}
for(i=jstart;i<n;i++) {
if (lr[i] >= xd[ndata-1]) {
if (lr[i] == xd[ndata-1]) {
jend = i;
}
else {
jend = i-1;
}
break;
}
}
int n_interp = jend-jstart +1;
interpolation(xd,yd,ndata,&lr[jstart],&ynew[jstart],&dlydlr[jstart],&d2lydlr[jstart],n_interp);
for(i=0;i<jstart;i++) {
ynew[i] = ynew[jstart] + dlydlr[jstart]*(lr[i]-lr[jstart]);
dlydlr[i] = dlydlr[jstart];
d2lydlr[i] = 0;
}
for(i=jend+1;i<n;i++) {
ynew[i] = ynew[jend] + dlydlr[jend]*(lr[i]-lr[jend]);
dlydlr[i] = dlydlr[jend];
d2lydlr[i] = 0;
}
// Add in inner truncation and outer truncation
if (add_flag) {
double ri = exp(lr[0])*.99;
double ro = exp(lr[n-1])/2.0;
double x;
for(i=0;i<n;i++) {
x = exp(lr[i]);
ynew[i] += log(1 - sqrt(ri/x)) - pow(x/ro,2);
dlydlr[i] += .5*sqrt(ri/x)*pow(1-sqrt(ri/x),-1) - 2*pow(x/ro,2);
d2lydlr[i] += -.25*sqrt(ri/x)*pow(1-sqrt(ri/x),-2) - 4*pow(x/ro,2);
}
}
return;
}
void read_sigma(char *fname, double *lr, double *sigma, double *dlsdlr, double *d2lsdlr, double *omega, double *dlomdlr, double *d2lomdlr, int n,int readomega) {
double temp;
size_t ndata;
double *xd,*yd;
int i;
size_t fres;
FILE *f = fopen(fname,"r");
ndata = 1;
fres = fread(&temp,sizeof(double),ndata,f);
FREAD_CHECK(fres,ndata);
ndata=(size_t)temp;
xd = (double *)malloc(sizeof(double)*ndata);
yd = (double *)malloc(sizeof(double)*ndata);
fres = fread(xd,sizeof(double),ndata,f);
FREAD_CHECK(fres,ndata);
fres = fread(yd,sizeof(double),ndata,f);
FREAD_CHECK(fres,ndata);
interpolate_onto_grid(xd,yd,ndata,lr,sigma,dlsdlr,d2lsdlr,n,TRUE);
if (readomega) {
fres = fread(yd,sizeof(double),ndata,f);
FREAD_CHECK(fres,ndata);
for(i=0;i<(int)ndata;i++) {
yd[i] = log( exp(yd[i])/pow(exp(xd[i]),2));
}
interpolate_onto_grid(xd,yd,ndata,lr,omega,dlomdlr,d2lomdlr,n,FALSE);
}
fclose(f);
SAFE_FREE(xd);
SAFE_FREE(yd);
return;
}
/*
int main(void) {
double *x,*y,*dy,*d2y;
int i;
double rmin = .01;
double rmax = 10;
int n = 1000;
x = (double *)malloc(sizeof(double)*n);
y = (double *)malloc(sizeof(double)*n);
dy = (double *)malloc(sizeof(double)*n);
d2y = (double *)malloc(sizeof(double)*n);
for(i=0;i<n;i++) {
x[i] = log(rmin) + i*log(rmax/rmin)/n;
y[i] = 0;
dy[i] = 0;
d2y[i] = 0;
}
read_sigma("../profiles/avg_profs/prof_q1e-3_a1e-2.bin",x,y,dy,d2y,n);
FILE *f = fopen("interp_res.dat","w");
double temp = (double)n;
fwrite(&temp,sizeof(double),1,f);
fwrite(x,sizeof(double),n,f);
fwrite(y,sizeof(double),n,f);
fwrite(dy,sizeof(double),n,f);
fwrite(d2y,sizeof(double),n,f);
SAFE_FREE(x);
SAFE_FREE(y);
SAFE_FREE(dy);
SAFE_FREE(d2y);
}
*/
| {
"alphanum_fraction": 0.5495838288,
"avg_line_length": 26.9551282051,
"ext": "c",
"hexsha": "86a41c2ac23bd3168b9889654afd8e6aca1b1b0a",
"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": "6551cb210311962d734dcaae292534fc27ce1490",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "adamdempsey90/linearwaves",
"max_forks_repo_path": "src/interpolation.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6551cb210311962d734dcaae292534fc27ce1490",
"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": "adamdempsey90/linearwaves",
"max_issues_repo_path": "src/interpolation.c",
"max_line_length": 174,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6551cb210311962d734dcaae292534fc27ce1490",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "adamdempsey90/linearwaves",
"max_stars_repo_path": "src/interpolation.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1407,
"size": 4205
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include "CosmoCalcs.h"
int main() {
UniverseLCDM myU;
double err = 0.0;
double x, y, z;
double Wl = 0.75;
double Wm = 0.05;
double Wr = 1e-6;
double Wk = 1.0 - Wl - Wm - Wr;
InitUniverse( &myU, 70.0 * MpcPerMeter * 1e3, Wl, Wm, Wr, false, true );
/*x = Dc(0.5, &err);
printf("GSL value, unc: %.16e, %.16e\n", x, err);*/
printf("Wl = %.16e, Wm = %.16e, Wr = %.16e\n", myU.OmegaLambda, myU.OmegaMatter, myU.OmegaRelativistic );
//z = 0.484375;
z = 0.5048828125;
y = tL0_Cosmic(&myU, z, true, 1e-6, 1e-6, 128, &err);
printf("z = %f, tL0 = %.16e, z' = %.16e\n", z, y, tL0Inv_Cosmic(&myU, y, 0, 1e-9, 1024));
z = 0.5;
y = tL0_Cosmic(&myU, z, true, 1e-6, 1e-6, 128, &err);
printf("z = %f, tL0 = %.16e, z' = %.16e\n", z, y, tL0Inv_Cosmic(&myU, y, 0, 1e-9, 1024));
z = 0.75;
y = tL0_Cosmic(&myU, z, true, 1e-6, 1e-6, 128, &err);
printf("z = %f, tL0 = %.16e, z' = %.16e\n", z, y, tL0Inv_Cosmic(&myU, y, 0, 1e-9, 1024));
z = 1.0;
y = tL0_Cosmic(&myU, z, true, 1e-6, 1e-6, 128, &err);
printf("z = %f, tL0 = %.16e, z' = %.16e\n", z, y, tL0Inv_Cosmic(&myU, y, 0, 1e-9, 1024));
z = 5.0;
y = tL0_Cosmic(&myU, z, true, 1e-6, 1e-6, 128, &err);
printf("z = %f, tL0 = %.16e, z' = %.16e\n", z, y, tL0Inv_Cosmic(&myU, y, 2, 1e-9, 1024));
return 0;
}
| {
"alphanum_fraction": 0.5503355705,
"avg_line_length": 27.9375,
"ext": "c",
"hexsha": "9995d3e844fc9c0ac8bf2bdde2862f846420c4f8",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2019-11-27T09:04:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-22T05:19:03.000Z",
"max_forks_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "odysseus9672/SELPythonLibs",
"max_forks_repo_path": "CosmoCalcs/test.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e",
"max_issues_repo_issues_event_max_datetime": "2017-08-25T04:44:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-08-22T05:27:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "odysseus9672/SELPythonLibs",
"max_issues_repo_path": "CosmoCalcs/test.c",
"max_line_length": 106,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "odysseus9672/SELPythonLibs",
"max_stars_repo_path": "CosmoCalcs/test.c",
"max_stars_repo_stars_event_max_datetime": "2020-06-12T11:44:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-15T18:06:50.000Z",
"num_tokens": 701,
"size": 1341
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nlopt.h>
// System definition and dimension
int mysys = 0;
int dim = 3;
// Semi-empirical method and parameter variation range
char * method = "pm7";
double pdev = 0.7;
// Algorithm parameters
nlopt_algorithm global_alg = NLOPT_GD_MLSL_LDS;
nlopt_algorithm local_alg = NLOPT_LN_BOBYQA;
int maxeval = 3;
double minrms = 0.01;
double tol = 0.001;
//Define here your system's input for MOPAC
void gen_srpgeo(int ndat, double ** data) {
long length;
char * buffer = 0;
char procedure[0x100];
switch (mysys) {
case 0: {
// Ar/C10H8
FILE * fp = fopen("./naf_geo.xyz", "r");
if (!fp)
exit(EXIT_FAILURE);
fseek(fp, 0L, SEEK_END);
length = ftell(fp);
rewind(fp);
buffer = (char *) malloc((length+1) * sizeof(char));
if (buffer) {
fread(buffer, sizeof(char), length, fp);
}
fclose(fp);
for (int i = 0; i < ndat; ++i) {
char buf[0x100];
snprintf(buf, sizeof(buf), "./inp_semp/geo_%d.mop", i);
FILE * fq = fopen(buf, "w");
strcpy(procedure, method);
strcpy(procedure, " charge=0 1scf EXTERNAL=mopac_parameter\n");
fprintf(fq, "%s", procedure);
fprintf(fq, "Dumb title rule\n");
fprintf(fq, " \n");
fprintf(fq, "Ar %f %f %f\n", data[i][0], data[i][1], data[i][2]);
fputs(buffer, fq);
fprintf(fq, " ");
fclose(fq);
}
free(buffer);
}
default:
break;
}
}
| {
"alphanum_fraction": 0.6280400572,
"avg_line_length": 20.8656716418,
"ext": "h",
"hexsha": "8f1b0c610ac05c256ee5d15fac05277e7d32a312",
"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": "d6a0c6e898fb3b82d7f90ca92a654d101db0fc5f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Panadestein/srpt_c",
"max_forks_repo_path": "systems.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d6a0c6e898fb3b82d7f90ca92a654d101db0fc5f",
"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": "Panadestein/srpt_c",
"max_issues_repo_path": "systems.h",
"max_line_length": 68,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d6a0c6e898fb3b82d7f90ca92a654d101db0fc5f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Panadestein/srpt_c",
"max_stars_repo_path": "systems.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 466,
"size": 1398
} |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_blas.h>
int main() {
int ret;
int i, j;
gsl_vector* tau;
gsl_matrix *A;
gsl_matrix *Q, *R, *RTR;
gsl_matrix_view Rtop;
int M = 4;
int N = 3;
/*
gsl_matrix A;
double data[9];
memset(&A, 0, sizeof(gsl_matrix));
A.size1 = 3;
A.size2 = 3;
A.tda = 3;
A.data = data;
gsl_matrix_set(&A, 0, 0, 34.0);
gsl_matrix_set(&A, 0, 1, 4.0);
gsl_matrix_set(&A, 0, 2, 14.0);
gsl_matrix_set(&A, 1, 0, 1.0);
gsl_matrix_set(&A, 1, 1, 8.0);
gsl_matrix_set(&A, 1, 2, 3.0);
gsl_matrix_set(&A, 2, 0, 7.0);
gsl_matrix_set(&A, 2, 1, 1.0);
gsl_matrix_set(&A, 2, 2, 8.0);
*/
A = gsl_matrix_alloc(M, N);
for (i=0; i<M; i++)
for (j=0; j<N; j++)
gsl_matrix_set(A, i, j, (double)rand()/(double)RAND_MAX);
for (i=0; i<A->size1; i++) {
printf((i==0) ? "A = (" : " (");
for (j=0; j<A->size2; j++) {
printf(" %12.5g ", gsl_matrix_get(A, i, j));
}
printf(")\n");
}
printf("\n");
tau = gsl_vector_alloc(N);
ret = gsl_linalg_QR_decomp(A, tau);
Q = gsl_matrix_alloc(M, M);
R = gsl_matrix_alloc(M, N);
ret = gsl_linalg_QR_unpack(A, tau, Q, R);
for (i=0; i<Q->size1; i++) {
printf((i==0) ? "Q = (" : " (");
for (j=0; j<Q->size2; j++) {
printf(" %12.5g ", gsl_matrix_get(Q, i, j));
}
printf(")\n");
}
printf("\n");
for (i=0; i<R->size1; i++) {
printf((i==0) ? "R = (" : " (");
for (j=0; j<R->size2; j++) {
printf(" %12.5g ", gsl_matrix_get(R, i, j));
}
printf(")\n");
}
printf("\n");
Rtop = gsl_matrix_submatrix(R, 0, 0, N, N);
RTR = gsl_matrix_alloc(N, N);
gsl_matrix_memcpy(RTR, &(Rtop.matrix));
ret = gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit,
1.0, RTR, RTR);
//(Rtop.matrix), &(Rtop.matrix));
for (i=0; i<RTR->size1; i++) {
printf((i==0) ? "RTR = (" : " (");
for (j=0; j<RTR->size2; j++) {
printf(" %12.5g ", gsl_matrix_get(RTR, i, j));
}
printf(")\n");
}
printf("\n");
gsl_matrix_free(RTR);
gsl_matrix_free(Q);
gsl_matrix_free(R);
gsl_vector_free(tau);
gsl_matrix_free(A);
return 0;
}
| {
"alphanum_fraction": 0.5586813187,
"avg_line_length": 20.4954954955,
"ext": "c",
"hexsha": "5b292a542ff5d487b10ffd22e948440723544a59",
"lang": "C",
"max_forks_count": 173,
"max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z",
"max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_forks_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_forks_repo_name": "juandesant/astrometry.net",
"max_forks_repo_path": "gsl-an/qr-demo.c",
"max_issues_count": 208,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z",
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "gsl-an/qr-demo.c",
"max_line_length": 70,
"max_stars_count": 460,
"max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_stars_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_stars_repo_name": "juandesant/astrometry.net",
"max_stars_repo_path": "gsl-an/qr-demo.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z",
"num_tokens": 912,
"size": 2275
} |
#include <petsc.h>
#include "plexview.h"
PetscErrorCode PlexViewFromOptions(DM plex) {
PetscErrorCode ierr;
PetscBool cell_cones = PETSC_FALSE,
closures_coords = PETSC_FALSE,
coords = PETSC_FALSE,
points = PETSC_FALSE,
use_height = PETSC_FALSE,
vertex_supports = PETSC_FALSE;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "plex_view_", "view options for tiny", "");CHKERRQ(ierr);
ierr = PetscOptionsBool("-cell_cones", "print cones of each cell",
"tiny.c", cell_cones, &cell_cones, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-closures_coords", "print vertex and edge (centers) coordinates for each cell",
"tiny.c", closures_coords, &closures_coords, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-coords", "print section and local vec for vertex coordinates",
"tiny.c", coords, &coords, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-points", "print point index ranges for vertices,edges,cells",
"tiny.c", points, &points, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-use_height", "use Height instead of Depth when printing points",
"tiny.c", use_height, &use_height, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-vertex_supports", "print supports of each vertex",
"tiny.c", vertex_supports, &vertex_supports, NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd();
if (points) {
ierr = PlexViewPointRanges(plex,use_height); CHKERRQ(ierr);
}
if (cell_cones) {
ierr = PlexViewFans(plex,2,2,1); CHKERRQ(ierr);
}
if (vertex_supports) {
ierr = PlexViewFans(plex,2,0,1); CHKERRQ(ierr);
}
if (coords) {
ierr = PlexViewCoords(plex); CHKERRQ(ierr);
}
if (closures_coords) {
ierr = PlexViewClosuresCoords(plex); CHKERRQ(ierr);
}
return 0;
}
static const char* stratanames[4][10] =
{{"vertex","", "", ""}, // dim=0 names
{"vertex","cell","", ""}, // dim=1 names
{"vertex","edge","cell",""}, // dim=2 names
{"vertex","edge","face","cell"}}; // dim=3 names
PetscErrorCode PlexViewPointRanges(DM plex, PetscBool use_height) {
PetscErrorCode ierr;
int dim, m, start, end;
const char *plexname;
MPI_Comm comm;
PetscMPIInt rank,size;
ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);
ierr = DMGetDimension(plex,&dim); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(comm,"point ranges for DMPlex %s in %dD:\n",plexname,dim); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(comm," [rank %d]",rank); CHKERRQ(ierr);
}
ierr = DMPlexGetChart(plex,&start,&end); CHKERRQ(ierr);
if (end < 1) { // nothing on this rank
ierr = PetscSynchronizedPrintf(comm,"\n"); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
ierr = PetscSynchronizedPrintf(comm,
" chart points %d,...,%d\n",start,end-1); CHKERRQ(ierr);
for (m = 0; m < dim + 1; m++) {
if (use_height) {
ierr = DMPlexGetHeightStratum(plex,m,&start,&end); CHKERRQ(ierr);
ierr = PetscSynchronizedPrintf(comm,
" height %d of size %d: %d,...,%d (%s)\n",
m,end-start,start,end-1,dim < 4 ? stratanames[dim][2-m] : ""); CHKERRQ(ierr);
} else {
ierr = DMPlexGetDepthStratum(plex,m,&start,&end); CHKERRQ(ierr);
ierr = PetscSynchronizedPrintf(comm,
" depth=dim %d of size %d: %d,...,%d (%s)\n",
m,end-start,start,end-1,dim < 4 ? stratanames[dim][m] : ""); CHKERRQ(ierr);
}
}
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
PetscErrorCode PlexViewFans(DM plex, int dim, int basestrata, int targetstrata) {
PetscErrorCode ierr;
const char *plexname;
const int *targets;
int j, m, start, end, cssize;
MPI_Comm comm;
PetscMPIInt rank,size;
ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(comm,"fans (cones or supports) for DMPlex %s:\n",plexname); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(comm," [rank %d]",rank); CHKERRQ(ierr);
}
ierr = PetscSynchronizedPrintf(comm,
" %s (= %s indices) of each %s\n",
(basestrata > targetstrata) ? "cones" : "supports",
stratanames[dim][targetstrata],stratanames[dim][basestrata]); CHKERRQ(ierr);
ierr = DMPlexGetDepthStratum(plex, basestrata, &start, &end); CHKERRQ(ierr);
for (m = start; m < end; m++) {
if (basestrata > targetstrata) {
ierr = DMPlexGetConeSize(plex,m,&cssize); CHKERRQ(ierr);
ierr = DMPlexGetCone(plex,m,&targets); CHKERRQ(ierr);
} else {
ierr = DMPlexGetSupportSize(plex,m,&cssize); CHKERRQ(ierr);
ierr = DMPlexGetSupport(plex,m,&targets); CHKERRQ(ierr);
}
ierr = PetscSynchronizedPrintf(comm,
" %s %d: ",stratanames[dim][basestrata],m); CHKERRQ(ierr);
for (j = 0; j < cssize-1; j++) {
ierr = PetscSynchronizedPrintf(comm,
"%d,",targets[j]); CHKERRQ(ierr);
}
ierr = PetscSynchronizedPrintf(comm,
"%d\n",targets[cssize-1]); CHKERRQ(ierr);
}
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
PetscErrorCode PlexViewCoords(DM plex) {
PetscErrorCode ierr;
PetscSection coordSection;
Vec coordVec;
const char *plexname;
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,"coordinate PetscSection and Vec for DMPlex %s:\n",plexname); CHKERRQ(ierr);
ierr = DMGetCoordinateSection(plex, &coordSection); CHKERRQ(ierr);
if (coordSection) {
ierr = PetscSectionView(coordSection,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
} else {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"[PlexViewCoords(): vertex coordinates PetscSection has not been set]\n"); CHKERRQ(ierr);
}
ierr = DMGetCoordinatesLocal(plex,&coordVec); CHKERRQ(ierr);
if (coordVec) {
ierr = VecViewLocalStdout(coordVec,PETSC_COMM_WORLD); CHKERRQ(ierr);
} else {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"[PlexViewCoords(): vertex coordinates Vec not been set]\n"); CHKERRQ(ierr);
}
return 0;
}
PetscErrorCode PlexViewClosuresCoords(DM plex) {
PetscErrorCode ierr;
DM cdm;
Vec coords;
double *acoords;
int numpts, *pts = NULL,
j, p, vertexstart, vertexend, edgeend, cellstart, cellend;
MPI_Comm comm;
PetscMPIInt rank,size;
const char *plexname;
ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(comm,
"closure points and coordinates for each cell in DMPlex %s:\n",plexname); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(comm," [rank %d]",rank); CHKERRQ(ierr);
}
ierr = DMPlexGetHeightStratum(plex, 0, &cellstart, &cellend); CHKERRQ(ierr);
if (cellend < 1) { // nothing on this rank
ierr = PetscSynchronizedPrintf(comm,"\n"); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
ierr = DMGetCoordinateDM(plex, &cdm); CHKERRQ(ierr);
ierr = DMGetCoordinatesLocal(plex,&coords); CHKERRQ(ierr);
ierr = DMPlexGetDepthStratum(plex, 0, &vertexstart, &vertexend); CHKERRQ(ierr);
ierr = DMPlexGetDepthStratum(plex, 1, NULL, &edgeend); CHKERRQ(ierr);
ierr = VecGetArray(coords, &acoords); CHKERRQ(ierr);
for (j = cellstart; j < cellend; j++) {
ierr = DMPlexGetTransitiveClosure(plex, j, PETSC_TRUE, &numpts, &pts);
ierr = PetscSynchronizedPrintf(comm," cell %d\n",j); CHKERRQ(ierr);
for (p = 0; p < numpts*2; p += 2) { // omit orientations
if ((pts[p] >= vertexstart) && (pts[p] < edgeend)) { // omit cells in closure
if (pts[p] < vertexend) { // get location from coords
int voff;
voff = pts[p] - vertexstart;
ierr = PetscSynchronizedPrintf(comm,
" vertex %3d at (%g,%g)\n",
pts[p],acoords[2*voff+0],acoords[2*voff+1]); CHKERRQ(ierr);
} else { // assume it is an edge ... compute center
const int *vertices;
int voff[2];
double x,y;
ierr = DMPlexGetCone(plex, pts[p], &vertices); CHKERRQ(ierr);
voff[0] = vertices[0] - vertexstart;
voff[1] = vertices[1] - vertexstart;
x = 0.5 * (acoords[2*voff[0]+0] + acoords[2*voff[1]+0]);
y = 0.5 * (acoords[2*voff[0]+1] + acoords[2*voff[1]+1]);
ierr = PetscSynchronizedPrintf(comm,
" edge %3d at (%g,%g)\n",pts[p],x,y); CHKERRQ(ierr);
}
}
}
ierr = DMPlexRestoreTransitiveClosure(plex, j, PETSC_TRUE, &numpts, &pts); CHKERRQ(ierr);
}
ierr = VecRestoreArray(coords, &acoords); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
PetscErrorCode VecViewLocalStdout(Vec v, MPI_Comm gcomm) {
PetscErrorCode ierr;
int m,locsize;
PetscMPIInt rank,size;
double *av;
const char *vecname;
ierr = MPI_Comm_size(gcomm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(gcomm,&rank); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)v,&vecname); CHKERRQ(ierr);
ierr = PetscPrintf(gcomm,"local Vec: %s %d MPI processes\n",
vecname,size); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(gcomm,"[rank %d]:\n",rank); CHKERRQ(ierr);
}
ierr = VecGetLocalSize(v,&locsize); CHKERRQ(ierr);
ierr = VecGetArray(v, &av); CHKERRQ(ierr);
for (m = 0; m < locsize; m++) {
ierr = PetscSynchronizedPrintf(gcomm,"%g\n",av[m]); CHKERRQ(ierr);
}
ierr = VecRestoreArray(v, &av); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(gcomm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
| {
"alphanum_fraction": 0.5949594959,
"avg_line_length": 44.979757085,
"ext": "c",
"hexsha": "2274c7980a115fd26c4162b952bb8df199493467",
"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/junk/plex/plexview.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/junk/plex/plexview.c",
"max_line_length": 116,
"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/junk/plex/plexview.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": 3003,
"size": 11110
} |
/**
*/
#include <math.h>
#include "fitsio.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_interp.h>
#include "spc_cfg.h"
#include "aXe_utils.h"
#include "aXe_errors.h"
#include "fringe_conf.h"
#define AXE_CONFIG_PATH "AXE_CONFIG_PATH"
/**
* Function: load_CCD_layer
* The function creates and returns a structure for an optical
* CCD layer. The input parameters are interpreted, and
* the data which defines the CCD layer is loaded.
*
* Parameters:
* @param refr_table - the name of the refractive index table
* @param thickness - the value for the thicknes keyword
(number or image name)
*
* Returns:
* @return opt_layer - the optical layer created
*/
ccd_layer *
load_CCD_layer(const char refr_table[], const char thickness[])
{
ccd_layer *opt_layer;
float tvalue;
char **t_err=NULL;
char refr_table_path[MAXCHAR];
char thickness_path[MAXCHAR];
// build the full pathname to the refraction table
build_path (AXE_CONFIG_PATH, refr_table, refr_table_path);
// allocate an error array
t_err = (char **) malloc(sizeof(char *)*1);
// allocate space for the return structure;
// complain if this fails
opt_layer = (ccd_layer *)malloc(sizeof(ccd_layer));
// initialize both, the single value
// as well as the matrix to NULL;
opt_layer->thickness = 0.0;
opt_layer->thickness2D = NULL;
// convert the keyvalue to a float
// tvalue = atof(thickness);
tvalue = strtod(thickness,t_err);
// in case the float value is NULL = 0.0
// the conversion failed, and it must be a string
// if (tvalue)
if (strcmp(thickness, t_err[0]))
{
#ifdef DEBUGFCONF
fprintf(stderr, "Setting the layer thickness to value: %f mum\n",tvalue);
#endif
// set the fixed thickness value
opt_layer->thickness = tvalue;
}
else
{
#ifdef DEBUGFCONF
fprintf(stderr, "Loading layer thickness image: %s\n", thickness);
#endif
// build the full pathname to the thickness image
build_path (AXE_CONFIG_PATH, thickness, thickness_path);
// load the 2D image for the thickness
opt_layer->thickness2D = FITSimage_to_gsl(thickness_path, 1, 1);
}
#ifdef DEBUGFCONF
fprintf(stderr, "Loading refractive index table: %s\n", refr_table);
#endif
// load the real part of the refraction index
opt_layer->re_refraction =
create_interp_ftable(refr_table_path, 2, "WAVELENGTH", "N",
REFRAC_INTERP_TYPE);
// load the real part of the refraction index
opt_layer->im_refraction =
create_interp_ftable(refr_table_path, 2, "WAVELENGTH", "K",
REFRAC_INTERP_TYPE);
// return the optical layer
return opt_layer;
}
/**
* Function: free_CCD_layer
* The function releases all the memory allocated
* in a structure for a CCD layer.
*
* Parameters:
* @param opt_layer - structure for CCD layer
*
* Returns:
* @return -
*/
void
free_CCD_layer(ccd_layer *opt_layer)
{
// free the thickness matrix
if (opt_layer->thickness2D)
gsl_matrix_free(opt_layer->thickness2D);
// free both interpolators
free_interp(opt_layer->re_refraction);
free_interp(opt_layer->im_refraction);
// free the rest
free(opt_layer);
// set the structure to NULL
opt_layer = NULL;
}
/**
* Function: load_CCD_layers
* The function extracts from a fringe configuration file
* all information on individual CCD layers. It creates
* the appropriate structure for every CCD layer,
* and creates and returns a structure which completely
* describes all layers in a CCD.
*
* Parameters:
* @param fring_conf_path - the name of a fringe configuration file
*
* Returns:
* @return opt_layers - the structure for the optical layers created
*/
ccd_layers *
load_CCD_layers(char fring_conf_path[])
{
ccd_layers *opt_layers;
char layer[MAXCHAR];
char refr_table[MAXCHAR];
//int nlayers;
int i=0;
struct CfgStrings LayerConfig[] = {
{NULL, NULL},
{NULL, NULL}
};
LayerConfig[0].name = layer;
// allocate space for the return structure;
// complain if this fails
opt_layers = malloc (sizeof (ccd_layers));
// initialize the substrate
opt_layers->substrate = NULL;
// detemrine the number of layers
// which are described in the
//configuration file
opt_layers->num_layers = 0;
for (i = 0; i < MAX_BEAMS; i++)
{
sprintf (layer, "REFR_INDEX_%c", BEAM (i));
CfgRead (fring_conf_path, LayerConfig);
if (LayerConfig[0].data != NULL)
{
opt_layers->num_layers += 1;
LayerConfig[0].data = NULL;
}
}
// if (opt_layers->num_layers < NLAYERS_MIN)
// aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
// "The number of layers in the configuration\n file is %i. "
// "There must be at least: %i!\n",
// opt_layers->num_layers, NLAYERS_MIN);
// allocate space for the array to
// the layers described in the
// configuration file
opt_layers->opt_layer =
(ccd_layer **)malloc (opt_layers->num_layers*sizeof(ccd_layers));
// successively find the
// description and finally
// load all layers
for (i = 0; i < MAX_BEAMS; i++)
{
// chekc for the first relevant keyword
sprintf (layer, "REFR_INDEX_%c", BEAM (i));
CfgRead (fring_conf_path, LayerConfig);
if (LayerConfig[0].data != NULL)
{
sprintf (refr_table, "%s", LayerConfig[0].data);
LayerConfig[0].data = NULL;
// check for the second relevant keyword
sprintf (layer, "THICKNESS_%c", BEAM (i));
CfgRead (fring_conf_path, LayerConfig);
if (LayerConfig[0].data != NULL)
{
// load the layer
opt_layers->opt_layer[i] =
load_CCD_layer(refr_table, LayerConfig[0].data);
LayerConfig[0].data = NULL;
}
else
{
// complain that a keyword is missing
// for a layer
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Could load index table %s,\n"
"but not thickness information "
"for beam %c\n", refr_table, BEAM (i));
}
}
}
// return the whole structure
return opt_layers;
}
/**
* Function: free_CCD_layers
* The function releases all memory allocated in a
* CCD layers structure.
*
* Parameters:
* @param opt_layers - the CCD layers structure
*
* Returns:
* @return -
*/
void
free_CCD_layers(ccd_layers *opt_layers)
{
int index=0;
// free each layer individually
for (index=0; index < opt_layers->num_layers; index++)
free_CCD_layer(opt_layers->opt_layer[index]);
// free the interpolator for the substrate
// free_linint(opt_layers->substrate);
free_interp(opt_layers->substrate);
// free everything
free(opt_layers);
// set the structure to NULL
opt_layers = NULL;
}
/**
* Function: load_fringe_conf
* The function loads the fringe configuration file given as parameter.
* All relevant data marked with keywords is extracted. A fringe
* configuration structure is built up and returned from the
* data given in the keyvalues.
*
* Parameters:
* @param fring_conf_path - the complete path-name to a fringe configuration file
*
* Returns:
* @return fconf - the fringe configuration structure created
*/
fringe_conf *
load_fringe_conf(char fring_conf_path[])
{
char beam[MAXCHAR];
char ffile_name[MAXCHAR];
char ffile_name_path[MAXCHAR];
int index=0;
fringe_conf *fconf=NULL;
gsl_vector *v=NULL;
struct CfgStrings FringeConfig[] =
{
{"FRINGE_AMPLITUDE", NULL},
{"FRINGE_PHASE", NULL},
{"FRINGE_RANGE", NULL},
{"MAX_DISPERSION", NULL},
{"FILTER_NAME", NULL},
{"FRINGE_STEP",NULL},
{"NUM_STEPS",NULL},
{"SUBSTR_TRANS",NULL},
{NULL, NULL},
{NULL, NULL} /* array terminator. REQUIRED !!! */
};
FringeConfig[8].name = beam;
// allocate space for the return structure;
// complain if this fails
fconf = malloc (sizeof (fringe_conf));
if (fconf == NULL)
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Could not allocate memory for fringe configuration");
}
// load the optical layers directly from the file
fconf->opt_layers = load_CCD_layers(fring_conf_path);
// read in the file
CfgRead (fring_conf_path, FringeConfig);
// make some intitializations
fconf->fringe_amp = 0.0;
fconf->fringe_phase = 1.0e+32;
fconf->fringe_step = 0.0;
fconf->num_steps = 0;
fconf->fringe_range = NULL;
fconf->max_dispersion = 0.0;
fconf->filter_through = NULL;
for (index = 0; index < 9; index++)
{
// read in the fringe amplitude
if (!strcmp (FringeConfig[index].name, "FRINGE_AMPLITUDE"))
{
if (FringeConfig[index].data != NULL)
{
fconf->fringe_amp = atof(FringeConfig[index].data);
}
}
// read in the fringe phase
if (!strcmp (FringeConfig[index].name, "FRINGE_PHASE"))
{
if (FringeConfig[index].data != NULL)
{
fconf->fringe_phase = atof(FringeConfig[index].data);
}
}
// read in the fringe step
if (!strcmp (FringeConfig[index].name, "FRINGE_STEP"))
{
if (FringeConfig[index].data != NULL)
{
fconf->fringe_step = atof(FringeConfig[index].data);
}
}
// read in the number of steps
if (!strcmp (FringeConfig[index].name, "NUM_STEPS"))
{
if (FringeConfig[index].data != NULL)
{
fconf->num_steps = atoi(FringeConfig[index].data);
}
}
// read in the fringe range
if (!strcmp (FringeConfig[index].name, "FRINGE_RANGE"))
{
if (FringeConfig[index].data != NULL)
{
v = string_to_gsl_array (FringeConfig[index].data);
fconf->fringe_range = v;
}
}
// read in the fringe amplitude
if (!strcmp (FringeConfig[index].name, "MAX_DISPERSION"))
{
if (FringeConfig[index].data != NULL)
{
fconf->max_dispersion = atof(FringeConfig[index].data);
}
}
// read in the filter name
if (!strcmp (FringeConfig[index].name, "FILTER_NAME"))
{
if (FringeConfig[index].data != NULL)
{
sprintf (ffile_name, "%s", FringeConfig[index].data);
// build the full pathname to the refraction table
build_path (AXE_CONFIG_PATH, ffile_name, ffile_name_path);
fconf->filter_through =
create_interp_ftable(ffile_name_path, 2, "WAVELENGTH",
"THROUGHPUT", FILTER_INTERP_TYPE);
}
}
// read in the substrate transmission
if (!strcmp (FringeConfig[index].name, "SUBSTR_TRANS"))
{
if (FringeConfig[index].data != NULL)
{
sprintf (ffile_name, "%s", FringeConfig[index].data);
// build the full pathname to the refraction table
build_path (AXE_CONFIG_PATH, ffile_name, ffile_name_path);
fconf->opt_layers->substrate =
create_interp_ftable(ffile_name_path, 2, "WAVELENGTH",
"TRANSMISSION", REFRAC_INTERP_TYPE);
}
}
}
return fconf;
}
/**
* Function: check_fringe_conf
*
* Parameters:
* @param fconf - the fringe configuration structure
*
* Returns:
* @return
*/
void
check_fringe_conf(fringe_conf *fconf)
{
// make sure the fringe amplitude is set
if (!fconf->fringe_amp)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"fringe_conf: The fringing amplitude must\n"
"be set to be able determining pixel fringing!\n");
// make sure the fringe phase is set
if (fconf->fringe_phase > 1.0e+31)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"fringe_conf: The fringing phase must\n"
"be set to be able determining pixel fringing!\n");
// make sure the transmission of the substrate
// layer is given
if (!fconf->opt_layers->substrate)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"fringe_conf: The substrate transmission\n"
"must be given to be able determining pixel fringing!\n");
// make sure that there is a minimum
// number of layers.
if (fconf->opt_layers->num_layers < NLAYERS_MIN)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"The number of layers in the configuration\n file is %i. "
"There must be at least: %i!\n",
fconf->opt_layers->num_layers, NLAYERS_MIN);
// if not defined, give a meaningfull
// default for the fringing range
if (!fconf->fringe_range)
{
fconf->fringe_range = gsl_vector_alloc(2);
gsl_vector_set(fconf->fringe_range, 0, DEFAULT_MIN_LAMBDA);
gsl_vector_set(fconf->fringe_range, 1, DEFAULT_MAX_LAMBDA);
fprintf(stdout, "Setting the fringing range to defaults: [ %f, %f].\n",
DEFAULT_MIN_LAMBDA, DEFAULT_MAX_LAMBDA);
}
// give reasonable default for
// the fringe step
if (!fconf->fringe_step)
{
fconf->fringe_step = DEFAULT_FRINGE_STEP;
fprintf(stdout, "Setting the fringing step to default: %f.\n",
DEFAULT_FRINGE_STEP);
}
// give a reasonable default for the
// number of steps
if (!fconf->num_steps)
{
fconf->num_steps = DEFAULT_NUM_STEPS;
fprintf(stdout, "Setting the number of steps to default: %i.\n",
DEFAULT_NUM_STEPS);
}
// give a reasonable default for the
// maximum dispersion to correct for
if (!fconf->max_dispersion)
{
fconf->max_dispersion = DEFAULT_MAX_DISPERSION;
fprintf(stdout, "Setting the maximal dispersion to default: %f.\n",
DEFAULT_MAX_DISPERSION);
}
}
/**
* Function: free_fringe_conf
* The function deallocates all memory in a
* fringe configuration structure.
*
* Parameters:
* @param fconf - the fringe configuration structure
*
* Returns:
* @return -
*/
void
free_fringe_conf(fringe_conf *fconf)
{
// free the filter throughput
if (fconf->filter_through)
free_interp(fconf->filter_through);
// free the optical layers
free_CCD_layers(fconf->opt_layers);
// free the fringe range
gsl_vector_free(fconf->fringe_range);
fconf->fringe_range = NULL;
// free everything
free(fconf);
}
/**
* Function: create_interp_ftable
* This function cretaes an interpolator from data values stored
* in a fits table. An interpolator is a structure to hold all
* data to compute the interpolated data values for different
* interpolation methods. Core of this structure is the interpolator
* types offered in the gsl-library.
* This function is a tool to extract the relevant data points from
* a fits table and to set up and return the interpolator.
*
*
* Parameters:
* @param table_name - the name of the fits table
* @param hdunum - the extension number with the data
* @param xcol - the column name with the indepenent values
* @param ycol - the column name with the dependent values
* @param interp_type - the interpolation type
*
* Returns:
* @return interp - the interpolation structure created
*/
interpolator *
create_interp_ftable(const char table_name[], const int hdunum,
char xcol[], char ycol[],
const gsl_interp_type *interp_type)
{
interpolator *interp;
double *x;
double *y;
int f_status = 0;
int hdutype, anynul;
long nrows=0;
int colnum=0;
fitsfile *input;
// allocate space for the return structure;
// complain if this fails
// interp = (interpolator *)malloc (sizeof (interpolator));
// if (interp == NULL)
// {
// aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
// "Could not allocate memory for interpolator");
// }
#ifdef DEBUGFCONF
fprintf(stderr, "Loading columns %s and %s of fitstable: %s\n", xcol, ycol, table_name);
#endif
// Open the file for reading
fits_open_file (&input, table_name, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not open" " file: %s",
table_name);
}
/* Move to the correct hdu */
fits_movabs_hdu (input, hdunum, &hdutype, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable:"
"Could not read extention %d from file: %s",
hdunum, table_name);
}
/* Get number of rows */
fits_get_num_rows (input, &nrows, &f_status);
if (f_status) {
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not determine the number of rows in"
" table %s",table_name);
}
/* Allocate temporary memory space */
x = (double *) malloc(nrows*sizeof(double));
if (!x) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
y = (double *) malloc(nrows*sizeof(double));
if (!y) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
/**************************/
/* Read the X-column */
/**************************/
/* Get column number */
fits_get_colnum (input, CASEINSEN, xcol, &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not determine column %s in "
" table %s", xcol, table_name);
}
/* Read the data */
fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, x,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not read content of WAVELENGTH column "
" from BINARY table %s",table_name);
}
/**************************/
/* Read the y-column */
/**************************/
/* Get column number */
fits_get_colnum (input, CASEINSEN, ycol, &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not determine column %s in "
" table %s", ycol, table_name);
}
/* Read the data */
fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, y,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not read column %s"
" from BINARY table %s", ycol, table_name);
}
fits_close_file(input,&f_status);
if (f_status) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Could not close %s", table_name);
}
// create the interpolator
interp = create_interp(nrows, interp_type, x, y);
// return the interpolator
return interp;
}
/**
* Function: create_interp
* The function creates, and intializes and returns an interpolator
* from the basic input, which is the data, the number of data
* items and the interpolator type requested.
*
* Parameters:
* @param nvals - the number of data values in the arrays
* @param interp_type - the interpolation type
* @param xvals - the array with the independent data values
* @param yvals - the array with the dependent data values
*
* Returns:
* @return interp - the interpolation structure created
*/
interpolator *
create_interp(const int nvals, const gsl_interp_type *interp_type,
double *xvals, double *yvals)
{
interpolator *interp;
// allocate space for the return structure;
// complain if this fails
interp = (interpolator *)malloc (sizeof (interpolator));
if (interp == NULL)
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Could not allocate memory for interpolator");
}
// store the min and max values
interp->xmin = xvals[0];
interp->xmax = xvals[nvals-1];
// check for ascending order in the
// independent values
if (interp->xmax < interp->xmin)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"The independent data values to be stored\n"
" in an interplator must be in INCREASING order!\n");
// store the number of data values
interp->nvals = nvals;
// store the data arrays
interp->xvals = xvals;
interp->yvals = yvals;
// create and intitialize the gsl inteprolator
interp->acc = gsl_interp_accel_alloc();
interp->interp = gsl_interp_alloc(interp_type, interp->nvals);
gsl_interp_init(interp->interp, interp->xvals, interp->yvals, interp->nvals);
// return the new structure
return interp;
}
/**
* Function: print_interp
*
* Parameters:
* @param interp - the interpolator structure
*
* Returns:
* @return -
*/
void
print_interp(interpolator *interp)
{
int index;
double x_typical;
x_typical = interp->xmin+(interp->xmax-interp->xmin)/2.0;
fprintf(stdout, "xmin: %e, xmax: %e\n",interp->xmin, interp->xmax);
fprintf(stdout, "number of data values: %i\n",interp->nvals);
fprintf(stdout, "Interpolation type: %s\n", gsl_interp_name(interp->interp));
fprintf(stdout, "Characteristic value pair: (x,y) = (%e, %e)\n",
x_typical, gsl_interp_eval(interp->interp, interp->xvals,
interp->yvals, x_typical, interp->acc));
fprintf(stdout, "Alternative value pair: (x,y) = (%e, %e)\n",
x_typical, eval_interp(interp, x_typical));
for (index=0; index < interp->nvals; index++)
fprintf(stdout, "xvalue: %e, yvalue: %e\n",interp->xvals[index], interp->yvals[index]);
fprintf(stdout, "\n");
}
/**
* Function: eval_interp
* The function computes and returns the interpolated value
* at a given position for an interpolater.
*
* Parameters:
* @param interp - the interpolator
* @param xval - the position to evaluate the interpolator
*
* Returns:
* @return (value) - the interpolated data value
*/
double
eval_interp(interpolator *interp, const double xval)
{
// check whether the x-value is within
// the range spanned by the data;
// complain if the x-value is outside
if (xval < interp->xmin || xval > interp->xmax)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"independent interpolation value %f "
"is outside interval (%f, %f)\n", xval,
interp->xmin, interp->xmax);
// evaluate and return the interpolated value
// in on the spot
return gsl_interp_eval(interp->interp, interp->xvals, interp->yvals,
xval, interp->acc);
}
/**
* Function: free_interp
* the function frees all memory allocated in
* an interpolator structure.
*
* Parameters:
* @param interp - the interpolator structure
*
* Returns:
* @return -
*/
void
free_interp(interpolator *interp)
{
// free the data vectors
free(interp->xvals);
free(interp->yvals);
// free the two gsl structures
gsl_interp_accel_free(interp->acc);
gsl_interp_free (interp->interp);
// free the rest
free(interp);
// set it to NULL
interp = NULL;
}
/**
* Function: create_linint_ftable
* This function creates a linear interpolator from data values stored
* in a fits table. An linear interpolator is a structure to hold all
* data to compute the linear interpolated data values at any
* point bracketed by the data.
* This function is a tool to extract the relevant data points from
* a fits table and to set up and return the linear interpolator.
*
* Parameters:
* @param table_name - the name of the fits table
* @param hdunum - the extension number with the data
* @param xcol - the column name with the indepenent values
* @param ycol - the column name with the dependent values
* @param interp_type - the interpolation type
*
* Returns:
* @return lin_int - the linear interplator structure created
*/
linear_interp *
create_linint_ftable(const char table_name[], const int hdunum,
char xcol[], char ycol[])
{
linear_interp *lin_int;
double *x;
double *y;
int f_status = 0;
int hdutype, anynul;
long nrows=0;
int colnum;
int index=0;
gsl_vector *xvals;
gsl_vector *yvals;
fitsfile *input;
// allocate space for the return structure;
// complain if this fails
lin_int = (linear_interp *)malloc (sizeof (linear_interp));
if (lin_int == NULL)
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Could not allocate memory for linear interpolator");
}
#ifdef DEBUGFCONF
fprintf(stderr, "Loading columns %s and %s of fitstable: %s\n", xcol, ycol, table_name);
#endif
// Open the file for reading
fits_open_file (&input, table_name, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"get_response_function_fromFITS: "
"Could not open" " file: %s",
table_name);
}
/* Move to the correct hdu */
fits_movabs_hdu (input, hdunum, &hdutype, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable:"
"Could not read extention %d from file: %s",
hdunum, table_name);
}
/* Get number of rows */
fits_get_num_rows (input, &nrows, &f_status);
if (f_status) {
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not determine the number of rows in"
" table %s",table_name);
}
/* Allocate temporary memory space */
x = (double *) malloc(nrows*sizeof(double));
if (!x) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
y = (double *) malloc(nrows*sizeof(double));
if (!y) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Memory allocation failed");
}
/**************************/
/* Read the X-column */
/**************************/
/* Get column number */
fits_get_colnum (input, CASEINSEN, xcol, &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not determine column %s in "
" table %s", xcol, table_name);
}
/* Read the data */
fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, x,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not read content of WAVELENGTH column "
" from BINARY table %s",table_name);
}
/**************************/
/* Read the y-column */
/**************************/
/* Get column number */
fits_get_colnum (input, CASEINSEN, ycol, &colnum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not determine column %s in "
" table %s", ycol, table_name);
}
/* Read the data */
fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, y,
&anynul, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"create_interp_ftable: "
"Could not read column %s"
" from BINARY table %s", ycol, table_name);
}
fits_close_file(input,&f_status);
if (f_status) {
aXe_message (aXe_M_ERROR, __FILE__, __LINE__,
"Could not close %s", table_name);
}
#ifdef DEBUGFCONF
fprintf(stderr, "Number of rows: %i\n", nrows);
#endif
// allocate space for the two vectors
xvals = gsl_vector_alloc(nrows);
yvals = gsl_vector_alloc(nrows);
// transport the values from the
// arrays to the gsl-arrays
for (index=0; index < nrows; index++)
{
gsl_vector_set(xvals, index, x[index]);
gsl_vector_set(yvals, index, y[index]);
}
// reverse both vectors if necessary
if (gsl_vector_get(xvals, 0) > gsl_vector_get(xvals, nrows-1))
{
gsl_vector_reverse(xvals);
gsl_vector_reverse(yvals);
}
// set the two helper elements
lin_int->act_index = 0;
lin_int->num_elem = nrows;
// set the minimum and maximum
lin_int->xmin = gsl_vector_get(xvals, 0);
lin_int->xmax = gsl_vector_get(xvals, nrows-1);
// set the two vectors
lin_int->xvals = xvals;
lin_int->yvals = yvals;
// release memory in the temp variables
free(x);
free(y);
// return the new structure
return lin_int;
}
/**
* Function: free_linint
* The function frees all memory allocated
* in a linear interpolator structure.
*
* Parameters:
* @param lin_int - the linear inteprolator
*
* Returns:
* @return -
*/
void
free_linint(linear_interp *lin_int)
{
// free the two gsl-vectors
gsl_vector_free(lin_int->xvals);
gsl_vector_free(lin_int->yvals);
// free the whole structure
free(lin_int);
// set the structure to NULL
lin_int = NULL;
}
| {
"alphanum_fraction": 0.6598574654,
"avg_line_length": 26.2201665125,
"ext": "c",
"hexsha": "282f11717402dab6027a8f7a59b567f52478e01c",
"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/fringe_conf.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/fringe_conf.c",
"max_line_length": 91,
"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/fringe_conf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7799,
"size": 28344
} |
//Gets deltas (1st order) and delta-deltas (2nd order) differences of X,
//which is assumed to be pre-allocated of triple size,
//Thus, for dim==0, C%3 must equal 0, and C/3 is the original ncols of X.
//And, for dim==1, R%3 must equal 0, and R/3 is the original nrows of X.
//I implement this just like FIR for speed and shorter code,
//except non-causal and mid-sample of B is 0,
//so I don't explicitly make B (e.g., B[n] just equals sc*n).
//Note that this may treat edge samples differently than other code.
//But this could be changed with a few lines of additional code here,
//without changing the super-efficient FIR implementation.
//That is, since out-of-range samps were assumed to be 0, nothing was
//added to Y for them, so can just add something later.
#include <stdio.h>
#include <cblas.h>
#ifdef __cplusplus
namespace ov {
extern "C" {
#endif
int add_delta_deltas_s (float *X, const int iscolmajor, const int R, const int C, const int dim, const int N);
int add_delta_deltas_d (double *X, const int iscolmajor, const int R, const int C, const int dim, const int N);
int add_delta_deltas_s (float *X, const int iscolmajor, const int R, const int C, const int dim, const int N)
{
const float z = 0.0f;
const int No = R*C/3;
int r, c, n;
float sc = 1.0f;
//Checks
if (R<1) { fprintf(stderr,"error in add_delta_deltas_s: R (nrows X) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in add_delta_deltas_s: C (ncols X) must be positive\n"); return 1; }
if (N<1) { fprintf(stderr,"error in add_delta_deltas_s: N (delta winlength) must be positive\n"); return 1; }
if (dim==0 && C%3!=0) { fprintf(stderr,"error in add_delta_deltas_s: for dim==0, C (ncols X) must be divisible by 3\n"); return 1; }
if (dim==1 && R%3!=0) { fprintf(stderr,"error in add_delta_deltas_s: for dim==1, R (nrows X) must be divisible by 3\n"); return 1; }
//Get sc (normalizer)
for (n=2; n<=N; n++) { sc += n*n; }
sc = 0.5f/sc;
if (dim==0)
{
if (iscolmajor)
{
cblas_scopy(2*No,&z,0,&X[No],1);
for (c=0; c<C/3; c++)
{
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[c*R],0,&X[No+c*R],1); //beg edge samps
cblas_saxpy(R-n,-sc*n,&X[c*R],1,&X[No+c*R+n],1); //past samps
cblas_saxpy(R-n,sc*n,&X[c*R+n],1,&X[No+c*R],1); //future samps
cblas_saxpy(n,sc*n,&X[c*R+R-1],0,&X[No+c*R+R-n],1); //end edge samps
}
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[No+c*R],0,&X[2*No+c*R],1); //beg edge samps
cblas_saxpy(R-n,-sc*n,&X[No+c*R],1,&X[2*No+c*R+n],1); //past samps
cblas_saxpy(R-n,sc*n,&X[No+c*R+n],1,&X[2*No+c*R],1); //future samps
cblas_saxpy(n,sc*n,&X[No+c*R+R-1],0,&X[2*No+c*R+R-n],1); //end edge samps
}
}
}
else
{
for (c=0; c<C/3; c++)
{
cblas_scopy(R,&z,0,&X[C/3+c],C);
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[c],0,&X[C/3+c],C); //beg edge samps
cblas_saxpy(R-n,-sc*n,&X[c],C,&X[C/3+c+n*C],C); //past samps
cblas_saxpy(R-n,sc*n,&X[c+n*C],C,&X[C/3+c],C); //future samps
cblas_saxpy(n,sc*n,&X[c+C*(R-1)],0,&X[C/3+c+C*(R-n)],C); //end edge samps
}
cblas_scopy(R,&z,0,&X[2*C/3+c],C);
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[C/3+c],0,&X[2*C/3+c],C); //beg edge samps
cblas_saxpy(R-n,-sc*n,&X[C/3+c],C,&X[2*C/3+c+n*C],C); //past samps
cblas_saxpy(R-n,sc*n,&X[C/3+c+n*C],C,&X[2*C/3+c],C); //future samps
cblas_saxpy(n,sc*n,&X[C/3+c+C*(R-1)],0,&X[2*C/3+c+C*(R-n)],C); //end edge samps
}
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R/3; r++)
{
cblas_scopy(C,&z,0,&X[R/3+r],R);
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[r],0,&X[R/3+r],R); //beg edge samps
cblas_saxpy(C-n,-sc*n,&X[r],R,&X[R/3+r+n*R],R); //past samps
cblas_saxpy(C-n,sc*n,&X[r+n*R],R,&X[R/3+r],R); //future samps
cblas_saxpy(n,sc*n,&X[r+R*(C-1)],0,&X[R/3+r+R*(C-n)],R); //end edge samps
}
cblas_scopy(C,&z,0,&X[2*R/3+r],R);
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[R/3+r],0,&X[2*R/3+r],R); //beg edge samps
cblas_saxpy(C-n,-sc*n,&X[R/3+r],R,&X[2*R/3+r+n*R],R); //past samps
cblas_saxpy(C-n,sc*n,&X[R/3+r+n*R],R,&X[2*R/3+r],R); //future samps
cblas_saxpy(n,sc*n,&X[R/3+r+R*(C-1)],0,&X[2*R/3+r+R*(C-n)],R); //end edge samps
}
}
}
else
{
cblas_scopy(2*No,&z,0,&X[No],1);
for (r=0; r<R/3; r++)
{
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[r*C],0,&X[No+r*C],1); //beg edge samps
cblas_saxpy(C-n,-sc*n,&X[r*C],1,&X[No+r*C+n],1); //past samps
cblas_saxpy(C-n,sc*n,&X[r*C+n],1,&X[No+r*C],1); //future samps
cblas_saxpy(n,sc*n,&X[r*C+C-1],0,&X[No+r*C+C-n],1); //end edge samps
}
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[No+r*C],0,&X[2*No+r*C],1); //beg edge samps
cblas_saxpy(C-n,-sc*n,&X[No+r*C],1,&X[2*No+r*C+n],1); //past samps
cblas_saxpy(C-n,sc*n,&X[No+r*C+n],1,&X[2*No+r*C],1); //future samps
cblas_saxpy(n,sc*n,&X[No+r*C+C-1],0,&X[2*No+r*C+C-n],1); //end edge samps
}
}
}
}
else
{
fprintf(stderr,"error in add_delta_deltas_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int add_delta_deltas_d (double *X, const int iscolmajor, const int R, const int C, const int dim, const int N)
{
const double z = 0.0;
const int No = R*C/3;
int r, c, n;
double sc = 1.0;
//Checks
if (R<1) { fprintf(stderr,"error in add_delta_deltas_d: R (nrows X) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in add_delta_deltas_d: C (ncols X) must be positive\n"); return 1; }
if (N<1) { fprintf(stderr,"error in add_delta_deltas_d: N (delta winlength) must be positive\n"); return 1; }
if (dim==0 && C%3!=0) { fprintf(stderr,"error in add_delta_deltas_d: C (ncols X) must be divisible by 3\n"); return 1; }
if (dim==1 && R%3!=0) { fprintf(stderr,"error in add_delta_deltas_d: R (nrows X) must be divisible by 3\n"); return 1; }
//Get sc (normalizer)
for (n=2; n<=N; n++) { sc += n*n; }
sc = 0.5/sc;
if (dim==0)
{
if (iscolmajor)
{
cblas_dcopy(2*No,&z,0,&X[No],1);
for (c=0; c<C/3; c++)
{
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[c*R],0,&X[No+c*R],1); //beg edge samps
cblas_daxpy(R-n,-sc*n,&X[c*R],1,&X[No+c*R+n],1); //past samps
cblas_daxpy(R-n,sc*n,&X[c*R+n],1,&X[No+c*R],1); //future samps
cblas_daxpy(n,sc*n,&X[c*R+R-1],0,&X[No+c*R+R-n],1); //end edge samps
}
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[No+c*R],0,&X[2*No+c*R],1); //beg edge samps
cblas_daxpy(R-n,-sc*n,&X[No+c*R],1,&X[2*No+c*R+n],1); //past samps
cblas_daxpy(R-n,sc*n,&X[No+c*R+n],1,&X[2*No+c*R],1); //future samps
cblas_daxpy(n,sc*n,&X[No+c*R+R-1],0,&X[2*No+c*R+R-n],1); //end edge samps
}
}
}
else
{
for (c=0; c<C/3; c++)
{
cblas_dcopy(R,&z,0,&X[C/3+c],C);
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[c],0,&X[C/3+c],C); //beg edge samps
cblas_daxpy(R-n,-sc*n,&X[c],C,&X[C/3+c+n*C],C); //past samps
cblas_daxpy(R-n,sc*n,&X[c+n*C],C,&X[C/3+c],C); //future samps
cblas_daxpy(n,sc*n,&X[c+C*(R-1)],0,&X[C/3+c+C*(R-n)],C); //end edge samps
}
cblas_dcopy(R,&z,0,&X[2*C/3+c],C);
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[C/3+c],0,&X[2*C/3+c],C); //beg edge samps
cblas_daxpy(R-n,-sc*n,&X[C/3+c],C,&X[2*C/3+c+n*C],C); //past samps
cblas_daxpy(R-n,sc*n,&X[C/3+c+n*C],C,&X[2*C/3+c],C); //future samps
cblas_daxpy(n,sc*n,&X[C/3+c+C*(R-1)],0,&X[2*C/3+c+C*(R-n)],C); //end edge samps
}
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R/3; r++)
{
cblas_dcopy(C,&z,0,&X[R/3+r],R);
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[r],0,&X[R/3+r],R); //beg edge samps
cblas_daxpy(C-n,-sc*n,&X[r],R,&X[R/3+r+n*R],R); //past samps
cblas_daxpy(C-n,sc*n,&X[r+n*R],R,&X[R/3+r],R); //future samps
cblas_daxpy(n,sc*n,&X[r+R*(C-1)],0,&X[R/3+r+R*(C-n)],R); //end edge samps
}
cblas_dcopy(C,&z,0,&X[2*R/3+r],R);
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[R/3+r],0,&X[2*R/3+r],R); //beg edge samps
cblas_daxpy(C-n,-sc*n,&X[R/3+r],R,&X[2*R/3+r+n*R],R); //past samps
cblas_daxpy(C-n,sc*n,&X[R/3+r+n*R],R,&X[2*R/3+r],R); //future samps
cblas_daxpy(n,sc*n,&X[R/3+r+R*(C-1)],0,&X[2*R/3+r+R*(C-n)],R); //end edge samps
}
}
}
else
{
cblas_dcopy(2*No,&z,0,&X[No],1);
for (r=0; r<R/3; r++)
{
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[r*C],0,&X[No+r*C],1); //beg edge samps
cblas_daxpy(C-n,-sc*n,&X[r*C],1,&X[No+r*C+n],1); //past samps
cblas_daxpy(C-n,sc*n,&X[r*C+n],1,&X[No+r*C],1); //future samps
cblas_daxpy(n,sc*n,&X[r*C+C-1],0,&X[No+r*C+C-n],1); //end edge samps
}
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[No+r*C],0,&X[2*No+r*C],1); //beg edge samps
cblas_daxpy(C-n,-sc*n,&X[No+r*C],1,&X[2*No+r*C+n],1); //past samps
cblas_daxpy(C-n,sc*n,&X[No+r*C+n],1,&X[2*No+r*C],1); //future samps
cblas_daxpy(n,sc*n,&X[No+r*C+C-1],0,&X[2*No+r*C+C-n],1); //end edge samps
}
}
}
}
else
{
fprintf(stderr,"error in add_delta_deltas_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4263228399,
"avg_line_length": 44.073800738,
"ext": "c",
"hexsha": "034f3bd9e1df2b49103599995c17a68af6c78950",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/aud",
"max_forks_repo_path": "c/add_delta_deltas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/aud",
"max_issues_repo_path": "c/add_delta_deltas.c",
"max_line_length": 136,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/aud",
"max_stars_repo_path": "c/add_delta_deltas.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4111,
"size": 11944
} |
#pragma once
#include "Periodic.h"
#include <gsl/gsl>
#include <algorithm>
#include <vector>
namespace ad {
class Rythm
{
public:
explicit Rythm(duration_t aPeriod, int aDuration) :
mMetronom(aPeriod),
mDuration(aDuration)
{}
Rythm & note(int aTime);
template <class T_functor, class... VT_args>
void forEachEvent(duration_t aDelta, const T_functor & aFunctor, VT_args &&... aArgs);
private:
Periodic mMetronom;
int mDuration;
std::vector<int> mScore{};
int mCurrentNote{0};
};
inline Rythm & Rythm::note(int aTime)
{
Expects( (aTime >= 0) && (aTime < mDuration) );
mScore.push_back(aTime);
return *this;
}
template <class T_functor, class... VT_args>
void Rythm::forEachEvent(duration_t aDelta, const T_functor & aFunctor, VT_args &&... aArgs)
{
mMetronom.forEachEvent(aDelta, [&aFunctor, this](duration_t aRemainingTime, VT_args &&... aArgs)
{
if (std::find(mScore.begin(), mScore.end(), mCurrentNote) != mScore.end())
{
aFunctor(aRemainingTime, std::forward<VT_args>(aArgs)...);
}
if (++mCurrentNote == mDuration)
{
mCurrentNote = 0;
};
}, std::forward<VT_args>(aArgs)...);
}
} // namespace ad
| {
"alphanum_fraction": 0.6233148295,
"avg_line_length": 20.6721311475,
"ext": "h",
"hexsha": "6d76da887b53447cebef75d03e41445dd3471ea6",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-31T13:17:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-31T13:17:54.000Z",
"max_forks_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "FranzPoize/shmurp",
"max_forks_repo_path": "src/app/shmurp/Utils/Rythm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474",
"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": "FranzPoize/shmurp",
"max_issues_repo_path": "src/app/shmurp/Utils/Rythm.h",
"max_line_length": 100,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "FranzPoize/shmurp",
"max_stars_repo_path": "src/app/shmurp/Utils/Rythm.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-06T08:48:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-06T08:48:31.000Z",
"num_tokens": 353,
"size": 1261
} |
/**
* Drizzle utilities
*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_statistics.h>
#include <math.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spc_trace_functions.h"
#include "crossdisp_utils.h"
#include "aper_conf.h"
#include "trace_conf.h"
#include "disp_conf.h"
#include "spc_wl_calib.h"
#include "drizzle_utils.h"
d_point
get_refwave_position(dispstruct * disp, trace_func * trace, d_point refpix,
aperture_conf *conf)
{
double a=0.0;
double b, c, c_star;
double *cf;
double rot;
double dx, dy, dtr;
d_point res;
// check for a dispersion solution
// higher that quadratic order
if (disp->pol->size > 3)
// this can not be solved; give an error
aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
"Order of dispersion solution: %i!\n"
"At most qudratic solutions are allowed!\n",
disp->pol->size-1);
else if (disp->pol->size > 2)
// store the quadratic term, if it exists
a = gsl_vector_get(disp->pol, 2); // ddlambda-term
else
// set the qudratic term to zero
a=0.0;
// store the constant and linear terms
b = gsl_vector_get(disp->pol, 1); // dlambda-term
c = gsl_vector_get(disp->pol, 0); // lambda0-term
// store the dydx value
cf = trace->data;
// dydx --> rotation angle
rot = get_rotation_angle(cf[2]);
// determine the wavelength difference
c_star = c - conf->drz_lamb0;
// transform the wavelength difference
// into a path length difference
if (a)
dtr = (-1.0*b+sqrt(b*b - 4.0*a*c_star))/(2.0*a);
else
dtr = c_star/b;
// path length difference --> dx, dy
dx = dtr*cos(rot);
dy = dtr*sin(rot);
// compute the absolute values
// for the reference position
// in the stamp images
res.x = refpix.x + dx;
res.y = refpix.y + dy;
// return the result
return res;
}
double
get_drizzle_width(object *ob, int beamnum,trace_func * trace)
{
double drizzle_width, drizzle_orient;
double orig_width, orig_orient;
double rotation, angle, oangle, factor;
double *cf;
beam *b = ob->beams+beamnum;
cf = trace->data;
rotation = get_rotation_angle(cf[2]);
orig_orient = b->orient;
orig_width = b->width;
drizzle_orient = orig_orient-rotation;
angle = drizzle_orient / M_PI * 180.;
oangle = orig_orient / M_PI * 180.;
drizzle_width = fabs(orig_width * sin (drizzle_orient));
factor = drizzle_width/orig_width;
if (angle > 180.0)
angle = angle-180.0;
if (angle < 30.0 || angle > 150.0)
fprintf (stdout,
"Angle: %4.0f --> %4.0f, Width: %5.1f --> %5.1f, %5.3f\n",
oangle, angle, orig_width, drizzle_width, factor);
return drizzle_width;
}
gsl_matrix *
get_drizzle_coeffs(dispstruct * disp, trace_func * trace,
int boxwidth, int boxheight, int trlength,
double relx, double rely, aperture_conf *conf,
double orient, dispstruct * outdisp, double cdcorr,
double sprefreso, double spmeanreso)
{
double a, b, c;
double ao, bo, co, bref, cref;
double a11, a12, a21, a22;
double xr, yr;
//double lambda0;
//double dlambda;
double tmp, rotation;
double *cf;
double shear_term;
gsl_matrix * ret = gsl_matrix_alloc(2,11);
gsl_matrix * rotcoeffs;
gsl_matrix_set_all (ret, 0.0);
/* get the dispersion at the objects point */
if (disp->pol->size > 2)
a = gsl_vector_get(disp->pol, 2);
// fprintf (stdout, "quadratic solution: %f\n", a);
else
a = 0.0;
b = gsl_vector_get(disp->pol, 1); // dlambda-term
c = gsl_vector_get(disp->pol, 0); // lambda0-term
/* get the dispersion at the mean reference point */
if (outdisp->pol->size > 2){
ao = gsl_vector_get(outdisp->pol, 2);
// fprintf (stdout, "quadratic solution: %f, old: %f\n", a, ao);
}
else{
ao = 0.0;
}
bo = gsl_vector_get(outdisp->pol, 1); // dlambda-term
co = gsl_vector_get(outdisp->pol, 0); // lambda0-term
if (conf->drz_resol == 0.0) {
conf->drz_resol = bo + ao*((double)trlength)/2.0;
}
if (conf->drz_lamb0 == 0.0) {
conf->drz_lamb0 = co;
}
// fprintf (stdout, "lambda terms: 4785.0 <-> %f, 24.0 <-> %f\n", cref, bref);
cref = conf->drz_lamb0;
bref = conf->drz_resol;
bref = sprefreso;
// Bugfix on Sept. 15th 2010:
// Check whether the ratio of the average dispersion on the grism images
// and the dispersion on the drizzled images is outsidethe range 0.95 < ratio < 1.05.
// If yes, adjust "trlength" which, from now on, is the length of the
// drizzled image. This fix is necessary to allow a different sampling
// in axedrizzle. The range was introduced such that the bug-fixed
// version delivers identical results when using the default sampling.
if ((spmeanreso / sprefreso > 1.05) || (spmeanreso / sprefreso < 0.95))
trlength = (int)(spmeanreso / sprefreso * (double)trlength) + 0.5;
/* put the below lines to go BACK to
* the old computation of the length of
* the aXedrizzled images:
fprintf(stdout, "New spectral length: %i", trlength);
trlength = (int)ceil(bo/bref*sqrt(pow((double)boxwidth,2.0)
+pow((double)boxheight,2.0)));
trlength = (int)ceil(spmeanreso/sprefreso*sqrt(pow((double)boxwidth,2.0)
+pow((double)boxheight,2.0)));
fprintf(stdout, "<--> old spectral length: %i\n", trlength);
*/
//fprintf (stdout,"Drizzled to resolution: %e, mean resolution for object: %e\n", sprefreso, spmeanreso);
gsl_matrix_set(ret, 0,10,trlength);
// gsl_matrix_set(ret, 1,10,bref);
cf = trace->data;
rotation = get_rotation_angle(cf[2]);
rotcoeffs = get_coeffs_back(trace);
a11 = gsl_matrix_get(rotcoeffs,0,0);
a12 = gsl_matrix_get(rotcoeffs,0,1);
a21 = gsl_matrix_get(rotcoeffs,1,0);
a22 = gsl_matrix_get(rotcoeffs,1,1);
// the following lines have to be changed
// in order to go from a integer
// center definition to floating point center
// definition.
xr = (relx+1.0)-((double)(boxwidth/2)+1); // +1.0 to compensate for "sp_sex.c" around line 537
yr = (rely+1.0)-((double)(boxheight/2)+1); // +1.0 to compensate for "sp_sex.c" around line 537
if (b < 0.0)
shear_term = -tan(orient-rotation);
else
shear_term = tan(orient-rotation);
// Transformations for X, without the lambda-terms, only rotation:
// tmp = xoffs-(((double)trlength/2.0)+1)-a11*xr-a12*yr;
// gsl_matrix_set(ret, 0,0,tmp); // constant term
// tmp = a11;
// gsl_matrix_set(ret, 0,1,tmp); // x-term
// tmp = a12;
// gsl_matrix_set(ret, 0,2,tmp); // y-term
//----------------------------------------------------------------------------------
//------------------------------------------------------------------
// Mathematica based run
tmp = 1.0/bref*(c - cref - a11*b*xr + a*a11*a11*xr*xr - a12*b*yr + 2*a*a11*a12*xr*yr + a*a12*a12*yr*yr) +
(a21*xr + a22*yr)/shear_term - ((double)(trlength/2)+1.0) + conf->drz_xstart;
gsl_matrix_set(ret, 0,0,tmp); // constant term
tmp = 1.0/bref*(a11*b - 2*a*a11*a11*xr - 2*a*a11*a12*yr) - a21/shear_term;
gsl_matrix_set(ret, 0,1,tmp); // x-term
tmp = 1.0/bref*(a12*b - 2*a*a12*a12*yr - 2*a*a11*a12*xr) - a22/shear_term;
gsl_matrix_set(ret, 0,2,tmp); // y-term
tmp = a*a11*a11/bref;
gsl_matrix_set(ret, 0,3,tmp); // x^2-term
tmp = 2*a*a11*a12/bref;
gsl_matrix_set(ret, 0,4,tmp); ; // xy-term
tmp = a*a12*a12/bref;
gsl_matrix_set(ret, 0,5,tmp); // y^2-term
//------------------------------------------------------------------
// Transformations for Y:
tmp = -1.0*(a21*xr+a22*yr) * cdcorr; // -1.5 is some kind of a fudge factor, no idea where it comes from
gsl_matrix_set(ret, 1,0,tmp); // constant term
tmp = a21 * cdcorr;
gsl_matrix_set(ret, 1,1,tmp); // x-term
tmp = a22 * cdcorr;
gsl_matrix_set(ret, 1,2,tmp); // y-term
gsl_matrix_free(rotcoeffs);
return ret;
}
gsl_matrix *
get_coeffs_back(trace_func * trace)
{
double *cf;
double rotation;
gsl_matrix * ret = gsl_matrix_alloc(2,2);
// ret = gsl_matrix_alloc (2,2);
gsl_matrix_set_all (ret, 0.0);
cf = trace->data;
rotation = get_rotation_angle(cf[2]);
gsl_matrix_set(ret, 0, 0, cos(rotation));
gsl_matrix_set(ret, 0, 1, sin(rotation));
gsl_matrix_set(ret, 1, 0, -1.0*sin(rotation));
gsl_matrix_set(ret, 1, 1, cos(rotation));
return ret;
}
double
get_rotation_angle(double dxdy){
double rotation=0.0;
rotation = atan2(dxdy, 1.0);
return rotation;
}
// Start functions for an alternative approach to store the object information
objectobs **
malloc_objectobs(){
objectobs **allobjects;
allobjects = (objectobs **) malloc (NMAXOBJ*sizeof(objectobs *));
return allobjects;
}
void
free_objectobs(objectobs **allobjects){
// int i, nobjs=0;
// while (allobjects[nobjs])
// nobjs++;
// for (i=0; i<nobjs; i++){
// free(allobjects[i]);
// // allobjects[i] = NULL;
// }
free(allobjects);
}
int
add_observation(char * filename, char * conf_file, objectobs ** allobjects, int nobjects,
object ** oblist, int list_size, px_point pixmax, int sci_numext)
{
int i, j, dec;
int beamID = 0;
int get_scale=0;
int tlength;
gsl_matrix * drzcoeffs;
double cdscale;
double drzscale;
dispstruct * disp;
calib_function *wl_calib;
double l1, l2, spreso;
drzcoeffs = get_crossdisp_matrix(filename, sci_numext);
if (drzcoeffs->size1 > 1 && drzcoeffs->size2)
get_scale = 1;
if (get_scale){
drzscale = (double)get_float_from_keyword(filename, 1, "DRZSCALE");
}
for (i=0; i < list_size; i++){
if (oblist[i]->beams[beamID].ignore == 0){
dec = 0;
if (get_scale)
cdscale = drzscale * get_crossdisp_scale(oblist[i]->beams[beamID].spec_trace,
oblist[i]->beams[beamID].refpoint, drzcoeffs, pixmax);
else
cdscale=1.0;
disp = get_dispstruct_at_pos(conf_file, 1, beamID,oblist[i]->beams[beamID].refpoint);
wl_calib = create_calib_from_gsl_vector(1, disp->pol);
l1 = wl_calib->func (0.0, wl_calib->order, wl_calib->coeffs);
l2 = wl_calib->func (1.0, wl_calib->order, wl_calib->coeffs);
spreso = fabs(l2-l1);
// compute the tracelength
tlength = get_beam_trace_length(oblist[i]->beams[beamID]);
for (j=0; j < nobjects; j++){
if (allobjects[j]->OBJID == oblist[i]->ID){
add_obs_to_allobj(allobjects[j], oblist[i], pixmax, cdscale, spreso, tlength);
dec = 1;
}
}
if (dec == 0) {
nobjects = add_obj_to_allobj(allobjects, nobjects, oblist[i], pixmax, cdscale, spreso, tlength);
}
free_dispstruct(disp);
free_calib(wl_calib);
}
}
gsl_matrix_free(drzcoeffs);
return nobjects;
}
void
add_obs_to_allobj(objectobs *actobject, object * actobs, px_point pixmax, double cdscale, double spreso, int tlength)
{
int xmin, xmax, ymin, ymax;
//double m, b;
gsl_vector_int * xvec;
gsl_vector_int * yvec;
px_point bbox;
px_point mins;
double *gaga;
xvec = gsl_vector_int_alloc (4);
yvec = gsl_vector_int_alloc (4);
/* Store the refpoint */
actobject->refpoint[actobject->nobs].x = actobs->beams[0].refpoint.x;
actobject->refpoint[actobject->nobs].y = actobs->beams[0].refpoint.y;
//*************************************************
// patch to correct the reference point in case
// that the the trace descritpion
// does have a non negligeable first order term!
gaga = actobs->beams[0].spec_trace->data;
actobject->refpoint[actobject->nobs].y = actobject->refpoint[actobject->nobs].y + gaga[1];
//*************************************************
gsl_vector_int_set(xvec, 0, actobs->beams[0].corners[0].x);
gsl_vector_int_set(xvec, 1, actobs->beams[0].corners[1].x);
gsl_vector_int_set(xvec, 2, actobs->beams[0].corners[2].x);
gsl_vector_int_set(xvec, 3, actobs->beams[0].corners[3].x);
xmin = gsl_stats_int_min(xvec->data, 1, 4);
xmax = gsl_stats_int_max(xvec->data, 1, 4);
gsl_vector_int_set(yvec, 0, actobs->beams[0].corners[0].y);
gsl_vector_int_set(yvec, 1, actobs->beams[0].corners[1].y);
gsl_vector_int_set(yvec, 2, actobs->beams[0].corners[2].y);
gsl_vector_int_set(yvec, 3, actobs->beams[0].corners[3].y);
ymin = gsl_stats_int_min(yvec->data, 1, 4);
ymax = gsl_stats_int_max(yvec->data, 1, 4);
bbox = recalc_bbox(xmin, xmax, ymin, ymax, pixmax);
mins = recalc_mins(xmin, xmax, ymin, ymax, pixmax);
actobject->width[actobject->nobs] = bbox.x;
actobject->height[actobject->nobs] = bbox.y;
actobject->tlength[actobject->nobs] = tlength;
actobject->objwidth[actobject->nobs] = actobs->beams[0].width;
actobject->orient[actobject->nobs] = actobs->beams[0].orient;
actobject->cdscale[actobject->nobs] = cdscale;
actobject->spreso[actobject->nobs] = spreso;
actobject->relrefpt[actobject->nobs].x = actobs->beams[0].refpoint.x - (double)mins.x;
actobject->relrefpt[actobject->nobs].y = actobs->beams[0].refpoint.y - (double)mins.y;
actobject->nobs = actobject->nobs + 1;
gsl_vector_int_free(xvec);
gsl_vector_int_free(yvec);
}
int
add_obj_to_allobj(objectobs **allobjects, int nobjects, object * actobs,
px_point pixmax, double cdscale, double spreso, int tlength)
{
int xmin, xmax, ymin, ymax;
//double m, b;
gsl_vector_int * xvec;
gsl_vector_int * yvec;
px_point bbox;
px_point mins;
double *gaga;
// object *ob = malloc (sizeof (object));
objectobs *objobs = malloc (sizeof (objectobs));
xvec = gsl_vector_int_alloc (4);
yvec = gsl_vector_int_alloc (4);
allobjects[nobjects] = objobs;
/* Store the refpoint */
allobjects[nobjects]->refpoint[0].x = actobs->beams[0].refpoint.x;
allobjects[nobjects]->refpoint[0].y = actobs->beams[0].refpoint.y;
//*************************************************
// patch to correct the reference point in case
// that the the trace descritpion
// does have a non negligeable first order term!
gaga = actobs->beams[0].spec_trace->data;
allobjects[nobjects]->refpoint[0].y = allobjects[nobjects]->refpoint[0].y + gaga[1];
//*************************************************
allobjects[nobjects]->OBJID = actobs->ID;
allobjects[nobjects]->nobs = 1;
allobjects[nobjects]->pointer = 0;
gsl_vector_int_set(xvec, 0, actobs->beams[0].corners[0].x);
gsl_vector_int_set(xvec, 1, actobs->beams[0].corners[1].x);
gsl_vector_int_set(xvec, 2, actobs->beams[0].corners[2].x);
gsl_vector_int_set(xvec, 3, actobs->beams[0].corners[3].x);
xmin = gsl_stats_int_min(xvec->data, 1, 4);
xmax = gsl_stats_int_max(xvec->data, 1, 4);
gsl_vector_int_set(yvec, 0, actobs->beams[0].corners[0].y);
gsl_vector_int_set(yvec, 1, actobs->beams[0].corners[1].y);
gsl_vector_int_set(yvec, 2, actobs->beams[0].corners[2].y);
gsl_vector_int_set(yvec, 3, actobs->beams[0].corners[3].y);
ymin = gsl_stats_int_min(yvec->data, 1, 4);
ymax = gsl_stats_int_max(yvec->data, 1, 4);
bbox = recalc_bbox(xmin, xmax, ymin, ymax, pixmax);
mins = recalc_mins(xmin, xmax, ymin, ymax, pixmax);
allobjects[nobjects]->width[0] = bbox.x;
allobjects[nobjects]->height[0] = bbox.y;
allobjects[nobjects]->tlength[0] = tlength;
allobjects[nobjects]->objwidth[0] = actobs->beams[0].width;
allobjects[nobjects]->orient[0] = actobs->beams[0].orient;
allobjects[nobjects]->cdscale[0] = cdscale;
allobjects[nobjects]->spreso[0] = spreso;
allobjects[nobjects]->relrefpt[0].x = actobs->beams[0].refpoint.x - (double)mins.x;
allobjects[nobjects]->relrefpt[0].y = actobs->beams[0].refpoint.y - (double)mins.y;
++nobjects;
gsl_vector_int_free(xvec);
gsl_vector_int_free(yvec);
return nobjects;
}
void print_objectobs(objectobs **allobjects, int nobjects){
int i, j;
for (i = 0; i < nobjects; i++){
fprintf(stdout, "OBJID: %i, no of observ.: %i\n", allobjects[i]->OBJID, allobjects[i]->nobs);
for (j = 0; j < allobjects[i]->nobs; j++){
fprintf(stdout, "No %i: width %f, height: %f, \n", j, allobjects[i]->relrefpt[j].x, allobjects[i]->relrefpt[j].y);
}
}
}
void print_objectobs2(objectobs allobjects[], int nobjects){
int i, j;
for (i = 0; i < nobjects; i++){
fprintf(stdout, "OBJID: %i, no of observ.: %i\n", allobjects[i].OBJID, allobjects[i].nobs);
for (j = 0; j < allobjects[i].nobs; j++){
fprintf(stdout, "No %i: width %f, height: %f, \n", j, allobjects[i].relrefpt[j].x, allobjects[i].relrefpt[j].y);
}
}
}
int make_refpoints( char * conf_file, char * filename, px_point pixmax, objectobs **allobjects, int nobjects)
{
int i, j;
int nobs;
int max_width, max_height, omax;
double xmean, ymean;
//double xdata[NMAXOBS];
//double ydata[NMAXOBS];
// objectobs oneobject;
objectobs *oneobject; // = malloc (sizeof (objectobs));
gsl_vector * xvec;
gsl_vector * yvec;
aperture_conf *conf;
gsl_matrix * drzcoeffs;
//double cdscale;
double drzscale;
trace_func *trace;
int beamID=0;
dispstruct * disp;
calib_function *wl_calib;
double l1, l2;
conf = get_aperture_descriptor(conf_file);
get_extension_numbers(filename, conf,conf->optkey1,conf->optval1);
drzcoeffs = get_crossdisp_matrix(filename,conf->science_numext);
drzscale = (double)get_float_from_keyword(filename, 1, "DRZSCALE");
for (i=0; i < nobjects; i++){
oneobject = allobjects[i];
nobs = oneobject->nobs;
xvec = gsl_vector_alloc (nobs);
yvec = gsl_vector_alloc (nobs);
for (j=0; j < nobs; j++){
gsl_vector_set(xvec, j, oneobject->refpoint[j].x);
gsl_vector_set(yvec, j, oneobject->refpoint[j].y);
}
xmean = gsl_stats_mean(xvec->data, 1, nobs);
ymean = gsl_stats_mean(yvec->data, 1, nobs);
max_width = gsl_stats_int_max(oneobject->width, 1, nobs);
max_height = gsl_stats_int_max(oneobject->height, 1, nobs);
omax = gsl_stats_max(oneobject->objwidth, 1, nobs);
allobjects[i]->mean_refpoint.x = xmean;
allobjects[i]->mean_refpoint.y = ymean;
allobjects[i]->max_width = max_width;
allobjects[i]->max_height = max_height;
allobjects[i]->owidthmax = omax;
allobjects[i]->max_tlength = gsl_stats_int_max(oneobject->tlength, 1, nobs);
/*
* Look whether the cross dispersion scale is given in the configuration.
* If not determine the cross dispersion scale at the mean reference point an store it
* store also the mean correction in for to correct the width.
*
*/
if (conf->drz_scale < 1.0e-16){
trace = get_tracefunc_at(conf_file, allobjects[i]->mean_refpoint);
allobjects[i]->cdrefscale = drzscale * get_crossdisp_scale(trace, allobjects[i]->mean_refpoint, drzcoeffs, pixmax);
}
else{
allobjects[i]->cdrefscale = conf->drz_scale;
}
for (j=0; j < nobs; j++){
gsl_vector_set(xvec, j, oneobject->cdscale[j]);
}
xmean = gsl_stats_mean(xvec->data, 1, nobs);
allobjects[i]->cdmeanscale = xmean;
/*
* look whether the wavelength dispersion is given in the conig file
* if not determine the wavelength dispersion at the mean reference point amd store
* it. Store also the mean wavelength dispersion to correct the length
*/
if (conf->drz_resol < 1.0e-16){
disp = get_dispstruct_at_pos(conf_file, 1, beamID, allobjects[i]->mean_refpoint);
wl_calib = create_calib_from_gsl_vector(1, disp->pol);
l1 = wl_calib->func (0.0, wl_calib->order, wl_calib->coeffs);
l2 = wl_calib->func (1.0, wl_calib->order, wl_calib->coeffs);
allobjects[i]->sprefreso = fabs(l2-l1);
}
else{
allobjects[i]->sprefreso = conf->drz_resol;
}
for (j=0; j < nobs; j++){
gsl_vector_set(xvec, j, oneobject->spreso[j]);
}
xmean = gsl_stats_mean(xvec->data, 1, nobs);
allobjects[i]->spmeanreso = xmean;
gsl_vector_free(xvec);
gsl_vector_free(yvec);
}
gsl_matrix_free(drzcoeffs);
free(conf);
return 0;
}
d_point
get_mean_refpoint(objectobs **allobjects, int nobjects, int ID,int * boxwidth,
int * boxheight, double * relx, double * rely,
double * objwidth, double *orient, double * cdref,
double *cdscale, double *cdmeanscale, double *sprefreso, double *spreso,
double *spmeanreso, int *tlength)
{
int i, dec=0;
d_point mpoint;
for (i=0; i < nobjects; i++){
if (allobjects[i]->OBJID == ID){
mpoint.x = allobjects[i]->mean_refpoint.x;
mpoint.y = allobjects[i]->mean_refpoint.y;
*boxwidth = allobjects[i]->max_width;
*boxheight = allobjects[i]->max_height;
*tlength = allobjects[i]->max_tlength;
*objwidth = allobjects[i]->owidthmax;
*cdref = allobjects[i]->cdrefscale;
*cdmeanscale = allobjects[i]->cdmeanscale;
*spmeanreso= allobjects[i]->spmeanreso;
*sprefreso = allobjects[i]->sprefreso;
*orient = allobjects[i]->orient[allobjects[i]->pointer];
*cdscale = allobjects[i]->cdscale[allobjects[i]->pointer];
*spreso = allobjects[i]->spreso[allobjects[i]->pointer];
*relx = allobjects[i]->relrefpt[allobjects[i]->pointer].x;
*rely = allobjects[i]->relrefpt[allobjects[i]->pointer].y;
++allobjects[i]->pointer;
dec=1;
}
}
return mpoint;
}
px_point
recalc_bbox(int xmin, int xmax, int ymin, int ymax, px_point pixmax)
{
px_point ret;
if (xmax > pixmax.x)
xmax = pixmax.x;
if (ymax > pixmax.y)
ymax = pixmax.y;
if (xmin < 1)
xmin = 1;
if (ymin < 1)
ymin = 1;
ret.x = xmax - xmin + 2;
ret.y = ymax - ymin + 2;
return ret;
}
/*
I am not sure what this routine is doing,
but one should make it better.
*/
px_point
recalc_mins(int xmin, int xmax, int ymin, int ymax, px_point pixmax)
{
double m, b;
px_point ret;
m = ((double)ymin - (double)ymax)/((double)xmax - (double)xmin);
b = (double)ymin - m * (double)xmax;
if (xmin < 1){
ymax = (int)ceil(1.0*m + b);
xmin=1;
}
if (xmax > pixmax.x){
ymin = (int)ceil((float)pixmax.x*m + b);
xmax = pixmax.x;
}
if (ymin < 1){
xmax = (int)ceil((1-b)/m);
ymin=1;
}
if (ymax > pixmax.y){
xmin = (int)ceil(((float)pixmax.y-b)/m);
ymax=pixmax.y;
}
ret.x = xmin;
ret.y = ymin;
return ret;
}
int
get_beam_trace_length(const beam actbeam)
{
int trlength=0;
double diagonal_1 = 0.0;
double diagonal_2 = 0.0;
double xdiff, ydiff;
// compute the x- and y- differences for one corner pair
xdiff = (float)actbeam.corners[0].x - (float)actbeam.corners[2].x;
ydiff = (float)actbeam.corners[0].y - (float)actbeam.corners[2].y;
// compute the diagonal distance
diagonal_1 = xdiff*xdiff + ydiff*ydiff;
// compute the x- and y- differences for the other corner pair
xdiff = (float)actbeam.corners[1].x - (float)actbeam.corners[3].x;
ydiff = (float)actbeam.corners[1].y - (float)actbeam.corners[3].y;
// compute the diagonal distance
diagonal_2 = xdiff*xdiff + ydiff*ydiff;
// compute the tracelength
// from the larger diagonal
if (diagonal_1 > diagonal_2)
trlength = (int)ceil(sqrt(diagonal_1)+3.0);
else
trlength = (int)ceil(sqrt(diagonal_2)+3.0);
// return the result
return trlength;
}
| {
"alphanum_fraction": 0.6344242632,
"avg_line_length": 30.6754270696,
"ext": "c",
"hexsha": "bad8d0a226c22cdaba6de26b3cb279ff3c340f4d",
"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/drizzle_utils.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/drizzle_utils.c",
"max_line_length": 121,
"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/drizzle_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7649,
"size": 23344
} |
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multiroots.h>
int rosenbrock_f (const gsl_vector * x, void *params,
gsl_vector * f);
int print_state (size_t iter, gsl_multiroot_fsolver * s);
struct rparams
{
double a;
double b;
};
int rosenbrock_f (const gsl_vector * x, void *params,
gsl_vector * f)
{
double a = ((struct rparams *) params)->a;
double b = ((struct rparams *) params)->b;
const double x0 = gsl_vector_get (x, 0);
const double x1 = gsl_vector_get (x, 1);
const double y0 = a * (1 - x0);
const double y1 = b * (x1 - x0 * x0);
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
return GSL_SUCCESS;
}
int print_state (size_t iter, gsl_multiroot_fsolver * s)
{
printf ("iter = %3u x = % .3f % .3f "
"f(x) = % .3e % .3e\n",
iter,
gsl_vector_get (s->x, 0),
gsl_vector_get (s->x, 1),
gsl_vector_get (s->f, 0),
gsl_vector_get (s->f, 1));
return 0;
}
int main (void)
{
const gsl_multiroot_fsolver_type *T;
gsl_multiroot_fsolver *s;
int status;
size_t iter = 0;
const size_t n = 2;
struct rparams p = {1.0, 10.0};
gsl_multiroot_function f = {&rosenbrock_f, n, &p};
double x_init[2] = {-10.0, -5.0};
gsl_vector *x = gsl_vector_alloc (n);
gsl_vector_set (x, 0, x_init[0]);
gsl_vector_set (x, 1, x_init[1]);
T = gsl_multiroot_fsolver_hybrids;
s = gsl_multiroot_fsolver_alloc (T, 2);
gsl_multiroot_fsolver_set (s, &f, x);
print_state (iter, s);
do
{
iter++;
status = gsl_multiroot_fsolver_iterate (s);
print_state (iter, s);
if (status) /* check if solver is stuck */
break;
status =
gsl_multiroot_test_residual (s->f, 1e-7);
}
while (status == GSL_CONTINUE && iter < 1000);
printf ("status = %s\n", gsl_strerror (status));
gsl_multiroot_fsolver_free (s);
gsl_vector_free (x);
return 0;
}
| {
"alphanum_fraction": 0.606199187,
"avg_line_length": 21.3913043478,
"ext": "c",
"hexsha": "0852fadc566bcf9d0887e82c16b7e89783c0ac81",
"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": "7b21457d4cc05560976f8407e839d30a644468cb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "turtlewangbin/Meanfield",
"max_forks_repo_path": "function_solve.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7b21457d4cc05560976f8407e839d30a644468cb",
"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": "turtlewangbin/Meanfield",
"max_issues_repo_path": "function_solve.c",
"max_line_length": 57,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "7b21457d4cc05560976f8407e839d30a644468cb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "turtlewangbin/Meanfield",
"max_stars_repo_path": "function_solve.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-18T14:05:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-18T14:05:49.000Z",
"num_tokens": 653,
"size": 1968
} |
/**
* @file likelihood.c
* @brief base functions to calculate the likelihood for general multitype OU processes on a phylogenetic tree
* @author Carl Boettiger <cboettig@gmail.com>
* @version 0.1
* @date 2011-04-22
*
* @section LICENSE
*
* Copyright (C)
* 2011 - Carl Boettiger
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include "optimizers.h"
#include "mvn.h"
typedef struct {
int n_nodes;
size_t n_regimes;
int * ancestor;
int * regimes;
double * branch_length;
double * traits;
double * alpha;
double * theta;
double * sigma;
double * Xo;
int * lca_matrix;
} tree;
int get_lca (int i, int j, int n_nodes, const int * ancestor,
const double * branch_length, double * sep);
void simulate (const gsl_rng * rng, tree * mytree);
void calc_lik (const double *Xo, const double alpha[],
const double theta[], const double sigma[],
const int regimes[], const int ancestor[],
const double branch_length[], const double traits[],
int *n_nodes, int lca_matrix[], double *llik);
| {
"alphanum_fraction": 0.6985796949,
"avg_line_length": 28.3731343284,
"ext": "h",
"hexsha": "d4ee09b4fd9df82367028d964824d906d75a4053",
"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": "93947673f4342266acf5af667141bd466de13b3a",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "cboettig/wrightscape",
"max_forks_repo_path": "src/likelihood.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a",
"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": "cboettig/wrightscape",
"max_issues_repo_path": "src/likelihood.h",
"max_line_length": 109,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "cboettig/wrightscape",
"max_stars_repo_path": "src/likelihood.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 484,
"size": 1901
} |
#pragma once
#include <gsl/gsl_vector.h>
#include <gsl/gsl_statistics_double.h>
#include <cmath>
#include <memory>
#include <cassert>
namespace halo {
// A simple wrapper for gsl_vector to manage its memory, and also some user-friendly additions.
class GSLVector {
public:
GSLVector(size_t Sz, bool Zeroed=true)
: Vec(gsl_vector_alloc(Sz), gsl_vector_free) {
if (Zeroed)
gsl_vector_set_all(Vec.get(), 0);
}
// number of elements the vector can handle
size_t capacity() const { return Vec->size; }
// The stride is the step-size from one element to the next in physical memory,
// measured in units of the appropriate datatype.
size_t stride() const { return Vec->stride; }
// clears the vector, setting everything to zero
void clear() {
gsl_vector_set_all(Vec.get(), 0);
}
// access underlying vector, without taking ownership.
gsl_vector* vec() { return Vec.get(); }
gsl_vector const* vec() const { return Vec.get(); }
// access the underlying vector's data
double* data() { return Vec->data; }
double const* data() const {return Vec->data; }
// read an element from the vector
double get(size_t idx) const { return gsl_vector_get(Vec.get(), idx); }
// write an element of the vector
void set(size_t idx, double val) { gsl_vector_set(Vec.get(), idx, val); }
private:
// a managed gsl_vector, which must be constructed with an explicit deleter.
std::unique_ptr<gsl_vector, decltype(&gsl_vector_free)> Vec;
};
/// A value whose quantity depends on some random phenomenon.
/// Not all observations are used to compute properties of the quantity,
/// with priority given to the most recent N observations, for some N.
class RandomQuantity {
public:
RandomQuantity(size_t N=10) : Obs(N) {}
/// Records an observation of the random quantity.
/// If the history becomes full, the oldest observation is dropped to make room
/// for this one.
void observe(double NewSample) {
Count += 1;
Obs.set(NextFree, NewSample);
const size_t Len = Obs.capacity();
NextFree = (NextFree + 1) % Len; // bump with wrap-around
// If this is the first observation, fill the vector with this value
// if (Count == 1)
// for (size_t i = NextFree; i < Len; i++)
// Obs.set(i, NewSample);
}
// adds observations from another random quantity into this one.
void merge(RandomQuantity const& RQ) {
for (size_t i = 0; i < RQ.size(); i++)
observe(RQ.Obs.get(i));
}
// resets the random quantity, forgetting all previous observations.
void clear() {
Obs.clear();
NextFree = 0;
Count = 0;
}
// returns the most recent observation
double last() const {
assert(Count > 0);
size_t LastIdx = NextFree == 0 ? Obs.capacity()-1 : NextFree-1;
return Obs.get(LastIdx);
}
/// returns the maximum capacity of this random quantity's ability to
/// remember observations.
size_t capacity() const {
return Obs.capacity();
}
/// returns the number of observations currently remembered
/// by this random quantity.
size_t size() const { return std::min(Count, Obs.capacity()); }
/// returns the mean of the RQ's observations.
double mean() const {
return gsl_stats_mean(Obs.data(), Obs.stride(), size());
}
/// Given the mean of this RQ's observations, returns the variance.
double variance(double mean) const {
return gsl_stats_variance_m(Obs.data(), Obs.stride(), size(), mean);
}
private:
GSLVector Obs;
size_t NextFree{0};
size_t Count{0};
};
} // end namespace halo | {
"alphanum_fraction": 0.6760168303,
"avg_line_length": 29.4628099174,
"ext": "h",
"hexsha": "90ba2ba7c741ed8d0decad6d8ed54c2a3441e422",
"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": "3caaaae31564ac28a59f64ead2cd6a854d3d8b42",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "halo-project/halo",
"max_forks_repo_path": "include/halo/tuner/RandomQuantity.h",
"max_issues_count": 42,
"max_issues_repo_head_hexsha": "3caaaae31564ac28a59f64ead2cd6a854d3d8b42",
"max_issues_repo_issues_event_max_datetime": "2020-07-10T20:49:47.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-06-27T19:26:36.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "halo-project/halo",
"max_issues_repo_path": "include/halo/tuner/RandomQuantity.h",
"max_line_length": 95,
"max_stars_count": 28,
"max_stars_repo_head_hexsha": "3caaaae31564ac28a59f64ead2cd6a854d3d8b42",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "halo-project/halo",
"max_stars_repo_path": "include/halo/tuner/RandomQuantity.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-11T03:42:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-15T20:34:56.000Z",
"num_tokens": 885,
"size": 3565
} |
/*
* 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 rose_fbed1fbf_2ba3_46bc_97da_b1df11752358_h
#define rose_fbed1fbf_2ba3_46bc_97da_b1df11752358_h
#include <gslib/utility.h>
#include <ariel/config.h>
#include <ariel/rendersys.h>
#include <ariel/painter.h>
#include <ariel/batch.h>
#include <ariel/texbatch.h>
__ariel_begin__
class rose;
/* this block was used for synchronize with the constant buffer */
struct rose_configs
{
vec4 screen;
float mapscreen[3][4];
/* more.. */
};
struct rose_bind_info_cr
{
vec4 color; /* RGBA */
};
struct rose_bind_info_tex
{
texture2d* img;
vec2 tex;
};
struct vertex_info_cr
{
vec2 pos;
vec4 cr;
};
struct vertex_info_klm_cr
{
vec2 pos;
vec3 klm;
vec4 cr;
};
struct vertex_info_coef_cr
{
vec2 pos;
vec4 coef; /* float3 coef & float tune */
vec4 cr;
};
struct vertex_info_klm_tex
{
vec2 pos;
vec3 klm;
vec2 tex;
};
struct vertex_info_coef_tex
{
vec2 pos;
vec4 coef;
vec2 tex;
};
class rose_batch;
typedef list<rose_bind_info_cr> rose_bind_list_cr;
typedef list<rose_bind_info_tex> rose_bind_list_tex;
typedef vector<rose_batch*> rose_batch_list;
typedef vector<vertex_info_cr> vertex_stream_cr;
typedef vector<vertex_info_klm_cr> vertex_stream_klm_cr;
typedef vector<vertex_info_coef_cr> vertex_stream_cf_cr;
typedef vector<vertex_info_klm_tex> vertex_stream_klm_tex;
typedef vector<vertex_info_coef_tex> vertex_stream_cf_tex;
typedef vector<int> index_stream;
typedef bat_type rose_batch_tag;
class __gs_novtable rose_batch abstract
{
public:
typedef rendersys::vertex_buffer vertex_buffer;
typedef rendersys::index_buffer index_buffer;
public:
rose_batch(int index);
virtual ~rose_batch();
virtual rose_batch_tag get_tag() const = 0;
virtual void create(bat_batch* bat) = 0;
virtual int buffering(rendersys* rsys) = 0;
virtual void draw(rendersys* rsys) = 0;
virtual void tracing() const = 0;
protected:
int _bat_index;
vertex_shader* _vertex_shader;
pixel_shader* _pixel_shader;
vertex_format* _vertex_format;
vertex_buffer* _vertex_buffer;
public:
int get_batch_index() const { return _bat_index; }
void set_vertex_shader(vertex_shader* p) { _vertex_shader = p; }
void set_pixel_shader(pixel_shader* p) { _pixel_shader = p; }
void set_vertex_format(vertex_format* p) { _vertex_format = p; }
void setup_vs_and_ps(rendersys* rsys);
void setup_vf_and_topology(rendersys* rsys, uint topo);
protected:
template<class stream_type>
int template_buffering(stream_type& stm, rendersys* rsys);
};
class rose_fill_batch_cr:
public rose_batch
{
public:
rose_fill_batch_cr(int index): rose_batch(index) {}
rose_batch_tag get_tag() const override { return bf_cr; }
void create(bat_batch* bat) override;
int buffering(rendersys* rsys) override;
void draw(rendersys* rsys) override;
void tracing() const override;
protected:
vertex_stream_cr _vertices;
private:
void create_from_fill(bat_fill_batch* bat);
void create_from_stroke(bat_stroke_batch* bat);
};
class rose_fill_batch_klm_cr:
public rose_batch
{
public:
rose_fill_batch_klm_cr(int index) : rose_batch(index) {}
rose_batch_tag get_tag() const override { return bf_klm_cr; }
void create(bat_batch* bat) override;
int buffering(rendersys* rsys) override;
void draw(rendersys* rsys) override;
void tracing() const override;
protected:
vertex_stream_klm_cr _vertices;
};
class rose_fill_batch_klm_tex:
public rose_batch
{
friend class rose_stroke_batch_assoc_with_klm_tex;
public:
rose_fill_batch_klm_tex(int index, render_sampler_state* ss);
~rose_fill_batch_klm_tex() { destroy(); }
rose_batch_tag get_tag() const override { return bf_klm_tex; }
void create(bat_batch* bat) override;
int buffering(rendersys* rsys) override;
void draw(rendersys* rsys) override;
void tracing() const override;
void destroy();
protected:
vertex_stream_klm_tex _vertices;
tex_batcher _texbatch;
render_sampler_state* _sstate;
shader_resource_view* _srv;
render_texture2d* _tex;
private:
void create_from_fill(bat_fill_batch* bat);
void create_from_stroke(bat_stroke_batch* bat);
};
class rose_stroke_batch_coef_cr:
public rose_batch
{
public:
rose_stroke_batch_coef_cr(int index) : rose_batch(index) {}
rose_batch_tag get_tag() const override { return bs_coef_cr; }
void create(bat_batch* bat) override;
int buffering(rendersys* rsys) override;
void draw(rendersys* rsys) override;
void tracing() const override;
protected:
vertex_stream_cf_cr _vertices;
};
class rose_stroke_batch_coef_tex:
public rose_batch
{
public:
rose_stroke_batch_coef_tex(int index, render_sampler_state* ss);
~rose_stroke_batch_coef_tex() { destroy(); }
rose_batch_tag get_tag() const override { return bs_coef_tex; }
void create(bat_batch* bat) override;
int buffering(rendersys* rsys) override;
void draw(rendersys* rsys) override;
void tracing() const override;
void destroy();
protected:
vertex_stream_cf_tex _vertices;
tex_batcher _texbatch;
render_sampler_state* _sstate;
shader_resource_view* _srv;
render_texture2d* _tex;
protected:
void create_vertices(bat_batch* bat);
void create_vertices(bat_lines& lines, const tex_batcher& bat);
};
class rose_stroke_batch_assoc_with_klm_tex:
public rose_stroke_batch_coef_tex
{
public:
rose_stroke_batch_assoc_with_klm_tex(int index, rose_fill_batch_klm_tex* assoc);
~rose_stroke_batch_assoc_with_klm_tex();
void create(bat_batch* bat) override;
int buffering(rendersys* rsys) override;
protected:
rose_fill_batch_klm_tex* _assoc;
protected:
void create_vertices(bat_batch* bat);
};
class rose_bindings
{
public:
rose_bind_list_cr& get_cr_bindings() { return _cr_bindings; }
rose_bind_list_tex& get_tex_bindings() { return _tex_bindings; }
void clear_binding_cache();
protected:
rose_bind_list_cr _cr_bindings;
rose_bind_list_tex _tex_bindings;
};
class graphics_obj_entity:
public loop_blinn_processor
{
public:
graphics_obj_entity(float w, float h) : loop_blinn_processor(w, h) {}
void proceed_fill(const painter_path& path) { __super::proceed(path); }
void proceed_stroke(const painter_path& path);
protected:
int create_from_path(const painter_path& path, int start);
struct path_seg
{
lb_line* first;
lb_line* last;
path_seg() { first = last = nullptr; }
};
void add_line_seg(path_seg& seg, const painter_path::line_to_node* node);
void add_quad_seg(path_seg& seg, const painter_node* node1, const painter_path::quad_to_node* node2);
void add_cubic_seg(path_seg& seg, const painter_node* node1, const painter_path::cubic_to_node* node2);
};
class graphics_obj:
public std::shared_ptr<graphics_obj_entity>
{
public:
graphics_obj(float w, float h);
};
extern void rose_paint_non_picture_brush(graphics_obj& gfx, rose_bindings& bindings, const painter_brush& brush);
extern void rose_paint_solid_brush(graphics_obj& gfx, rose_bind_list_cr& bind_cache, const painter_brush& brush);
extern void rose_paint_picture_brush(graphics_obj& gfx, const rectf& bound, rose_bind_list_tex& bind_cache, const painter_brush& brush);
extern void rose_paint_pen(graphics_obj& gfx, const painter_path& path, rose_bindings& bindings, const painter_pen& pen);
extern void rose_paint_solid_pen(graphics_obj& gfx, rose_bind_list_cr& bind_cache, const painter_pen& pen);
extern void rose_paint_picture_pen(graphics_obj& gfx, const rectf& bound, rose_bind_list_tex& bind_cache, const painter_pen& pen);
/* more to come. */
class rose:
public painter
{
public:
typedef render_constant_buffer constant_buffer;
typedef render_sampler_state sampler_state;
typedef list<graphics_obj> graphics_obj_cache;
public:
rose();
virtual ~rose();
virtual void resize(int w, int h) override {}
virtual void draw_path(const painter_path& path) override;
virtual void on_draw_begin() override;
virtual void on_draw_end() override;
public:
void setup(rendersys* rsys);
rendersys* get_rendersys() const { return _rsys; }
void fill_non_picture_graphics_obj(graphics_obj& gfx, uint brush_tag);
bat_batch* fill_picture_graphics_obj(graphics_obj& gfx);
void stroke_graphics_obj(graphics_obj& gfx, uint pen_tag);
protected:
template<class _addline>
void meta_stroke_graphics_obj(graphics_obj& gfx, _addline fn_add);
protected:
rendersys* _rsys;
rose_configs _cfgs;
batch_processor _bp;
rose_batch_list _batches;
rose_bindings _bindings;
graphics_obj_cache _gocache;
float _nextz;
protected:
void setup_configs();
void prepare_fill(const painter_path& path, const painter_brush& brush);
void prepare_picture_fill(const painter_path& path, const painter_brush& brush);
void prepare_stroke(const painter_path& path, const painter_pen& pen);
rose_batch* create_fill_batch_cr(int index);
rose_batch* create_fill_batch_klm_cr(int index);
rose_batch* create_fill_batch_klm_tex(int index);
rose_batch* create_stroke_batch_cr(int index);
rose_batch* create_stroke_batch_tex(int index);
rose_batch* create_stroke_batch_assoc(int index, rose_fill_batch_klm_tex* assoc);
void clear_batches();
void prepare_batches();
void draw_batches();
#if use_rendersys_d3d_11
protected:
void initialize();
void destroy_miscs();
sampler_state* acquire_default_sampler_state();
protected:
vertex_shader* _vsf_cr;
vertex_shader* _vsf_klm_cr;
vertex_shader* _vsf_klm_tex;
pixel_shader* _psf_cr;
pixel_shader* _psf_klm_cr;
pixel_shader* _psf_klm_tex;
vertex_format* _vf_cr;
vertex_format* _vf_klm_cr;
vertex_format* _vf_klm_tex;
vertex_shader* _vss_coef_cr;
vertex_shader* _vss_coef_tex;
pixel_shader* _pss_coef_cr;
pixel_shader* _pss_coef_tex;
vertex_format* _vf_coef_cr;
vertex_format* _vf_coef_tex;
sampler_state* _sampler_state;
constant_buffer* _cb_configs;
uint _cb_config_slot;
#endif
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.718687207,
"avg_line_length": 30.6256410256,
"ext": "h",
"hexsha": "f345a188a1be66b410e88d483aaa0bd74382897a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/ariel/rose.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/ariel/rose.h",
"max_line_length": 136,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/ariel/rose.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": 2945,
"size": 11944
} |
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <cconfigspace.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#define NUM_SAMPLES 10000
static void test_create_normal_distribution() {
ccs_distribution_t distrib = NULL;
ccs_result_t err = CCS_SUCCESS;
int32_t refcount;
ccs_object_type_t otype;
ccs_distribution_type_t dtype;
ccs_scale_type_t stype;
ccs_numeric_type_t data_type;
ccs_numeric_t quantization;
ccs_float_t mu, sigma;
ccs_interval_t interval;
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
1.0,
2.0,
CCS_LINEAR,
CCSF(0.0),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_object_get_type(distrib, &otype);
assert( err == CCS_SUCCESS );
assert( otype == CCS_DISTRIBUTION );
err = ccs_distribution_get_type(distrib, &dtype);
assert( err == CCS_SUCCESS );
assert( dtype == CCS_NORMAL );
err = ccs_distribution_get_data_types(distrib, &data_type);
assert( err == CCS_SUCCESS );
assert( data_type == CCS_NUM_FLOAT );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_FLOAT );
assert( interval.lower.f == -CCS_INFINITY );
assert( interval.lower_included == CCS_FALSE );
assert( interval.upper.f == CCS_INFINITY );
assert( interval.upper_included == CCS_FALSE );
err = ccs_normal_distribution_get_parameters(distrib, &mu, &sigma, &stype, &quantization);
assert( err == CCS_SUCCESS );
assert( mu == 1.0 );
assert( sigma == 2.0 );
assert( stype == CCS_LINEAR );
assert( quantization.f == 0.0 );
err = ccs_object_get_refcount(distrib, &refcount);
assert( err == CCS_SUCCESS );
assert( refcount == 1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
}
static void test_create_normal_distribution_errors() {
ccs_distribution_t distrib = NULL;
ccs_result_t err = CCS_SUCCESS;
// check wrong data_type
err = ccs_create_normal_distribution(
(ccs_numeric_type_t)CCS_STRING,
1.0,
2.0,
CCS_LINEAR,
CCSF(0.0),
&distrib);
assert( err == -CCS_INVALID_TYPE );
// check wrong data_type
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
1.0,
2.0,
(ccs_scale_type_t)0xdeadbeef,
CCSF(0.0),
&distrib);
assert( err == -CCS_INVALID_SCALE );
// check wrong quantization
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
1.0,
2.0,
CCS_LINEAR,
CCSF(-1.0),
&distrib);
assert( err == -CCS_INVALID_VALUE );
// check wrong pointer
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
1.0,
2.0,
CCS_LINEAR,
CCSF(0.0),
NULL);
assert( err == -CCS_INVALID_VALUE );
}
static void to_float(ccs_numeric_t * values, size_t length) {
for (size_t i = 0; i < length; i++) {
values[i].f = values[i].i;
}
}
static void to_log(ccs_numeric_t * values, size_t length) {
for (size_t i = 0; i < length; i++) {
values[i].f = log(values[i].f);
}
}
static void test_normal_distribution_int() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 1;
const ccs_float_t sigma = 2;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_INTEGER,
mu,
sigma,
CCS_LINEAR,
CCSI(0),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_INTEGER );
assert( interval.lower.i == CCS_INT_MIN );
assert( interval.lower_included == CCS_TRUE );
assert( interval.upper.i == CCS_INT_MAX );
assert( interval.upper_included == CCS_TRUE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
to_float(samples, num_samples);
mean = gsl_stats_mean((double*)samples, 1, num_samples);
assert( mean < mu + 0.1 );
assert( mean > mu - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, mu);
assert( sig < sigma + 0.1 );
assert( sig > sigma - 0.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_float() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 1;
const ccs_float_t sigma = 2;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
mu,
sigma,
CCS_LINEAR,
CCSF(0.0),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_FLOAT );
assert( interval.lower.f == -CCS_INFINITY );
assert( interval.lower_included == CCS_FALSE );
assert( interval.upper.f == CCS_INFINITY );
assert( interval.upper_included == CCS_FALSE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
mean = gsl_stats_mean((double*)samples, 1, num_samples);
assert( mean < mu + 0.1 );
assert( mean > mu - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, mu);
assert( sig < sigma + 0.1 );
assert( sig > sigma - 0.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_int_log() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 1;
const ccs_float_t sigma = 2;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
double tmean, tsigma, alpha, zee, pdfa;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_INTEGER,
mu,
sigma,
CCS_LOGARITHMIC,
CCSI(0),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_INTEGER );
assert( interval.lower.i == 1 );
assert( interval.lower_included == CCS_TRUE );
assert( interval.upper.i == CCS_INT_MAX );
assert( interval.upper_included == CCS_TRUE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
to_float(samples, num_samples);
to_log(samples, num_samples);
mean = gsl_stats_mean((double*)samples, 1, num_samples);
// cutoff at 0.0 to have exp(v) >= 1
// see https://en.wikipedia.org/wiki/Truncated_normal_distribution
alpha = (log(0.5) - mu)/sigma;
zee = (1.0 - gsl_cdf_ugaussian_P(alpha));
pdfa = gsl_ran_ugaussian_pdf(alpha);
tmean = mu + pdfa * sigma / zee;
assert( mean < tmean + 0.1 );
assert( mean > tmean - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, tmean);
tsigma = sqrt( sigma * sigma * ( 1.0 + alpha * pdfa / zee - ( pdfa * pdfa )/( zee * zee ) ) );
assert( sig < tsigma + 0.1 );
assert( sig > tsigma - 1.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_float_log() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 1;
const ccs_float_t sigma = 2;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
mu,
sigma,
CCS_LOGARITHMIC,
CCSF(0.0),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_FLOAT );
assert( interval.lower.f == 0.0 );
assert( interval.lower_included == CCS_FALSE );
assert( interval.upper.f == CCS_INFINITY );
assert( interval.upper_included == CCS_FALSE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
to_log(samples, num_samples);
mean = gsl_stats_mean((double*)samples, 1, num_samples);
assert( mean < mu + 0.1 );
assert( mean > mu - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, mu);
assert( sig < sigma + 0.1 );
assert( sig > sigma - 0.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_int_quantize() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 1;
const ccs_float_t sigma = 2;
const ccs_int_t q = 2L;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_INTEGER,
mu,
sigma,
CCS_LINEAR,
CCSI(q),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_INTEGER );
assert( interval.lower.i == (CCS_INT_MIN/q)*q );
assert( interval.lower_included == CCS_TRUE );
assert( interval.upper.i == (CCS_INT_MAX/q)*q );
assert( interval.upper_included == CCS_TRUE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
to_float(samples, num_samples);
mean = gsl_stats_mean((double*)samples, 1, num_samples);
assert( mean < mu + 0.1 );
assert( mean > mu - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, mu);
assert( sig < sigma + 0.1 );
assert( sig > sigma - 0.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_float_quantize() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 1;
const ccs_float_t sigma = 2;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
mu,
sigma,
CCS_LINEAR,
CCSF(0.2),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_FLOAT );
assert( interval.lower.f == -CCS_INFINITY );
assert( interval.lower_included == CCS_FALSE );
assert( interval.upper.f == CCS_INFINITY );
assert( interval.upper_included == CCS_FALSE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
mean = gsl_stats_mean((double*)samples, 1, num_samples);
assert( mean < mu + 0.1 );
assert( mean > mu - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, mu);
assert( sig < sigma + 0.1 );
assert( sig > sigma - 0.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_int_log_quantize() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 3;
const ccs_float_t sigma = 2;
const ccs_int_t quantize = 2L;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
double tmean, tsigma, alpha, zee, pdfa;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_INTEGER,
mu,
sigma,
CCS_LOGARITHMIC,
CCSI(quantize),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_INTEGER );
assert( interval.lower.i == quantize );
assert( interval.lower_included == CCS_TRUE );
assert( interval.upper.i == (CCS_INT_MAX/quantize)*quantize );
assert( interval.upper_included == CCS_TRUE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
to_float(samples, num_samples);
to_log(samples, num_samples);
mean = gsl_stats_mean((double*)samples, 1, num_samples);
// cutoff at 0.0 to have exp(v) >= 1
// see https://en.wikipedia.org/wiki/Truncated_normal_distribution
alpha = (log(0.5*quantize) - mu)/sigma;
zee = (1.0 - gsl_cdf_ugaussian_P(alpha));
pdfa = gsl_ran_ugaussian_pdf(alpha);
tmean = mu + pdfa * sigma / zee;
assert( mean < tmean + 0.1 );
assert( mean > tmean - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, tmean);
tsigma = sqrt( sigma * sigma * ( 1.0 + alpha * pdfa / zee - ( pdfa * pdfa )/( zee * zee ) ) );
assert( sig < tsigma + 0.1 );
assert( sig > tsigma - 1.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_float_log_quantize() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 3;
const ccs_float_t sigma = 2;
const ccs_float_t quantization = 2.0;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
double tmean, tsigma, alpha, zee, pdfa;
ccs_interval_t interval;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
mu,
sigma,
CCS_LOGARITHMIC,
CCSF(quantization),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_FLOAT );
assert( interval.lower.f == quantization );
assert( interval.lower_included == CCS_TRUE );
assert( interval.upper.f == CCS_INFINITY );
assert( interval.upper_included == CCS_FALSE );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
to_log(samples, num_samples);
mean = gsl_stats_mean((double*)samples, 1, num_samples);
// cutoff at log(quantization/2.0) to have quantized(exp(v)) >= quantization
// see https://en.wikipedia.org/wiki/Truncated_normal_distribution
alpha = (log(quantization*0.5) - mu)/sigma;
zee = (1.0 - gsl_cdf_ugaussian_P(alpha));
pdfa = gsl_ran_ugaussian_pdf(alpha);
tmean = mu + pdfa * sigma / zee;
assert( mean < tmean + 0.1 );
assert( mean > tmean - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, tmean);
tsigma = sqrt( sigma * sigma * ( 1.0 + alpha * pdfa / zee - ( pdfa * pdfa )/( zee * zee ) ) );
assert( sig < tsigma + 0.1 );
assert( sig > tsigma - 0.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_strided_samples() {
ccs_distribution_t distrib1 = NULL;
ccs_distribution_t distrib2 = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu1 = 1;
const ccs_float_t sigma1 = 2;
const ccs_float_t mu2 = 0;
const ccs_float_t sigma2 = 2;
ccs_numeric_t samples[NUM_SAMPLES*2];
double mean, sig;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
mu1,
sigma1,
CCS_LINEAR,
CCSF(0.0),
&distrib1);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
mu2,
sigma2,
CCS_LINEAR,
CCSF(0.0),
&distrib2);
assert( err == CCS_SUCCESS );
err = ccs_distribution_strided_samples(distrib1, rng, num_samples, 2, samples);
assert( err == CCS_SUCCESS );
err = ccs_distribution_strided_samples(distrib2, rng, num_samples, 2, &(samples[0]) + 1);
assert( err == CCS_SUCCESS );
mean = gsl_stats_mean((double*)samples, 2, num_samples);
assert( mean < mu1 + 0.1 );
assert( mean > mu1 - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 2, num_samples, mu1);
assert( sig < sigma1 + 0.1 );
assert( sig > sigma1 - 0.1 );
mean = gsl_stats_mean((double*)samples + 1, 2, num_samples);
assert( mean < mu2 + 0.1 );
assert( mean > mu2 - 0.1 );
sig = gsl_stats_sd_m((double*)samples + 1, 2, num_samples, mu2);
assert( sig < sigma2 + 0.1 );
assert( sig > sigma2 - 0.1 );
err = ccs_release_object(distrib1);
assert( err == CCS_SUCCESS );
err = ccs_release_object(distrib2);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_normal_distribution_soa_samples() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
const ccs_float_t mu = 1;
const ccs_float_t sigma = 2;
ccs_numeric_t samples[NUM_SAMPLES];
double mean, sig;
ccs_interval_t interval;
ccs_numeric_t *p_samples;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
mu,
sigma,
CCS_LINEAR,
CCSF(0.0),
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_FLOAT );
assert( interval.lower.f == -CCS_INFINITY );
assert( interval.lower_included == CCS_FALSE );
assert( interval.upper.f == CCS_INFINITY );
assert( interval.upper_included == CCS_FALSE );
p_samples = &(samples[0]);
err = ccs_distribution_soa_samples(distrib, rng, num_samples, &p_samples);
assert( err == CCS_SUCCESS );
mean = gsl_stats_mean((double*)samples, 1, num_samples);
assert( mean < mu + 0.1 );
assert( mean > mu - 0.1 );
sig = gsl_stats_sd_m((double*)samples, 1, num_samples, mu);
assert( sig < sigma + 0.1 );
assert( sig > sigma - 0.1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
int main() {
ccs_init();
test_create_normal_distribution();
test_create_normal_distribution_errors();
test_normal_distribution_int();
test_normal_distribution_int_log();
test_normal_distribution_int_quantize();
test_normal_distribution_int_log_quantize();
test_normal_distribution_float();
test_normal_distribution_float_log();
test_normal_distribution_float_quantize();
test_normal_distribution_float_log_quantize();
test_normal_distribution_strided_samples();
test_normal_distribution_soa_samples();
ccs_fini();
return 0;
}
| {
"alphanum_fraction": 0.6901977021,
"avg_line_length": 29.5443425076,
"ext": "c",
"hexsha": "053b068166c1dec2976086f9cdfb4818ab1c25a7",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z",
"max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "deephyper/CCS",
"max_forks_repo_path": "tests/test_normal_distribution.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "deephyper/CCS",
"max_issues_repo_path": "tests/test_normal_distribution.c",
"max_line_length": 95,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "deephyper/CCS",
"max_stars_repo_path": "tests/test_normal_distribution.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z",
"num_tokens": 5309,
"size": 19322
} |
//#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp.h>
static double fun(double x)
{
return x + cos(x*x);
}
int main (void)
{
const double a = 1.0;
const double b = 10.0;
const int steps = 10;
double xi, yi, x[100], y[100], dx;
FILE *input, *output;
int i;
input = fopen("wartosci.txt", "w");
output = fopen("gsl_interp_steffen.txt", "w");
dx = (b-a) / (double) steps;
for (i = 0; i <= steps; ++i) {
x[i] = a + (double)i * dx + 0.5 * sin((double)i * dx);
y[i] = fun(x[i]);
fprintf (input,"%g %g\n", x[i], y[i]);
}
{
gsl_interp_accel *acc
= gsl_interp_accel_alloc ();
gsl_spline *spline
= gsl_spline_alloc (gsl_interp_steffen, steps + 1);
gsl_spline_init (spline, x, y, steps + 1);
for (xi = a; xi <= b; xi += 0.01) {
yi = gsl_spline_eval (spline, xi, acc);
fprintf (output,"%g %g\n", xi, yi);
}
gsl_spline_free (spline);
gsl_interp_accel_free(acc);
}
return 0;
}
//Porownanie roznych interpolacji
//Opisanie komend, screeny
//https://stackoverflow.com/questions/10792015/gnuplot-plotting-multiple-line-graphs
//https://stackoverflow.com/questions/40296851/gnuplot-log-plot-y-axis
//http://lowrank.net/gnuplot/plot3d2-e.html
//http://gnuplot-surprising.blogspot.com/2012/05/how-to-pick-out-maximum-and-minimum.html
//http://gnuplot.sourceforge.net/docs_4.2/node237.html
//http://gnuplot.sourceforge.net/demo/stats.html
// stats "dane2.dat" u 3 nooutput
// set label 1 "Maximun" at STATS_pos_max, STATS_max offset 1,-0.5
// set label 2 "Minimun" at STATS_pos_min, STATS_min offset 1,0.5
// splot "dane2.dat" w p pt 3 lc rgb"#ff0000" notitle, \
// STATS_min w l lc rgb"#00ffff" notitle, \
// STATS_max w l lc rgb"#00ffff" notitle
stats "dane2.dat" u 1:3 nooutput
a = STATS_pos_max_y
stats "dane2.dat" u 2:3 nooutput
b = STATS_pos_max_y
stats "dane2.dat" u 3 nooutput
c = STATS_max
set arrow 1 from -5, -2.1, c+5 to a,b,c fill
splot "dane2.dat" w p pt 3 lc rgb"#ff0000" notitle, \
STATS_min w l lc rgb"#00ffff" notitle, \
STATS_max w l lc rgb"#00ffff" notitle
n=100
max=3.
min=-3.
width=(max-min)/n
hist(x,width)=width*floor(x/width)+width/2.0
set xrange [min:max]
set yrange[-5:5]
set offset graph 0.05,0.05,0.05,0.0
set xtics min,(max-min)/5,max
set boxwidth width*0.82
set tics out nomirror
set xlabel "x"
set ylabel "Frequency"
plot 2*cos(x*sin(x)) smooth freq w boxes lc rgb"blue", \
sin (x**5) lt rgb"#00ff00", \
3*sin(x) lt rgb"red", \
"fun1.txt" with yerrorbars lt rgb"red" | {
"alphanum_fraction": 0.6538607836,
"avg_line_length": 26.8265306122,
"ext": "c",
"hexsha": "5bcf894dab5d501d101b6239f8dd34fcce255438",
"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": "5fca38f9856cb17e129007eb3ad50112520af16e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "komilll/mownit_linux",
"max_forks_repo_path": "zad2/interpolacja.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e",
"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": "komilll/mownit_linux",
"max_issues_repo_path": "zad2/interpolacja.c",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "komilll/mownit_linux",
"max_stars_repo_path": "zad2/interpolacja.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 931,
"size": 2629
} |
#ifndef _PARRSB_H_
#define _PARRSB_H_
#include <gslib.h>
typedef struct {
/* General options */
int global_partitioner; // -1 - None, 0 - RSB, 1 - RCB, 2 - RIB (Default: 0)
int local_partitioner; // -1 - None, 0 - RSB, 1 - RCB, 2 - RIB (Default: -1)
int debug_level; // 0, 1, 2, .. etc (Default: 0)
int print_timing_info; // 0 or 1 (Default: 0)
/* RSB specific */
int rsb_algo; // 0 - Lanczos, 1 - MG (Default: 0)
int rsb_prepartition; // 0 - None, 1 - RCB , 2 - RIB (Default: 1)
int rsb_grammian; // 0 or 1 (Default: 1)
} parRSB_options;
extern parRSB_options parrsb_default_options;
#define fparRSB_partMesh FORTRAN_UNPREFIXED(fparrsb_partmesh, FPARRSB_PARTMESH)
void fparRSB_partMesh(int *part, int *seq, long long *vtx, double *coord,
int *nel, int *nve, int *options, int *comm, int *err);
int parRSB_partMesh(int *part, int *seq, long long *vtx, double *coord, int nel,
int nv, parRSB_options *options, MPI_Comm comm);
#define fparRSB_findConnectivity \
FORTRAN_UNPREFIXED(fparrsb_findconnectivity, FPARRSB_FINDCONNECTIVITY)
void fparRSB_findConnectivity(long long *vertexId, double *coord, int *nel,
int *nDim, long long *periodicInfo,
int *nPeriodicFaces, double *tol, MPI_Fint *fcomm,
int *verbose, int *err);
int parRSB_findConnectivity(long long *vertexid, double *coord, int nel,
int nDim, long long *periodicInfo,
int nPeriodicFaces, double tol, MPI_Comm comm,
int verbose);
#endif
| {
"alphanum_fraction": 0.5998828354,
"avg_line_length": 41.6341463415,
"ext": "h",
"hexsha": "412f69437c84f83ff31d8a84a5e13760ec97fe30",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-09-10T20:12:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-10T20:12:48.000Z",
"max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "neams-th-coe/nekRS",
"max_forks_repo_path": "3rd_party/nek5000_parRSB/src/parRSB.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb",
"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": "neams-th-coe/nekRS",
"max_issues_repo_path": "3rd_party/nek5000_parRSB/src/parRSB.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "ffc02bca33ece6ba3330c4ee24565b1c6b5f7242",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "RonRahaman/nekRS",
"max_stars_repo_path": "3rd_party/nek5000_parRSB/src/parRSB.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-06T16:16:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-01-06T16:16:08.000Z",
"num_tokens": 500,
"size": 1707
} |
/**
*
* @file core_slauum.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Julien Langou
* @author Henricus Bouwmeester
* @author Mathieu Faverge
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:46 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_slauum - Computes the product U * U' or L' * L, where the triangular
* factor U or L is stored in the upper or lower triangular part of
* the array A.
*
* If UPLO = 'U' or 'u' then the upper triangle of the result is stored,
* overwriting the factor U in A.
* If UPLO = 'L' or 'l' then the lower triangle of the result is stored,
* overwriting the factor L in A.
*
*******************************************************************************
*
* @param[in] uplo
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in] N
* The order of the triangular factor U or L. N >= 0.
*
* @param[in,out] A
* On entry, the triangular factor U or L.
* On exit, if UPLO = 'U', the upper triangle of A is
* overwritten with the upper triangle of the product U * U';
* if UPLO = 'L', the lower triangle of A is overwritten with
* the lower triangle of the product L' * L.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,N).
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_slauum = PCORE_slauum
#define CORE_slauum PCORE_slauum
#endif
void CORE_slauum(PLASMA_enum uplo, int N, float *A, int LDA)
{
LAPACKE_slauum_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, A, LDA );
}
| {
"alphanum_fraction": 0.5658163265,
"avg_line_length": 32.131147541,
"ext": "c",
"hexsha": "166c5ee81acfd749a2feb83b5464aa5f133bebf0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_slauum.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_slauum.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_slauum.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 526,
"size": 1960
} |
#include "ccv_nnc.h"
#include "ccv_nnc_easy.h"
#include "ccv_nnc_internal.h"
#include "ccv_internal.h"
#include "3rdparty/khash/khash.h"
#ifdef HAVE_GSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#else
#include "3rdparty/sfmt/SFMT.h"
#endif
KHASH_MAP_INIT_INT64(ctx, ccv_array_t*)
struct ccv_cnnp_dataframe_s {
int row_count;
int column_size;
int* shuffled_idx;
#ifdef HAVE_GSL
gsl_rng* rng;
#else
sfmt_t sfmt;
#endif
khash_t(ctx)* data_ctx; // The stream context based cache for data entity of columns. This helps us to avoid allocations when iterate through data.
ccv_array_t* derived_column_data;
ccv_cnnp_column_data_t column_data[1];
};
typedef struct {
int stream_type;
int column_idx_size;
int* column_idxs;
ccv_cnnp_column_data_enum_f data_enum;
ccv_cnnp_column_data_deinit_f data_deinit;
void* context;
ccv_cnnp_column_data_context_deinit_f context_deinit;
ccv_cnnp_column_data_map_f map;
} ccv_cnnp_derived_column_data_t;
ccv_cnnp_dataframe_t* ccv_cnnp_dataframe_new(const ccv_cnnp_column_data_t* const column_data, const int column_size, const int row_count)
{
assert(column_size >= 0);
ccv_cnnp_dataframe_t* const dataframe = (ccv_cnnp_dataframe_t*)cccalloc(1, sizeof(ccv_cnnp_dataframe_t) + sizeof(ccv_cnnp_column_data_t) * (column_size - 1));
dataframe->row_count = row_count;
dataframe->column_size = column_size;
dataframe->data_ctx = kh_init(ctx);
if (column_size > 0)
memcpy(dataframe->column_data, column_data, sizeof(ccv_cnnp_column_data_t) * column_size);
return dataframe;
}
void ccv_cnnp_dataframe_shuffle(ccv_cnnp_dataframe_t* const dataframe)
{
assert(dataframe->row_count);
int i;
if (!dataframe->shuffled_idx)
{
dataframe->shuffled_idx = (int*)ccmalloc(sizeof(int) * dataframe->row_count);
for (i = 0; i < dataframe->row_count; i++)
dataframe->shuffled_idx[i] = i;
#ifdef HAVE_GSL
assert(!dataframe->rng);
gsl_rng_env_setup();
dataframe->rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(dataframe->rng, (unsigned long int)dataframe);
#else
sfmt_init_gen_rand(&dataframe->sfmt, (uint32_t)dataframe);
#endif
}
#ifdef HAVE_GSL
gsl_ran_shuffle(dataframe->rng, dataframe->shuffled_idx, dataframe->row_count, sizeof(int));
#else
sfmt_genrand_shuffle(&dataframe->sfmt, dataframe->shuffled_idx, dataframe->row_count, sizeof(int));
#endif
}
int ccv_cnnp_dataframe_row_count(ccv_cnnp_dataframe_t* const dataframe)
{
return dataframe->row_count;
}
int ccv_cnnp_dataframe_add(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_column_data_enum_f data_enum, const int stream_type, ccv_cnnp_column_data_deinit_f data_deinit, void* const context, ccv_cnnp_column_data_context_deinit_f context_deinit)
{
if (!dataframe->derived_column_data)
dataframe->derived_column_data = ccv_array_new(sizeof(ccv_cnnp_derived_column_data_t), 1, 0);
ccv_cnnp_derived_column_data_t column_data = {
.stream_type = stream_type,
.data_enum = data_enum,
.data_deinit = data_deinit,
.context = context,
.context_deinit = context_deinit,
};
ccv_array_push(dataframe->derived_column_data, &column_data);
return dataframe->column_size + dataframe->derived_column_data->rnum - 1;
}
int ccv_cnnp_dataframe_map(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_column_data_map_f map, const int stream_type, ccv_cnnp_column_data_deinit_f data_deinit, const int* const column_idxs, const int column_idx_size, void* const context, ccv_cnnp_column_data_context_deinit_f context_deinit)
{
assert(column_idx_size > 0);
if (!dataframe->derived_column_data)
dataframe->derived_column_data = ccv_array_new(sizeof(ccv_cnnp_derived_column_data_t), 1, 0);
const int column_size = dataframe->column_size + dataframe->derived_column_data->rnum;
int i;
for (i = 0; i < column_idx_size; i++)
{ assert(column_idxs[i] < column_size); }
ccv_cnnp_derived_column_data_t column_data = {
.stream_type = stream_type,
.column_idx_size = column_idx_size,
.column_idxs = (int*)ccmalloc(sizeof(int) * column_idx_size),
.map = map,
.data_deinit = data_deinit,
.context = context,
.context_deinit = context_deinit,
};
memcpy(column_data.column_idxs, column_idxs, sizeof(int) * column_idx_size);
ccv_array_push(dataframe->derived_column_data, &column_data);
return dataframe->column_size + dataframe->derived_column_data->rnum - 1;
}
void* ccv_cnnp_dataframe_column_context(const ccv_cnnp_dataframe_t* const dataframe, const int column_idx)
{
assert(column_idx >= 0);
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
assert(column_idx < column_size);
if (column_idx < dataframe->column_size)
return dataframe->column_data[column_idx].context;
assert(dataframe->derived_column_data);
ccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, column_idx - dataframe->column_size);
return derived_column_data->context;
}
typedef struct {
int flag; // Mark this as cached or not.
uint64_t ctx; // The stream context.
void* data;
} ccv_cnnp_dataframe_data_item_t;
typedef struct {
ccv_nnc_stream_context_t* stream_context;
ccv_nnc_stream_signal_t* signal;
} ccv_cnnp_dataframe_column_ctx_t;
KHASH_MAP_INIT_INT64(iter_ctx, ccv_cnnp_dataframe_column_ctx_t*)
struct ccv_cnnp_dataframe_iter_s {
int idx;
int prefetch_head;
int prefetch_tail;
int column_idx_size;
int fetched_size; // The size of fetched data.
ccv_cnnp_dataframe_t* dataframe;
void**** derived_data; // This is ridiculous, but it is true.
void** fetched_data; // The cache to store fetched data.
khash_t(iter_ctx)* column_ctx; // Column context specific to a stream context. The key will be a parent stream context and value will be child stream context + signal.
ccv_array_t* prefetches; // The prefetch contents.
int* column_idxs;
ccv_cnnp_dataframe_data_item_t cached_data[1]; // The data cached when deriving data.
};
#define INDEX_DATA(iter) ((int*)((iter)->fetched_data))
#define FETCHED_DATA(iter, idx) ((iter)->fetched_data + ((idx) + 1) * (iter)->fetched_size)
ccv_cnnp_dataframe_iter_t* ccv_cnnp_dataframe_iter_new(ccv_cnnp_dataframe_t* const dataframe, const int* const column_idxs, const int column_idx_size)
{
assert(column_idx_size > 0);
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
int i;
for (i = 0; i < column_idx_size; i++)
{ assert(column_idxs[i] < column_size); }
ccv_cnnp_dataframe_iter_t* const iter = (ccv_cnnp_dataframe_iter_t*)cccalloc(1, sizeof(ccv_cnnp_dataframe_iter_t) + sizeof(ccv_cnnp_dataframe_data_item_t) * column_size + sizeof(void*) * (column_idx_size - 1) + sizeof(int) * column_idx_size);
iter->dataframe = dataframe;
iter->prefetch_tail = -1;
iter->column_idx_size = column_idx_size;
iter->column_idxs = (int*)(iter->cached_data + column_size);
memcpy(iter->column_idxs, column_idxs, sizeof(int) * column_idx_size);
// Preallocate fetched data.
iter->fetched_size = 1;
iter->fetched_data = (void**)ccmalloc(sizeof(void*) * (column_size + 1));
return iter;
}
static void _ccv_cnnp_dataframe_enqueue_data(ccv_cnnp_dataframe_t* const dataframe, void* const data, const int column_idx, const uint64_t ctx)
{
if (!data)
return;
khash_t(ctx)* const data_ctx = dataframe->data_ctx;
int ret = 0;
khiter_t k = kh_put(ctx, data_ctx, ctx, &ret);
assert(ret >= 0);
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
assert(column_idx < column_size);
// If ret == 0, the key already exist, we can get the columns directly, otherwise, create and assign back.
ccv_array_t* const columns = (ret == 0) ? kh_val(data_ctx, k) : ccv_array_new(sizeof(ccv_array_t*), column_size, 0);
if (ret != 0)
kh_val(data_ctx, k) = columns;
if (columns->rnum < column_size)
ccv_array_resize(columns, column_size);
ccv_array_t* column = *(ccv_array_t**)ccv_array_get(columns, column_idx);
if (!column)
{
column = ccv_array_new(sizeof(void*), 1, 0);
*(ccv_array_t**)ccv_array_get(columns, column_idx) = column;
}
ccv_array_push(column, &data);
}
static void* _ccv_cnnp_dataframe_dequeue_data(ccv_cnnp_dataframe_t* const dataframe, const int column_idx, ccv_nnc_stream_context_t* const stream_context)
{
const uint64_t ctx = (uint64_t)(uintptr_t)stream_context;
khash_t(ctx)* const data_ctx = dataframe->data_ctx;
khiter_t k = kh_get(ctx, data_ctx, ctx);
if (k == kh_end(data_ctx))
return 0;
ccv_array_t* const columns = kh_val(data_ctx, k);
if (column_idx >= columns->rnum)
return 0;
ccv_array_t* const column = *(ccv_array_t**)ccv_array_get(columns, column_idx);
if (!column || column->rnum == 0)
return 0;
void* const data = *(void**)ccv_array_get(column, column->rnum - 1);
--column->rnum;
return data;
}
static ccv_cnnp_dataframe_column_ctx_t _ccv_cnnp_child_column_ctx_for_stream_type(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_dataframe_iter_t* const iter, const int column_idx, ccv_nnc_stream_context_t* const stream_context, const int stream_type)
{
ccv_cnnp_dataframe_column_ctx_t child_ctx = {
.stream_context = stream_context,
};
if (stream_context && ccv_nnc_stream_context_type(stream_context) != stream_type && stream_type != 0)
{
if (!iter->column_ctx)
iter->column_ctx = kh_init(iter_ctx);
khash_t(iter_ctx)* const column_ctx = iter->column_ctx;
int ret = 0;
khiter_t k = kh_put(iter_ctx, column_ctx, (uint64_t)(uintptr_t)stream_context, &ret);
assert(ret >= 0);
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
ccv_cnnp_dataframe_column_ctx_t* const ctx = (ret == 0) ? kh_val(column_ctx, k) : cccalloc(column_size, sizeof(ccv_cnnp_dataframe_column_ctx_t));
if (ret != 0)
kh_val(column_ctx, k) = ctx;
if (!ctx[column_idx].stream_context)
ctx[column_idx].stream_context = ccv_nnc_stream_context_new(stream_type);
if (!ctx[column_idx].signal)
ctx[column_idx].signal = ccv_nnc_stream_signal_new(stream_type);
child_ctx = ctx[column_idx];
}
return child_ctx;
}
static void _ccv_cnnp_dataframe_column_data(ccv_cnnp_dataframe_t* const dataframe, ccv_cnnp_dataframe_iter_t* const iter, ccv_cnnp_dataframe_data_item_t* const cached_data, void** const fetched_data, const int* const row_idxs, const int row_size, const int column_idx, const int cached_step, ccv_nnc_stream_context_t* const stream_context)
{
int i;
if (cached_data[column_idx * cached_step].flag)
{
for (i = 1; i < row_size; i++)
{ assert(cached_data[i + column_idx * cached_step].flag); }
for (i = 0; i < row_size; i++)
fetched_data[i] = cached_data[i + column_idx * cached_step].data;
return;
} else {
for (i = 1; i < row_size; i++)
{ assert(!cached_data[i + column_idx * cached_step].flag); }
for (i = 0; i < row_size; i++)
fetched_data[i] = _ccv_cnnp_dataframe_dequeue_data(dataframe, column_idx, stream_context);
}
if (column_idx >= dataframe->column_size)
{
assert(dataframe->derived_column_data);
const int derived_column_idx = column_idx - dataframe->column_size;
const ccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, derived_column_idx);
ccv_cnnp_dataframe_column_ctx_t child_ctx = _ccv_cnnp_child_column_ctx_for_stream_type(dataframe, iter, column_idx, stream_context, derived_column_data->stream_type);
const int column_idx_size = derived_column_data->column_idx_size;
if (derived_column_data->map)
{
int i;
if (!iter->derived_data)
iter->derived_data = (void****)cccalloc(dataframe->derived_column_data->rnum, sizeof(void***));
if (!iter->derived_data[derived_column_idx])
iter->derived_data[derived_column_idx] = (void***)cccalloc(derived_column_data->column_idx_size, sizeof(void**));
void*** const derived_data = iter->derived_data[derived_column_idx];
for (i = 0; i < column_idx_size; i++)
{
derived_data[i] = FETCHED_DATA(iter, derived_column_data->column_idxs[i]);
_ccv_cnnp_dataframe_column_data(dataframe, iter, cached_data, derived_data[i], row_idxs, row_size, derived_column_data->column_idxs[i], cached_step, stream_context);
}
derived_column_data->map(derived_data, derived_column_data->column_idx_size, row_size, fetched_data, derived_column_data->context, child_ctx.stream_context);
} else
derived_column_data->data_enum(column_idx, row_idxs, row_size, fetched_data, derived_column_data->context, child_ctx.stream_context);
if (child_ctx.stream_context != stream_context)
{
ccv_nnc_stream_context_emit_signal(child_ctx.stream_context, child_ctx.signal);
ccv_nnc_stream_context_wait_signal(stream_context, child_ctx.signal);
}
} else {
const ccv_cnnp_column_data_t* const column_data = dataframe->column_data + column_idx;
ccv_cnnp_dataframe_column_ctx_t child_ctx = _ccv_cnnp_child_column_ctx_for_stream_type(dataframe, iter, column_idx, stream_context, column_data->stream_type);
column_data->data_enum(column_idx, row_idxs, row_size, fetched_data, column_data->context, child_ctx.stream_context);
if (child_ctx.stream_context != stream_context)
{
ccv_nnc_stream_context_emit_signal(child_ctx.stream_context, child_ctx.signal);
ccv_nnc_stream_context_wait_signal(stream_context, child_ctx.signal);
}
}
for (i = 0; i < row_size; i++)
{
cached_data[i + column_idx * cached_step].flag = 1;
cached_data[i + column_idx * cached_step].ctx = (uint64_t)(uintptr_t)stream_context;
cached_data[i + column_idx * cached_step].data = fetched_data[i];
}
}
int ccv_cnnp_dataframe_iter_next(ccv_cnnp_dataframe_iter_t* const iter, void** const data_ref, const int column_idx_size, ccv_nnc_stream_context_t* const stream_context)
{
ccv_cnnp_dataframe_t* const dataframe = iter->dataframe;
assert(column_idx_size <= iter->column_idx_size);
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
int i;
// Push existing data back to reusable state (note, these may not be reused immediately because they may be on a different stream context).
for (i = 0; i < column_size; i++)
if (iter->cached_data[i].flag)
{
_ccv_cnnp_dataframe_enqueue_data(dataframe, iter->cached_data[i].data, i, iter->cached_data[i].ctx);
iter->cached_data[i].flag = 0;
iter->cached_data[i].data = 0;
iter->cached_data[i].ctx = 0;
}
const int idx = iter->idx;
if (idx == dataframe->row_count)
return -1;
if (iter->prefetch_tail != -1) // If there is something in prefetch log.
{
ccv_array_t* const prefetches = iter->prefetches;
assert(prefetches);
const int lines = prefetches->rnum / column_size;
if (iter->prefetch_head == iter->prefetch_tail) // Only one item.
iter->prefetch_tail = -1;
ccv_cnnp_dataframe_data_item_t* const cached_data = (ccv_cnnp_dataframe_data_item_t*)ccv_array_get(iter->prefetches, iter->prefetch_head);
for (i = 0; i < column_size; i++)
{
if (!cached_data[i * lines].flag)
continue;
if (cached_data[i * lines].ctx == (uint64_t)(uintptr_t)stream_context) // If match existing stream context.
iter->cached_data[i] = cached_data[i * lines];
else // Recycle
_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[i * lines].data, i, cached_data[i * lines].ctx);
}
++iter->prefetch_head;
assert(prefetches->rnum % column_size == 0);
if (iter->prefetch_head >= lines)
iter->prefetch_head = 0;
}
for (i = 0; i < column_idx_size; i++)
_ccv_cnnp_dataframe_column_data(dataframe, iter, iter->cached_data, data_ref + i, dataframe->shuffled_idx ? dataframe->shuffled_idx + idx : &idx, 1, iter->column_idxs[i], 1, stream_context);
++iter->idx;
return 0;
}
static void _ccv_cnnp_null_prefetches(ccv_cnnp_dataframe_iter_t* const iter)
{
ccv_cnnp_dataframe_t* const dataframe = iter->dataframe;
assert(dataframe);
int i, j;
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
if (iter->prefetch_head <= iter->prefetch_tail)
{
assert(iter->prefetches);
const int lines = iter->prefetches->rnum / column_size;
for (i = iter->prefetch_head; i <= iter->prefetch_tail; i++)
{
ccv_cnnp_dataframe_data_item_t* const cached_data = ccv_array_get(iter->prefetches, i);
for (j = 0; j < column_size; j++)
if (cached_data[j * lines].flag)
_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[j * lines].data, j, cached_data[j * lines].ctx);
}
} else if (iter->prefetch_tail >= 0) { // -1 means no item.
assert(iter->prefetches);
const int lines = iter->prefetches->rnum / column_size;
for (i = iter->prefetch_head; i < lines; i++)
{
ccv_cnnp_dataframe_data_item_t* const cached_data = ccv_array_get(iter->prefetches, i);
for (j = 0; j < column_size; j++)
if (cached_data[j * lines].flag)
_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[j * lines].data, j, cached_data[j * lines].ctx);
}
for (i = 0; i <= iter->prefetch_tail; i++)
{
ccv_cnnp_dataframe_data_item_t* const cached_data = ccv_array_get(iter->prefetches, i);
for (j = 0; j < column_size; j++)
if (cached_data[j * lines].flag)
_ccv_cnnp_dataframe_enqueue_data(dataframe, cached_data[j * lines].data, j, cached_data[j * lines].ctx);
}
}
iter->prefetch_head = 0;
iter->prefetch_tail = -1;
}
static void _ccv_cnnp_prefetch_cached_data(ccv_cnnp_dataframe_iter_t* const iter, ccv_cnnp_dataframe_data_item_t* const cached_data, const int idx, const int max_to_prefetch, ccv_nnc_stream_context_t* const stream_context)
{
ccv_cnnp_dataframe_t* const dataframe = iter->dataframe;
assert(dataframe);
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
assert(iter->prefetches);
const int lines = iter->prefetches->rnum / column_size;
int i, j;
// Reset
for (i = 0; i < column_size; i++)
for (j = 0; j < max_to_prefetch; j++)
{
cached_data[j + i * lines].flag = 0;
cached_data[j + i * lines].data = 0;
cached_data[j + i * lines].ctx = 0;
}
if (iter->fetched_size < max_to_prefetch)
{
iter->fetched_data = ccrealloc(iter->fetched_data, sizeof(void*) * max_to_prefetch * (column_size + 1));
iter->fetched_size = max_to_prefetch;
}
if (dataframe->shuffled_idx)
for (i = 0; i < iter->column_idx_size; i++)
_ccv_cnnp_dataframe_column_data(dataframe, iter, cached_data, FETCHED_DATA(iter, iter->column_idxs[i]), dataframe->shuffled_idx + idx, max_to_prefetch, iter->column_idxs[i], lines, stream_context);
else {
for (i = 0; i < max_to_prefetch; i++)
INDEX_DATA(iter)[i] = idx + i;
for (i = 0; i < iter->column_idx_size; i++)
_ccv_cnnp_dataframe_column_data(dataframe, iter, cached_data, FETCHED_DATA(iter, iter->column_idxs[i]), INDEX_DATA(iter), max_to_prefetch, iter->column_idxs[i], lines, stream_context);
}
}
int ccv_cnnp_dataframe_iter_prefetch(ccv_cnnp_dataframe_iter_t* const iter, const int prefetch_count, ccv_nnc_stream_context_t* const stream_context)
{
ccv_cnnp_dataframe_t* const dataframe = iter->dataframe;
assert(dataframe);
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
int i, j;
assert(iter->idx <= dataframe->row_count);
int lines, next, max_to_prefetch;
if (iter->prefetch_tail == -1)
{
if (iter->idx == dataframe->row_count)
return -1; // Cannot be done.
max_to_prefetch = ccv_min(dataframe->row_count - iter->idx, prefetch_count);
if (!iter->prefetches)
{
iter->prefetches = ccv_array_new(sizeof(ccv_cnnp_dataframe_data_item_t), max_to_prefetch * column_size, 0);
ccv_array_resize(iter->prefetches, max_to_prefetch * column_size);
}
iter->prefetch_tail = iter->prefetch_head = 0; // Advance!
next = iter->idx;
lines = iter->prefetches->rnum / column_size;
// Reset to enough space.
if (lines < max_to_prefetch)
{
ccv_array_resize(iter->prefetches, max_to_prefetch * column_size);
lines = max_to_prefetch;
}
} else {
assert(iter->prefetches);
ccv_array_t* const prefetches = iter->prefetches;
assert(prefetches->rnum % column_size == 0);
lines = prefetches->rnum / column_size;
const int prefetched = iter->prefetch_tail >= iter->prefetch_head ? iter->prefetch_tail - iter->prefetch_head + 1: lines - iter->prefetch_head + iter->prefetch_tail + 1;
if (iter->idx + prefetched == dataframe->row_count) // Nothing to prefetch.
return -1;
max_to_prefetch = ccv_min(dataframe->row_count - (iter->idx + prefetched), prefetch_count);
// Not enough space, need to resize.
if (prefetched + max_to_prefetch > lines)
{
const int new_lines = prefetched + max_to_prefetch;
ccv_array_resize(prefetches, new_lines * column_size);
// These are overlap moves, have to make sure start from the end and move it up to the beginning.
if (iter->prefetch_head > iter->prefetch_tail)
{
const int offset = new_lines - lines;
for (i = column_size - 1; i >= 0; i--)
{
for (j = lines - 1; j >= iter->prefetch_head; j--)
*(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + offset + i * new_lines) = *(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * lines);
for (j = iter->prefetch_tail; j >= 0; j--)
*(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * new_lines) = *(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * lines);
}
iter->prefetch_head += offset;
} else {
for (i = column_size - 1; i >= 0; i--)
for (j = iter->prefetch_tail; j >= iter->prefetch_head; j--)
*(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * new_lines) = *(ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, j + i * lines);
}
lines = new_lines;
}
++iter->prefetch_tail; // Move to the next ready tail.
if (iter->prefetch_tail >= lines)
iter->prefetch_tail = 0;
next = iter->idx + prefetched;
}
ccv_array_t* const prefetches = iter->prefetches;
ccv_cnnp_dataframe_data_item_t* const cached_data = (ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, iter->prefetch_tail);
// If the tail is before the head, we must have enough space for the max_to_prefetch
if (iter->prefetch_tail < iter->prefetch_head)
{
assert(iter->prefetch_tail + max_to_prefetch - 1 < iter->prefetch_head);
_ccv_cnnp_prefetch_cached_data(iter, cached_data, next, max_to_prefetch, stream_context);
iter->prefetch_tail += max_to_prefetch - 1;
} else {
// First, fetch to the end.
const int fetch_to_end = ccv_min(max_to_prefetch, lines - iter->prefetch_tail);
_ccv_cnnp_prefetch_cached_data(iter, cached_data, next, fetch_to_end, stream_context);
if (fetch_to_end == max_to_prefetch)
iter->prefetch_tail += fetch_to_end - 1;
else {
// Need to fetch more.
ccv_cnnp_dataframe_data_item_t* const more_data = (ccv_cnnp_dataframe_data_item_t*)ccv_array_get(prefetches, 0);
assert(max_to_prefetch > fetch_to_end);
_ccv_cnnp_prefetch_cached_data(iter, more_data, next + fetch_to_end, max_to_prefetch - fetch_to_end, stream_context);
iter->prefetch_tail = max_to_prefetch - fetch_to_end - 1;
}
}
return 0;
}
int ccv_cnnp_dataframe_iter_set_cursor(ccv_cnnp_dataframe_iter_t* const iter, const int idx)
{
ccv_cnnp_dataframe_t* const dataframe = iter->dataframe;
assert(dataframe);
if (idx >= dataframe->row_count)
return -1;
if (idx == iter->idx)
return 0;
iter->idx = idx;
_ccv_cnnp_null_prefetches(iter);
return 0;
}
void ccv_cnnp_dataframe_iter_free(ccv_cnnp_dataframe_iter_t* const iter)
{
ccv_cnnp_dataframe_t* const dataframe = iter->dataframe;
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
int i;
// Push existing data back to reusable state (note, these may not be reused immediately because they may be on a different stream context).
for (i = 0; i < column_size; i++)
if (iter->cached_data[i].flag)
_ccv_cnnp_dataframe_enqueue_data(dataframe, iter->cached_data[i].data, i, iter->cached_data[i].ctx);
// Push prefetches back to reusable state.
_ccv_cnnp_null_prefetches(iter);
if (iter->prefetches)
ccv_array_free(iter->prefetches);
if (iter->derived_data)
{
assert(dataframe->derived_column_data);
for (i = 0; i < dataframe->derived_column_data->rnum; i++)
if (iter->derived_data[i])
ccfree(iter->derived_data[i]);
ccfree(iter->derived_data);
}
ccfree(iter->fetched_data);
if (iter->column_ctx)
{
khash_t(iter_ctx)* const column_ctx = iter->column_ctx;
khiter_t k;
for (k = kh_begin(column_ctx); k != kh_end(column_ctx); ++k)
{
if (!kh_exist(column_ctx, k))
continue;
ccv_cnnp_dataframe_column_ctx_t* const ctx = kh_val(column_ctx, k);
for (i = 0; i < column_size; i++)
{
if (ctx[i].stream_context)
ccv_nnc_stream_context_free(ctx[i].stream_context);
if (ctx[i].signal)
ccv_nnc_stream_signal_free(ctx[i].signal);
}
}
kh_destroy(iter_ctx, column_ctx);
}
ccfree(iter);
}
void ccv_cnnp_dataframe_free(ccv_cnnp_dataframe_t* const dataframe)
{
int i, j;
khash_t(ctx)* const data_ctx = dataframe->data_ctx;
khiter_t k;
const int column_size = dataframe->column_size + (dataframe->derived_column_data ? dataframe->derived_column_data->rnum : 0);
for (k = kh_begin(data_ctx); k != kh_end(data_ctx); ++k)
{
if (!kh_exist(data_ctx, k))
continue;
ccv_array_t* const columns = kh_val(data_ctx, k);
assert(columns->rnum <= column_size);
for (i = 0; i < columns->rnum; i++)
{
ccv_array_t* const column = *(ccv_array_t**)ccv_array_get(columns, i);
void* context;
ccv_cnnp_column_data_deinit_f data_deinit;
if (i < dataframe->column_size)
{
data_deinit = dataframe->column_data[i].data_deinit;
context = dataframe->column_data[i].context;
} else {
assert(dataframe->derived_column_data);
ccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, i - dataframe->column_size);
data_deinit = derived_column_data->data_deinit;
context = derived_column_data->context;
}
if (data_deinit)
for (j = 0; j < column->rnum; j++)
data_deinit(*(void**)ccv_array_get(column, j), context);
ccv_array_free(column);
}
ccv_array_free(columns);
}
kh_destroy(ctx, data_ctx);
if (dataframe->derived_column_data)
{
for (i = 0; i < dataframe->derived_column_data->rnum; i++)
{
ccv_cnnp_derived_column_data_t* const derived_column_data = (ccv_cnnp_derived_column_data_t*)ccv_array_get(dataframe->derived_column_data, i);
if (derived_column_data->context_deinit)
derived_column_data->context_deinit(derived_column_data->context);
ccfree(derived_column_data->column_idxs);
}
ccv_array_free(dataframe->derived_column_data);
}
for (i = 0; i < dataframe->column_size; i++)
if (dataframe->column_data[i].context_deinit)
dataframe->column_data[i].context_deinit(dataframe->column_data[i].context);
if (dataframe->shuffled_idx)
ccfree(dataframe->shuffled_idx);
#ifdef HAVE_GSL
if (dataframe->rng)
gsl_rng_free(dataframe->rng);
#endif
ccfree(dataframe);
}
| {
"alphanum_fraction": 0.7487695585,
"avg_line_length": 42.9432176656,
"ext": "c",
"hexsha": "124e8d44eab6b54337b7ee813d7f479b876d5e5a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-05-18T15:50:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-18T15:50:49.000Z",
"max_forks_repo_head_hexsha": "cf86aacc6a59fcc4f3e203eb3889a89c5e8f5c66",
"max_forks_repo_licenses": [
"CC0-1.0",
"CC-BY-4.0"
],
"max_forks_repo_name": "lyp365859350/ccv",
"max_forks_repo_path": "lib/nnc/ccv_cnnp_dataframe.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cf86aacc6a59fcc4f3e203eb3889a89c5e8f5c66",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0",
"CC-BY-4.0"
],
"max_issues_repo_name": "lyp365859350/ccv",
"max_issues_repo_path": "lib/nnc/ccv_cnnp_dataframe.c",
"max_line_length": 339,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "655cb2c4a95694a69b81eab5ccb823dbcaa805e4",
"max_stars_repo_licenses": [
"CC0-1.0",
"CC-BY-4.0"
],
"max_stars_repo_name": "xiaoye77/ccv",
"max_stars_repo_path": "lib/nnc/ccv_cnnp_dataframe.c",
"max_stars_repo_stars_event_max_datetime": "2019-06-26T11:40:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-26T11:40:31.000Z",
"num_tokens": 7680,
"size": 27226
} |
/*! /file global.h
* /brief Declarations of global variables and functions. */
#ifndef GLOBAL_H
#define GLOBAL_H
#ifdef COOLING_CPU
#include <gsl/gsl_spline.h>
#include <gsl/gsl_spline2d.h>
#endif
#if PRECISION==1
#ifndef TYPEDEF_DEFINED_REAL
typedef float Real;
#endif
#endif
#if PRECISION==2
#ifndef TYPEDEF_DEFINED_REAL
typedef double Real;
#endif
#endif
#define MAXLEN 140
#define TINY_NUMBER 1.0e-20
#define PI 3.141592653589793
#define MP 1.672622e-24 // mass of proton, grams
#define KB 1.380658e-16 // boltzmann constant, cgs
//#define GN 6.67259e-8 // gravitational constant, cgs
#define GN 4.49451e-18 // gravitational constant, kpc^3 / M_sun / kyr^2
#define MYR 31.536e12 //Myears in secs
#define KPC 3.086e16 // kpc in km
#define G_COSMO 4.300927161e-06; // gravitational constant, kpc km^2 s^-2 Msun^-1
#define MSUN_CGS 1.98847e33; //Msun in gr
#define KPC_CGS 3.086e21; //kpc in cm
#define KM_CGS 1e5; //km in cm
#define TIME_UNIT 3.15569e10 // 1 kyr in s
#define LENGTH_UNIT 3.08567758e21 // 1 kpc in cm
#define MASS_UNIT 1.98855e33 // 1 solar mass in grams
#define DENSITY_UNIT (MASS_UNIT/(LENGTH_UNIT*LENGTH_UNIT*LENGTH_UNIT))
#define VELOCITY_UNIT (LENGTH_UNIT/TIME_UNIT)
#define ENERGY_UNIT (DENSITY_UNIT*VELOCITY_UNIT*VELOCITY_UNIT)
#define PRESSURE_UNIT (DENSITY_UNIT*VELOCITY_UNIT*VELOCITY_UNIT)
#define SP_ENERGY_UNIT (VELOCITY_UNIT*VELOCITY_UNIT)
#define LOG_FILE_NAME "run_output.log"
//Conserved Floor Values
#define TEMP_FLOOR 1e-3
#define DENS_FLOOR 1e-5
//Parameter for Enzo dual Energy Condition
#define DE_ETA_1 0.001 //Ratio of U to E for wich Inetrnal Energy is used to compute the Pressure
#define DE_ETA_2 0.035 //Ratio of U to max(E_local) used to select wich Internal Energy is used for the update.
// Maximum time step for cosmological simulations
#define MAX_DELTA_A 0.001
#define MAX_EXPANSION_RATE 0.01 // Limit delta(a)/a
#ifdef COOLING_GRACKLE
#ifdef GRACKLE_METALS
#define NSCALARS 7
#else
#define NSCALARS 6
#endif // GRACKLE_METALS
#else
#ifdef SCALAR
// Set Number of scalar fields when not using grackle
#define NSCALARS 1
#endif//SCALAR
#endif//COOLING_GRACKLE
// Inital Chemistry fractions
#define INITIAL_FRACTION_HI 0.75984603480
#define INITIAL_FRACTION_HII 1.53965115054e-4
#define INITIAL_FRACTION_HEI 0.23999999997
#define INITIAL_FRACTION_HEII 9.59999999903e-15
#define INITIAL_FRACTION_HEIII 9.59999999903e-18
#define INITIAL_FRACTION_ELECTRON 1.53965115054e-4
#define INITIAL_FRACTION_METAL 1.00000000000e-10
//Default Gravity Compiler Flags
#define GRAVITY_LONG_INTS
#define COUPLE_GRAVITATIONAL_WORK
//Default Particles Compiler Flags
#define PARTICLES_LONG_INTS
#define PARTICLES_KDK
#ifdef GRAVITY
#ifdef GRAVITY_5_POINTS_GRADIENT
#ifdef PARTICLES
#define N_GHOST_POTENTIAL 3 // 3 ghost cells are needed for 5 point gradient, ( one is for the CIC interpolation of the potential )
#else
#define N_GHOST_POTENTIAL 2 // 2 ghost cells are needed for 5 point gradient
#endif //PARTICLES
#else
#ifdef PARTICLES
#define N_GHOST_POTENTIAL 2 // 2 ghost cells are needed for 3 point gradient, ( one is for the CIC interpolation of the potential )
#else
#define N_GHOST_POTENTIAL 1 // 1 ghost cells are needed for 3 point gradient
#endif //PARTICLES
#endif //GRAVITY_5_POINTS_GRADIENT
#ifdef GRAVITY_LONG_INTS
typedef long int grav_int_t;
#else
typedef int grav_int_t;
#endif//GRAVITY_LONG_INTS
#endif
#ifdef PARTICLES
#ifdef PARTICLES_LONG_INTS
typedef long int part_int_t;
#else
typedef int part_int_t;
#endif//PARTICLES_LONG_INTS
#include <vector>
typedef std::vector<Real> real_vector_t;
typedef std::vector<part_int_t> int_vector_t;
#ifdef MPI_CHOLLA
// Constants for the inital size of the buffers for particles transfer
// and the number of data transfered for each particle
extern int N_PARTICLES_TRANSFER;
extern int N_DATA_PER_PARTICLE_TRANSFER;
#endif//MPI_CHOLLA
#ifdef AVERAGE_SLOW_CELLS
#define SLOW_FACTOR 10
#endif//AVERAGE_SLOW_CELLS
#endif//PARTICLES
#define SIGN(a) ( ((a) < 0.) ? -1. : 1. )
/* Global variables */
extern Real gama; // Ratio of specific heats
extern Real C_cfl; // CFL number (0 - 0.5)
extern Real t_comm;
extern Real t_other;
#ifdef COOLING_CPU
extern gsl_interp_accel *acc;
extern gsl_interp_accel *xacc;
extern gsl_interp_accel *yacc;
extern gsl_spline *highT_C_spline;
extern gsl_spline2d *lowT_C_spline;
extern gsl_spline2d *lowT_H_spline;
#endif
#ifdef COOLING_GPU
extern float *cooling_table;
extern float *heating_table;
#endif
/*! \fn void Set_Gammas(Real gamma_in)
* \brief Set gamma values for Riemann solver. */
extern void Set_Gammas(Real gamma_in);
/*! \fn double get_time(void)
* \brief Returns the current clock time. */
extern double get_time(void);
/*! \fn int sgn
* \brief Mathematical sign function. Returns sign of x. */
extern int sgn(Real x);
#ifndef CUDA
/*! \fn Real calc_eta(Real cW[], Real gamma)
* \brief Calculate the eta value for the H correction. */
extern Real calc_eta(Real cW[], Real gamma);
#endif
struct parameters
{
int nx;
int ny;
int nz;
double tout;
double outstep;
int n_steps_output;
Real gamma;
char init[MAXLEN];
int nfile;
int outstep_hydro;
int outstep_particle;
int outstep_projection;
int outstep_rotated_projection;
int outstep_slice;
Real xmin;
Real ymin;
Real zmin;
Real xlen;
Real ylen;
Real zlen;
int xl_bcnd;
int xu_bcnd;
int yl_bcnd;
int yu_bcnd;
int zl_bcnd;
int zu_bcnd;
#ifdef MPI_CHOLLA
int xlg_bcnd;
int xug_bcnd;
int ylg_bcnd;
int yug_bcnd;
int zlg_bcnd;
int zug_bcnd;
#endif /*MPI_CHOLLA*/
char custom_bcnd[MAXLEN];
char outdir[MAXLEN];
char indir[MAXLEN]; //Folder to load Initial conditions from
Real rho;
Real vx;
Real vy;
Real vz;
Real P;
Real A;
Real rho_l;
Real v_l;
Real P_l;
Real rho_r;
Real v_r;
Real P_r;
Real diaph;
#ifdef ROTATED_PROJECTION
int nxr;
int nzr;
Real delta;
Real theta;
Real phi;
Real Lx;
Real Lz;
int n_delta;
Real ddelta_dt;
int flag_delta;
#endif /*ROTATED_PROJECTION*/
#ifdef COSMOLOGY
Real H0;
Real Omega_M;
Real Omega_L;
Real Omega_b;
Real Init_redshift;
Real End_redshift;
char scale_outputs_file[MAXLEN]; //File for the scale_factor output values for cosmological simulations
#endif //COSMOLOGY
#ifdef TILED_INITIAL_CONDITIONS
Real tile_length;
#endif //TILED_INITIAL_CONDITIONS
#ifdef SET_MPI_GRID
// Set the MPI Processes grid [n_proc_x, n_proc_y, n_proc_z]
int n_proc_x;
int n_proc_y;
int n_proc_z;
#endif
int bc_potential_type;
#ifdef COOLING_GRACKLE
char UVB_rates_file[MAXLEN];
#endif
#ifdef ANALYSIS
char analysis_scale_outputs_file[MAXLEN]; //File for the scale_factor output values for cosmological simulations {{}}
char analysisdir[MAXLEN];
int lya_skewers_stride;
Real lya_Pk_d_log_k;
#ifdef OUTPUT_SKEWERS
char skewersdir[MAXLEN];
#endif
#endif
};
/*! \fn void parse_params(char *param_file, struct parameters * parms);
* \brief Reads the parameters in the given file into a structure. */
extern void parse_params (char *param_file, struct parameters * parms);
/*! \fn int is_param_valid(char *name);
* \brief Verifies that a param is valid (even if not needed). Avoids "warnings" in output. */
extern int is_param_valid(const char *name);
#endif //GLOBAL_H
| {
"alphanum_fraction": 0.7577495562,
"avg_line_length": 25.1649484536,
"ext": "h",
"hexsha": "c5b9ea82c5d69e4f358426f1637f774391626d07",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-02-26T18:06:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-11T09:35:15.000Z",
"max_forks_repo_head_hexsha": "fa828dcef6e7c82e425b5b36981d15a87f5e40ae",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bvillasen/cholla",
"max_forks_repo_path": "src/global.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "fa828dcef6e7c82e425b5b36981d15a87f5e40ae",
"max_issues_repo_issues_event_max_datetime": "2021-04-05T18:47:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-04-05T18:47:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "bvillasen/cholla",
"max_issues_repo_path": "src/global.h",
"max_line_length": 131,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "fa828dcef6e7c82e425b5b36981d15a87f5e40ae",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bvillasen/cholla",
"max_stars_repo_path": "src/global.h",
"max_stars_repo_stars_event_max_datetime": "2019-01-12T04:15:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-12-15T23:35:22.000Z",
"num_tokens": 2179,
"size": 7323
} |
#pragma once
#include <gsl/gsl>
#include <map>
#include "halley/text/halleystring.h"
#include "halley/maths/vector4.h"
namespace Halley
{
class Path;
class Image;
struct ImageData;
class AsepriteReader
{
public:
static std::vector<ImageData> importAseprite(String baseName, gsl::span<const gsl::byte> fileData, bool trim);
};
}
| {
"alphanum_fraction": 0.7374631268,
"avg_line_length": 17.8421052632,
"ext": "h",
"hexsha": "637b311e4692c9183cd844869c628d846c6104b1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h",
"max_line_length": 112,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z",
"num_tokens": 92,
"size": 339
} |
#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"
/*! \file conduction.c
* \brief Computes conduction bases on an implicit diffusion solver
*
*/
#ifdef CONDUCTION
#define MAX_COND_ITER 25
#define COND_ITER_ACCURACY 1.0e-4
static struct conductiondata_in
{
MyDouble Pos[3];
MyFloat Hsml;
MyFloat Density;
MyFloat Kappa;
int NodeList[NODELISTLENGTH];
}
*ConductionDataIn, *ConductionDataGet;
static struct conductiondata_out
{
MyFloat Out;
MyFloat Sum;
}
*ConductionDataResult, *ConductionDataOut;
static double *Energy, *EnergyOld;
static double *Residual, *DVec, *QVec;
static double *Kappa;
/* we will use the conjugate gradient method to compute a solution
of the implicitly formulate diffusion equation */
/* Note: the conduction equation we solve is really formulated with u instead of T, i.e.
the factor (gamma-1)*mu*mp/k_B that converts from T to u is implicitely absorbed in a
redefinition of kappa */
void conduction(void)
{
int i, iter;
double delta0, delta1, alpha, beta, a3inv, dt, rel_change, loc_max_rel_change, glob_max_rel_change;
double sumnew, sumold, sumtransfer, sumnew_tot, sumold_tot, sumtransfer_tot;
if(ThisTask == 0)
{
printf("Start thermal conduction...\n");
fflush(stdout);
}
Energy = (double *) mymalloc(N_gas * sizeof(double));
EnergyOld = (double *) mymalloc(N_gas * sizeof(double));
Residual = (double *) mymalloc(N_gas * sizeof(double));
DVec = (double *) mymalloc(N_gas * sizeof(double));
QVec = (double *) mymalloc(N_gas * sizeof(double));
Kappa = (double *) mymalloc(N_gas * sizeof(double));
if(All.ComovingIntegrationOn)
a3inv = 1 / (All.Time * All.Time * All.Time);
else
a3inv = 1.0;
dt = (All.Conduction_Ti_endstep - All.Conduction_Ti_begstep) * All.Timebase_interval;
if(All.ComovingIntegrationOn)
dt *= All.Time / hubble_function(All.Time);
if(ThisTask == 0)
{
printf("dt=%g\n", dt);
}
/* First, let's compute the thermal energies per unit mass and
conductivities for all particles */
for(i = 0; i < N_gas; i++)
{
if(P[i].Type == 0)
{
/* this gives the thermal energy per unit mass for particle i */
Energy[i] = EnergyOld[i] = SphP[i].Entropy *
pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1;
#ifdef CONDUCTION_CONSTANT
Kappa[i] = All.ConductionCoeff;
#else
Kappa[i] = All.ConductionCoeff * pow(EnergyOld[i], 2.5);
#ifdef CONDUCTION_SATURATION
electron_free_path = All.ElectronFreePathFactor * Energy[i] * Energy[i] / (SphP[i].Density * a3inv);
temp_scale_length =
atime * fabs(smoothentr) / sqrt(gradentr[0] * gradentr[0] +
gradentr[1] * gradentr[1] + gradentr[2] * gradentr[2]);
Kappa[i] /= (1 + 4.2 * electron_free_path / temp_scale_length);
#endif
#endif
#ifdef SFR
if(SphP[i].Density * a3inv >= All.PhysDensThresh)
Kappa[i] = 0;
#endif
/* we'll factor the timestep into the conductivities, for simplicity */
Kappa[i] *= dt;
}
}
/* Let's start the Conjugate Gradient Algorithm */
/* Initialization */
conduction_matrix_multiply(EnergyOld, Residual);
for(i = 0; i < N_gas; i++)
{
if(P[i].Type == 0)
{
Residual[i] = EnergyOld[i] - Residual[i];
DVec[i] = Residual[i];
}
}
delta1 = conduction_vector_multiply(Residual, Residual);
delta0 = delta1;
iter = 0; /* iteration counter */
glob_max_rel_change = 1 + COND_ITER_ACCURACY; /* to make sure that we enter the iteration */
while(iter < MAX_COND_ITER && glob_max_rel_change > COND_ITER_ACCURACY && delta1 > 0)
{
conduction_matrix_multiply(DVec, QVec);
alpha = delta1 / conduction_vector_multiply(DVec, QVec);
for(i = 0, loc_max_rel_change = 0; i < N_gas; i++)
{
Energy[i] += alpha * DVec[i];
Residual[i] -= alpha * QVec[i];
rel_change = alpha * DVec[i] / Energy[i];
if(loc_max_rel_change < rel_change)
loc_max_rel_change = rel_change;
}
delta0 = delta1;
delta1 = conduction_vector_multiply(Residual, Residual);
beta = delta1 / delta0;
for(i = 0; i < N_gas; i++)
DVec[i] = Residual[i] + beta * DVec[i];
iter++;
MPI_Allreduce(&loc_max_rel_change, &glob_max_rel_change, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
if(ThisTask == 0)
{
printf("conduction iter=%d delta1=%g delta1/delta0=%g max-rel-change=%g\n",
iter, delta1, delta1 / delta0, glob_max_rel_change);
fflush(stdout);
}
}
/* Now we have the solution vector in Energy[] */
/* assign it to the entropies, and update the pressure */
for(i = 0, sumnew = sumold = sumtransfer = 0; i < N_gas; i++)
{
if(P[i].Type == 0)
{
sumnew += P[i].Mass * Energy[i];
sumold += P[i].Mass * EnergyOld[i];
sumtransfer += P[i].Mass * fabs(Energy[i] - EnergyOld[i]);
SphP[i].Entropy = Energy[i] / pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1) * GAMMA_MINUS1;
}
}
MPI_Allreduce(&sumnew, &sumnew_tot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&sumold, &sumold_tot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&sumtransfer, &sumtransfer_tot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
if(ThisTask == 0)
{
printf("\nconduction finished. energy_before=%g energy_after=%g rel-change=%g rel-transfer=%g\n\n",
sumold_tot, sumnew_tot, (sumnew_tot - sumold_tot) / sumold_tot, sumtransfer_tot / sumold_tot);
fflush(stdout);
}
myfree(Kappa);
myfree(QVec);
myfree(DVec);
myfree(Residual);
myfree(EnergyOld);
myfree(Energy);
}
double conduction_vector_multiply(double *a, double *b)
{
int i;
double sum, sumall;
for(i = 0, sum = 0; i < N_gas; i++)
if(P[i].Type == 0)
sum += a[i] * b[i];
MPI_Allreduce(&sum, &sumall, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
return sumall;
}
void conduction_matrix_multiply(double *in, double *out)
{
int i, j, k, ngrp, ndone, ndone_flag, dummy;
int sendTask, recvTask, nexport, nimport, place;
double *sum;
/* allocate buffers to arrange communication */
Ngblist = (int *) mymalloc(NumPart * sizeof(int));
All.BunchSize =
(int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +
sizeof(struct conductiondata_in) +
sizeof(struct conductiondata_out) +
sizemax(sizeof(struct conductiondata_in),
sizeof(struct conductiondata_out))));
DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));
DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));
sum = (double *) mymalloc(N_gas * sizeof(double));
i = 0; /* need to go over all gas particles */
do
{
for(j = 0; j < NTask; j++)
{
Send_count[j] = 0;
Exportflag[j] = -1;
}
/* do local particles and prepare export list */
for(nexport = 0; i < N_gas; i++)
if(P[i].Type == 0)
{
if(conduction_evaluate(i, 0, in, out, sum, &nexport, Send_count) < 0)
break;
}
#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
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
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];
}
}
ConductionDataGet = (struct conductiondata_in *) mymalloc(nimport * sizeof(struct conductiondata_in));
ConductionDataIn = (struct conductiondata_in *) mymalloc(nexport * sizeof(struct conductiondata_in));
/* prepare particle data for export */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
for(k = 0; k < 3; k++)
ConductionDataIn[j].Pos[k] = P[place].Pos[k];
ConductionDataIn[j].Hsml = PPP[place].Hsml;
ConductionDataIn[j].Density = SphP[place].d.Density;
ConductionDataIn[j].Kappa = Kappa[place];
memcpy(ConductionDataIn[j].NodeList,
DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));
}
/* exchange particle data */
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(&ConductionDataIn[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct conductiondata_in), MPI_BYTE,
recvTask, TAG_HYDRO_A,
&ConductionDataGet[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct conductiondata_in), MPI_BYTE,
recvTask, TAG_HYDRO_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
myfree(ConductionDataIn);
ConductionDataResult =
(struct conductiondata_out *) mymalloc(nimport * sizeof(struct conductiondata_out));
ConductionDataOut = (struct conductiondata_out *) mymalloc(nexport * sizeof(struct conductiondata_out));
/* now do the particles that were sent to us */
for(j = 0; j < nimport; j++)
conduction_evaluate(j, 1, in, out, sum, &dummy, &dummy);
if(i >= N_gas)
ndone_flag = 1;
else
ndone_flag = 0;
MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
/* get the result */
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(&ConductionDataResult[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct conductiondata_out),
MPI_BYTE, recvTask, TAG_HYDRO_B,
&ConductionDataOut[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct conductiondata_out),
MPI_BYTE, recvTask, TAG_HYDRO_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
/* add the result to the local particles */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
out[place] += ConductionDataOut[j].Out;
sum[place] += ConductionDataOut[j].Sum;
}
myfree(ConductionDataOut);
myfree(ConductionDataResult);
myfree(ConductionDataGet);
}
while(ndone < NTask);
/* do final operations */
for(i = 0; i < N_gas; i++)
if(P[i].Type == 0)
{
out[i] += in[i] * (1 + sum[i]);
}
myfree(sum);
myfree(DataNodeList);
myfree(DataIndexTable);
myfree(Ngblist);
}
int conduction_evaluate(int target, int mode, double *in, double *out, double *sum,
int *nexport, int *nsend_local)
{
int startnode, numngb, listindex = 0;
int j, n;
MyDouble *pos;
MyFloat h_i, rho;
double dx, dy, dz;
double h_i2, hinv_i, hinv4_i, hinv_j, hinv4_j;
double dwk_i, h_j, dwk_j, dwk;
double r, r2, u, Kappa_i, kappa_mean, w, out_sum, w_sum;
if(mode == 0)
{
pos = P[target].Pos;
h_i = PPP[target].Hsml;
rho = SphP[target].d.Density;
Kappa_i = Kappa[target];
}
else
{
pos = ConductionDataGet[target].Pos;
h_i = ConductionDataGet[target].Hsml;
rho = ConductionDataGet[target].Density;
Kappa_i = ConductionDataGet[target].Kappa;
}
h_i2 = h_i * h_i;
hinv_i = 1.0 / h_i;
#ifndef TWODIMS
hinv4_i = hinv_i * hinv_i * hinv_i * hinv_i;
#else
hinv4_i = hinv_i * hinv_i * hinv_i / boxSize_Z;
#endif
/* initialize variables before SPH loop is started */
out_sum = 0;
w_sum = 0;
/* Now start the actual SPH computation for this particle */
if(mode == 0)
{
startnode = All.MaxPart; /* root node */
}
else
{
startnode = ConductionDataGet[target].NodeList[0];
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
while(startnode >= 0)
{
while(startnode >= 0)
{
numngb = ngb_treefind_pairs(pos, h_i, target, &startnode, mode, nexport, nsend_local);
if(numngb < 0)
return -1;
for(n = 0; n < numngb; 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;
h_j = PPP[j].Hsml;
if(r2 < h_i2 || r2 < h_j * h_j)
{
r = sqrt(r2);
if(r > 0)
{
if(r2 < h_i2)
{
u = r * hinv_i;
if(u < 0.5)
dwk_i = hinv4_i * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);
else
dwk_i = hinv4_i * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);
}
else
dwk_i = 0;
if(r2 < h_j * h_j)
{
hinv_j = 1.0 / h_j;
#ifndef TWODIMS
hinv4_j = hinv_j * hinv_j * hinv_j * hinv_j;
#else
hinv4_j = hinv_j * hinv_j * hinv_j / boxSize_Z;
#endif
u = r * hinv_j;
if(u < 0.5)
dwk_j = hinv4_j * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);
else
dwk_j = hinv4_j * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);
}
else
dwk_j = 0;
/* conduction equation kernel */
if((Kappa_i + Kappa[j]) > 0)
{
kappa_mean = 2 * (Kappa_i * Kappa[j]) / (Kappa_i + Kappa[j]);
dwk = 0.5 * (dwk_i + dwk_j);
w = 2.0 * P[j].Mass / (rho * SphP[j].d.Density) * kappa_mean * (-dwk) / r;
out_sum += (-w * in[j]);
w_sum += w;
}
}
}
}
}
if(mode == 1)
{
listindex++;
if(listindex < NODELISTLENGTH)
{
startnode = ConductionDataGet[target].NodeList[listindex];
if(startnode >= 0)
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
}
}
/* Now collect the result at the right place */
if(mode == 0)
{
out[target] = out_sum;
sum[target] = w_sum;
}
else
{
ConductionDataResult[target].Out = out_sum;
ConductionDataResult[target].Sum = w_sum;
}
return 0;
}
#endif
| {
"alphanum_fraction": 0.62487946,
"avg_line_length": 25.2486956522,
"ext": "c",
"hexsha": "3f26b42b9de229e9a3740926cb678ca21ed2f421",
"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/conduction.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/conduction.c",
"max_line_length": 110,
"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/conduction.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4558,
"size": 14518
} |
#pragma once
#include <petsc.h>
// TODO: include this in a different header?
#ifdef PETSC_USE_64BIT_INDICES
#define builtin_parity __builtin_parityl
#else
#define builtin_parity __builtin_parity
#endif
/* define a struct & enum to hold subspace information */
// TODO: more descriptive name?
typedef enum _subspace_type
{
FULL,
PARITY,
AUTO
} subspace_type;
typedef struct _subspaces_t
{
subspace_type left_type;
subspace_type right_type;
void *left_data;
void *right_data;
} subspaces_t;
/***** FULL *****/
typedef struct _data_Full
{
PetscInt L;
} data_Full;
static inline PetscErrorCode CopySubspaceData_Full(data_Full** out_p, const data_Full* in) {
PetscErrorCode ierr;
ierr = PetscMalloc1(1, out_p);CHKERRQ(ierr);
ierr = PetscMemcpy(*out_p, in, sizeof(data_Full));CHKERRQ(ierr);
return ierr;
}
static inline PetscErrorCode DestroySubspaceData_Full(data_Full* data) {
PetscErrorCode ierr;
ierr = PetscFree(data);CHKERRQ(ierr);
return ierr;
}
static inline PetscInt Dim_Full(const data_Full* data) {
return (PetscInt)1 << data->L;
}
static inline PetscInt S2I_Full(PetscInt state, const data_Full* data) {
return state;
}
static inline PetscInt S2I_nocheck_Full(PetscInt state, const data_Full* data) {
return state;
}
static inline PetscInt I2S_Full(PetscInt idx, const data_Full* data) {
return idx;
}
static inline void S2I_Full_array(int n, const data_Full* data, const PetscInt* states, PetscInt* idxs) {
PetscMemcpy(idxs, states, n*sizeof(PetscInt));
}
static inline void I2S_Full_array(int n, const data_Full* data, const PetscInt* idxs, PetscInt* states) {
PetscMemcpy(states, idxs, n*sizeof(PetscInt));
}
/***** PARITY *****/
typedef struct _data_Parity
{
PetscInt L;
PetscInt space;
} data_Parity;
static inline PetscErrorCode CopySubspaceData_Parity(data_Parity** out_p, const data_Parity* in) {
PetscErrorCode ierr;
ierr = PetscMalloc1(1, out_p);CHKERRQ(ierr);
ierr = PetscMemcpy(*out_p, in, sizeof(data_Parity));CHKERRQ(ierr);
return ierr;
}
static inline PetscErrorCode DestroySubspaceData_Parity(data_Parity* data) {
PetscErrorCode ierr;
ierr = PetscFree(data);CHKERRQ(ierr);
return ierr;
}
static inline PetscInt Dim_Parity(const data_Parity* data) {
return (PetscInt)1 << (data->L-1);
}
static inline PetscInt S2I_Parity(PetscInt state, const data_Parity* data) {
if (builtin_parity(state) == data->space) {
return state>>1;
}
else {
return (PetscInt)(-1);
}
}
static inline PetscInt S2I_nocheck_Parity(PetscInt state, const data_Parity* data) {
return state>>1;
}
static inline PetscInt I2S_Parity(PetscInt idx, const data_Parity* data) {
return (idx<<1) | (builtin_parity(idx) ^ data->space);
}
static inline void S2I_Parity_array(int n, const data_Parity* data, const PetscInt* states, PetscInt* idxs) {
PetscInt i;
for (i = 0; i < n; ++i) {
idxs[i] = S2I_Parity(states[i], data);
}
}
static inline void I2S_Parity_array(int n, const data_Parity* data, const PetscInt* idxs, PetscInt* states) {
PetscInt i;
for (i = 0; i < n; ++i) {
states[i] = I2S_Parity(idxs[i], data);
}
}
/***** AUTO *****/
typedef struct _data_Auto
{
PetscInt L;
PetscInt dim;
PetscInt* state_map;
PetscInt* rmap_indices;
PetscInt* rmap_states;
} data_Auto;
static inline PetscErrorCode CopySubspaceData_Auto(data_Auto** out_p, const data_Auto* in) {
PetscErrorCode ierr;
ierr = PetscMalloc1(1, out_p);CHKERRQ(ierr);
ierr = PetscMemcpy(*out_p, in, sizeof(data_Auto));CHKERRQ(ierr);
ierr = PetscMalloc1(in->dim, &((*out_p)->state_map));CHKERRQ(ierr);
ierr = PetscMemcpy((*out_p)->state_map, in->state_map, in->dim*sizeof(PetscInt));CHKERRQ(ierr);
ierr = PetscMalloc1(in->dim, &((*out_p)->rmap_indices));CHKERRQ(ierr);
ierr = PetscMemcpy((*out_p)->rmap_indices, in->rmap_indices, in->dim*sizeof(PetscInt));CHKERRQ(ierr);
ierr = PetscMalloc1(in->dim, &((*out_p)->rmap_states));CHKERRQ(ierr);
ierr = PetscMemcpy((*out_p)->rmap_states, in->rmap_states, in->dim*sizeof(PetscInt));CHKERRQ(ierr);
return ierr;
}
static inline PetscErrorCode DestroySubspaceData_Auto(data_Auto* data) {
PetscErrorCode ierr;
ierr = PetscFree(data->state_map);CHKERRQ(ierr);
ierr = PetscFree(data->rmap_indices);CHKERRQ(ierr);
ierr = PetscFree(data->rmap_states);CHKERRQ(ierr);
ierr = PetscFree(data);CHKERRQ(ierr);
return ierr;
}
static inline PetscInt Dim_Auto(const data_Auto* data) {
return data->dim;
}
static inline PetscInt S2I_Auto(PetscInt state, const data_Auto* data) {
/* do a binary search on rmap_states */
PetscInt left, right, mid;
left = 0;
right = data->dim;
while (left <= right) {
mid = left + (right-left)/2;
if (data->rmap_states[mid] == state) {
return data->rmap_indices[mid];
}
if (data->rmap_states[mid] < state) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
/* element was not in the array */
return -1;
}
static inline PetscInt I2S_Auto(PetscInt idx, const data_Auto* data) {
return data->state_map[idx];
}
static inline void S2I_Auto_array(int n, const data_Auto* data, const PetscInt* states, PetscInt* idxs) {
PetscInt i;
for (i = 0; i < n; ++i) {
idxs[i] = S2I_Auto(states[i], data);
}
}
static inline void I2S_Auto_array(int n, const data_Auto* data, const PetscInt* idxs, PetscInt* states) {
PetscInt i;
for (i = 0; i < n; ++i) {
states[i] = I2S_Auto(idxs[i], data);
}
}
| {
"alphanum_fraction": 0.7044787078,
"avg_line_length": 25.9428571429,
"ext": "h",
"hexsha": "76e76716c58a69dd1810d5a1d5059eb2b4bf03d7",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-01-26T21:38:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-02-21T19:36:47.000Z",
"max_forks_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "GregDMeyer/dynamite",
"max_forks_repo_path": "dynamite/_backend/bsubspace_impl.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265",
"max_issues_repo_issues_event_max_datetime": "2021-02-03T20:35:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-11T22:57:09.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "GregDMeyer/dynamite",
"max_issues_repo_path": "dynamite/_backend/bsubspace_impl.h",
"max_line_length": 109,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "GregDMeyer/dynamite",
"max_stars_repo_path": "dynamite/_backend/bsubspace_impl.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-23T01:17:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-11T22:53:30.000Z",
"num_tokens": 1631,
"size": 5448
} |
#ifndef L_1_LASSO_C_H
#define L_1_LASSO_C_H
#include "Matrix.h"
#include "PDCD.h"
#include <string>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <stdio.h> /* printf */
#include <time.h>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <math.h>
//This class solves problem of the form lambda3\|Ax- b\|_1+ g(x) by SMART_CD;
// where g(x)=\frac{lambda2}{2}\|x\|_2+lambda1\|x\|_1.
// phi_i(x)= 0, h_i(x)= lambda3\|x- b_i\|_1.
template<typename L, typename D>
class L_1_Lasso_c: public PDCD<L, D>
{
private:
D lambda1;
D lambda2;
D lambda3;
Matrix<L,D> my_M;
D val_lambda_f;
protected:
public:
L_1_Lasso_c(const char* Matrix_file,D val_lambda1, D val_lambda2, D val_lambda3)
:PDCD<L,D>(),my_M(Matrix_file)
{
lambda1=val_lambda1;
lambda2=val_lambda2;
lambda3=val_lambda3;
val_lambda_f=0;
this->mu_f=0;
this->mu_g=lambda2;
}
L get_n(){return my_M.nfeatures;}
L get_m(){return my_M.nsamples;}
inline D gradient_of_phi_j(D x1, L i){
return 0;
}
inline D value_of_g_i(D x, L i){
return lambda2*x*x/2+lambda1*fabs(x);
}
inline D value_of_phi_j(D x1, L i){return 0;}
inline D value_of_h_j(D x, L i){
return lambda3*fabs(x- my_M.b[i]);
}
inline D value_of_h_star_j(D x, L j){
if (x<= lambda3 && x>= -lambda3){
return my_M.b[j]*x;
}
else{
cout<< "error in h*(x)"<< endl;
return std::numeric_limits<double>::max();
}
}
inline D prox_of_g_i(D x1,D x2,D x3, L i){
return compute_one_step(1.0/x2, x1, x3)-x3;
}
D compute_one_step(D tau, D u, D x){
D new_x;
if(x>tau*(lambda1+u))
new_x=(x-tau*(lambda1+u))/(1+lambda2*tau);
else if(x<tau*(u-lambda1))
new_x=(x-tau*(u-lambda1))/(1+lambda2*tau);
else
new_x=0;
return new_x;
}
// compute argmin_x h^*(x)+ x2/2*(x- x1)*(x- x1)
inline D prox_of_h_star_j(D x1, D x2, L j){
if (x1- my_M.b[j]/x2> lambda3){
return lambda3;
}
else if (x1- my_M.b[j]/x2< -lambda3){
return -lambda3;
}
else{
return x1- my_M.b[j]/x2;
}
}
inline D value_of_phistar_i(D x,L i) {return 0;}
inline void set_matrix_M(){
this->data_M=my_M;
}
inline void set_matrix_A(){
this->data_A.nsamples=0;
this->data_A.nfeatures=this->data_M.nfeatures;
this->data_A.nnz=0;
this->data_A.ptr.resize(1,0);
this->data_A.ptr_t.resize(this->data_M.nfeatures+1,0);
}
void SMART_CD_solver(D beta_0, vector<D> & x0,vector<D> & y0,L val_tau, L max_nb_outer, L p_N, string filename1, D time){
this->PDCD_solver(beta_0, x0,y0, val_tau, max_nb_outer, p_N, val_lambda_f, filename1, time);
}
};
#endif
| {
"alphanum_fraction": 0.5872796405,
"avg_line_length": 20.2307692308,
"ext": "h",
"hexsha": "e4a34d0aadc60714e4a49a46f94e090c4c9af24a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "lifei16/supplementary_code",
"max_forks_repo_path": "IPALM/L_1_Lasso_c.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-Source-Code"
],
"max_issues_repo_name": "lifei16/supplementary_code",
"max_issues_repo_path": "IPALM/L_1_Lasso_c.h",
"max_line_length": 124,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "lifei16/supplementary_code",
"max_stars_repo_path": "IPALM/L_1_Lasso_c.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 960,
"size": 2893
} |
/****************************************************************
gsl.h
Defines wrappers for gsl functions.
Language: C++
Mark A. Caprio
University of Notre Dame
- 3/26/17 (mac): Created, based on code from spncci utilities (aem).
****************************************************************/
#ifndef MCUTILS_GSL_H_
#define MCUTILS_GSL_H_
#include <gsl/gsl_sf_gamma.h>
namespace mcutils {
// GSL factorial wrappers
//
// Use more efficient int implementation for int arguments, else use
// generic gamma function for double arguments.
inline double Factorial(int x)
{
return gsl_sf_fact(x);
}
inline double Factorial(double x)
{
return gsl_sf_gamma(x+1);
}
// GSL combinatorial function wrappers
inline int Choose(int x, int y)
{
int choose=0;
if ((x>=y)&&(y>=0))
{
gsl_sf_result result;
gsl_sf_choose_e(x,y,&result);
choose=result.val;
}
return choose;
}
} // namespace
#endif
| {
"alphanum_fraction": 0.5633802817,
"avg_line_length": 18.0727272727,
"ext": "h",
"hexsha": "03a40cff4c05c1aae403c15398c9334cd01681fe",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2019-07-10T23:34:16.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-24T20:11:16.000Z",
"max_forks_repo_head_hexsha": "bc12cf054b7a2ca756d23686673927f73c5f933c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nd-nuclear-theory/mcutils",
"max_forks_repo_path": "gsl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bc12cf054b7a2ca756d23686673927f73c5f933c",
"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": "nd-nuclear-theory/mcutils",
"max_issues_repo_path": "gsl.h",
"max_line_length": 70,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bc12cf054b7a2ca756d23686673927f73c5f933c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nd-nuclear-theory/mcutils",
"max_stars_repo_path": "gsl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 234,
"size": 994
} |
#pragma once
#include <cmath>
#include <gsl/gsl_math.h>
bool to_fraction(double num, long& numerator, long& denominator){
double sign = num < 0 ? -1 : 1;
double g = std::abs(num);
long a = 0, b = 1, c = 1, d = 0;
long s;
int iter = 0;
numerator = 0, denominator = 1;
while (iter++ < 1e6){
s = (long) std::floor(g);
numerator = a + s*c;
denominator = b + s*d;
a = c;
b = d;
c = numerator;
d = denominator;
g = 1.0/(g-s);
if(gsl_fcmp(sign*numerator, num*denominator, 1e-13) == 0){
numerator *= sign;
return true;
}
}
return false;
}
| {
"alphanum_fraction": 0.4910979228,
"avg_line_length": 22.4666666667,
"ext": "h",
"hexsha": "1dfa3017a97e49ab2474b5ce53831c5f683b7583",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoniojkim/CalcPlusPlus",
"max_forks_repo_path": "MathEngine/Utils/Fraction.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "antoniojkim/CalcPlusPlus",
"max_issues_repo_path": "MathEngine/Utils/Fraction.h",
"max_line_length": 66,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoniojkim/CalcPlusPlus",
"max_stars_repo_path": "MathEngine/Utils/Fraction.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 210,
"size": 674
} |
#include <math.h>
#include <gsl/gsl_blas.h>
#include "qdm.h"
#define TAU_INITIAL_GUESS 0.5
#define TAU_EPS 0.001
#define TAU_ITERATION_MAX 1000
#define RESET_SIZE 30
const double RESET_VALUES[RESET_SIZE] = {
0.010000000000000000,
0.010100000000000000,
0.010200000000000001,
0.010300000000000000,
0.010400000000000000,
0.010500000000000001,
0.010600000000000000,
0.010699999999999999,
0.010800000000000001,
0.010900000000000000,
0.010999999999999999,
0.010999999999999999,
0.150714285714285717,
0.290428571428571425,
0.430142857142857160,
0.569857142857142840,
0.709571428571428520,
0.849285714285714310,
0.988999999999999990,
0.988999999999999990,
0.989099999999999979,
0.989199999999999968,
0.989299999999999957,
0.989399999999999946,
0.989500000000000046,
0.989600000000000035,
0.989700000000000024,
0.989800000000000013,
0.989900000000000002,
0.989999999999999991,
};
/* Helper: Compute ispline by mmm dot product. */
static
int
ispline_mmm(
double *result,
double tau,
size_t spline_df,
const gsl_vector *knots,
const gsl_vector *mmm
)
{
int status = 0;
size_t m = (knots->size - spline_df) + 1;
gsl_vector *ispline = gsl_vector_alloc(m);
qdm_ispline_vector(ispline, tau, spline_df, knots);
status = gsl_blas_ddot(ispline, mmm, result);
if (status != 0) {
goto cleanup;
}
cleanup:
gsl_vector_free(ispline);
return status;
}
/* Helper: Compute mspline by mmm dot product. */
static
int
mspline_mmm(
double *result,
double tau,
size_t spline_df,
const gsl_vector *knots,
const gsl_vector *mmm
)
{
int status = 0;
size_t m = (knots->size - spline_df) + 1;
gsl_vector *mspline = gsl_vector_alloc(m);
qdm_mspline_vector(mspline, tau, spline_df, knots);
status = gsl_blas_ddot(mspline, mmm, result);
if (status != 0) {
goto cleanup;
}
cleanup:
gsl_vector_free(mspline);
return status;
}
int
qdm_find_tau(
double *result,
double v,
size_t spline_df,
const gsl_vector *knots,
const gsl_vector *mmm
)
{
int status = 0;
double tau = TAU_INITIAL_GUESS;
double qi_u = 0;
double qm_u = 0;
size_t reset_i = 0;
for (size_t i = 0; i < TAU_ITERATION_MAX; i++) {
if (reset_i >= RESET_SIZE) {
tau = TAU_INITIAL_GUESS;
break;
}
/* Calculate position... */
status = ispline_mmm(&qi_u, tau, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
/* Calculate slope... */
status = mspline_mmm(&qm_u, tau, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
/* Check if the update is within our desired interval [0, 1]. */
double update = tau - (qi_u - v) / qm_u;
if (update < 0 || update > 1) {
tau = RESET_VALUES[reset_i];
reset_i++;
continue;
} else {
tau = update;
}
if (fabs(qi_u - v) <= TAU_EPS) {
break;
}
}
*result = tau;
cleanup:
return status;
}
int
qdm_logl(
double *log_likelihood,
double *tau,
double v,
size_t spline_df,
const gsl_vector *knots,
const gsl_vector *mmm,
double tau_low,
double tau_high,
double xi_low,
double xi_high
)
{
int status = 0;
double low_threshold = 0;
double high_threshold = 0;
status = ispline_mmm(&low_threshold, tau_low, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
status = ispline_mmm(&high_threshold, tau_high, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
if (v <= low_threshold) {
double sigma_low = 0;
status = mspline_mmm(&sigma_low, tau_low, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
sigma_low *= tau_low;
double z = low_threshold - v;
*log_likelihood = log(tau_low / sigma_low * pow(1 + (xi_low * z) / sigma_low, -1 / xi_low - 1));
*tau = (1 - (1 - pow(1 + xi_low * z / sigma_low, -1 / xi_low))) * tau_low;
} else if (v >= high_threshold) {
double sigma_high = 0;
status = mspline_mmm(&sigma_high, tau_high, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
sigma_high *= (1 - tau_high);
double z = v - high_threshold;
*log_likelihood = log((1 - tau_high) / sigma_high * pow(1 + (xi_high * z) / sigma_high, -1 / xi_high - 1));
*tau = (1 - pow(1 + xi_high * z / sigma_high, -1 / xi_high)) * (1 - tau_high) + tau_high;
} else {
double d = 0;
status = qdm_find_tau(tau, v, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
status = mspline_mmm(&d, *tau, spline_df, knots, mmm);
if (status != 0) {
goto cleanup;
}
*log_likelihood = log(1 / d);
}
cleanup:
return status;
}
int
qdm_logl_2(
double *log_likelihood,
double *tau,
double x,
double y,
double tau_low,
double tau_high,
double xi_low,
double xi_high,
size_t spline_df,
const gsl_matrix *theta,
const gsl_vector *knots
)
{
int status = 0;
double xi_data[2] = {1, x};
gsl_vector_view xi = gsl_vector_view_array(xi_data, 2);
double mmm_data[theta->size2];
gsl_vector_view mmm = gsl_vector_view_array(mmm_data, theta->size2);
status = gsl_blas_dgemv(CblasTrans, 1, theta, &xi.vector, 0, &mmm.vector);
if (status != 0) {
return status;
}
status = qdm_logl(
log_likelihood,
tau,
y,
spline_df,
knots,
&mmm.vector,
tau_low,
tau_high,
xi_low,
xi_high
);
if (status != 0) {
return status;
}
return status;
}
void
qdm_logl_3(
double *log_likelihood,
double *tau,
double x,
double y,
const qdm_tau *t,
const gsl_vector *xi,
const gsl_matrix *theta
)
{
double xi_intercept_data[2] = {1, x};
gsl_vector_view xi_intercept = gsl_vector_view_array(xi_intercept_data, 2);
double mmm_data[theta->size2];
gsl_vector_view mmm = gsl_vector_view_array(mmm_data, theta->size2);
gsl_blas_dgemv(CblasTrans, 1, theta, &xi_intercept.vector, 0, &mmm.vector);
double low_threshold = qdm_tau_ispline_mmm(t, t->low, &mmm.vector);
double high_threshold = qdm_tau_ispline_mmm(t, t->high, &mmm.vector);
/*
fprintf(stderr, "x : %f\n", x);
fprintf(stderr, "y : %f\n", y);
fprintf(stderr, "tl : %f\n", t->low);
fprintf(stderr, "th : %f\n", t->high);
fprintf(stderr, "low : %f\n", low_threshold);
fprintf(stderr, "high : %f\n", high_threshold);
qdm_matrix_csv_fwrite(stderr, theta);
*/
double xi_low = gsl_vector_get(xi, 0);
double xi_high = gsl_vector_get(xi, 1);
if (y <= low_threshold) {
double sigma_low = qdm_tau_mspline_mmm(t, t->low, &mmm.vector) * t->low;
double z = low_threshold - y;
*log_likelihood = log(t->low / sigma_low * pow(1 + (xi_low * z) / sigma_low, -1 / xi_low - 1));
*tau = (1 - (1 - pow(1 + xi_low * z / sigma_low, -1 / xi_low))) * t->low;
} else if (y >= high_threshold) {
double sigma_high = qdm_tau_mspline_mmm(t, t->high, &mmm.vector) * (1 - t->high);
double z = y - high_threshold;
*log_likelihood = log((1 - t->high) / sigma_high * pow(1 + (xi_high * z) / sigma_high, -1 / xi_high - 1));
*tau = (1 - pow(1 + xi_high * z / sigma_high, -1 / xi_high)) * (1 - t->high) + t->high;
} else {
*tau = qdm_tau_find(t, y, &mmm.vector);
*log_likelihood = log(1 / qdm_tau_mspline_mmm(t, *tau, &mmm.vector));
}
/*
fprintf(stderr, "ll : %f\n", *log_likelihood);
fprintf(stderr, "tau : %f\n", *tau);
*/
}
| {
"alphanum_fraction": 0.6288879989,
"avg_line_length": 20.8083333333,
"ext": "c",
"hexsha": "0f59d37a59e4b5676b920fff0ce5522a2698ce42",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "src/logl.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "src/logl.c",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "src/logl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2483,
"size": 7491
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.