Search is not available for this dataset
text string | meta dict |
|---|---|
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_linalg.h>
#include "userFunc.h"
#define G 6.67384e-8 /* 2010 CODATA value in CGS units */
#define QCRIT 1.0 /* Q value at which GI turns on */
#define QDAMP 10.0 /* Rate of damping of alpha above Qcrit */
#define ALPHAMIN 1.0e-6 /* Minimum allowed alpha value */
/**************************************************************************/
/* This defines userFunc routines for the Krumholz & Burkert (2010) GI */
/* disk problem. */
/**************************************************************************/
void
userEOS(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
void *params,
double *gamma, double *delta) {
fprintf(stderr,
"Warning: userEOS function called but not implemented!\n");
return;
}
void
userAlpha(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
void *params,
double *alpha) {
static int nr = 0;
static double rmin = -1.0, rmax = -1.0;
static double *x = NULL;
static double *h1 = NULL;
static double *h0 = NULL;
static double *H = NULL;
static double *Q = NULL;
static gsl_vector *ud_g = NULL;
static gsl_vector *ld_g = NULL;
static gsl_vector *diag_g = NULL;
static gsl_vector *rhs_g = NULL;
static gsl_vector *tau_g = NULL;
double eta = ((double *) params)[0];
double chi = ((double *) params)[1];
double tQ = ((double *) params)[2];
double u, dlnx, sL, s, sR, dsdx, beta, dbetadx;
double mdot;
double dlnQdlnt;
int i;
/* Allocate memory if necessary */
if (grd->nr != nr) {
nr = grd->nr;
rmin = -1.0;
rmax = -1.0;
/* If previously allocated, free */
if (x != NULL) free(x);
if (h1 != NULL) free(h1);
if (h0 != NULL) free(h0);
if (H != NULL) free(H);
if (Q != NULL) free(Q);
if (ud_g != NULL) gsl_vector_free(ud_g);
if (ld_g != NULL) gsl_vector_free(ld_g);
if (diag_g != NULL) gsl_vector_free(diag_g);
if (rhs_g != NULL) gsl_vector_free(rhs_g);
if (tau_g != NULL) gsl_vector_free(tau_g);
/* Allocate new memory */
if (!(x = calloc(grd->nr, sizeof(double)))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(h1 = calloc(grd->nr, sizeof(double)))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(h0 = calloc(grd->nr, sizeof(double)))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(H = calloc(grd->nr, sizeof(double)))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(Q = calloc(grd->nr, sizeof(double)))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(ud_g = gsl_vector_alloc(grd->nr+1))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(ld_g = gsl_vector_alloc(grd->nr+1))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(diag_g = gsl_vector_alloc(grd->nr+2))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(rhs_g = gsl_vector_alloc(grd->nr+2))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
if (!(tau_g = gsl_vector_alloc(grd->nr+2))) {
fprintf(stderr, "Error: unable to allocate memory in userAlpha!\n");
exit(1);
}
}
/* Initailize x if necessary */
if ((rmin != grd->r_h[0]) || (rmax != grd->r_h[grd->nr+1])) {
for (i=0; i<grd->nr; i++) x[i] = grd->r_g[i+1]/grd->r_h[grd->nr];
rmin = grd->r_h[0];
rmax = grd->r_h[grd->nr+1];
}
/* Compute coefficients of torque equation */
dlnx = log(grd->r_g[1]/grd->r_g[0]);
for (i=0; i<grd->nr; i++) {
/* Define dimensionless velocity */
u = grd->vphi_g[i+1] / grd->vphi_h[grd->nr];
/* Note: compute derivatives of s using one-sided differences at
edge cells, centered-limited differences elsewhere. */
if (i==0) {
s = sL = sqrt(pres[0]/col[0])/grd->vphi_h[grd->nr];
sR = sqrt(pres[1]/col[1])/grd->vphi_h[grd->nr];
dsdx = (sR - sL) / (x[i]*dlnx);
} else if (i==grd->nr-1) {
sL = sqrt(pres[grd->nr-2]/col[grd->nr-2])/grd->vphi_h[grd->nr];
s = sR = sqrt(pres[grd->nr-1]/col[grd->nr-1])/grd->vphi_h[grd->nr];
dsdx = (sR - sL) / (x[i]*dlnx);
} else {
sL = sqrt(pres[i+1]/col[i+1])/grd->vphi_h[grd->nr];
s = sqrt(pres[i]/col[i])/grd->vphi_h[grd->nr];
sR = sqrt(pres[i-1]/col[i-1])/grd->vphi_h[grd->nr];
dsdx = ((sL-s)*(s-sR)) > 0 ? (sL-sR)/(2.0*x[i]*dlnx) : 0;
}
/* Compute derivative of beta using centered difference */
beta = grd->beta_g[i+1];
dbetadx = (grd->beta_h[i+1] - grd->beta_h[i]) / (x[i]*dlnx);
/* Compute torque equation coefficients */
h1[i] = -(5.0*(beta+1)*x[i]*dsdx + 2.0*s*(beta+SQR(beta)+x[i]*dbetadx)) /
(2.0*(beta+1)*s*x[i]);
h0[i] = (SQR(beta)-1) * SQR(u/(x[i]*s)) / 2.0;
Q[i] = sqrt(2.0*(1+beta))*grd->vphi_g[i+1]/grd->r_g[i+1] *
s*grd->vphi_h[grd->nr]/(M_PI*G*col[i]);
dlnQdlnt = Q[i] < QCRIT ? -(exp(QCRIT/Q[i]) - exp(1.0))*u/x[i] : 0.0;
H[i] = G*grd->r_h[grd->nr]*u*(1+beta)*col[i] *
(2*M_PI*u*eta - 3*dlnQdlnt/tQ) / (2.0*SQR(grd->vphi_h[grd->nr])*chi);
}
/* Load matrix elements for tridiagonal solve */
for (i=0; i<grd->nr; i++) {
gsl_vector_set(ld_g, i, 1.0/SQR(x[i]*dlnx) +
1.0/(2.0*SQR(x[i])*dlnx) - h1[i]/(2.0*x[i]*dlnx));
gsl_vector_set(diag_g, i+1, -2.0/SQR(x[i]*dlnx) + h0[i]);
gsl_vector_set(ud_g, i+1, 1.0/SQR(x[i]*dlnx) -
1.0/(2.0*SQR(x[i])*dlnx) + h1[i]/(2.0*x[i]*dlnx));
gsl_vector_set(rhs_g, i+1, H[i]);
}
/* Load boundary conditions into matrix */
/* Inner BC: tau = -x in ghost cell */
gsl_vector_set(diag_g, 0, 1);
gsl_vector_set(ud_g, 0, 0);
gsl_vector_set(rhs_g, 0, -grd->r_g[0]/grd->r_h[grd->nr]);
/* Outer BC: tau' = -beta-1 */
gsl_vector_set(ld_g, grd->nr, -1.0/dlnx);
gsl_vector_set(diag_g, grd->nr+1, 1.0/dlnx);
gsl_vector_set(rhs_g, grd->nr+1, -grd->beta_g[grd->nr+1]-1);
/* Solve matrix equation to get dimensionless torque */
gsl_linalg_solve_tridiag(diag_g, ud_g, ld_g, rhs_g, tau_g);
/* Use torque to compute alpha */
mdot = chi*SQR(grd->vphi_h[grd->nr])*grd->vphi_h[grd->nr] / G;
for (i=0; i<grd->nr; i++) {
alpha[i] = -gsl_vector_get(tau_g, i+1)*mdot*grd->vphi_h[grd->nr] *
grd->r_h[grd->nr] /
(2.0*M_PI*SQR(grd->r_g[i+1])*pres[i]);
if (Q[i] > QCRIT) alpha[i] *= exp(-QDAMP*(Q[i]-QCRIT));
if (alpha[i] < 0.0) alpha[i] = ALPHAMIN;
}
}
void
userMassSrc(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
void *params,
double *massSrc) {
fprintf(stderr,
"Warning: userMassSrc function called but not implemented!\n");
return;
}
void
userIntEnSrc(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
void *params,
double *intEnSrc) {
/* Cooling rate = eta Sigma sigma^2 Omega = eta P vphi/r */
int i;
double eta = ((double *) params)[0];
for (i=0; i<grd->nr; i++)
intEnSrc[i] = -eta * pres[i] * grd->vphi_g[i+1] / grd->r_g[i+1];
}
void
userIBC(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
const pres_bc_type ibc_pres, const enth_bc_type ibc_enth,
void *params,
double *ibc_pres_val, double *ibc_enth_val) {
/* Set torque. If Q <= QCRIT in innermost cell, so that disk is
gravitationally unstable at the center, dimensionless torque =
-x, dimensional torque = -(r_in/R) Mdot vphi/R. If Q > QCRIT in
innermost cell, scale down torque in the same way as in
userAlpha. */
double chi = ((double *) params)[1];
double x, mdot, s, Q;
s = sqrt(pres[0]/col[0])/grd->vphi_h[grd->nr];
Q = sqrt(2.0*(1+grd->beta_g[1]))*grd->vphi_g[1]/grd->r_g[1] *
s*grd->vphi_h[grd->nr]/(M_PI*G*col[0]);
mdot = chi*SQR(grd->vphi_h[grd->nr])*grd->vphi_h[grd->nr] / G;
x = grd->r_g[0] / grd->r_h[grd->nr];
*ibc_pres_val = -x * mdot * grd->vphi_g[0] * grd->r_h[grd->nr];
if (Q > QCRIT) *ibc_pres_val *= exp(-QDAMP*(Q-QCRIT));
*ibc_enth_val = gamma[0]/(gamma[0]-1.0)*pres[0]/col[0];
}
void
userOBC(const double t, const double dt, const grid *grd,
const double *col, const double *pres, const double *eInt,
const double *gamma, const double *delta,
const pres_bc_type obc_pres, const enth_bc_type obc_enth,
void *params,
double *obc_pres_val, double *obc_enth_val) {
fprintf(stderr,
"Warning: userOBC function called but not implemented!\n");
return;
}
void
userPreTimestep(const double t, const double dt,
const grid *grd, double *col, double *pres,
double *eInt, double *mBnd, double *eBnd,
double *mSrc, double *eSrc,
void *params, const unsigned long nUserOut,
double *userOut) {
fprintf(stderr,
"Warning: userPreTimestep function called but not implemented!\n");
return;
}
void
userCheckRead(
FILE *fp, grid *grd, const unsigned long nOut,
double *tOut, double *colOut,
double *presOut, double *eIntOut, double *mBndOut,
double *eBndOut, double *mSrcOut, double *eSrcOut,
const unsigned long nUserOut, double *userOut,
void *params
) {
fprintf(stderr,
"Warning: userCheckRead function called but not implemented!\n");
return;
}
void
userCheckWrite(
FILE *fp,
const grid *grd, const unsigned long nOut,
const double *tOut, const double *colOut,
const double *presOut, const double *eIntOut,
const double *mBndOut, const double *eBndOut,
const double *mSrcOut, const double *eSrcOut,
const unsigned long nUserOut, const double *userOut,
const void *params
) {
fprintf(stderr,
"Warning: userCheckWrite function called but not implemented!\n");
return;
}
| {
"alphanum_fraction": 0.5968113715,
"avg_line_length": 35.1756756757,
"ext": "c",
"hexsha": "c3f86c23cf44ec453f4a046deab096488f8b96a7",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z",
"max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "franciscaconcha/amuse-vader",
"max_forks_repo_path": "src/amuse/community/vader/src/prob/userFunc_gidisk.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "franciscaconcha/amuse-vader",
"max_issues_repo_path": "src/amuse/community/vader/src/prob/userFunc_gidisk.c",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "franciscaconcha/amuse-vader",
"max_stars_repo_path": "src/amuse/community/vader/src/prob/userFunc_gidisk.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3552,
"size": 10412
} |
#ifndef TREE_H
#define TREE_H
#include "node.h"
#include <string>
#include <vector>
#include <gsl/gsl_rng.h>
#include "data.h"
using namespace std;
namespace weakarg
{
extern gsl_rng * rng;
/**
@brief Genealogy of the isolates under study
*/
class Tree
{
protected:
Node * root;///<Root node of the genealogy
std::vector<Node*> nodes;///<Vector of all the nodes in the genealogy
int n;///<Number of isolates
double ttotal;///<Sum of branch lengths
public:
Tree(std::string newick,bool isFilename=true,bool forceages=true);///<Creates a tree from a Newick file
Tree(int n);///< Creates a Coalescent tree by simulation
Tree(Tree *intree);///< Creates a copy of a tree via newick (== slow)
Tree(Data * data);///< Creates a UPGMA tree
Tree(const Tree& t);///< Copy constructor
void assign(const Tree& t);///< Copy a tree while allocating as little new storage as possible
~Tree();
std::string newick(int p=6) const; ///<Returns a Newick description of the tree (precision options)
std::string newickNoInternalLabels(int p=6) const; ///<Returns a Newick description of the tree (precision options)
void makeFromNewick(std::string newick,bool forceages=false);///< Creates a tree from a newick string
inline int getN() const
{
return n;
}///<Returns the number of isolates
inline Node* getNode(int i) const
{
return nodes[i];
}///<Returns a node given its index
inline Node* getRoot() const
{
return root;
}///<Returns the root node
inline double getDist(int i) const
{
return nodes[i]->getDist();
}///<Returns the time of a node given its index
double prior() const; ///<Returns log-prior of the tree
inline double getTTotal() const
{
return ttotal;
}///<Returns the sum of branch lengths
void computeTTotal(); ///<Computes the sum of branch lengths
int getPoint(double * dist, std::vector<int> * samplespace=NULL) const; ///<Returns a point chosen uniformly at random on the tree, or uniformally on a subspace of specified clonal edges
std::vector<int> getAllChildren(int e);///<Returns a vector of the indices of the children of a given node
std::vector<int> getAllSampledSeqs(int e);///<Returns a vector of all the observed sequences of the children of a given node
void orderNodes(double dist=1);///<orders the list by age
int orderNodes(int which, double dist);///<places a node in a new place in the list
void swapFather(int a,int b);///<Swaps the father of two nodes
void swapNode(int a, int b);///<Swaps two nodes in the list
int getOldestReversedNode();///<Returns the oldest node that has been age reversed
void testNodeAges() const; ///<Tests node ages
double tavare() const;
inline int otherChild(int par,int onechild){
if(getNode(par)->getLeft()->getId()==onechild) return(getNode(par)->getRight()->getId());
else if(getNode(par)->getRight()->getId()==onechild) return(getNode(par)->getLeft()->getId());
else{cerr<<"Error in RecTree::otherChild: parent doesn't have a suitable child!"<<endl;throw("unknown child error");}
};
std::vector<int> getMinEdgeList(std::vector<int> seqs);
int getNextGroup(std::vector<int> *seqs);
bool isParentToOnly(int e, std::vector<int> seqs,std::vector<int> *which);
};
} // end namespace weakarg
#endif
| {
"alphanum_fraction": 0.6837126811,
"avg_line_length": 39.8,
"ext": "h",
"hexsha": "d627d86a5467e3dd75d6d3887940dd8a78dfe82a",
"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/tree.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/tree.h",
"max_line_length": 190,
"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/tree.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 852,
"size": 3383
} |
/**
* Copyright 2019 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es>
*
* This file is part of Matrix Market Suite.
*
* Matrix Market Suite 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.
*
* Matrix Market Suite 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 Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cblas.h>
#include "ConjugateGradientSolver.h"
int ConjugateGradientSolver(unsigned long *II, unsigned long *J, double *A, unsigned long M, unsigned long N, unsigned long long nz, double *b, unsigned long M_Vector, unsigned long N_Vector, unsigned long long nz_vector, double *x, int iterationNumber) {
//A*x=b
double *Ap=(double *) malloc(nz_vector * sizeof(double));
double *r=(double *) malloc(nz_vector * sizeof(double));
double *p=(double *) malloc(nz_vector * sizeof(double));
//double *x=(double *) calloc(nz_vector,sizeof(double));
//r = b-A*x
//If we take x=0 the init multiplication is avoided and r=b
memcpy(r, b, N*sizeof(double));
//p=r
memcpy(p, r, N*sizeof(double));
//rsold = r*r
double rsold = cblas_ddot(N,r,1,r,1);
int stop = 0;
double alphaCG = 0.0;
double rsnew = 0.0;
unsigned long k = 0;
unsigned long maxIterations = M*2;
if(iterationNumber != 0 ){
maxIterations = iterationNumber;
}
//int i = 0;
while(!stop){
//Ap=A*p
// for(i=0; i<M; i++){
// Ap[i] = 0.0;
// }
cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, p, 1, 0.0, Ap, 1);
//alphaCG=rsold/(p'*Ap)
alphaCG = rsold/cblas_ddot(N,p,1,Ap,1);
//x=x+alphaCG*p
cblas_daxpy(N,alphaCG,p,1,x,1);
//r=r-alphaCG*Ap
cblas_daxpy(N,-alphaCG,Ap,1,r,1);
//rsnew = r'*r
rsnew = cblas_ddot(N,r,1,r,1);
if((sqrt(rsnew)<=EPSILON)||(k == maxIterations)){
stop = 1;
}
//p=r+rsnew/rsold*p
cblas_dscal(N, rsnew/rsold, p, 1);
cblas_daxpy(N,1.0,r,1,p,1);
rsold = rsnew;
k++;
}
//memcpy(b, x, N*sizeof(double));
free(Ap);
free(r);
free(p);
//free(x);
fprintf(stderr, "[%s] Number of iterations %lu\n",__func__,k);
return 1;
}
| {
"alphanum_fraction": 0.6443498452,
"avg_line_length": 24.8461538462,
"ext": "c",
"hexsha": "277c12d5b98cc43bc06690908eb4d1ad44667416",
"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": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "vkeller/math-454",
"max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/solvers/ConjugateGradientSolver.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"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": "vkeller/math-454",
"max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/solvers/ConjugateGradientSolver.c",
"max_line_length": 255,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "vkeller/math-454",
"max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/solvers/ConjugateGradientSolver.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z",
"num_tokens": 823,
"size": 2584
} |
/*
* -----------------------------------------------------------------
* Binary Search Tree Library --- bst_lib.c
* Version: 1.6180
* Date: Mar 12, 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 implementation file of a library
* to work with binary search trees.
* -----------------------------------------------------------------
*/
#include <stdlib.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_errno.h>
#include "../include/bst_lib.h"
/*
*------------------------------------------------------------
* bst_leaf_alloc
*
* This function allocates a struct leaf.
*
* Input:
* void
*
* Output:
* leaf - pointer to a struct leaf
*
* last update: May 10, 2009
*------------------------------------------------------------
*/
bst_leaf *bst_leaf_alloc()
{
bst_leaf *leaf = NULL;
/* memory allocation for bst_leaf */
leaf = (bst_leaf *) malloc(sizeof(bst_leaf));
if ( leaf == NULL )
return NULL;
/* setting bst_leaf elements equal to NULL */
leaf->phi = NULL;
leaf->Rphi = NULL;
leaf->A = NULL;
leaf->L = NULL;
return leaf;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_node_alloc
*
* This function allocates a struct node.
*
* Input:
* void
*
* Output:
* node - pointer to a struct node
*
* last update: May 10, 2009
*------------------------------------------------------------
*/
bst_node* bst_node_alloc()
{
bst_node *node = NULL;
/* memory allocation for bst_node */
node = (bst_node *) malloc(sizeof(bst_node));
if ( node == NULL )
return NULL;
/* setting bst_node elements equal to NULL */
node->v = NULL;
node->r_node = NULL;
node->l_node = NULL;
node->r_leaf = NULL;
node->l_leaf = NULL;
return node;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_leaf_free
*
* This function frees the memory used by a struct leaf.
*
* Input:
* leaf - pointer to a struct leaf
*
* Output:
* void
*
* last update: May 9, 2009
*------------------------------------------------------------
*/
void bst_leaf_free(void **leaf_bl)
{
bst_leaf *leaf = NULL;
/* checking if leaf_bl is NULL */
if ( *leaf_bl == NULL )
return;
leaf = (bst_leaf *) (*leaf_bl);
/* releasing bst_leaf elements */
if( leaf->phi != NULL )
{
gsl_vector_free(leaf->phi);
leaf->phi = NULL;
}
if( leaf->Rphi != NULL )
{
gsl_vector_free(leaf->Rphi);
leaf->Rphi = NULL;
}
if( leaf->A != NULL )
{
gsl_matrix_free(leaf->A);
leaf->A = NULL;
}
if( leaf->L != NULL )
{
gsl_matrix_free(leaf->L);
leaf->L = NULL;
}
/* releasing allocated memory by bst_leaf */
free(*leaf_bl);
*leaf_bl = NULL;
return;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_node_free
*
* This function frees the memory used by a struct node.
*
* Input:
* node - pointer to a struct node
*
* Output:
* void
*
* last update: Feb 19, 2010
*------------------------------------------------------------
*/
void bst_node_free(void **node_bl)
{
bst_node *node = NULL;
/* checking if node_bl is NULL */
if ( *node_bl == NULL )
return;
node = (bst_node *) (*node_bl);
/* releasing allocated memory by bst_node elements */
if( node->l_leaf != NULL )
{
bst_leaf_free((void **)&(node->l_leaf));
node->l_leaf = NULL;
}
if( node->r_leaf != NULL )
{
bst_leaf_free((void **)&(node->r_leaf));
node->r_leaf = NULL;
}
if( node->l_node != NULL )
{
bst_node_free((void **)&(node->l_node));
node->l_node = NULL;
}
if( node->r_node != NULL )
{
bst_node_free((void **)&(node->r_node));
node->r_node = NULL;
}
if( node->v != NULL )
{
gsl_vector_free(node->v);
node->v = NULL;
}
/* releasing allocated memory by bst_node */
free(*node_bl);
*node_bl = NULL;
return;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_leaf_set
*
* This function sets the bst_leaf elements equal to
* the input elements and returns GSL_SUCCESS if
* there is no problem during its execution.
*
* Input:
* phi - composition
* Rphi - reaction mapping
* A - mapping gradient matrix
* L - ellipsoid Cholesky matrix
*
* Output:
* leaf - pointer to a struct leaf
* success or error
*
* last update: Feb 22, 2009
*------------------------------------------------------------
*/
int bst_leaf_set(gsl_vector *phi,gsl_vector *Rphi,
gsl_matrix *A,gsl_matrix *L,bst_leaf *leaf)
{
/* checking if leaf is NULL */
if ( leaf == NULL )
return GSL_EFAILED;
/* setting phi equal to the input vector phi */
if ( leaf->phi == NULL )
leaf->phi = gsl_vector_calloc(phi->size);
gsl_vector_memcpy(leaf->phi,phi);
/* setting Rphi equal to the input vector Rphi */
if ( leaf->Rphi == NULL )
leaf->Rphi = gsl_vector_calloc(Rphi->size);
gsl_vector_memcpy(leaf->Rphi,Rphi);
/* setting A equal to the input matrix A */
if ( leaf->A == NULL )
leaf->A = gsl_matrix_calloc(A->size1,A->size2);
gsl_matrix_memcpy(leaf->A,A);
/* setting L equal to the input matrix L */
if ( leaf->L == NULL )
leaf->L = gsl_matrix_calloc(L->size1,L->size2);
gsl_matrix_memcpy(leaf->L,L);
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_cutplane
*
* This function compute the vector ( v = phi_r - phi_l )
* and the scalar ( a = (|phi_r|^2-|phi_l|^2)/2 )
* which define a cutting plane used to search any
* information in the binary search tree.
*
* Input:
* phi_l - left composition
* phi_r - right compositon
*
* Output:
* v - cutting plane normal vector
* a - cutting plane scalar
*
* last update: Feb 27, 2009
*------------------------------------------------------------
*/
double bst_cutplane(gsl_vector *phi_l,gsl_vector *phi_r,gsl_vector *v)
{
double a1, a2;
/* v := phi_r */
gsl_vector_memcpy(v,phi_r);
/* v := phi_r - phi_l */
gsl_vector_sub(v,phi_l);
/* a1 := |phi_r|^2 */
gsl_blas_ddot(phi_r,phi_r,&a1);
/* a2 := |phi_l|^2 */
gsl_blas_ddot(phi_l,phi_l,&a2);
return 0.5*(a1-a2);
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_node_set
*
* This function set the bst_node elements equal to
* the input elements and define the vector and
* scalar to do the search for a information.
*
* Input:
* l_leaf - left leaf
* r_leaf - right leaf
*
* Output:
* node - pointer to a struct node
* success or error
*
* last update: Feb 27, 2009
*------------------------------------------------------------
*/
int bst_node_set(bst_leaf *l_leaf,bst_leaf *r_leaf,bst_node *node)
{
/* checking if node is NULL */
if ( node == NULL )
return GSL_EFAILED;
/* memory allocation for v */
if ( node->v == NULL )
node->v = gsl_vector_calloc(r_leaf->phi->size);
/* setting v and a */
node->a = bst_cutplane(l_leaf->phi,r_leaf->phi,node->v);
/* setting leaf elements equal to the input leaves */
node->l_leaf = l_leaf;
node->r_leaf = r_leaf;
/* setting node elements equal to NULL */
node->l_node = NULL;
node->r_node = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_node_add
*
* This function adds a new node to a given side
* of a old node and returns GSL_SUCCESS if
* there is no problem during its execution.
*
* Input:
* side - new node side
* old_node - pointer to the old node
* new_node - pointer to the new node
*
* Output:
* success or error
*
* last update: Feb 22, 2009
*------------------------------------------------------------
*/
int bst_node_add(int side,bst_node *old_node,bst_node *new_node)
{
if( side == RIGHT )
{
if( old_node->r_node != NULL )
return GSL_EFAILED;
else
{
/* adding a new right node */
old_node->r_node = new_node;
old_node->r_leaf = NULL;
return GSL_SUCCESS;
}
}
else if( side == LEFT )
{
if( old_node->l_node != NULL )
return GSL_EFAILED;
else
{
/* adding a new left node */
old_node->l_node = new_node;
old_node->l_leaf = NULL;
return GSL_SUCCESS;
}
}
else
return GSL_EFAILED;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_search
*
* This function searchs for a near composition phi0 in the
* binary search tree.
*
* Input:
* root - binary tree root
* phi - composition
*
* Output:
* end_leaf - leaf with the near composition
* end_node - node with the near composition
* side - near compositon leaf side
*
* last update: Feb 3, 2009
*------------------------------------------------------------
*/
int bst_search(bst_node *root,gsl_vector *phi,
bst_node **end_node,bst_leaf **end_leaf)
{
double dot;
if( root == NULL )
{
*end_leaf = NULL;
*end_node = NULL;
return GSL_EFAILED;
}
/* dot := v^T*phi */
gsl_blas_ddot(root->v,phi,&dot);
/* if dot > a then right node else left node */
if( dot > root->a )
{
/* extern node */
if( root->r_node == NULL )
{
*end_leaf = root->r_leaf;
*end_node = root;
return RIGHT;
}
else
return bst_search(root->r_node,phi,end_node,end_leaf);
}
else
{
/* extern node */
if( root->l_node == NULL )
{
*end_leaf = root->l_leaf;
*end_node = root;
return LEFT;
}
else
return bst_search(root->l_node,phi,end_node,end_leaf);
}
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* bst_height
*
* This function computes the binary search tree height.
*
* Input:
* root - binary tree root
*
* Output:
* height - binary search tree height
*
* last update: Nov 2, 2009
*------------------------------------------------------------
*/
int bst_height(bst_node *root)
{
int l_tree_height = 0;
int r_tree_height = 0;
if ( root != NULL )
{
l_tree_height = bst_height(root->l_node);
r_tree_height = bst_height(root->r_node);
if ( l_tree_height > r_tree_height )
return l_tree_height + 1;
else
return r_tree_height + 1;
}
else
return 0;
}
/*------------------------------------------------------------*/
| {
"alphanum_fraction": 0.4674925043,
"avg_line_length": 22.1573426573,
"ext": "c",
"hexsha": "fddb9d328bd60e2b2970c6cbfe137d316e4631d7",
"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/src/bst_lib.c",
"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/src/bst_lib.c",
"max_line_length": 70,
"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/src/bst_lib.c",
"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": 2997,
"size": 12674
} |
#include "std_includes.h"
#ifndef MATRIX_H
#define MATRIX_H
#ifdef CRANIUM_USE_MKL
#define CRANIUM_USE_BLAS
#include "mkl.h"
#else
#ifdef CRANIUM_USE_CBLAS
#define CRANIUM_USE_BLAS
#include <cblas.h>
#endif
#endif
// represents user-supplied training data
typedef struct DataSet_ {
size_t rows;
size_t cols;
float** data;
} DataSet;
// represents a matrix of data in row-major order
typedef struct Matrix_ {
size_t rows;
size_t cols;
float* data;
} Matrix;
#ifndef RAND_MOD
#define RAND_MOD 2147483647
#endif
// create dataset given user data
static DataSet* createDataSet(size_t rows, size_t cols, float** data);
// uses memory of the original data to split dataset into batches
static DataSet** createBatches(DataSet* allData, int numBatches);
// split a dataset into row matrices
static Matrix** splitRows(DataSet* dataset);
// destroy dataset
static void destroyDataSet(DataSet* dataset);
// convert dataset to matrix
static Matrix* dataSetToMatrix(DataSet* dataset);
// creates a matrix given data
static Matrix* createMatrix(size_t rows, size_t cols, float* data);
// creates a matrix zeroed out
static Matrix* createMatrixZeroes(size_t rows, size_t cols);
// get an element of a matrix
static float getMatrix(Matrix* mat, size_t row, size_t col);
// set an element of a matrix
static void setMatrix(Matrix* mat, size_t row, size_t col, float val);
// sets the values in $to equal to values in $from
static void copyValuesInto(Matrix* from, Matrix* to);
// prints the entries of a matrix
static void printMatrix(Matrix* input);
// sets each entry in matrix to 0
static void zeroMatrix(Matrix* orig);
// returns transpose of matrix
static Matrix* transpose(Matrix* orig);
// transposes matrix and places data into $origT
static void transposeInto(Matrix* orig, Matrix* origT);
// adds two matrices and returns result
static Matrix* add(Matrix* A, Matrix* b);
// adds $from to $to and places result in $to
static void addTo(Matrix* from, Matrix* to);
// adds $B, a row vector, to each row of $A
static Matrix* addToEachRow(Matrix* A, Matrix* B);
// multiplies every element of $orig by $C
static void scalarMultiply(Matrix* orig, float c);
// multiplies $A and $B (ordering: AB) and returns product matrix
static Matrix* multiply(Matrix* A, Matrix* B);
// multiplies $A and $B (ordering: AB) and places values into $into
static void multiplyInto(Matrix* A, Matrix* B, Matrix* into);
// element-wise multiplcation
static Matrix* hadamard(Matrix* A, Matrix* B);
// places values of hadamard product of $A and $B into $into
static void hadamardInto(Matrix* A, Matrix* B, Matrix* into);
// returns a shallow copy of input matrix
static Matrix* copy(Matrix* orig);
// returns 1 if matrices are equal, 0 otherwise
static int equals(Matrix* A, Matrix* B);
// frees a matrix and its data
static void destroyMatrix(Matrix* matrix);
/*
Begin functions.
*/
static DataSet* createDataSet(size_t rows, size_t cols, float** data){
DataSet* dataset = (DataSet*)malloc(sizeof(DataSet));
dataset->rows = rows;
dataset->cols = cols;
dataset->data = data;
return dataset;
}
DataSet** createBatches(DataSet* allData, int numBatches){
DataSet** batches = (DataSet**)malloc(sizeof(DataSet*) * numBatches);
int remainder = allData->rows % numBatches;
int i;
int curRow = 0;
for (i = 0; i < numBatches; i++){
size_t batchSize = allData->rows / numBatches;
if (remainder-- > 0){
batchSize++;
}
batches[i] = createDataSet(batchSize, allData->cols, allData->data + curRow);
curRow += batchSize;
}
return batches;
}
static Matrix** splitRows(DataSet* dataset){
Matrix** rows = (Matrix**)malloc(sizeof(Matrix*) * dataset->rows);
int i;
for (i = 0; i < dataset->rows; i++){
rows[i] = createMatrix(1, dataset->cols, dataset->data[i]);
}
return rows;
}
void shuffleTogether(DataSet* A, DataSet* B, std::minstd_rand &gen){
assert(A->rows == B->rows);
int i;
for (i = 0; i < A->rows - 1; i++){
size_t j = i + gen() / (RAND_MOD / (A->rows - i) + 1);
float* tmpA = A->data[j];
A->data[j] = A->data[i];
A->data[i] = tmpA;
float* tmpB = B->data[j];
B->data[j] = B->data[i];
B->data[i] = tmpB;
}
}
static void destroyDataSet(DataSet* dataset){
int i;
for (i = 0; i < dataset->rows; i++){
free(dataset->data[i]);
}
free(dataset->data);
free(dataset);
}
static Matrix* dataSetToMatrix(DataSet* dataset){
Matrix* convert = (Matrix*)malloc(sizeof(Matrix));
convert->rows = dataset->rows;
convert->cols = dataset->cols;
convert->data = (float*)malloc(sizeof(float) * dataset->rows * dataset->cols);
int i, j;
for (i = 0; i < dataset->rows; i++){
for (j = 0; j < dataset->cols; j++){
setMatrix(convert, i, j, dataset->data[i][j]);
}
}
return convert;
}
Matrix* createMatrix(size_t rows, size_t cols, float* data){
assert(rows > 0 && cols > 0);
Matrix* matrix = (Matrix*)malloc(sizeof(Matrix));
matrix->rows = rows;
matrix->cols = cols;
matrix->data = data;
return matrix;
}
Matrix* createMatrixZeroes(size_t rows, size_t cols){
assert(rows > 0 && cols > 0);
Matrix* matrix = (Matrix*)malloc(sizeof(Matrix));
matrix->rows = rows;
matrix->cols = cols;
float* data = (float*)calloc(rows * cols, sizeof(float));
matrix->data = data;
return matrix;
}
inline float getMatrix(Matrix* mat, size_t row, size_t col){
return mat->data[row * mat->cols + col];
}
inline void setMatrix(Matrix* mat, size_t row, size_t col, float val){
mat->data[row * mat->cols + col] = val;
}
void copyValuesInto(Matrix* from, Matrix* to){
assert(from->rows == to->rows && from->cols == to->cols);
memcpy(to->data, from->data, sizeof(float) * to->rows * to->cols);
}
void printMatrix(Matrix* input){
int i, j;
for (i = 0; i < input->rows; i++){
printf("\n");
for (j = 0; j < input->cols; j++){
printf("%.2f ", getMatrix(input, i, j));
}
}
printf("\n");
}
void zeroMatrix(Matrix* orig){
memset(orig->data, 0, orig->rows * orig->cols * sizeof(float));
}
Matrix* transpose(Matrix* orig){
float* data = (float*)malloc(sizeof(float) * orig->rows * orig->cols);
Matrix* transpose = createMatrix(orig->cols, orig->rows, data);
int i, j;
for (i = 0; i < orig->rows; i++){
for (j = 0; j < orig->cols; j++){
setMatrix(transpose, i, j, getMatrix(orig, i, j));
}
}
return transpose;
}
void transposeInto(Matrix* orig, Matrix* origT){
assert(orig->rows == origT->cols && orig->cols == origT->rows);
int i, j;
for (i = 0; i < orig->rows; i++){
for (j = 0; j < orig->cols; j++){
setMatrix(origT, j, i, getMatrix(orig, i, j));
}
}
}
Matrix* add(Matrix* A, Matrix* B){
assert(A->rows == B->rows && A->cols == B->cols);
float* data = (float*)malloc(sizeof(float) * A->rows * B->rows);
Matrix* result = createMatrix(A->rows, A->cols, data);
int i, j;
for (i = 0; i < A->rows; i++){
for (j = 0; j < A->cols; j++){
setMatrix(result, i, j, getMatrix(B, i, j) + getMatrix(A, i, j));
}
}
return result;
}
void matrix_mul_add(Matrix * to, float a, Matrix * x, float b, bool square = false) {
assert(to->rows == x->rows && to->cols == x->cols);
int i, j;
for (i = 0; i < to->rows; i++) {
if (!square) {
for (j = 0; j < to->cols; j++)
setMatrix(to, i, j, getMatrix(to, i, j) * a + getMatrix(x, i, j) * b);
}
else for (j = 0; j < to->cols; j++) {
float val = getMatrix(x, i, j);
setMatrix(to, i, j, getMatrix(to, i, j) * a + val * val * b);
}
}
}
void matrix_replace(Matrix * to, Matrix * x, float b) {
assert(to->rows == x->rows && to->cols == x->cols);
int i, j;
for (i = 0; i < to->rows; i++) {
for (j = 0; j < to->cols; j++)
setMatrix(to, i, j, getMatrix(x, i, j) * b);
}
}
void adam_update(Matrix * to, Matrix * m, Matrix * v, float a) {
assert(to->rows == m->rows && to->cols == m->cols);
assert(to->rows == v->rows && to->cols == v->cols);
int i, j;
for (i = 0; i < to->rows; i++) {
for (j = 0; j < to->cols; j++)
setMatrix(to, i, j, (getMatrix(m, i, j) * a) / (sqrt(getMatrix(v, i, j)) + 0.000000001));
}
}
void addTo(Matrix* from, Matrix* to){
assert(from->rows == to->rows && from->cols == to->cols);
int i, j;
for (i = 0; i < from->rows; i++){
for (j = 0; j < from->cols; j++){
setMatrix(to, i, j, getMatrix(from, i, j) + getMatrix(to, i, j));
}
}
}
// add B to each row of A
Matrix* addToEachRow(Matrix* A, Matrix* B){
assert(A->cols == B->cols && B->rows == 1);
float* data = (float*)malloc(sizeof(float) * A->rows * A->cols);
Matrix* result = createMatrix(A->rows, A->cols, data);
int i, j;
for (i = 0; i < A->rows; i++){
for (j = 0; j < A->cols; j++){
setMatrix(result, i, j, getMatrix(A, i, j) + getMatrix(B, 0, j));
}
}
return result;
}
void scalarMultiply(Matrix* orig, float c){
int i, j;
for (i = 0; i < orig->rows; i++){
for (j = 0; j < orig->cols; j++){
setMatrix(orig, i, j, getMatrix(orig, i, j) * c);
}
}
}
Matrix* multiply(Matrix* A, Matrix* B){
assert(A->cols == B->rows);
float* data = (float*)malloc(sizeof(float) * A->rows * B->cols);
Matrix* result = createMatrix(A->rows, B->cols, data);
#ifdef CRANIUM_USE_BLAS
zeroMatrix(result);
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A->rows, B->cols
, A->cols, 1, A->data, A->cols, B->data, B->cols, 1, result->data, result->cols);
return result;
#endif
int i, j;
for (i = 0; i < A->rows; i++){
for (j = 0; j < B->cols; j++){
float sum = 0;
int k;
for (k = 0; k < B->rows; k++){
sum += getMatrix(A, i, k) * getMatrix(B, k, j);
}
setMatrix(result, i, j, sum);
}
}
return result;
}
void multiplyInto(Matrix* A, Matrix* B, Matrix* into){
#ifdef CRANIUM_USE_BLAS
zeroMatrix(into);
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A->rows, B->cols
, A->cols, 1, A->data, A->cols, B->data, B->cols, 1, into->data, into->cols);
return;
#endif
assert(A->cols == B->rows);
assert(A->rows == into->rows && B->cols == into->cols);
int i, j;
for (i = 0; i < A->rows; i++){
for (j = 0; j < B->cols; j++){
float sum = 0;
int k;
for (k = 0; k < B->rows; k++){
sum += getMatrix(A, i, k) * getMatrix(B, k, j);
}
setMatrix(into, i, j, sum);
}
}
}
Matrix* hadamard(Matrix* A, Matrix* B){
assert(A->rows == B->rows && A->cols == B->cols);
float* data = (float*)malloc(sizeof(float) * A->rows * A->cols);
Matrix* result = createMatrix(A->rows, A->cols, data);
int i, j;
for (i = 0; i < A->rows; i++){
for (j = 0; j < A->cols; j++){
setMatrix(result, i, j, getMatrix(A, i, j) * getMatrix(B, i, j));
}
}
return result;
}
void hadamardInto(Matrix* A, Matrix* B, Matrix* into){
assert(A->rows == B->rows && A->cols == B->cols);
assert(A->rows == into->rows && A->cols == into->cols);
int i, j;
for (i = 0; i < A->rows; i++){
for (j = 0; j < A->cols; j++){
setMatrix(into, i, j, getMatrix(A, i, j) * getMatrix(B, i, j));
}
}
}
Matrix* copy(Matrix* orig){
float* data = (float*)malloc(sizeof(float) * orig->rows * orig->cols);
memcpy(data, orig->data, sizeof(float) * orig->cols * orig->rows);
return createMatrix(orig->rows, orig->cols, data);
}
int equals(Matrix* A, Matrix* B){
if (A->rows != B->rows){
return 0;
}
if (A->cols != B->cols){
return 0;
}
int i, j;
for (i = 0; i < A->rows; i++){
for (j = 0; j < A->cols; j++){
if (getMatrix(A, i, j) != getMatrix(B, i, j)){
return 0;
}
}
}
return 1;
}
void destroyMatrix(Matrix* matrix){
free(matrix->data);
free(matrix);
}
#endif | {
"alphanum_fraction": 0.5593767215,
"avg_line_length": 29.4143518519,
"ext": "h",
"hexsha": "9ce3a18507c661ed2b77a945a9237231b0b2fee0",
"lang": "C",
"max_forks_count": 35,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T07:13:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-27T01:44:07.000Z",
"max_forks_repo_head_hexsha": "043090bdb60bcb77b51ebf6c56f8d19b43814eed",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "ewail/DiaNN",
"max_forks_repo_path": "cranium/src/matrix.h",
"max_issues_count": 197,
"max_issues_repo_head_hexsha": "043090bdb60bcb77b51ebf6c56f8d19b43814eed",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T10:35:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-18T03:00:16.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "ewail/DiaNN",
"max_issues_repo_path": "cranium/src/matrix.h",
"max_line_length": 93,
"max_stars_count": 89,
"max_stars_repo_head_hexsha": "043090bdb60bcb77b51ebf6c56f8d19b43814eed",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "ewail/DiaNN",
"max_stars_repo_path": "cranium/src/matrix.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-16T03:30:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-16T09:16:13.000Z",
"num_tokens": 3703,
"size": 12707
} |
#pragma once
#include "BasicTypes.h"
#include "CharInfo.h"
#include "Distance.h"
#include "FontTypes.h"
#include "types/ND0.h"
#include "types/ND1_Node.h"
#include "types/ND1_Box.h"
#include "types/ND2_Char.h"
#include "types/ND2_Box.h"
#include "types/ND2_Rule.h"
#include "types/ND2_Glue.h"
#include "types/ND2_Kern.h"
#include "types/ND2_Penalty.h"
#include <gsl.h>
#include <list>
| {
"alphanum_fraction": 0.7338501292,
"avg_line_length": 20.3684210526,
"ext": "h",
"hexsha": "7741ef9fc9b866a0203787414766e71be4ac10db",
"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": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "robin33n/formulae-cxx",
"max_forks_repo_path": "include/node/BoxTypes.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "robin33n/formulae-cxx",
"max_issues_repo_path": "include/node/BoxTypes.h",
"max_line_length": 30,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "robin33n/formulae-cxx",
"max_stars_repo_path": "include/node/BoxTypes.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z",
"num_tokens": 122,
"size": 387
} |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef BITVEC_H
#define BITVEC_H
#include <gsl/gsl_assert> // for Expects
#include <gsl/gsl_util> // for narrow_cast, narrow
using gsl::narrow_cast;
#include <cstddef> // for ptrdiff_t, size_t, nullptr_t
#include <iterator> // for reverse_iterator, distance, random_access_...
#include <memory>
#ifdef _MSC_VER
#pragma warning(push)
// turn off some warnings that are noisy about our Expects statements
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4702) // unreachable code
// Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool.
#pragma warning( \
disable : 26495) // uninitalized member when constructor calls constructor
#pragma warning( \
disable : 26446) // parser bug does not allow attributes on some templates
#endif // _MSC_VER
namespace gb {
template <std::ptrdiff_t Extent> class bitvec {
public:
// constants and types
using element_type = unsafe_bit_t;
using value_type = std::remove_cv_t<element_type>;
using index_type = std::ptrdiff_t;
using pointer = shared_ptr_unsynchronized<element_type>;
using iterator = details::span_iterator<bitvec<Extent>, false>;
using const_iterator = details::span_iterator<bitvec<Extent>, true>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using size_type = index_type;
// [bitvec.cons], bitvec constructors, copy, assignment, and destructor
template <bool Dependent = false,
// "Dependent" is needed to make "std::enable_if_t<Dependent ||
// Extent <= 0>" SFINAE, since "std::enable_if_t<Extent <= 0>" is
// ill-formed when Extent is greater than 0.
class = std::enable_if_t<(Dependent || Extent <= 0)>>
bitvec() noexcept : storage_(nullptr, details::extent_type<0>()) {};
bitvec(pointer ptr, index_type count) : storage_(ptr, count) {}
bitvec(const bitvec &other) noexcept = default;
template <std::ptrdiff_t OtherExtent,
class = std::enable_if_t<OtherExtent == Extent ||
Extent == dynamic_extent>>
bitvec(const bitvec<OtherExtent> &other)
: storage_(other.data(),
details::extent_type<OtherExtent>(other.size())) {}
~bitvec() noexcept = default;
bitvec &operator=(const bitvec &other) noexcept = default;
inline void operator=(bool value) {
write(*this, value);
};
template <std::ptrdiff_t OtherExtent>
void operator&=(const bitvec<OtherExtent> &other) noexcept {
static_assert(Extent == OtherExtent || Extent == dynamic_extent || OtherExtent == dynamic_extent,
"Mismatching operand sizes");
_and(*this, *this, other);
};
template <std::ptrdiff_t OtherExtent>
void operator|=(const bitvec<OtherExtent> &other) noexcept {
static_assert(Extent == OtherExtent || Extent == dynamic_extent || OtherExtent == dynamic_extent,
"Mismatching operand sizes");
_or(*this, *this, other);
};
template <std::ptrdiff_t OtherExtent>
void operator^=(const bitvec<OtherExtent> &other) noexcept {
static_assert(Extent == OtherExtent || Extent == dynamic_extent || OtherExtent == dynamic_extent,
"Mismatching operand sizes");
_xor(*this, *this, other);
};
// [bitvec.sub], bitvec subviews
template <std::ptrdiff_t Count> bitvec<Count> first() const {
Expects(Count >= 0 && Count <= size());
return {data(), Count};
}
template <std::ptrdiff_t Count = 1>
GSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute
bitvec<Count> last() const {
Expects(Count >= 0 && size() - Count >= 0);
return {data_plus(size() - Count), Count};
}
template <std::ptrdiff_t Offset, std::ptrdiff_t Count = dynamic_extent>
GSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute
auto subspan() const ->
typename details::calculate_subspan_type<Extent, Offset, Count>::type {
Expects((Offset >= 0 && size() - Offset >= 0) &&
(Count == dynamic_extent ||
(Count >= 0 && Offset + Count <= size())));
return {data_plus(Offset),
Count == dynamic_extent ? size() - Offset : Count};
}
template <std::ptrdiff_t Count>
bitvec<Count> subspan(std::ptrdiff_t offset) const {
Expects((offset >= 0 && size() - offset >= 0) &&
(Count == dynamic_extent ||
(Count >= 0 && offset + Count <= size())));
return {data_plus(offset),
Count == dynamic_extent ? size() - offset : Count};
}
bitvec<dynamic_extent> first(index_type count) const {
Expects(count >= 0 && count <= size());
return {data(), count};
}
bitvec<dynamic_extent> last(index_type count) const {
return make_subspan(size() - count, dynamic_extent,
subspan_selector<Extent>{});
}
bitvec<dynamic_extent> subspan(index_type offset,
index_type count = dynamic_extent) const {
return make_subspan(offset, count, subspan_selector<Extent>{});
}
// [bitvec.obs], bitvec observers
index_type size() const noexcept { return storage_.size(); }
index_type size_bytes() const noexcept {
return size() * narrow_cast<index_type>(sizeof(element_type));
}
bool empty() const noexcept { return size() == 0; }
bitvec<1> operator[](index_type idx) const { return {data_plus(idx), 1}; }
pointer at(index_type idx) const {
Expects(CheckRange(idx, idx < storage_.size()));
return data()[idx];
}
pointer operator()(index_type idx) const { return this->operator[](idx); }
pointer data() const noexcept { return storage_.data(); }
element_type *cptr() const noexcept { return storage_.data().get(); }
// [bitvec.iter], bitvec iterator support
iterator begin() const noexcept { return {this, 0}; }
iterator end() const noexcept { return {this, size()}; }
const_iterator cbegin() const noexcept { return {this, 0}; }
const_iterator cend() const noexcept { return {this, size()}; }
reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; }
reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; }
const_reverse_iterator crbegin() const noexcept {
return const_reverse_iterator{cend()};
}
const_reverse_iterator crend() const noexcept {
return const_reverse_iterator{cbegin()};
}
#ifdef _MSC_VER
// Tell MSVC how to unwrap spans in range-based-for
pointer _Unchecked_begin() const noexcept { return data(); }
pointer _Unchecked_end() const noexcept {
GSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute
return data() + size();
}
#endif // _MSC_VER
private:
static constexpr bool CheckRange(index_type idx, index_type size) {
// Optimization:
//
// idx >= 0 && idx < size
// =>
// static_cast<size_t>(idx) < static_cast<size_t>(size)
//
// because size >=0 by bitvec construction, and negative idx will
// wrap around to a value always greater than size when casted.
// check if we have enough space to wrap around
if (sizeof(index_type) <= sizeof(size_t)) {
return narrow_cast<size_t>(idx) < narrow_cast<size_t>(size);
} else {
return idx >= 0 && idx < size;
}
}
// Needed to remove unnecessary null check in subspans
struct KnownNotNull {
pointer p;
};
// this implementation detail class lets us take advantage of the
// empty base class optimization to pay for only storage of a single
// pointer in the case of fixed-size spans
template <class ExtentType> class storage_type : public ExtentType {
public:
// KnownNotNull parameter is needed to remove unnecessary null check
// in subspans and constructors from arrays
template <class OtherExtentType>
storage_type(KnownNotNull data, OtherExtentType ext)
: ExtentType(ext), data_(data.p) {
Expects(ExtentType::size() >= 0);
}
template <class OtherExtentType>
storage_type(pointer data, OtherExtentType ext)
: ExtentType(ext), data_(data) {
Expects(ExtentType::size() >= 0);
Expects(data || ExtentType::size() == 0);
}
pointer data() const noexcept { return data_; }
private:
pointer data_;
};
storage_type<details::extent_type<Extent>> storage_;
// The rest is needed to remove unnecessary null check
// in subspans and constructors from arrays
bitvec(KnownNotNull ptr, index_type count) : storage_(ptr, count) {}
template <std::ptrdiff_t CallerExtent> class subspan_selector {};
template <std::ptrdiff_t CallerExtent>
bitvec<dynamic_extent> make_subspan(index_type offset, index_type count,
subspan_selector<CallerExtent>) const {
const bitvec<dynamic_extent> tmp(*this);
return tmp.subspan(offset, count);
}
GSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute
bitvec<dynamic_extent> make_subspan(index_type offset, index_type count,
subspan_selector<dynamic_extent>) const {
Expects(offset >= 0 && size() - offset >= 0);
pointer p = data_plus(offset);
if (count == dynamic_extent) {
return {KnownNotNull{p}, size() - offset};
}
Expects(count >= 0 && size() - offset >= count);
return {KnownNotNull{p}, count};
}
private:
// Implements `data() + offset` taking care of ownership.
pointer data_plus(index_type offset) const {
Expects(offset >= 0 && size() - offset >= 0);
// Uses same ref counter as data()
return pointer(data(), data().get() + offset);
}
};
} // namespace gb
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
#endif // BITVEC_H
| {
"alphanum_fraction": 0.67178034,
"avg_line_length": 34.6915254237,
"ext": "h",
"hexsha": "8539417fa595770a79a44fa089a415e482730e30",
"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": "1271f2d65b3390c7156606b266b93c5d23ed398a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "CapacitorSet/Glovebox",
"max_forks_repo_path": "include/bitvec.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a",
"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": "CapacitorSet/Glovebox",
"max_issues_repo_path": "include/bitvec.h",
"max_line_length": 99,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "CapacitorSet/FHE-tools",
"max_stars_repo_path": "include/bitvec.h",
"max_stars_repo_stars_event_max_datetime": "2019-02-26T22:06:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-28T04:50:57.000Z",
"num_tokens": 2487,
"size": 10234
} |
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <float.h>
#include <time.h>
#include <errno.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_errno.h>
#include "function.h"
#include "norm.h"
// Exception system configuration
#define ERR_T int
#define ERR_V ERRNO
#define OK 0
#include "exceptions.h"
// Input
#define MAX_BUF 256
#define MATCH(line, str) !strncmp(line, str, strlen(str))
// User options
#define DEFAULT_TOLERANCE 1.0e-12
#define DEFAULT_REL_TOL 1
#define DEFAULT_MAX_ZERO_DIST 1.0e-12
#define DEFAULT_USER_NORM 0
#define DEFAULT_MAX_ITER 25
#define DEFAULT_MAX_DIV_ITER 10
#define DEFAULT_JX_REUSE 5
struct options {
double tolerance;
char rel_tol;
double max_zero_dist;
char user_norm;
unsigned int max_iter;
unsigned int max_div_iter;
unsigned int jx_reuse;
};
// Result
struct additional_data {
double max_error;
double* fx;
unsigned int iter_count;
double delta_t;
};
// Function declarations
/*
* The result will be stored in x and x0 will contain the difference between x
* and the result of the previous iteration.
*/
ERR_T findroot(int dim, double* x0, double* x, struct options* options,
struct additional_data* data);
ERR_T norm(int dim, double* x, double* n, struct options* options);
ERR_T input_data(char* path, int* dim, double** x0, struct options* options);
void output_result(int dim, double* result, struct additional_data* data);
void output_vector(int dim, double* x);
void handler(const char* reason, const char* file, int line, int gsl_errno);
// Program
int main(int argc, char** argv) {
int dim;
char* path;
double* x = NULL;
double* x0 = NULL;
struct options options;
struct additional_data additional_data;
// Save the conf file path
TRY(1, argc == 2)
path = argv[1];
// Initialize options with default data
options.tolerance = DEFAULT_TOLERANCE;
options.rel_tol = DEFAULT_REL_TOL;
options.max_zero_dist = DEFAULT_MAX_ZERO_DIST;
options.user_norm = DEFAULT_USER_NORM;
options.max_iter = DEFAULT_MAX_ITER;
options.max_div_iter = DEFAULT_MAX_DIV_ITER;
options.jx_reuse = DEFAULT_JX_REUSE;
// Get conf file data
TRY(2, input_data(path, &dim, &x0, &options) == OK)
// Find root
TRY(3, (x = (double*) malloc(dim * sizeof(double))) != NULL)
TRY(4, findroot(dim, x0, x, &options, &additional_data) == OK)
output_result(dim, x, &additional_data);
RETURN(0)
EXCEPT(
case 1:
printf("Usage: findroot path\n");
break;
case 2:
fprintf(stderr,
"[x] Ezin izan da konfigurazio fitxategia ondo "
"irakurri.\n");
break;
case 3:
fprintf(stderr,
"[x] Ezin izan da memoria nahikoa erreserbatu.\n");
printf("[?] MEMORIA KOPURUA: %lu\n", dim * sizeof(double));
break;
case 4:
fprintf(stderr, "[x] Ezin izan da emaitza kalkulatu.\n");
break;
)
FINALLY(
free(x);
free(x0);
)
}
ERR_T findroot(int dim, double* x0, double* x, struct options* options,
struct additional_data* data) {
int s;
unsigned int iter_count, iter_div_count, jx_reuse_count;
double max_err, max_err_prev, zero_dist;
double* fx = NULL;
double* jx = NULL;
clock_t begin, end;
// INITIALIZATION
TRY(1, (fx = (double*) malloc(dim * sizeof(double))) != NULL)
TRY(2, (jx = (double*) malloc(dim * dim * sizeof(double))) != NULL)
gsl_set_error_handler(&handler);
gsl_vector_view x_gsl = gsl_vector_view_array(x, dim);
gsl_vector_view x0_gsl = gsl_vector_view_array(x0, dim);
gsl_vector_view fx_gsl = gsl_vector_view_array(fx, dim);
gsl_matrix_view jx_gsl = gsl_matrix_view_array(jx, dim, dim);
gsl_permutation* p = gsl_permutation_alloc(dim);
// NEWTON-RAPHSON LOOP
begin = clock();
/*
* a, b and c are vectors of dim dimensions
* FX and JX are square matrixes of dim dimensions
*
* b = a - c
* WHERE JX * c = FX
*
* a beign the result of the previous iteration (or the initial point)
* b beign the result of the current iteration (or the final result)
*/
// x0 == a
memcpy(x, x0, dim * sizeof(double));
// x == a
// x0 == a
iter_count = 0;
iter_div_count = 0;
max_err = DBL_MAX;
max_err_prev = DBL_MAX;
jx_reuse_count = options->jx_reuse;
do {
f(dim, x, fx);
// Reusage of the Jacobian matrix
if (jx_reuse_count == options->jx_reuse) {
jakobiarra(dim, x, jx);
TRY(3, gsl_linalg_LU_decomp(&jx_gsl.matrix, p, &s) == OK)
jx_reuse_count = 0;
} else {
++jx_reuse_count;
}
TRY(4,
gsl_linalg_LU_solve(
&jx_gsl.matrix, p, &fx_gsl.vector, &x0_gsl.vector) == OK
)
// x == a
// x0 == c
TRY(5, gsl_vector_sub(&x_gsl.vector, &x0_gsl.vector) == OK)
TRY(6, norm(dim, x0, &max_err, options) == OK)
// Relative error
if (options->rel_tol) {
// zero_dist is reused to save memory
TRY(7, norm(dim, x, &zero_dist, options) == OK)
max_err /= zero_dist;
}
// Zero dist
TRY(8, norm(dim, fx, &zero_dist, options) == OK)
// x == b
// x0 == c
// UPDATES
++iter_count;
// Track divergence iterations
if (max_err > max_err_prev) {
++iter_div_count;
} else {
iter_div_count = 0;
}
max_err_prev = max_err;
} while ((max_err > options->tolerance ||
zero_dist > options->max_zero_dist) &&
iter_count < options->max_iter &&
iter_div_count < options->max_div_iter);
end = clock();
if (iter_count == options->max_iter)
printf("[!] Iterazio mugara iritsi da.\n");
if (iter_div_count == options->max_div_iter)
printf("[!] Iterazio dibergente mugara iritsi da.\n");
data->max_error = max_err;
data->fx = fx;
data->iter_count = iter_count;
data->delta_t = (double) (end - begin) / (double) CLOCKS_PER_SEC;
EXCEPT(
case 1:
fprintf(stderr,
"[x] Ezin izan da memoria nahikoa erreserbatu.\n");
printf("[?] MEMORIA KOPURUA: %lu\n", dim * sizeof(double));
break;
case 2:
fprintf(stderr,
"[x] Ezin izan da memoria nahikoa erreserbatu.\n");
printf("[?] MEMORIA KOPURUA: %lun", dim * dim * sizeof(double));
break;
case 3:
fprintf(stderr,
"[x] Ezin izan da JX * x = FX ekuazio sistema "
"linealaren LU deskonposaketa egin.\n");
printf("[?] HURBILPEN PARTZIALA: ");
output_vector(dim, x);
printf("[?] ERRORE MAXIMOA: %.*g\n", DBL_DIG, max_err);
printf("[?] F(X): ");
output_vector(dim, fx);
printf("[?] ITERAZIO_KOPURUA: %u\n", iter_count);
break;
case 4:
fprintf(stderr,
"[x] Ezin izan da JX * x = FX ekuazio sistema lineala "
"ebatzi LU deskonposaketa erabiliz.\n");
printf("[?] HURBILPEN PARTZIALA: ");
output_vector(dim, x);
printf("[?] ERRORE MAXIMOA: %.*g\n", DBL_DIG, max_err);
printf("[?] F(X): ");
output_vector(dim, fx);
printf("[?] ITERAZIO_KOPURUA: %u\n", iter_count);
break;
case 5:
fprintf(stderr,
"[x] Bektoreen arteko kenketa egitean errore kritiko "
"bat egon da.");
printf("[?] F(X): ");
output_vector(dim, fx);
printf("[?] ITERAZIO_KOPURUA: %u\n", iter_count);
break;
case 6:
fprintf(stderr,
"[x] JX * x = FX ekuazio sistema linealaren emaitzaren "
"norma kalkulatzean errore kritiko bat egon da.\n");
printf("[?] F(X): ");
output_vector(dim, fx);
printf("[?] ITERAZIO_KOPURUA: %u\n", iter_count);
break;
case 7:
fprintf(stderr,
"[x] x-ren norma kalkulatzean errore kritiko bat egon "
"da.\n");
printf("[?] HURBILPEN PARTZIALA: ");
output_vector(dim, x);
printf("[?] F(X): ");
output_vector(dim, fx);
printf("[?] ITERAZIO_KOPURUA: %u\n", iter_count);
break;
case 8:
fprintf(stderr,
"[x] f(x)-ren norma kalkulatzean errore kritiko bat egon "
"da.\n");
printf("[?] HURBILPEN PARTZIALA: ");
output_vector(dim, x);
printf("[?] ERRORE MAXIMOA: %.*g\n", DBL_DIG, max_err);
output_vector(dim, fx);
printf("[?] ITERAZIO_KOPURUA: %u\n", iter_count);
break;
)
FINALLY(
free(fx);
free(jx);
gsl_permutation_free(p);
)
}
ERR_T norm(int dim, double* x, double* n, struct options* options) {
if (options->user_norm) {
norma(dim, x, n);
} else {
gsl_vector_view x_gsl = gsl_vector_view_array(x, dim);
TRY(1, (*n = gsl_blas_dnrm2(&x_gsl.vector)) >= 0.0)
}
EXCEPT(
case 1:
fprintf(stderr, "[x] Ezin izan da norma kalkulatu, posible da "
"bektorea handiegia izatea.\n");
break;
)
FINALLY()
}
ERR_T input_data(char* path, int* dim, double** x0, struct options* options) {
FILE* f;
char line[MAX_BUF];
int count = 0;
TRY(1, (f = fopen(path, "r")) != NULL)
// Read dimension
*dim = 0;
while (fgets(line, MAX_BUF, f) != NULL) {
if (line[0] != '#' && (line[0] != '\0')) {
if (MATCH(line, "dimentsioa")) {
TRY(2, sscanf(line, "dimentsioa %d", dim) == 1)
TRY(3, *dim > 0)
break;
}
}
}
TRY(4, *dim != 0)
TRY(5, (*x0 = (double*) malloc((*dim) * sizeof(double))) != NULL)
// Read x0 and optional parameters
while (fgets(line, MAX_BUF, f) != NULL) {
if (line[0] != '#' && (line[0] != '\0')) {
if (MATCH(line, "tolerantzia")) {
TRY(6,
sscanf(line, "tolerantzia %lf", &(options->tolerance)) == 1)
TRY(7, options->tolerance > 0.0)
} else if (MATCH(line, "erlatiboa")) {
if (MATCH(line, "erlatiboa bai")) {
options->rel_tol = 1;
} else if (MATCH(line, "erlatiboa ez")) {
options->rel_tol = 0;
} else {
TRY(8, 0);
}
} else if (MATCH(line, "max_zero_distantzia")) {
TRY(9,
sscanf(line, "max_zero_distantzia %lf",
&(options->max_zero_dist)) == 1)
TRY(10, options->max_zero_dist > 0.0)
} else if (MATCH(line, "ordezko_norma")) {
if (MATCH(line, "ordezko_norma bai")) {
options->user_norm = 1;
} else if (MATCH(line, "ordezko_norma ez")) {
options->user_norm = 0;
} else {
TRY(11, 0);
}
} else if (MATCH(line, "iterazio_maximoa")) {
TRY(12, sscanf(line, "iterazio_maximoa %u",
&(options->max_iter)) == 1)
TRY(13, options->max_iter != 0)
} else if (MATCH(line, "dibergentzia_iterazio_maximoa")) {
TRY(14, sscanf(line, "dibergentzia_iterazio_maximoa %u",
&(options->max_div_iter)) == 1)
} else if (MATCH(line, "jakobiar_berrerabilpena")) {
TRY(15, sscanf(line, "jakobiar_berrerabilpena %u",
&(options->jx_reuse)) == 1)
} else {
TRY(16, count <= *dim)
TRY(17, sscanf(line, "%lf", (*x0) + count) == 1)
++count;
}
}
}
TRY(18, count == *dim)
EXCEPT(
case 1:
fprintf(stdout,
"[x] Ezin izan da konfigurazio fitxategia ireki.\n");
break;
case 2:
fprintf(stdout,
"[x] Sintaxi desegokia dimentsioa emateko lerroan\n");
printf("[?] LERROA: %s", line);
break;
case 3:
fprintf(stdout,
"[x] Dimentsioak zero baina handiagoa izan behar du.\n");
printf("[?] LERROA: %s", line);
break;
case 4:
fprintf(stdout, "[x] Ez da aurkitu dimentsioa.\n");
break;
case 5:
fprintf(stdout,
"[x] Ezin izan da X0-rentzat memoria erreserbatu\n.");
printf("[?] MEMORIA KOPURUA: %lu", (*dim) * sizeof(double));
break;
case 6:
fprintf(stdout,
"[x] Sintaxi desegokia tolerantzia emateko lerroan\n.");
printf("[?] LERROA: %s", line);
break;
case 7:
fprintf(stdout,
"[x] Tolerantziak zero baina handiagoa izan behar du.\n");
printf("[?] LERROA: %s", line);
break;
case 8:
fprintf(stdout,
"[x] Sintaxi desegokia tolerantzia erlatiboa aukeratzeko "
"lerroan. Aukera honek 'bai' eta 'ez' balioak hartu "
"ditzake soilik.\n");
printf("[?] LERROA: %s", line);
break;
case 9:
fprintf(stdout,
"[x] Sintaxi okerra zerotik distantzia maximoa emateko "
"lerroan.\n");
printf("[?] LERROA: %s", line);
break;
case 10:
fprintf(stdout,
"[x] Zerotik distantzia maximoak zero baina handiagoa izan "
"behar du.\n");
printf("[?] LERROA: %s", line);
break;
case 11:
fprintf(stdout,
"[x] Sintaxi desegokia ordezko norma aukeratzeko "
"lerroan. Aukera honek 'bai' eta 'ez' balioak hartu "
"ditzake soilik.\n");
printf("[?] LERROA: %s", line);
break;
case 12:
fprintf(stdout,
"[x] Sintaxi okerra iterazio kopuru maximoa emateko "
"lerroan. Kopuruak ezin du negatiboa izan.\n");
printf("[?] LERROA: %s", line);
break;
case 13:
fprintf(stdout,
"[x] Iterazio kopuru maximoak ezin du zero izan.\n");
printf("[?] LERROA: %s", line);
break;
case 14:
fprintf(stdout,
"[x] Sintaxi okerra iterazio dibergente kopuru maximoa "
"emateko lerroan. Kopuruak ezin du negatiboa izan.\n");
printf("[?] LERROA: %s", line);
break;
case 15:
fprintf(stdout,
"[x] Sintaxi okerra jakobiarraren berrerabilpen ratioa "
"emateko lerroan. Ratioak ezin du negatiboa izan.\n");
printf("[?] LERROA: %s", line);
break;
case 16:
fprintf(stdout,
"[x] X0-ren elementu kopurura dimentsioa baina handiagoa "
"da.\n");
printf("[?] DIMENTSIOA: %i\n", *dim);
break;
case 17:
fprintf(stdout,
"[x] Sintaxi desegokia.\n");
printf("[?] LERROA: %s", line);
break;
case 18:
fprintf(stdout,
"[x] Dimentsioa eta X0-ren tamaina ez datoz bat.\n");
printf("[?] DIMENTSIOA: %i\n", *dim);
printf("[?] TAMAINA: %i\n", count);
break;
case 19:
fprintf(stdout,
"[x] Konfigurazio fitxategia ixtean errore kritiko bat "
"egon da.\n");
break;
)
FINALLY(
if (f != NULL) {
TRY(19, fclose(f) == OK);
// On fail, so that it doesn't try again and again
f = NULL;
}
)
}
void output_result(int dim, double* result, struct additional_data* data) {
printf("\n");
printf("Erroa: ");
output_vector(dim, result);
printf("Errore maximoa: %.*g\n", DBL_DIG, data->max_error);
printf("Erroaren irudia: ");
output_vector(dim, data->fx);
printf("Iterazio kopurua: %u\n", data->iter_count);
printf("Denbora: %.*g seg\n", DBL_DIG, data->delta_t);
printf("\n");
}
void output_vector(int dim, double* x) {
int i;
printf("(");
printf("%.*g", DBL_DIG, x[0]);
for (i = 1; i < dim; ++i)
printf(", %.*g", DBL_DIG, x[i]);
printf(")\n");
}
void handler(const char* reason, const char* file, int line, int gsl_errno) {
fprintf(stderr, "[x] ");
switch(gsl_errno) {
case GSL_EDOM:
fprintf(stderr, "GSL DOMAIN ERROR: ");
break;
case GSL_ERANGE:
fprintf(stderr, "GSL RANGE ERROR: ");
break;
case GSL_ENOMEM:
fprintf(stderr, "GSL NO MEMORY AVAILABLE: ");
break;
case GSL_EINVAL:
fprintf(stderr, "GSL INVALID ARGUMENT: ");
break;
default:
fprintf(stderr, "GSL ERROR: ");
break;
}
fprintf(stderr, "%s\n", reason);
}
| {
"alphanum_fraction": 0.6329551743,
"avg_line_length": 24.924137931,
"ext": "c",
"hexsha": "abc958e244fb142e1bca1976dcb3dfd82a6cc04b",
"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": "0262380d6558485559d9d05e24f58edf3c1c1188",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "oersted/find-root",
"max_forks_repo_path": "src/findroot.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0262380d6558485559d9d05e24f58edf3c1c1188",
"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": "oersted/find-root",
"max_issues_repo_path": "src/findroot.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0262380d6558485559d9d05e24f58edf3c1c1188",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "oersted/find-root",
"max_stars_repo_path": "src/findroot.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4867,
"size": 14456
} |
/// @file
///
/// @brief test of gsl pointer wrappers
///
/// @copyright (c) 2007 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution 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
///
/// @author Max Voronkov <maxim.voronkov@csiro.au>
// unit test include
#include <cppunit/extensions/HelperMacros.h>
// own includes
#include "utils/SharedGSLTypes.h"
// gsl includes
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
namespace askap {
namespace utility {
/// @brief helper specialisation to allow testing of the destructor call
/// @details It is not used anywhere outside this test suit
template<> struct CustomGSLDeleter<bool> {
/// @brief this method just sets the passed object to true
/// @param[in] obj pointer to a boolean variable
void operator()(bool *obj) const { *obj = true; }
};
class SharedGSLTypesTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(SharedGSLTypesTest);
CPPUNIT_TEST(testVector);
CPPUNIT_TEST(testMatrix);
CPPUNIT_TEST_EXCEPTION(testNullPointer,AskapError);
CPPUNIT_TEST(testDestruction);
CPPUNIT_TEST_SUITE_END();
public:
void testVector() {
const size_t nElements = 10;
SharedGSLVector vec = createGSLVector(nElements);
for (size_t el = 0; el < nElements; ++el) {
gsl_vector_set(vec.get(), el, double(el));
}
// check the content (can't really check that the destructor is
// called)
for (size_t el = 0; el < nElements; ++el) {
CPPUNIT_ASSERT_DOUBLES_EQUAL(double(el), gsl_vector_get(vec.get(), el), 1e-6);
}
// destructor should be called on leaving this method
}
void testMatrix() {
const size_t nRow = 10;
const size_t nCol = 12;
SharedGSLMatrix matr = createGSLMatrix(nRow, nCol);
for (size_t row = 0; row < nRow; ++row) {
for (size_t col = 0; col < nCol; ++col) {
gsl_matrix_set(matr.get(), row, col, double(row*col));
}
}
// check the content (can't really check that the destructor is
// called)
for (size_t row = 0; row < nRow; ++row) {
for (size_t col = 0; col < nCol; ++col) {
CPPUNIT_ASSERT_DOUBLES_EQUAL(double(row*col), gsl_matrix_get(matr.get(), row,col), 1e-6);
}
}
// destructor should be called on leaving this method
}
void testNullPointer() {
gsl_vector *nullVec = NULL;
// the following should throw an exception
createGSLObject(nullVec);
}
void testDestruction() {
bool destructorCalledBuf = false;
{
const boost::shared_ptr<bool> destructorCalledPtr = createGSLObject(&destructorCalledBuf);
CPPUNIT_ASSERT(destructorCalledPtr);
CPPUNIT_ASSERT_EQUAL(false, *destructorCalledPtr);
CPPUNIT_ASSERT_EQUAL(false, destructorCalledBuf);
}
CPPUNIT_ASSERT_EQUAL(true, destructorCalledBuf);
}
};
} // namespace utility
} // namespace askap
| {
"alphanum_fraction": 0.666837388,
"avg_line_length": 33.093220339,
"ext": "h",
"hexsha": "b5fc6ce95e9dfc8aa10eb7b570c8e1bdbab45412",
"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": "d839c052d5c62ad8a511e58cd4b6548491a6006f",
"max_forks_repo_licenses": [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
],
"max_forks_repo_name": "ATNF/askapsoft",
"max_forks_repo_path": "Code/Base/scimath/current/tests/utils/SharedGSLTypesTest.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
],
"max_issues_repo_name": "ATNF/askapsoft",
"max_issues_repo_path": "Code/Base/scimath/current/tests/utils/SharedGSLTypesTest.h",
"max_line_length": 105,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e",
"max_stars_repo_licenses": [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
],
"max_stars_repo_name": "rtobar/askapsoft",
"max_stars_repo_path": "Code/Base/scimath/current/tests/utils/SharedGSLTypesTest.h",
"max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z",
"num_tokens": 960,
"size": 3905
} |
/* rng/lecuyer21.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This generator is taken from
*
* Donald E. Knuth
* The Art of Computer Programming
* Volume 2
* Third Edition
* Addison-Wesley
* Page 108
*
* This implementation copyright (C) 2001 Brian Gough, Carlo Perassi
* and (C) 2003 Heiko Bauke.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#define AAA 40692
#define MMM 2147483399UL
#define QQQ 52774
#define RRR 3791
static inline unsigned long int ran_get (void *vstate);
static double ran_get_double (void *vstate);
static void ran_set (void *state, unsigned long int s);
typedef struct
{
unsigned long int x;
}
ran_state_t;
static inline unsigned long int
ran_get (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
long int y = state->x;
long int r = RRR * (y / QQQ);
y = AAA * (y % QQQ) - r;
if (y < 0)
y += MMM;
state->x = y;
return state->x;
}
static double
ran_get_double (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
return ran_get (state) / 2147483399.0;
}
static void
ran_set (void *vstate, unsigned long int s)
{
ran_state_t *state = (ran_state_t *) vstate;
if ((s%MMM) == 0)
s = 1; /* default seed is 1 */
state->x = s % MMM;
return;
}
static const gsl_rng_type ran_type = {
"lecuyer21", /* name */
MMM-1, /* RAND_MAX */
1, /* RAND_MIN */
sizeof (ran_state_t),
&ran_set,
&ran_get,
&ran_get_double
};
const gsl_rng_type *gsl_rng_lecuyer21 = &ran_type;
| {
"alphanum_fraction": 0.6624175824,
"avg_line_length": 22.75,
"ext": "c",
"hexsha": "ee581283ed5d14170c746642074513c76c349dd0",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/rng/lecuyer21.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/rng/lecuyer21.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/rng/lecuyer21.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": 643,
"size": 2275
} |
#ifndef libceed_solids_examples_utils_h
#define libceed_solids_examples_utils_h
#include <ceed.h>
#include <petsc.h>
// Translate PetscMemType to CeedMemType
static inline CeedMemType MemTypeP2C(PetscMemType mem_type) {
return PetscMemTypeDevice(mem_type) ? CEED_MEM_DEVICE : CEED_MEM_HOST;
}
#endif // libceed_solids_examples_utils_h
| {
"alphanum_fraction": 0.8294117647,
"avg_line_length": 26.1538461538,
"ext": "h",
"hexsha": "685339916afbd3192b9706f87a390c508063390f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wence-/libCEED",
"max_forks_repo_path": "examples/solids/include/utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "wence-/libCEED",
"max_issues_repo_path": "examples/solids/include/utils.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wence-/libCEED",
"max_stars_repo_path": "examples/solids/include/utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 91,
"size": 340
} |
/* Copyright (C) 2021 Atsushi Togo */
/* All rights reserved. */
/* This file is part of phonopy. */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions */
/* are met: */
/* * Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* * Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the */
/* distribution. */
/* * Neither the name of the phonopy project nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */
/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */
/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */
/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */
/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */
/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
#ifndef __phono3py_H__
#define __phono3py_H__
#ifdef MKL_LAPACKE
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include "phonoc_array.h"
long ph3py_get_interaction(Darray *fc3_normal_squared,
const char *g_zero,
const Darray *frequencies,
const lapack_complex_double *eigenvectors,
const long (*triplets)[3],
const long num_triplets,
const long (*bz_grid_addresses)[3],
const long D_diag[3],
const long Q[3][3],
const double *fc3,
const long is_compact_fc3,
const double (*svecs)[3],
const long multi_dims[2],
const long (*multi)[2],
const double *masses,
const long *p2s_map,
const long *s2p_map,
const long *band_indices,
const long symmetrize_fc3_q,
const double cutoff_frequency);
long ph3py_get_pp_collision(double *imag_self_energy,
const long relative_grid_address[24][4][3], /* thm */
const double *frequencies,
const lapack_complex_double *eigenvectors,
const long (*triplets)[3],
const long num_triplets,
const long *triplet_weights,
const long (*bz_grid_addresses)[3], /* thm */
const long *bz_map, /* thm */
const long bz_grid_type,
const long D_diag[3],
const long Q[3][3],
const double *fc3,
const long is_compact_fc3,
const double (*svecs)[3],
const long multi_dims[2],
const long (*multi)[2],
const double *masses,
const long *p2s_map,
const long *s2p_map,
const Larray *band_indices,
const Darray *temperatures,
const long is_NU,
const long symmetrize_fc3_q,
const double cutoff_frequency);
long ph3py_get_pp_collision_with_sigma(
double *imag_self_energy,
const double sigma,
const double sigma_cutoff,
const double *frequencies,
const lapack_complex_double *eigenvectors,
const long (*triplets)[3],
const long num_triplets,
const long *triplet_weights,
const long (*bz_grid_addresses)[3],
const long D_diag[3],
const long Q[3][3],
const double *fc3,
const long is_compact_fc3,
const double (*svecs)[3],
const long multi_dims[2],
const long (*multi)[2],
const double *masses,
const long *p2s_map,
const long *s2p_map,
const Larray *band_indices,
const Darray *temperatures,
const long is_NU,
const long symmetrize_fc3_q,
const double cutoff_frequency);
void ph3py_get_imag_self_energy_at_bands_with_g(
double *imag_self_energy,
const Darray *fc3_normal_squared,
const double *frequencies,
const long (*triplets)[3],
const long *triplet_weights,
const double *g,
const char *g_zero,
const double temperature,
const double cutoff_frequency,
const long num_frequency_points,
const long frequency_point_index);
void ph3py_get_detailed_imag_self_energy_at_bands_with_g(
double *detailed_imag_self_energy,
double *imag_self_energy_N,
double *imag_self_energy_U,
const Darray *fc3_normal_squared,
const double *frequencies,
const long (*triplets)[3],
const long *triplet_weights,
const long (*bz_grid_addresses)[3],
const double *g,
const char *g_zero,
const double temperature,
const double cutoff_frequency);
void ph3py_get_real_self_energy_at_bands(double *real_self_energy,
const Darray *fc3_normal_squared,
const long *band_indices,
const double *frequencies,
const long (*triplets)[3],
const long *triplet_weights,
const double epsilon,
const double temperature,
const double unit_conversion_factor,
const double cutoff_frequency);
void ph3py_get_real_self_energy_at_frequency_point(
double *real_self_energy,
const double frequency_point,
const Darray *fc3_normal_squared,
const long *band_indices,
const double *frequencies,
const long (*triplets)[3],
const long *triplet_weights,
const double epsilon,
const double temperature,
const double unit_conversion_factor,
const double cutoff_frequency);
void ph3py_get_collision_matrix(double *collision_matrix,
const Darray *fc3_normal_squared,
const double *frequencies,
const long (*triplets)[3],
const long *triplets_map,
const long *map_q,
const long *rotated_grid_points,
const double *rotations_cartesian,
const double *g,
const long num_ir_gp,
const long num_gp,
const long num_rot,
const double temperature,
const double unit_conversion_factor,
const double cutoff_frequency);
void ph3py_get_reducible_collision_matrix(double *collision_matrix,
const Darray *fc3_normal_squared,
const double *frequencies,
const long (*triplets)[3],
const long *triplets_map,
const long *map_q,
const double *g,
const long num_gp,
const double temperature,
const double unit_conversion_factor,
const double cutoff_frequency);
void ph3py_get_isotope_scattering_strength(
double *gamma,
const long grid_point,
const double *mass_variances,
const double *frequencies,
const lapack_complex_double *eigenvectors,
const long num_grid_points,
const long *band_indices,
const long num_band,
const long num_band0,
const double sigma,
const double cutoff_frequency);
void ph3py_get_thm_isotope_scattering_strength(
double *gamma,
const long grid_point,
const long *ir_grid_points,
const long *weights,
const double *mass_variances,
const double *frequencies,
const lapack_complex_double *eigenvectors,
const long num_ir_grid_points,
const long *band_indices,
const long num_band,
const long num_band0,
const double *integration_weights,
const double cutoff_frequency);
void ph3py_distribute_fc3(double *fc3,
const long target,
const long source,
const long *atom_mapping,
const long num_atom,
const double *rot_cart);
void ph3py_rotate_delta_fc2(double (*fc3)[3][3][3],
const double (*delta_fc2s)[3][3],
const double *inv_U,
const double (*site_sym_cart)[3][3],
const long *rot_map_syms,
const long num_atom,
const long num_site_sym,
const long num_disp);
void ph3py_get_permutation_symmetry_fc3(double *fc3, const long num_atom);
void ph3py_get_permutation_symmetry_compact_fc3(double *fc3,
const long p2s[],
const long s2pp[],
const long nsym_list[],
const long perms[],
const long n_satom,
const long n_patom);
void ph3py_transpose_compact_fc3(double *fc3,
const long p2s[],
const long s2pp[],
const long nsym_list[],
const long perms[],
const long n_satom,
const long n_patom,
const long t_type);
long ph3py_get_triplets_reciprocal_mesh_at_q(long *map_triplets,
long *map_q,
const long grid_point,
const long mesh[3],
const long is_time_reversal,
const long num_rot,
const long (*rec_rotations)[3][3],
const long swappable);
long ph3py_get_BZ_triplets_at_q(long (*triplets)[3],
const long grid_point,
const long (*bz_grid_addresses)[3],
const long *bz_map,
const long *map_triplets,
const long num_map_triplets,
const long D_diag[3],
const long Q[3][3],
const long bz_grid_type);
long ph3py_get_integration_weight(double *iw,
char *iw_zero,
const double *frequency_points,
const long num_band0,
const long relative_grid_address[24][4][3],
const long mesh[3],
const long (*triplets)[3],
const long num_triplets,
const long (*bz_grid_addresses)[3],
const long *bz_map,
const long bz_grid_type,
const double *frequencies1,
const long num_band1,
const double *frequencies2,
const long num_band2,
const long tp_type,
const long openmp_per_triplets,
const long openmp_per_bands);
void ph3py_get_integration_weight_with_sigma(double *iw,
char *iw_zero,
const double sigma,
const double sigma_cutoff,
const double *frequency_points,
const long num_band0,
const long (*triplets)[3],
const long num_triplets,
const double *frequencies,
const long num_band,
const long tp_type);
long ph3py_get_grid_index_from_address(const long address[3],
const long mesh[3]);
void ph3py_get_gr_grid_addresses(long gr_grid_addresses[][3],
const long D_diag[3]);
long ph3py_get_reciprocal_rotations(long rec_rotations[48][3][3],
const long (*rotations)[3][3],
const long num_rot,
const long is_time_reversal);
long ph3py_transform_rotations(long (*transformed_rots)[3][3],
const long (*rotations)[3][3],
const long num_rot,
const long D_diag[3],
const long Q[3][3]);
long ph3py_get_snf3x3(long D_diag[3],
long P[3][3],
long Q[3][3],
const long A[3][3]);
long ph3py_transform_rotations(long (*transformed_rots)[3][3],
const long (*rotations)[3][3],
const long num_rot,
const long D_diag[3],
const long Q[3][3]);
long ph3py_get_ir_grid_map(long *ir_grid_map,
const long D_diag[3],
const long PS[3],
const long (*grg_rotations)[3][3],
const long num_rot);
long ph3py_get_bz_grid_addresses(long (*bz_grid_addresses)[3],
long *bz_map,
long *bzg2grg,
const long D_diag[3],
const long Q[3][3],
const long PS[3],
const double rec_lattice[3][3],
const long type);
long ph3py_rotate_bz_grid_index(const long bz_grid_index,
const long rotation[3][3],
const long (*bz_grid_addresses)[3],
const long *bz_map,
const long D_diag[3],
const long PS[3],
const long bz_grid_type);
void ph3py_symmetrize_collision_matrix(double *collision_matrix,
const long num_column,
const long num_temp,
const long num_sigma);
void ph3py_expand_collision_matrix(double *collision_matrix,
const long *rot_grid_points,
const long *ir_grid_points,
const long num_ir_gp,
const long num_grid_points,
const long num_rot,
const long num_sigma,
const long num_temp,
const long num_band);
long ph3py_get_neighboring_gird_points(long *relative_grid_points,
const long *grid_points,
const long (*relative_grid_address)[3],
const long mesh[3],
const long (*bz_grid_addresses)[3],
const long *bz_map,
const long bz_grid_type,
const long num_grid_points,
const long num_relative_grid_address);
long ph3py_get_thm_integration_weights_at_grid_points(
double *iw,
const double *frequency_points,
const long num_band0,
const long num_band,
const long num_gp,
const long (*relative_grid_address)[4][3],
const long D_diag[3],
const long *grid_points,
const long (*bz_grid_addresses)[3],
const long *bz_map,
const long bz_grid_type,
const double *frequencies,
const long *gp2irgp_map,
const char function);
#endif
| {
"alphanum_fraction": 0.4869593925,
"avg_line_length": 48.9865229111,
"ext": "h",
"hexsha": "fc0e6e2f89c0983eee5b7674d3493cf06b2e51d5",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-02-17T10:24:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-06T21:20:18.000Z",
"max_forks_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "phonopy/phono3py",
"max_forks_repo_path": "c/phono3py.h",
"max_issues_count": 56,
"max_issues_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56",
"max_issues_repo_issues_event_max_datetime": "2022-03-28T20:35:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-02T22:11:02.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "phonopy/phono3py",
"max_issues_repo_path": "c/phono3py.h",
"max_line_length": 81,
"max_stars_count": 31,
"max_stars_repo_head_hexsha": "c3246c0384f3596cb2ff109193b9106ddb466b56",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "phonopy/phono3py",
"max_stars_repo_path": "c/phono3py.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-16T10:37:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-28T09:52:37.000Z",
"num_tokens": 3113,
"size": 18174
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2018 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "engine_error.h"
#include "protocol_binary.h"
#include "rbac.h"
#include "types.h"
#include <mcbp/protocol/opcode.h>
#include <nlohmann/json_fwd.hpp>
#include <gsl/gsl>
#include <string>
/**
* Commands to operate on a specific cookie.
*/
struct ServerCookieIface {
virtual ~ServerCookieIface() = default;
/**
* Store engine-specific session data on the given cookie.
*
* The engine interface allows for a single item to be
* attached to the connection that it can use to track
* connection-specific data throughout duration of the
* connection.
*
* @param cookie The cookie provided by the frontend
* @param engine_data pointer to opaque data
*/
virtual void store_engine_specific(gsl::not_null<const void*> cookie,
void* engine_data) = 0;
/**
* Retrieve engine-specific session data for the given cookie.
*
* @param cookie The cookie provided by the frontend
*
* @return the data provied by store_engine_specific or NULL
* if none was provided
*/
virtual void* get_engine_specific(gsl::not_null<const void*> cookie) = 0;
/**
* Check if datatype is supported by the connection.
*
* @param cookie The cookie provided by the frontend
* @param datatype The datatype to test
*
* @return true if connection supports the datatype or else false.
*/
virtual bool is_datatype_supported(gsl::not_null<const void*> cookie,
protocol_binary_datatype_t datatype) = 0;
/**
* Check if mutation extras is supported by the connection.
*
* @param cookie The cookie provided by the frontend
*
* @return true if supported or else false.
*/
virtual bool is_mutation_extras_supported(
gsl::not_null<const void*> cookie) = 0;
/**
* Check if collections are supported by the connection.
*
* @param cookie The cookie provided by the frontend
*
* @return true if supported or else false.
*/
virtual bool is_collections_supported(
gsl::not_null<const void*> cookie) = 0;
/**
* Retrieve the opcode of the connection, if
* ewouldblock flag is set. Please note that the ewouldblock
* flag for a connection is cleared before calling into
* the engine interface, so this method only works in the
* notify hooks.
*
* @param cookie The cookie provided by the frontend
*
* @return the opcode from the binary_header saved in the
* connection.
*/
virtual cb::mcbp::ClientOpcode get_opcode_if_ewouldblock_set(
gsl::not_null<const void*> cookie) = 0;
/**
* Validate given ns_server's session cas token against
* saved token in memached, and if so incrment the session
* counter.
*
* @param cas The cas token from the request
*
* @return true if session cas matches the one saved in
* memcached
*/
virtual bool validate_session_cas(uint64_t cas) = 0;
/**
* Decrement session_cas's counter everytime a control
* command completes execution.
*/
virtual void decrement_session_ctr() = 0;
/**
* Let a connection know that IO has completed.
* @param cookie cookie representing the connection
* @param status the status for the io operation
*/
virtual void notify_io_complete(gsl::not_null<const void*> cookie,
ENGINE_ERROR_CODE status) = 0;
/**
* Notify the core that we're holding on to this cookie for
* future use. (The core guarantees it will not invalidate the
* memory until the cookie is invalidated by calling release())
*/
virtual ENGINE_ERROR_CODE reserve(gsl::not_null<const void*> cookie) = 0;
/**
* Notify the core that we're releasing the reference to the
* The engine is not allowed to use the cookie (the core may invalidate
* the memory)
*/
virtual ENGINE_ERROR_CODE release(gsl::not_null<const void*> cookie) = 0;
/**
* Set the priority for this connection
*/
virtual void set_priority(gsl::not_null<const void*> cookie,
CONN_PRIORITY priority) = 0;
/**
* Get the priority for this connection
*/
virtual CONN_PRIORITY get_priority(gsl::not_null<const void*> cookie) = 0;
/**
* Get the bucket the connection is bound to
*
* @cookie The connection object
* @return the bucket identifier for a cookie
*/
virtual bucket_id_t get_bucket_id(gsl::not_null<const void*> cookie) = 0;
/**
* Get connection id
*
* @param cookie the cookie sent to the engine for an operation
* @return a unique identifier for a connection
*/
virtual uint64_t get_connection_id(gsl::not_null<const void*> cookie) = 0;
/**
* Check if the cookie have the specified privilege in it's
* active set.
*
* @todo We should probably add the key we want to access as part
* of the API. We're going to need that when we're adding
* support for collections. For now let's assume that it
* won't be a big problem to fix that later on.
* @param cookie the cookie sent to the engine for an operation
* @param privilege the privilege to check for
* @return true if the cookie have the privilege in its active set,
* false otherwise
*/
virtual cb::rbac::PrivilegeAccess check_privilege(
gsl::not_null<const void*> cookie,
cb::rbac::Privilege privilege) = 0;
/**
* Method to map an engine error code to the appropriate mcbp response
* code (the client may not support all error codes so we may have
* to remap some).
*
* @param cookie the client cookie (to look up the client connection)
* @param code the engine error code to get the mcbp response code.
* @return the mcbp response status to use
* @throws std::engine_error if the error code results in being
* ENGINE_DISCONNECT after remapping
* std::logic_error if the error code doesn't make sense
* std::invalid_argument if the code doesn't exist
*/
virtual cb::mcbp::Status engine_error2mcbp(
gsl::not_null<const void*> cookie, ENGINE_ERROR_CODE code) = 0;
/**
* Get the log information to be used for a log entry.
*
* The typical log entry from the core is:
*
* `id> message` - Data read from ta client
* `id: message` - Status messages for this client
* `id< message` - Data sent back to the client
*
* If the caller wants to dump more information about the connection
* (like socket name, peer name, user name) the pair returns this
* info as the second field. The info may be invalidated by the core
* at any time (but not while the engine is operating in a single call
* from the core) so it should _not_ be cached.
*/
virtual std::pair<uint32_t, std::string> get_log_info(
gsl::not_null<const void*> cookie) = 0;
virtual std::string get_authenticated_user(
gsl::not_null<const void*> cookie) = 0;
virtual in_port_t get_connected_port(gsl::not_null<const void*> cookie) = 0;
/**
* Set the error context string to be sent in response. This should not
* contain security sensitive information. If sensitive information needs to
* be preserved, log it with a UUID and send the UUID.
*
* Note this has no affect for the following response codes.
* cb::mcbp::Status::Success
* cb::mcbp::Status::SubdocSuccessDeleted
* cb::mcbp::Status::SubdocMultiPathFailure
* cb::mcbp::Status::Rollback
* cb::mcbp::Status::NotMyVbucket
*
* @param cookie the client cookie (to look up client connection)
* @param message the message string to be set as the error context
*/
virtual void set_error_context(gsl::not_null<void*> cookie,
cb::const_char_buffer message) = 0;
/**
* Set a JSON object to be included in an error response (along side
* anything set by set_error_context).
*
* The json object cannot include "error" as a top-level key
*
* Note this has no affect for the following response codes.
* cb::mcbp::Status::Success
* cb::mcbp::Status::SubdocSuccessDeleted
* cb::mcbp::Status::SubdocMultiPathFailure
* cb::mcbp::Status::Rollback
* cb::mcbp::Status::NotMyVbucket
*
* @param cookie the client cookie (to look up client connection)
* @param json extra json object to include in a error response.
*/
virtual void set_error_json_extras(gsl::not_null<void*> cookie,
const nlohmann::json& json) = 0;
};
| {
"alphanum_fraction": 0.642199938,
"avg_line_length": 36.3646616541,
"ext": "h",
"hexsha": "c10951d9ed684f594a8fd3584729747c5fe01a21",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z",
"max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "paolococchi/kv_engine",
"max_forks_repo_path": "include/memcached/server_cookie_iface.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45",
"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": "paolococchi/kv_engine",
"max_issues_repo_path": "include/memcached/server_cookie_iface.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6fc9dc957844f077d44dc6992794ffe35e91e1f7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "scwright027/kv_engine",
"max_stars_repo_path": "include/memcached/server_cookie_iface.h",
"max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z",
"num_tokens": 2283,
"size": 9673
} |
/* multimin/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi
*
* 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 <gsl/gsl_test.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_ieee_utils.h>
#include "test_funcs.h"
int
test_fdf(const char * desc, gsl_multimin_function_fdf *f, initpt_function initpt, const gsl_multimin_fdfminimizer_type *T);
int
main (void)
{
const gsl_multimin_fdfminimizer_type *fdfminimizers[5];
const gsl_multimin_fdfminimizer_type ** T;
gsl_ieee_env_setup ();
fdfminimizers[0] = gsl_multimin_fdfminimizer_steepest_descent;
fdfminimizers[1] = gsl_multimin_fdfminimizer_conjugate_pr;
fdfminimizers[2] = gsl_multimin_fdfminimizer_conjugate_fr;
fdfminimizers[3] = gsl_multimin_fdfminimizer_vector_bfgs;
fdfminimizers[4] = 0;
T = fdfminimizers;
while (*T != 0)
{
test_fdf("Roth", &roth, roth_initpt,*T);
test_fdf("Wood", &wood, wood_initpt,*T);
test_fdf("Rosenbrock", &rosenbrock, rosenbrock_initpt,*T);
T++;
}
T = fdfminimizers;
while (*T != 0)
{
test_fdf("NRoth", &Nroth, roth_initpt,*T);
test_fdf("NWood", &Nwood, wood_initpt,*T);
test_fdf("NRosenbrock", &Nrosenbrock, rosenbrock_initpt,*T);
T++;
}
exit (gsl_test_summary());
}
int
test_fdf(const char * desc,
gsl_multimin_function_fdf *f,
initpt_function initpt,
const gsl_multimin_fdfminimizer_type *T)
{
int status;
size_t iter = 0;
double step_size;
gsl_vector *x = gsl_vector_alloc (f->n);
gsl_multimin_fdfminimizer *s;
(*initpt) (x);
step_size = 0.1 * gsl_blas_dnrm2 (x);
s = gsl_multimin_fdfminimizer_alloc(T, f->n);
gsl_multimin_fdfminimizer_set (s, f, x, step_size, 0.1);
#ifdef DEBUG
printf("x "); gsl_vector_fprintf (stdout, s->x, "%g");
printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g");
#endif
do
{
iter++;
status = gsl_multimin_fdfminimizer_iterate(s);
#ifdef DEBUG
printf("%i: \n",iter);
printf("x "); gsl_vector_fprintf (stdout, s->x, "%g");
printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g");
printf("f(x) %g\n",s->f);
printf("dx %g\n",gsl_blas_dnrm2(s->dx));
printf("\n");
#endif
status = gsl_multimin_test_gradient(s->gradient,1e-3);
}
while (iter < 5000 && status == GSL_CONTINUE);
status |= (fabs(s->f) > 1e-5);
gsl_test(status, "%s, on %s: %i iterations, f(x)=%g",
gsl_multimin_fdfminimizer_name(s),desc, iter, s->f);
gsl_multimin_fdfminimizer_free(s);
gsl_vector_free(x);
return status;
}
| {
"alphanum_fraction": 0.6814186117,
"avg_line_length": 26.392,
"ext": "c",
"hexsha": "2ffe4b969a69bb97408b3792945e2a61a9bfac4b",
"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/multimin/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/multimin/test.c",
"max_line_length": 123,
"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/multimin/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": 1044,
"size": 3299
} |
#pragma once
#include <gsl/gsl>
#include "halley/utils/utils.h"
#include <vector>
namespace Halley {
class String;
class Path;
class FileSystem
{
public:
static bool exists(const Path& p);
static bool createDir(const Path& p);
static bool createParentDir(const Path& p);
static int64_t getLastWriteTime(const Path& p);
static bool isFile(const Path& p);
static bool isDirectory(const Path& p);
static void copyFile(const Path& src, const Path& dst);
static bool remove(const Path& path);
static void writeFile(const Path& path, gsl::span<const gsl::byte> data);
static void writeFile(const Path& path, const Bytes& data);
static Bytes readFile(const Path& path);
static std::vector<Path> enumerateDirectory(const Path& path);
static Path getRelative(const Path& path, const Path& parentPath);
static Path getAbsolute(const Path& path);
static size_t fileSize(const Path& path);
static Path getTemporaryPath();
static int runCommand(const String& command);
};
}
| {
"alphanum_fraction": 0.7280788177,
"avg_line_length": 24.1666666667,
"ext": "h",
"hexsha": "8fda1ad4abf1a0a63637573ca4966a21557668c0",
"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": "aa58e1abe22cda9e80637922721c03574779cd81",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Healthire/halley",
"max_forks_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81",
"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": "Healthire/halley",
"max_issues_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Healthire/halley",
"max_stars_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 239,
"size": 1015
} |
/*
sstmap C extension module.
##############################################################################
# SSTMap: A Python library for the calculation of water structure and
# thermodynamics on solute surfaces from molecular dynamics
# trajectories.
# MIT License
# Copyright 2016-2017 Lehman College City University of New York and the Authors
#
# Authors: Kamran Haider, Steven Ramsay, Anthony Cruz Balberdy
#
# 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.
###############################################################################
*/
#define _USE_MATH_DEFINES
#include <math.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/arrayobject.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
void invert_matrix(float *matrix){
// Using GSL for matrix inversion
// See also https://lists.gnu.org/archive/html/help-gsl/2008-11/msg00001.html
double temp_matrix[9] = { (double) *(matrix + 0), (double) *(matrix + 1), (double) *(matrix + 2),
(double) *(matrix + 3), (double) *(matrix + 4), (double) *(matrix + 5),
(double) *(matrix + 6), (double) *(matrix + 7), (double) *(matrix + 8) };
double inva[9];
gsl_matrix_view m = gsl_matrix_view_array(temp_matrix,3,3);
gsl_matrix_view inv = gsl_matrix_view_array(inva,3,3);
gsl_permutation *p = gsl_permutation_alloc (3);
int s;
gsl_linalg_LU_decomp (&m.matrix, p, &s);
gsl_linalg_LU_invert (&m.matrix, p, &inv.matrix);
*(matrix + 0) = (float) gsl_matrix_get(&inv.matrix, 0, 0);
*(matrix + 1) = (float) gsl_matrix_get(&inv.matrix, 0, 1);
*(matrix + 2) = (float) gsl_matrix_get(&inv.matrix, 0, 2);
*(matrix + 3) = (float) gsl_matrix_get(&inv.matrix, 1, 0);
*(matrix + 4) = (float) gsl_matrix_get(&inv.matrix, 1, 1);
*(matrix + 5) = (float) gsl_matrix_get(&inv.matrix, 1, 2);
*(matrix + 6) = (float) gsl_matrix_get(&inv.matrix, 2, 0);
*(matrix + 7) = (float) gsl_matrix_get(&inv.matrix, 2, 1);
*(matrix + 8) = (float) gsl_matrix_get(&inv.matrix, 2, 2);
//printf("DEBUG: %10.8f %10.8f %10.8f\n", *(matrix + 0), *(matrix +1), *(matrix + 2));
//printf("DEBUG: %10.8f %10.8f %10.8f\n", *(matrix + 3), *(matrix +4), *(matrix + 5));
//printf("DEBUG: %10.8f %10.8f %10.8f\n", *(matrix + 6), *(matrix +7), *(matrix + 8));
gsl_permutation_free (p);
}
void matrix_vector_product(float *matrix, float *vector, float *product){
*(product + 0) = *(matrix + 0) * *(vector + 0) + *(matrix + 1) * *(vector + 1) + *(matrix + 2) * *(vector + 2);
*(product + 1) = *(matrix + 3) * *(vector + 0) + *(matrix + 4) * *(vector + 1) + *(matrix + 5) * *(vector + 2);
*(product + 2) = *(matrix + 6) * *(vector + 0) + *(matrix + 7) * *(vector + 1) + *(matrix + 8) * *(vector + 2);
}
float dist_mic_tric_squared(float *x1, float *x2, float *x3, float *y1, float *y2, float *y3, float *uc_vec, float *inv_uc_vec) {
/* distance calculation for mic in non-orthorombic unit cells using brute force
*/
float x[3]; x[0]=*x1; x[1]=*x2; x[2]=*x3; // << real space position vector
float y[3]; y[0]=*y1; y[1]=*y2; y[2]=*y3; // << real space position vector
//printf("DEBUG: X %6.3f %6.3f %6.3f\n", x[0], x[1], x[2] );
//printf("DEBUG: Y %6.3f %6.3f %6.3f\n", y[0], y[1], y[2] );
float x_f[3] = {0,0,0}; matrix_vector_product(inv_uc_vec, &x[0], &x_f[0]);// frac space position vector
float y_f[3] = {0,0,0}; matrix_vector_product(inv_uc_vec, &y[0], &y_f[0]);// frac space position vector
//printf("DEBUG: x_f(?|?|?) %6.3f %6.3f %6.3f\n", x_f[0], x_f[1], x_f[2] );
//printf("DEBUG: y_f(?|?|?) %6.3f %6.3f %6.3f\n", y_f[0], y_f[1], y_f[2] );
//translate back to (0|0|0) cell
x_f[0] = x_f[0] - floor(x_f[0]);
x_f[1] = x_f[1] - floor(x_f[1]);
x_f[2] = x_f[2] - floor(x_f[2]);
y_f[0] = y_f[0] - floor(y_f[0]);
y_f[1] = y_f[1] - floor(y_f[1]);
y_f[2] = y_f[2] - floor(y_f[2]);
//printf("DEBUG: x_f(0|0|0) %6.3f %6.3f %6.3f\n", x_f[0], x_f[1], x_f[2] );
//printf("DEBUG: y_f(0|0|0) %6.3f %6.3f %6.3f\n", y_f[0], y_f[1], y_f[2] );
// n_dist2 stores the closest squared distance, t_dist2 stores the most recent
// squared distance
float x_r[3] = {0,0,0}; matrix_vector_product(uc_vec, &x_f[0], &x_r[0]);
float y_r[3] = {0,0,0}; matrix_vector_product(uc_vec, &y_f[0], &y_r[0]);
float n_dist2, t_dist2;
n_dist2 = pow(x_r[0]-y_r[0], 2) + pow(x_r[1]-y_r[1], 2) + pow(x_r[2]-y_r[2], 2);
//printf ("DEBUG: nearest %10.7f\n", nearest);
int i,j,k;
float nc[3] = {-1,0,1};
float t_y_f[3];
for (i=0; i<3; i++) {
t_y_f[0] = y_f[0] + nc[i];
for (j=0; j<3; j++) {
t_y_f[1] = y_f[1] + nc[j];
for (k=0; k<3; k++) {
t_y_f[2] = y_f[2] + nc[k];
//printf("DEBUG: d_f %6.3f %6.3f %6.3f\n", d_f[0], d_f[1], d_f[2]);
// x_f is our reference point, y_f is tested in all 27 neighboring cells
matrix_vector_product(uc_vec, &t_y_f[0], &y_r[0]);
t_dist2 = pow(x_r[0]-y_r[0], 2) + pow(x_r[1]-y_r[1], 2) + pow(x_r[2]-y_r[2], 2);
if (t_dist2 <= n_dist2) n_dist2 = t_dist2;
}
}
}
return n_dist2;
}
double dist_mic(double x1, double x2, double x3, double y1, double y2, double y3, double b1, double b2, double b3) {
/* Method for obtaining inter atom distance using minimum image convention
*/
//printf("x1: %f, x2: %f, x3: %f\n", x1, x2, x3);
//printf("y1: %f, y2: %f, y3: %f\n", y1, y2, y3);
double dx, dy, dz;
dx = x1-y1;
dy = x2-y2;
dz = x3-y3;
//printf("dx: %f, dy: %f, dz: %f\n", dx, dy, dz);
//printf("bx: %f, by: %f, bz: %f\n", b1/2.0, b2/2.0, b3/2.0);
if (dx > b1/2.0) dx -= b1;
else if (dx < -b1/2.0) dx += b1;
if (dy > b2/2.0) dy -= b2;
else if (dy < -b2/2.0) dy += b2;
if (dz > b3/2.0) dz -= b3;
else if (dz < -b3/2.0) dz += b3;
//printf("dist = %f", sqrt(pow(dx, 2) + pow(dy, 2) + pow(dz, 2)));
return 1.0/(sqrt((dx*dx) +(dy*dy) + (dz*dz)));
}
double dist_mic_squared(float *x1, float *x2, float *x3, float *y1, float *y2, float *y3, float *b1, float *b2, float *b3) {
/* Method for obtaining inter atom distance using minimum image convention
*/
//printf("x1: %f, x2: %f, x3: %f\n", x1, x2, x3);
//printf("y1: %f, y2: %f, y3: %f\n", y1, y2, y3);
double dx, dy, dz;
dx = *x1-*y1;
dy = *x2-*y2;
dz = *x3-*y3;
//printf("dx: %f, dy: %f, dz: %f\n", dx, dy, dz);
//printf("bx: %f, by: %f, bz: %f\n", b1/2.0, b2/2.0, b3/2.0);
if (dx > *b1/2.0) dx -= *b1;
else if (dx < -*b1/2.0) dx += *b1;
if (dy > *b2/2.0) dy -= *b2;
else if (dy < -*b2/2.0) dy += *b2;
if (dz > *b3/2.0) dz -= *b3;
else if (dz < -*b3/2.0) dz += *b3;
//printf("dist = %f", sqrt(pow(dx, 2) + pow(dy, 2) + pow(dz, 2)));
return (dx*dx) + (dy*dy) + (dz*dz);
}
double dist(double x1, double x2, double x3, double y1, double y2, double y3) {
/* Method for Euclidean distance between two points
*/
double dx, dy, dz;
dx = x1-y1;
dy = x2-y2;
dz = x3-y3;
//printf("dist = %f", sqrt(pow(dx, 2) + pow(dy, 2) + pow(dz, 2)));
return sqrt(pow(dx, 2)+ pow(dy, 2)+ pow(dz, 2));
}
double dist_squared(double x1, double x2, double x3, double y1, double y2, double y3) {
/* Method for Euclidean distance between two points
*/
double dx, dy, dz;
dx = x1-y1;
dy = x2-y2;
dz = x3-y3;
//printf("dist = %f", sqrt(pow(dx, 2) + pow(dy, 2) + pow(dz, 2)));
return pow(dx, 2)+ pow(dy, 2)+ pow(dz, 2);
}
/*
Calculates electrostatic energy of a query water molecule against a set of target atoms
*/
PyObject *_sstmap_ext_assign_voxels(PyObject *self, PyObject *args)
{
int n_frames, i_frame, n_wat, i_wat;
PyArrayObject *coords, *grid_dim, *grid_max, *grid_orig, *wat_oxygen_ids;
PyObject *frame_data;
// declare local variables
double grid_max_x, grid_max_y, grid_max_z;
double grid_orig_x, grid_orig_y, grid_orig_z;
int grid_dim_x, grid_dim_y, grid_dim_z;
int grid_index_x, grid_index_y, grid_index_z;
double wat_translated_x, wat_translated_y, wat_translated_z;
int wat_id; // id of current water
float *wat_x, *wat_y, *wat_z; // coordinates
int dims[1];
PyArrayObject *wat_data;
PyObject *curr_voxel;
int voxel_id;
if (!PyArg_ParseTuple(args, "O!O!O!O!O!O!",
&PyArray_Type, &coords,
&PyArray_Type, &grid_dim,
&PyArray_Type, &grid_max,
&PyArray_Type, &grid_orig,
&PyList_Type, &frame_data,
&PyArray_Type, &wat_oxygen_ids
))
{
return NULL;
}
//Set the number of frames
n_frames = PyArray_DIM(coords, 0);
n_wat = PyArray_DIM(wat_oxygen_ids, 0);
//printf("The number of frames passed = %i\n", n_frames);
//printf("The number of waters passed = %i\n", n_wat);
grid_max_x = *(double *)PyArray_GETPTR1(grid_max, 0);
grid_max_y = *(double *)PyArray_GETPTR1(grid_max, 1);
grid_max_z = *(double *)PyArray_GETPTR1(grid_max, 2);
grid_orig_x = *(double *)PyArray_GETPTR1(grid_orig, 0);
grid_orig_y = *(double *)PyArray_GETPTR1(grid_orig, 1);
grid_orig_z = *(double *)PyArray_GETPTR1(grid_orig, 2);
grid_dim_x = *(int *)PyArray_GETPTR1(grid_dim, 0);
grid_dim_y = *(int *)PyArray_GETPTR1(grid_dim, 1);
grid_dim_z = *(int *)PyArray_GETPTR1(grid_dim, 2);
for (i_frame = 0; i_frame < n_frames; i_frame++)
{
//printf("Iterating over frame: %i\n", i_frame);
for (i_wat = 0; i_wat < n_wat; i_wat++)
{
dims[0] = 2;
// get water ID to and use it to get x, y, z coordinates and vdw params
wat_id = *(int *) PyArray_GETPTR1(wat_oxygen_ids, i_wat); // obtain atom index for this atom
wat_x = (float *) PyArray_GETPTR3(coords, i_frame, wat_id, 0);
wat_y = (float *) PyArray_GETPTR3(coords, i_frame, wat_id, 1);
wat_z = (float *) PyArray_GETPTR3(coords, i_frame, wat_id, 2);
wat_translated_x = *wat_x - grid_orig_x;
wat_translated_y = *wat_y - grid_orig_y;
wat_translated_z = *wat_z - grid_orig_z;
//printf("water oxygen ID %i and coordinates %f %f %f\n", wat_id, *wat_x, *wat_y, *wat_z);
// check if the distance between wateer coordinates and grid origin is less than the max grid point
if (wat_translated_x <= grid_max_x && wat_translated_y <= grid_max_y && wat_translated_z <= grid_max_z &&
wat_translated_x >= -1.5 && wat_translated_y >= -1.5 && wat_translated_z >= -1.5)
{
if (wat_translated_x >= 0 && wat_translated_y >= 0 && wat_translated_z >= 0)
{
// transform water coordinates in units of grid dimensions
grid_index_x = (int) (wat_translated_x/0.5);
grid_index_y = (int) (wat_translated_y/0.5);
grid_index_z = (int) (wat_translated_z/0.5);
// check if water coords (in grid dimensions) are less than grid dimensions in each direction
if (grid_index_x < grid_dim_x && grid_index_y < grid_dim_y && grid_index_z < grid_dim_z)
{
// obtain the voxel ID for this water
voxel_id = (grid_index_x*grid_dim_y + grid_index_y)*grid_dim_z + grid_index_z;
//voxel_ = (gridindex[0]*griddim_[1] + gridindex[1])*griddim_[2] + gridindex[2];
//printf("Water atom ID %i with coordinates %f %f %f assigned to voxel %i.\n", wat_id, *wat_x, *wat_y, *wat_z, voxel_id);
wat_data = (PyArrayObject *) PyArray_FromDims(1, dims, NPY_INT);
*(int *)PyArray_GETPTR1(wat_data, 0) = voxel_id;
*(int *)PyArray_GETPTR1(wat_data, 1) = wat_id;
//printf("wat_data: %d %d %d\n", voxel_id, *(int *)PyArray_GETPTR1(wat_data, 0), *(int *)PyArray_GETPTR1(wat_data, 1));
//curr_voxel = PyList_GetItem(frame_data, i_frame);
PyList_Append(frame_data, wat_data);
//DECREF?
}
}
}
} // finish iterating over waters
}
return Py_BuildValue("i", 1);
}
PyObject *_sstmap_ext_get_pairwise_distances(PyObject *self, PyObject *args)
{
PyArrayObject *wat, *target_at_ids, *coords, *uc, *dist_array;
float uc_vec[9], inv_uc_vec[9]; // << This is unit cell matrix and reciprocal unit cell
int wat_sites, wat_atom, wat_atom_id;
int num_target_at, target_at, target_at_id;
int frame = 0;
double d;
float *wat_x, *wat_y, *wat_z;
float *target_at_x, *target_at_y, *target_at_z;
int is_ortho = 0;
if (!PyArg_ParseTuple(args, "O!O!O!O!O!",
&PyArray_Type, &wat,
&PyArray_Type, &target_at_ids,
&PyArray_Type, &coords,
&PyArray_Type, &uc,
&PyArray_Type, &dist_array
))
{
return NULL;
}
// do distance calc here
// retrieve unit cell lengths for this frame
uc_vec[0] = *(float *) PyArray_GETPTR2(uc, 0, 0);
uc_vec[1] = *(float *) PyArray_GETPTR2(uc, 0, 1);
uc_vec[2] = *(float *) PyArray_GETPTR2(uc, 0, 2);
uc_vec[3] = *(float *) PyArray_GETPTR2(uc, 1, 0);
uc_vec[4] = *(float *) PyArray_GETPTR2(uc, 1, 1);
uc_vec[5] = *(float *) PyArray_GETPTR2(uc, 1, 2);
uc_vec[6] = *(float *) PyArray_GETPTR2(uc, 2, 0);
uc_vec[7] = *(float *) PyArray_GETPTR2(uc, 2, 1);
uc_vec[8] = *(float *) PyArray_GETPTR2(uc, 2, 2);
if ( uc_vec[1] < 0.000001 && uc_vec[1] > -0.000001 &&
uc_vec[2] < 0.000001 && uc_vec[2] > -0.000001 &&
uc_vec[3] < 0.000001 && uc_vec[3] > -0.000001 &&
uc_vec[5] < 0.000001 && uc_vec[5] > -0.000001 &&
uc_vec[6] < 0.000001 && uc_vec[6] > -0.000001 &&
uc_vec[7] < 0.000001 && uc_vec[7] > -0.000001 ) is_ortho = 1;
if ( !is_ortho ) {
memcpy( inv_uc_vec, uc_vec, sizeof(inv_uc_vec));
invert_matrix(&inv_uc_vec[0]);
//printf("Unit cell: %f %f %f\n", uc_vec[0], uc_vec[1], uc_vec[2]);
//printf("Unit cell: %f %f %f\n", uc_vec[3], uc_vec[4], uc_vec[5]);
//printf("Unit cell: %f %f %f\n", uc_vec[6], uc_vec[7], uc_vec[8]);
//printf("Inv. unit cell: %f %f %f\n", inv_uc_vec[0], inv_uc_vec[1], inv_uc_vec[2]);
//printf("Inv. unit cell: %f %f %f\n", inv_uc_vec[3], inv_uc_vec[4], inv_uc_vec[5]);
//printf("Inv. unit cell: %f %f %f\n", inv_uc_vec[6], inv_uc_vec[7], inv_uc_vec[8]);
//printf("\n");
}
wat_sites = PyArray_DIM(dist_array, 0);
num_target_at = PyArray_DIM(target_at_ids, 0);
for (wat_atom = 0; wat_atom < wat_sites; wat_atom++)
{
wat_atom_id = *(int *) PyArray_GETPTR1(wat, 1) + wat_atom;
wat_x = (float *) PyArray_GETPTR3(coords, frame, wat_atom_id, 0);
wat_y = (float *) PyArray_GETPTR3(coords, frame, wat_atom_id, 1);
wat_z = (float *) PyArray_GETPTR3(coords, frame, wat_atom_id, 2);
for (target_at = 0; target_at < num_target_at; target_at++)
{
target_at_id = *(int *) PyArray_GETPTR1(target_at_ids, target_at);
target_at_x = (float *) PyArray_GETPTR3(coords, frame, target_at_id, 0);
target_at_y = (float *) PyArray_GETPTR3(coords, frame, target_at_id, 1);
target_at_z = (float *) PyArray_GETPTR3(coords, frame, target_at_id, 2);
//printf("Iterator: %d, atom id: %d\n", target_at, target_at_id);
//printf("Water atom coords %f %f %f\n", *wat_x, *wat_y, *wat_z);
//printf("Target atom coords %f %f %f\n", *target_at_x, *target_at_y, *target_at_z);
if ( is_ortho ) {
//printf("Using dist_mic_squared routine.\n");
d = dist_mic_squared(wat_x, wat_y, wat_z, target_at_x, target_at_y, target_at_z, &uc_vec[0], &uc_vec[4], &uc_vec[8]);
}
else {
//printf("Using dist_mic_tric_squared routine.\n");
d = dist_mic_tric_squared(wat_x, wat_y, wat_z, target_at_x, target_at_y, target_at_z, &uc_vec[0], &inv_uc_vec[0]);
}
//printf("Distance between %d and %d = %3.2f\n", wat_atom_id, target_at_id, d);
*(double *)PyArray_GETPTR2(dist_array, wat_atom, target_at) += d;
}
}
return Py_BuildValue("i", 1);
}
PyObject *_sstmap_ext_getNNOrEntropy(PyObject *self, PyObject *args)
{
int nwtot, n, l;
double NNor, dW, wat_or_ent;
double voxel_dTSor = 0.0;
double rx, ry, rz;
PyArrayObject *voxel_wat_Eulers;
double twopi = 2*M_PI;
// Argument parsing to reterive everything sent from Python correctly
if (!PyArg_ParseTuple(args, "iO!",
&nwtot,
&PyArray_Type, &voxel_wat_Eulers))
{
return NULL; /* raise argument parsing exception*/
}
// for each water in the voxel
for (n = 0; n < nwtot; n++){
NNor = 10000;
for (l = 0; l < nwtot; l++){
if(l == n) continue;
//printf("Calculating orientational distancce between water: %i and %i\n", l, n);
rx = cos(*(double *)PyArray_GETPTR2(voxel_wat_Eulers, l, 0)) - cos(*(double *)PyArray_GETPTR2(voxel_wat_Eulers, n, 0));
ry = *(double *)PyArray_GETPTR2(voxel_wat_Eulers, l, 1) - *(double *)PyArray_GETPTR2(voxel_wat_Eulers, n, 1);
rz = *(double *)PyArray_GETPTR2(voxel_wat_Eulers, l, 2) - *(double *)PyArray_GETPTR2(voxel_wat_Eulers, n, 2);
if (ry>M_PI) ry = twopi-ry;
else if (ry<-M_PI) ry = twopi+ry;
if (rz>M_PI) rz = twopi-rz;
else if (rz<-M_PI) rz = twopi+rz;
dW = sqrt(rx*rx + ry*ry + rz*rz);
//dR = 0.0;
// get six-D distance
// get translational nearest neighbor
if (dW>0 && dW<NNor) NNor = dW;
// get six-D nearest neighbor
}
//calculate translational entropy
if (NNor<9999 && NNor>0) {
//printf("Nearest neighbour translational distance: %f\n", NNtr);
//wat_tr_ent = log(nwtot*NNtr*NNtr*NNtr/(3.0*twopi));
//voxel_dTStr_norm += wat_tr_ent;
wat_or_ent = log(nwtot*NNor*NNor*NNor/(3.0*twopi));
voxel_dTSor += wat_or_ent;
}
}
//
//*(double *)PyArray_GETPTR1(ent, 2) += voxel_dTSor_norm;
return Py_BuildValue("f", voxel_dTSor);
}
PyObject *_sstmap_ext_getNNTrEntropy(PyObject *self, PyObject *args)
{
float ref_dens;
float voxel_vol;
float temp;
int num_frames, n0, n1;
double dTStranstot = 0.0;
double dTSorienttot = 0;
double dTSt = 0.0;
double dTSs = 0.0;
double dTSo = 0.0;
int nwts = 0;
int nwtt = 0;
double pi = 3.141592653589793;
double twopi = 6.283185307179586;
double gas_kcal = 0.0019872041;
double euler_masc = 0.5772156649;
unsigned int voxel;
PyArrayObject *voxel_data, *grid_dims;
PyObject *voxel_O_coords, *voxel_quarts;
// Argument parsing to reterive everything sent from Python correctly
if (!PyArg_ParseTuple(args, "ifffO!O!O!O!",
&num_frames,
&voxel_vol,
&ref_dens,
&temp,
&PyArray_Type, &grid_dims,
&PyArray_Type, &voxel_data,
&PyList_Type, &voxel_O_coords,
&PyList_Type, &voxel_quarts))
{
return NULL; /* raise argument parsing exception*/
}
unsigned int nx = *(int *)PyArray_GETPTR1(grid_dims, 0);
unsigned int ny = *(int *)PyArray_GETPTR1(grid_dims, 1);
unsigned int nz = *(int *)PyArray_GETPTR1(grid_dims, 2);
unsigned max_voxel_index = nx * ny * nz;
unsigned int addx = ny * nz;
unsigned int addy = nz;
unsigned int addz = 1;
//PyObject *curr_voxel_coords;
//PyObject *curr_voxel_quarts;
//printf("grid dims: %i %i %i frames\n", nx, ny, nz);
//printf("DEBUG2: nx %d ny %d nz %d\n", nx, ny, nz);
for (voxel = 0; voxel < max_voxel_index; voxel++)
{
//
int numplane = voxel / addx;
double nw_total = *(double *)PyArray_GETPTR2(voxel_data, voxel, 4);
nwtt += nw_total;
//printf("DEBUG1 voxel %i N_waters %g 1.0*N_waters %g NFRAME_ %i Vvox %g\n", voxel, nw_total, 1.0 * nw_total, num_frames, voxel_vol);
double voxel_dens = 1.0 * nw_total / (num_frames * voxel_vol);
//printf("DEBUG2 voxel %i gO %g rho %g occ %g\n", voxel, voxel_dens/ref_dens, ref_dens, voxel_dens);
*(double *) PyArray_GETPTR2(voxel_data, voxel, 5) += voxel_dens / ref_dens;
//printf("DEBUG2 voxel %d gO %g rho %g occ %g\n", voxel, voxel_dens/ref_dens, ref_dens, voxel_dens);
PyObject *curr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel);
PyObject *curr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel);
for (n0 = 0; n0 < (int) nw_total; n0++)
{
double NNd = 10000;
double NNs = 10000;
double NNr = 10000;
int i0 = n0 * 3; // index over O coordinates
int q0 = n0 * 4; // index over quar
// access oxygen coordinates
PyObject *VX0 = PyList_GetItem(curr_voxel_coords, i0);
double vx0 = PyFloat_AsDouble(VX0);
PyObject *VY0 = PyList_GetItem(curr_voxel_coords, i0 + 1);
double vy0 = PyFloat_AsDouble(VY0);
PyObject *VZ0 = PyList_GetItem(curr_voxel_coords, i0 + 2);
double vz0 = PyFloat_AsDouble(VZ0);
// access quaternions
PyObject *QW0 = PyList_GetItem(curr_voxel_quarts, q0);
double qw0 = PyFloat_AsDouble(QW0);
PyObject *QX0 = PyList_GetItem(curr_voxel_quarts, q0 + 1);
double qx0 = PyFloat_AsDouble(QX0);
PyObject *QY0 = PyList_GetItem(curr_voxel_quarts, q0 + 2);
double qy0 = PyFloat_AsDouble(QY0);
PyObject *QZ0 = PyList_GetItem(curr_voxel_quarts, q0 + 3);
double qz0 = PyFloat_AsDouble(QZ0);
for (n1 = 0; n1 < (int) nw_total; n1++)
if ( n1 != n0)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(curr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(curr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(curr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(curr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(curr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(curr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(curr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
//printf("DEBUG1: %g\n", rR);
if (rR > 0 && rR < NNr) NNr = rR;
}
if (nw_total > 1)
{
if (NNr < 9999 && NNr > 0)
{
double dbl = log(NNr * NNr * NNr * nw_total / (3.0 * twopi));
//printf("DEBUG1: dbl %f\n", dbl);
*(double *) PyArray_GETPTR2(voxel_data, voxel, 10) += dbl;
dTSo += dbl;
}
}
bool cannotAddZ = (nz == 0 || ( voxel%nz == nz-1 ));
bool cannotAddY = ((nz == 0 || ny-1 == 0) || ( voxel%(nz*(ny-1)+(numplane*addx)) < nz));
bool cannotAddX = (voxel >= addx * (nx-1) && voxel < addx * nx );
bool cannotSubZ = (nz == 0 || voxel%nz == 0);
bool cannotSubY = ((nz == 0 || ny == 0) || (voxel%addx < nz));
bool cannotSubX = ((nz == 0 || ny == 0) || (voxel >= 0 && voxel < addx));
bool boundary = ( cannotAddZ || cannotAddY || cannotAddX ||
cannotSubZ || cannotSubY || cannotSubX );
//printf("DEBUG2: boundary= %d\n", boundary);
//TODO: Replace this massive code repetition with a reusable function
if (!boundary)
{
PyObject *nbr_voxel_coords, *nbr_voxel_quarts;
double n1_total;
/* Iterate over neighbor voxel in +Z direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addz, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addz);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addz);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Z direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addz, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addz);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addz);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Z +Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addz + addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addz + addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addz + addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Z -Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addz - addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addz - addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addz - addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Z +Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addz + addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addz + addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addz + addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Z -Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addz - addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addz - addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addz - addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Z +Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addz + addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addz + addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addz + addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Z -Y direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addz - addy, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addz - addy);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addz - addy);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Z +X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addz + addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addz + addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addz + addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Z -X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addz - addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addz - addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addz - addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Z +X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addz + addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addz + addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addz + addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Z -X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addz - addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addz - addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addz - addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Y +X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addy + addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addy + addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addy + addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in +Y -X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel + addy - addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel + addy - addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel + addy - addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Y +X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addy + addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addy + addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addy + addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
/* Iterate over neighbor voxel in -Y -X direction
*/
n1_total = *(double *)PyArray_GETPTR2(voxel_data, voxel - addy - addx, 4);
nbr_voxel_coords = PyList_GetItem(voxel_O_coords, voxel - addy - addx);
nbr_voxel_quarts = PyList_GetItem(voxel_quarts, voxel - addy - addx);
for (n1 = 0; n1 != (int)n1_total; n1++)
{
// access oxygen coordinates
int i1 = n1 * 3; // index over O coordinates
int q1 = n1 * 4; // index over quar
PyObject *VX1 = PyList_GetItem(nbr_voxel_coords, i1);
double vx1 = PyFloat_AsDouble(VX1);
PyObject *VY1 = PyList_GetItem(nbr_voxel_coords, i1 + 1);
double vy1 = PyFloat_AsDouble(VY1);
PyObject *VZ1 = PyList_GetItem(nbr_voxel_coords, i1 + 2);
double vz1 = PyFloat_AsDouble(VZ1);
// access quaternions
PyObject *QW1 = PyList_GetItem(nbr_voxel_quarts, q1);
double qw1 = PyFloat_AsDouble(QW1);
PyObject *QX1 = PyList_GetItem(nbr_voxel_quarts, q1 + 1);
double qx1 = PyFloat_AsDouble(QX1);
PyObject *QY1 = PyList_GetItem(nbr_voxel_quarts, q1 + 2);
double qy1 = PyFloat_AsDouble(QY1);
PyObject *QZ1 = PyList_GetItem(nbr_voxel_quarts, q1 + 3);
double qz1 = PyFloat_AsDouble(QZ1);
double dd = dist_squared(vx0, vy0, vz0, vx1, vy1, vz1);
if (dd < NNd && dd > 0) { NNd = dd; }
double rR = 2 * acos(qw0 * qw1 +
qx0 * qx1 +
qy0 * qy1 +
qz0 * qz1 );
double ds = rR * rR + dd;
if (ds < NNs && ds > 0) {NNs = ds; }
//printf("DEBUG2: voxel=%i water=%i\n", voxel, n0);
//printf("DEBUG2: self NNd=%f NNs=%f\n", NNd, NNs);
}
NNd = sqrt(NNd);
NNs = sqrt(NNs);
if (NNd < 3 && NNd > 0)
{
double dbl = log((NNd * NNd * NNd * num_frames * 4 * pi * ref_dens) / 3);
*(double *) PyArray_GETPTR2(voxel_data, voxel, 8) += dbl;
dTSt += dbl;
dbl = log((NNs * NNs * NNs * NNs * NNs * NNs * num_frames * pi * ref_dens) / 48);
*(double *) PyArray_GETPTR2(voxel_data, voxel, 12) += dbl;
dTSs += dbl;
}
}
} // end loop over waters in this voxel
double dTStrans_norm = *(double *)PyArray_GETPTR2(voxel_data, voxel, 8);
double dTSorient_norm = *(double *)PyArray_GETPTR2(voxel_data, voxel, 10);
double dTSsix_norm = *(double *)PyArray_GETPTR2(voxel_data, voxel, 12);
if (dTSorient_norm != 0)
{
*(double *)PyArray_GETPTR2(voxel_data, voxel, 10) = gas_kcal * temp * ((dTSorient_norm/nw_total) + euler_masc);
*(double *)PyArray_GETPTR2(voxel_data, voxel, 9) = *(double *)PyArray_GETPTR2(voxel_data, voxel, 10) * nw_total / (num_frames * voxel_vol);
}
dTSorienttot += *(double *)PyArray_GETPTR2(voxel_data, voxel, 9);
if (dTStrans_norm != 0)
{
nwts += nw_total;
*(double *) PyArray_GETPTR2(voxel_data, voxel, 8) = gas_kcal * temp * ((dTStrans_norm / nw_total) +
euler_masc);
*(double *) PyArray_GETPTR2(voxel_data, voxel, 12) = gas_kcal * temp * ((dTSsix_norm / nw_total) +
euler_masc);
}
*(double *) PyArray_GETPTR2(voxel_data, voxel, 7) = *(double *) PyArray_GETPTR2(voxel_data, voxel, 8) * nw_total / (num_frames * voxel_vol);
*(double *) PyArray_GETPTR2(voxel_data, voxel, 11) = *(double *) PyArray_GETPTR2(voxel_data, voxel, 12) * nw_total / (num_frames * voxel_vol);
dTStranstot += *(double *) PyArray_GETPTR2(voxel_data, voxel, 7);
} // end loop over all grid points
dTStranstot *= voxel_vol;
dTSorienttot *= voxel_vol;
double dTSst = 0.0;
double dTStt = 0.0;
if (nwts > 0)
{
dTSst = gas_kcal * temp * ((dTSs / nwts) + euler_masc);
dTStt = gas_kcal * temp * ((dTSt/nwts) + euler_masc);
}
printf("Total referenced orientational entropy of the grid:"
" dTSorient = %9.5f kcal/mol, Nf=%d\n", dTSorienttot, num_frames);
double dTSot = gas_kcal * temp * ((dTSo/nwtt) + euler_masc);
//printf("watcount in vol = %d\n", nwtt);
//printf("watcount in subvol = %d\n", nwts);
printf("Total referenced translational entropy of the grid:"
" dTStrans = %9.5f kcal/mol, Nf=%d\n", dTStranstot, num_frames);
printf("Total 6d if all one vox: %9.5f kcal/mol\n", dTSst);
printf("Total t if all one vox: %9.5f kcal/mol\n", dTStt);
printf("Total o if all one vox: %9.5f kcal/mol\n", dTSot);
return Py_BuildValue("i", 0);
}
PyObject *_sstmap_ext_get_dist_matrix(PyObject *self, PyObject *args)
{
int nwtot, n, l;
double dR, nx, ny, nz, lx, ly, lz;
PyArrayObject *dist_matrix;
PyArrayObject *wat_coords;
// Argument parsing to reterive everything sent from Python correctly
if (!PyArg_ParseTuple(args, "iO!O!",
&nwtot,
&PyArray_Type, &dist_matrix,
&PyArray_Type, &wat_coords))
{
return NULL; /* raise argument parsing exception*/
}
// for each water in the voxel
for (n = 0; n < nwtot; n++)
{
nx = *(double *)PyArray_GETPTR2(wat_coords, n, 0);
ny = *(double *)PyArray_GETPTR2(wat_coords, n, 1);
nz = *(double *)PyArray_GETPTR2(wat_coords, n, 2);
for (l = 0; l < nwtot; l++)
{
if(l == n) continue;
//printf("Calculating orientational distancce between water: %i and %i\n", l, n);
lx = *(double *)PyArray_GETPTR2(wat_coords, l, 0);
ly = *(double *)PyArray_GETPTR2(wat_coords, l, 1);
lz = *(double *)PyArray_GETPTR2(wat_coords, l, 2);
dR = dist(nx, ny, nz, lx, ly, lz);
*(double *)PyArray_GETPTR2(dist_matrix, n, l) = dR;
}
}
return Py_BuildValue("i", 1);
}
PyObject *_sstmap_ext_calculate_energy(PyObject *self, PyObject *args)
{
PyArrayObject *dist, *chg, *acoeff, *bcoeff;
int solvent_at_sites, n_atoms, wat, i, j, at_i;
double *d, *a, *b, *c;
double d_sqrt, d_inv, d6, d12;
//PyObject* nbrs = PyList_New(100);
if (!PyArg_ParseTuple(args, "iO!O!O!O!",
&wat,
&PyArray_Type, &dist,
&PyArray_Type, &chg,
&PyArray_Type, &acoeff,
&PyArray_Type, &bcoeff))
{
return NULL;
}
solvent_at_sites = PyArray_DIM(dist, 0);
n_atoms = PyArray_DIM(dist, 1);
//printf("The number of solvent atoms = %i\n", solvent_at_sites);
//printf("The number of target atoms = %i\n", n_atoms);
// for each water in the voxel
for (i = 0; i < solvent_at_sites; i++)
{
at_i = wat + i;
for (j = 0; j < n_atoms; j++)
{
if (at_i == j) continue;
d = (double *) PyArray_GETPTR2(dist, i, j);
a = (double *) PyArray_GETPTR2(acoeff, i, j);
b = (double *) PyArray_GETPTR2(bcoeff, i, j);
c = (double *) PyArray_GETPTR2(chg, i, j);
//printf("Acoeff between %i and %i is %f\n", at_i, j, *a);
//printf("Bcoeff between %i and %i is %f\n", at_i, j, *b);
//printf("CHP between %i and %i is %f\n", i, j, *c);
d_sqrt = sqrt(*d);
d_inv = 1.0 / *d;
d6 = d_inv * d_inv * d_inv;
d12 = d6 * d6;
//e_vdw += (*a * d12) + (*b * d6);
//e_elec += *c * 1/d_sqrt;
*a *= d12;
*a -= (*b * d6);
*c /= d_sqrt;
//if (at_i > 4614 && j >= 4614)
//{
// printf("Dist of elec energy between %i and %i is %f\n", at_i, j, d_sqrt);
// //printf("Pairwise elec energy between %i and %i is %f\n", at_i, j, *c);
//}
}
}
return Py_BuildValue("i", 1);
}
/* Method Table
* Registering all the functions that will be called from Python
*/
static PyMethodDef _sstmap_ext_methods[] = {
{
"assign_voxels",
(PyCFunction)_sstmap_ext_assign_voxels,
METH_VARARGS,
"Process grid"
},
{
"get_pairwise_distances",
(PyCFunction)_sstmap_ext_get_pairwise_distances,
METH_VARARGS,
"get distance matrix"
},
{
"getNNOrEntropy",
(PyCFunction)_sstmap_ext_getNNOrEntropy,
METH_VARARGS,
"get voxel entropy"
},
{
"getNNTrEntropy",
(PyCFunction)_sstmap_ext_getNNTrEntropy,
METH_VARARGS,
"get voxel entropy"
},
{
"calculate_energy",
(PyCFunction)_sstmap_ext_calculate_energy,
METH_VARARGS,
"get energy"
},
{
"get_dist_matrix",
(PyCFunction)_sstmap_ext_get_dist_matrix,
METH_VARARGS,
"get voxel entropy"
},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define MOD_ERROR_VAL NULL
#define MOD_SUCCESS_VAL(val) val
#define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
#define MOD_DEF(ob, name, doc, methods) \
static struct PyModuleDef extmoduledef = { \
PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
ob = PyModule_Create(&extmoduledef);
#else
#define MOD_ERROR_VAL
#define MOD_SUCCESS_VAL(val)
#define MOD_INIT(name) void init##name(void)
#define MOD_DEF(ob, name, doc, methods) \
ob = Py_InitModule3(name, methods, doc);
#endif
/* Initialization function for this module
*/
MOD_INIT(_sstmap_ext)
{
PyObject *m;
MOD_DEF(m, "_sstmap_ext", "Process GIST calcs.\n", _sstmap_ext_methods)
if (m == NULL)
return MOD_ERROR_VAL;
import_array();
return MOD_SUCCESS_VAL(m);
}
| {
"alphanum_fraction": 0.5075887725,
"avg_line_length": 48.2649625935,
"ext": "c",
"hexsha": "49dbb457e991d951e4bdd764c95d6faa95244f1b",
"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": "7b50907cb051e6cca0a89441b37352c920234c73",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "acruzpr/SSTMap",
"max_forks_repo_path": "sstmap/_sstmap_ext.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7b50907cb051e6cca0a89441b37352c920234c73",
"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": "acruzpr/SSTMap",
"max_issues_repo_path": "sstmap/_sstmap_ext.c",
"max_line_length": 151,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "7b50907cb051e6cca0a89441b37352c920234c73",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "acruzpr/SSTMap",
"max_stars_repo_path": "sstmap/_sstmap_ext.c",
"max_stars_repo_stars_event_max_datetime": "2018-04-25T17:08:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-04-25T17:08:45.000Z",
"num_tokens": 22491,
"size": 77417
} |
#pragma once
#include "halley/plugin/iasset_importer.h"
#include <gsl/gsl>
namespace Halley
{
class AudioImporter : public IAssetImporter
{
public:
ImportAssetType getType() const override { return ImportAssetType::Audio; }
void import(const ImportingAsset& asset, IAssetCollector& collector) override;
private:
Bytes encodeVorbis(int channels, int sampleRate, gsl::span<const std::vector<float>> src);
static std::vector<float> resampleChannel(int from, int to, gsl::span<const float> src);
};
}
| {
"alphanum_fraction": 0.7563352827,
"avg_line_length": 27,
"ext": "h",
"hexsha": "c6037aca89b6dbd8aa64971c785058d675d8dc9f",
"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/assets/importers/audio_importer.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/assets/importers/audio_importer.h",
"max_line_length": 92,
"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/assets/importers/audio_importer.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": 129,
"size": 513
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "arcana/type_traits.h"
#include "arcana/either.h"
#include "arcana/iterators.h"
#include <memory>
#include <gsl/gsl>
#include <utility>
#include <cereal/cereal.hpp>
#include <cereal/archives/json.hpp>
namespace mira
{
//
// Generic object used to iterate an object hierarchy in order to
// iterate all its members in the goal of introspecting objects as they
// flow through a system.
//
// CallableT is anything that can get invoked to introspect an object hierarchy.
// It supports cereal serialization out of the box in order to help writing out
// object hierarchies to file, so one thing to be aware of is that when iterating
// if you need to handle T's and cereal::NameValuePair<T>'s.
//
// The introspection contract isn't as strict as the serialization contract.
// If a type is already serializable using cereal, it should already support
// being introspected.
//
// If the type can't be serialized for any reason it can still be introspected.
// All a type needs in order to be introspected is a free function with the following
// signature:
//
// template<typename ArchiveT>
// void introspect_object(introspector<ArchiveT>& archive, const Foo& object)
// {
// archive(
// cereal::make_nvp("Param1", object.param1),
// object.param2 // if the name doesn't matter, but it usually helps.
// );
// }
//
namespace internal
{
// helper struct to support nested introspectable types
// that create objects in the serializer.
struct nested_serialize_object
{
std::function<void()> callback;
template<typename ArchiveT>
void save(ArchiveT&) const
{
callback();
}
};
// helper struct to support nested introspectable objects
// that don't create objects but act as additional data to the parent.
struct nested_serialize_inline
{
std::function<void()> callback;
template<typename ArchiveT>
void save(ArchiveT&) const
{
callback();
}
};
inline void prologue(cereal::JSONOutputArchive&, const nested_serialize_inline&)
{}
inline void epilogue(cereal::JSONOutputArchive&, const nested_serialize_inline&)
{}
}
template<typename CallableT>
class introspector
{
template<typename L>
struct has_internal_introspection_function_test
{
template<typename T,
typename = decltype(introspect_object_internal(instance_of<introspector<CallableT>>(), instance_of<T>()))>
static std::true_type test(T* = nullptr);
static std::false_type test(...);
};
template<typename T>
using has_internal_introspection_function = decltype(has_internal_introspection_function_test<CallableT>::test(&instance_of<T>()));
template<typename L>
struct has_custom_introspection_function_test
{
template<typename T,
typename = decltype(introspect_object(instance_of<introspector<CallableT>>(), instance_of<T>()))>
static std::true_type test(T* = nullptr);
static std::false_type test(...);
};
template<typename T>
using has_custom_introspection_function = decltype(has_custom_introspection_function_test<CallableT>::test(&instance_of<T>()));
public:
template<typename ItrT>
explicit introspector(ItrT&& i)
: m_callable{ std::forward<ItrT>(i) }
{}
using internally_introspected = std::integral_constant<size_t, 0>;
using externally_introspected = std::integral_constant<size_t, 1>;
using default_introspected = std::integral_constant<size_t, 2>;
template<typename T>
using introspection_type =
find_first_index<has_internal_introspection_function<T>, has_custom_introspection_function<T>>;
template<typename T>
static constexpr bool should_introspect()
{
return introspection_type<T>::value < default_introspected::value;
}
template<typename ...ArgTs>
void operator()(ArgTs&& ...args)
{
mira::static_foreach([this](auto&& arg)
{
introspect(std::forward<decltype(arg)>(arg));
}, std::forward<ArgTs>(args)...);
}
template<typename T>
void introspect(const T& value)
{
introspect_dispatch(value, introspection_type<T>{});
}
CallableT& callable()
{
return m_callable;
}
const CallableT& callable() const
{
return m_callable;
}
private:
template<typename T>
void introspect_dispatch(const T& value, internally_introspected)
{
introspect_object_internal(*this, value);
}
template<typename T>
void introspect_dispatch(const T& value, externally_introspected)
{
internal::nested_serialize_object nested{ [&]
{
introspect_object(*this, value);
} };
m_callable(nested);
}
template<typename T>
void introspect_dispatch(const T& value, default_introspected)
{
m_callable(value);
}
CallableT m_callable;
};
template<typename CallableT, typename T>
void introspect_object_internal(introspector<CallableT>& ar, const cereal::NameValuePair<T>& named)
{
internal::nested_serialize_inline nested{ [&]
{
ar.introspect(named.value);
} };
ar.callable()(cereal::make_nvp(named.name, nested));
}
template<typename CallableT, typename T>
void introspect_object_internal(introspector<CallableT>& ar, const T* object)
{
if (!object)
{
ar.callable()(cereal::make_nvp("pointer", nullptr));
}
else
{
internal::nested_serialize_inline nested{ [&]
{
ar.introspect(*object);
} };
ar.callable()(cereal::make_nvp("pointer", nested));
}
}
template<typename CallableT, typename T>
void introspect_object(introspector<CallableT>& ar, const std::shared_ptr<T>& ptr)
{
ar.introspect(ptr.get());
}
template<typename CallableT, typename T, typename D>
void introspect_object(introspector<CallableT>& ar, const std::unique_ptr<T, D>& ptr)
{
ar.introspect(ptr.get());
}
template<typename CallableT, typename T, std::ptrdiff_t Extent>
void introspect_object(introspector<CallableT>& ar, gsl::span<T, Extent> elements)
{
ar.callable()(cereal::SizeTag<cereal::size_type>(elements.size()));
for (auto& el : elements)
{
ar.introspect(el);
}
}
template<typename CallableT, typename T, typename AllocT>
void introspect_object(introspector<CallableT>& ar, const std::vector<T, AllocT>& elements)
{
introspect_object(ar, gsl::make_span(elements));
}
template<typename CallableT, typename A, typename B>
void introspect_object(introspector<CallableT>& ar, const std::pair<A, B>& elements)
{
ar(
cereal::make_nvp("First", elements.first),
cereal::make_nvp("Second", elements.second)
);
}
}
| {
"alphanum_fraction": 0.6094359241,
"avg_line_length": 31.1497975709,
"ext": "h",
"hexsha": "525e4827c54eb835a95f9d9a42e52d66dd208fc4",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/introspector.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/introspector.h",
"max_line_length": 139,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/introspector.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 1638,
"size": 7694
} |
#include <stdio.h>
#include <stdlib.h>
#define COMPEARTH_PRIVATE_GEM3 1
#define COMPEARTH_PRIVATE_GEMT3 1
#include "compearth.h"
#ifdef DEBUG
#ifdef COMPEARTH_USE_MKL
#include <mkl_cblas.h>
#else
#include <cblas.h>
#endif
#endif
/*!
* @brief Transforms a set of 3 x 3 tensors using transformation matrix T.
*
* @param[in] nmt Number of moment tensors.
* @param[in] T 3 x 3 transformation matrix in column major order.
* @param[in] Min [3 x 3 x n] input matrices. Each [3 x 3] matrix is in
* column major order.
* @param[out] Mout [3 x 3 x n] output matrices. Each [3 x 3] matrix is
* in column major order.
* @result 0 indicates success.
*
* @author Carl Tape and translated to C by Ben Baker.
*
*/
int compearth_transform_mat(const int nmt,
const double *__restrict__ T,
const double *__restrict__ Min,
double *__restrict__ Mout)
{
double TM[9];
int imt; //i, j
// Compute T*Min*T'
for (imt=0; imt<nmt; imt++)
{
#ifdef DEBUG
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
3, 3, 3, 1.0, T, 3, &Min[9*imt], 3, 0.0, TM, 3);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
3, 3, 3, 1.0, TM, 3, T, 3, 0.0, &Mout[9*imt], 3);
#else
gemm3_colMajorNoTransTrans(T, &Min[9*imt], TM);
gemm3_colMajorNoTransTrans(TM, T, &Mout[9*imt]);
#endif
}
return 0;
}
| {
"alphanum_fraction": 0.5922974768,
"avg_line_length": 29.5294117647,
"ext": "c",
"hexsha": "ddb12aa28020ae6cf6a3250b742922c9b14cd342",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z",
"max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "carltape/mtbeach",
"max_forks_repo_path": "c_src/transform_mat.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "carltape/mtbeach",
"max_issues_repo_path": "c_src/transform_mat.c",
"max_line_length": 75,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OUCyf/mtbeach",
"max_stars_repo_path": "c_src/transform_mat.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z",
"num_tokens": 481,
"size": 1506
} |
#ifndef GLOBALS_H
#define GLOBALS_H
#define PROG_NAME "WVT ICs"
#define VERSION "1.0"
/* C std lib */
#include <stdlib.h> // system
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <limits.h>
#include <complex.h>
/* GNU Scientifc Library */
#include <gsl/gsl_math.h>
#include <gsl/gsl_const_cgsm.h>
#include <gsl/gsl_const_num.h>
#include <gsl/gsl_rng.h>
#include <omp.h>
/* Global Prototypes */
#include "macro.h"
#include "peano.h"
#include "proto.h"
/* To eat PNG density files */
#ifdef EAT_PNG
#include "png.h"
#include "zlib.h"
#endif
#include "peanowalk.h"
/* Code parameters */
#define CHARBUFSIZE 512 // For any char buffer !
#define MAXTAGS 300 // In parameter file
#ifdef TWO_DIM
#ifdef SPH_CUBIC_SPLINE
#define DESNNGB 14 // SPH kernel weighted number of neighbours
#define NNGBDEV 0.01 // error tolerance in SPH kernel weighted neighb.
#define NGBMAX (DESNNGB*16) // size of neighbour list
#else
#ifdef SPH_WC2
#define DESNNGB 16 // SPH kernel weighted number of neighbours
#define NNGBDEV 0.01 // error tolerance in SPH kernel weighted neighb.
#define NGBMAX (DESNNGB*8) // size of neighbour list
#else
#define DESNNGB 44 // SPH kernel weighted number of neighbours
#define NNGBDEV 0.01 // error tolerance in SPH kernel weighted neighb.
#define NGBMAX (DESNNGB*8) // size of neighbour list
#endif // SPH_WC2
#endif // SPH_CUBIC_SPLINE
#else
#ifdef SPH_CUBIC_SPLINE
#define DESNNGB 50 // SPH kernel weighted number of neighbours
#define NNGBDEV 0.05 // error tolerance in SPH kernel weighted neighb.
#define NGBMAX (DESNNGB*16) // size of neighbour list
#else
#ifdef SPH_WC2
#define DESNNGB 64 // SPH kernel weighted number of neighbours
#define NNGBDEV 0.05 // error tolerance in SPH kernel weighted neighb.
#define NGBMAX (DESNNGB*8) // size of neighbour list
#else
#define DESNNGB 295 // SPH kernel weighted number of neighbours
#define NNGBDEV 0.05 // error tolerance in SPH kernel weighted neighb.
#define NGBMAX (DESNNGB*8) // size of neighbour list
#endif // SPH_WC2
#endif // SPH_CUBIC_SPLINE
#endif // TWO_DIM
/* mathematical constants */
#define pi M_PI
#define sqrt2 M_SQRT2
#define sqrt3 1.73205080756887719
#define fourpithird 4.18879032135009765
extern const double ULength, UMass, UVel; // Standard Gadget units (setup.c)
extern struct OpenMP_infos {
int NThreads; // Number of openMP threads
int ThreadID; // Thread ID of this thread
unsigned short Seed[3]; // random number seed: erand48(Omp.Seed)
} Omp;
#pragma omp threadprivate(Omp)
extern struct Parameters {
int Npart;
int Maxiter;
double MpsFraction; // move this fraction of the mean particle sep
double StepReduction; // force convergence at this rate
double BiasCorrection; // density bias correction factor
double LimitMps[4]; // Convergence criterium for particle movement
double MoveFractionMin; // move at least this fraction of particles during redistribution steps
double MoveFractionMax; // move at most this fraction of particles during redistribution steps
double ProbesFraction;
int RedistributionFrequency;
int LastMoveStep;
int Problem_Flag;
int Problem_Subflag;
} Param;
extern struct ProblemParameters {
char Name[CHARBUFSIZE];
double Mpart;
double Boxsize[3]; // [0] is ALWAYS the largest one !
double Rho_Max;
bool Periodic[3];
} Problem;
#ifdef EAT_PNG
extern struct ImageProperties {
char Name[CHARBUFSIZE];
float *Density;
int Xpix;
int Ypix;
int Zpix;
} Image;
#endif
extern struct ParticleData {
double Pos[3];
double Vel[3];
int32_t ID;
int Type;
peanoKey Key;
int Tree_Parent;
bool Redistributed;
} *P;
extern struct GasParticleData {
float U;
float Rho;
float Hsml;
float VarHsmlFac;
float ID;
float Rho_Model;
float Bfld[3];
} *SphP;
extern float ( *Density_Func_Ptr ) ( const int, const double );
extern float ( *U_Func_Ptr ) ( const int );
extern void ( *Velocity_Func_Ptr ) ( const int, float * );
extern void ( *Magnetic_Field_Func_Ptr ) ( const int, float * );
extern void ( *PostProcessing_Func_Ptr ) ();
double G; // gravitational constant in code units
#endif
| {
"alphanum_fraction": 0.6966569441,
"avg_line_length": 25.4685714286,
"ext": "h",
"hexsha": "84fb37858c868a668c7a7edae1db9c7459ddc3c4",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-19T12:31:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-07-29T09:38:57.000Z",
"max_forks_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "elehcim/WVTICs",
"max_forks_repo_path": "src/globals.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03",
"max_issues_repo_issues_event_max_datetime": "2021-02-23T12:22:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-23T12:22:14.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "elehcim/WVTICs",
"max_issues_repo_path": "src/globals.h",
"max_line_length": 99,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "elehcim/WVTICs",
"max_stars_repo_path": "src/globals.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T08:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-07-29T04:44:13.000Z",
"num_tokens": 1187,
"size": 4457
} |
#ifndef MAINH
#define MAINH
#include <stdlib.h>
#include <string.h>
#include "data.h"
#include "lda-seq.h"
#include "lda.h"
#include <gsl/gsl_matrix.h>
typedef struct dtm_fit_params
{
char* datafile;
char* outname;
char* heldout;
int start;
int end;
int ntopics;
int lda_max_em_iter;
double top_obs_var;
double top_chain_var;
double alpha;
} dtm_fit_params;
#endif
| {
"alphanum_fraction": 0.6789215686,
"avg_line_length": 15.6923076923,
"ext": "h",
"hexsha": "cb843c0b343f15df0dc11dcf821ee3594c8674c5",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z",
"max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwangjian/topic-extractor",
"max_forks_repo_path": "scripts/lib/DTM/dtm/main.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"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": "iwangjian/topic-extractor",
"max_issues_repo_path": "scripts/lib/DTM/dtm/main.h",
"max_line_length": 29,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwangjian/dtm-lab",
"max_stars_repo_path": "scripts/lib/DTM/dtm/main.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z",
"num_tokens": 114,
"size": 408
} |
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <mpi.h>
#include <cblas.h>
#include "utils.h"
#ifndef MATRIX_SIZE
#define MATRIX_SIZE 128
#pragma message "Using default matrix size"
#endif
#define MIN_BUFF_SIZE MATRIX_SIZE*MATRIX_SIZE*sizeof(double)
#ifndef REUSE_BUFFER
#define REUSE_BUFFER 1
#endif
#if REUSE_BUFFER
#pragma message "Using the same buffers for communications and computations"
#else
#pragma message "Using different buffers for communications and computations"
#endif
#define MAX_NAME_SIZE 100
#define NB_RUNS 10
static void *my_send_buffer;
static void *my_recv_buffer;
static void *aux_buffer;
static double *matrix_A, *matrix_B, *matrix_C;
static int op_id = 0;
FILE *open_file(const char *dir_name, const char *file_prefix){
char* filename= malloc(MAX_NAME_SIZE*sizeof(char));
int my_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
sprintf(filename, "%s/%s_%d.csv", dir_name, file_prefix, my_rank);
FILE *file = fopen(filename, "w");
if(!file) {
perror("open_file");
fprintf(stderr, "Maybe directory %s does not exist?\n", dir_name);
exit(errno);
}
free(filename);
MPI_Barrier(MPI_COMM_WORLD);
return file;
}
void send_msg(int size, int dst, FILE *file, int args[], int nb_args, unsigned long long base_time) {
unsigned long long start_time=get_time();
MPI_Send(my_send_buffer, size, MPI_CHAR, dst, 0, MPI_COMM_WORLD);
unsigned long long total_time=get_time()-start_time;
print_in_file(file, "MPI_Send", args, nb_args, start_time-base_time, total_time);
}
void recv_msg(int size, int src, FILE *file, int args[], int nb_args, unsigned long long base_time, int busy_waiting) {
int flag = 0;
// Meanwhile we are waiting for a message to be there, we call dgemm
while(busy_waiting & !flag) {
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, MATRIX_SIZE, MATRIX_SIZE, MATRIX_SIZE, 1., matrix_A,
MATRIX_SIZE, matrix_B, MATRIX_SIZE, 1., matrix_C, MATRIX_SIZE);
MPI_Iprobe(src, 0, MPI_COMM_WORLD, &flag, MPI_STATUS_IGNORE);
}
unsigned long long start_time=get_time();
MPI_Recv(my_recv_buffer, size, MPI_CHAR, src, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
unsigned long long total_time=get_time()-start_time;
print_in_file(file, "MPI_Recv", args, nb_args, start_time-base_time, total_time);
}
void get_ring(FILE *file, int size, int nb_it, unsigned long long base_time) {
static int my_rank = -1;
static int nb_ranks = -1;
if(my_rank < 0) {
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &nb_ranks);
}
for(int i=0; i<nb_it; i++) {
int args[] = {my_rank, size, op_id++};
int recv_from = (my_rank-1+nb_ranks)%nb_ranks;
int send_to = (my_rank+1)%nb_ranks;
// I am the root of the broadcast, I send
if(my_rank == 0) {
send_msg(size, send_to, file, args, sizeof(args)/sizeof(args[0]), base_time);
}
// I receive
recv_msg(size, recv_from, file, args, sizeof(args)/sizeof(args[0]), base_time, 1);
// I am *not* the root of the broadcast, I send
if(my_rank != 0) {
send_msg(size, send_to, file, args, sizeof(args)/sizeof(args[0]), base_time);
}
}
}
void get_ringrong(FILE *file, int size, int nb_it, unsigned long long base_time) {
static int my_rank = -1;
static int nb_ranks = -1;
if(my_rank < 0) {
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &nb_ranks);
}
for(int i=0; i<nb_it; i++) {
int args[] = {my_rank, size, op_id++};
int prev = (my_rank-1+nb_ranks)%nb_ranks;
int next = (my_rank+1)%nb_ranks;
if(my_rank == 0) {
send_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time);
recv_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time, 0);
recv_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time, 1);
send_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time);
}
else {
recv_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time, 1);
send_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time);
send_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time);
recv_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time, 0);
}
}
}
static const char *names[] = {"Ring", "RingRong", NULL};
static const void (*functions[])(FILE*, int, int, unsigned long long) = {get_ring, get_ringrong};
void test_op(FILE *result_file, experiment_t *exp, int nb_runs, unsigned long long base_time) {
functions[exp->op_id](result_file, exp->sizes[0], nb_runs, base_time);
}
void *allocate_buffer(int size) {
if(size < MIN_BUFF_SIZE)
size = MIN_BUFF_SIZE;
char *buffer = (void*)malloc(size);
if(buffer == NULL){
fprintf(stderr, "Can't allocate memory (%g GB), decrease max size of the messages \n",
size*1e-9);
perror("malloc");
exit(1);
}
for(int i = 0; i < size; i++) {
buffer[i] = rand();
}
return(buffer);
}
int main(int argc, char *argv[]) {
printf("Matrix size: %d\n", MATRIX_SIZE);
if(argc != 3) {
fprintf(stderr, "Syntax: %s <input_file> <output_directory>\n");
exit(1);
}
const char *input = argv[1];
const char *output = argv[2];
MPI_Init(&argc, &argv);
int nb_exp, largest_size;
experiment_t *experiments = parse_experiment_file(names, input, &nb_exp, &largest_size, -1, (int)1e9, 1);
FILE *result_file = open_file(output, "result");
my_recv_buffer = allocate_buffer(largest_size);
my_send_buffer = allocate_buffer(largest_size);
aux_buffer = allocate_buffer(largest_size);
#if REUSE_BUFFER
matrix_A = my_recv_buffer;
matrix_B = my_send_buffer;
matrix_C = aux_buffer;
#else
matrix_A = allocate_buffer(MIN_BUFF_SIZE);
matrix_B = allocate_buffer(MIN_BUFF_SIZE);
matrix_C = allocate_buffer(MIN_BUFF_SIZE);
#endif
MPI_Barrier(MPI_COMM_WORLD);
unsigned long long base_time=get_time();
for(int j = 0; j < nb_exp; j++) {
test_op(result_file, &experiments[j], NB_RUNS, base_time);
}
MPI_Finalize();
fflush(result_file);
fclose(result_file);
free(experiments);
free(my_recv_buffer);
free(my_send_buffer);
free(aux_buffer);
#if REUSE_BUFFER
#else
free(matrix_A);
free(matrix_B);
free(matrix_C);
#endif
return 0;
}
| {
"alphanum_fraction": 0.658698941,
"avg_line_length": 34.7894736842,
"ext": "c",
"hexsha": "f35ccbbf77dcadee4a30545fbf495eec29ce55e1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-07T15:52:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-07T15:52:04.000Z",
"max_forks_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Ezibenroc/platform-calibration",
"max_forks_repo_path": "src/calibration/test_ring.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T07:50:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-01-13T10:44:10.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Ezibenroc/platform-calibration",
"max_issues_repo_path": "src/calibration/test_ring.c",
"max_line_length": 119,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Ezibenroc/platform-calibration",
"max_stars_repo_path": "src/calibration/test_ring.c",
"max_stars_repo_stars_event_max_datetime": "2018-11-06T16:12:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-06T16:12:26.000Z",
"num_tokens": 1779,
"size": 6610
} |
/*
** Task-related edge density, main algorithm
**
** Ref: Lohmann et al (2016) PLoS One, 11(6):e0158185
**
** G.Lohmann, MPI-KYB, Jan 2015
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_sort_float.h>
#include "viaio/Vlib.h"
#include "viaio/VImage.h"
#include "viaio/mu.h"
#include "viaio/option.h"
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
#define SQR(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
extern VImage *VImagePointer(VAttrList list,int *nt);
extern void VReadImagePointer(VAttrList list,VImage *src);
extern VImage VoxelMap(VImage mask,size_t *nvoxels);
extern void VDataMatrix(VImage *src,int first,int len,VImage map,gsl_matrix_float *X);
extern void VCheckMatrix(gsl_matrix_float *X);
extern long VMaskCoverage(VAttrList list,VImage mask);
extern float ZMatrix(gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,
VImage roi,VImage map,VImage,int,float elength,float quantile,int,int);
extern void GetSNR(gsl_matrix_float **X1,gsl_matrix_float **X2,int *,int n,gsl_matrix_float *SNR,int);
extern void GetMedian(gsl_matrix_float **X1,gsl_matrix_float **X2,int *,int n,gsl_matrix_float *SNR,int);
extern void VPrintHistogram(gsl_histogram *histogram,int numperm,VString filename);
extern void HistoUpdate(float *A,size_t nvox,gsl_histogram *hist);
extern size_t EdgeDensity(float *C,int *I,int *J,size_t nedges,
gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,
VImage roi,VImage map,VImage,int,float,float,int,int,int,float,int);
extern size_t EstimateEdges(float *E,int *I,int *J,size_t fulldim,
gsl_histogram *TedHist,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,
VImage roi,VImage map,VImage mapimage,int adjdef,float elength,float zthreshold,float,int);
/* generate permutation table */
int genperm(gsl_rng *rx,int *table,int n,int numperm)
{
int s=0;
int ks = 0;
int kc=3;
if (numperm < 10) {
if (n%2==0) kc = n/2;
else kc = n/2-1;
}
int iter=0;
while ((ks < kc || ks > n-kc)) {
if (iter > 100) VError(" not possible to generate random permutations, perhaps not enough input data ?");
ks=0;
for (s=0; s<n; s++) {
table[s] = 0;
if (gsl_ran_bernoulli (rx,(double)0.5) == 1) {
table[s] = 1;
ks++;
}
}
iter++;
}
return ks;
}
void VReleaseStorage(VAttrList list)
{
VImage src;
VAttrListPosn posn;
for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
if(VGetAttrRepn(& posn) != VImageRepn) continue;
VGetAttrValue(& posn, NULL, VImageRepn, & src);
VDestroyImage(src);
src = NULL;
}
}
/* Check mask coverage */
VAttrList VCheckMaskCoverage(VStringConst *in_filenames,size_t n,VImage mask)
{
size_t i;
VAttrList list=NULL;
VAttrList geolist = NULL;
FILE *fp=NULL;
for (i=0; i<n; i++) {
fp = VOpenInputFile (in_filenames[i], TRUE);
list = VReadFile (fp, NULL);
if (! list) VError("Error reading image");
fclose(fp);
/* read geometry info, if unknown */
if (geolist == NULL) geolist = VGetGeoInfo(list);
long count = VMaskCoverage(list,mask);
if (count > 100) fprintf(stderr," incomplete mask_coverage %s: %ld\n",in_filenames[i],count);
VReleaseStorage(list);
list = NULL;
}
return geolist;
}
gsl_matrix_float **VReadImageData(VStringConst *in_filenames,VImage *src,VImage map,size_t n,size_t nvox,size_t first,size_t len)
{
size_t i;
VAttrList list=NULL;
FILE *fp=NULL;
/* allocate data struct */
gsl_matrix_float **X = VCalloc(n,sizeof(gsl_matrix_float));
for (i=0; i<n; i++) {
X[i] = gsl_matrix_float_calloc(nvox,len);
if (!X[i]) VError(" err allocating data matrix");
}
/* read data */
for (i=0; i<n; i++) {
fp = VOpenInputFile (in_filenames[i], TRUE);
list = VReadFile (fp, NULL);
if (! list) VError("Error reading image");
fclose(fp);
VReadImagePointer(list,src);
VDataMatrix(src,(int)first,(int)len,map,X[i]);
VCheckMatrix(X[i]);
VReleaseStorage(list);
list = NULL;
}
return X;
}
VDictEntry ADJDict[] = {
{ "6", 0 },
{ "18", 1 },
{ "26", 2 },
{ NULL }
};
VDictEntry TypeDict[] = {
{ "SNR", 0 },
{ "median", 1 },
{ NULL }
};
VDictEntry MetricDict[] = {
{ "pearson", 0 },
{ "spearman", 1 },
{ NULL }
};
int main (int argc,char *argv[])
{
static VArgVector in_files1;
static VArgVector in_files2;
static VString out_filename = "";
static VString mask_filename = "";
static VString roi_filename = "";
static VString hist_filename= "";
static VShort first = 0;
static VShort len = 0;
static VLong seed = 99402622;
static VFloat qthreshold = 0.99;
static VFloat elength = 5;
static VFloat noise_cutoff = 0.01;
static VShort adjdef = 2;
static VShort numperm = 0;
static VShort type = 0;
static VShort metric = 0;
static VShort nproc = 10;
static VShort step = 2;
static VOptionDescRec options[] = {
{"in1", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,"Input files 1" },
{"in2", VStringRepn, 0, & in_files2, VRequiredOpt, NULL,"Input files 2" },
{"out", VStringRepn, 1, & out_filename, VOptionalOpt, NULL,"Output file" },
{"mask", VStringRepn, 1, & mask_filename, VRequiredOpt, NULL,"Mask file" },
{"roi", VStringRepn, 1, & roi_filename, VOptionalOpt, NULL,"ROI file" },
{"histogram",VStringRepn,1,(VPointer) &hist_filename,VRequiredOpt,NULL,"Output histogram filename"},
{"permutations",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,"Number of permutations"},
{"qthreshold",VFloatRepn,1,(VPointer) &qthreshold,VOptionalOpt,NULL,"Initial quantile threshold"},
{"adj",VShortRepn,1,(VPointer) &adjdef,VOptionalOpt,ADJDict,"Definition of adjacency"},
{"seed",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,"Seed for random number generator"},
{"first",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,"First timepoint to use within trial"},
{"len",VShortRepn,1,(VPointer) &len,VOptionalOpt,NULL,"Number of timepoints to use, '0' to use all"},
{"type",VShortRepn,1,(VPointer) &type,VOptionalOpt,TypeDict,"Type of trial average"},
{"metric",VShortRepn,1,(VPointer) &metric,VOptionalOpt,MetricDict,"Correlation metric"},
{"edgelength",VFloatRepn,1,(VPointer) &elength,VOptionalOpt,NULL,"Minimal edge length in voxels"},
{"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"},
/* {"noisecutoff",VFloatRepn,1,(VPointer) &noise_cutoff,VOptionalOpt,NULL,"estimate of noisy edges"}, */
/* {"step",VShortRepn,1,(VPointer) &step,VOptionalOpt,NULL,"first iteration ZMatrix step size"} */
};
FILE *fp=NULL;
VAttrList list=NULL,list1=NULL,geolist=NULL;
VAttrListPosn posn;
VImage mask=NULL;
size_t nvox=0,i=0;
/* parse command line */
if (! VParseCommand (VNumber (options), options, & argc, argv)) {
VReportUsage (argv[0], VNumber (options), options, NULL);
exit (EXIT_FAILURE);
}
if (argc > 1) {
VReportBadArgs (argc, argv);
exit (EXIT_FAILURE);
}
/* whether to produce output file, or only compute histogram */
VBoolean histonly = FALSE;
if (strlen(out_filename) < 2) histonly = TRUE;
/* omp-stuff */
#ifdef _OPENMP
int num_procs=omp_get_num_procs();
int jprocs = num_procs;
if (nproc > 0 && nproc < num_procs) jprocs = nproc;
fprintf(stderr," using %d cores of %d\n",(int)jprocs,(int)num_procs);
omp_set_num_threads(jprocs);
#endif /* _OPENMP */
/* input filenames */
size_t n1 = (size_t)in_files1.number;
size_t n2 = (size_t)in_files2.number;
if (n1 != n2) VError(" n1 != n2, %d %d",n1,n2);
VStringConst *in_filenames1 = (VStringConst *) VCalloc(n1,sizeof(VStringConst));
for (i=0; i<n1; i++) {
in_filenames1[i] = ((VStringConst *) in_files1.vector)[i];
}
VStringConst *in_filenames2 = (VStringConst *) VCalloc(n2,sizeof(VStringConst));
for (i=0; i<n2; i++) {
in_filenames2[i] = ((VStringConst *) in_files2.vector)[i];
}
/* read mask */
fp = VOpenInputFile (mask_filename, TRUE);
list1 = VReadFile (fp, NULL);
if (! list1) VError("Error reading mask file");
fclose(fp);
for (VFirstAttr (list1, & posn); VAttrExists (& posn); VNextAttr (& posn)) {
if (VGetAttrRepn (& posn) != VImageRepn) continue;
VGetAttrValue (& posn, NULL,VImageRepn, & mask);
if (VPixelRepn(mask) == VFloatRepn || VPixelRepn(mask) == VDoubleRepn) {
mask = NULL;
continue;
}
}
if (mask == NULL) VError(" no mask found");
int nslices = VImageNBands(mask);
int nrows = VImageNRows(mask);
int ncols = VImageNColumns(mask);
/* read ROI */
VAttrList list2 = NULL;
VImage roi = NULL;
if (strlen(roi_filename) > 1) {
fp = VOpenInputFile (roi_filename, TRUE);
list2 = VReadFile (fp, NULL);
if (! list2) VError("Error reading roi file");
fclose(fp);
for (VFirstAttr (list2, & posn); VAttrExists (& posn); VNextAttr (& posn)) {
if (VGetAttrRepn (& posn) != VImageRepn) continue;
VGetAttrValue (& posn, NULL,VImageRepn, & roi);
if (VPixelRepn(roi) == VFloatRepn || VPixelRepn(roi) == VDoubleRepn) {
roi = NULL;
continue;
}
}
if (roi == NULL) VError(" no roi found");
}
/* Check mask coverage */
VAttrList geo=NULL;
geo = VCheckMaskCoverage(in_filenames1,n1,mask);
geo = VCheckMaskCoverage(in_filenames2,n2,mask);
if (geolist == NULL) geolist = geo;
/* voxel map */
VImage map = VoxelMap(mask,&nvox);
/* get image dimensions */
fp = VOpenInputFile (in_filenames1[0], TRUE);
list = VReadFile (fp, NULL);
if (! list) VError("Error reading image");
fclose(fp);
int nt=0;
VImage *src = VImagePointer(list,&nt);
if (first >= nt || first < 0) VError(" illegal value, first= %d, nt= %d",first,nt);
if (len <= 0) len = nt-first;
if (first + len >= nt) len = nt-first;
if (len < 2) VError(" len= %d",len);
fprintf(stderr," image: %d x %d x %d, nt: %d, nvox: %ld\n",(int)nslices,(int)nrows,(int)ncols,nt,nvox);
/* read image data */
gsl_matrix_float **X1 = VReadImageData(in_filenames1,src,map,n1,nvox,first,len);
gsl_matrix_float **X2 = VReadImageData(in_filenames2,src,map,n2,nvox,first,len);
/* voxel addresses */
VImage mapimage = VCreateImage(nslices,nrows,ncols,VIntegerRepn);
VFillImage(mapimage,VAllBands,(VInteger)(-1));
for (i=0; i<nvox; i++) {
int b = VPixel(map,0,0,i,VShort);
int r = VPixel(map,0,1,i,VShort);
int c = VPixel(map,0,2,i,VShort);
VPixel(mapimage,b,r,c,VInteger) = (VInteger)i;
}
/* tmp storage for SNR time courses */
int dim=0;
if (type < 3) dim = len;
else if (type == 3) dim = len*n1;
else VError(" illegal type %d",type);
gsl_matrix_float *SNR1 = gsl_matrix_float_calloc(nvox,dim);
gsl_matrix_float *SNR2 = gsl_matrix_float_calloc(nvox,dim);
/* ini zhist */
size_t hbins = 10000;
double hmin = 0.0,hmax = 1.001;
gsl_histogram *TedHist = gsl_histogram_alloc (hbins);
gsl_histogram_set_ranges_uniform (TedHist,hmin,hmax);
gsl_histogram_reset(TedHist);
/* fuer z-threshold */
size_t nbins = 25000;
hmin = -1.001,hmax = 1.001;
gsl_histogram *ZvalHist = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (ZvalHist,hmin,hmax);
gsl_histogram_reset(ZvalHist);
/* ini random */
size_t n = n1;
gsl_rng_env_setup();
const gsl_rng_type *T = gsl_rng_default;
gsl_rng *rx = gsl_rng_alloc(T);
gsl_rng_set(rx,(unsigned long int)seed);
int *table = (int *) VCalloc(n,sizeof(int));
for (i=0; i<n; i++) table[i] = 0;
/* allocate output structure */
size_t nedges=0;
size_t fulldim = (nvox*(nvox+1)/2);
double qx = 1.0-qthreshold;
qx += 0.001;
size_t nedges_estimated = (size_t) (qx*(double)fulldim);
/* ini matrices */
float *E=NULL; /* matrix of edge densities */
int *I=NULL; /* row indices in matrix E */
int *J=NULL; /* col indices in matrix E */
if (histonly == FALSE && noise_cutoff < 0.00001) {
E = VCalloc(nedges_estimated,sizeof(float)); /* matrix of edge densities */
I = VCalloc(nedges_estimated,sizeof(int)); /* row indices in matrix E */
J = VCalloc(nedges_estimated,sizeof(int)); /* col indices in matrix E */
}
/* main loop */
size_t s;
int ks=0,nperm=0;
int startperm=0;
if (numperm > 0) startperm = 1;
for (nperm = startperm; nperm <= numperm; nperm++) {
fprintf(stderr,"\n perm %3d: ",nperm);
if (nperm > 0) {
ks = genperm(rx,table,n,(int)numperm);
}
for (s=0; s<n; s++) {
fprintf(stderr,"%d",table[s]);
}
fprintf(stderr," %3d\n",ks);
/* get SNR data */
if (type == 0) {
GetSNR(X1,X2,table,n,SNR1,metric);
GetSNR(X2,X1,table,n,SNR2,metric);
}
if (type == 1) {
GetMedian(X1,X2,table,n,SNR1,metric);
GetMedian(X2,X1,table,n,SNR2,metric);
}
/* corr matrices */
float zthr = ZMatrix(ZvalHist,SNR1,SNR2,n1,n2,roi,map,mapimage,(int)adjdef,
(float)elength,(float)qthreshold,(int)step,(int)metric);
/* estimate number of truly needed edges, estimate noise */
if (noise_cutoff > 0.0 && nperm == numperm && histonly == FALSE) {
size_t old_estimate = nedges_estimated;
nedges_estimated = EstimateEdges(E,I,J,old_estimate,TedHist,SNR1,SNR2,n1,n2,roi,map,mapimage,
(int)adjdef,elength,zthr,noise_cutoff,(int)metric);
E = VCalloc(nedges_estimated,sizeof(float)); /* matrix of edge densities */
I = VCalloc(nedges_estimated,sizeof(int)); /* row indices in matrix E */
J = VCalloc(nedges_estimated,sizeof(int)); /* col indices in matrix E */
}
/* edge densities */
fprintf(stderr," Computing edge densities...\n");
nedges = EdgeDensity(E,I,J,nedges_estimated,TedHist,SNR1,SNR2,n1,n2,roi,map,mapimage,(int)adjdef,
elength,zthr,nperm,numperm,(int)1,noise_cutoff,(int)metric);
}
/* free storage */
for (i=0; i<n; i++) {
gsl_matrix_float_free(X1[i]);
gsl_matrix_float_free(X2[i]);
}
gsl_matrix_float_free(SNR1);
gsl_matrix_float_free(SNR2);
VFree(table);
/* print histogram */
VPrintHistogram(TedHist,(int)numperm,hist_filename);
if (histonly == TRUE) {
fprintf (stderr," %s: done.\n", argv[0]);
exit(0);
}
/* write edge density matrix in triplet sparse format */
size_t edim = nedges*3;
float filesize1 = (float)(edim*sizeof(float))/(1000.0*1000.0);
float filesize2 = (float)(edim*sizeof(float))/(1000.0*1000.0*1000.0);
fprintf(stderr," nedges= %ld, filesize= %.3f MByte (%.3f GByte)\n",nedges,filesize1,filesize2);
/* output */
VAttrList elist = VCreateAttrList();
VAttrList ilist = VCreateAttrList();
VAttrList jlist = VCreateAttrList();
VBundle edgedens = VCreateBundle ("data",elist,nedges*sizeof(float),(VPointer)E);
VBundle rowindex = VCreateBundle ("data",ilist,nedges*sizeof(int),(VPointer)I);
VBundle colindex = VCreateBundle ("data",jlist,nedges*sizeof(int),(VPointer)J);
VAttrList out_list = VCreateAttrList();
VSetGeoInfo(geolist,out_list);
VAppendAttr(out_list,"EdgeDensity",NULL,VBundleRepn,(VBundle)edgedens);
VAppendAttr(out_list,"RowIndex",NULL,VBundleRepn,(VBundle)rowindex);
VAppendAttr(out_list,"ColIndex",NULL,VBundleRepn,(VBundle)colindex);
VAppendAttr(out_list,"nedges",NULL,VLongRepn,(VLong)nedges);
VAppendAttr(out_list,"map",NULL,VImageRepn,map);
VAppendAttr(out_list,"qthreshold",NULL,VFloatRepn,(VFloat)qthreshold);
FILE *fp_out = VOpenOutputFile (out_filename, TRUE);
if (! VWriteFile (fp_out, out_list)) exit (1);
fclose(fp_out);
fprintf (stderr," %s: done.\n\n", argv[0]);
exit(0);
}
| {
"alphanum_fraction": 0.6619348383,
"avg_line_length": 31.540433925,
"ext": "c",
"hexsha": "17a444e5eabebf6914d269556bf3682eb2b8317d",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/ted/vted/vted.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/ted/vted/vted.c",
"max_line_length": 129,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/ted/vted/vted.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 5080,
"size": 15991
} |
#pragma once
#include <string>
#include <gsl/span>
namespace crypto {
/*
Use the Windows CNG API to compute a MD5 hash of the
provided data view and return it as a lowercase hex
string.
*/
std::string MD5AsString(gsl::span<uint8_t> data);
}
| {
"alphanum_fraction": 0.7047244094,
"avg_line_length": 15.875,
"ext": "h",
"hexsha": "9113310ed79d4bcc62f167a80174a9f497f9436f",
"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/include/infrastructure/crypto.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/include/infrastructure/crypto.h",
"max_line_length": 54,
"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/include/infrastructure/crypto.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": 69,
"size": 254
} |
// MIT License
//
// Copyright (c) 2021 Daniel Robertson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef HX711_DISCOVERY_H_82654AF1_3AA3_4885_9BE7_FA38117DE328
#define HX711_DISCOVERY_H_82654AF1_3AA3_4885_9BE7_FA38117DE328
#include "HX711.h"
#include <chrono>
#include <vector>
#include <pthread.h>
#include <sched.h>
#include <thread>
#include <algorithm>
#include <cmath>
#include <gsl/gsl_statistics.h>
namespace HX711 {
using namespace std::chrono;
struct TimingResult {
public:
Value v;
high_resolution_clock::time_point start;
high_resolution_clock::time_point waitStart;
high_resolution_clock::time_point waitEnd;
high_resolution_clock::time_point convertStart;
high_resolution_clock::time_point convertEnd;
high_resolution_clock::time_point end;
std::chrono::microseconds getWaitTime() const noexcept {
return std::chrono::duration_cast<std::chrono::microseconds>(
this->waitEnd - this->waitStart);
}
std::chrono::microseconds getConversionTime() const noexcept {
return std::chrono::duration_cast<std::chrono::microseconds>(
this->convertEnd - this->convertStart);
}
std::chrono::microseconds getTotalTime() const noexcept {
return std::chrono::duration_cast<std::chrono::microseconds>(
this->end - this->start);
}
};
class TimingCollection : public std::vector<TimingResult> {
public:
struct Stats {
double min;
double max;
double med;
double std;
bool inRange(const double n) const noexcept {
const double minDev = this->med - this->std;
const double maxDev = this->med + this->std;
return n >= minDev && n <= maxDev;
}
};
protected:
Stats _statsFromVector(std::vector<double>& vec) const noexcept {
Stats s;
std::sort(vec.begin(), vec.end());
s.min = gsl_stats_min(vec.data(), 1, vec.size());
s.max = gsl_stats_max(vec.data(), 1, vec.size());
s.med = gsl_stats_median_from_sorted_data(vec.data(), 1, vec.size());
//double work[vec.size()];
s.std = gsl_stats_sd(vec.data(), 1, vec.size());
return s;
}
public:
Stats getWaitTimeStats() const noexcept {
std::vector<double> vec;
vec.reserve(this->size());
for(auto it = this->cbegin(); it != this->cend(); ++it) {
vec.push_back(static_cast<double>(it->getWaitTime().count()));
}
return _statsFromVector(vec);
}
Stats getConversionTimeStats() const noexcept {
std::vector<double> vec;
vec.reserve(this->size());
for(auto it = this->cbegin(); it != this->cend(); ++it) {
vec.push_back(static_cast<double>(it->getConversionTime().count()));
}
return _statsFromVector(vec);
}
Stats getTotalTimeStats() const noexcept {
std::vector<double> vec;
vec.reserve(this->size());
for(auto it = this->cbegin(); it != this->cend(); ++it) {
vec.push_back(static_cast<double>(it->getTotalTime().count()));
}
return _statsFromVector(vec);
}
};
class Discovery : public HX711 {
public:
Discovery(const int dataPin, const int clockPin, const Rate rate) :
HX711(dataPin, clockPin, rate) {
this->connect();
}
TimingCollection getTimings(const std::size_t samples) {
using namespace std::chrono;
TimingCollection vec;
vec.reserve(samples);
for(size_t i = 0; i < samples; ++i) {
TimingResult tr;
tr.start = high_resolution_clock::now();
tr.waitStart = high_resolution_clock::now();
while(!this->isReady()) ;
tr.waitEnd = high_resolution_clock::now();
tr.convertStart = high_resolution_clock::now();
tr.v = this->readValue();
tr.convertEnd = high_resolution_clock::now();
tr.end = high_resolution_clock::now();
vec.push_back(tr);
}
return vec;
}
std::vector<std::chrono::nanoseconds> getTimeToReady(const std::size_t samples) {
using namespace std::chrono;
std::vector<nanoseconds> timings;
timings.reserve(samples);
//do an initial read
while(!this->isReady()) ;
this->readValue();
for(std::size_t i = 0; i < samples; ++i) {
high_resolution_clock::time_point start = high_resolution_clock::now();
while(!this->isReady()) ;
high_resolution_clock::time_point end = high_resolution_clock::now();
timings.push_back(end - start);
this->readValue();
}
return timings;
}
};
};
#endif | {
"alphanum_fraction": 0.6366139023,
"avg_line_length": 27.1588785047,
"ext": "h",
"hexsha": "ca2270970251a1fd5a1a66e7e3ef38df43a006a6",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-26T09:43:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-29T14:14:36.000Z",
"max_forks_repo_head_hexsha": "b1cb63a55b52b76e48a75648901d8954bd67a2f0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "endail/hx711",
"max_forks_repo_path": "include/Discovery.h",
"max_issues_count": 30,
"max_issues_repo_head_hexsha": "b1cb63a55b52b76e48a75648901d8954bd67a2f0",
"max_issues_repo_issues_event_max_datetime": "2022-02-07T04:49:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-04-19T04:20:22.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "endail/hx711",
"max_issues_repo_path": "include/Discovery.h",
"max_line_length": 85,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "b1cb63a55b52b76e48a75648901d8954bd67a2f0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "endail/hx711",
"max_stars_repo_path": "include/Discovery.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-17T19:14:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-03-01T20:05:09.000Z",
"num_tokens": 1315,
"size": 5812
} |
//This does CELL (~soma) stage of GRU (gated recurrent unit) model.
//This requires each neuron to have 3 input time series, X, Xr, Xz,
//where X is the usual input and Xr, Xz the inputs for the reset and update gates.
//X, Xr, Xz are the output of a separate linear IN stage (weights and baises).
//For dim=0, R[:,t] = sig{Xr[:,t] + Ur*Y[:,t-1]} \n";
// Z[:,t] = sig{Xz[:,t] + Uz*Y[:,t-1]} \n";
// H[:,t] = R[:,t].*Y[:,t-1] \n";
// Y[:,t] = Z[:,t].*Y[:,t-1] + (1-Z[:,t]).*tanh{X[:,t] + U*H[:,t]} \n";
//with sizes X, Xr, Xz: N x T \n";
// U, Ur, Uz: N x N \n";
// Y : N x T \n";
//
//For dim=1, R[t,:] = sig{Xr[t,:] + Y[t-1,:]*Ur} \n";
// Z[t,:] = sig{Xz[t,:] + Y[t-1,:]*Uz} \n";
// H[t,:] = R[t,:].*Y[t-1,:] \n";
// Y[t,:] = Z[t,:].*Y[t-1,:] + (1-Z[t,:]).*tanh{X[t,:] + H[t,:]*U} \n";
//with sizes X, Xr, Xz: T x N \n";
// U, Ur, Uz: N x N \n";
// Y : T x N \n";
//
//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),
//R is the reset gate, Z is the update gate, H is an intermediate (hidden) vector,
//U, Ur, Uz are NxN matrices, and Y is the output.
//Note that, the neurons of a layer are independent only if U, Ur, Uz are diagonal matrices.
//This is only really a CELL (~soma) stage in that case.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int gru3_s (float *Y, const float *X, const float *Xr, const float *Xz, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru3_d (double *Y, const double *X, const double *Xr, const double *Xz, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru3_inplace_s (float *X, const float *Xr, const float *Xz, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru3_inplace_d (double *X, const double *Xr, const double *Xz, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru3_s (float *Y, const float *X, const float *Xr, const float *Xz, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
size_t nT, tN;
float *R, *Z, *H;
if (!(R=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru3_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(Z=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru3_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru3_s: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
//R[0] = 1.0f / (1.0f+expf(-Xr[0]));
Z[0] = 1.0f / (1.0f+expf(-Xz[0]));
Y[0] = (1.0f-Z[0]) * tanhf(X[0]);
for (size_t t=1; t<T; ++t)
{
//R[0] = 1.0f / (1.0f+expf(-Xr[t]-Ur[0]*Y[t-1]));
Z[0] = 1.0f / (1.0f+expf(-Xz[t]-Uz[0]*Y[t-1]));
//H[0] = R[0] * Y[t-1];
H[0] = Y[t-1] / (1.0f+expf(-Xr[t]-Ur[0]*Y[t-1]));
Y[t] = Z[0]*Y[t-1] + (1.0f-Z[0])*tanhf(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
//R[n] = 1.0f / (1.0f+expf(-Xr[n]));
Z[n] = 1.0f / (1.0f+expf(-Xz[n]));
Y[n] = (1.0f-Z[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xr[tN],1,R,1); cblas_scopy((int)N,&Xz[tN],1,Z,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
//R[n] = 1.0f / (1.0f+expf(-R[n]));
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
//H[n] = R[n] * Y[tN-N+n];
H[n] = Y[tN-N+n] / (1.0f+expf(-R[n]));
}
cblas_scopy((int)N,&X[tN],1,&Y[tN],1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0f-Z[n])*tanhf(Y[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
//R[n] = 1.0f / (1.0f+expf(-Xr[nT]));
Z[n] = 1.0f / (1.0f+expf(-Xz[nT]));
Y[nT] = (1.0f-Z[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xr[t],(int)T,R,1); cblas_scopy((int)N,&Xz[t],(int)T,Z,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
//R[n] = 1.0f / (1.0f+expf(-R[n]));
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
//H[n] = R[n] * Y[t-1+n*T];
H[n] = Y[t-1+n*T] / (1.0f+expf(-R[n]));
}
cblas_scopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0f-Z[n])*tanhf(Y[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Z[n] = 1.0f / (1.0f+expf(-Xz[nT]));
Y[nT] = (1.0f-Z[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xr[t],(int)T,R,1); cblas_scopy((int)N,&Xz[t],(int)T,Z,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
H[n] = Y[t-1+n*T] / (1.0f+expf(-R[n]));
}
cblas_scopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0f-Z[n])*tanhf(Y[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0f / (1.0f+expf(-Xz[n]));
Y[n] = (1.0f-Z[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xr[tN],1,R,1); cblas_scopy((int)N,&Xz[tN],1,Z,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
H[n] = Y[tN-N+n] / (1.0f+expf(-R[n]));
}
cblas_scopy((int)N,&X[tN],1,&Y[tN],1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0f-Z[n])*tanhf(Y[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru3_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int gru3_d (double *Y, const double *X, const double *Xr, const double *Xz, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
size_t nT, tN;
double *R, *Z, *H;
if (!(R=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru3_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(Z=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru3_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru3_d: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
Z[0] = 1.0 / (1.0+exp(-Xz[0]));
Y[0] = (1.0-Z[0]) * tanh(X[0]);
for (size_t t=1; t<T; ++t)
{
Z[0] = 1.0 / (1.0+exp(-Xz[t]-Uz[0]*Y[t-1]));
H[0] = Y[t-1] / (1.0+exp(-Xr[t]-Ur[0]*Y[t-1]));
Y[t] = Z[0]*Y[t-1] + (1.0-Z[0])*tanh(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Xz[n]));
Y[n] = (1.0-Z[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xr[tN],1,R,1); cblas_dcopy((int)N,&Xz[tN],1,Z,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = Y[tN-N+n] / (1.0+exp(-R[n]));
}
cblas_dcopy((int)N,&X[tN],1,&Y[tN],1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0-Z[n])*tanh(Y[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Z[n] = 1.0 / (1.0+exp(-Xz[nT]));
Y[nT] = (1.0-Z[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xr[t],(int)T,R,1); cblas_dcopy((int)N,&Xz[t],(int)T,Z,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = Y[t-1+n*T] / (1.0+exp(-R[n]));
}
cblas_dcopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0-Z[n])*tanh(Y[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Z[n] = 1.0 / (1.0+exp(-Xz[nT]));
Y[nT] = (1.0-Z[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xr[t],(int)T,R,1); cblas_dcopy((int)N,&Xz[t],(int)T,Z,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[t-1],(int)T,o,R,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = Y[t-1+n*T] / (1.0+exp(-R[n]));
}
cblas_dcopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = Z[n]*Y[t-1+nT] + (1.0-Z[n])*tanh(Y[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Xz[n]));
Y[n] = (1.0-Z[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xr[tN],1,R,1); cblas_dcopy((int)N,&Xz[tN],1,Z,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&Y[tN-N],1,o,R,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&Y[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = Y[tN-N+n] / (1.0+exp(-R[n]));
}
cblas_dcopy((int)N,&X[tN],1,&Y[tN],1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = Z[n]*Y[tN-N+n] + (1.0-Z[n])*tanh(Y[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru3_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int gru3_inplace_s (float *X, const float *Xr, const float *Xz, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
size_t nT, tN;
float *R, *Z, *H;
if (!(R=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru3_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(Z=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru3_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru3_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
//R[0] = 1.0f / (1.0f+expf(-Xr[0]));
Z[0] = 1.0f / (1.0f+expf(-Xz[0]));
X[0] = (1.0f-Z[0]) * tanhf(X[0]);
for (size_t t=1; t<T; ++t)
{
//R[0] = 1.0f / (1.0f+expf(-Xr[t]-Ur[0]*X[t-1]));
Z[0] = 1.0f / (1.0f+expf(-Xz[t]-Uz[0]*X[t-1]));
//H[0] = R[0] * X[t-1];
H[0] = X[t-1] / (1.0f+expf(-Xr[t]-Ur[0]*X[t-1]));
X[t] = Z[0]*X[t-1] + (1.0f-Z[0])*tanhf(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
//R[n] = 1.0f / (1.0f+expf(-Xr[n]));
Z[n] = 1.0f / (1.0f+expf(-Xz[n]));
X[n] = (1.0f-Z[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xr[tN],1,R,1); cblas_scopy((int)N,&Xz[tN],1,Z,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN-N],1,o,R,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
//R[n] = 1.0f / (1.0f+expf(-R[n]));
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
//H[n] = R[n] * X[tN-N+n];
H[n] = X[tN-N+n] / (1.0f+expf(-R[n]));
}
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = Z[n]*X[tN-N+n] + (1.0f-Z[n])*tanhf(X[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Z[n] = 1.0f / (1.0f+expf(-Xz[nT]));
X[nT] = (1.0f-Z[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xr[t],(int)T,R,1); cblas_scopy((int)N,&Xz[t],(int)T,Z,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
H[n] = X[t-1+n*T] / (1.0f+expf(-R[n]));
}
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = Z[n]*X[t-1+nT] + (1.0f-Z[n])*tanhf(X[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Z[n] = 1.0f / (1.0f+expf(-Xz[nT]));
X[nT] = (1.0f-Z[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xr[t],(int)T,R,1); cblas_scopy((int)N,&Xz[t],(int)T,Z,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
H[n] = X[t-1+n*T] / (1.0f+expf(-R[n]));
}
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = Z[n]*X[t-1+nT] + (1.0f-Z[n])*tanhf(X[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0f / (1.0f+expf(-Xz[n]));
X[n] = (1.0f-Z[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xr[tN],1,R,1); cblas_scopy((int)N,&Xz[tN],1,Z,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN-N],1,o,R,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0f / (1.0f+expf(-Z[n]));
H[n] = X[tN-N+n] / (1.0f+expf(-R[n]));
}
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = Z[n]*X[tN-N+n] + (1.0f-Z[n])*tanhf(X[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru3_inplace_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int gru3_inplace_d (double *X, const double *Xr, const double *Xz, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
size_t nT, tN;
double *R, *Z, *H;
if (!(R=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru3_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(Z=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru3_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru3_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
Z[0] = 1.0 / (1.0+exp(-Xz[0]));
X[0] = (1.0-Z[0]) * tanh(X[0]);
for (size_t t=1; t<T; ++t)
{
Z[0] = 1.0 / (1.0+exp(-Xz[t]-Uz[0]*X[t-1]));
H[0] = X[t-1] / (1.0+exp(-Xr[t]-Ur[0]*X[t-1]));
X[t] = Z[0]*X[t-1] + (1.0-Z[0])*tanh(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Xz[n]));
X[n] = (1.0-Z[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xr[tN],1,R,1); cblas_dcopy((int)N,&Xz[tN],1,Z,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN-N],1,o,R,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = X[tN-N+n] / (1.0+exp(-R[n]));
}
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = Z[n]*X[tN-N+n] + (1.0-Z[n])*tanh(X[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Z[n] = 1.0 / (1.0+exp(-Xz[nT]));
X[nT] = (1.0-Z[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xr[t],(int)T,R,1); cblas_dcopy((int)N,&Xz[t],(int)T,Z,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = X[t-1+n*T] / (1.0+exp(-R[n]));
}
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = Z[n]*X[t-1+nT] + (1.0-Z[n])*tanh(X[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Z[n] = 1.0 / (1.0+exp(-Xz[nT]));
X[nT] = (1.0-Z[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xr[t],(int)T,R,1); cblas_dcopy((int)N,&Xz[t],(int)T,Z,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,R,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[t-1],(int)T,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = X[t-1+n*T] / (1.0+exp(-R[n]));
}
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = Z[n]*X[t-1+nT] + (1.0-Z[n])*tanh(X[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Xz[n]));
X[n] = (1.0-Z[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xr[tN],1,R,1); cblas_dcopy((int)N,&Xz[tN],1,Z,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ur,(int)N,&X[tN-N],1,o,R,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uz,(int)N,&X[tN-N],1,o,Z,1);
for (size_t n=0u; n<N; ++n)
{
Z[n] = 1.0 / (1.0+exp(-Z[n]));
H[n] = X[tN-N+n] / (1.0+exp(-R[n]));
}
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = Z[n]*X[tN-N+n] + (1.0-Z[n])*tanh(X[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru3_inplace_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4085361021,
"avg_line_length": 40.3099041534,
"ext": "c",
"hexsha": "3f291295968a9b13f3ed40db99f88e61cea9f85b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/nn",
"max_forks_repo_path": "c/gru3.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/nn",
"max_issues_repo_path": "c/gru3.c",
"max_line_length": 202,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/nn",
"max_stars_repo_path": "c/gru3.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z",
"num_tokens": 9296,
"size": 25234
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <float.h>
#include <math.h>
#include "sacio.h"
#include "parmt_utils.h"
#ifdef PARMT_USE_INTEL
#include <mkl.h>
#include <mkl_lapacke.h>
#include <mkl_cblas.h>
#else
#include <lapacke.h>
#include <cblas.h>
#endif
#include "parmt_mtsearch.h"
#include "iscl/array/array.h"
#include "iscl/memory/memory.h"
#include "iscl/random/random.h"
#include "iscl/signal/convolve.h"
#include "iscl/time/time.h"
int testBlockSize(void);
int main()
{
char *ffList[10] = {"rotation_data/B00103ZDS.sac\0",
"rotation_data/B00106ZSS.sac\0",
"rotation_data/B00101ZDD.sac\0",
"rotation_data/B00109ZEX.sac\0",
"rotation_data/B00104RDS.sac\0",
"rotation_data/B00107RSS.sac\0",
"rotation_data/B00102RDD.sac\0",
"rotation_data/B00110REX.sac\0",
"rotation_data/B00105TDS.sac\0",
"rotation_data/B00108TSS.sac\0"};
struct parmtNoiseBasis_struct basis;
struct sacData_struct sacZDS, sacZSS, sacZDD, sacZEX,
sacRDS, sacRSS, sacRDD, sacREX,
sacTDS, sacTSS, sac;
double *CeInv, *CeInvDiag, *d, *dn, *G, *R, *X,
*mts, *betas, *gammas, *kappas, *M0s,
*phi, *sigmas, *thetas, *xrand, *var, *eye;
double baz, betaMax, betaMin, gammaMax, gammaMin, kappaMin, kappaMax,
m0Min, m0Max, sigmaMax, sigmaMin, thetaMax, thetaMin;
double cmpaz, cmpinc, sigma, xnorm;
int *lags, i, icomp, ierr, imt, imtopt, j, ldc, ldz, ng, nb, nk,
nlags, ns, nt, nm, nmt, npgrns, npts, rank;
bool lrescale = false;
const double oneDeg = M_PI/180.0; // one degree for padding
const double az = 25.0;
const int ldm = 8;
const int blockSize = 32;
iscl_init();
// Discretize the moment tensor space
ng = 11; // longitudes
nb = 11; // colatitudes
nk = 11; // strike angles
ns = 11; // rake
nt = 11; // dip
nm = 4; // magnitudes
betaMin = 0.0 + oneDeg;
betaMax = M_PI - oneDeg;
gammaMin =-M_PI/6.0 + oneDeg;
gammaMax = M_PI/6.0 - oneDeg;
kappaMin = 0.0 + oneDeg;
kappaMax = 2.0*M_PI - oneDeg;
thetaMin = 0.0 + oneDeg;
thetaMax = 0.5*M_PI - oneDeg;
sigmaMin =-0.5*M_PI + oneDeg;
sigmaMax = 0.5*M_PI - oneDeg;
m0Min = 1.0/sqrt(2.0);
m0Max = 2.0/sqrt(2.0);
//m0Max = 1.e8/sqrt(2.0) + (double) (nm - 1)*1.e8/sqrt(2.0);
//omp_set_num_threads(nthreads);
mkl_set_num_threads(1);
// Discretize the MT space
M0s = array_linspace64f(m0Min, m0Max, nm, &ierr);
betas = array_linspace64f(betaMin, betaMax, nb, &ierr);
gammas = array_linspace64f(gammaMin, gammaMax, ng, &ierr);
kappas = array_linspace64f(kappaMin, kappaMax, nk, &ierr);
thetas = array_linspace64f(thetaMin, thetaMax, nt, &ierr);
sigmas = array_linspace64f(sigmaMin, sigmaMax, ns, &ierr);
nmt = ng*nb*nk*ns*nt*nm;
mts = memory_calloc64f(nmt*ldm);
ierr = parmt_discretizeMT64f(ng, gammas,
nb, betas,
nm, M0s,
nk, kappas,
nt, thetas,
ns, sigmas,
ldm, nmt, mts);
if (ierr != 0)
{
printf("Failed to discretize MTs\n");
return EXIT_FAILURE;
}
memory_free64f(&M0s);
memory_free64f(&betas);
memory_free64f(&gammas);
memory_free64f(&kappas);
memory_free64f(&thetas);
memory_free64f(&sigmas);
// Read the green's functions generated by CPS
memset(&sacZDS, 0, sizeof(struct sacData_struct));
memset(&sacZSS, 0, sizeof(struct sacData_struct));
memset(&sacZDD, 0, sizeof(struct sacData_struct));
memset(&sacZEX, 0, sizeof(struct sacData_struct));
memset(&sacRDS, 0, sizeof(struct sacData_struct));
memset(&sacRSS, 0, sizeof(struct sacData_struct));
memset(&sacRDD, 0, sizeof(struct sacData_struct));
memset(&sacREX, 0, sizeof(struct sacData_struct));
memset(&sacTDS, 0, sizeof(struct sacData_struct));
memset(&sacTSS, 0, sizeof(struct sacData_struct));
ierr = sacio_readTimeSeriesFile(ffList[0], &sacZDS);
ierr += sacio_readTimeSeriesFile(ffList[1], &sacZSS);
ierr += sacio_readTimeSeriesFile(ffList[2], &sacZDD);
ierr += sacio_readTimeSeriesFile(ffList[3], &sacZEX);
ierr += sacio_readTimeSeriesFile(ffList[4], &sacRDS);
ierr += sacio_readTimeSeriesFile(ffList[5], &sacRSS);
ierr += sacio_readTimeSeriesFile(ffList[6], &sacRDD);
ierr += sacio_readTimeSeriesFile(ffList[7], &sacREX);
ierr += sacio_readTimeSeriesFile(ffList[8], &sacTDS);
ierr += sacio_readTimeSeriesFile(ffList[9], &sacTSS);
if (ierr != 0)
{
printf("Failed to load fundmaental faults\n");
return EXIT_FAILURE;
}
// Set the green's functions
npgrns = MIN(64, sacZDS.npts);
npts = npgrns;
icomp = 1; // vertical
cmpaz = 0.0; // channel azimuth
cmpinc =-90.0; // channel orientation (-90+ up 0 is horizontal)
G = memory_calloc64f(6*npgrns);
printf("Setting Green's functions...\n");
baz = fmod(az + 180, 360.0);
ierr = parmt_utils_ff2mtGreens64f(npgrns, icomp,
az, baz,
cmpaz, cmpinc,
sacZDS.data, sacZSS.data,
sacZDD.data, sacZEX.data,
sacRDS.data, sacRSS.data,
sacRDD.data, sacREX.data,
sacTDS.data, sacTSS.data,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns]);
if (ierr != 0)
{
printf("Failed to set Green's functions\n");
return EXIT_FAILURE;
}
// Free intermediate memory
sacio_free(&sacZDS);
sacio_free(&sacZSS);
sacio_free(&sacZDD);
sacio_free(&sacZEX);
sacio_free(&sacRDS);
sacio_free(&sacRSS);
sacio_free(&sacRDD);
sacio_free(&sacREX);
sacio_free(&sacTDS);
sacio_free(&sacTSS);
// make a noise matrix
ldc = npts;
CeInv = memory_calloc64f(npts*ldc);
R = memory_calloc64f(npts*ldc);
X = memory_calloc64f((2*npts-1)*ldc);
//xrand = random_randn64f(npts, 0.0, 0.01, &ierr);
xrand = random_rand64f(npts, &ierr);
xrand[0] = 0.0;
xrand[npts-1] = 0.0;
xnorm = cblas_dnrm2(npts, xrand, 1);
cblas_dscal(npts, 1.0/xnorm, xrand, 1);
ierr = convolve_corrmtx64f_work(npts, xrand,
npts-1, ldc, X,
CORRMTX_AUTOCORRELATION,
true, ldc, R);
FILE *fmat = fopen("xcmat.txt", "w");
for (i=0; i<npts; i++)
{
for (j=0; j<npts; j++)
{
fprintf(fmat, "%d %d %e\n", i+1, npts-j, R[i*ldc+j]);
}
fprintf(fmat,"\n");
}
fclose(fmat);
memory_free64f(&X);
cblas_dcopy(npts*ldc, R, 1, CeInv, 1);
// Make a noise basis
ierr = parmt_utils_getNoiseBasisFromCtC64f(npts, ldc, R, &basis);
if (ierr != 0)
{
printf("Failed to compute eigenbasis\n");
return EXIT_FAILURE;
}
// Compute inverse of R
ierr = LAPACKE_dpotrf(LAPACK_ROW_MAJOR, 'U', npts, CeInv, ldc);
if (ierr != 0)
{
printf("Failed to compute chol(CeInv)\n");
return EXIT_FAILURE;
}
ierr = LAPACKE_dpotri(LAPACK_ROW_MAJOR, 'U', npts, CeInv, ldc);
if (ierr != 0)
{
printf("Failed to compute CeInv %d\n", ierr);
return EXIT_FAILURE;
}
// The KL basis uses sqrt(eig) but for consistency with inv(Ce) need
// just the regular old eigenvalues
for (i=0; i<basis.nvals; i++)
{
basis.sqrtEvals[i] = pow(basis.sqrtEvals[i], 2);
}
// Copy upper to lower
for (i=0; i<npts; i++)
{
for (j=0; j<i; j++)
{
CeInv[i*ldc+j] = CeInv[j*ldc+i];
}
}
CeInvDiag = memory_calloc64f(npts);
for (i=0; i<npts; i++){CeInvDiag[i] = CeInv[ldc*i+i];}
// Make a synthetic
imtopt = MIN(nmt-1, MAX(0, (3*nmt)/8));
d = memory_calloc64f(npts);
cblas_dgemv(CblasColMajor, CblasNoTrans,
npgrns, 6, 1.0, G, npgrns,
&mts[ldm*imtopt], 1, 0.0, d, 1);
// make a noisy synthetic so Ei doesn't blow up
double relError = 0.2;
rank = parmt_utils_getEffectiveRank(relError, basis);
printf("%d\n", rank);
// rank = basis.npts/4;
//printf("%d\n", rank);
//getchar();
printf("Effective rank used: %d\n", rank);
sigma = 1.0;
double snr = 15.0;
dn = memory_calloc64f(npts);
parmt_utils_makeKLNoise(rank, npts, basis, dn);
double xsum = array_sum64f(npts, dn, &ierr);
for (i=0; i<npts; i++){dn[i] = dn[i] - xsum/(double) npts;}
double signalEnergy = cblas_dnrm2(npts, d, 1); // signal variance
double noiseEnergy = cblas_dnrm2(npts, dn, 1); // noise variance
printf("%f %f\n", signalEnergy, noiseEnergy);
double xvar = 0.0;
double xfact = (1.0/noiseEnergy)*signalEnergy/pow(10.0, 0.05*snr);
for (i=0; i<npts; i++)
{
dn[i] = xfact*dn[i] + d[i];
}
sigma = 0.0;
for (i=0; i<npts; i++)
{
sigma = sigma + pow(dn[i] - d[i], 2); // noise variance
}
sigma = sqrt(sigma);
//sigma = pow(cblas_dnrm2(npts, dn, 1), 2);
printf("variance: %f\n", sigma);
//sigma = 0.002;
printf("%e %e %e %e\n", xfact, sigma, d[14], dn[14]);
//------------------------------------------------------------------------//
// unlagged conventional //
//------------------------------------------------------------------------//
// run the inversion for a diagonal matrix
phi = memory_calloc64f(nmt);
time_tic();
nlags = 0;
ierr = parmt_mtSearch64f(ldm, nlags, nmt,
npts, ldc,
true,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
CeInvDiag, mts, d, phi);
if (ierr != 0)
{
printf("Failed calling mtSearch64f 1\n");
return EXIT_FAILURE;
}
imt = array_argmin64f(nmt, phi, &ierr);
if (imt != imtopt)
{
printf("Failed to recover optimal index in test 1\n");
return EXIT_FAILURE;
}
printf("Unlagged diagonal matrix time: %f (s)\n", time_toc());
time_tic();
printf("est + true optimal indices: %d %d %e\n", imt, imtopt, phi[imt]);
ierr = parmt_mtSearch64f(ldm, nlags, nmt,
npts, ldc,
false,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
CeInv, mts, dn, phi);
if (ierr != 0)
{
printf("Failed calling mtSearch64f 2\n");
return EXIT_FAILURE;
}
imt = array_argmin64f(nmt, phi, &ierr);
if (imt != imtopt)
{
printf("Failed to recover optimal index in test 2 %d %d\n", imt, imtopt);
//return EXIT_FAILURE;
}
imt = array_argmin64f(nmt, phi, &ierr);
printf("est + true optimal indices: %d %d %e\n", imt, imtopt, phi[imt]);
printf("Unlagged time: %f (s)\n", time_toc());
lags = memory_calloc32i(nmt);
var = memory_calloc64f(npts);
nlags = 0;
eye = array_set64f(npts, 1.0, &ierr);
time_tic();
ierr = parmt_mtSearchL164f(ldm, nmt, npts, blockSize,
nlags, false,
lrescale,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
eye, mts, d, phi, var, lags);
imt = array_argmax64f(nmt, phi, &ierr);
printf("L1 est + true optimal indices: %d %d %e %e\n",
imt, imtopt, phi[imt], phi[imtopt]);
printf("Unlagged general matrix time: %f (s)\n", time_toc());
nlags = 4;
omp_set_num_threads(1);
ierr = parmt_mtSearchL164f(ldm, nmt, npts, blockSize,
nlags, true,
lrescale,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
eye, mts, d, phi, var, lags);
imt = array_argmax64f(nmt, phi, &ierr);
printf("L1 lagged est + true optimal indices: %d %d %d %e %e\n",
imt, imtopt, lags[imt], phi[imt], phi[imtopt]);
printf("Lagged time: %f (s)\n", time_toc());
time_tic();
ierr = parmt_mtSearchL164f(ldm, nmt, npts, blockSize,
nlags, true,
true, //lrescale,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
eye, mts, d, phi, var, lags);
int imtNew = array_argmax64f(nmt, phi, &ierr);
if (imtNew != imt)
{
if (fabs(phi[imtNew] - phi[imt]) > 1.e-14)
{
printf("Failed to locate lrescaled script %e\n",
fabs(phi[imtNew] - phi[imt]));
return EXIT_FAILURE;
}
}
printf("L1 rescaled lagged est + true optimal indices: %d %d %d %e %e\n",
imt, imtopt, lags[imt], phi[imt], phi[imtopt]);
printf("Rescaled lagged time: %f (s)\n", time_toc());
// repeat with lags
ierr = testBlockSize();
/*
nlags = 10;
eye = array_set64f(npts, 1.0, &ierr);
ierr = parmt_mtSearchL164f(ldm, nmt, npts, blockSize,
nlags, true,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
eye, mts, d, phi, var, lags);
imt = array_argmax64f(nmt, phi, &ierr);
printf("L1 est + true optimal indices: %d %d %e %d\n", imt, imtopt, phi[imt], lags[imt]);
printf("Unlagged general matrix time: %f (s)\n", time_toc());
*/
/*
//------------------------------------------------------------------------//
// unlagged kl //
//------------------------------------------------------------------------//
time_tic();
ldz = basis.lde;
ierr = parmt_mtSearchKL64f(nlags, nmt,
npts, ldz,
rank,
sigma,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
basis.sqrtEvals,
basis.evects,
mts, dn, phi);
if (ierr != 0)
{
printf("Failed calling mtSearchKL64f unlagged\n");
return EXIT_FAILURE;
}
imt = array_argmax64f(nmt, phi, &ierr);
*/
/*
if (imt != imtopt)
{
printf("Failed to locate unlagged kl optimum\n");
return EXIT_FAILURE;
}
*/
/*
printf("est + true optimal indices: %d %d %e %e %e\n", imt, imtopt,
phi[imt], phi[imtopt], phi[array_argmin64f(nmt, phi)]);
printf("%e\n", array_sum64f(nmt, phi, &ierr));
printf("Unlagged general kl time %f (s)\n", time_toc());
*/
//TEST:;
/*
double *est = memory_calloc64f(npts);
cblas_dgemv(CblasColMajor, CblasNoTrans,
npgrns, 6, 1.0, G, npgrns,
&mts[ldm*imt], 1, 0.0, est, 1);
FILE *fn = fopen("noise.txt","w");
for (i=0; i<npts; i++)
{
fprintf(fn, "%d %e %e %e %e\n", i, d[i], dn[i], est[i], d[i] - dn[i]);
}
fclose(fn);
*/
// Free memory
parmt_utils_freeNoiseBasis(&basis);
memory_free64f(&G);
memory_free64f(&CeInv);
memory_free64f(&CeInvDiag);
memory_free64f(&mts);
memory_free64f(&d);
memory_free64f(&phi);
memory_free64f(&var);
memory_free64f(&eye);
iscl_finalize();
return EXIT_SUCCESS;
}
//============================================================================//
int testPolarityMTSearch(void)
{
const char *fcnm = "testPolarityMTSearch\0";
const int blockSizes[4] = {1, 2, 32, 64};
int ierr, nb, ng, nk, nm, ns, nt;
double *betas, *gammas, *kappas, *mts, *M0s, *thetas, *sigmas;
double betaMin, betaMax, gammaMin, gammaMax, kappaMin, kappaMax,
m0Min, m0Max, sigmaMin, sigmaMax, thetaMin, thetaMax;
const double oneDeg = M_PI/180.0; // one degree for padding
// Discretize the moment tensor space
ng = 5; // longitudes
nb = 6; // colatitudes
nk = 7; // strike angles
ns = 8; // rake
nt = 9; // dip
nm = 1; // magnitudes
betaMin = 0.0 + oneDeg;
betaMax = M_PI - oneDeg;
gammaMin =-M_PI/6.0 + oneDeg;
gammaMax = M_PI/6.0 - oneDeg;
kappaMin = 0.0 + oneDeg;
kappaMax = 2.0*M_PI - oneDeg;
thetaMin = 0.0 + oneDeg;
thetaMax = 0.5*M_PI - oneDeg;
sigmaMin =-0.5*M_PI + oneDeg;
sigmaMax = 0.5*M_PI - oneDeg;
m0Min = 1.0/sqrt(2.0);
m0Max = 2.0/sqrt(2.0);
ierr = parmt_discretizeCells64f(nb, betaMin, betaMax,
ng, gammaMin, gammaMax,
nk, kappaMin, kappaMax,
ns, sigmaMin, sigmaMax,
nt, thetaMin, thetaMax,
nm, m0Min, m0Max, false,
&betas, &gammas, &kappas,
&sigmas, &thetas, &M0s);
if (ierr != 0)
{
printf("%s: Error making cell discretization\n", fcnm);
return EXIT_FAILURE;
}
memory_free64f(&betas);
memory_free64f(&gammas);
memory_free64f(&kappas);
memory_free64f(&sigmas);
memory_free64f(&thetas);
memory_free64f(&M0s);
// Investigate different block sizes
return EXIT_SUCCESS;
}
//============================================================================//
/*!
* @brief Tests the effect of blocksize in gemm on performance
*/
int testBlockSize(void)
{
const char *fcnm = "testBlockSize\0";
FILE *fout;
char fname[PATH_MAX];
double *G, *d, *eye, *phi, *phiOri, *var, time, dnorm, xmin;
int *lags = NULL;
int i, ierr, imt, nmt, nt0, npmax, npts, npgrns, pSize;
const int nblocks = 10;
const int nps = 6;
int pSizes[6] = {32, 64, 128, 256, 512, 1024};
int blockSizes[10] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
const int nlags = 0;
const int ldm = 6;
const bool lwantLags = false;
int imtopt, ng, nb, nk, ns, nt, nm;
const bool lrescale = false;
double *betas, *gammas, *kappas, *mts, *M0s, *thetas, *sigmas;
double betaMin, betaMax, gammaMin, gammaMax, kappaMin, kappaMax,
m0Min, m0Max, sigmaMin, sigmaMax, thetaMin, thetaMax;
const double oneDeg = M_PI/180.0; // one degree for padding
// disretize the moment tensor
// Discretize the moment tensor space
ng = 5; // longitudes
nb = 5; // colatitudes
nk = 7; // strike angles
ns = 7; // rake
nt = 7; // dip
nm = 1; // magnitudes
betaMin = 0.0 + oneDeg;
betaMax = M_PI - oneDeg;
gammaMin =-M_PI/6.0 + oneDeg;
gammaMax = M_PI/6.0 - oneDeg;
kappaMin = 0.0 + oneDeg;
kappaMax = 2.0*M_PI - oneDeg;
thetaMin = 0.0 + oneDeg;
thetaMax = 0.5*M_PI - oneDeg;
sigmaMin =-0.5*M_PI + oneDeg;
sigmaMax = 0.5*M_PI - oneDeg;
m0Min = 1.0/sqrt(2.0);
m0Max = 2.0/sqrt(2.0);
// Discretize the MT space
M0s = array_linspace64f(m0Min, m0Max, nm, &ierr);
betas = array_linspace64f(betaMin, betaMax, nb, &ierr);
gammas = array_linspace64f(gammaMin, gammaMax, ng, &ierr);
kappas = array_linspace64f(kappaMin, kappaMax, nk, &ierr);
thetas = array_linspace64f(thetaMin, thetaMax, nt, &ierr);
sigmas = array_linspace64f(sigmaMin, sigmaMax, ns, &ierr);
nmt = ng*nb*nk*ns*nt*nm;
imtopt = nmt/2;
mts = memory_calloc64f(nmt*ldm);
ierr = parmt_discretizeMT64f(ng, gammas,
nb, betas,
nm, M0s,
nk, kappas,
nt, thetas,
ns, sigmas,
ldm, nmt, mts);
if (ierr != 0)
{
printf("Failed to discretize MTs\n");
return EXIT_FAILURE;
}
memory_free64f(&M0s);
memory_free64f(&betas);
memory_free64f(&gammas);
memory_free64f(&kappas);
memory_free64f(&thetas);
memory_free64f(&sigmas);
// make some random data for testing
npmax = array_max32i(nps, pSizes, &ierr);
G = random_rand64f(6*npmax, &ierr);
// set space
phiOri = memory_calloc64f(nmt);
phi = memory_calloc64f(nmt);
var = memory_calloc64f(npmax);
d = memory_calloc64f(npmax);
eye = array_set64f(npmax, 1.0, &ierr);
// fix the number of threads
nt0 = omp_get_num_threads();
omp_set_num_threads(1);
// loop on point sizes
for (pSize=0; pSize<nps; pSize++)
{
// make synthetic data
memset(fname, 0, PATH_MAX*sizeof(char));
sprintf(fname, "blockSize_%d.txt", pSizes[pSize]);
fout = fopen(fname, "w");
npts = pSizes[pSize];
npgrns = npts;
cblas_dgemv(CblasColMajor, CblasNoTrans,
npgrns, 6, 1.0, G, npgrns, &mts[ldm*imtopt], 1, 0.0, d, 1);
for (i=0; i<nblocks; i++)
{
time_tic();
ierr = parmt_mtSearchL164f(ldm, nmt, npts, blockSizes[i],
nlags, lwantLags,
lrescale,
&G[0*npgrns], &G[1*npgrns], &G[2*npgrns],
&G[3*npgrns], &G[4*npgrns], &G[5*npgrns],
eye, mts, d, phi, var, lags);
time = time_toc();
fprintf(fout, "%d %d %e %e %d\n",
npts, blockSizes[i], 1.e6*time/(double) nmt, time/(double) nmt, nmt);
if (i == 0)
{
ierr = array_copy64f_work(nmt, phi, phiOri);
}
dnorm = array_normDiff64f(nmt, phi, phiOri, ONE_NORM, 1.0, &ierr);
xmin = array_min64f(nmt, phi, &ierr);
if (dnorm > DBL_EPSILON*(double) nmt)
{
printf("Error computing blocksize\n");
ierr = 1;
goto ERROR;
}
imt = array_argmax64f(nmt, phi, &ierr);
if (imt != imtopt)
{
printf("Failed to locate optimum\n");
ierr = 1;
goto ERROR;
}
}
fclose(fout);
}
ERROR:;
// restore number of threads
omp_set_num_threads(nt0);
// clear memory
memory_free64f(&d);
memory_free64f(&phiOri);
memory_free64f(&phi);
memory_free64f(&eye);
memory_free64f(&var);
memory_free64f(&mts);
memory_free64f(&G);
return 0;
}
| {
"alphanum_fraction": 0.517851042,
"avg_line_length": 36.8755905512,
"ext": "c",
"hexsha": "bdd10a16277c45022a7248964d7bf0c27fc6e00e",
"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": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_forks_repo_licenses": [
"Intel"
],
"max_forks_repo_name": "bakerb845/parmt",
"max_forks_repo_path": "src/unit_tests.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Intel"
],
"max_issues_repo_name": "bakerb845/parmt",
"max_issues_repo_path": "src/unit_tests.c",
"max_line_length": 93,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_stars_repo_licenses": [
"Intel"
],
"max_stars_repo_name": "bakerb845/parmt",
"max_stars_repo_path": "src/unit_tests.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7396,
"size": 23416
} |
#pragma once
#include <gsl/span>
#include "simple_math.h"
constexpr auto VECTOR_SIZE = sizeof(float) * 4;
class CBufferBase;
struct CBufferAlign
{
size_t size;
explicit CBufferAlign(size_t size_ = VECTOR_SIZE) : size(size_) {}
};
__forceinline CBufferAlign cbuff_align(size_t size = VECTOR_SIZE)
{
return CBufferAlign(size);
}
class ICBuffer
{
public:
virtual ~ICBuffer() = default;
virtual void write(CBufferBase& cbuf) const = 0;
size_t cbuffer_size() const;
template <typename T>
static size_t cbuffer_size()
{
T t;
return t.cbuffer_size();
}
};
class CBufferBase
{
protected:
size_t offset_ = 0;
size_t alignment_ = 0;
public:
virtual ~CBufferBase() = default;
bool align(size_t size = VECTOR_SIZE);
void add(size_t size);
void reset();
size_t offset() const { return offset_; }
size_t alignment() const { return alignment_; }
template <typename T>
CBufferBase& operator<<(const T& data) = delete;
template <typename T>
CBufferBase& operator<<(const gsl::span<T>& data) = delete;
template <typename T>
CBufferBase& operator<<(const gsl::span<const T>& data) = delete;
CBufferBase& operator<<(const CBufferAlign& align_of);
template <typename T, size_t size>
__forceinline CBufferBase& operator<<(const std::array<T, size>& array)
{
return *this << gsl::span<const T>(array);
}
template <typename T, size_t size>
__forceinline CBufferBase& operator<<(const T(&array)[size])
{
return *this << gsl::span<const T>(array);
}
template <typename T>
__forceinline CBufferBase& operator<<(const dirty_t<T>& value)
{
return *this << value.data();
}
virtual void write(const void* data, size_t size)
{
align(size);
add(size);
}
};
template <>
CBufferBase& CBufferBase::operator<<(const int32_t& data);
template <>
CBufferBase& CBufferBase::operator<<(const uint32_t& data);
template <>
CBufferBase& CBufferBase::operator<<(const float& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Matrix& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector2& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector3& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector4& data);
template <>
CBufferBase& CBufferBase::operator<<(const gsl::span<float>& data);
template <>
CBufferBase& CBufferBase::operator<<(const gsl::span<const float>& data);
template <>
__forceinline CBufferBase& CBufferBase::operator<<(const DWORD& data)
{
return *this << static_cast<uint32_t>(data);
}
template <>
__forceinline CBufferBase& CBufferBase::operator<<(const bool& data)
{
return *this << (data ? 1 : 0);
}
class CBufferWriter : public CBufferBase
{
uint8_t* ptr = nullptr;
public:
CBufferWriter(uint8_t* ptr_);
private:
void write(const void* data, size_t size) override;
};
| {
"alphanum_fraction": 0.7216027875,
"avg_line_length": 22.2480620155,
"ext": "h",
"hexsha": "127cc6a73efb0678f7037d2e1ae0cfe87f48ab00",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-04-06T19:38:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-27T11:20:53.000Z",
"max_forks_repo_head_hexsha": "bdfa3fc0d6485d4f9f44a83a43df937ba0b4f68c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "michael-fadely/sadx-d3d11",
"max_forks_repo_path": "sadx-d3d11/CBufferWriter.h",
"max_issues_count": 14,
"max_issues_repo_head_hexsha": "bdfa3fc0d6485d4f9f44a83a43df937ba0b4f68c",
"max_issues_repo_issues_event_max_datetime": "2018-11-09T11:58:54.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-05-14T22:33:18.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SonicFreak94/sadx-d3d11",
"max_issues_repo_path": "sadx-d3d11/CBufferWriter.h",
"max_line_length": 79,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "bdfa3fc0d6485d4f9f44a83a43df937ba0b4f68c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SonicFreak94/sadx-d3d11",
"max_stars_repo_path": "sadx-d3d11/CBufferWriter.h",
"max_stars_repo_stars_event_max_datetime": "2018-10-23T19:51:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-04-27T09:07:57.000Z",
"num_tokens": 751,
"size": 2870
} |
#include <stdio.h>
#include <cblas.h>
double A[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };
double x[] = { 1.0, -1.0, 2.0 };
double y[] = { -1.0, 0.0, 2.0 };
int main() {
int i;
cblas_dgemv(CblasRowMajor, CblasNoTrans, 3, 3, 2.5, A, 3, x, 1, 1.2, y, 1);
for (i = 0; i < 3; ++i) { printf("%6.1f\n", y[i]); }
return 0;
}
| {
"alphanum_fraction": 0.4808259587,
"avg_line_length": 21.1875,
"ext": "c",
"hexsha": "dccb6a35fc8f11a42a6c244b9da3b0c66d49b83f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a",
"max_forks_repo_licenses": [
"FSFAP"
],
"max_forks_repo_name": "julnamoo/practice-linux",
"max_forks_repo_path": "src_book0/ex10/list1022/list1022.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"FSFAP"
],
"max_issues_repo_name": "julnamoo/practice-linux",
"max_issues_repo_path": "src_book0/ex10/list1022/list1022.c",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a",
"max_stars_repo_licenses": [
"FSFAP"
],
"max_stars_repo_name": "julnamoo/practice-linux",
"max_stars_repo_path": "src_book0/ex10/list1022/list1022.c",
"max_stars_repo_stars_event_max_datetime": "2018-09-14T05:43:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-14T05:43:58.000Z",
"num_tokens": 191,
"size": 339
} |
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file mpepc_optimizer.h
* \author Collin Johnson and Jong Jin Park
*
* Declaration of MPEPCOptimizer.
*/
#ifndef MPEPC_OPTIMIZER_H
#define MPEPC_OPTIMIZER_H
#include "core/pose.h"
#include "mpepc/trajectory/params.h"
#include "mpepc/trajectory/robot_trajectory_info.h"
#include <memory>
#include <nlopt.h>
#include <vector>
namespace vulcan
{
namespace mpepc
{
const int kOptimizationDimension = 5;
const int kIdxR = 0;
const int kIdxTheta = 1;
const int kIdxDelta = 2;
const int kIdxVGain = 3;
const int kIdxK1 = 4;
/**
* optimizer_coords_t is a coordinate of optimization space for the MPEPCOptimizer,
* i.e. the argument to the objective function to be minimized.
*/
struct optimizer_coords_t
{
double r;
double theta;
double delta;
double velocityGain;
double k1;
double k2;
explicit optimizer_coords_t(double r = 0,
double theta = 0,
double delta = 0,
double velocityGain = 0,
double k1 = 1.0,
double k2 = 1.0)
: r(r)
, theta(theta)
, delta(delta)
, velocityGain(velocityGain)
, k1(k1)
, k2(k2)
{
}
explicit optimizer_coords_t(const double x[kOptimizationDimension])
: r(x[kIdxR])
, theta(x[kIdxTheta])
, delta(x[kIdxDelta])
, velocityGain(x[kIdxVGain])
, k1(x[kIdxK1])
{
}
void toArray(double x[kOptimizationDimension]) const
{
x[kIdxR] = r;
x[kIdxTheta] = theta;
x[kIdxDelta] = delta;
x[kIdxVGain] = velocityGain;
x[kIdxK1] = k1;
}
bool operator==(const optimizer_coords_t& rhs) const
{
return (r == rhs.r) && (theta == rhs.theta) && (delta == rhs.delta) && (velocityGain == rhs.velocityGain)
&& (k1 == rhs.k1);
}
bool operator!=(const optimizer_coords_t& rhs) const { return !(*this == rhs); }
};
class RobotSimulator;
class TrajectoryEvaluator;
class TaskManifold;
struct motion_target_t;
struct trajectory_planner_debug_info_t;
/**
* MPEPCTrajectoryOptimizer handles the optimization task within the MPEPC planner.
* The optimizer recieves the simulator and the cost evaluator to use, along with
* the state for the current planning problem, i.e. planner_data_t, and finds the
* time-optimal trajectory in the form of a motion target.
*
* The optimizer handles the simulate/evaluate loop internally and finds the optimal
* target along with the intermediate trajectories generated by the optimization
* algorithm. NLopt package is used for the numerical optimzation, and a number of
* different algorithms can be implemented.
*/
class MPEPCOptimizer
{
public:
/**
* Constructor for MPEPCOptimizer.
*
* \param params Parameters for the optimization
*/
MPEPCOptimizer(const mpepc_optimizer_params_t& params);
/**
* Destructor for MPEPCOptimizer.
*/
~MPEPCOptimizer(void);
/**
* Setup sets up the optmizer with the robot simulator and trajectory evaluator to be used.
*
* \param simulator RobotSimulator to use for the trajectory generation.
* \param evaluator TrajectoryEvaluator for calculating the cost of a trajectory.
*/
void setup(RobotSimulator& simulator,
TrajectoryEvaluator& evaluator); // NOTE: This feels very unsafe. A better way?
/**
* setInitialGuesses adds a goal pose (if navigation task) and the previous optimum
* to the initial guesses for local optimizer.
*
* \param task TaskManifold that contains the goal.
* \param previousMotionTarget Previous output of the metric planner, i.e. the previous optimum.
*/
void setInitialGuesses(const TaskManifold& task, const motion_target_t& previousMotionTarget);
/**
* run runs the optimizer and finds the best motion target by evaluating the expected
* costs of an estimated trajectory generated from a candidate motion target.
*
* It returns the optimal target found, while the intermediate information including
* all trajectories considered are stored in the provided debug info instance.
*
* \param debugInfo Place to store relevant information
* \return Optimal target found
*/
motion_target_t runOptimizer(trajectory_planner_debug_info_t& debugInfo);
/**
* evaluateCost calculates the cost of a fixed-length trajectory represented by the given optimizer_target_t.
* The length of the trajectory is specified in the given instance of the planner_data_t.
*
* \param coords Optimization variable, currently encoding a target pose in the robot frame and a
* velocity gain for the kinematic control law. \return Cost of the trajectory.
*/
double evaluateCost(const optimizer_coords_t& coords);
// get getSurvivability of the trajectroy associated with the optimizer coords. Will assert failure if the given
// coordinate is not the same as the one used for cost evaluation
double getChanceConstraint(const optimizer_coords_t& coords);
/**
* evaluateGradient calculates the gradient around a particular point, by a simple forward differencing.
*
* \param coords Optimization variable, currently encoding a target pose in the robot frame and a
* velocity gain for the kinematic control law. \param cost Evaluated cost at the given coordinate.
* \param gradient Calculated gradient for each dimension (r, theta, delta, velocity) [output]
*/
void evaluateGradient(const optimizer_coords_t& coords, double cost, double gradient[kOptimizationDimension]);
bool haveFoundSolution(void) const { return haveFoundSolution_; };
// /**
// * evaluateSingleMotionTarget is a method which resets the data and info struct and evaluate a single
// optimizer target.
// * The optimization_info_t will hold a single trajectory considered. TODO: Do i need this?
// *
// * \param candidateMotionTarget
// * \param data
// * \param info
// */
// double evaluateSingleMotionTarget(const motion_target_t& candidateMotionTarget, const planner_data_t& data,
// optimization_info_t& info);
private:
// setting up the optimizer
void setupGlobalOptimizer(void);
void setupLocalOptimizer(void);
// loading a predetermined set of initial points for local optimizer
void loadGuessesFromFile(const std::string& filename);
// checking if the target is within a specified bounds
bool isTargetValid(const optimizer_coords_t& target) const;
// selecting the best inital point for the local optimizer
// assumes there are valid trajectories stored in optimizerInfo_
void selectBestInitialPoint(const std::vector<optimizer_coords_t>& initialGuesses,
double x[kOptimizationDimension]);
std::size_t bestTrajectoryIdx(void);
// optimizers
nlopt_opt globalOptimizer;
nlopt_opt localOptimizer;
optimizer_coords_t coordEvaluated_;
double globalOptimizerSeed_[kOptimizationDimension];
// simulator and evaluator
RobotSimulator* simulator_;
TrajectoryEvaluator* evaluator_;
robot_trajectory_info_t trajectory; // Trajectory to use for everything -- just reset it before each use
// debug info
trajectory_planner_debug_info_t* optimizerInfo_;
// a set of initial guesses for optmization
std::vector<optimizer_coords_t> defaultGuesses_;
std::vector<optimizer_coords_t> newGuesses_;
// inital robot state
pose_t robotPose_;
// indicator for finding a right solution
bool haveFoundSolution_;
// parameters
mpepc_optimizer_params_t params_;
};
} // namespace mpepc
} // namespace vulcan
#endif // MPEPC_OPTIMIZER_H
| {
"alphanum_fraction": 0.6859058795,
"avg_line_length": 33.6733870968,
"ext": "h",
"hexsha": "6406273124fc548322b5990a814575ab421d183b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z",
"max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "anuranbaka/Vulcan",
"max_forks_repo_path": "src/mpepc/trajectory/mpepc_optimizer.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028",
"max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "anuranbaka/Vulcan",
"max_issues_repo_path": "src/mpepc/trajectory/mpepc_optimizer.h",
"max_line_length": 118,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "anuranbaka/Vulcan",
"max_stars_repo_path": "src/mpepc/trajectory/mpepc_optimizer.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z",
"num_tokens": 1884,
"size": 8351
} |
/* specfunc/gsl_sf_erf.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_ERF_H__
#define __GSL_SF_ERF_H__
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Complementary Error Function
* erfc(x) := 2/Sqrt[Pi] Integrate[Exp[-t^2], {t,x,Infinity}]
*
* exceptions: none
*/
int gsl_sf_erfc_e(double x, gsl_sf_result * result);
double gsl_sf_erfc(double x);
/* Log Complementary Error Function
*
* exceptions: none
*/
int gsl_sf_log_erfc_e(double x, gsl_sf_result * result);
double gsl_sf_log_erfc(double x);
/* Error Function
* erf(x) := 2/Sqrt[Pi] Integrate[Exp[-t^2], {t,0,x}]
*
* exceptions: none
*/
int gsl_sf_erf_e(double x, gsl_sf_result * result);
double gsl_sf_erf(double x);
/* Probability functions:
* Z(x) : Abramowitz+Stegun 26.2.1
* Q(x) : Abramowitz+Stegun 26.2.3
*
* exceptions: none
*/
int gsl_sf_erf_Z_e(double x, gsl_sf_result * result);
int gsl_sf_erf_Q_e(double x, gsl_sf_result * result);
double gsl_sf_erf_Z(double x);
double gsl_sf_erf_Q(double x);
/* Hazard function, also known as the inverse Mill's ratio.
*
* H(x) := Z(x)/Q(x)
* = Sqrt[2/Pi] Exp[-x^2 / 2] / Erfc[x/Sqrt[2]]
*
* exceptions: GSL_EUNDRFLW
*/
int gsl_sf_hazard_e(double x, gsl_sf_result * result);
double gsl_sf_hazard(double x);
__END_DECLS
#endif /* __GSL_SF_ERF_H__ */
| {
"alphanum_fraction": 0.7137254902,
"avg_line_length": 24.9456521739,
"ext": "h",
"hexsha": "d63b3176e18401badace06fd91f5a76f7eee64d4",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z",
"max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "snipekill/FPGen",
"max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_erf.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "snipekill/FPGen",
"max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_erf.h",
"max_line_length": 81,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "snipekill/FPGen",
"max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_erf.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z",
"num_tokens": 665,
"size": 2295
} |
#ifndef CWANNIER_HTIGHTBINDING_H
#define CWANNIER_HTIGHTBINDING_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_errno.h>
#include "bstrlib/bstrlib.h"
typedef struct {
int num_rs, num_bands;
double *ras;
double *rbs;
double *rcs;
double *degens;
gsl_matrix_complex **Hrs;
} HTightBinding;
HTightBinding* ExtractHTightBinding(char *filePath);
void FreeHTightBinding(HTightBinding *Hrs);
void HkRecip(HTightBinding *Hrs, double k[3], gsl_matrix_complex *Hk);
gsl_matrix_complex* HrAtR(HTightBinding *Hrs, double R[3], double *degen);
#endif // CWANNIER_HTIGHTBINDING_H
| {
"alphanum_fraction": 0.749672346,
"avg_line_length": 23.1212121212,
"ext": "h",
"hexsha": "714a41ac73ef3c87440e9a27940c8ab830178346",
"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": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/cwannier",
"max_forks_repo_path": "HTightBinding.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/cwannier",
"max_issues_repo_path": "HTightBinding.h",
"max_line_length": 74,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/cwannier",
"max_stars_repo_path": "HTightBinding.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 232,
"size": 763
} |
/**
* File: nicback_utils.c
* Subroutine for the NICMOS background subtraction
*
*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit_nlin.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spc_FITScards.h"
#include "spce_sect.h"
#include "spce_fitting.h"
#include "spce_is_in.h"
#include "spc_back.h"
#include "spce_pathlength.h"
#include "trfit_utils.h"
#include "nicback_utils.h"
/**
* Function: make_nicmos_back
* The subroutine computes and stores the background image for a specific
* NICMOS grism image. The non-masked pixels in the grism image are
* correlated with their corresponding values in the master background image.
* A linear relation is fitted to the value pairs. Deviating points are
* excluded using kappa-sigma clipping.
* Using the slope of the final fit, the background image is computed
* and stored as a fits image.
*
* Parameters:
* @param obs - the observation for the grism image
* @param msk_name - the full name of the mask file
* @param master_bck - the full name of the master sky background
* @param bck_name - the full name of the background image
*
* Returns:
* @return -
*/
void
make_nicmos_back(const observation * const obs, const char *msk_name,
const char *master_bck, char bck_name[], char plist_name[],
const char corr_bck[])
{
px_point npixels;
double skypix_frac;
gsl_matrix *msk_img;
gsl_matrix *mbck_img;
gsl_matrix *corr_img=NULL;
gsl_matrix *grism_bck;
gsl_vector *lfit;
fitbck_data *fbck_data;
//int f_status=0;
FITScards *cards;
char ID[MAXCHAR];
// fix the extension name
sprintf (ID, "BCK");
// load the master background image
fprintf(stdout,"Loading DATA from: %s...", master_bck);
mbck_img = FITSimage_to_gsl(master_bck, 1, 1);
fprintf(stdout,". Done.\n");
if (strlen(corr_bck) > 0)
{
// load the correction background image
fprintf(stdout,"Loading DATA from: %s...", corr_bck);
corr_img = FITSimage_to_gsl(corr_bck, 1, 1);
fprintf(stdout,". Done.\n");
}
// load the mask image
fprintf(stdout,"Loading DATA from: %s...", msk_name);
msk_img = FITSimage_to_gsl(msk_name, 2, 1);
fprintf(stdout,". Done.\n");
// get the dimension of
// the grism image
npixels = get_npixel(obs);
// allocate memory for the fit data
fbck_data = alloc_fitbck_data(npixels.x * npixels.y);
// fill the fit data into the structure
fill_fbck_data(obs, msk_img, mbck_img, fbck_data, plist_name, corr_img);
// make the fit, including
// kappa-sigma iterations
lfit = make_ksig_linfit(fbck_data);
// report the result of the fit onto the screen
fprintf(stdout, "\nFitting result: c0 = %f +- %f , c1 = %f +- %f , chi^2 = %f\n\n",
gsl_vector_get(lfit, 1), gsl_vector_get(lfit, 3),
gsl_vector_get(lfit, 2), gsl_vector_get(lfit, 4), gsl_vector_get(lfit, 6));
// compute the background for the grism frame
grism_bck = compute_nicmos_back(mbck_img, gsl_vector_get(lfit, 2),
gsl_vector_get(lfit, 1), corr_img);
// write the background image to a file
fprintf(stdout,"Writing data to: %s...", bck_name);
gsl_to_FITSimage (grism_bck, bck_name, 1, ID);
fprintf(stdout,". Done.\n");
// determine the fraction of pixels
// used in the background determination
skypix_frac = get_skypix_frac(fbck_data);
// create the fits keywords
cards = nicbck_info_to_FITScards(skypix_frac, gsl_vector_get(lfit, 2),
gsl_vector_get(lfit, 1));
// transfer the fits keywords
// to the background image
put_FITS_cards (bck_name, 2, cards);
// release memory
free_fitbck_data(fbck_data);
gsl_matrix_free(mbck_img);
if (corr_img != NULL)
gsl_matrix_free(corr_img);
gsl_matrix_free(msk_img);
gsl_matrix_free(grism_bck);
gsl_vector_free(lfit);
free_FITScards(cards);
}
/**
* Function: alloc_fitbck_data
*/
fitbck_data *
alloc_fitbck_data(const int n_data)
{
fitbck_data *fbck_data;
fbck_data = (fitbck_data *)malloc(sizeof(fitbck_data));
fbck_data->x_values = (double *)malloc(n_data * sizeof(double));
fbck_data->y_values = (double *)malloc(n_data * sizeof(double));
fbck_data->e_values = (double *)malloc(n_data * sizeof(double));
fbck_data->x_pos = (int *)malloc(n_data * sizeof(int));
fbck_data->y_pos = (int *)malloc(n_data * sizeof(int));
fbck_data->n_data = n_data;
return fbck_data;
}
/**
* Function: get_skypix_frac
* The subroutine computes the fraction of image pixels which were used for
* determining the scaling factor of the master background and the computation
* of the bacground image. Pixels not used were masked out, since they are part
* of an object beam or rejected in the kappa-sigma clipping.
*
* Parameters:
* @param fbck_data - the data used for the fit
*
* Returns:
* @return skypix_frac - fraction of pixels used for background determination
*/
double
get_skypix_frac(const fitbck_data *fbck_data)
{
int index;
int nvalues=0;
double skypix_frac=0.0;
// go over all data values
for (index=0; index < fbck_data->n_data; index++)
{
// check whether the weight is not NULL
if (fbck_data->e_values[index])
// enhance the number of used pixels
nvalues++;
}
// compute the fration of used pixels
skypix_frac = (double)nvalues / (double)fbck_data->n_data;
// return the fraction
return skypix_frac;
}
/**
* Function: compute_nicmos_back
* The subroutine applies a scaling factor to a master background
* in order to get the background image for a specific grism image.
*
* Parameters:
* @param mbck_img - the master background pixel
* @param factor - the scaling factor
*
* Returns:
* @return grism_bck - the background image as gsl-matrix
*/
gsl_matrix *
compute_nicmos_back(const gsl_matrix *mbck_img, const double factor,
const double offset, const gsl_matrix *corr_img)
{
gsl_matrix *grism_bck;
int ii, jj;
// allocate the space for the background image
grism_bck = gsl_matrix_alloc(mbck_img->size1, mbck_img->size2);
// go over each row
for (ii=0; ii < (int)mbck_img->size1; ii++)
{
// go over each column
for (jj=0; jj < (int)mbck_img->size2; jj++)
{
// compute and set the value in the background image
if (corr_img != NULL)
// using the pedestal image
gsl_matrix_set(grism_bck, ii, jj,
(gsl_matrix_get(mbck_img, ii, jj) + gsl_matrix_get(corr_img, ii, jj)) * factor);
else
// using the fit values only
gsl_matrix_set(grism_bck, ii, jj, gsl_matrix_get(mbck_img, ii, jj) * factor + offset);
}
}
// return the background image
return grism_bck;
}
/**
* Function: compute_nicmos_back
* The subroutine iteratively fits a linear relation to the pairs of
* grism image - master background pixel values. After each fit,
* pairs with large deviations are determined and excluded.
* The result of the final fit is returned.
*
* Parameters:
* @param fbck_data - the data used for the fits
*
* Returns:
* @return lfit - the results of the final fit
*/
gsl_vector *
make_ksig_linfit(fitbck_data *fbck_data)
{
gsl_vector *lfit=NULL;
int index=0;
int clipped=1;
// check whether iterations still
// must be done and whether
// the data was changed from clipping
while (index < N_KSIGBCK_ITER && clipped)
{
if (check_fbck_data(fbck_data))
{
// make a non-weighted linear fit
lfit = det_vector_linear(fbck_data->x_values, fbck_data->y_values, fbck_data->e_values,
fbck_data->n_data, 0);
// make a clipping iteration
clipped = clipp_fbck_data(fbck_data, lfit, N_KSIGBCK_KAPPA);
// inhance the clipping counter
index++;
}
else
{
// release the space
// for the old vector
if (lfit)
gsl_vector_free(lfit);
// get a new dummy vector
lfit = get_fbck_defaults();
break;
}
}
// check whether the scale is within the boundaries
if (gsl_vector_get(lfit, 2) < BCK_SCALE_MIN || gsl_vector_get(lfit, 2) > BCK_SCALE_MAX)
{
fprintf(stdout, "aXe_NICBACK: Background scale is out of bounds. It is re-adjusted.\n");
// release the space
// for the old vector
gsl_vector_free(lfit);
// get a new dummy vector
lfit = get_fbck_defaults();
}
// return the fit result
return lfit;
}
int
check_fbck_data(fitbck_data *fbck_data)
{
int check=1;
int ix_min=60000;
int ix_max=0;
int iy_min=60000;
int iy_max=0;
int index;
double frac;
double x_ext, y_ext;
// get the fraction of background pixel
frac = get_skypix_frac(fbck_data);
if (frac < FRAC_BPIX_MIN)
{
check = 0;
fprintf(stdout, "aXe_NICBACK: Not enough background pixels. Fraction: %e\n", frac);
}
else
{
// go over all data values
for (index=0; index < fbck_data->n_data; index++)
{
// check whether the weight is not NULL
if (fbck_data->e_values[index])
{
if (fbck_data->x_pos[index] > ix_max)
ix_max = fbck_data->x_pos[index];
if (fbck_data->x_pos[index] < ix_min)
ix_min = fbck_data->x_pos[index];
if (fbck_data->y_pos[index] > iy_max)
iy_max = fbck_data->y_pos[index];
if (fbck_data->y_pos[index] < iy_min)
iy_min = fbck_data->y_pos[index];
}
}
x_ext = (float)(ix_max-ix_min) / NPIX_DIM1;
y_ext = (float)(iy_max-iy_min) / NPIX_DIM2;
if (x_ext < AREA_EXTEND_MIN || y_ext < AREA_EXTEND_MIN)
{
check = 0;
fprintf(stdout, "aXe_NICBACK: Not enough coverage. xcover,ycover: %e,%e\n", x_ext, y_ext);
}
}
return check;
}
gsl_vector*
get_fbck_defaults()
{
gsl_vector *ret;
ret = gsl_vector_alloc(10);
/*
gsl_vector_set(ret, 0, xean);
gsl_vector_set(ret, 1, c0);
gsl_vector_set(ret, 2, c1);
gsl_vector_set(ret, 3, cov00);
gsl_vector_set(ret, 4, cov01);
gsl_vector_set(ret, 5, cov11);
gsl_vector_set(ret, 6, chisq);
*/
gsl_vector_set(ret, 0, 0.0);
gsl_vector_set(ret, 1, 0.0);
gsl_vector_set(ret, 2, 1.0);
gsl_vector_set(ret, 3, 1.0);
gsl_vector_set(ret, 4, 0.0);
gsl_vector_set(ret, 5, 1.0);
gsl_vector_set(ret, 6, 0.0);
return ret;
}
/**
* Function: clipp_fbck_data
* The subroutine applies kappa-sigma clipping to a set of data points.
* The difference between the measured values and the expected values
* according to linear regression are determined.
* Data which is outside of the accepted interval is excluded by
* setting the weight to '0.0'. If at least one value was clipped,
* '1' is returned, otherwise '0' (if all values are within the
* accepted interval.
*
* Parameters:
* @param fbck_data - the data used for the fits
* @param lfit - the result of the fit
* @param kappa - the kappa value
*
* Returns:
* @return clipped - boolean to indicate clipped values
*/
int
clipp_fbck_data(fitbck_data *fbck_data, const gsl_vector *lfit, const float kappa)
{
int clipped=0;
int nclipps=0;
int ndata=0;
int index;
double dy_mean=0.0;
double stdev=0.0;
double absdev;
double dy_act;
double *y_diff;
// allocate memory for the tmp-vector
y_diff = (double *) malloc(fbck_data->n_data * sizeof(double));
// go over all data values
for (index=0; index < fbck_data->n_data; index++)
{
// check whether the weight is not NULL
if (fbck_data->e_values[index])
{
// compute the difference from the data point
// to the prediction from the fit
dy_act = (fbck_data->x_values[index] - gsl_vector_get(lfit, 0)) * gsl_vector_get(lfit, 2)
+ gsl_vector_get(lfit, 1)-fbck_data->y_values[index];
// fill the tmp vector
y_diff[ndata] = dy_act;
// pre-comute the mean
dy_mean += dy_act;
// enhance the counter
// of non-NULL values
ndata++;
}
}
// compute the mean offset
dy_mean = dy_mean / (double)ndata;
// compute the standard deviation
stdev = comp_stdev_from_array(y_diff, ndata, dy_mean);
// get the maximum allowed
// deviation
absdev = kappa*stdev;
// go over the data
for (index=0; index < fbck_data->n_data; index++)
{
// check whether the data has weigth
if (fbck_data->e_values[index])
{
// compute the absolute difference from the data point
// to the prediction from the fit
dy_act = fabs((fbck_data->x_values[index] - gsl_vector_get(lfit, 0)) * gsl_vector_get(lfit, 2)
+ gsl_vector_get(lfit, 1)-fbck_data->y_values[index]);
// check whether the difference
// is larger than allowed
if (dy_act > absdev)
{
// make the weight NULL
fbck_data->e_values[index] = 0.0;
// set the clipped flagg
clipped=1;
nclipps++;
}
}
}
fprintf(stdout, "Number of clipped pixels: %i\n", nclipps);
// release memory
free(y_diff);
// return the integer
// indicating clipped values
return clipped;
}
/**
* Function: comp_stdev_from_array
* The subroutine computes the standard deviation
* of a data vector, using the known mean value.
*
* Parameters:
* @param data - the data vector
* @param ndata - number of data points to use
* @param mean - mean value of the data points
*
* Returns:
* @return clipped - boolean to indicate clipped values
*/
double
comp_stdev_from_array(const double *data, const int ndata, const double mean)
{
int index=0;
double stdev=0.0;
// go over the data array
for (index=0; index < ndata; index++)
{
// compute and add the square difference to the mean
stdev += (data[index] - mean) * (data[index] - mean);
}
// compute the average square difference
if (ndata > 1)
stdev /= ((double)ndata-1);
// compute the final
// standard deviation
stdev = sqrt(stdev);
// return the stdev
return stdev;
}
/**
* Function: make_nicmos_back
* The subroutine creates and fills a structure with pairs of correpsonding
* from a grism image and a master sky background. Dq-masked pixels values
* and pixels which are part of an object beam are used, but marked with
* a zero weight.
*
* Parameters:
* @param obs - the observation for the grism image
* @param msk_image - the maks image values
* @param mbck_img - the master background values
* @param fbck_data - structure with the data pairs
*
* Returns:
* @return -
*/
void
fill_fbck_data(const observation * const obs, const gsl_matrix *msk_img,
const gsl_matrix *mbck_img, fitbck_data *fbck_data, char plist_name[],
const gsl_matrix *corr_img)
{
int ix=0;
int iy=0;
int index=0;
char Buffer[10240];
FILE *fout;
int px_min=20;
int px_max=180;
int py_min=50;
int py_max=245;
//int px_min=0;
//int px_max=255;
//int py_min=0;
//int py_max=255;
//10:240,15:245[10:180,20:245][20:180,50:245]
// intitialize the index for
// the fit_data structure
index = 0;
double diffval;
fout = fopen(plist_name, "w");
// go over all pixels
// in the grism image
for (ix=0; ix < (int)obs->grism->size1; ix++)
{
for (iy=0; iy < (int)obs->grism->size2; iy++)
{
// set the master background pixel as independent variable
fbck_data->x_values[index] = gsl_matrix_get(mbck_img, ix, iy);
if (corr_img != NULL)
// subtract the correction value from the background value
diffval = gsl_matrix_get(obs->grism, ix, iy) - gsl_matrix_get(corr_img, ix, iy);
else
// use the naked background value
diffval = gsl_matrix_get(obs->grism, ix, iy);
// set the grism image pixel as dependent variable
//fbck_data->y_values[index] = gsl_matrix_get(obs->grism, ix, iy);
// set the difference as dependent variable
fbck_data->y_values[index] = diffval;
// set the x- and y-positions
fbck_data->x_pos[index] = ix;
fbck_data->y_pos[index] = iy;
// check whether the pixel was masked out
// or is part of an object
if (isnan(gsl_matrix_get(obs->grism, ix, iy))
|| gsl_matrix_get(msk_img, ix, iy) < -9.0e+05)
// mask the pixel in the array
fbck_data->e_values[index] = 0.0;
else
{
// give the pixel full weight
//x,y,value_back,value_grism_imag
fbck_data->e_values[index] = 1.0;
sprintf (Buffer, "%i %i %e %e\n",ix, iy, gsl_matrix_get(obs->grism, ix, iy), gsl_matrix_get(mbck_img, ix, iy));
fputs (Buffer, fout);
}
// check whether the pixel is in the
// allowed are
if (ix < px_min || ix > px_max
|| iy < py_min || iy > py_max)
// mask the pixel in the array
fbck_data->e_values[index] = 0.0;
// enhance the counter
index++;
}
}
fclose (fout);
}
/*
* Function: free_fitbck_data
* The function releases the memory allocated in
* a fit-data structure
*
* Parameters:
* @param fbck_data - the allocated structure
*
* Returns:
* @return -
*/
void
free_fitbck_data(fitbck_data *fbck_data)
{
free(fbck_data->x_values);
free(fbck_data->y_values);
free(fbck_data->e_values);
free(fbck_data->x_pos);
free(fbck_data->y_pos);
free(fbck_data);
fbck_data = NULL;
}
| {
"alphanum_fraction": 0.6754090614,
"avg_line_length": 25.8458015267,
"ext": "c",
"hexsha": "3eac35d2a95ec274c9f7fb815ce8044bcdf99dfd",
"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/nicback_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/nicback_utils.c",
"max_line_length": 118,
"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/nicback_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4969,
"size": 16929
} |
/* integration/qag.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include "initialise.c"
#include "set_initial.c"
#include "qpsrt.c"
#include "util.c"
static int
qag (const gsl_function *f,
const double a, const double b,
const double epsabs, const double epsrel,
const size_t limit,
gsl_integration_workspace * workspace,
double * result, double * abserr,
gsl_integration_rule * q) ;
int
gsl_integration_qag (const gsl_function *f,
double a, double b,
double epsabs, double epsrel, size_t limit,
int key,
gsl_integration_workspace * workspace,
double * result, double * abserr)
{
int status ;
gsl_integration_rule * integration_rule = gsl_integration_qk15 ;
if (key < GSL_INTEG_GAUSS15)
{
key = GSL_INTEG_GAUSS15 ;
}
else if (key > GSL_INTEG_GAUSS61)
{
key = GSL_INTEG_GAUSS61 ;
}
switch (key)
{
case GSL_INTEG_GAUSS15:
integration_rule = gsl_integration_qk15 ;
break ;
case GSL_INTEG_GAUSS21:
integration_rule = gsl_integration_qk21 ;
break ;
case GSL_INTEG_GAUSS31:
integration_rule = gsl_integration_qk31 ;
break ;
case GSL_INTEG_GAUSS41:
integration_rule = gsl_integration_qk41 ;
break ;
case GSL_INTEG_GAUSS51:
integration_rule = gsl_integration_qk51 ;
break ;
case GSL_INTEG_GAUSS61:
integration_rule = gsl_integration_qk61 ;
break ;
default:
GSL_ERROR("value of key does specify a known integration rule",
GSL_EINVAL) ;
}
status = qag (f, a, b, epsabs, epsrel, limit,
workspace,
result, abserr,
integration_rule) ;
return status ;
}
static int
qag (const gsl_function * f,
const double a, const double b,
const double epsabs, const double epsrel,
const size_t limit,
gsl_integration_workspace * workspace,
double *result, double *abserr,
gsl_integration_rule * q)
{
double area, errsum;
double result0, abserr0, resabs0, resasc0;
double tolerance;
size_t iteration = 0;
int roundoff_type1 = 0, roundoff_type2 = 0, error_type = 0;
double round_off;
/* Initialize results */
initialise (workspace, a, b);
*result = 0;
*abserr = 0;
if (limit > workspace->limit)
{
GSL_ERROR ("iteration limit exceeds available workspace", GSL_EINVAL) ;
}
if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))
{
GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel",
GSL_EBADTOL);
}
/* perform the first integration */
q (f, a, b, &result0, &abserr0, &resabs0, &resasc0);
set_initial_result (workspace, result0, abserr0);
/* Test on accuracy */
tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));
/* need IEEE rounding here to match original quadpack behavior */
round_off = GSL_COERCE_DBL (50 * GSL_DBL_EPSILON * resabs0);
if (abserr0 <= round_off && abserr0 > tolerance)
{
*result = result0;
*abserr = abserr0;
GSL_ERROR ("cannot reach tolerance because of roundoff error "
"on first attempt", GSL_EROUND);
}
else if ((abserr0 <= tolerance && abserr0 != resasc0) || abserr0 == 0.0)
{
*result = result0;
*abserr = abserr0;
return GSL_SUCCESS;
}
else if (limit == 1)
{
*result = result0;
*abserr = abserr0;
GSL_ERROR ("a maximum of one iteration was insufficient", GSL_EMAXITER);
}
area = result0;
errsum = abserr0;
iteration = 1;
do
{
double a1, b1, a2, b2;
double a_i, b_i, r_i, e_i;
double area1 = 0, area2 = 0, area12 = 0;
double error1 = 0, error2 = 0, error12 = 0;
double resasc1, resasc2;
double resabs1, resabs2;
/* Bisect the subinterval with the largest error estimate */
retrieve (workspace, &a_i, &b_i, &r_i, &e_i);
a1 = a_i;
b1 = 0.5 * (a_i + b_i);
a2 = b1;
b2 = b_i;
q (f, a1, b1, &area1, &error1, &resabs1, &resasc1);
q (f, a2, b2, &area2, &error2, &resabs2, &resasc2);
area12 = area1 + area2;
error12 = error1 + error2;
errsum += (error12 - e_i);
area += area12 - r_i;
if (resasc1 != error1 && resasc2 != error2)
{
double delta = r_i - area12;
if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)
{
roundoff_type1++;
}
if (iteration >= 10 && error12 > e_i)
{
roundoff_type2++;
}
}
tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));
if (errsum > tolerance)
{
if (roundoff_type1 >= 6 || roundoff_type2 >= 20)
{
error_type = 2; /* round off error */
}
/* set error flag in the case of bad integrand behaviour at
a point of the integration range */
if (subinterval_too_small (a1, a2, b2))
{
error_type = 3;
}
}
update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);
retrieve (workspace, &a_i, &b_i, &r_i, &e_i);
iteration++;
}
while (iteration < limit && !error_type && errsum > tolerance);
*result = sum_results (workspace);
*abserr = errsum;
if (errsum <= tolerance)
{
return GSL_SUCCESS;
}
else if (error_type == 2)
{
GSL_ERROR ("roundoff error prevents tolerance from being achieved",
GSL_EROUND);
}
else if (error_type == 3)
{
GSL_ERROR ("bad integrand behavior found in the integration interval",
GSL_ESING);
}
else if (iteration == limit)
{
GSL_ERROR ("maximum number of subdivisions reached", GSL_EMAXITER);
}
else
{
GSL_ERROR ("could not integrate function", GSL_EFAILED);
}
}
| {
"alphanum_fraction": 0.6267253147,
"avg_line_length": 24.7857142857,
"ext": "c",
"hexsha": "64798de94e4c2a9cc3e81c315f5efbef5b1933f1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/integration/qag.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/integration/qag.c",
"max_line_length": 78,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/integration/qag.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": 1917,
"size": 6593
} |
/**
*
* @file testing_zhegv.c
*
* PLASMA testing routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Azzam Haidar
* @author Hatem Ltaief
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <core_blas.h>
#include "testing_zmain.h"
#undef REAL
#define COMPLEX
static int check_orthogonality(int itype, int uplo, int N,
PLASMA_Complex64_t *Z, int LDZ,
PLASMA_Complex64_t *B, PLASMA_Complex64_t *CHOLB, int LDB,
double eps);
static int check_reduction(int itype, int uplo, int N, double *D,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *B, int LDB,
PLASMA_Complex64_t *Z, int LDZ,
double eps );
static int check_solution(int N, double *E1, double *E2, double eps);
int testing_zhegv(int argc, char **argv)
{
/* Check for number of arguments*/
if (argc != 3) {
USAGE("HEGV", "N LDA LDB",
" - N : size of the matrices A and B\n"
" - LDA : leading dimension of the matrix A\n"
" - LDB : leading dimension of the matrix B\n");
return -1;
}
double eps = LAPACKE_dlamch_work('e');
PLASMA_enum vec = PlasmaVec;
int N = atoi(argv[0]);
int LDA = atoi(argv[1]);
int LDB = atoi(argv[2]);
int LDQ = LDA;
int LDAxN = LDA*N;
int LDBxN = LDB*N;
int LDQxN = LDQ*N;
int info_ortho = 0;
int info_solution = 0;
int info_reduction = 0;
int i, u;
PLASMA_Complex64_t *A1 = (PLASMA_Complex64_t *)malloc(LDAxN*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *A2 = (PLASMA_Complex64_t *)malloc(LDAxN*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *B1 = (PLASMA_Complex64_t *)malloc(LDBxN*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *B2 = (PLASMA_Complex64_t *)malloc(LDBxN*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *Q = (PLASMA_Complex64_t *)malloc(LDQxN*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *Ainit = (PLASMA_Complex64_t *)malloc(LDAxN*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *Binit = (PLASMA_Complex64_t *)malloc(LDBxN*sizeof(PLASMA_Complex64_t));
double *W1 = (double *)malloc(N*sizeof(double));
double *W2 = (double *)malloc(N*sizeof(double));
PLASMA_Complex64_t *work = (PLASMA_Complex64_t *)malloc(3*N* sizeof(PLASMA_Complex64_t));
PLASMA_desc *T;
/* Check if unable to allocate memory */
if ((!A1)||(!A2)||(!B1)||(!B2)||(!Q)||(!Ainit)||(!Binit)){
printf("Out of Memory \n ");
return -2;
}
PLASMA_Disable(PLASMA_AUTOTUNING);
PLASMA_Set(PLASMA_TILE_SIZE, 120);
PLASMA_Set(PLASMA_INNER_BLOCK_SIZE, 20);
PLASMA_Enable(PLASMA_WARNINGS);
PLASMA_Enable(PLASMA_ERRORS);
PLASMA_Alloc_Workspace_zhegv(N, N, &T);
/*----------------------------------------------------------
* TESTING ZHEGV
*/
/* Initialize A1 and Ainit */
PLASMA_zplghe(0., N, A1, LDA, 5198);
PLASMA_zlacpy(PlasmaUpperLower, N, N, A1, LDA, Ainit, LDA);
/* Initialize B1 and Binit */
PLASMA_zplghe((double)N, N, B1, LDB, 4321 );
PLASMA_zlacpy(PlasmaUpperLower, N, N, B1, LDB, Binit, LDB);
printf("\n");
printf("------ TESTS FOR PLASMA ZHEGV ROUTINE ------- \n");
printf(" Size of the Matrix %d by %d\n", N, N);
printf("\n");
printf(" The matrix A is randomly generated for each test.\n");
printf("============\n");
printf(" The relative machine precision (eps) is to be %e \n",eps);
printf(" Computational tests pass if scaled residuals are less than 60.\n");
/*----------------------------------------------------------
* TESTING ZHEGV
*/
for (i=0; i<3; i++) {
for (u=0; u<2; u++) {
memcpy(A2, Ainit, LDAxN*sizeof(PLASMA_Complex64_t));
memcpy(B2, Binit, LDBxN*sizeof(PLASMA_Complex64_t));
/* CALL ZHEGV with itype= 1, 2, 3 and uplo= L,U */
PLASMA_zhegv(itype[i], vec, uplo[u], N, A2, LDA, B2, LDB, W2, T, Q, LDQ);
/* CALL LAPACK to compute eigenvalues. */
memcpy(A1, Ainit, LDAxN*sizeof(PLASMA_Complex64_t));
memcpy(B1, Binit, LDBxN*sizeof(PLASMA_Complex64_t));
LAPACKE_zhegv( LAPACK_COL_MAJOR,
itype[i], lapack_const(vec), lapack_const(uplo[u]),
N, A1, LDA, B1, LDB, W1);
/* CHECK */
info_solution = check_solution(N, W1, W2, eps);
/* Check the orthogonality, reduction and the eigen solutions */
if (vec == PlasmaVec){
info_ortho = check_orthogonality(itype[i], uplo[u], N, Q, LDQ, Binit, B1, LDB, eps);
info_reduction = check_reduction(itype[i], uplo[u], N, W2, Ainit, LDA, Binit, LDB, Q, LDQ, eps );
}
if ( (info_ortho == 0) & (info_reduction == 0) & (info_solution == 0)) {
printf("***************************************************\n");
printf(" ---- TESTING ZHEGV (%s, %s) ...................... PASSED !\n", itypestr[i], uplostr[u]);
printf("***************************************************\n");
}
else {
printf("************************************************\n");
printf(" - TESTING ZHEGV (%s, %s) ... FAILED !\n", itypestr[i], uplostr[u]);
printf("************************************************\n");
}
}
}
PLASMA_Dealloc_Handle_Tile(&T);
free(A1);
free(A2);
free(B1);
free(B2);
free(Q);
free(Ainit);
free(Binit);
free(W1);
free(W2);
free(work);
return 0;
}
/*-------------------------------------------------------------------
* Check the orthogonality of Z
*/
static int check_orthogonality(int itype, int uplo, int N,
PLASMA_Complex64_t *Z, int LDZ,
PLASMA_Complex64_t *B, PLASMA_Complex64_t *CHOLB, int LDB,
double eps)
{
static PLASMA_Complex64_t zone = 1.0;
static PLASMA_Complex64_t mzone = -1.0;
static PLASMA_Complex64_t zzero = 0.0;
static double done = 1.0;
static double mdone = -1.0;
PLASMA_enum trans;
double normQ, result;
int info_ortho;
double *work = (double *)malloc(N*sizeof(double));
PLASMA_Complex64_t *TEMP = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *Id = (PLASMA_Complex64_t *) malloc(N*N*sizeof(PLASMA_Complex64_t));
char *str;
/* Build the idendity matrix */
LAPACKE_zlaset_work(LAPACK_COL_MAJOR, 'A', N, N, 0., 1., Id, N);
/* Perform orth test*/
if ( itype == 3 ) {
/*
* if ITYPE = 3, Z**H*inv(B)*Z = I.
* inv(B) = inv(L)**H * inv(L) or inv(U)*inv(U)**H
*/
str = "Z**H*inv(B)*Z";
if( uplo==PlasmaUpper ) {
trans = PlasmaConjTrans;
} else {
trans = PlasmaNoTrans;
}
/* Compute inv(L)*Z or inv(U)**H*Z */
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower),
N, N, Z, LDZ, TEMP, N);
cblas_ztrsm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans,
CblasNonUnit, N, N,
CBLAS_SADDR(zone), CHOLB, LDB,
TEMP, N);
/*
* Compute Z**H*inv(B)*Z-Id = (Z**H*inv(L)**H) * (inv(L)*Z) - Id
*
* Note: Z**H*inv(L)**H is the ConjTranspose of the previous result, so we use ZHERK
*/
cblas_zherk(CblasColMajor, (CBLAS_UPLO)uplo, CblasConjTrans,
N, N, done, TEMP, N, mdone, Id, N);
} else {
/*
* if ITYPE = 1 or 2, Z**H*B*Z = I;
*/
str = "Z**H*B*Z";
cblas_zhemm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N,
CBLAS_SADDR(zone), B, LDB,
Z, LDZ,
CBLAS_SADDR(zzero), TEMP, N);
cblas_zgemm(CblasColMajor, CblasConjTrans, CblasNoTrans, N, N, N,
CBLAS_SADDR(zone), Z, LDZ,
TEMP, N,
CBLAS_SADDR(mzone), Id , N);
}
normQ = LAPACKE_zlanhe_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), 'U', N, Id, N, work);
result = normQ / (N * eps);
printf(" ======================================================\n");
printf(" | Id-%s |_oo / (N*eps) : %15.3E \n",str, result );
printf(" ======================================================\n");
if ( isnan(result) || isinf(result) || (result > 60.0) ) {
printf("-- Orthogonality is suspicious ! \n");
info_ortho=1;
}
else {
printf("-- Orthogonality is CORRECT ! \n");
info_ortho=0;
}
free(work); free(Id); free(TEMP);
return info_ortho;
}
/*------------------------------------------------------------
* Check the reduction
*/
static int check_reduction(int itype, int uplo, int N, double *D,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *B, int LDB,
PLASMA_Complex64_t *Z, int LDZ,
double eps )
{
PLASMA_Complex64_t zone = 1.0;
PLASMA_Complex64_t zzero = 0.0;
PLASMA_Complex64_t mzone = -1.0;
double Anorm, Znorm, Rnorm, result;
int info_reduction;
int i;
char *str;
PLASMA_Complex64_t *TEMP = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *Residual = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));
double *work = (double *)malloc(N*sizeof(double));
if( itype == 1 ) {
/*
* | A Z - B Z D | / ( |A| |Z| n ulp )
*/
str = " A Z - B Z D ";
/* Compute TEMP = Z*D */
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower),
N, N, Z, LDZ, TEMP, N);
for (i=0; i<N; i++) {
cblas_zdscal(N, D[i], TEMP + i*N, 1);
}
/* Compute Residual = B*Z*D = B*TEMP */
cblas_zhemm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N,
CBLAS_SADDR(zone), B, LDB,
TEMP, N,
CBLAS_SADDR(zzero), Residual, N);
/* Compute A*Z - B*Z*D */
cblas_zhemm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N,
CBLAS_SADDR(zone), A, LDA,
Z, LDZ,
CBLAS_SADDR(mzone), Residual, N);
}
else if( itype == 2 ) {
/*
* | A B Z - Z D | / ( |A| |Z| n ulp )
*/
str = " A B Z - Z D ";
/* Compute Residual = Z*D */
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower),
N, N, Z, LDZ, Residual, N);
for (i=0; i<N; i++) {
cblas_zdscal(N, D[i], Residual + i*N, 1);
}
/* Compute TEMP = B*Z */
cblas_zhemm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N,
CBLAS_SADDR(zone), B, LDB,
Z, LDZ,
CBLAS_SADDR(zzero), TEMP, N);
/* Compute A*B*Z - Z*D = A*TEMP-Residual */
cblas_zhemm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N,
CBLAS_SADDR(zone), A, LDA,
TEMP, N,
CBLAS_SADDR(mzone), Residual, N);
} else {
/*
* | B A Z - Z D | / ( |A| |Z| n ulp )
*/
str = " B A Z - Z D ";
/* Compute Residual = Z*D */
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower),
N, N, Z, LDZ, Residual, N);
for (i=0; i<N; i++) {
cblas_zdscal(N, D[i], Residual + i*N, 1);
}
/* Compute TEMP = A*Z */
cblas_zhemm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N,
CBLAS_SADDR(zone), A, LDA,
Z, LDZ,
CBLAS_SADDR(zzero), TEMP, N);
/* Compute B*A*Z - Z*D = B*TEMP-Residual */
cblas_zhemm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N,
CBLAS_SADDR(zone), B, LDB,
TEMP, N,
CBLAS_SADDR(mzone), Residual, N);
}
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), N, N, Residual, N, work);
Anorm = LAPACKE_zlanhe_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), lapack_const(uplo), N, A, LDA, work);
Znorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), N, N, Z, LDZ, work);
result = Rnorm / ( Anorm * Znorm * N * eps);
printf(" ======================================================\n");
printf(" | %s |_oo/(|A|_oo.|Z|_oo.N.eps) : %15.3E \n", str, result );
printf(" ======================================================\n");
if ( isnan(result) || isinf(result) || (result > 60.0) ) {
printf("-- Reduction is suspicious ! \n");
info_reduction = 1;
}
else {
printf("-- Reduction is CORRECT ! \n");
info_reduction = 0;
}
free(TEMP); free(Residual); free(work);
return info_reduction;
}
/*--------------------------------------------------------------
* Check the solution
*/
static int check_solution(int N, double *E1, double *E2, double eps)
{
int info_solution, i;
double resid;
double maxtmp;
double maxel = fabs( fabs(E1[0]) - fabs(E2[0]) );
double maxeig = max( fabs(E1[0]), fabs(E2[0]) );
for (i=1; i<N; i++) {
resid = fabs(fabs(E1[i])-fabs(E2[i]));
maxtmp = max(fabs(E1[i]), fabs(E2[i]));
/* Update */
maxeig = max(maxtmp, maxeig);
maxel = max(resid, maxel );
}
maxel = maxel / (maxeig * N * eps);
printf(" ======================================================\n");
printf(" | D - eigcomputed | / (|D| * N * eps) : %15.3E \n", maxel );
printf(" ======================================================\n");
printf("============\n");
printf("Checking the eigenvalues of A\n");
if ( isnan(maxel) || isinf(maxel) || (maxel > 100) ) {
printf("-- The eigenvalues are suspicious ! \n");
info_solution = 1;
}
else{
printf("-- The eigenvalues are CORRECT ! \n");
info_solution = 0;
}
return info_solution;
}
| {
"alphanum_fraction": 0.4914059928,
"avg_line_length": 36.8567961165,
"ext": "c",
"hexsha": "1915a39a9be9ae65532dd206ebc2eea019ea8440",
"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": "testing/testing_zhegv.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": "testing/testing_zhegv.c",
"max_line_length": 123,
"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": "testing/testing_zhegv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4544,
"size": 15185
} |
/*
* Portions Copyright (c) 2010-Present Couchbase
* Portions Copyright (c) 2008 Sun Microsystems
*
* Use of this software is governed by the Apache License, Version 2.0 and
* BSD 3 Clause included in the files licenses/APL2.txt and
* licenses/BSD-3-Clause-Sun-Microsystems.txt
*/
#pragma once
#include "dockey.h"
#include <gsl/gsl-lite.hpp>
#include <memcached/vbucket.h>
#include <platform/socket.h>
#ifndef WIN32
#include <arpa/inet.h>
#endif
#include <cstdint>
#include <stdexcept>
#include <string>
namespace cb::durability {
enum class Level : uint8_t;
} // namespace cb::durability
/**
* \addtogroup Protocol
* @{
*/
/**
* This file contains definitions of the constants and packet formats
* defined in the binary specification. Please note that you _MUST_ remember
* to convert each multibyte field to / from network byte order to / from
* host order.
*/
#include <mcbp/protocol/datatype.h>
#include <mcbp/protocol/dcp_stream_end_status.h>
#include <mcbp/protocol/feature.h>
#include <mcbp/protocol/magic.h>
#include <mcbp/protocol/opcode.h>
#include <mcbp/protocol/request.h>
#include <mcbp/protocol/response.h>
#include <mcbp/protocol/status.h>
// For backward compatibility with old sources
/**
* Definition of the header structure for a request packet.
* See section 2
*/
union protocol_binary_request_header {
cb::mcbp::Request request;
uint8_t bytes[24];
};
/**
* Definition of the header structure for a response packet.
* See section 2
*/
union protocol_binary_response_header {
cb::mcbp::Response response;
uint8_t bytes[24];
};
/**
* Definition of a request-packet containing no extras
*/
typedef union {
struct {
protocol_binary_request_header header;
} message;
uint8_t bytes[sizeof(protocol_binary_request_header)];
} protocol_binary_request_no_extras;
/**
* Definition of a response-packet containing no extras
*/
typedef union {
struct {
protocol_binary_response_header header;
} message;
uint8_t bytes[sizeof(protocol_binary_response_header)];
} protocol_binary_response_no_extras;
/**
* Definition of the packet used by set, add and replace
* See section 4
*/
namespace cb::mcbp::request {
#pragma pack(1)
class MutationPayload {
public:
/// The memcached core keep the flags stored in network byte order
/// internally as it does not use them for anything else than sending
/// them back to the client
uint32_t getFlagsInNetworkByteOrder() const {
return flags;
}
uint32_t getFlags() const {
return ntohl(flags);
}
void setFlags(uint32_t flags) {
MutationPayload::flags = htonl(flags);
}
uint32_t getExpiration() const {
return ntohl(expiration);
}
void setExpiration(uint32_t expiration) {
MutationPayload::expiration = htonl(expiration);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t flags = 0;
uint32_t expiration = 0;
};
static_assert(sizeof(MutationPayload) == 8, "Unexpected struct size");
class ArithmeticPayload {
public:
uint64_t getDelta() const {
return ntohll(delta);
}
void setDelta(uint64_t delta) {
ArithmeticPayload::delta = htonll(delta);
}
uint64_t getInitial() const {
return ntohll(initial);
}
void setInitial(uint64_t initial) {
ArithmeticPayload::initial = htonll(initial);
}
uint32_t getExpiration() const {
return ntohl(expiration);
}
void setExpiration(uint32_t expiration) {
ArithmeticPayload::expiration = htonl(expiration);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
private:
uint64_t delta = 0;
uint64_t initial = 0;
uint32_t expiration = 0;
};
static_assert(sizeof(ArithmeticPayload) == 20, "Unexpected struct size");
class DeprecatedSetClusterConfigPayload {
public:
int32_t getRevision() const {
return ntohl(revision);
}
void setRevision(int32_t rev) {
revision = htonl(rev);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
int32_t revision{};
};
static_assert(sizeof(DeprecatedSetClusterConfigPayload) == 4,
"Unexpected struct size");
class SetClusterConfigPayload {
public:
int64_t getEpoch() const {
return ntohll(epoch);
}
void setEpoch(int64_t ep) {
epoch = htonll(ep);
}
int64_t getRevision() const {
return ntohll(revision);
}
void setRevision(int64_t rev) {
revision = htonll(rev);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
int64_t epoch{0};
int64_t revision{0};
};
static_assert(sizeof(SetClusterConfigPayload) == 16, "Unexpected struct size");
class VerbosityPayload {
public:
uint32_t getLevel() const {
return ntohl(level);
}
void setLevel(uint32_t level) {
VerbosityPayload::level = htonl(level);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t level = 0;
};
static_assert(sizeof(VerbosityPayload) == 4, "Unexpected size");
class TouchPayload {
public:
uint32_t getExpiration() const {
return ntohl(expiration);
}
void setExpiration(uint32_t expiration) {
TouchPayload::expiration = htonl(expiration);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t expiration = 0;
};
static_assert(sizeof(TouchPayload) == 4, "Unexpected size");
using GatPayload = TouchPayload;
using GetLockedPayload = TouchPayload;
class SetCtrlTokenPayload {
public:
uint64_t getCas() const {
return ntohll(cas);
}
void setCas(uint64_t cas) {
SetCtrlTokenPayload::cas = htonll(cas);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t cas = 0;
};
static_assert(sizeof(SetCtrlTokenPayload) == 8, "Unexpected size");
#pragma pack()
} // namespace cb::mcbp::request
/**
* Definitions for extended (flexible) metadata
*
* @1: Flex Code to identify the number of extended metadata fields
* @2: Size of the Flex Code, set to 1 byte
* @3: Current size of extended metadata
*/
typedef enum {
FLEX_META_CODE = 0x01,
FLEX_DATA_OFFSET = 1,
EXT_META_LEN = 1
} protocol_binary_flexmeta;
/**
* Definitions of sub-document path flags (this is a bitmap)
*/
typedef enum : uint8_t {
/** No flags set */
SUBDOC_FLAG_NONE = 0x0,
/** (Mutation) Should non-existent intermediate paths be created? */
SUBDOC_FLAG_MKDIR_P = 0x01,
/**
* 0x02 is unused
*/
/**
* If set, the path refers to an Extended Attribute (XATTR).
* If clear, the path refers to a path inside the document body.
*/
SUBDOC_FLAG_XATTR_PATH = 0x04,
/**
* 0x08 is unused
*/
/**
* Expand macro values inside extended attributes. The request is
* invalid if this flag is set without SUBDOC_FLAG_XATTR_PATH being
* set.
*/
SUBDOC_FLAG_EXPAND_MACROS = 0x10,
} protocol_binary_subdoc_flag;
namespace mcbp::subdoc {
/**
* Definitions of sub-document doc flags (this is a bitmap).
*/
enum class doc_flag : uint8_t {
None = 0x0,
/**
* (Mutation) Create the document if it does not exist. Implies
* SUBDOC_FLAG_MKDIR_P and Set (upsert) mutation semantics. Not valid
* with Add.
*/
Mkdoc = 0x1,
/**
* (Mutation) Add the document only if it does not exist. Implies
* SUBDOC_FLAG_MKDIR_P. Not valid with Mkdoc.
*/
Add = 0x02,
/**
* Allow access to XATTRs for deleted documents (instead of
* returning KEY_ENOENT). The result of mutations on a deleted
* document is still a deleted document unless ReviveDocument is
* being used.
*/
AccessDeleted = 0x04,
/**
* (Mutation) Used with Mkdoc / Add; if the document does not exist then
* create it in the Deleted state, instead of the normal Alive state.
* Not valid unless Mkdoc or Add specified.
*/
CreateAsDeleted = 0x08,
/**
* (Mutation) If the document exists and isn't deleted the operation
* will fail with SubdocCanOnlyReviveDeletedDocuments. If the input
* document _is_ deleted the result of the operation will store the
* document as a "live" document instead of a deleted document.
*/
ReviveDocument = 0x10,
};
/**
* Used for validation at parsing the doc-flags.
* The value depends on how many bits the doc_flag enum is actually using and
* must change accordingly.
*/
static constexpr uint8_t extrasDocFlagMask = 0xe0;
} // namespace mcbp::subdoc
/**
* Definition of the packet used by SUBDOCUMENT single-path commands.
*
* The path, which is always required, is in the Body, after the Key.
*
* Header: 24 @0: <protocol_binary_request_header>
* Extras:
* Sub-document pathlen 2 @24: <variable>
* Sub-document flags 1 @26: <protocol_binary_subdoc_flag>
* Expiry 4 @27: (Optional) Mutations only. The
* ttl
* Sub-document doc flags 1 @27: (Optional) @31 if expiry is
* set. Note these are the
* subdocument doc flags not the
* flag section in the document.
* Body:
* Key keylen @27: <variable>
* Path pathlen @27+keylen: <variable>
* Value to insert/replace
* vallen-keylen-pathlen @27+keylen+pathlen: [variable]
*/
typedef union {
struct {
protocol_binary_request_header header;
struct {
uint16_t pathlen; // Length in bytes of the sub-doc path.
uint8_t subdoc_flags; // See protocol_binary_subdoc_flag
/* uint32_t expiry (optional for mutations only - present
if extlen == 7 or extlen == 8) */
/* uint8_t doc_flags (optional - present if extlen == 4 or
extlen == 8) Note these are the
subdocument doc flags not the flag
\section in the document. */
} extras;
} message;
uint8_t bytes[sizeof(protocol_binary_request_header) + 3];
} protocol_binary_request_subdocument;
/** Definition of the packet used by SUBDOCUMENT responses.
*/
typedef union {
struct {
protocol_binary_response_header header;
} message;
uint8_t bytes[sizeof(protocol_binary_response_header)];
} protocol_binary_response_subdocument;
/**
* Definition of the request packets used by SUBDOCUMENT multi-path commands.
*
* Multi-path sub-document commands differ from single-path in that they
* encode a series of multiple paths to operate on (from a single key).
* There are two multi-path commands - MULTI_LOOKUP and MULTI_MUTATION.
* - MULTI_LOOKUP consists of variable number of subdoc lookup commands
* (SUBDOC_GET or SUBDOC_EXISTS).
* - MULTI_MUTATION consists of a variable number of subdoc mutation
* commands (i.e. all subdoc commands apart from
* SUBDOC_{GET,EXISTS}).
*
* Each path to be operated on is specified by an Operation Spec, which are
* contained in the body. This defines the opcode, path, and value
* (for mutations).
*
* A maximum of MULTI_MAX_PATHS paths (operations) can be encoded in a
* single multi-path command.
*
* SUBDOC_MULTI_LOOKUP:
* Header: 24 @0: <protocol_binary_request_header>
* Extras: 0 or 1 @24: (optional) doc_flags. Note these are
* the subdocument doc flags not the flag
* section in the document.
* Body: <variable> @24:
* Key keylen @24: <variable>
* 1..MULTI_MAX_PATHS [Lookup Operation Spec]
*
* Lookup Operation Spec:
* 1 @0 : Opcode
* 1 @1 : Flags
* 2 @2 : Path Length
* pathlen @4 : Path
*/
static const int PROTOCOL_BINARY_SUBDOC_MULTI_MAX_PATHS = 16;
typedef struct {
cb::mcbp::ClientOpcode opcode;
uint8_t flags;
uint16_t pathlen;
/* uint8_t path[pathlen] */
} protocol_binary_subdoc_multi_lookup_spec;
typedef protocol_binary_request_no_extras
protocol_binary_request_subdocument_multi_lookup;
/*
*
* SUBDOC_MULTI_MUTATION
* Header: 24 @0: <protocol_binary_request_header>
* Extras: 0 OR 4 @24: (optional) expiration
* 0 OR 1 @24: (optional) doc_flags. Note these are
* the subdocument doc flags not the
* flag section in the document.
* Body: variable @24 + extlen:
* Key keylen @24: <variable>
* 1..MULTI_MAX_PATHS [Mutation Operation Spec]
*
* Mutation Operation Spec:
* 1 @0 : Opcode
* 1 @1 : Flags
* 2 @2 : Path Length
* 4 @4 : Value Length
* pathlen @8 : Path
* vallen @8+pathlen : Value
*/
typedef struct {
cb::mcbp::ClientOpcode opcode;
uint8_t flags;
uint16_t pathlen;
uint32_t valuelen;
/* uint8_t path[pathlen] */
/* uint8_t value[valuelen] */
} protocol_binary_subdoc_multi_mutation_spec;
typedef protocol_binary_request_no_extras
protocol_binary_request_subdocument_multi_mutation;
/**
* Definition of the response packets used by SUBDOCUMENT multi-path
* commands.
*
* SUBDOC_MULTI_LOOKUP - Body consists of a series of lookup_result structs,
* one per lookup_spec in the request.
*
* Lookup Result:
* 2 @0 : status
* 4 @2 : resultlen
* resultlen @6 : result
*/
typedef struct {
protocol_binary_request_header header;
/* Variable-length 1..PROTOCOL_BINARY_SUBDOC_MULTI_MAX_PATHS */
protocol_binary_subdoc_multi_lookup_spec body[1];
} protocol_binary_response_subdoc_multi_lookup;
/**
* SUBDOC_MULTI_MUTATION response
*
* Extras is either 0 or 16 if MUTATION_SEQNO is enabled.
*
* Body consists of a variable number of subdoc_multi_mutation_result_spec
* structs:
*
* On success (header.status == SUCCESS), zero or more result specs, one for
* each multi_mutation_spec which wishes to return a value.
*
* Mutation Result (success):
* [0..N] of:
* 1 @0 : index - Index of multi_mutation spec this result
* corresponds to.
* 2 @1 : status - Status of the mutation (should always
* be SUCCESS for successful multi-mutation
* requests).
* 4 @3 : resultlen - Result value length
* resultlen @7 : Value payload
*
* On one of more of the mutation specs failing, there is exactly one
* result spec, specifying the index and status code of the first failing
* mutation spec.
*
* Mutation Result (failure):
* 1 of:
* 1 @0 : index - Index of multi_mutation spec this result
* corresponds to.
* 2 @1 : status - Status of the mutation (should always be
* !SUCCESS for failures).
*
* (Note: On failure the multi_mutation_result_spec only includes the
* first two fields).
*/
typedef union {
struct {
protocol_binary_response_header header;
} message;
uint8_t bytes[sizeof(protocol_binary_response_header)];
} protocol_binary_response_subdoc_multi_mutation;
/* DCP related stuff */
namespace cb::mcbp {
namespace request {
#pragma pack(1)
class DcpOpenPayload {
public:
uint32_t getSeqno() const {
return ntohl(seqno);
}
void setSeqno(uint32_t seqno) {
DcpOpenPayload::seqno = htonl(seqno);
}
uint32_t getFlags() const {
return ntohl(flags);
}
void setFlags(uint32_t flags) {
DcpOpenPayload::flags = htonl(flags);
}
// Flags is a bitmask where the following values are used:
/**
* If set a Producer connection should be opened, if clear a Consumer
* connection should be opened.
*/
static const uint32_t Producer = 1;
/// Invalid - should not be set (Previously the Notifier flag)
static const uint32_t Invalid = 2;
/**
* Indicate that the server include the documents' XATTRs
* within mutation and deletion bodies.
*/
static const uint32_t IncludeXattrs = 4;
/**
* Indicate that the server should strip off the values (note,
* if you add INCLUDE_XATTR those will be present)
*/
static const uint32_t NoValue = 8;
static const uint32_t Unused = 16;
/**
* Request that DCP delete message include the time the a delete was
* persisted. This only applies to deletes being backfilled from storage,
* in-memory deletes will have a delete time of 0
*/
static const uint32_t IncludeDeleteTimes = 32;
/**
* Indicates that the server should strip off the values, but return the
* datatype of the underlying document (note, if you add
* INCLUDE_XATTR those will be present).
* Note this differs from DCP_OPEN_NO_VALUE in that the datatype field will
* contain the underlying datatype of the document; not the datatype of the
* transmitted payload.
* This flag can be used to obtain the full, original datatype for a
* document without the user's value. Not valid to specify with
* DCP_OPEN_NO_VALUE.
*/
static const uint32_t NoValueWithUnderlyingDatatype = 64;
/// Requst PiTR for the connection (only legal for Producers)
static const uint32_t PiTR = 128;
/**
* Indicates that the server includes the document UserXattrs within
* deletion values.
*/
static const uint32_t IncludeDeletedUserXattrs = 256;
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t seqno = 0;
uint32_t flags = 0;
};
static_assert(sizeof(DcpOpenPayload) == 8, "Unexpected struct size");
} // namespace request
namespace response {
class DcpAddStreamPayload {
public:
uint32_t getOpaque() const {
return ntohl(opaque);
}
void setOpaque(uint32_t opaque) {
DcpAddStreamPayload::opaque = htonl(opaque);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t opaque = 0;
};
static_assert(sizeof(DcpAddStreamPayload) == 4, "Unexpected struct size");
} // namespace response
namespace request {
class DcpAddStreamPayload {
public:
uint32_t getFlags() const {
return ntohl(flags);
}
void setFlags(uint32_t flags) {
DcpAddStreamPayload::flags = htonl(flags);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
/*
* The following flags are defined
*/
#define DCP_ADD_STREAM_FLAG_TAKEOVER 1
#define DCP_ADD_STREAM_FLAG_DISKONLY 2
#define DCP_ADD_STREAM_FLAG_LATEST 4
/**
* This flag is not used anymore, and should NOT be
* set. It is replaced by DCP_OPEN_NO_VALUE.
*/
#define DCP_ADD_STREAM_FLAG_NO_VALUE 8
/**
* Indicate the server to add stream only if the vbucket
* is active.
* If the vbucket is not active, the stream request fails with
* error cb::engine_errc::not_my_vbucket
*/
#define DCP_ADD_STREAM_ACTIVE_VB_ONLY 16
/**
* Indicate the server to check for vb_uuid match even at start_seqno 0 before
* adding the stream successfully.
* If the flag is set and there is a vb_uuid mismatch at start_seqno 0, then
* the server returns cb::engine_errc::rollback error.
*/
#define DCP_ADD_STREAM_STRICT_VBUUID 32
uint32_t flags = 0;
};
static_assert(sizeof(DcpAddStreamPayload) == 4, "Unexpected struct size");
class DcpStreamReqPayload {
public:
uint32_t getFlags() const {
return ntohl(flags);
}
void setFlags(uint32_t flags) {
DcpStreamReqPayload::flags = htonl(flags);
}
uint32_t getReserved() const {
return ntohl(reserved);
}
void setReserved(uint32_t reserved) {
DcpStreamReqPayload::reserved = htonl(reserved);
}
uint64_t getStartSeqno() const {
return ntohll(start_seqno);
}
void setStartSeqno(uint64_t start_seqno) {
DcpStreamReqPayload::start_seqno = htonll(start_seqno);
}
uint64_t getEndSeqno() const {
return ntohll(end_seqno);
}
void setEndSeqno(uint64_t end_seqno) {
DcpStreamReqPayload::end_seqno = htonll(end_seqno);
}
uint64_t getVbucketUuid() const {
return ntohll(vbucket_uuid);
}
void setVbucketUuid(uint64_t vbucket_uuid) {
DcpStreamReqPayload::vbucket_uuid = htonll(vbucket_uuid);
}
uint64_t getSnapStartSeqno() const {
return ntohll(snap_start_seqno);
}
void setSnapStartSeqno(uint64_t snap_start_seqno) {
DcpStreamReqPayload::snap_start_seqno = htonll(snap_start_seqno);
}
uint64_t getSnapEndSeqno() const {
return ntohll(snap_end_seqno);
}
void setSnapEndSeqno(uint64_t snap_end_seqno) {
DcpStreamReqPayload::snap_end_seqno = htonll(snap_end_seqno);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t flags = 0;
uint32_t reserved = 0;
uint64_t start_seqno = 0;
uint64_t end_seqno = 0;
uint64_t vbucket_uuid = 0;
uint64_t snap_start_seqno = 0;
uint64_t snap_end_seqno = 0;
};
static_assert(sizeof(DcpStreamReqPayload) == 48, "Unexpected struct size");
class DcpStreamEndPayload {
public:
DcpStreamEndStatus getStatus() const {
return DcpStreamEndStatus(ntohl(status));
}
void setStatus(DcpStreamEndStatus status) {
DcpStreamEndPayload::status = htonl(uint32_t(status));
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
/**
* Note the following is maintained in network/big endian
* see protocol/dcp_stream_end_status.h for values
*/
uint32_t status = 0;
};
static_assert(sizeof(DcpStreamEndPayload) == 4, "Unexpected struct size");
class DcpSnapshotMarkerV1Payload {
public:
uint64_t getStartSeqno() const {
return ntohll(start_seqno);
}
void setStartSeqno(uint64_t start_seqno) {
DcpSnapshotMarkerV1Payload::start_seqno = htonll(start_seqno);
}
uint64_t getEndSeqno() const {
return ntohll(end_seqno);
}
void setEndSeqno(uint64_t end_seqno) {
DcpSnapshotMarkerV1Payload::end_seqno = htonll(end_seqno);
}
uint32_t getFlags() const {
return ntohl(flags);
}
void setFlags(uint32_t flags) {
DcpSnapshotMarkerV1Payload::flags = htonl(flags);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t start_seqno = 0;
uint64_t end_seqno = 0;
uint32_t flags = 0;
};
static_assert(sizeof(DcpSnapshotMarkerV1Payload) == 20,
"Unexpected struct size");
enum class DcpSnapshotMarkerFlag : uint32_t {
Memory = 0x01,
Disk = 0x02,
Checkpoint = 0x04,
Acknowledge = 0x08
};
enum class DcpSnapshotMarkerV2xVersion : uint8_t { Zero = 0, One = 1 };
// Version 2.x
class DcpSnapshotMarkerV2xPayload {
public:
explicit DcpSnapshotMarkerV2xPayload(DcpSnapshotMarkerV2xVersion v)
: version(v) {
}
DcpSnapshotMarkerV2xVersion getVersion() const {
return version;
}
void setVersion(DcpSnapshotMarkerV2xVersion v) {
version = v;
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
DcpSnapshotMarkerV2xVersion version{DcpSnapshotMarkerV2xVersion::Zero};
};
static_assert(sizeof(DcpSnapshotMarkerV2xPayload) == 1,
"Unexpected struct size");
class DcpSnapshotMarkerV2_0Value : public DcpSnapshotMarkerV1Payload {
public:
uint64_t getMaxVisibleSeqno() const {
return ntohll(maxVisibleSeqno);
}
void setMaxVisibleSeqno(uint64_t maxVisibleSeqno) {
DcpSnapshotMarkerV2_0Value::maxVisibleSeqno = htonll(maxVisibleSeqno);
}
uint64_t getHighCompletedSeqno() const {
return ntohll(highCompletedSeqno);
}
void setHighCompletedSeqno(uint64_t highCompletedSeqno) {
DcpSnapshotMarkerV2_0Value::highCompletedSeqno =
htonll(highCompletedSeqno);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t maxVisibleSeqno{0};
uint64_t highCompletedSeqno{0};
};
static_assert(sizeof(DcpSnapshotMarkerV2_0Value) == 36,
"Unexpected struct size");
class DcpSnapshotMarkerV2_1Value : public DcpSnapshotMarkerV2_0Value {
public:
uint64_t getTimestamp() const {
return ntohll(timestamp);
}
void setTimestamp(uint64_t value) {
timestamp = htonll(value);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t timestamp{0};
};
static_assert(sizeof(DcpSnapshotMarkerV2_1Value) == 44,
"Unexpected struct size");
class DcpMutationPayload {
public:
DcpMutationPayload() = default;
DcpMutationPayload(uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t flags,
uint32_t expiration,
uint32_t lock_time,
uint8_t nru)
: by_seqno(htonll(by_seqno)),
rev_seqno(htonll(rev_seqno)),
flags(flags),
expiration(htonl(expiration)),
lock_time(htonl(lock_time)),
nru(nru) {
}
uint64_t getBySeqno() const {
return ntohll(by_seqno);
}
void setBySeqno(uint64_t by_seqno) {
DcpMutationPayload::by_seqno = htonll(by_seqno);
}
uint64_t getRevSeqno() const {
return ntohll(rev_seqno);
}
void setRevSeqno(uint64_t rev_seqno) {
DcpMutationPayload::rev_seqno = htonll(rev_seqno);
}
uint32_t getFlags() const {
return flags;
}
void setFlags(uint32_t flags) {
DcpMutationPayload::flags = flags;
}
uint32_t getExpiration() const {
return ntohl(expiration);
}
void setExpiration(uint32_t expiration) {
DcpMutationPayload::expiration = htonl(expiration);
}
uint32_t getLockTime() const {
return ntohl(lock_time);
}
void setLockTime(uint32_t lock_time) {
DcpMutationPayload::lock_time = htonl(lock_time);
}
uint16_t getNmeta() const {
return ntohs(nmeta);
}
uint8_t getNru() const {
return nru;
}
void setNru(uint8_t nru) {
DcpMutationPayload::nru = nru;
}
std::string_view getBuffer() const {
return {reinterpret_cast<const char*>(this), sizeof(*this)};
}
protected:
uint64_t by_seqno = 0;
uint64_t rev_seqno = 0;
uint32_t flags = 0;
uint32_t expiration = 0;
uint32_t lock_time = 0;
/// We don't set this anymore, but old servers may send it to us
/// but we'll ignore it
const uint16_t nmeta = 0;
uint8_t nru = 0;
};
static_assert(sizeof(DcpMutationPayload) == 31, "Unexpected struct size");
class DcpDeletionV1Payload {
public:
DcpDeletionV1Payload(uint64_t _by_seqno, uint64_t _rev_seqno)
: by_seqno(htonll(_by_seqno)), rev_seqno(htonll(_rev_seqno)) {
}
uint64_t getBySeqno() const {
return ntohll(by_seqno);
}
void setBySeqno(uint64_t by_seqno) {
DcpDeletionV1Payload::by_seqno = htonll(by_seqno);
}
uint64_t getRevSeqno() const {
return ntohll(rev_seqno);
}
void setRevSeqno(uint64_t rev_seqno) {
DcpDeletionV1Payload::rev_seqno = htonll(rev_seqno);
}
uint16_t getNmeta() const {
return ntohs(nmeta);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t by_seqno = 0;
uint64_t rev_seqno = 0;
const uint16_t nmeta = 0;
};
static_assert(sizeof(DcpDeletionV1Payload) == 18, "Unexpected struct size");
class DcpDeleteRequestV1 {
public:
DcpDeleteRequestV1(uint32_t opaque,
Vbid vbucket,
uint64_t cas,
uint16_t keyLen,
uint32_t valueLen,
protocol_binary_datatype_t datatype,
uint64_t bySeqno,
uint64_t revSeqno)
: req{}, body(bySeqno, revSeqno) {
req.setMagic(cb::mcbp::Magic::ClientRequest);
req.setOpcode(cb::mcbp::ClientOpcode::DcpDeletion);
req.setExtlen(gsl::narrow<uint8_t>(sizeof(body)));
req.setKeylen(keyLen);
req.setBodylen(gsl::narrow<uint32_t>(sizeof(body) + keyLen + valueLen));
req.setOpaque(opaque);
req.setVBucket(vbucket);
req.setCas(cas);
req.setDatatype(cb::mcbp::Datatype(datatype));
}
protected:
cb::mcbp::Request req;
DcpDeletionV1Payload body;
};
static_assert(sizeof(DcpDeleteRequestV1) == 42, "Unexpected struct size");
class DcpDeletionV2Payload {
public:
DcpDeletionV2Payload(uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time)
: by_seqno(htonll(by_seqno)),
rev_seqno(htonll(rev_seqno)),
delete_time(htonl(delete_time)) {
}
uint64_t getBySeqno() const {
return ntohll(by_seqno);
}
void setBySeqno(uint64_t by_seqno) {
DcpDeletionV2Payload::by_seqno = htonll(by_seqno);
}
uint64_t getRevSeqno() const {
return ntohll(rev_seqno);
}
void setRevSeqno(uint64_t rev_seqno) {
DcpDeletionV2Payload::rev_seqno = htonll(rev_seqno);
}
uint32_t getDeleteTime() const {
return ntohl(delete_time);
}
void setDeleteTime(uint32_t delete_time) {
DcpDeletionV2Payload::delete_time = htonl(delete_time);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t by_seqno = 0;
uint64_t rev_seqno = 0;
uint32_t delete_time = 0;
const uint8_t unused = 0;
};
static_assert(sizeof(DcpDeletionV2Payload) == 21, "Unexpected struct size");
class DcpDeleteRequestV2 {
public:
DcpDeleteRequestV2(uint32_t opaque,
Vbid vbucket,
uint64_t cas,
uint16_t keyLen,
uint32_t valueLen,
protocol_binary_datatype_t datatype,
uint64_t bySeqno,
uint64_t revSeqno,
uint32_t deleteTime)
: req{}, body(bySeqno, revSeqno, deleteTime) {
req.setMagic(cb::mcbp::Magic::ClientRequest);
req.setOpcode(cb::mcbp::ClientOpcode::DcpDeletion);
req.setExtlen(gsl::narrow<uint8_t>(sizeof(body)));
req.setKeylen(keyLen);
req.setBodylen(gsl::narrow<uint32_t>(sizeof(body) + keyLen + valueLen));
req.setOpaque(opaque);
req.setVBucket(vbucket);
req.setCas(cas);
req.setDatatype(cb::mcbp::Datatype(datatype));
}
protected:
cb::mcbp::Request req;
DcpDeletionV2Payload body;
};
static_assert(sizeof(DcpDeleteRequestV2) == 45, "Unexpected struct size");
class DcpExpirationPayload {
public:
DcpExpirationPayload() = default;
DcpExpirationPayload(uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time)
: by_seqno(htonll(by_seqno)),
rev_seqno(htonll(rev_seqno)),
delete_time(htonl(delete_time)) {
}
uint64_t getBySeqno() const {
return ntohll(by_seqno);
}
void setBySeqno(uint64_t by_seqno) {
DcpExpirationPayload::by_seqno = htonll(by_seqno);
}
uint64_t getRevSeqno() const {
return ntohll(rev_seqno);
}
void setRevSeqno(uint64_t rev_seqno) {
DcpExpirationPayload::rev_seqno = htonll(rev_seqno);
}
uint32_t getDeleteTime() const {
return ntohl(delete_time);
}
void setDeleteTime(uint32_t delete_time) {
DcpExpirationPayload::delete_time = htonl(delete_time);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t by_seqno = 0;
uint64_t rev_seqno = 0;
uint32_t delete_time = 0;
};
static_assert(sizeof(DcpExpirationPayload) == 20, "Unexpected struct size");
class DcpSetVBucketState {
public:
uint8_t getState() const {
return state;
}
void setState(uint8_t state) {
DcpSetVBucketState::state = state;
}
bool isValid() const {
return is_valid_vbucket_state_t(state);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint8_t state;
};
static_assert(sizeof(DcpSetVBucketState) == 1, "Unexpected struct size");
class DcpBufferAckPayload {
public:
uint32_t getBufferBytes() const {
return ntohl(buffer_bytes);
}
void setBufferBytes(uint32_t buffer_bytes) {
DcpBufferAckPayload::buffer_bytes = htonl(buffer_bytes);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t buffer_bytes = 0;
};
static_assert(sizeof(DcpBufferAckPayload) == 4, "Unexpected struct size");
enum class DcpOsoSnapshotFlags : uint32_t {
Start = 0x01,
End = 0x02,
};
class DcpOsoSnapshotPayload {
public:
explicit DcpOsoSnapshotPayload(uint32_t flags) : flags(htonl(flags)) {
}
uint32_t getFlags() const {
return ntohl(flags);
}
void setFlags(uint32_t flags) {
DcpOsoSnapshotPayload::flags = htonl(flags);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t flags = 0;
};
static_assert(sizeof(DcpOsoSnapshotPayload) == 4, "Unexpected struct size");
class DcpSeqnoAdvancedPayload {
public:
explicit DcpSeqnoAdvancedPayload(uint64_t seqno) : by_seqno(htonll(seqno)) {
}
[[nodiscard]] uint64_t getSeqno() const {
return ntohll(by_seqno);
}
void setSeqno(uint64_t seqno) {
DcpSeqnoAdvancedPayload::by_seqno = htonll(seqno);
}
[[nodiscard]] cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t by_seqno = 0;
};
static_assert(sizeof(DcpSeqnoAdvancedPayload) == 8, "Unexpected struct size");
#pragma pack()
} // namespace request
} // namespace cb::mcbp
/**
* Events that the system may send
*/
namespace mcbp::systemevent {
enum class id : uint32_t {
CreateCollection = 0,
DeleteCollection = 1,
FlushCollection = 2,
CreateScope = 3,
DropScope = 4
};
enum class version : uint8_t { version0 = 0, version1 = 1 };
} // namespace mcbp::systemevent
namespace cb::mcbp::request {
#pragma pack(1)
class DcpSystemEventPayload {
public:
DcpSystemEventPayload() = default;
DcpSystemEventPayload(uint64_t by_seqno,
::mcbp::systemevent::id event,
::mcbp::systemevent::version version)
: by_seqno(htonll(by_seqno)),
event(htonl(static_cast<uint32_t>(event))),
version(static_cast<uint8_t>(version)) {
}
uint64_t getBySeqno() const {
return ntohll(by_seqno);
}
void setBySeqno(uint64_t by_seqno) {
DcpSystemEventPayload::by_seqno = htonll(by_seqno);
}
uint32_t getEvent() const {
return ntohl(event);
}
void setEvent(uint32_t event) {
DcpSystemEventPayload::event = htonl(event);
}
uint8_t getVersion() const {
return version;
}
void setVersion(uint8_t version) {
DcpSystemEventPayload::version = version;
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
/**
* Validate that the uint32_t event field represents a valid systemevent::id
*/
bool isValidEvent() const {
using ::mcbp::systemevent::id;
switch (id(getEvent())) {
case id::CreateCollection:
case id::DeleteCollection:
case id::FlushCollection:
case id::CreateScope:
case id::DropScope:
return true;
}
return false;
}
/**
* Validate that the uint8_t version represents a valid systemevent::version
*/
bool isValidVersion() const {
using ::mcbp::systemevent::version;
switch (version(getVersion())) {
case version::version0:
case version::version1:
return true;
}
return false;
}
protected:
uint64_t by_seqno = 0;
uint32_t event = 0;
uint8_t version = 0;
};
static_assert(sizeof(DcpSystemEventPayload) == 13, "Unexpected struct size");
class DcpPreparePayload {
public:
DcpPreparePayload() = default;
DcpPreparePayload(uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t flags,
uint32_t expiration,
uint32_t lock_time,
uint8_t nru)
: by_seqno(htonll(by_seqno)),
rev_seqno(htonll(rev_seqno)),
flags(flags),
expiration(htonl(expiration)),
lock_time(htonl(lock_time)),
nru(nru) {
}
uint64_t getBySeqno() const {
return ntohll(by_seqno);
}
void setBySeqno(uint64_t by_seqno) {
DcpPreparePayload::by_seqno = htonll(by_seqno);
}
uint64_t getRevSeqno() const {
return ntohll(rev_seqno);
}
void setRevSeqno(uint64_t rev_seqno) {
DcpPreparePayload::rev_seqno = htonll(rev_seqno);
}
uint32_t getFlags() const {
return flags;
}
void setFlags(uint32_t flags) {
DcpPreparePayload::flags = flags;
}
uint32_t getExpiration() const {
return ntohl(expiration);
}
void setExpiration(uint32_t expiration) {
DcpPreparePayload::expiration = htonl(expiration);
}
uint32_t getLockTime() const {
return ntohl(lock_time);
}
void setLockTime(uint32_t lock_time) {
DcpPreparePayload::lock_time = htonl(lock_time);
}
uint8_t getNru() const {
return nru;
}
void setNru(uint8_t nru) {
DcpPreparePayload::nru = nru;
}
uint8_t getDeleted() const {
return deleted;
}
void setDeleted(uint8_t deleted) {
DcpPreparePayload::deleted = deleted;
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
cb::durability::Level getDurabilityLevel() const;
void setDurabilityLevel(cb::durability::Level level);
protected:
uint64_t by_seqno = 0;
uint64_t rev_seqno = 0;
uint32_t flags = 0;
uint32_t expiration = 0;
uint32_t lock_time = 0;
uint8_t nru = 0;
// set to true if this is a document deletion
uint8_t deleted = 0;
uint8_t durability_level = 0;
};
static_assert(sizeof(DcpPreparePayload) == 31, "Unexpected struct size");
class DcpSeqnoAcknowledgedPayload {
public:
explicit DcpSeqnoAcknowledgedPayload(uint64_t prepared)
: prepared_seqno(htonll(prepared)) {
}
uint64_t getPreparedSeqno() const {
return ntohll(prepared_seqno);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
// Stored in network order.
uint64_t prepared_seqno = 0;
};
static_assert(sizeof(DcpSeqnoAcknowledgedPayload) == 8,
"Unexpected struct size");
class DcpCommitPayload {
public:
DcpCommitPayload(uint64_t prepared, uint64_t committed)
: prepared_seqno(htonll(prepared)), commit_seqno(htonll(committed)) {
}
uint64_t getPreparedSeqno() const {
return ntohll(prepared_seqno);
}
void setPreparedSeqno(uint64_t prepared_seqno) {
DcpCommitPayload::prepared_seqno = htonll(prepared_seqno);
}
uint64_t getCommitSeqno() const {
return ntohll(commit_seqno);
}
void setCommitSeqno(uint64_t commit_seqno) {
DcpCommitPayload::commit_seqno = htonll(commit_seqno);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t prepared_seqno = 0;
uint64_t commit_seqno = 0;
};
static_assert(sizeof(DcpCommitPayload) == 16, "Unexpected struct size");
class DcpAbortPayload {
public:
DcpAbortPayload(uint64_t prepared, uint64_t aborted)
: prepared_seqno(htonll(prepared)), abort_seqno(htonll(aborted)) {
}
uint64_t getPreparedSeqno() const {
return ntohll(prepared_seqno);
}
void setPreparedSeqno(uint64_t seqno) {
prepared_seqno = htonll(seqno);
}
uint64_t getAbortSeqno() const {
return ntohll(abort_seqno);
}
void setAbortSeqno(uint64_t seqno) {
abort_seqno = htonll(seqno);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t prepared_seqno = 0;
uint64_t abort_seqno = 0;
};
static_assert(sizeof(DcpAbortPayload) == 16, "Unexpected struct size");
class SetParamPayload {
public:
enum class Type : uint32_t {
Flush = 1,
Replication,
Checkpoint,
Dcp,
Vbucket
};
Type getParamType() const {
return static_cast<Type>(ntohl(param_type));
}
void setParamType(Type param_type) {
SetParamPayload::param_type = htonl(static_cast<uint32_t>(param_type));
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
bool validate() const {
switch (getParamType()) {
case Type::Flush:
case Type::Replication:
case Type::Checkpoint:
case Type::Dcp:
case Type::Vbucket:
return true;
}
return false;
}
protected:
uint32_t param_type = 0;
};
static_assert(sizeof(SetParamPayload) == 4, "Unexpected size");
#pragma pack()
} // namespace cb::mcbp::request
/**
* This flag is used by the setWithMeta/addWithMeta/deleteWithMeta packets
* to specify that the operation should be forced. The update will not
* be subject to conflict resolution and the target vb can be active/pending or
* replica.
*/
#define FORCE_WITH_META_OP 0x01
/**
* This flag is used to indicate that the *_with_meta should be accepted
* regardless of the bucket config. LWW buckets require this flag.
*/
#define FORCE_ACCEPT_WITH_META_OPS 0x02
/**
* This flag asks that the server regenerates the CAS. The server requires
* that SKIP_CONFLICT_RESOLUTION_FLAG is set along with this option.
*/
#define REGENERATE_CAS 0x04
/**
* This flag is used by the setWithMeta/addWithMeta/deleteWithMeta packets
* to specify that the conflict resolution mechanism should be skipped for
* this operation.
*/
#define SKIP_CONFLICT_RESOLUTION_FLAG 0x08
/**
* This flag is used by deleteWithMeta packets to specify if the delete sent
* instead represents an expiration.
*/
#define IS_EXPIRATION 0x10
/**
* This flag is used with the get meta response packet. If set it
* specifies that the item recieved has been deleted, but that the
* items meta data is still contained in ep-engine. Eg. the item
* has been soft deleted.
*/
#define GET_META_ITEM_DELETED_FLAG 0x01
namespace cb::mcbp::request {
#pragma pack(1)
class SetWithMetaPayload {
public:
uint32_t getFlags() const {
return ntohl(flags);
}
uint32_t getFlagsInNetworkByteOrder() const {
return flags;
}
void setFlags(uint32_t flags) {
SetWithMetaPayload::flags = htonl(flags);
}
void setFlagsInNetworkByteOrder(uint32_t flags) {
SetWithMetaPayload::flags = flags;
}
uint32_t getExpiration() const {
return ntohl(expiration);
}
void setExpiration(uint32_t expiration) {
SetWithMetaPayload::expiration = htonl(expiration);
}
uint64_t getSeqno() const {
return ntohll(seqno);
}
void setSeqno(uint64_t seqno) {
SetWithMetaPayload::seqno = htonll(seqno);
}
uint64_t getCas() const {
return ntohll(cas);
}
void setCas(uint64_t cas) {
SetWithMetaPayload::cas = htonll(cas);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t flags = 0;
uint32_t expiration = 0;
uint64_t seqno = 0;
uint64_t cas = 0;
};
static_assert(sizeof(SetWithMetaPayload) == 24, "Unexpected struct size");
class DelWithMetaPayload {
public:
DelWithMetaPayload(uint32_t flags,
uint32_t delete_time,
uint64_t seqno,
uint64_t cas)
: flags(htonl(flags)),
delete_time(htonl(delete_time)),
seqno(htonll(seqno)),
cas(htonll(cas)) {
}
uint32_t getFlags() const {
return ntohl(flags);
}
uint32_t getFlagsInNetworkByteOrder() const {
return flags;
}
void setFlags(uint32_t flags) {
DelWithMetaPayload::flags = htonl(flags);
}
uint32_t getDeleteTime() const {
return ntohl(delete_time);
}
void setDeleteTime(uint32_t delete_time) {
DelWithMetaPayload::delete_time = htonl(delete_time);
}
uint64_t getSeqno() const {
return ntohll(seqno);
}
void setSeqno(uint64_t seqno) {
DelWithMetaPayload::seqno = htonll(seqno);
}
uint64_t getCas() const {
return ntohll(cas);
}
void setCas(uint64_t cas) {
DelWithMetaPayload::cas = htonll(cas);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t flags = 0;
uint32_t delete_time = 0;
uint64_t seqno = 0;
uint64_t cas = 0;
};
static_assert(sizeof(DelWithMetaPayload) == 24, "Unexpected struct size");
#pragma pack()
} // namespace cb::mcbp::request
/**
* The physical layout for a CMD_GET_META command returns the meta-data
* section for an item:
*/
typedef protocol_binary_request_no_extras protocol_binary_request_get_meta;
/**
* Structure holding getMeta command response fields
*/
#pragma pack(1)
struct GetMetaResponse {
uint32_t deleted;
uint32_t flags;
uint32_t expiry;
uint64_t seqno;
uint8_t datatype;
GetMetaResponse() : deleted(0), flags(0), expiry(0), seqno(0), datatype(0) {
}
GetMetaResponse(uint32_t deleted,
uint32_t flags,
uint32_t expiry,
uint64_t seqno,
uint8_t datatype)
: deleted(deleted),
flags(flags),
expiry(expiry),
seqno(seqno),
datatype(datatype) {
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
};
#pragma pack()
static_assert(sizeof(GetMetaResponse) == 21, "Incorrect compiler padding");
/* Meta data versions for GET_META */
enum class GetMetaVersion : uint8_t {
V1 = 1, // returns deleted, flags, expiry and seqno
V2 = 2, // The 'spock' version returns V1 + the datatype
};
/**
* The physical layout for the CMD_RETURN_META
*/
namespace cb::mcbp::request {
#pragma pack(1)
enum class ReturnMetaType : uint32_t { Set = 1, Add = 2, Del = 3 };
class ReturnMetaPayload {
public:
ReturnMetaType getMutationType() const {
return static_cast<ReturnMetaType>(ntohl(mutation_type));
}
void setMutationType(ReturnMetaType mutation_type) {
ReturnMetaPayload::mutation_type =
htonl(static_cast<uint32_t>(mutation_type));
}
uint32_t getFlags() const {
return ntohl(flags);
}
void setFlags(uint32_t flags) {
ReturnMetaPayload::flags = htonl(flags);
}
uint32_t getExpiration() const {
return ntohl(expiration);
}
void setExpiration(uint32_t expiration) {
ReturnMetaPayload::expiration = htonl(expiration);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t mutation_type = 0;
uint32_t flags = 0;
uint32_t expiration = 0;
};
static_assert(sizeof(ReturnMetaPayload) == 12, "Unexpected struct size");
/**
* Message format for CMD_COMPACT_DB
*
* The PROTOCOL_BINARY_CMD_COMPACT_DB is used by ns_server to
* issue a compaction request to ep-engine to compact the
* underlying store's database files
*
* Request:
*
* Header: Contains the vbucket id. The vbucket id will be used
* to identify the database file if the backend is
* couchstore. If the vbucket id is set to 0xFFFF, then
* the vbid field will be used for compaction.
* Body:
* - purge_before_ts: Deleted items whose expiry timestamp is less
* than purge_before_ts will be purged.
* - purge_before_seq: Deleted items whose sequence number is less
* than purge_before_seq will be purged.
* - drop_deletes: whether to purge deleted items or not.
* - vbid : Database file id for the underlying store.
*
* Response:
*
* The response will return a SUCCESS after compaction is done
* successfully and a NOT_MY_VBUCKET (along with cluster config)
* if the vbucket isn't found.
*/
class CompactDbPayload {
public:
uint64_t getPurgeBeforeTs() const {
return ntohll(purge_before_ts);
}
void setPurgeBeforeTs(uint64_t purge_before_ts) {
CompactDbPayload::purge_before_ts = htonll(purge_before_ts);
}
uint64_t getPurgeBeforeSeq() const {
return ntohll(purge_before_seq);
}
void setPurgeBeforeSeq(uint64_t purge_before_seq) {
CompactDbPayload::purge_before_seq = htonll(purge_before_seq);
}
uint8_t getDropDeletes() const {
return drop_deletes;
}
void setDropDeletes(uint8_t drop_deletes) {
CompactDbPayload::drop_deletes = drop_deletes;
}
const Vbid getDbFileId() const {
return db_file_id.ntoh();
}
void setDbFileId(const Vbid& db_file_id) {
CompactDbPayload::db_file_id = db_file_id.hton();
}
// Generate a method which use align_pad1 and 3 to avoid the compiler
// to generate a warning about unused member (because we
bool validate() const {
return align_pad1 == 0 && align_pad3 == 0;
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t purge_before_ts = 0;
uint64_t purge_before_seq = 0;
uint8_t drop_deletes = 0;
uint8_t align_pad1 = 0;
Vbid db_file_id = Vbid{0};
uint32_t align_pad3 = 0;
};
#pragma pack()
static_assert(sizeof(CompactDbPayload) == 24, "Unexpected struct size");
} // namespace cb::mcbp::request
#define OBS_STATE_NOT_PERSISTED 0x00
#define OBS_STATE_PERSISTED 0x01
#define OBS_STATE_NOT_FOUND 0x80
#define OBS_STATE_LOGICAL_DEL 0x81
/**
* The physical layout for the PROTOCOL_BINARY_CMD_AUDIT_PUT
*/
typedef union {
struct {
protocol_binary_request_header header;
struct {
uint32_t id;
} body;
} message;
uint8_t bytes[sizeof(protocol_binary_request_header) + 4];
} protocol_binary_request_audit_put;
typedef protocol_binary_response_no_extras protocol_binary_response_audit_put;
/**
* The PROTOCOL_BINARY_CMD_OBSERVE_SEQNO command is used by the
* client to retrieve information about the vbucket in order to
* find out if a particular mutation has been persisted or
* replicated at the server side. In order to do so, the client
* would pass the vbucket uuid of the vbucket that it wishes to
* observe to the serve. The response would contain the last
* persisted sequence number and the latest sequence number in the
* vbucket. For example, if a client sends a request to observe
* the vbucket 0 with uuid 12345 and if the response contains the
* values <58, 65> and then the client can infer that sequence
* number 56 has been persisted, 60 has only been replicated and
* not been persisted yet and 68 has not been replicated yet.
*/
/**
* Definition of the request packet for the observe_seqno command.
*
* Header: Contains the vbucket id of the vbucket that the client
* wants to observe.
*
* Body: Contains the vbucket uuid of the vbucket that the client
* wants to observe. The vbucket uuid is of type uint64_t.
*
*/
typedef union {
struct {
protocol_binary_request_header header;
struct {
uint64_t uuid;
} body;
} message;
uint8_t bytes[sizeof(protocol_binary_request_header) + 8];
} protocol_binary_request_observe_seqno;
/**
* Definition of the response packet for the observe_seqno command.
* Body: Contains a tuple of the form
* <format_type, vbucket id, vbucket uuid, last_persisted_seqno,
* current_seqno>
*
* - format_type is of type uint8_t and it describes whether
* the vbucket has failed over or not. 1 indicates a hard
* failover, 0 indicates otherwise.
* - vbucket id is of type Vbid and it is the identifier for
* the vbucket.
* - vbucket uuid is of type uint64_t and it represents a UUID for
* the vbucket.
* - last_persisted_seqno is of type uint64_t and it is the
* last sequence number that was persisted for this
* vbucket.
* - current_seqno is of the type uint64_t and it is the
* sequence number of the latest mutation in the vbucket.
*
* In the case of a hard failover, the tuple is of the form
* <format_type, vbucket id, vbucket uuid, last_persisted_seqno,
* current_seqno, old vbucket uuid, last_received_seqno>
*
* - old vbucket uuid is of type uint64_t and it is the
* vbucket UUID of the vbucket prior to the hard failover.
*
* - last_received_seqno is of type uint64_t and it is the
* last received sequence number in the old vbucket uuid.
*
* The other fields are the same as that mentioned in the normal case.
*/
typedef protocol_binary_response_no_extras
protocol_binary_response_observe_seqno;
/**
* Definition of the request packet for the command
* PROTOCOL_BINARY_CMD_GET_ALL_VB_SEQNOS
*
* Header: Only opcode field is used.
*
* Body: Contains the vBucket state and/or collection id for which the vb
* sequence numbers are requested.
* Please note that these fields are optional, header.request.extlen is
* checked to see if they are present. If a vBucket state is not
* present or 0 it implies request is for all vbucket states. If
* collection id is not present it it implies the request is for the
* vBucket high seqno number.
*
*/
typedef union {
struct {
protocol_binary_request_header header;
struct {
RequestedVBState state;
CollectionIDType cid;
} body;
} message;
uint8_t bytes[sizeof(protocol_binary_request_header) +
sizeof(RequestedVBState) + sizeof(CollectionIDType)];
} protocol_binary_request_get_all_vb_seqnos;
/**
* Definition of the payload in the PROTOCOL_BINARY_CMD_GET_ALL_VB_SEQNOS
* response.
*
* The body contains a "list" of "vbucket id - seqno pairs" for all
* active and replica buckets on the node in network byte order.
*
*
* Byte/ 0 | 1 | 2 | 3 |
* / | | | |
* |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|
* +---------------+---------------+---------------+---------------+
* 0| VBID | VBID | SEQNO | SEQNO |
* +---------------+---------------+---------------+---------------+
* 4| SEQNO | SEQNO | VBID | VBID |
* +---------------+---------------+---------------+---------------+
* 4| SEQNO | SEQNO |
* +---------------+---------------+
*/
typedef protocol_binary_response_no_extras
protocol_binary_response_get_all_vb_seqnos;
/**
* Message format for PROTOCOL_BINARY_CMD_GET_KEYS
*
* The extras field may contain a 32 bit integer specifying the number
* of keys to fetch. If no value specified 1000 keys is transmitted.
*
* Key is mandatory and specifies the starting key
*
* Get keys is used to fetch a sequence of keys from the server starting
* at the specified key.
*/
typedef protocol_binary_request_no_extras protocol_binary_request_get_keys;
namespace cb::mcbp::request {
#pragma pack(1)
class AdjustTimePayload {
public:
enum class TimeType : uint8_t { TimeOfDay = 0, Uptime = 1 };
uint64_t getOffset() const {
return ntohll(offset);
}
void setOffset(uint64_t offset) {
AdjustTimePayload::offset = htonll(offset);
}
TimeType getTimeType() const {
return time_type;
}
void setTimeType(TimeType time_type) {
AdjustTimePayload::time_type = time_type;
}
bool isValid() const {
switch (getTimeType()) {
case TimeType::TimeOfDay:
case TimeType::Uptime:
return true;
}
return false;
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint64_t offset = 0;
TimeType time_type = TimeType::TimeOfDay;
};
static_assert(sizeof(AdjustTimePayload) == 9, "Unexpected struct size");
/**
* Message format for PROTOCOL_BINARY_CMD_EWOULDBLOCK_CTL
*
* See engines/ewouldblock_engine for more information.
*/
class EWB_Payload {
public:
uint32_t getMode() const {
return ntohl(mode);
}
void setMode(uint32_t m) {
mode = htonl(m);
}
uint32_t getValue() const {
return ntohl(value);
}
void setValue(uint32_t v) {
value = htonl(v);
}
uint32_t getInjectError() const {
return ntohl(inject_error);
}
void setInjectError(uint32_t ie) {
inject_error = htonl(ie);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint32_t mode = 0; // See EWB_Engine_Mode
uint32_t value = 0;
uint32_t inject_error = 0; // cb::engine_errc to inject.
};
static_assert(sizeof(EWB_Payload) == 12, "Unepected struct size");
/**
* Message format for PROTOCOL_BINARY_CMD_GET_ERRORMAP
*
* The payload (*not* specified as extras) contains a 2 byte payload
* containing a 16 bit encoded version number. This version number should
* indicate the highest version number of the error map the client is able
* to understand. The server will return a JSON-formatted error map
* which is formatted to either the version requested by the client, or
* a lower version (thus, clients must be ready to parse lower version
* formats).
*/
class GetErrmapPayload {
public:
uint16_t getVersion() const {
return ntohs(version);
}
void setVersion(uint16_t version) {
GetErrmapPayload::version = htons(version);
}
cb::const_byte_buffer getBuffer() const {
return {reinterpret_cast<const uint8_t*>(this), sizeof(*this)};
}
protected:
uint16_t version = 0;
};
static_assert(sizeof(GetErrmapPayload) == 2, "Unexpected struct size");
#pragma pack()
} // namespace cb::mcbp::request
/**
* Message format for PROTOCOL_BINARY_CMD_COLLECTIONS_SET_MANIFEST
*
* The body contains a JSON collections manifest.
* No key and no extras
*/
typedef union {
struct {
protocol_binary_request_header header;
} message;
uint8_t bytes[sizeof(protocol_binary_request_header)];
} protocol_binary_collections_set_manifest;
typedef protocol_binary_response_no_extras
protocol_binary_response_collections_set_manifest;
/**
* @}
*/
inline protocol_binary_subdoc_flag operator|(protocol_binary_subdoc_flag a,
protocol_binary_subdoc_flag b) {
return protocol_binary_subdoc_flag(static_cast<uint8_t>(a) |
static_cast<uint8_t>(b));
}
namespace mcbp::subdoc {
inline constexpr mcbp::subdoc::doc_flag operator|(mcbp::subdoc::doc_flag a,
mcbp::subdoc::doc_flag b) {
return mcbp::subdoc::doc_flag(static_cast<uint8_t>(a) |
static_cast<uint8_t>(b));
}
inline constexpr mcbp::subdoc::doc_flag operator&(mcbp::subdoc::doc_flag a,
mcbp::subdoc::doc_flag b) {
return mcbp::subdoc::doc_flag(static_cast<uint8_t>(a) &
static_cast<uint8_t>(b));
}
inline constexpr mcbp::subdoc::doc_flag operator~(mcbp::subdoc::doc_flag a) {
return mcbp::subdoc::doc_flag(~static_cast<uint8_t>(a));
}
inline std::string to_string(mcbp::subdoc::doc_flag a) {
using mcbp::subdoc::doc_flag;
switch (a) {
case doc_flag::None:
return "None";
case doc_flag::Mkdoc:
return "Mkdoc";
case doc_flag::AccessDeleted:
return "AccessDeleted";
case doc_flag::Add:
return "Add";
case doc_flag::CreateAsDeleted:
return "CreateAsDeleted";
case doc_flag::ReviveDocument:
return "ReviveDocument";
}
return std::to_string(static_cast<uint8_t>(a));
}
inline bool hasAccessDeleted(mcbp::subdoc::doc_flag a) {
return (a & mcbp::subdoc::doc_flag::AccessDeleted) !=
mcbp::subdoc::doc_flag::None;
}
inline bool hasMkdoc(mcbp::subdoc::doc_flag a) {
return (a & mcbp::subdoc::doc_flag::Mkdoc) != mcbp::subdoc::doc_flag::None;
}
inline bool hasAdd(mcbp::subdoc::doc_flag a) {
return (a & mcbp::subdoc::doc_flag::Add) != mcbp::subdoc::doc_flag::None;
}
inline bool hasReviveDocument(mcbp::subdoc::doc_flag a) {
return (a & mcbp::subdoc::doc_flag::ReviveDocument) ==
mcbp::subdoc::doc_flag::ReviveDocument;
}
inline bool hasCreateAsDeleted(mcbp::subdoc::doc_flag a) {
return (a & mcbp::subdoc::doc_flag::CreateAsDeleted) !=
mcbp::subdoc::doc_flag::None;
}
inline bool isNone(mcbp::subdoc::doc_flag a) {
return a == mcbp::subdoc::doc_flag::None;
}
inline bool impliesMkdir_p(mcbp::subdoc::doc_flag a) {
return hasAdd(a) || hasMkdoc(a);
}
} // namespace mcbp::subdoc
namespace mcbp::cas {
/**
* The special value used as a wildcard and match all CAS values
*/
const uint64_t Wildcard = 0x0;
} // namespace mcbp::cas
namespace cb::mcbp::request {
#pragma pack(1)
// Payload for get_collection_id opcode 0xbb, data stored in network byte order
class GetCollectionIDPayload {
public:
GetCollectionIDPayload() = default;
GetCollectionIDPayload(uint64_t manifestId, CollectionID collectionId)
: manifestId(htonll(manifestId)),
collectionId(htonl(uint32_t(collectionId))) {
}
CollectionID getCollectionId() const {
return ntohl(collectionId);
}
uint64_t getManifestId() const {
return ntohll(manifestId);
}
std::string_view getBuffer() const {
return {reinterpret_cast<const char*>(this), sizeof(*this)};
}
protected:
uint64_t manifestId{0};
uint32_t collectionId{0};
};
// Payload for get_scope_id opcode 0xbc, data stored in network byte order
class GetScopeIDPayload {
public:
GetScopeIDPayload() = default;
GetScopeIDPayload(uint64_t manifestId, ScopeID scopeId)
: manifestId(htonll(manifestId)), scopeId(htonl(uint32_t(scopeId))) {
}
ScopeID getScopeId() const {
return ntohl(scopeId);
}
uint64_t getManifestId() const {
return ntohll(manifestId);
}
std::string_view getBuffer() const {
return {reinterpret_cast<const char*>(this), sizeof(*this)};
}
protected:
uint64_t manifestId{0};
uint32_t scopeId{0};
};
// Payload for get_rando_key opcode 0xb6, data stored in network byte order
class GetRandomKeyPayload {
public:
GetRandomKeyPayload() = default;
explicit GetRandomKeyPayload(uint32_t collectionId)
: collectionId(htonl(collectionId)) {
}
CollectionID getCollectionId() const {
return ntohl(collectionId);
}
std::string_view getBuffer() const {
return {reinterpret_cast<const char*>(this), sizeof(*this)};
}
protected:
CollectionIDType collectionId{0};
};
#pragma pack()
} // namespace cb::mcbp::request
| {
"alphanum_fraction": 0.6490447013,
"avg_line_length": 29.4890965732,
"ext": "h",
"hexsha": "2ef559e292ce7b52fb2668ef4ae2eedd927fa475",
"lang": "C",
"max_forks_count": 71,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z",
"max_forks_repo_head_hexsha": "d9dd3f0be3700ef13cb59fa40e375b5ba73e5add",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "couchbase/kv_engine",
"max_forks_repo_path": "include/memcached/protocol_binary.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "d9dd3f0be3700ef13cb59fa40e375b5ba73e5add",
"max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z",
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "couchbase/kv_engine",
"max_issues_repo_path": "include/memcached/protocol_binary.h",
"max_line_length": 80,
"max_stars_count": 104,
"max_stars_repo_head_hexsha": "d9dd3f0be3700ef13cb59fa40e375b5ba73e5add",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "couchbase/kv_engine",
"max_stars_repo_path": "include/memcached/protocol_binary.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z",
"num_tokens": 16550,
"size": 66262
} |
#pragma once
#include <memory>
#include <gsl/gsl>
#include "../platform/d3d.h"
#include "../infrastructure/macros.h"
namespace gfx {
class IndexBuffer {
friend class RenderingDevice;
public:
IndexBuffer(CComPtr<ID3D11Buffer> buffer, size_t count);
~IndexBuffer();
void Update(gsl::span<uint16_t> data);
NO_COPY_OR_MOVE(IndexBuffer)
private:
void Unlock();
size_t mCount;
CComPtr<ID3D11Buffer> mBuffer;
};
using IndexBufferPtr = std::shared_ptr<IndexBuffer>;
class VertexBuffer {
friend class RenderingDevice;
friend class BufferBinding;
public:
VertexBuffer(CComPtr<ID3D11Buffer> vertexBufferNew, size_t size);
~VertexBuffer();
void Update(gsl::span<const uint8_t> data);
template <typename T>
void Update(gsl::span<T> data) {
Update(gsl::span(reinterpret_cast<const uint8_t*>(&data[0]), data.size_bytes()));
}
NO_COPY_OR_MOVE(VertexBuffer);
private:
size_t mSize;
CComPtr<ID3D11Buffer> mBuffer;
};
using VertexBufferPtr = std::shared_ptr<VertexBuffer>;
}
| {
"alphanum_fraction": 0.7489919355,
"avg_line_length": 18.7169811321,
"ext": "h",
"hexsha": "5aadb81ec819808795313195978e0e5b2954f244",
"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/include/graphics/buffers.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/include/graphics/buffers.h",
"max_line_length": 83,
"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/include/graphics/buffers.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": 256,
"size": 992
} |
/* applying a t-model to performance data to obtain a robust
estimate of the mean via ML of the loglikelihood function */
/* PREPROCESSOR FLAGS:
NR - Algorithms from Numerical Recipes
NELDER - Nelder-Mead algorithm, not working
POWELL - Powell's method
QUASI_NEWTON - quasi-Newton (Newton-Raphson) method
GSL - algrithms from GSL library
(select Conjugate gradient, BFGS or steepest decent in function
gsl_minimize_loglikelihood)
MAIN - compile with main() and test data
SUMMARY - short output of results
DEBUG - turns on various output
*/
// Nealder and Mead: does not work
//gcc -DNR -DMAIN -DNELDER robust.c dfpmin.c lnsrch.c nrutil.c amoeba.c amotry.c -I/usr/include/gsl -lm -L/usr/local/lib -lgsl -lgslcblas -g -o test.x
// quasi-Newton:
//gcc -DNR -DMAIN -DQUASI_NEWTON robust.c dfpmin.c lnsrch.c nrutil.c -I/usr/include/gsl -lm -L/usr/local/lib -lgsl -lgslcblas -g -o test.x
// Powell:
// gcc -DNR -DMAIN -DPOWELL robust.c nrutil.c powell.c linmin.c f1dim.c mnbrak.c brent.c -I/usr/include/gsl -lm -L/usr/local/lib -lgsl -lgslcblas -g -o test.x
// GSL:
// gcc -DGSL -DMAIN robust.c dfpmin.c lnsrch.c nrutil.c -I/usr/include/gsl -lm -L/usr/local/lib -lgsl -lgslcblas -g -o test.x
#if defined(GSL) || defined(NR)
#ifdef NR
#include <stdlib.h>
#include <stdio.h>
#define NRANSI
#include "nr.h"
#include "nrutil.h"
#endif
#ifdef GSL
#include <gsl_math.h>
#include <gsl_sort.h>
#include <gsl_sf_gamma.h>
#include <gsl_sf_psi.h>
#include <gsl_sf_log.h>
#include <gsl/gsl_sf_pow_int.h>
#include <gsl_statistics_double.h>
#include <gsl/gsl_sf_pow_int.h>
#include <gsl_multimin.h>
#endif
#ifdef NR
void get_starting_value(float* x0);
void output_results(float* x0, int iter, float* val);
#endif
#ifdef GSL
void get_starting_value(gsl_vector* x0, void* params);
void output_results(gsl_vector* x0, int iter, double* val, void* params);
void loglikelihood_fdf (const gsl_vector *x, void *params, double *f,
gsl_vector *df);
int gsl_minimize_loglikelihood(const double step_size, const double tol,
const double eps_abs, const int maxiter, gsl_vector* x0, double* val, int* iter,
void* params);
int gsl_minimize_loglikelihood_old(const double step_size, const double tol,
const double eps_abs, const int maxiter, gsl_vector* x0, double* val, int* iter,
void* params);
#endif
#ifdef NR
void nelder_mead(float* x0, float (*func)(float []), float* ftol,
float* val);
#endif
static int nfunc; // number of function calls
static int ndfunc; // number of calls to compute derivative
double nu=3;
int with_nu;
double nustart=4.0;
int ndim;
#ifdef MAIN
/* speed of light data set */
double c_data[66] = {
28.0, 26.0, 33.0, 24.0, 34.0, -44.0, 27.0, 16.0, 40.0, -2.0,
29.0, 22.0, 24.0, 21.0, 25.0, 30.0, 23.0, 29.0, 31.0, 19.0,
24.0, 20.0, 36.0, 32.0, 36.0, 28.0, 25.0, 21.0, 28.0, 29.0,
37.0, 25.0, 28.0, 26.0, 30.0, 32.0, 36.0, 26.0, 30.0, 22.0,
36.0, 23.0, 27.0, 27.0, 28.0, 27.0, 31.0, 27.0, 26.0, 33.0,
26.0, 32.0, 32.0, 24.0, 39.0, 28.0, 24.0, 25.0, 32.0, 25.0,
29.0, 27.0, 28.0, 29.0, 16.0, 23.0};
#endif
int ndata; // #data points
double *data;
/*****************************************************************************/
#ifdef NR
float loglikelihood_f(float x[])
#endif
#ifdef GSL
double loglikelihood_f(const gsl_vector *x, void *params)
#endif
/*****************************************************************************/
{
double mu, // estimate of location
sigma2; // estimate of scale
double delta, g, psi;
#ifdef GSL
int ndata;
double nu, *data;
double * tmp = (double *) params;
#endif
double y; // temporary variable
int i;
nfunc++;
#ifdef NR
mu = x[1];
sigma2 = x[2];
if (with_nu) nu = x[3];
#else
/* extract arguments and parameters */
mu = gsl_vector_get(x, 0);
sigma2 = gsl_vector_get(x, 1);
nu = tmp[0];
if (nu == 0){
with_nu = 1;
nu = gsl_vector_get(x,2);
}
ndata = (int) tmp[1];
data = &(tmp[2]);
//printf("%d %f %f\n", n, nu, data[0]);
#endif
y = - 0.5 * gsl_sf_log(sigma2) * ndata;
for (i=0; i<ndata; i++){
delta = (data[i] - mu)*( data[i] - mu) / (nu * sigma2);
y = y - 0.5 * (nu + 1.) * gsl_sf_log( 1+delta );
}
if (with_nu){ /* compute whole log likelyhood function */
g = gsl_sf_lngamma(0.5*(nu+1.)) - gsl_sf_lngamma(0.5*nu)
- 0.5 * gsl_sf_log(nu);
y = y + ndata * g;
}
#ifdef DEBUG
if (with_nu)
printf("mu=%.12f, sigma=%.12f, nu=%.12f, y=%.12f\n", mu, sqrt(sigma2), nu, y);
else
printf("mu=%.12f, sigma=%.12f, y=%.12f\n", mu, sqrt(sigma2), y);
#endif
return -y; /* since we're minimizing, not maximizing */
}
/*****************************************************************************/
#ifdef NR
void loglikelihood_df(float x[],float df[])
#endif
#ifdef GSL
void loglikelihood_df(const gsl_vector *x, void *params, gsl_vector *df)
#endif
/*****************************************************************************/
/* this function should store the n-dimensional gradient
g_i = d f(x,params) / d x_i in the vector g for argument x and parameters
params, returning an appropriate error code if the function cannot be computed. */
{
double mu, sigma2;
int i, k;
double dldtheta, dldphi, dldnu, y, r, t, d, g, s1, s2;
#ifdef GSL
int ndata, with_nu = 0;
double nu, *data;
double * tmp = (double *) params;
#endif
ndfunc++;
#ifdef NR
/* extract arguments and parameters */
mu = x[1];
sigma2 = x[2];
if (with_nu) nu = x[3];
#endif
#ifdef GSL
/* extract arguments and parameters */
mu = gsl_vector_get(x, 0);
sigma2 = gsl_vector_get(x, 1);
nu = tmp[0];
if (nu == 0){
with_nu = 1;
nu = gsl_vector_get(x,2);
}
ndata = (int) tmp[1];
data = &(tmp[2]);
//printf("%d %f %f\n", ndata, nu, data[0]);
//printf("df mu=%lf sigma=%lf nu=%lf \n", mu, sqrt(sigma2), nu);
#endif
dldtheta = 0.;
dldphi = 0.;
if (with_nu) {
dldnu = 0.;
s1 = 0.;
s2 = 0.;
}
/* calculate terms depending on data[i] */
for (i=0; i<ndata; i++){
y = data[i];
d = y - mu;
r = d*d / (sigma2*nu);
dldtheta = dldtheta + d / ( 1 + r );
dldphi = dldphi + r / (1+r); // + 0.5/sigma2;
if (with_nu){
s1 = s1 + r / (1+r); //t * d;
s2 = s2 + gsl_sf_log(1+r) ;
}
}
/* add constant terms */
dldtheta = (nu+1)/(sigma2*nu) * dldtheta;
dldphi = - 0.5*ndata/sigma2 + 0.5*(nu+1)/sigma2 * dldphi;
if (with_nu) {
/* digamma(z) = psi(z) = d/dz( ln gamma(z) ) */
g = 0.5 * ndata * ( gsl_sf_psi((nu+1)/2) - gsl_sf_psi(0.5*nu) - 1./nu );
dldnu = g + 0.5*(nu+1)/nu * s1 - 0.5 * s2;
}
/* change signs since we are minimizing, not maximizing */
#ifdef NR
df[1] = - dldtheta;
df[2] = - dldphi;
if (with_nu) df[3] = - dldnu;
#endif
#ifdef GSL
gsl_vector_set(df, 0, - dldtheta);
gsl_vector_set(df, 1, - dldphi);
if (with_nu) {
gsl_vector_set(df, 2, - dldnu);
}
#endif
#ifdef DEBUG
#ifdef NR
if (with_nu) printf(" df %lf %lf %lf\n", df[1], df[2], df[3]);
else printf(" df %lf %lf \n", df[1], df[2]);
#endif
#ifdef GSL
if (with_nu) printf(" df %lf %lf %lf\n", gsl_vector_get(df, 0), gsl_vector_get(df, 1),
gsl_vector_get(df, 2));
else printf(" df %lf %lf \n", gsl_vector_get(df, 0), gsl_vector_get(df, 1));
#endif
#endif
}
/*****************************************************************************/
#ifdef NR
int ml(const int ndata_loc, double* const data_loc, double* nu, double* mu,
double* sigma, float* val)
#endif
#ifdef GSL
int ml(const int ndata, double* const data, double* nu, double* mu,
double* sigma, double* val)
#endif
/*****************************************************************************/
/* performs a ML method for a t model
ndata (in) size of data
data (in) data / measurements
nu (in/out) if nu is 0, optimize also for nu and return
optimized value
if nu is != 0, accept nu as parameter
mu (out) optimized value for mu
sigma (out) optimized value for sigma
val (out) if nu is variable, value of log likelihood function
if nu is fixed, value of simplified log likelihood
function*/
{
#ifdef NR
float *x0; // starting point / maximum
#endif
#ifdef GSL
gsl_vector *x0; // starting point / maximum
double *params;
double step_size, tol, eps_abs;
#endif
int maxiter = 1000;
int iter = 0, i, j;
/* init starting point */
if (*nu == 0)
ndim = 3;
else
ndim = 2;
#ifdef NR
ndata = ndata_loc;
data = data_loc;
x0 = vector(1,ndim);
#endif
#ifdef GSL
/* init parameters */
params = malloc((ndata+2)*sizeof(double));
params[0] = *nu;
params[1] = (double) ndata;
for (i=0; i<ndata; i++){
params[2+i] = data[i];
}
x0 = gsl_vector_alloc(ndim);
#endif
#ifdef NR
get_starting_value(x0);
#endif
#ifdef GSL
get_starting_value(x0, params);
#endif
nfunc = ndfunc = 0;
#ifdef NR
#ifdef NELDER
float ftol = 1.0e-6;
nelder_mead(x0, loglikelihood_f, &(ftol), val);
#endif
#ifdef POWELL
float ftol = 1.0e-6;
float **p;
p=matrix(1,ndim,1,ndim);
for (i=1;i<=ndim;i++)
for (j=1;j<=ndim;j++)
p[i][j]=(i == j ? 1. : 0.0);
if (with_nu)
p[3][3] = 0.01;
iter = maxiter;
powell(x0,p,ndim,ftol,&iter,val,loglikelihood_f);
free_matrix(p,1,ndim,1,ndim);
#endif
#ifdef QUASI_NEWTON
float gtol = 1.0e-8;
dfpmin(x0,ndim,gtol,&iter,val,loglikelihood_f,loglikelihood_df);
#endif
// endif NR
#endif
#ifdef GSL
step_size = 0.1; // size of first trial step
tol = 0.1; // accuracy of line minimization, 0.1 will do
eps_abs = 1e-8;
gsl_minimize_loglikelihood(step_size, tol, eps_abs, maxiter, x0, val,
&(iter), params);
#endif
#ifdef SUMMARY
#ifdef NR
output_results(x0, iter, val);
#endif
#ifdef GSL
output_results(x0, iter, val, params);
#endif
#endif
#ifdef NR
*mu = (double) x0[1];
*sigma = sqrt((double) x0[2]);
if (with_nu)
*nu = (double) x0[3];
free_vector(x0,1,ndim);
#endif
#ifdef GSL
*mu = gsl_vector_get(x0, 0);
*sigma = sqrt(gsl_vector_get(x0, 1));
if (with_nu)
*nu = gsl_vector_get(x0, 2);
gsl_vector_free(x0);
free (params);
#endif
return 0;
}
#ifdef MAIN
/*****************************************************************************/
int main()
/*****************************************************************************/
{
int i, varnu=0;
#ifdef NR
float val;
#endif
#ifdef GSL
double val;
#endif
double mu, sigma;
const int ndata_loc = 66;
double *data_loc = &(c_data[0]);
//nu = 0.0; with_nu = 1;
nu = 4.0; with_nu = 0;
ml(ndata_loc, data_loc, &(nu), &(mu), &(sigma), &(val));
#ifdef SUMMARY
printf("\n\nReturn values:\n");
printf("nu=%.5lf mu=%.5lf sigma=%.5lf val=%.5lf\n", nu, mu, sigma, val);
#endif
return 0;
}
#endif
/*****************************************************************************/
#ifdef NR
void get_starting_value(float* x0)
#endif
#ifdef GSL
void get_starting_value(gsl_vector* x0, void* params)
#endif
/*****************************************************************************/
/* computes an estimate of location and scale */
/*****************************************************************************/
{
double mean, variance;
double median, *madv, mad;
int i;
#ifdef GSL
double* tmp = (double*) params;
int ndata = (int) tmp[1];
double* data = &(tmp[2]);
#endif
/* Possiblity I: Use mean and variance as starting value
this is probably going to crash when outliers are present */
mean = gsl_stats_mean(&(data[0]), (size_t) 1,(size_t) ndata);
variance = gsl_stats_variance_with_fixed_mean(&(data[0]),
(size_t) 1, (size_t) ndata, mean);
#ifdef NR
x0[1] = mean;
x0[2] = variance;
#endif
#ifdef GSL
gsl_vector_set(x0, 0, mean);
gsl_vector_set(x0, 1, variance);
#endif
/* Possiblity II: Use median and 1.483*MAD as starting value
Absolute Deviatons MAD(x) = med_i {|x_i - med_j (x_j)|} */
gsl_sort(data, (size_t) 1, (size_t) ndata);
median = gsl_stats_median_from_sorted_data(data, (size_t) 1, (size_t) ndata);
madv = (double*) malloc(ndata * sizeof(double));
for (i=0; i<ndata; i++){
madv[i] = abs(data[i] - median);
}
gsl_sort(madv, (size_t) 1, (size_t) ndata);
mad = 1.483 * gsl_stats_median_from_sorted_data(madv, (size_t) 1, (size_t) ndata);
//printf("median: %20.5f, mad : %20.5f\n", median, mad);
//mad = 2 * median; //5.25 * gsl_stats_median_from_sorted_data(madv, (size_t) 1, (size_t) ndata);
free(madv);
#ifdef NR
x0[1] = median;
x0[2] = 0.7*mad*mad;
if (with_nu)
x0[3] = nustart;
#ifdef SUMMARY
printf("\nStarting vector : ");
for (i=1;i<=ndim;i++) printf("%12.6f",x0[i]);
#endif
#endif
#ifdef GSL
gsl_vector_set(x0, 0, median);
gsl_vector_set(x0, 1, 0.7*mad*mad);
if (with_nu)
gsl_vector_set(x0, 2, nustart);
#ifdef SUMMARY
printf("\nStarting vector : ");
for (i=0;i<ndim;i++) printf("%12.6f", gsl_vector_get(x0, i));
#endif
#endif
}
/*****************************************************************************/
#ifdef NR
void output_results(float* x0, int iter, float* val)
#endif
#ifdef GSL
void output_results(gsl_vector* x0, int iter, double* val, void* params)
#endif
/*****************************************************************************/
/* output of minimum and statistics */
/*****************************************************************************/
{
int i;
#ifdef NR
float *xdf; // gradient at maximum
xdf = vector(1,ndim);
#endif
#ifdef GSL
int with_nu = 0;
gsl_vector *xdf; // gradient at maximum
double* tmp = (double*) params;
double nu;
xdf = gsl_vector_alloc(ndim);
nu = tmp[0];
if (nu == 0.0) with_nu = 1;
#endif
printf("\n\nIterations : %3d\n",iter);
printf("Func. evals : %3d\n",nfunc);
#ifdef QUASI_NEWTON
printf("Deriv. evals : %3d\n",ndfunc);
#endif
printf("\nMaximum found at : ");
#ifdef NR
x0[2] = sqrt(x0[2]);
for (i=1;i<=ndim;i++) printf("%12.6f",x0[i]);
x0[2] = x0[2] * x0[2];
#endif
#ifdef GSL
gsl_vector_set(x0, 1, sqrt(gsl_vector_get(x0, 1)));
for (i=0;i<ndim;i++) printf("%12.6f", gsl_vector_get(x0, i));
gsl_vector_set(x0, 1, gsl_vector_get(x0, 1) * gsl_vector_get(x0, 1));
#endif
printf("\nMaximum function value : %12.6f\n",*val);
printf("Derivative at maximum : ");
#ifdef NR
loglikelihood_df(x0, xdf);
for (i=1;i<=ndim;i++) printf("%12.6f",xdf[i]);
#endif
#ifdef GSL
loglikelihood_df(x0, params, xdf);
for (i=0;i<ndim;i++) printf("%12.6f",gsl_vector_get(xdf, i));
#endif
#ifdef MAIN
if (with_nu){ // for variable nu
printf("\n\nTrue maximum is at (mu_hat, sigma_hat, vu) = (27.40, 3.81, 2.13)\n");
#ifdef NR
x0[1] = 27.40;
x0[2] = 3.81*3.81;
x0[3] = 2.13;
printf("Test: function value at maximum = %12.6f\n", loglikelihood_f(x0));
printf("Derivative at maximum : ");
loglikelihood_df(x0, xdf);
for (i=1;i<=ndim;i++) printf("%12.6f",xdf[i]);
#endif
#ifdef GSL
gsl_vector_set(x0, 0, 27.40);
gsl_vector_set(x0, 1, 3.81*3.81);
gsl_vector_set(x0, 2, 2.13);
printf("Test: function value at maximum = %12.6f\n", loglikelihood_f(x0, params));
loglikelihood_df(x0, params, xdf);
printf("Derivative at maximum : ");
for (i=0;i<ndim;i++) printf("%12.6f",gsl_vector_get(xdf, i));
#endif
} else { // for fixed nu=4:
printf("\n\nTrue maximum is at (mu_hat, sigma_hat) = (27.49, 4.51)\n");
#ifdef NR
x0[1] = 27.49;
x0[2] = 4.51 * 4.51;
printf("Test: function value at maximum : %12.6f\n", loglikelihood_f(x0));
printf("Derivative at true maximum : ");
loglikelihood_df(x0, xdf);
for (i=1;i<=ndim;i++) printf("%12.6f",xdf[i]);
#endif
#ifdef GSL
gsl_vector_set(x0, 0, 27.40);
gsl_vector_set(x0, 1, 4.51 * 4.51);
printf("Test: function value at maximum : %12.6f\n", loglikelihood_f(x0, params));
loglikelihood_df(x0, params, xdf);
printf("Derivative at true maximum : ");
for (i=0;i<ndim;i++) printf("%12.6f",gsl_vector_get(xdf, i));
#endif
}
#endif
#ifdef NR
free_vector(xdf,1,ndim);
#endif
#ifdef GSL
gsl_vector_free(xdf);
#endif
}
#ifdef NR
#ifdef NELDER
/*****************************************************************************/
void nelder_mead(float* x0, float(*func)(float []), float* ftol,
float* val)
/*****************************************************************************/
/* computes minimum with method of Nelder and Mead from numerical recipes */
/*
/* parameters:
/* x0 on input: starting value; on output: minimum
/* func function
/* ftol tolerance
/* val function value at minimum */
/*****************************************************************************/
{
int i, j;
float *x, *y, **p;
double delta_mu, delta_sigma2;
if (ndim != 2) {
printf("ndim != 2 not implemented\n");
exit(0);
}
x=vector(1,ndim);
y=vector(1,ndim+1);
p=matrix(1,ndim+1,1,ndim);
delta_mu = 0.5e0;
delta_sigma2 = 1e0;
for (i=1;i<=ndim+1;i++) {
x[1] = p[i][1]=(i == (j+1) ? x0[1] + delta_mu : x0[1] - delta_mu );
x[2] = p[i][2]=(i == (j+1) ? x0[2] + delta_sigma2 : x0[2] - delta_sigma2);
y[i]=loglikelihood_f(x);
}
amoeba(p,y,ndim,*ftol,func,&nfunc);
y[2] = sqrt(y[2]);
printf("Vertices of final 3-d simplex and\n");
printf("function values at the vertices:\n\n");
printf("%3s %10s %12s %14s\n\n",
"i","x[i]","y[i]", "function");
for (i=1;i<=ndim+1;i++) {
printf("%3d ",i);
for (j=1;j<=ndim;j++) printf("%12.6f ",p[i][j]);
printf("%12.6f\n",y[i]);
}
for (j=1;j<=ndim;j++) {
// sum up vertices of final simplex
x0[j] = p[1][j];
for (i=2;i<=ndim+1;i++)
x0[j] = x0[j] + p[i][j];
// ... and average ...
x0[j] = x0[j]/(ndim+1);
}
// calculate average function value at maximum
*val = y[1];
for (i=2;i<=ndim+1;i++)
*val = *val + y[i];
*val = *val / (ndim+1);
free_vector(x,1,ndim);
free_matrix(p,1,ndim+1,1,ndim);
free_vector(y,1,ndim+1);
}
//endif NELDER
#endif
//endif NR
#endif
#ifdef GSL
/* Compute both f and df together. */
void loglikelihood_fdf (const gsl_vector *x, void *params, double *f,
gsl_vector *df)
{
*f = loglikelihood_f(x, params);
loglikelihood_df(x, params, df);
//printf("fdf =%lf %lf %lf %lf \n", gsl_vector_get(x,0), gsl_vector_get(x,1),
// gsl_vector_get(df,0), gsl_vector_get(df,1));
}
int gsl_minimize_loglikelihood(const double step_size, const double tol,
const double eps_abs, const int maxiter, gsl_vector* x0, double* val, int* iter,
void* params){
/*
s (in) GSL multimin fminimizer object
eps_abs (in)
maxiter (in) maximum number of iterations
iter (in/out) number of iterations */
const gsl_multimin_fdfminimizer_type *T;
gsl_multimin_fdfminimizer *s;
gsl_multimin_function_fdf my_func;
double* tmp = (double*) params;
double nu = tmp[0];
double sigma2;
int my_iter = 0;
int status;
/* init function object */
if (nu != 0.0) my_func.n = 2;
else my_func.n = 3;
my_func.f = &loglikelihood_f;
my_func.df = &loglikelihood_df;
my_func.fdf = &loglikelihood_fdf;
my_func.params = params;
/* set up solver */
T = gsl_multimin_fdfminimizer_conjugate_fr;
// T = gsl_multimin_fdfminimizer_vector_bfgs;
// T = gsl_multimin_fdfminimizer_steepest_descent;
if (nu != 0.0) s = gsl_multimin_fdfminimizer_alloc(T,2);
else s = gsl_multimin_fdfminimizer_alloc(T,3);
/* call minimizer */
//s->f = my_func->f;
//gsl_multimin_fminimizer_set(s, &my_func, x0, step_size)
gsl_multimin_fdfminimizer_set(s, &my_func, x0, step_size, tol);
/* let gsl minimizer iterate */
do
{
status = gsl_multimin_fdfminimizer_iterate(s);
if (status) break;
status = gsl_multimin_test_gradient(s->gradient, eps_abs);
/* if (status == GSL_SUCCESS){
printf("Maximum found after %d iterations at:\n", *iter);
}
printf ("%5d %.5f %.5f %10.5f\n", *iter,
gsl_vector_get (s->x, 0), sqrt(gsl_vector_get (s->x, 1)), s->f); */
(*iter)++;
} while (status == GSL_CONTINUE && *iter < maxiter);
/* just precaution */
sigma2 = gsl_vector_get(x0, 1);
if (isnan(sigma2)){
printf("!!! sigma2 is nan\n");
printf("%5d %15.5f %15.5f", *iter,
gsl_vector_get(s->x, 0),
sqrt(gsl_vector_get(s->x, 1)));
if (nu == 0.0) printf("%15.5f", gsl_vector_get(s->x, 2));
printf("%15.5f\n", -gsl_multimin_fdfminimizer_minimum(s));
exit;
}
/* set return values */
gsl_vector_set(x0, 0, gsl_vector_get(s->x, 0));
gsl_vector_set(x0, 1, gsl_vector_get(s->x, 1));
if (nu == 0.0) /* return optimized value */
gsl_vector_set(x0, 2, gsl_vector_get(s->x, 2));
*val = -gsl_multimin_fdfminimizer_minimum(s);
/* clean up */
//gsl_multimin_fminimizer_free(s);
gsl_multimin_fdfminimizer_free(s);
return 0;
}
// obsolete
int gsl_minimize_loglikelihood_old(const double step_size, const double tol,
const double eps_abs, const int maxiter, gsl_vector* x0, double* val, int* iter,
void* params){
/*
s (in) GSL multimin fminimizer object
eps_abs (in)
maxiter (in) maximum number of iterations
iter (in/out) number of iterations */
const gsl_multimin_fdfminimizer_type *T;
gsl_multimin_fdfminimizer *s;
gsl_multimin_function_fdf my_func;
double* tmp = (double*) params;
double nu = tmp[0];
double sigma2;
int my_iter = 0;
int status;
int converged = 0;
double start=0.4;
double median = gsl_vector_get(x0, 0);
double mad = gsl_vector_get(x0, 1);
mad = sqrt(mad/0.7);
/* init function object */
if (nu != 0.0) my_func.n = 2;
else my_func.n = 3;
my_func.f = &loglikelihood_f;
my_func.df = &loglikelihood_df;
my_func.fdf = &loglikelihood_fdf;
my_func.params = params;
/* set up solver */
T = gsl_multimin_fdfminimizer_conjugate_fr;
// T = gsl_multimin_fdfminimizer_vector_bfgs;
// T = gsl_multimin_fdfminimizer_steepest_descent;
if (nu != 0.0) s = gsl_multimin_fdfminimizer_alloc(T,2);
else s = gsl_multimin_fdfminimizer_alloc(T,3);
/* call minimizer */
//s->f = my_func->f;
//gsl_multimin_fminimizer_set(s, &my_func, x0, step_size)
gsl_multimin_fdfminimizer_set(s, &my_func, x0, step_size, tol);
do {//while (!converged && my_iter < 10){
converged = 1;
/* let gsl minimizer iterate */
do
{
status = gsl_multimin_fdfminimizer_iterate(s);
if (status) break;
status = gsl_multimin_test_gradient(s->gradient, eps_abs);
/* if (status == GSL_SUCCESS){
printf("Maximum found after %d iterations at:\n", *iter);
}
printf ("%5d %.5f %.5f %10.5f\n", *iter,
gsl_vector_get (s->x, 0), sqrt(gsl_vector_get (s->x, 1)), s->f); */
(*iter)++;
} while (status == GSL_CONTINUE && *iter < maxiter);
sigma2 = gsl_vector_get(x0, 1);
if (!isnan(sigma2)) break;
gsl_vector_set(x0, 0, median);
gsl_vector_set(x0, 1, start*mad*mad);
gsl_multimin_fdfminimizer_set (s, &my_func, x0, step_size, tol);
start = start + 0.5;
my_iter = my_iter + 1;
if (my_iter > 1) printf("-- it=%d, sigma=%lf\n", my_iter, sqrt(sigma2));
} while (my_iter < 10);
if (*iter > maxiter){
printf("!!! sigma2 is nan\n");
printf("%5d %15.5f %15.5f", *iter,
gsl_vector_get(s->x, 0),
sqrt(gsl_vector_get(s->x, 1)));
if (nu == 0.0) printf("%15.5f", gsl_vector_get(s->x, 2));
printf("%15.5f\n", -gsl_multimin_fdfminimizer_minimum(s));
}
gsl_vector_set(x0, 0, gsl_vector_get(s->x, 0));
gsl_vector_set(x0, 1, gsl_vector_get(s->x, 1));
if (nu == 0.0) /* return optimized value */
gsl_vector_set(x0, 2, gsl_vector_get(s->x, 2));
*val = -gsl_multimin_fdfminimizer_minimum(s);
/* clean up */
//gsl_multimin_fminimizer_free(s);
gsl_multimin_fdfminimizer_free(s);
return 0;
}
//endif GSL
#endif
#endif
// GSL || NR
| {
"alphanum_fraction": 0.5649626836,
"avg_line_length": 27.8458100559,
"ext": "c",
"hexsha": "0c1f3f4566d6740976f0701ed2897ab4a635d001",
"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": "d65afdb54f1ffad98dd7ec981cf33884c5e023fd",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "PSTL-UH/ADCL",
"max_forks_repo_path": "utils/robust.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d65afdb54f1ffad98dd7ec981cf33884c5e023fd",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "PSTL-UH/ADCL",
"max_issues_repo_path": "utils/robust.c",
"max_line_length": 161,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "d65afdb54f1ffad98dd7ec981cf33884c5e023fd",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "edgargabriel/ADCL",
"max_stars_repo_path": "utils/robust.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-18T19:06:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-14T00:42:21.000Z",
"num_tokens": 8086,
"size": 24922
} |
#ifndef SPC_FITSCARDS_H
#define SPC_FITSCARDS_H
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "aXe_grism.h"
#include "fitsio.h"
#include "disp_conf.h"
#include "aper_conf.h"
typedef struct
{
int n; /* Number of cards in the **cards array */
char **cards; /* A pointer to an array of strings */
} FITScards;
extern FITScards *
allocate_FITScards(int n);
extern void
free_FITScards(FITScards *cards);
extern FITScards *
get_WCS_FITScards(const double rval1, const double delta1, const double rval2);
extern FITScards *
beam_to_FITScards(object *ob, int beamnum);
extern FITScards *
stpmin_to_FITScards(d_point stp_min);
extern FITScards *
drzinfo_to_FITScards(object *ob, int beamnum, d_point outref,
aperture_conf *conf, gsl_matrix *drizzcoeffs,
int trlength, double relx, double rely,
double objwidth, d_point refwave_pos,
float sky_cps, double drizzle_width,
double cdcorr, double spcorr);
extern FITScards *
nicbck_info_to_FITScards(const double skypix_frac, const double scale_factor,
const double offset);
extern FITScards *
dispstruct_to_FITScards(dispstruct *disp);
extern void
update_contam_model(fitsfile *fptr, char model_name[]);
extern int
check_quantitative_contamination(fitsfile *fptr);
extern void
transport_cont_modname(char grism_file_path[], char PET_file_path[]);
#endif
| {
"alphanum_fraction": 0.7569493942,
"avg_line_length": 23.3833333333,
"ext": "h",
"hexsha": "984c34eb082f0e49253d10991e044004fd761e07",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spc_FITScards.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/spc_FITScards.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spc_FITScards.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 387,
"size": 1403
} |
/* multifit/gsl_multifit.h
*
* Copyright (C) 2000, 2007, 2010 Brian Gough
* Copyright (C) 2013, Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MULTIFIT_H__
#define __GSL_MULTIFIT_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_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t nmax; /* maximum number of observations */
size_t pmax; /* maximum number of parameters */
size_t n; /* number of observations in current SVD decomposition */
size_t p; /* number of parameters in current SVD decomposition */
gsl_matrix * A; /* least squares matrix for SVD, n-by-p */
gsl_matrix * Q;
gsl_matrix * QSI;
gsl_vector * S;
gsl_vector * t;
gsl_vector * xt;
gsl_vector * D;
double rcond; /* reciprocal condition number */
}
gsl_multifit_linear_workspace;
GSL_FUN gsl_multifit_linear_workspace *
gsl_multifit_linear_alloc (const size_t n, const size_t p);
GSL_FUN void
gsl_multifit_linear_free (gsl_multifit_linear_workspace * w);
GSL_FUN int
gsl_multifit_linear (const gsl_matrix * X,
const gsl_vector * y,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_tsvd (const gsl_matrix * X,
const gsl_vector * y,
const double tol,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
size_t * rank,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_svd (const gsl_matrix * X,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_bsvd (const gsl_matrix * X,
gsl_multifit_linear_workspace * work);
GSL_FUN size_t
gsl_multifit_linear_rank(const double tol, const gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_solve (const double lambda,
const gsl_matrix * X,
const gsl_vector * y,
gsl_vector * c,
double *rnorm,
double *snorm,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_applyW(const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * WX,
gsl_vector * Wy);
GSL_FUN int
gsl_multifit_linear_stdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_wstdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_L_decomp (gsl_matrix * L, gsl_vector * tau);
GSL_FUN int
gsl_multifit_linear_stdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_matrix * M,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_wstdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_matrix * M,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_genform1 (const gsl_vector * L,
const gsl_vector * cs,
gsl_vector * c,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_genform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * y,
const gsl_vector * cs,
const gsl_matrix * M,
gsl_vector * c,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_wgenform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
const gsl_vector * cs,
const gsl_matrix * M,
gsl_vector * c,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_lreg (const double smin, const double smax,
gsl_vector * reg_param);
GSL_FUN int
gsl_multifit_linear_lcurve (const gsl_vector * y,
gsl_vector * reg_param,
gsl_vector * rho, gsl_vector * eta,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_lcurvature (const gsl_vector * y,
const gsl_vector * reg_param,
const gsl_vector * rho,
const gsl_vector * eta,
gsl_vector * kappa,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_lcorner(const gsl_vector *rho,
const gsl_vector *eta,
size_t *idx);
GSL_FUN int
gsl_multifit_linear_lcorner2(const gsl_vector *reg_param,
const gsl_vector *eta,
size_t *idx);
GSL_FUN int
gsl_multifit_linear_Lk(const size_t p, const size_t k, gsl_matrix *L);
GSL_FUN int
gsl_multifit_linear_Lsobolev(const size_t p, const size_t kmax,
const gsl_vector *alpha, gsl_matrix *L,
gsl_multifit_linear_workspace *work);
GSL_FUN int
gsl_multifit_wlinear (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_wlinear_tsvd (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
const double tol,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
size_t * rank,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_wlinear_svd (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
double tol,
size_t * rank,
gsl_vector * c,
gsl_matrix * cov,
double *chisq,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_wlinear_usvd (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
double tol,
size_t * rank,
gsl_vector * c,
gsl_matrix * cov,
double *chisq,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_est (const gsl_vector * x,
const gsl_vector * c,
const gsl_matrix * cov, double *y, double *y_err);
GSL_FUN double
gsl_multifit_linear_rcond (const gsl_multifit_linear_workspace * w);
GSL_FUN int
gsl_multifit_linear_residuals (const gsl_matrix *X, const gsl_vector *y,
const gsl_vector *c, gsl_vector *r);
/* gcv.c */
GSL_FUN int
gsl_multifit_linear_gcv_init(const gsl_vector * y,
gsl_vector * reg_param,
gsl_vector * UTy,
double * delta0,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_gcv_curve(const gsl_vector * reg_param,
const gsl_vector * UTy,
const double delta0,
gsl_vector * G,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_gcv_min(const gsl_vector * reg_param,
const gsl_vector * UTy,
const gsl_vector * G,
const double delta0,
double * lambda,
gsl_multifit_linear_workspace * work);
GSL_FUN double
gsl_multifit_linear_gcv_calc(const double lambda,
const gsl_vector * UTy,
const double delta0,
gsl_multifit_linear_workspace * work);
GSL_FUN int
gsl_multifit_linear_gcv(const gsl_vector * y,
gsl_vector * reg_param,
gsl_vector * G,
double * lambda,
double * G_lambda,
gsl_multifit_linear_workspace * work);
typedef struct
{
const char * name; /* method name */
int (*wfun)(const gsl_vector *r, gsl_vector *w);
int (*psi_deriv)(const gsl_vector *r, gsl_vector *dpsi);
double tuning_default; /* default tuning constant */
} gsl_multifit_robust_type;
typedef struct
{
double sigma_ols; /* OLS estimate of sigma */
double sigma_mad; /* MAD estimate of sigma */
double sigma_rob; /* robust estimate of sigma */
double sigma; /* final estimate of sigma */
double Rsq; /* R^2 coefficient of determination */
double adj_Rsq; /* degree of freedom adjusted R^2 */
double rmse; /* root mean squared error */
double sse; /* residual sum of squares */
size_t dof; /* degrees of freedom */
size_t numit; /* number of iterations */
gsl_vector *weights; /* final weights */
gsl_vector *r; /* final residuals y - X c */
} gsl_multifit_robust_stats;
typedef struct
{
size_t n; /* number of observations */
size_t p; /* number of parameters */
size_t numit; /* number of iterations */
size_t maxiter; /* maximum iterations */
const gsl_multifit_robust_type *type;
double tune; /* tuning parameter */
gsl_vector *r; /* residuals at current iteration */
gsl_vector *weights; /* weights at current iteration */
gsl_vector *c_prev; /* coefficients from previous iteration */
gsl_vector *resfac; /* multiplicative factors for residuals */
gsl_vector *psi; /* psi(r) */
gsl_vector *dpsi; /* psi'(r) */
gsl_matrix *QSI; /* Q S^{-1} of original matrix X */
gsl_vector *D; /* balancing parameters of original matrix X */
gsl_vector *workn; /* workspace of length n */
gsl_multifit_robust_stats stats; /* various statistics */
gsl_multifit_linear_workspace *multifit_p;
} gsl_multifit_robust_workspace;
/* available types */
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_default;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_bisquare;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_cauchy;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_fair;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_huber;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_ols;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_welsch;
GSL_FUN gsl_multifit_robust_workspace *gsl_multifit_robust_alloc(const gsl_multifit_robust_type *T,
const size_t n, const size_t p);
GSL_FUN void gsl_multifit_robust_free(gsl_multifit_robust_workspace *w);
GSL_FUN int gsl_multifit_robust_tune(const double tune,
gsl_multifit_robust_workspace *w);
GSL_FUN int gsl_multifit_robust_maxiter(const size_t maxiter,
gsl_multifit_robust_workspace *w);
GSL_FUN const char *gsl_multifit_robust_name(const gsl_multifit_robust_workspace *w);
GSL_FUN gsl_multifit_robust_stats gsl_multifit_robust_statistics(const gsl_multifit_robust_workspace *w);
GSL_FUN int gsl_multifit_robust_weights(const gsl_vector *r, gsl_vector *wts,
gsl_multifit_robust_workspace *w);
GSL_FUN int gsl_multifit_robust(const gsl_matrix * X, const gsl_vector * y,
gsl_vector * c, gsl_matrix *cov,
gsl_multifit_robust_workspace *w);
GSL_FUN int gsl_multifit_robust_est(const gsl_vector * x, const gsl_vector * c,
const gsl_matrix * cov, double *y, double *y_err);
GSL_FUN int gsl_multifit_robust_residuals(const gsl_matrix * X,
const gsl_vector * y,
const gsl_vector * c, gsl_vector * r,
gsl_multifit_robust_workspace * w);
__END_DECLS
#endif /* __GSL_MULTIFIT_H__ */
| {
"alphanum_fraction": 0.5443284708,
"avg_line_length": 39.8596491228,
"ext": "h",
"hexsha": "691b91202180aabe59ef4b823c6bbcdcaca95463",
"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": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/VimbaCamJILA",
"max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_multifit.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/VimbaCamJILA",
"max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_multifit.h",
"max_line_length": 106,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgreter/astrometrylib",
"max_stars_repo_path": "vendor/gsl/gsl/gsl_multifit.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 3344,
"size": 15904
} |
/**
*
* @file core_spamm.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 Dulceneia Becker
* @date 2011-06-14
* @generated s Tue Jan 7 11:44:49 2014
*
**/
#include <cblas.h>
#include <lapacke.h>
#include "common.h"
static inline int CORE_spamm_a2(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,
int M, int N, int K, int L,
int vi2, int vi3,
float *A2, int LDA2,
const float *V, int LDV,
float *W, int LDW);
static inline int CORE_spamm_w(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,
int M, int N, int K, int L,
int vi2, int vi3,
const float *A1, int LDA1,
float *A2, int LDA2,
const float *V, int LDV,
float *W, int LDW);
/***************************************************************************//**
*
* @ingroup CORE_float
*
* ZPAMM performs one of the matrix-matrix operations
*
* LEFT RIGHT
* OP PlasmaW : W = A1 + op(V) * A2 or W = A1 + A2 * op(V)
* OP PlasmaA2 : A2 = A2 - op(V) * W or A2 = A2 - W * op(V)
*
* where op( V ) is one of
*
* op( V ) = V or op( V ) = V**T or op( V ) = V**T,
*
* A1, A2 and W are general matrices, and V is:
*
* l = k: rectangle + triangle
* l < k: rectangle + trapezoid
* l = 0: rectangle
*
* Size of V, both rowwise and columnwise, is:
*
* ----------------------
* side trans size
* ----------------------
* left N M x K
* T K x M
* right N K x N
* T N x K
* ----------------------
*
* LEFT (columnwise and rowwise):
*
* | K | | M |
* _ __________ _ _______________ _
* | | | | | \
* V: | | | V': |_____________|___\ K
* | | | M-L | |
* M | | | |__________________| _
* |____| | _
* \ | | | M - L | L |
* \ | | L
* _ \|____| _
*
*
* RIGHT (columnwise and rowwise):
*
* | K | | N |
* _______________ _ _ __________ _
* | | \ | | |
* V': |_____________|___\ N V: | | |
* | | | | | K-L
* |__________________| _ K | | |
* |____| | _
* | K - L | L | \ | |
* \ | | L
* _ \|____| _
*
* Arguments
* ==========
*
* @param[in] op
*
* OP specifies which operation to perform:
*
* @arg PlasmaW : W = A1 + op(V) * A2 or W = A1 + A2 * op(V)
* @arg PlasmaA2 : A2 = A2 - op(V) * W or A2 = A2 - W * op(V)
*
* @param[in] side
*
* SIDE specifies whether op( V ) multiplies A2
* or W from the left or right as follows:
*
* @arg PlasmaLeft : multiply op( V ) from the left
* OP PlasmaW : W = A1 + op(V) * A2
* OP PlasmaA2 : A2 = A2 - op(V) * W
*
* @arg PlasmaRight : multiply op( V ) from the right
* OP PlasmaW : W = A1 + A2 * op(V)
* OP PlasmaA2 : A2 = A2 - W * op(V)
*
* @param[in] storev
*
* Indicates how the vectors which define the elementary
* reflectors are stored in V:
*
* @arg PlasmaColumnwise
* @arg PlasmaRowwise
*
* @param[in] M
* The number of rows of the A1, A2 and W
* If SIDE is PlasmaLeft, the number of rows of op( V )
*
* @param[in] N
* The number of columns of the A1, A2 and W
* If SIDE is PlasmaRight, the number of columns of op( V )
*
* @param[in] K
* If SIDE is PlasmaLeft, the number of columns of op( V )
* If SIDE is PlasmaRight, the number of rows of op( V )
*
* @param[in] L
* The size of the triangular part of V
*
* @param[in] A1
* On entry, the M-by-N tile A1.
*
* @param[in] LDA1
* The leading dimension of the array A1. LDA1 >= max(1,M).
*
* @param[in,out] A2
* On entry, the M-by-N tile A2.
* On exit, if OP is PlasmaA2 A2 is overwritten
*
* @param[in] LDA2
* The leading dimension of the tile A2. LDA2 >= max(1,M).
*
* @param[in] V
* The matrix V as described above.
* If SIDE is PlasmaLeft : op( V ) is M-by-K
* If SIDE is PlasmaRight: op( V ) is K-by-N
*
* @param[in] LDV
* The leading dimension of the array V.
*
* @param[in,out] W
* On entry, the M-by-N matrix W.
* On exit, W is overwritten either if OP is PlasmaA2 or PlasmaW.
* If OP is PlasmaA2, W is an input and is used as a workspace.
*
* @param[in] LDW
* The leading dimension of array WORK.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
int
CORE_spamm(int op, PLASMA_enum side, PLASMA_enum storev,
int M, int N, int K, int L,
const float *A1, int LDA1,
float *A2, int LDA2,
const float *V, int LDV,
float *W, int LDW)
{
int vi2, vi3, uplo, trans, info;
/* Check input arguments */
if ((op != PlasmaW) && (op != PlasmaA2)) {
coreblas_error(1, "Illegal value of op");
return -1;
}
if ((side != PlasmaLeft) && (side != PlasmaRight)) {
coreblas_error(2, "Illegal value of side");
return -2;
}
if ((storev != PlasmaColumnwise) && (storev != PlasmaRowwise)) {
coreblas_error(3, "Illegal value of storev");
return -3;
}
if (M < 0) {
coreblas_error(4, "Illegal value of M");
return -4;
}
if (N < 0) {
coreblas_error(5, "Illegal value of N");
return -5;
}
if (K < 0) {
coreblas_error(6, "Illegal value of K");
return -6;
}
if (L < 0) {
coreblas_error(7, "Illegal value of L");
return -7;
}
if (LDA1 < 0) {
coreblas_error(9, "Illegal value of LDA1");
return -9;
}
if (LDA2 < 0) {
coreblas_error(11, "Illegal value of LDA2");
return -11;
}
if (LDV < 0) {
coreblas_error(13, "Illegal value of LDV");
return -13;
}
if (LDW < 0) {
coreblas_error(15, "Illegal value of LDW");
return -15;
}
/* Quick return */
if ((M == 0) || (N == 0) || (K == 0))
return PLASMA_SUCCESS;
/*
* TRANS is set as:
*
* -------------------------------------
* side direct PlasmaW PlasmaA2
* -------------------------------------
* left colwise T N
* rowwise N T
* right colwise N T
* rowwise T N
* -------------------------------------
*/
/* Columnwise*/
if (storev == PlasmaColumnwise) {
uplo = CblasUpper;
if (side == PlasmaLeft) {
trans = op == PlasmaA2 ? PlasmaNoTrans : PlasmaTrans;
vi2 = trans == PlasmaNoTrans ? M - L : K - L;
}
else {
trans = op == PlasmaW ? PlasmaNoTrans : PlasmaTrans;
vi2 = trans == PlasmaNoTrans ? K - L : N - L;
}
vi3 = LDV * L;
}
/* Rowwise */
else {
uplo = CblasLower;
if (side == PlasmaLeft) {
trans = op == PlasmaW ? PlasmaNoTrans : PlasmaTrans;
vi2 = trans == PlasmaNoTrans ? K - L : M - L;
}
else {
trans = op == PlasmaA2 ? PlasmaNoTrans : PlasmaTrans;
vi2 = trans == PlasmaNoTrans ? N - L : K - L;
}
vi2 *= LDV;
vi3 = L;
}
/**/
if (op==PlasmaW) {
info = CORE_spamm_w(
side, trans, uplo, M, N, K, L, vi2, vi3,
A1, LDA1, A2, LDA2, V, LDV, W, LDW);
if (info != 0)
return info;
} else if (op==PlasmaA2) {
info = CORE_spamm_a2(
side, trans, uplo, M, N, K, L, vi2, vi3,
A2, LDA2, V, LDV, W, LDW);
if (info != 0)
return info;
}
return PLASMA_SUCCESS;
}
/***************************************************************************/
static inline int
CORE_spamm_w(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,
int M, int N, int K, int L,
int vi2, int vi3,
const float *A1, int LDA1,
float *A2, int LDA2,
const float *V, int LDV,
float *W, int LDW)
{
/*
* W = A1 + op(V) * A2 or W = A1 + A2 * op(V)
*/
int j;
static float zone = 1.0;
static float zzero = 0.0;
if (side == PlasmaLeft) {
if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||
((trans == PlasmaNoTrans) && (uplo == CblasLower))) {
/*
* W = A1 + V' * A2
*/
/* W = A2_2 */
LAPACKE_slacpy_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaUpperLower),
L, N,
&A2[K-L], LDA2, W, LDW);
/* W = V_2' * W + V_1' * A2_1 (ge+tr, top L rows of V') */
if (L > 0) {
/* W = V_2' * W */
cblas_strmm(
CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, L, N,
(zone), &V[vi2], LDV,
W, LDW);
/* W = W + V_1' * A2_1 */
if (K > L) {
cblas_sgemm(
CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,
L, N, K-L,
(zone), V, LDV,
A2, LDA2,
(zone), W, LDW);
}
}
/* W_2 = V_3' * A2: (ge, bottom M-L rows of V') */
if (M > L) {
cblas_sgemm(
CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,
(M-L), N, K,
(zone), &V[vi3], LDV,
A2, LDA2,
(zzero), &W[L], LDW);
}
/* W = A1 + W */
for(j = 0; j < N; j++) {
cblas_saxpy(
M, (zone),
&A1[LDA1*j], 1,
&W[LDW*j], 1);
}
}
else {
printf("Left Upper/NoTrans & Lower/ConjTrans not implemented yet\n");
return PLASMA_ERR_NOT_SUPPORTED;
}
}
else { //side right
if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||
((trans == PlasmaNoTrans) && (uplo == CblasLower))) {
printf("Right Upper/ConjTrans & Lower/NoTrans not implemented yet\n");
return PLASMA_ERR_NOT_SUPPORTED;
}
else {
/*
* W = A1 + A2 * V
*/
if (L > 0) {
/* W = A2_2 */
LAPACKE_slacpy_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaUpperLower),
M, L,
&A2[LDA2*(K-L)], LDA2, W, LDW);
/* W = W * V_2 --> W = A2_2 * V_2 */
cblas_strmm(
CblasColMajor, CblasRight, (CBLAS_UPLO)uplo,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, M, L,
(zone), &V[vi2], LDV,
W, LDW);
/* W = W + A2_1 * V_1 */
if (K > L) {
cblas_sgemm(
CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,
M, L, K-L,
(zone), A2, LDA2,
V, LDV,
(zone), W, LDW);
}
}
/* W = W + A2 * V_3 */
if (N > L) {
cblas_sgemm(
CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,
M, N-L, K,
(zone), A2, LDA2,
&V[vi3], LDV,
(zzero), &W[LDW*L], LDW);
}
/* W = A1 + W */
for (j = 0; j < N; j++) {
cblas_saxpy(
M, (zone),
&A1[LDA1*j], 1,
&W[LDW*j], 1);
}
}
}
return PLASMA_SUCCESS;
}
/***************************************************************************/
static inline int
CORE_spamm_a2(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,
int M, int N, int K, int L,
int vi2, int vi3,
float *A2, int LDA2,
const float *V, int LDV,
float *W, int LDW)
{
/*
* A2 = A2 + op(V) * W or A2 = A2 + W * op(V)
*/
int j;
static float zone = 1.0;
static float mzone = -1.0;
if (side == PlasmaLeft) {
if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||
((trans == PlasmaNoTrans) && (uplo == CblasLower))) {
printf("Left Upper/ConjTrans & Lower/NoTrans not implemented yet\n");
return PLASMA_ERR_NOT_SUPPORTED;
}
else { //trans
/*
* A2 = A2 - V * W
*/
/* A2_1 = A2_1 - V_1 * W_1 */
if (M > L) {
cblas_sgemm(
CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,
M-L, N, L,
(mzone), V, LDV,
W, LDW,
(zone), A2, LDA2);
}
/* W_1 = V_2 * W_1 */
cblas_strmm(
CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, L, N,
(zone), &V[vi2], LDV,
W, LDW);
/* A2_2 = A2_2 - W_1 */
for(j = 0; j < N; j++) {
cblas_saxpy(
L, (mzone),
&W[LDW*j], 1,
&A2[LDA2*j+(M-L)], 1);
}
/* A2 = A2 - V_3 * W_2 */
if (K > L) {
cblas_sgemm(
CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,
M, N, (K-L),
(mzone), &V[vi3], LDV,
&W[L], LDW,
(zone), A2, LDA2);
}
}
}
else { //side right
if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||
((trans == PlasmaNoTrans) && (uplo == CblasLower))) {
/*
* A2 = A2 - W * V'
*/
/* A2 = A2 - W_2 * V_3' */
if (K > L) {
cblas_sgemm(
CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,
M, N, K-L,
(mzone), &W[LDW*L], LDW,
&V[vi3], LDV,
(zone), A2, LDA2);
}
/* A2_1 = A2_1 - W_1 * V_1' */
if (N > L) {
cblas_sgemm(
CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,
M, N-L, L,
(mzone), W, LDW,
V, LDV,
(zone), A2, LDA2);
}
/* A2_2 = A2_2 - W_1 * V_2' */
if (L > 0) {
cblas_strmm(
CblasColMajor, CblasRight, (CBLAS_UPLO)uplo,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, M, L,
(mzone), &V[vi2], LDV,
W, LDW);
for (j = 0; j < L; j++) {
cblas_saxpy(
M, (zone),
&W[LDW*j], 1,
&A2[LDA2*(N-L+j)], 1);
}
}
}
else {
printf("Right Upper/NoTrans & Lower/ConjTrans not implemented yet\n");
return PLASMA_ERR_NOT_SUPPORTED;
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.3817897842,
"avg_line_length": 30.7597864769,
"ext": "c",
"hexsha": "d64e5b39c283b0862a8f0aea055eef9c4d39d073",
"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_spamm.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_spamm.c",
"max_line_length": 86,
"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_spamm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4787,
"size": 17287
} |
/* expfit.c -- model functions for exponential + background */
#include <math.h>
#include <stddef.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
struct usertype {
size_t n;
double * y;
double * sigma;
};
int expb_f (const gsl_vector * x, void *data,
gsl_vector * f) {
size_t n = ((struct usertype *)data)->n;
double *y = ((struct usertype *)data)->y;
double *sigma = ((struct usertype *) data)->sigma;
double A = gsl_vector_get (x, 0);
double lambda = gsl_vector_get (x, 1);
double b = gsl_vector_get (x, 2);
size_t i;
for (i = 0; i < n; i++)
{
/* Model Yi = A * exp(-lambda * i) + b */
double t = i;
double Yi = A * exp (-lambda * t) + b;
gsl_vector_set (f, i, (Yi - y[i])/sigma[i]);
}
return GSL_SUCCESS;
}
int expb_df (const gsl_vector * x, void *params,
gsl_matrix * J) {
struct usertype *myparams = (struct usertype *) params;
int n = myparams->n;
double *sigma = myparams->sigma;
double A = gsl_vector_get (x, 0);
double lambda = gsl_vector_get (x, 1);
size_t i;
/*for (i = 0; i<10; i++){
printf("sigma[%z] = %5.3f\n",i,sigma[i]);
}*/
for (i = 0; i < n; i++)
{
/* Jacobian matrix J(i,j) = dfi / dxj, */
/* where fi = (Yi - yi)/sigma[i], */
/* Yi = A * exp(-lambda * i) + b */
/* and the xj are the parameters (A,lambda,b) */
double t = i;
double s = sigma[i];
double e = exp(-lambda * t);
gsl_matrix_set (J, i, 0, e/s);
gsl_matrix_set (J, i, 1, -t * A * e/s);
gsl_matrix_set (J, i, 2, 1/s);
}
return GSL_SUCCESS;
}
int expb_fdf (const gsl_vector * x, void *data,
gsl_vector * f, gsl_matrix * J) {
expb_f (x, data, f);
expb_df (x, data, J);
return GSL_SUCCESS;
}
void eval_F ( int fstatus, const int n, const int m,
const double *x, double *f, const void *params){
// first, convert x from an array into a gsl_vector...
gsl_vector * x_gsl = gsl_vector_alloc(n);
int i;
for (i = 0; i < n; i++) {
gsl_vector_set(x_gsl,i,x[i]);
}
// then call the expb_f function
gsl_vector * f_gsl = gsl_vector_alloc(m);
expb_f ( x_gsl, params, f_gsl);
// then convert f back into an array...
// f = f_gsl->data;
for (i = 0; i < m; i++){
f[i] = gsl_vector_get( f_gsl,i);
// f[i] = f_gsl->data[i];
}
gsl_vector_free(x_gsl);
gsl_vector_free(f_gsl);
}
void eval_J ( int fstatus, const int n, const int m,
const double *x, double *J, const void *params){
// first, convert x from an array into a gsl_vector...
gsl_vector * x_gsl = gsl_vector_alloc(n);
int i;
int jj;
for (i = 0; i < n; i++) {
gsl_vector_set(x_gsl,i,x[i]);
}
// then call the expb_f function
gsl_matrix * J_gsl = gsl_matrix_alloc(40,3);
expb_df (x_gsl, params, J_gsl);
// then convert J into an array...
// (find better way...)
gsl_matrix * J_gsl_t = gsl_matrix_alloc(3,40);
gsl_matrix_transpose_memcpy(J_gsl_t, J_gsl);
for ( i = 0; i < m*n; i++){
J[i] = J_gsl_t->data[i];
}
// the following code loses the pointer to J (maybe...)
// J = J_gsl_t->data;
gsl_vector_free(x_gsl);
gsl_matrix_free(J_gsl);
gsl_matrix_free(J_gsl_t);
}
void eval_HF ( int fstatus, const int n, const int m,
const double *x, const double *f, double *hf, const void *params){
}
| {
"alphanum_fraction": 0.5764809903,
"avg_line_length": 23.5625,
"ext": "c",
"hexsha": "1b30ae586c6cfee536151788f72468f4d26792cd",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-08-23T17:12:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-02T12:24:47.000Z",
"max_forks_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "andpic/RALFit",
"max_forks_repo_path": "libRALFit/example/C/expfit.c",
"max_issues_count": 95,
"max_issues_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3",
"max_issues_repo_issues_event_max_datetime": "2021-07-23T14:08:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-09-13T15:16:54.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "andpic/RALFit",
"max_issues_repo_path": "libRALFit/example/C/expfit.c",
"max_line_length": 74,
"max_stars_count": 25,
"max_stars_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "andpic/RALFit",
"max_stars_repo_path": "libRALFit/example/C/expfit.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-04-02T12:24:44.000Z",
"num_tokens": 1125,
"size": 3393
} |
/*
* Dice Tester - Counter tool to display statistics about the randomness of dice
*/
#include <gsl/gsl_cdf.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
getSides(int argc, char **argv) {
int sides = 6;
if (argc >= 2 && atoi(argv[1]) > 0)
sides = atoi(argv[1]);
return sides;
}
double
chiSquared(double *observed, double *expected, int sides) {
double sum = 0.0;
for (int i = 0; i < sides; i++)
sum += pow((observed[i] - expected[i]), 2) / expected[i];
return sum;
}
int
main(int argc, char **argv)
{
char input[8];
int num, total, sides, memSize;
double *observed, *expected;
total = 0;
sides = getSides(argc, argv);
memSize = sizeof(double) * sides;
observed = malloc(memSize);
expected = malloc(memSize);
printf("HERE %d\n", sides);
for (int i = 0; i < sides; i++)
observed[i] = 0.0;
printf("HERE %d\n", sides);
printf("Obs: %f\n", observed[0]);
/* Load observed data */
while (scanf("%s", input) != EOF) {
num = atoi(input);
if (num >= 1 && num <= sides) {
printf("%d\n", num);
observed[num-1] += 1;
total += 1;
}
getchar();
}
/* Random = flat distribution */
for (int i = 0; i < sides; i++)
expected[i] = (double) total / sides;
double chi2 = chiSquared(observed, expected, sides);
double pval = 1-gsl_cdf_chisq_P(chi2, sides-1);
fputs("\n########## RESULTS ##########\n", stderr);
fputs("Num:\tExp:\tObs:\tPer:\t\n", stderr);
for (int i = 0; i < sides; i++)
fprintf(stderr, "%d:\t %2.0f\t %2.0f\t %3.0f%%\n", i+1, expected[i], observed[i], (observed[i] / total)*100);
if (pval >= 0.1)
fputs("\nDie is fair :)\n", stderr);
else if (pval > 0.05)
fputs("\nDie is probably fair\n", stderr);
else
fputs("\nDie not fair :(\n", stderr);
free(observed);
free(expected);
return 0;
}
| {
"alphanum_fraction": 0.5752401281,
"avg_line_length": 23.1358024691,
"ext": "c",
"hexsha": "58beb881a92a59a58dc580f4405b8dae0c6e9fcb",
"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": "43c4c656bfe92d7815eb9850e39eea84ff81dfe7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Seth0110/dicetester",
"max_forks_repo_path": "dt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "43c4c656bfe92d7815eb9850e39eea84ff81dfe7",
"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": "Seth0110/dicetester",
"max_issues_repo_path": "dt.c",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "43c4c656bfe92d7815eb9850e39eea84ff81dfe7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Seth0110/dicetester",
"max_stars_repo_path": "dt.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 616,
"size": 1874
} |
/* interpolation/interp_poly.c
*
* Copyright (C) 2001 DAN, HO-JIN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_interp.h>
typedef struct
{
double *d;
double *coeff;
double *work;
}
polynomial_state_t;
static void *
polynomial_alloc (size_t size)
{
polynomial_state_t *state =
(polynomial_state_t *) malloc (sizeof (polynomial_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for polynomial state",
GSL_ENOMEM);
}
state->d = (double *) malloc (sizeof (double) * size);
if (state->d == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for d", GSL_ENOMEM);
}
state->coeff = (double *) malloc (sizeof (double) * size);
if (state->coeff == 0)
{
free (state->d);
free (state);
GSL_ERROR_NULL ("failed to allocate space for d", GSL_ENOMEM);
}
state->work = (double *) malloc (sizeof (double) * size);
if (state->work == 0)
{
free (state->coeff);
free (state->d);
free (state);
GSL_ERROR_NULL ("failed to allocate space for d", GSL_ENOMEM);
}
return state;
}
static int
polynomial_init (void *vstate,
const double xa[], const double ya[], size_t size)
{
polynomial_state_t *state = (polynomial_state_t *) vstate;
int status = gsl_poly_dd_init (state->d, xa, ya, size);
return status;
}
static int
polynomial_eval (const void *vstate,
const double xa[], const double ya[], size_t size, double x,
gsl_interp_accel * acc, double *y)
{
const polynomial_state_t *state = (const polynomial_state_t *) vstate;
*y = gsl_poly_dd_eval (state->d, xa, size, x);
return GSL_SUCCESS;
}
static int
polynomial_deriv (const void *vstate,
const double xa[], const double ya[], size_t size, double x,
gsl_interp_accel * acc, double *y)
{
const polynomial_state_t *state = (const polynomial_state_t *) vstate;
gsl_poly_dd_taylor (state->coeff, x, state->d, xa, size, state->work);
*y = state->coeff[1];
return GSL_SUCCESS;
}
static int
polynomial_deriv2 (const void *vstate,
const double xa[], const double ya[], size_t size,
double x, gsl_interp_accel * acc, double *y)
{
const polynomial_state_t *state = (const polynomial_state_t *) vstate;
gsl_poly_dd_taylor (state->coeff, x, state->d, xa, size, state->work);
*y = 2.0 * state->coeff[2];
return GSL_SUCCESS;
}
static int
polynomial_integ (const void *vstate, const double xa[], const double ya[],
size_t size, gsl_interp_accel * acc, double a, double b,
double *result)
{
const polynomial_state_t *state = (const polynomial_state_t *) vstate;
size_t i;
double sum;
gsl_poly_dd_taylor (state->coeff, 0.0, state->d, xa, size, state->work);
sum = state->coeff[0] * (b - a);
for (i = 1; i < size; i++)
{
sum += state->coeff[i] * (pow (b, i + 1) - pow (a, i + 1)) / (i + 1.0);
}
*result = sum;
return GSL_SUCCESS;
}
static void
polynomial_free (void *vstate)
{
polynomial_state_t *state = (polynomial_state_t *) vstate;
free (state->d);
free (state->coeff);
free (state->work);
free (state);
}
static const gsl_interp_type polynomial_type = {
"polynomial",
3,
&polynomial_alloc,
&polynomial_init,
&polynomial_eval,
&polynomial_deriv,
&polynomial_deriv2,
&polynomial_integ,
&polynomial_free,
};
const gsl_interp_type *gsl_interp_polynomial = &polynomial_type;
| {
"alphanum_fraction": 0.6510500808,
"avg_line_length": 24.9022988506,
"ext": "c",
"hexsha": "a0cd68aa123614e21ec2d653d03894000a6b4237",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/interpolation/poly.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/interpolation/poly.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/interpolation/poly.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": 1169,
"size": 4333
} |
// matrix.h
// This matrix class is a C++ wrapper for the GNU Scientific Library
// Copyright (C) 2001 Ramin Nakisa
// 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.
#if !defined( _matrix_int_h )
#define _matrix_int_h
#ifdef __HP_aCC //for aCC B3910B A.01.27
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#else //for gcc3
#include <iostream>
#include <fstream>
#include <iomanip>
#endif
#include <math.h>
#include <stdlib.h>
#include <assert.h>
///
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix_int.h>
#include <gsl/gsl_linalg.h>
#include <gslwrap/permutation.h>
#include <gslwrap/vector_int.h>
#define type_is_int
#ifdef type_is
#define type_is_double
#endif
namespace gsl
{
///
class matrix_int
{
#ifdef type_is_double
friend class matrix_float;
friend class matrix_int;
#endif
public:
typedef int value_type;
typedef vector_int vector_type;
///
matrix_int();
///
matrix_int( size_t new_rows, size_t new_cols, bool clear = true );
template<class oclass>
void copy(const oclass &other)
{
if ( static_cast<const void *>( this ) == static_cast<const void *>( &other ) )
return;
set_dimensions( other.get_rows(), other.get_cols() );
for ( size_t i = 0; i < get_rows(); i++ )
{
for ( size_t j = 0; j < get_cols(); j++ )
{
gsl_matrix_int_set( m, i, j, (int)other(i,j));
}
}
}
/* template<> */
/* void copy<matrix_int>(const matrix_int &other) */
/* { */
/* set_dimensions(other.size1(),other.size2()); */
/* gsl_matrix_int_memcpy( m, other.m ); */
/* } */
// copy constructor for type matrix_int
matrix_int( const matrix_int &other ):m(NULL) {copy(other);}
///
template<class oclass>
matrix_int( const oclass &other ):m(NULL) {copy(other);}
///
~matrix_int();
///
// matrix_int( const char *Filename );
///
size_t get_rows() const {return m->size1;}
///
size_t get_cols() const {return m->size2;}
///
size_t size1() const {return m->size1;}
///
size_t size2() const {return m->size2;}
///
void dimensions( size_t *num_rows, size_t *num_cols ) const;
///
int get_element ( size_t row, size_t col ) const {return gsl_matrix_int_get( m, row, col ) ;}
const int &operator()( size_t row, size_t col ) const {return *gsl_matrix_int_ptr( m, row, col ) ;}
int &operator()( size_t row, size_t col ) {return *gsl_matrix_int_ptr( m, row, col ) ;}
///
void set_element( size_t row, size_t col, const int &v ){ gsl_matrix_int_set( m, row, col, v );}
///
void set_elements( const int & new_value );
void set_all ( const int & new_value ) {gsl_matrix_int_set_all ( m, new_value );}
void set_zero() {gsl_matrix_int_set_zero( m );}
///
void set_dimensions( size_t new_rows, size_t new_cols );
///
void load( const char *filename );
///
void save( const char *filename ) const;
///
friend ostream& operator<< ( ostream& os, const matrix_int& m );
//This function writes the elements of the matrix m to the stream stream in binary format. The return value is 0 for success and GSL_EFAILED if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures.
int fwrite (FILE * stream) const {return gsl_matrix_int_fwrite (stream, m);}
//This function reads into the matrix m from the open stream stream in binary format. The matrix m must be preallocated with the correct dimensions since the function uses the size of m to determine how many bytes to read. The return value is 0 for success and GSL_EFAILED if there was a problem reading from the file. The data is assumed to have been written in the native binary format on the same architecture.
int fread (FILE * stream) {return gsl_matrix_int_fread (stream, m);}
///
void load_binary( const char *filename );
///
void save_binary( const char *filename ) const;
///
bool operator==( const matrix_int &other ) const;
bool operator!=( const matrix_int &other ) const {return !((*this)==other);}
matrix_int& operator=( const matrix_int &other ) {copy( other );return *this;}
/// converts from any other matrix type
template<class omatrix>
matrix_int &operator=( const omatrix& other )
{
copy(other);
return *this;
}
///
matrix_int operator+( const matrix_int &other ) const;
///
matrix_int operator+( const int &f ) const;
///
friend matrix_int operator+( const int &f, const matrix_int &other );
///
matrix_int &operator+=( const int &f );
///
matrix_int &operator+=( const matrix_int &other );
///
matrix_int operator-( const matrix_int &other ) const;
///
matrix_int operator-( const int &f ) const;
///
friend matrix_int operator-( const int &f, const matrix_int &other );
///
matrix_int &operator-=( const int &f );
///
matrix_int &operator-=( const matrix_int &other );
///
matrix_int operator*( const matrix_int &other ) const;
///
matrix_int operator*( const int &f ) const;
///
friend matrix_int operator*( const int &f, const matrix_int &other );
///
matrix_int &operator*=( const int &f );
///
matrix_int &operator*=( const matrix_int &other );
///
matrix_int operator/( const int &) const;
///
matrix_int &operator/=( const int &);
///
matrix_int transpose() const;
///
matrix_int LU_decomp(gsl::permutation *perm=NULL,int *psign=NULL) const;
///
matrix_int LU_invert() const;
// return a submatrix of the this from row_min to row_max (not included!)
matrix_int submatrix(size_t row_min, size_t row_max, size_t col_min, size_t col_max) const
{
matrix_int m(row_max - row_min, col_max - col_min);
for (size_t i = row_min ; i < row_max ; i++)
{
for (size_t j = col_min ; j < col_max ; j++)
{
m(i - row_min,j - col_min) = (*this)(i,j);
}
}
return m;
}
private:
///
void LU_decomp( gsl_matrix_int **a,
gsl_permutation **permutation,
int *sign ) const;
public:
/** returns sum of all the matrix elements. */
int sum() const;
/** returns logarithm of the determinant of the matrix. */
double LU_lndet() const;
/** returns a vector_int_view of a single row of the matrix. */
vector_int_view row( size_t rowindex );
const vector_int_view row( size_t rowindex ) const ;
/** returns a vector_int_view of a single column of the matrix. */
vector_int_view column( size_t colindex );
const vector_int_view column( size_t colindex ) const;
/** returns a vector_int_view of the diagonal elements of the matrix. */
vector_int_view diagonal();
const vector_int_view diagonal() const;
/** returns a column matrix containing a single row of the matrix. */
matrix_int get_row( size_t rowindex ) const;
/** returns a column matrix containing a single column of the matrix. */
matrix_int get_col( size_t colindex ) const;
/** calculates sum of rows returned as a column matrix. */
matrix_int row_sum() const;
/** calculates sum of columns returned as a row matrix. */
matrix_int column_sum() const;
/** returns trace (diagonal sum) of a square matrix. */
double trace() const;
/** calculates cholesky decomposition of the matrix, returning success if matrix is positive definite. */
int cholesky_decomp( matrix_int &a ) const;
// /** returns index of nearest row in matrix to vector argument. */
// int nearest_row_index( const matrix_int &v ) const;
/** calculates covariance of the matrix columns. */
matrix_int covariance() const;
/** returns 1 if matrix is square, 0 otherwise. */
bool is_square() const;
/** diag operator (sets the diagonal elements of the matrix to the elements of v */
void diag(const vector_int& v);
/** set diagonal elements of a square matrix to f. */
void set_diagonal( int f );
/** sets matrix to a k dimensional unit matrix. */
void identity( size_t k );
/** returns sum of nth power of all elements. */
double norm( double n ) const;
/* Function: double gsl_matrix_max (const gsl_matrix * m) */
/* This function returns the maximum value in the matrix m. */
double max() const {return gsl_matrix_int_max(m);}
/* Function: double gsl_matrix_min (const gsl_matrix * m) */
/* This function returns the minimum value in the matrix m. */
double min()const{return gsl_matrix_int_min(m);}
/** This function returns 1 if all the elements of the matrix m are zero, and 0 otherwise. */
bool isnull() const { return gsl_matrix_int_isnull(m);}
/* Function: void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out) */
/* This function returns the minimum and maximum values in the matrix m, storing them in min_out and max_out. */
/* Function: void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t * jmax) */
/* This function returns the indices of the maximum value in the matrix m, storing them in imax and jmax. When there are several equal maximum elements then the first element found */
/* is returned. */
/* Function: void gsl_matrix_min_index (const gsl_matrix * m, size_t * imax, size_t * jmax) */
/* This function returns the indices of the minimum value in the matrix m, storing them in imax and jmax. When there are several equal minimum elements then the first element found */
/* is returned. */
/* Function: void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * imax) */
/* This function returns the indices of the minimum and maximum values in the matrix m, storing them in (imin,jmin) and (imax,jmax). When there are several equal minimum or */
/* maximum elements then the first elements found are returned. */
/** for interfacing with gsl c */
/* gsl_matrix_int *gslobj() {if (!m){cout << "matrix_int::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return m;} */
/* const gsl_matrix_int *gslobj() const {if (!m){cout << "matrix_int::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return m;} */
gsl_matrix_int *gslobj() {assert(m);return m;}
const gsl_matrix_int *gslobj() const {assert(m);return m;}
private:
///
gsl_matrix_int *m;
};
}
#undef type_is_int
#undef type_is_double
#endif // _matrix_int_h
| {
"alphanum_fraction": 0.6937674419,
"avg_line_length": 36.8150684932,
"ext": "h",
"hexsha": "96377d108d9e0ba5b24e88c2e3b867730dfcee97",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_forks_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_forks_repo_name": "entn-at/GlottDNN",
"max_forks_repo_path": "src/gslwrap/matrix_int.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_issues_repo_name": "entn-at/GlottDNN",
"max_issues_repo_path": "src/gslwrap/matrix_int.h",
"max_line_length": 414,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_stars_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_stars_repo_name": "entn-at/GlottDNN",
"max_stars_repo_path": "src/gslwrap/matrix_int.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z",
"num_tokens": 2748,
"size": 10750
} |
/**
*
* @file zcgels.c
*
* PLASMA computational routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Emmanuel Agullo
* @date 2010-11-15
* @precisions mixed zc -> ds
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <lapacke.h>
#include "common.h"
#define PLASMA_zlag2c(_descA, _descSB) \
plasma_parallel_call_4(plasma_pzlag2c, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descSB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_clag2z(_descSA, _descB) \
plasma_parallel_call_4(plasma_pclag2z, \
PLASMA_desc, (_descSA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_zlange(_norm, _descA, _result, _work) \
_result = 0; \
plasma_parallel_call_6(plasma_pzlange, \
PLASMA_enum, (_norm), \
PLASMA_desc, (_descA), \
double*, (_work), \
double*, &(_result), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request);
#define PLASMA_zlacpy(_descA, _descB) \
plasma_parallel_call_5(plasma_pzlacpy, \
PLASMA_enum, PlasmaUpperLower, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_zgeadd(_alpha, _descA, _descB) \
plasma_parallel_call_5(plasma_pzgeadd, \
PLASMA_Complex64_t, (_alpha), \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t
*
* PLASMA_zcgels - Solves overdetermined or underdetermined linear systems involving an M-by-N
* matrix A using the QR or the LQ factorization of A. It is assumed that A has full rank.
* The following options are provided:
*
* # trans = PlasmaNoTrans and M >= N: find the least squares solution of an overdetermined
* system, i.e., solve the least squares problem: minimize || B - A*X ||.
*
* # trans = PlasmaNoTrans and M < N: find the minimum norm solution of an underdetermined
* system A * X = B.
*
* Several right hand side vectors B and solution vectors X can be handled in a single call;
* they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS
* solution matrix X.
*
* PLASMA_zcgels first attempts to factorize the matrix in COMPLEX and use this
* factorization within an iterative refinement procedure to produce a
* solution with COMPLEX*16 normwise backward error quality (see below).
* If the approach fails the method switches to a COMPLEX*16
* factorization and solve.
*
* The iterative refinement is not going to be a winning strategy if
* the ratio COMPLEX performance over COMPLEX*16 performance is too
* small. A reasonable strategy should take the number of right-hand
* sides and the size of the matrix into account. This might be done
* with a call to ILAENV in the future. Up to now, we always try
* iterative refinement.
*
* The iterative refinement process is stopped if ITER > ITERMAX or
* for all the RHS we have: RNRM < N*XNRM*ANRM*EPS*BWDMAX
* where:
*
* - ITER is the number of the current iteration in the iterative refinement process
* - RNRM is the infinity-norm of the residual
* - XNRM is the infinity-norm of the solution
* - ANRM is the infinity-operator-norm of the matrix A
* - EPS is the machine epsilon returned by DLAMCH('Epsilon').
*
* Actually, in its current state (PLASMA 2.1.0), the test is slightly relaxed.
*
* The values ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 respectively.
*
* We follow Bjorck's algorithm proposed in "Iterative Refinement of Linear
* Least Squares solutions I", BIT, 7:257-278, 1967.
*
*******************************************************************************
*
* @param[in] trans
* Intended usage:
* = PlasmaNoTrans: the linear system involves A;
* = PlasmaConjTrans: the linear system involves A**H.
* Currently only PlasmaNoTrans is supported.
*
* @param[in] M
* The number of rows of the matrix A. M >= 0.
*
* @param[in] N
* The number of columns of the matrix A. N >= 0.
*
* @param[in] NRHS
* The number of right hand sides, i.e., the number of columns of the matrices B and X.
* NRHS >= 0.
*
* @param[in] A
* The M-by-N matrix A. This matrix is not modified.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[in] B
* The M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified.
*
* @param[in] LDB
* The leading dimension of the array B. LDB >= MAX(1,M,N).
*
* @param[out] X
* If return value = 0, the solution vectors, stored columnwise.
* if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual
* sum of squares for the solution in each column is given by the sum of squares of the
* modulus of elements N+1 to M in that column;
* if M < N, rows 1 to N of X contain the minimum norm solution vectors;
*
* @param[in] LDX
* The leading dimension of the array X. LDX >= MAX(1,M,N).
*
* @param[out] ITER
* The number of the current iteration in the iterative refinement process
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
*******************************************************************************
*
* @sa PLASMA_zcgels_Tile
* @sa PLASMA_zcgels_Tile_Async
* @sa PLASMA_dsgels
* @sa PLASMA_zgels
*
******************************************************************************/
int PLASMA_zcgels(PLASMA_enum trans, int M, int N, int NRHS,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *B, int LDB,
PLASMA_Complex64_t *X, int LDX, int *ITER)
{
int i, j;
int NB, NBNB, MT, NT, NTRHS;
int status;
PLASMA_desc descA;
PLASMA_desc descB;
PLASMA_desc *descT;
PLASMA_desc descX;
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zcgels", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
*ITER = 0;
/* Check input arguments */
if (trans != PlasmaNoTrans &&
trans != PlasmaConjTrans &&
trans != PlasmaTrans )
{
plasma_error("PLASMA_zcgels", "illegal value of trans");
return -1;
}
if (trans != PlasmaNoTrans) {
plasma_error("PLASMA_zcgels", "only PlasmaNoTrans supported");
return PLASMA_ERR_NOT_SUPPORTED;
}
if (M < 0) {
plasma_error("PLASMA_zcgels", "illegal value of M");
return -2;
}
if (N < 0) {
plasma_error("PLASMA_zcgels", "illegal value of N");
return -3;
}
if (NRHS < 0) {
plasma_error("PLASMA_zcgels", "illegal value of NRHS");
return -4;
}
if (LDA < max(1, M)) {
plasma_error("PLASMA_zcgels", "illegal value of LDA");
return -6;
}
if (LDB < max(1, max(M, N))) {
plasma_error("PLASMA_zcgels", "illegal value of LDB");
return -9;
}
if (LDX < max(1, max(M, N))) {
plasma_error("PLASMA_zcgels", "illegal value of LDX");
return -10;
}
/* Quick return */
if (min(M, min(N, NRHS)) == 0) {
for (i = 0; i < max(M, N); i++)
for (j = 0; j < NRHS; j++)
B[j*LDB+i] = 0.0;
return PLASMA_SUCCESS;
}
/* Tune NB & IB depending on M, N & NRHS; Set NBNB */
status = plasma_tune(PLASMA_FUNC_ZCGELS, M, N, NRHS);
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcgels", "plasma_tune() failed");
return status;
}
/* Set MT, NT & NTRHS */
NB = PLASMA_NB;
NBNB = NB*NB;
NT = (N%NB==0) ? (N/NB) : (N/NB+1);
MT = (M%NB==0) ? (M/NB) : (M/NB+1);
NTRHS = (NRHS%NB==0) ? (NRHS/NB) : (NRHS/NB+1);
printf("M %d, N %d, NRHS %d, NB %d, MT %d, NT %d, NTRHS %d\n", M, N, NRHS, NB, MT, NT, NTRHS);
plasma_sequence_create(plasma, &sequence);
descA = plasma_desc_init(
PlasmaComplexDouble,
NB, NB, NBNB,
M, N, 0, 0, M, N);
if (M >= N) {
descB = plasma_desc_init(
PlasmaComplexDouble,
NB, NB, NBNB,
M, NRHS, 0, 0, M, NRHS);
descX = plasma_desc_init(
PlasmaComplexDouble,
NB, NB, NBNB,
M, NRHS, 0, 0, M, NRHS);
}
else {
descB = plasma_desc_init(
PlasmaComplexDouble,
NB, NB, NBNB,
N, NRHS, 0, 0, N, NRHS);
descX = plasma_desc_init(
PlasmaComplexDouble,
NB, NB, NBNB,
N, NRHS, 0, 0, N, NRHS);
}
/* DOUBLE PRECISION INITIALIZATION */
/* Allocate memory for matrices in block layout */
if (plasma_desc_mat_alloc(&descA) || plasma_desc_mat_alloc(&descB) || plasma_desc_mat_alloc(&descX)) {
plasma_error("PLASMA_zcgels", "plasma_shared_alloc() failed");
plasma_desc_mat_free(&descA);
plasma_desc_mat_free(&descB);
plasma_desc_mat_free(&descX);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
plasma_parallel_call_5(plasma_pzlapack_to_tile,
PLASMA_Complex64_t*, A,
int, LDA,
PLASMA_desc, descA,
PLASMA_sequence*, sequence,
PLASMA_request*, &request);
plasma_parallel_call_5(plasma_pzlapack_to_tile,
PLASMA_Complex64_t*, B,
int, LDB,
PLASMA_desc, descB,
PLASMA_sequence*, sequence,
PLASMA_request*, &request);
/* Allocate workspace */
PLASMA_Alloc_Workspace_zgels_Tile(M, N, &descT);
/* Call the native interface */
status = PLASMA_zcgels_Tile_Async(PlasmaNoTrans, &descA, descT, &descB, &descX, ITER,
sequence, &request);
if (status == PLASMA_SUCCESS) {
plasma_parallel_call_5(plasma_pztile_to_lapack,
PLASMA_desc, descX,
PLASMA_Complex64_t*, X,
int, LDX,
PLASMA_sequence*, sequence,
PLASMA_request*, &request);
}
plasma_dynamic_sync();
PLASMA_Dealloc_Handle_Tile(&descT);
plasma_sequence_destroy(plasma, sequence);
plasma_desc_mat_free(&descA);
plasma_desc_mat_free(&descB);
plasma_desc_mat_free(&descX);
return status;
}
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t_Tile
*
* PLASMA_zcgels_Tile - Solves overdetermined or underdetermined linear system of equations
* using the tile QR or the tile LQ factorization and mixed-precision iterative refinement.
* Tile equivalent of PLASMA_zcgesv().
* Operates on matrices stored by tiles.
* All matrices are passed through descriptors.
* All dimensions are taken from the descriptors.
*
*******************************************************************************
*
* @param[in] trans
* Intended usage:
* = PlasmaNoTrans: the linear system involves A;
* = PlasmaConjTrans: the linear system involves A**H.
* Currently only PlasmaNoTrans is supported.
*
* @param[in,out] A
* - If the iterative refinement converged, A is not modified;
* - otherwise, it fell back to double precision solution, and
* on exit the M-by-N matrix A contains:
* if M >= N, A is overwritten by details of its QR factorization as returned by
* PLASMA_zgeqrf;
* if M < N, A is overwritten by details of its LQ factorization as returned by
* PLASMA_zgelqf.
*
* @param[out] T
* On exit:
* - if the iterative refinement converged, T is not modified;
* - otherwise, it fell back to double precision solution,
* and then T is an auxiliary factorization data.
*
* @param[in,out] B
* On entry, the M-by-NRHS matrix B of right hand side vectors, stored columnwise;
* On exit, if return value = 0, B is overwritten by the solution vectors, stored
* columnwise:
* if M >= N, rows 1 to N of B contain the least squares solution vectors; the residual
* sum of squares for the solution in each column is given by the sum of squares of the
* modulus of elements N+1 to M in that column;
* if M < N, rows 1 to N of B contain the minimum norm solution vectors;
*
* @param[in] B
* The descriptor of the M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified.
*
* @param[in,out] X
* On entry, it's only the descriptor where to store the result.
* On exit, if return value = 0, X is the solution vectors, stored columnwise:
* if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual
* sum of squares for the solution in each column is given by the sum of squares of the
* modulus of elements N+1 to M in that column;
* if M < N, rows 1 to N of X contain the minimum norm solution vectors;
*
* @param[out] ITER
* If > 0, ITER is the number of the current iteration in the iterative refinement process.
* -ITERMAX-1, if the refinment step failed and the double precision factorization has been used.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
*
*******************************************************************************
*
* @sa PLASMA_zcgels
* @sa PLASMA_zcgels_Tile_Async
* @sa PLASMA_dsgels_Tile
* @sa PLASMA_zgels_Tile
*
******************************************************************************/
int PLASMA_zcgels_Tile(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,
PLASMA_desc *B, PLASMA_desc *X, int *ITER)
{
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
int status;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zcgels_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
plasma_sequence_create(plasma, &sequence);
status = PLASMA_zcgels_Tile_Async(trans, A, T, B, X, ITER, sequence, &request);
if (status != PLASMA_SUCCESS)
return status;
plasma_dynamic_sync();
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t_Tile_Async
*
* PLASMA_zcgels_Tile_Async - Solves overdetermined or underdetermined linear
* system of equations using the tile QR or the tile LQ factorization and
* mixed-precision iterative refinement.
* Non-blocking equivalent of PLASMA_zcgels_Tile().
* May return before the computation is finished.
* Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
*******************************************************************************
*
* @sa PLASMA_zcgels
* @sa PLASMA_zcgels_Tile
* @sa PLASMA_dsgels_Tile_Async
* @sa PLASMA_zgels_Tile_Async
*
******************************************************************************/
int PLASMA_zcgels_Tile_Async(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,
PLASMA_desc *B, PLASMA_desc *X, int *ITER,
PLASMA_sequence *sequence, PLASMA_request *request)
{
int M, N, NRHS, NB, NBNB, MT, NT, NTRHS;
PLASMA_desc descA;
PLASMA_desc descT;
PLASMA_desc descB;
PLASMA_desc descX;
plasma_context_t *plasma;
double *work;
const int itermax = 30;
const double bwdmax = 1.0;
const PLASMA_Complex64_t negone = -1.0;
const PLASMA_Complex64_t one = 1.0;
int iiter;
double Anorm, cte, eps, Rnorm, Xnorm;
*ITER=0;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zcgels_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
if (sequence == NULL) {
plasma_fatal_error("PLASMA_zcgels_Tile", "NULL sequence");
return PLASMA_ERR_UNALLOCATED;
}
if (request == NULL) {
plasma_fatal_error("PLASMA_zcgels_Tile", "NULL request");
return PLASMA_ERR_UNALLOCATED;
}
/* Check sequence status */
if (sequence->status == PLASMA_SUCCESS)
request->status = PLASMA_SUCCESS;
else
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Check descriptors for correctness */
if (plasma_desc_check(A) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcgels_Tile", "invalid first descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descA = *A;
}
if (plasma_desc_check(T) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcgels_Tile", "invalid second descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descT = *T;
}
if (plasma_desc_check(B) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcgels_Tile", "invalid third descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descB = *B;
}
if (plasma_desc_check(X) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcgels_Tile", "invalid fourth descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descX = *X;
}
/* Check input arguments */
if (descA.nb != descA.mb || descB.nb != descB.mb || descX.nb != descX.mb) {
plasma_error("PLASMA_zcgels_Tile", "only square tiles supported");
return PLASMA_ERR_ILLEGAL_VALUE;
}
if (trans != PlasmaNoTrans) {
plasma_error("PLASMA_zcgels_Tile", "only PlasmaNoTrans supported");
return PLASMA_ERR_NOT_SUPPORTED;
}
/* Quick return - currently NOT equivalent to LAPACK's:
if (min(M, min(N, NRHS)) == 0) {
for (i = 0; i < max(M, N); i++)
for (j = 0; j < NRHS; j++)
B[j*LDB+i] = 0.0;
return PLASMA_SUCCESS;
}
*/
if (0 == 0) {
// START SPECIFIC
/* Set M, M, NRHS, NB, MT, NT & NTRHS */
M = descA.lm;
N = descA.ln;
NRHS = descB.ln;
NB = descA.nb;
NBNB = NB*NB;
MT = (M%NB==0) ? (M/NB) : (M/NB+1);
NT = (N%NB==0) ? (N/NB) : (N/NB+1);
NTRHS = (NRHS%NB==0) ? (NRHS/NB) : (NRHS/NB+1);
printf("M %d, N %d, NRHS %d, NB %d, MT %d, NT %d, NTRHS %d\n", M, N, NRHS, NB, MT, NT, NTRHS);
work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble);
if (work == NULL) {
plasma_error("PLASMA_zcgesv", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, work);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
PLASMA_desc descR = plasma_desc_init(
PlasmaComplexDouble,
NB, NB, NBNB,
M, NRHS, 0, 0, M, NRHS);
if (plasma_desc_mat_alloc(&descR)) {
plasma_error("PLASMA_zcgesv", "plasma_shared_alloc() failed");
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
PLASMA_desc descSA = plasma_desc_init(
PlasmaComplexFloat,
NB, NB, NBNB,
M, N, 0, 0, M, N);
PLASMA_desc descST = plasma_desc_init(
PlasmaComplexFloat,
IB, NB, IBNB,
M, N, 0, 0, M, N);
PLASMA_desc descSX = plasma_desc_init(
PlasmaComplexFloat,
NB, NB, NBNB,
M, NRHS, 0, 0, M, NRHS);
/* Allocate memory for single precision matrices in block layout */
if (plasma_desc_mat_alloc(&descSA) || plasma_desc_mat_alloc(&descST) || plasma_desc_mat_alloc(&descSX)) {
plasma_error("PLASMA_zcgesv", "plasma_shared_alloc() failed");
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descST);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
/* Compute some constants */
PLASMA_zlange(PlasmaInfNorm, descA, Anorm, work);
eps = LAPACKE_dlamch_work('e');
printf("Anorm=%e, cte=%e\n", Anorm, cte);
/* Convert B from double precision to single precision and store
the result in SX. */
PLASMA_zlag2c(descB, descSX);
if (sequence->status != PLASMA_SUCCESS)
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Convert A from double precision to single precision and store
the result in SA. */
PLASMA_zlag2c(descA, descSA);
if (sequence->status != PLASMA_SUCCESS)
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
if (descSA.m >= descSA.n) {
/* Compute the QR factorization of SA */
printf("Facto\n"); fflush(stdout);
plasma_parallel_call_4(plasma_pcgeqrf,
PLASMA_desc, descSA,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
printf("Solve\n"); fflush(stdout);
plasma_parallel_call_5(plasma_pcunmqr,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.n, descSA.n),
PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.n, descSX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
else {
plasma_parallel_call_3(plasma_pztile_zero,
PLASMA_desc, plasma_desc_submatrix(descSX, descSA.m, 0, descSA.n-descSA.m, descSX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_4(plasma_pcgelqf,
PLASMA_desc, descSA,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaLower,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.m, descSA.m),
PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.m, descSX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_5(plasma_pcunmlq,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
/* Convert SX back to double precision */
PLASMA_clag2z(descSX, descX);
/* Compute R = B - AX. */
printf("R = B - Ax\n"); fflush(stdout);
printf("R = B - Ax ... cpy\n"); fflush(stdout);
PLASMA_zlacpy(descB,descR);
printf("R = B - Ax ... gemm\n"); fflush(stdout);
plasma_parallel_call_9(plasma_pzgemm,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNoTrans,
PLASMA_Complex64_t, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_Complex64_t, one,
PLASMA_desc, descR,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Check whether the NRHS normwise backward error satisfies the
stopping criterion. If yes return. Note that ITER=0 (already set). */
printf("Norm of X and R\n"); fflush(stdout);
PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);
/* Wait the end of Anorm, Xnorm and Bnorm computations */
plasma_dynamic_sync();
cte = Anorm*eps*((double) N)*bwdmax;
if (Rnorm < Xnorm * cte){
/* The NRHS normwise backward errors satisfy the
stopping criterion. We are good to exit. */
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descST);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_SUCCESS;
}
printf("Rnorm=%e, Xnorm * cte=%e, Rnorm=%e, cte=%e\n", Rnorm, Xnorm * cte, Rnorm, cte);
/* Iterative refinement */
for (iiter = 0; iiter < itermax; iiter++){
/* Convert R from double precision to single precision
and store the result in SX. */
PLASMA_zlag2c(descR, descSX);
/* Solve the system SA*SX = SR */
if (descSA.m >= descSA.n) {
plasma_parallel_call_5(plasma_pcunmqr,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.n, descSA.n),
PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.n, descSX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
} else {
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaLower,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.m, descSA.m),
PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.m, descSX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_5(plasma_pcunmlq,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
/* Convert SX back to double precision and update the current
iterate. */
PLASMA_clag2z(descSX, descR);
PLASMA_zgeadd(one, descR, descX);
/* Compute R = B - AX. */
PLASMA_zlacpy(descB,descR);
plasma_parallel_call_9(plasma_pzgemm,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNoTrans,
PLASMA_Complex64_t, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_Complex64_t, one,
PLASMA_desc, descR,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Check whether the NRHS normwise backward errors satisfy the
stopping criterion. If yes, set ITER=IITER>0 and return. */
PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);
/* Wait the end of Xnorm and Bnorm computations */
plasma_dynamic_sync();
printf("Rnorm=%e, Xnorm * cte=%e, Rnorm=%e, cte=%e\n", Rnorm, Xnorm * cte, Rnorm, cte);
if (Rnorm < Xnorm * cte){
/* The NRHS normwise backward errors satisfy the
stopping criterion. We are good to exit. */
*ITER = iiter;
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descST);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_SUCCESS;
}
}
/* We have performed ITER=itermax iterations and never satisified
the stopping criterion, set up the ITER flag accordingly and
follow up on double precision routine. */
*ITER = -itermax - 1;
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descST);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
printf("Go back DOUBLE\n");
// END SPECIFIC
}
/* Single-precision iterative refinement failed to converge to a
satisfactory solution, so we resort to double precision. */
PLASMA_zlacpy(descB, descX);
if (descA.m >= descA.n) {
plasma_parallel_call_4(plasma_pzgeqrf,
PLASMA_desc, descA,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_5(plasma_pzunmqr,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pztrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex64_t, 1.0,
PLASMA_desc, plasma_desc_submatrix(descA, 0, 0, descA.n, descA.n),
PLASMA_desc, plasma_desc_submatrix(descX, 0, 0, descA.n, descX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
else {
plasma_parallel_call_3(plasma_pztile_zero,
PLASMA_desc, plasma_desc_submatrix(descX, descA.m, 0, descA.n-descA.m, descX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_4(plasma_pzgelqf,
PLASMA_desc, descA,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pztrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaLower,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex64_t, 1.0,
PLASMA_desc, plasma_desc_submatrix(descA, 0, 0, descA.m, descA.m),
PLASMA_desc, plasma_desc_submatrix(descX, 0, 0, descA.m, descX.n),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_5(plasma_pzunmlq,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5838284441,
"avg_line_length": 36.7227272727,
"ext": "c",
"hexsha": "c25ec07f0117765e7eb4fd97f9b2c4f9702ca968",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "compute/zcgels.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "compute/zcgels.c",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "compute/zcgels.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8584,
"size": 32316
} |
/*! \file Function.h
* \brief header file that defines several function structures
*/
// Function.h
#ifndef NBODYFUNCTION_H
#define NBODYFUNCTION_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
namespace Math
{
/// \struct Math::gsl_math_function
/// \brief gsl function wrapper
struct gsl_math_function
{
int (* function) (const gsl_vector *params, void * data, gsl_vector *output);
};
/// \struct Math::gsl_math_function
/// \brief gsl function wrapper differentiating wrt params, storing info in Jacobian matrix
struct gsl_math_function_df
{
int (* function) (const gsl_vector * params, void * data, gsl_matrix * outputJacobian);
};
/// \struct Math::gsl_fitting_data
struct gsl_fitting_data {
size_t n;
double * x;
double * y;
size_t npar;
int * iparindex;
size_t nallparams;
double *allparams;
};
/// \struct Math::math_function
/// \brief single dependent variable function
struct math_function
{
Double_t (* function) (Double_t x, void * params);
int (* gsl_function) (const gsl_vector *params, void * data, gsl_vector *output);
int (* gsl_function_df) (const gsl_vector *params, void * data, gsl_matrix * outputJacobian);
void * params;
};
/// \struct Math::math_multidim_function
/// \brief multi-dimensional function
struct math_multidim_function
{
Double_t (* function) (Double_t *x, int ndim, void * params);
int ndim;
void * params;
};
}
#endif
| {
"alphanum_fraction": 0.722182849,
"avg_line_length": 23.5166666667,
"ext": "h",
"hexsha": "7cd017261649bd458f9ebf1cb7e6172138bbae8d",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z",
"max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ICRAR/NBodylib",
"max_forks_repo_path": "src/Math/Function.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ICRAR/NBodylib",
"max_issues_repo_path": "src/Math/Function.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ICRAR/NBodylib",
"max_stars_repo_path": "src/Math/Function.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 370,
"size": 1411
} |
#include <petsc.h>
typedef struct _msc_t {
PetscInt nmasks;
PetscInt* masks;
PetscInt* mask_offsets;
PetscInt* signs;
PetscScalar* coeffs;
} msc_t;
typedef struct _shell_context {
PetscInt nmasks;
PetscInt* masks;
PetscInt* mask_offsets;
PetscInt* signs;
PetscReal* real_coeffs; // we store only the real or complex part -- whichever is nonzero
void *left_subspace_data;
void *right_subspace_data;
PetscReal nrm;
} shell_context;
| {
"alphanum_fraction": 0.7343412527,
"avg_line_length": 21.0454545455,
"ext": "h",
"hexsha": "a4feaaad39ff55faabcb34015ee75cffa0756a79",
"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/shell_context.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/shell_context.h",
"max_line_length": 95,
"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/shell_context.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": 129,
"size": 463
} |
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#if defined(PARSEC_HAVE_SCHED_SETAFFINITY) && defined (__USE_GNU) || 1
#include <linux/unistd.h>
#define gettid() syscall(__NR_gettid)
#else
#warning Not using sched_setaffinity
#endif /* PARSEC_HAVE_SCHED_SETAFFINITY */
#include <sched.h>
#include <cblas.h>
#define MAX_THREADS 128
static int NB = 120;
static volatile int running = 1;
#define TYPE float
#define GEMM_FUNC cblas_sgemm
/*
#define TYPE double
#define GEMM_FUNC cblas_dgemm
*/
static void run_gemm(const TYPE *A, const TYPE *B, TYPE *C)
{
GEMM_FUNC( (const enum CBLAS_ORDER)CblasColMajor,
(const enum CBLAS_TRANSPOSE)CblasNoTrans, (const enum CBLAS_TRANSPOSE)CblasNoTrans,
NB /* A.rows */,
NB /* A.cols */,
NB /* B.rows */,
1.0, (TYPE*)A, NB /* A.data_stride */,
(TYPE*)B, NB /* B.data_stride */,
1.0, (TYPE*)C, NB /* C.data_stride */);
}
static TYPE *init_matrix(void)
{
TYPE *res;
int i, j;
res = (TYPE*)calloc(NB*NB, sizeof(TYPE));
for(i = 0; i < NB; i++)
for(j = 0; j < NB; j++)
res[i*NB+j] = (TYPE)rand() / (TYPE)RAND_MAX;
return res;
}
static void *thread_loop(void *_proc)
{
TYPE *A, *B, *C;
unsigned long int proc = (unsigned long int)_proc;
int i;
unsigned long long int time;
struct timespec start, end;
A = init_matrix();
B = init_matrix();
C = init_matrix();
#if defined(PARSEC_HAVE_SCHED_SETAFFINITY) && defined (__USE_GNU)
{
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(proc, &cpuset);
if( -1 == sched_setaffinity(gettid(), sizeof(cpu_set_t), &cpuset) ) {
printf( "Unable to set the thread affinity (%s)\n", strerror(errno) );
}
}
#endif /* PARSEC_HAVE_SCHED_SETAFFINITY */
if( proc == 0 ) {
for(i = 0; i < 100; i++) {
/* Ensures that all threads run cblas_dgemm on another core */
/* while warming up */
run_gemm(A, B, C);
}
for(i = 0; i < 1000; i++) {
/* Take the time */
clock_gettime(CLOCK_REALTIME, &start);
run_gemm(A, B, C);
clock_gettime(CLOCK_REALTIME, &end);
time = end.tv_nsec - start.tv_nsec + ( (end.tv_sec - start.tv_sec) * 1000000000ULL );
printf("NB = %d TIME = %llu ns %f GFlops\n", NB, time,
(2*(NB/1e3)*(NB/1e3)*(NB/1e3)) / ((double)time / 1e9));
}
running = 0;
} else {
while( running ) {
run_gemm(A, B, C);
}
}
return NULL;
}
int main(int argc, char *argv[])
{
unsigned long int i, nbcores;
pthread_t threads[MAX_THREADS];
if( argc != 3 ) {
fprintf(stderr, "usage: %s <Matrix Size> <Nb Cores>\n", argv[0]);
return 1;
}
NB = atoi(argv[1]);
nbcores = atoi(argv[2]);
if( NB <= 1 || nbcores < 1 ) {
fprintf(stderr, "usage: %s <Matrix Size> <Nb Cores>\n", argv[0]);
return 1;
}
for(i = 0; i < nbcores; i++) {
pthread_create(&threads[i], NULL, thread_loop, (void*)(i+1));
}
thread_loop((void*)0);
for(i = 0; i < nbcores; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
| {
"alphanum_fraction": 0.5478158205,
"avg_line_length": 25.4736842105,
"ext": "c",
"hexsha": "c91efc50477bc8c614447ac14680ad09b8432f81",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "NLAFET/ABFT",
"max_forks_repo_path": "tools/gpu/testbandwidth/gemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "NLAFET/ABFT",
"max_issues_repo_path": "tools/gpu/testbandwidth/gemm.c",
"max_line_length": 98,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "NLAFET/ABFT",
"max_stars_repo_path": "tools/gpu/testbandwidth/gemm.c",
"max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z",
"num_tokens": 997,
"size": 3388
} |
// -*- c++ -*-
#if 1
#include <string>
#include <vector>
#include <utility> // for std::pair
#include <stdint.h>
#include <iostream>
class Foo
{
public:
static std::string GetName() { return "Foo"; }
Foo();
~Foo();
void setDouble(double d) { m_d = d;}
void setDouble(double d, float x) { m_d = d+x;}
//void setFoo(const std::string &s) {std::cout << s << std::endl;}
void setFoo(const std::string &s="f", double x=1) {std::cout << s << x << std::endl;}
void setInt(int i) { std::cout << i << std::endl;}
void setInt(long i, float x=2) {std::cout << i+x << std::endl;}
double getDouble() { return m_d; }
void setUint64(uint64_t v) { m_uint64 = v; }
uint64_t getUint64() { return m_uint64; }
std::vector<Foo> getCollection() { return std::vector<Foo>(1, *this); }
std::vector<std::vector<std::pair<int, int> > > getMatrix() { return std::vector<std::vector<std::pair<int,int> > >(); }
std::vector< int>::iterator getIterator() { return std::vector<int>().begin(); }
static void frobnicate() { std::cout << "frobnicate"; }
//void frobnicate() { std::cout << "frobnicate -- non static"; }
Foo operator+(const Foo& a) { return Foo(); }
Foo& operator+=(const Foo& a) {
this->m_d += a.m_d;
this->m_uint64 += a.m_uint64;
return *this;
}
Foo& operator=(const Foo& rhs) {
this->m_d = rhs.m_d;
this->m_uint64 = rhs.m_uint64;
return *this;
}
void save(std::ostream &out) { out << m_d << m_uint64; }
double getme(double d) { return d; }
int getme(int i) { return i; }
void getme() const { return ; }
void getme() { return ; }
private:
double m_d;
uint64_t m_uint64;
};
Foo::Foo()
{}
Foo::~Foo()
{}
class IFoo
{
public:
virtual
void virtual_meth() const {}
virtual
void pure_virtual_meth() const = 0;
};
//template class std::vector<Foo>;
namespace Math {
void do_hello() {
std::cout << "helllo" << std::endl;
}
double do_add(double i, double j=2) { return i+j; }
double do_add(int i, int j=2, int k=3, int l=4) { return i+j+k+l; }
double do_add() { return 42; }
const std::string& say_hello() { static std::string hi="hi"; return hi;}
double adder(double i, double j) { return i+j; }
}
namespace Math2 {
// std::string do_hello() {
// return "hi";
// }
std::string do_hello(const std::string& name = "you") {
return std::string("hello ") + name;
}
std::string do_hello(const char* name) {
return std::string("hello -- ") + std::string(name);
}
std::string do_hello_c(const char* name) {
return std::string("hello -- ") + std::string(name);
}
}
namespace NS {
class Bar {
public:
Bar() {}
void syHello() {
std::cout << "hello" << std::endl;
}
};
template<class F> F tmpl_fct() { return F(); }
template<> int tmpl_fct<int>() { return 42; }
template<int N> int tmpl_fct_n() { return N; }
template<> int tmpl_fct_n<42>() { return 42; }
template<> int tmpl_fct_n<-1>() { return -1; }
}
namespace TT {
typedef int foo_t;
typedef foo_t* bar_t;
typedef const bar_t baz_t;
//'int *' 'foo *' 'bar'
}
#endif
#define BIT(n) (1ULL << (n))
enum MyEnum {
kValue = BIT(2)
};
typedef int Ssiz_t; //String size (int)
struct LongStr_t
{
Ssiz_t fCap; // Max string length (including null)
Ssiz_t fSize; // String length (excluding null)
char *fData; // Long string data
};
enum Enum0 {
kMinCap = (sizeof(LongStr_t) - 1)/sizeof(char) <= 2 ?
2 : (sizeof(LongStr_t) - 1)/sizeof(char),
kMin1 = 1 >= 2 ? 1 : 2
};
typedef void (*Func_t)();
class TVersionCheck {
public:
TVersionCheck(int versionCode); // implemented in TSystem.cxx
};
//static TVersionCheck gVersionCheck(335360);
//#define ROOT_VERSION_CODE 335360
//static TVersionCheck gVersionCheck = ROOT_VERSION_CODE;
class EnumNs
{
public:
enum ESTLtype { kSTL = 300 /* TVirtualStreamerInfo::kSTL */,
kSTLbitset = 8
};
// TStreamerElement status bits
enum {
kHasRange = BIT(6),
kCache = BIT(9),
kRepeat = BIT(10),
kRead = BIT(11),
kWrite = BIT(12),
kDoNotDelete = BIT(13)
};
};
class Base
{
public:
virtual void initialize() = 0;
};
class Base2
{
public:
virtual void execute() = 0;
};
class Alg : public Base, virtual public Base2
{
public:
virtual void initialize() { std::cout << "::initialize();\n"; }
virtual void execute() { std::cout << "::execute();\n"; }
};
class WithPrivateBase: public Base, private Base2
{
public:
virtual void initialize() { std::cout << "::initialize();\n"; }
virtual void execute() { std::cout << "::execute();\n"; }
WithPrivateBase() {}
WithPrivateBase(int /*i*/) {}
Enum0 myenum;
operator double() { return myenum; }
enum Enum1 {
kMinCap = (sizeof(LongStr_t) - 1)/sizeof(char) <= 2 ?
2 : (sizeof(LongStr_t) - 1)/sizeof(char),
kMin1 = 1 >= 2 ? 1 : 2
};
private:
void some_private_method() { std::cout << "::private()\n"; }
};
// #include <cblas.h>
| {
"alphanum_fraction": 0.5893102771,
"avg_line_length": 22.1260869565,
"ext": "h",
"hexsha": "9b76fd61a39811d85ba17e06b0c9a59af2675040",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2019-08-21T22:54:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-22T05:52:27.000Z",
"max_forks_repo_head_hexsha": "538632c38965335a9043e4b8dc7ca56533f54a5b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "sbinet/go-cxxdict",
"max_forks_repo_path": "example/mylib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "538632c38965335a9043e4b8dc7ca56533f54a5b",
"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": "sbinet/go-cxxdict",
"max_issues_repo_path": "example/mylib.h",
"max_line_length": 122,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "538632c38965335a9043e4b8dc7ca56533f54a5b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "sbinet/go-cxxdict",
"max_stars_repo_path": "example/mylib.h",
"max_stars_repo_stars_event_max_datetime": "2019-08-22T10:09:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-07-25T12:07:15.000Z",
"num_tokens": 1576,
"size": 5089
} |
#ifndef __MATH_SO3_H__
#define __MATH_SO3_H__
#include <string.h>
#include <assert.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "fasttrig.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
% ROTX Compute a rotation matrix about the X-axis.
% R = ROTX(PHI) returns [3x3] rotation matrix R. Note: PHI
% is measured in radians. PHI measures orientation of coordinate
% frame 2 relative to coordinate frame 1. Multiplication by rotation
% matrix R rotates a vector in coordinate frame 1 into coordinate
% frame 2.
*/
static inline void
so3_rotx (double Rx[9], const double phi)
{
double s, c;
fsincos (phi, &s, &c);
const double data[] = { 1, 0, 0,
0, c, s,
0, -s, c };
memcpy (Rx, data, 9 * sizeof(double));
}
static inline void
so3_rotx_gsl (gsl_matrix *Rx, const double phi)
{
assert (Rx->size1==3 && Rx->size2==3 && Rx->tda==3);
so3_rotx (Rx->data, phi);
}
/*
% ROTY Compute a rotation matrix about the Y-axis.
% R = ROTY(THETA) returns [3x3] rotation matrix R. Note: THETA
% is measured in radians. THETA measures orientation of coordinate
% frame 2 relative to coordinate frame 1. Multiplication by rotation
% matrix R rotates a vector in coordinate frame 1 into coordinate
% frame 2.
*/
static inline void
so3_roty (double Ry[9], const double theta)
{
double s, c;
fsincos (theta, &s, &c);
const double data[] = { c, 0, -s,
0, 1, 0,
s, 0, c };
memcpy (Ry, data, 9 * sizeof(double));
}
static inline void
so3_roty_gsl (gsl_matrix *Ry, const double theta)
{
assert (Ry->size1==3 && Ry->size2==3 && Ry->tda==3);
so3_roty (Ry->data, theta);
}
/*
% ROTZ Compute a rotation matrix about the Z-axis.
% R = ROTZ(PSI) returns [3x3] rotation matrix R. Note: PSI
% is measured in radians. PSI measures orientation of coordinate
% frame 2 relative to coordinate frame 1. Multiplication by rotation
% matrix R rotates a vector in coordinate frame 1 into coordinate
% frame 2.
*/
static inline void
so3_rotz (double Rz[9], const double psi)
{
double s, c;
fsincos (psi, &s, &c);
const double data[] = { c, s, 0,
-s, c, 0,
0, 0, 1 };
memcpy (Rz, data, 9 * sizeof(double));
}
static inline void
so3_rotz_gsl (gsl_matrix *Rz, const double psi)
{
assert (Rz->size1==3 && Rz->size2==3 && Rz->tda==3);
so3_rotz (Rz->data, psi);
}
/*
% ROTXYZ Compute a rotation matrix about the XYZ-axes.
% R = ROTXYZ(RPH) returns [3x3] rotation matrix R where RPH
% is a 3-vector of Euler angles [roll,pitch,heading] measured in
% radians. RPH measures orientation of coordinate frame 2
% relative to coordinate frame 1. Multiplication by rotation
% matrix R rotates a vector in coordinate frame 2 into coordinate
% frame 1.
*/
static inline void
so3_rotxyz (double R[9], const double rph[3])
{
double sr, sp, sh, cr, cp, ch;
fsincos (rph[0], &sr, &cr);
fsincos (rph[1], &sp, &cp);
fsincos (rph[2], &sh, &ch);
const double data[] = { ch*cp, -sh*cr + ch*sp*sr, sh*sr + ch*sp*cr,
sh*cp, ch*cr + sh*sp*sr, -ch*sr + sh*sp*cr,
-sp, cp*sr, cp*cr };
memcpy (R, data, 9 * sizeof(double));
}
static inline void
so3_rotxyz_gsl (gsl_matrix *R, const gsl_vector *rph)
{
assert (R->size1==3 && R->size2==3 && rph->size==3);
// when rph is vector view, stride might not be 1
double rph_data[3] = {rph->data[0], rph->data[rph->stride], rph->data[2*rph->stride]};
if (R->tda==3) {
so3_rotxyz (R->data, rph_data);
}
else {
double rot[9];
so3_rotxyz (rot, rph_data);
for (int i=0; i < 3; ++i)
for (int j=0; j < 3; ++j)
gsl_matrix_set (R, i, j, rot[i*3 + j]);
}
}
static inline void
so3_rotxyz_cmath (double R[9], const double rph[3])
{
double sr, sp, sh, cr, cp, ch;
sr = sin(rph[0]); cr = cos(rph[0]);
sp = sin(rph[1]); cp = cos(rph[1]);
sh = sin(rph[2]); ch = cos(rph[2]);
const double data[] = { ch*cp, -sh*cr + ch*sp*sr, sh*sr + ch*sp*cr,
sh*cp, ch*cr + sh*sp*sr, -ch*sr + sh*sp*cr,
-sp, cp*sr, cp*cr };
memcpy (R, data, 9 * sizeof(double));
}
/*
%ROT2RPH Convert rotation matrix into Euler roll,pitch,heading.
% RPH = ROT2RPH(R) computes 3-vector of Euler angles
% [roll,pitch,heading] from [3x3] rotation matrix R. Angles are
% measured in radians.
%
*/
static inline void
so3_rot2rph (const double R[9], double rph[3])
{
#define R(i,j) (R[i*3+j])
// heading
rph[2] = fatan2 (R(1,0), R(0,0));
double sh, ch;
fsincos (rph[2], &sh, &ch);
// pitch
rph[1] = fatan2 (-R(2,0), R(0,0)*ch + R(1,0)*sh);
// roll
rph[0] = fatan2 (R(0,2)*sh - R(1,2)*ch, -R(0,1)*sh + R(1,1)*ch);
#undef R
}
static inline void
so3_rot2rph_gsl (const gsl_matrix *R, gsl_vector *rph)
{
assert (R->size1==3 && R->size2==3 && R->tda==3 && rph->size==3);
so3_rot2rph (R->data, rph->data);
}
/*
% DROTX Compute the derivative of a rotation matrix about the X-axis.
% dRx = DROTZ(PHI) returns [3x3] rotation matrix dRx. Note: PHI
% is measured in radians. PHI measures orientation of coordinate
% frame 2 relative to coordinate frame 1.
*/
static inline void
so3_drotx (double dRx[9], const double phi)
{
double s, c;
fsincos (phi, &s, &c);
const double data[9] = { 0, 0, 0,
0, -s, c,
0, -c, -s };
memcpy (dRx, data, 9 * sizeof(double));
}
static inline void
so3_drotx_gsl (gsl_matrix *dRx, const double phi)
{
assert (dRx->size1==3 && dRx->size2==3 && dRx->tda==3);
so3_drotx (dRx->data, phi);
}
/*
% DROTY Compute the derivative of a rotation matrix about the Y-axis.
% dRy = DROTY(THETA) returns [3x3] rotation matrix dRy. Note: THETA
% is measured in radians. THETA measures orientation of coordinate
% frame 2 relative to coordinate frame 1.
*/
static inline void
so3_droty (double dRy[9], const double theta)
{
double s, c;
fsincos (theta, &s, &c);
const double data[9] = { -s, 0, -c,
0, 0, 0,
c, 0, -s };
memcpy (dRy, data, 9 * sizeof(double));
}
static inline void
so3_droty_gsl (gsl_matrix *dRy, const double theta)
{
assert (dRy->size1==3 && dRy->size2==3 && dRy->tda==3);
so3_droty (dRy->data, theta);
}
/*
% DROTZ Compute the derivative of a rotation matrix about the Z-axis.
% dRz = DROTZ(PSI) returns [3x3] rotation matrix dRz. Note: PSI
% is measured in radians. PSI measures orientation of coordinate
% frame 2 relative to coordinate frame 1.
*/
static inline void
so3_drotz (double dRz[9], const double psi)
{
double s, c;
fsincos (psi, &s, &c);
const double data[9] = { -s, c, 0,
-c, -s, 0,
0, 0, 0 };
memcpy (dRz, data, 9 * sizeof(double));
}
static inline void
so3_drotz_gsl (gsl_matrix *dRz, const double psi)
{
assert (dRz->size1==3 && dRz->size2==3 && dRz->tda==3);
so3_drotz (dRz->data, psi);
}
/*
% QUAT2ROT quaternion to rotation matrix.
% R = QUAT2ROT(q) takes a 4-vector unit quaternion reprsented by q,
% (i.e. q = [q0;qx;qy;qz]) and returns the corresponding [3 x 3]
% orthonormal rotation matrix R.
*/
static inline void
so3_quat2rot (const double q[4], double R[9])
{
const double q0 = q[0], qx = q[1], qy = q[2], qz = q[3];
const double q0q0 = q0*q0;
const double qxqx = qx*qx;
const double qyqy = qy*qy;
const double qzqz = qz*qz;
const double q0qx = q0*qx;
const double q0qz = q0*qz;
const double q0qy = q0*qy;
const double qxqy = qx*qy;
const double qxqz = qx*qz;
const double qyqz = qy*qz;
const double data[9] =
{ q0q0 + qxqx - qyqy - qzqz, 2*(qxqy - q0qz), 2*(qxqz + q0qy),
2*(qxqy + q0qz), q0q0 - qxqx + qyqy - qzqz, 2*(qyqz - q0qx),
2*(qxqz - q0qy), 2*(qyqz + q0qx), q0q0 - qxqx - qyqy + qzqz };
memcpy (R, data, 9 * sizeof(double));
}
static inline void
so3_quat2rot_gsl (const gsl_vector *q, gsl_matrix *R)
{
assert (q->size==4 && R->size1==3 && R->size2==3 && R->tda==3);
so3_quat2rot (q->data, R->data);
}
/*
% ROT2QUAT rotation matrix to quaternion.
% q = ROT2QUAT(R) returns a 4-vector unit quaternion reprsented by q,
% (i.e. q = [q0;qx;qy;qz]) corresponding to the [3 x 3]
% orthonormal rotation matrix R.
*/
static inline void
so3_rot2quat (const double R[9], double q[4])
{
// read
const double r00 = R[0], r01 = R[1], r02 = R[2];
const double r10 = R[3], r11 = R[4], r12 = R[5];
const double r20 = R[6], r21 = R[7], r22 = R[8];
const double tr = r00 + r11 + r22;
double qw, qx, qy, qz;
if (tr > 0) {
const double S = sqrt (tr+1.0) * 2; // S=4*qw
qw = 0.25 * S;
qx = (r21 - r12) / S;
qy = (r02 - r20) / S;
qz = (r10 - r01) / S;
} else if ((r00 > r11) && (r00 > r22)) {
const double S = sqrt (1.0 + r00 - r11 - r22) * 2; // S=4*qx
qw = (r21 - r12) / S;
qx = 0.25 * S;
qy = (r01 + r10) / S;
qz = (r02 + r20) / S;
} else if (r11 > r22) {
const double S = sqrt (1.0 + r11 - r00 - r22) * 2; // S=4*qy
qw = (r02 - r20) / S;
qx = (r01 + r10) / S;
qy = 0.25 * S;
qz = (r12 + r21) / S;
} else {
const double S = sqrt (1.0 + r22 - r00 - r11) * 2; // S=4*qz
qw = (r10 - r01) / S;
qx = (r02 + r20) / S;
qy = (r12 + r21) / S;
qz = 0.25 * S;
}
// write
q[0] = qw; q[1] = qx; q[2] = qy; q[3] = qz;
}
static inline void
so3_rot2quat_gsl (const gsl_matrix *R, gsl_vector *q)
{
assert (q->size==4 && R->size1==3 && R->size2==3 && R->tda==3);
so3_rot2quat (R->data, q->data);
}
/*
% QUAT2RPH converts unit quaternion to Euler RPH.
% rph = QUAT2RPH(q) returns a [3 x 1] Euler xyz representation
% equivalent to the [4 x 1] unit quaternion (provided q is
% not near an Euler singularity).
*/
static inline void
so3_quat2rph (const double q[4], double rph[3])
{
double R[9];
so3_quat2rot (q, R);
so3_rot2rph (R, rph);
}
static inline void
so3_quat2rph_gsl (const gsl_vector *q, gsl_vector *rph)
{
assert (q->size==4 && rph->size==4);
so3_quat2rph (q->data, rph->data);
}
/*
% RPH2QUAT converts Euler RPH to unit quaternion.
% q = RPH2QUAT(R) converts [3 x 1] Euler xyz representation
% to an equivalent [4 x 1] unit quaternion (provided R is
% not near an Euler singularity).
*/
static inline void
so3_rph2quat (const double rph[3], double q[4])
{
double R[9];
so3_rotxyz (R, rph);
so3_rot2quat (R, q);
}
static inline void
so3_rph2quat_gsl (const gsl_vector *rph, gsl_vector *q)
{
assert (q->size==4 && rph->size==4);
so3_rph2quat (rph->data, q->data);
}
/*
% function [rph_dot,J] = body2euler(pqr,rph)
% BODY2EULER converts body frame angular rates to Euler rates.
% RPH_DOT = BODY2EULER(PQR,RPH) converts body frame angular rates PQR to
% Euler angular rates RPH_DOT given Euler angles RPH.
%
% [RPH_DOT,J] = BODY2EULER(PQR,RPH) also returns the [3 x 6] Jacobian J
% associated with the transformation where J = [J_pqr, J_rph].
% see body2euler.m for cleaner notation
*/
static inline void
so3_body2euler (const double pqr[3], const double rph[3],
double rph_dot[3], double J[18]) {
double p = pqr[0];
double q = pqr[1];
double r = pqr[2];
double sr, cr;
fsincos (rph[0], &sr, &cr);
double sp, cp;
fsincos (rph[1], &sp, &cp);
double tp = ftan (rph[1]);
double kp = 1.0/cp;
//Euler angular rates
rph_dot[0] = p+sr*tp*q+cr*tp*r;
rph_dot[1] = cr*q-sr*r;
rph_dot[2] = sr*kp*q+cr*kp*r;
if (J != NULL) {
// Jacobian wrt
// first row
J[0] = 1; J[1] = sr*tp; J[2] = cr*tp;
J[3] = cr*tp*q-sr*tp*r; J[4] = sr*kp*kp*q+cr*kp*kp*r; J[5] = 0;
// second row
J[6] = 0; J[7] = cr; J[8] = -sr;
J[9] = -sr*q-cr*r; J[10] = 0; J[11] = 0;
// third row
J[12] = 0; J[13] = sr*kp; J[14] = cr*kp;
J[15] = cr*kp*q-sr*kp*r; J[16] = sr*kp*tp*q+cr*kp*tp*r; J[17] = 0;
}
}
/*
% function [pqr,J] = euler2body(rph_dot,rph)
% converts euler rates to body frame angular rates
%
% if not null also returns the [3 x 6] Jacobian J
% associated with the transformation where J = [rph_dot, J_rph].
% see body2euler.m for cleaner notation
*/
static inline void
so3_euler2body (const double rph_dot[3], const double rph[3],
double pqr[3], double J[18]) {
double rd = rph_dot[0];
double pd = rph_dot[1];
double hd = rph_dot[2];
double sr, cr;
fsincos (rph[0], &sr, &cr);
double sp, cp;
fsincos (rph[1], &sp, &cp);
//body rates
pqr[0] = -sp*hd + rd;
pqr[1] = sr*cp*hd + cr*pd;
pqr[2] = cr*cp*hd - sr*pd;
if (J != NULL) {
// Jacobian wrt
// first row
J[0] = 1; J[1] = 0; J[2] = -sp;
J[3] = 0; J[4] = -cp*hd; J[5] = 0;
// second row
J[6] = 0; J[7] = cr; J[8] = sr*cp;
J[9] = cr*cp*hd-sr*pd; J[10] = sr*-sp*hd; J[11] = 0;
// third row
J[12] = 0; J[13] = sr; J[14] = cr*cp;
J[15] = -sr*cp*hd-cr*pd; J[16] = cr*+sp*hd; J[17] = 0;
}
}
static inline void
so3_body2euler_gsl (const gsl_vector *pqr, const gsl_vector *rph,
gsl_vector *rph_dot, gsl_matrix *J) {
assert (pqr->size==3 && rph->size==3 && rph_dot->size==3
&& J->size1==3 && J->size2==6 && J->tda==6);
so3_body2euler (pqr->data, rph->data, rph_dot->data, J->data);
}
#ifdef __cplusplus
}
#endif
#endif // __MATH_SO3_H__
| {
"alphanum_fraction": 0.5525781851,
"avg_line_length": 29.2889344262,
"ext": "h",
"hexsha": "1a4b7ce787742c8d7ed2ffcb935d64b65e61cfb3",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-31T01:33:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-29T04:21:35.000Z",
"max_forks_repo_head_hexsha": "e8ce317fa3e0c089e30894fbb472669831eb0828",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tsnowak/rob550-botlab",
"max_forks_repo_path": "src/vx/math/so3.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e8ce317fa3e0c089e30894fbb472669831eb0828",
"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": "tsnowak/rob550-botlab",
"max_issues_repo_path": "src/vx/math/so3.h",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f7039adc78fbf89442c1881f9d9d2c2b28bf4c76",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gaomeitao/balance-gyrodometry-robot",
"max_stars_repo_path": "botgui/vx/math/so3.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T19:09:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-27T19:09:46.000Z",
"num_tokens": 5165,
"size": 14293
} |
#pragma once
/*For Engine Only*/
//#include <glad\glad.h>
//#include <GLFW\glfw3.h>
//#include <gsl\gsl>
//#include <SOIL2.h>
//#include <imgui.h>
//#include <glm\glm.hpp>
//#include <spdlog\spdlog.h>
//
///*Logger System*/
//#include "BooErEngine\Utils\Log.h"
//
///*Event's System*/
//#include "BooErEngine\Events\Event.h"
//#include "BooErEngine\Events\AppEvent.h"
//
///* Layer System*/
//#include "BooErEngine\Layers\LayerSatck.h"
//
///* InputMgr */
//#include "BooErEngine\ImputMgr.h"
//#include "BooErEngine\Platforms\Windows\WindowsInputMgr.h"
| {
"alphanum_fraction": 0.6750448833,
"avg_line_length": 19.8928571429,
"ext": "h",
"hexsha": "01ff15aa2d012a7956cba2114372a9d0c97b153e",
"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": "b2f390cbd5f7ec498307383d540f1381a7e634a6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Concarster/booErEngine",
"max_forks_repo_path": "BooErEngine/src/IncEngine.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b2f390cbd5f7ec498307383d540f1381a7e634a6",
"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": "Concarster/booErEngine",
"max_issues_repo_path": "BooErEngine/src/IncEngine.h",
"max_line_length": 60,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b2f390cbd5f7ec498307383d540f1381a7e634a6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Concarster/booErEngine",
"max_stars_repo_path": "BooErEngine/src/IncEngine.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 176,
"size": 557
} |
#include "./economic-model.h"
#include <gsl/gsl_randist.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
person *makePerson(int birthYear, int deathYear, int iq,
personality *_personality)
{
person *p = malloc(sizeof(person));
p->birth_year = birthYear;
p->death_year = deathYear;
p->iq = iq;
p->personality = _personality;
return p;
}
int getAge(int year, person *p)
{
if (p == NULL)
{
return -1;
}
if (p->death_year > -1)
{
return (p->death_year - p->birth_year);
}
return year - p->birth_year;
}
int healthCheck(int year, person *p)
{
if (p->death_year != -1)
{
return p->death_year;
}
int age = getAge(year, p);
if (age >= 100)
{
p->death_year = year;
return year;
}
return -1;
}
void personTick(int year, person *p) { healthCheck(year, p); }
int countPeople(person **people)
{
int i = 0;
while (people[i] != NULL)
{
i++;
}
return i;
}
/**
* TODO: growth should be logarithmic - easy to grow early when
* complexity is low and harder thereafter.
*
* Growth may even be negative e.g. starting a high level of experience over
* the past years but this year the intensity drops. Yearly attrition.
*/
int getGrowthFromExperience(experience_option *option, person *p)
{
double r = getRandomGaussian(5, 2, NULL, NULL);
return round(r);
}
| {
"alphanum_fraction": 0.6353111433,
"avg_line_length": 18.4266666667,
"ext": "c",
"hexsha": "93a25cefb482ad2c45d0d4e66f02f965207b0d8d",
"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": "574b1d6ff87d6b0a51385fde22710e6a60ed0169",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kunal-mandalia/economic-model",
"max_forks_repo_path": "src/person.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "574b1d6ff87d6b0a51385fde22710e6a60ed0169",
"max_issues_repo_issues_event_max_datetime": "2019-09-16T23:39:47.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-16T23:39:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "kunal-mandalia/economic-model",
"max_issues_repo_path": "src/person.c",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "574b1d6ff87d6b0a51385fde22710e6a60ed0169",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kunal-mandalia/economic-model",
"max_stars_repo_path": "src/person.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 398,
"size": 1382
} |
/// @brief Compile-time configurable Policy-based ring buffer
///
/// `RingBuffer` has an API matching `std::vector` in its default configuration or can be configured
/// to provide a subset of that API, but provide lock-free concurrency
#pragma once
#include <Hyperion/BasicTypes.h>
#include <Hyperion/Concepts.h>
#include <Hyperion/HyperionDef.h>
#include <Hyperion/Memory.h>
#include <atomic>
#include <compare>
#include <gsl/gsl>
#include <iostream>
#include <iterator>
#include <limits>
#include <tuple>
namespace hyperion {
/// @brief The thread-safety type of the `RingBuffer`
enum class RingBufferType : usize {
NotThreadSafe = 0,
ThreadSafe = 1
};
IGNORE_PADDING_START
/// @brief A simple Ring Buffer implementation.
/// Supports resizing, writing, reading, erasing, and provides mutable and immutable
/// random access iterators.
///
/// # Iterator Invalidation
/// * Iterators are lazily evaluated, so will only ever be invalidated at their current state.
/// Performing any mutating operation (mutating the iterator, not the underlying data) on them
/// will re-sync them with their associated `RingBuffer`.
/// The following operations will invalidate an iterator's current state:
/// - Read-only operations: never
/// - clear: always
/// - reserve: only if the `RingBuffer` changed capacity
/// - erase: Erased elements and all following elements
/// - push_back, emplace_back: only `end()` until `capacity()` is reached,
/// then `begin()` and `end()`
/// - insert, emplace: only the element at the position inserted/emplaced
/// - pop_back: the element removed and `end()`
/// - pop_front: the element removed and `begin()`
///
/// @tparam T - The type to store in the `RingBuffer`. Must Be Default Constructible.
/// Does not currently support `T` of array types (eg, `T` = `U[]` or `T` = `U[N]`)
template<concepts::DefaultConstructible T,
RingBufferType ThreadSafety = RingBufferType::NotThreadSafe,
template<typename ElementType> typename Allocator = std::allocator>
class RingBuffer {
public:
/// Default capacity of `RingBuffer`
static const constexpr usize DEFAULT_CAPACITY = 16;
using allocator_traits = std::allocator_traits<Allocator<T>>;
using unique_pointer
= decltype(allocate_unique<T[]>(std::declval<Allocator<T[]>>(), // NOLINT
DEFAULT_CAPACITY));
/// @brief Random-Access Bidirectional iterator for `RingBuffer`
/// @note All navigation operators are checked such that any movement past `begin()` or
/// `end()` is ignored.
class Iterator {
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = value_type*;
using reference = value_type&;
constexpr explicit Iterator(pointer ptr,
RingBuffer* containerPtr,
usize currentIndex) noexcept
: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {
}
constexpr Iterator(const Iterator& iter) noexcept = default;
constexpr Iterator(Iterator&& iter) noexcept = default;
~Iterator() noexcept = default;
/// @brief Returns the index in the `RingBuffer` that corresponds
/// to the element this iterator points to
///
/// @return The index corresponding with the element this points to
[[nodiscard]] inline constexpr auto get_index() const noexcept -> usize {
return m_current_index;
}
constexpr auto operator=(const Iterator& iter) noexcept -> Iterator& = default;
constexpr auto operator=(Iterator&& iter) noexcept -> Iterator& = default;
inline constexpr auto operator==(const Iterator& rhs) const noexcept -> bool {
return m_ptr == rhs.m_ptr;
}
inline constexpr auto operator!=(const Iterator& rhs) const noexcept -> bool {
return m_ptr != rhs.m_ptr;
}
inline constexpr auto operator*() const noexcept -> reference {
return *m_ptr;
}
inline constexpr auto operator->() noexcept -> pointer {
return m_ptr;
}
inline constexpr auto operator++() noexcept -> Iterator& {
m_current_index++;
if(m_current_index >= m_container_ptr->capacity()) {
m_current_index = m_container_ptr->capacity();
m_ptr = m_container_ptr->end().m_ptr;
}
else {
m_ptr = &(*m_container_ptr)[m_current_index];
}
return *this;
}
inline constexpr auto operator++(int) noexcept -> Iterator {
Iterator temp = *this;
++(*this);
return temp;
}
inline constexpr auto operator--() noexcept -> Iterator& {
if(m_current_index == 0) {
return *this;
}
m_current_index--;
m_ptr = &(*m_container_ptr)[m_current_index];
return *this;
}
inline constexpr auto operator--(int) noexcept -> Iterator {
Iterator temp = *this;
--(*this);
return temp;
}
inline constexpr auto
operator+(concepts::Integral auto rhs) const noexcept -> Iterator {
const auto diff = static_cast<usize>(rhs);
if(rhs < 0) {
return std::move(*this - -rhs);
}
auto temp = *this;
temp.m_current_index += diff;
if(temp.m_current_index > temp.m_container_ptr->capacity()) {
temp.m_current_index = temp.m_container_ptr->capacity();
temp.m_ptr = temp.m_container_ptr->end().m_ptr;
}
else {
temp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto operator+=(concepts::Integral auto rhs) noexcept -> Iterator& {
*this = std::move(*this + rhs);
return *this;
}
inline constexpr auto
operator-(concepts::Integral auto rhs) const noexcept -> Iterator {
const auto diff = static_cast<usize>(rhs);
if(rhs < 0) {
return std::move(*this + -rhs);
}
auto temp = *this;
if(diff > temp.m_current_index) {
temp.m_ptr = temp.m_container_ptr->begin().m_ptr;
temp.m_current_index = 0;
}
else {
temp.m_current_index -= diff;
temp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto operator-=(concepts::Integral auto rhs) noexcept -> Iterator& {
*this = std::move(*this - rhs);
return *this;
}
inline constexpr auto operator-(const Iterator& rhs) const noexcept -> difference_type {
return static_cast<std::ptrdiff_t>(m_current_index)
- static_cast<std::ptrdiff_t>(rhs.m_current_index);
}
inline constexpr auto operator[](concepts::Integral auto index) noexcept -> Iterator {
return std::move(*this + index);
}
inline constexpr auto operator>(const Iterator& rhs) const noexcept -> bool {
return m_current_index > rhs.m_current_index;
}
inline constexpr auto operator<(const Iterator& rhs) const noexcept -> bool {
return m_current_index < rhs.m_current_index;
}
inline constexpr auto operator>=(const Iterator& rhs) const noexcept -> bool {
return m_current_index >= rhs.m_current_index;
}
inline constexpr auto operator<=(const Iterator& rhs) const noexcept -> bool {
return m_current_index <= rhs.m_current_index;
}
private:
pointer m_ptr;
RingBuffer* m_container_ptr = nullptr;
usize m_current_index = 0;
};
/// @brief Read-only Random-Access Bidirectional iterator for `RingBuffer`
/// @note All navigation operators are checked such that any movement past `begin()` or
/// `end()` is ignored.
class ConstIterator {
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = const value_type*;
using reference = const value_type&;
constexpr explicit ConstIterator(pointer ptr,
RingBuffer* containerPtr,
usize currentIndex) noexcept
: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {
}
constexpr ConstIterator(const ConstIterator& iter) noexcept = default;
constexpr ConstIterator(ConstIterator&& iter) noexcept = default;
~ConstIterator() noexcept = default;
/// @brief Returns the index in the `RingBuffer` that corresponds
/// to the element this iterator points to
///
/// @return The index corresponding with the element this points to
[[nodiscard]] inline constexpr auto get_index() const noexcept -> usize {
return m_current_index;
}
constexpr auto
operator=(const ConstIterator& iter) noexcept -> ConstIterator& = default;
constexpr auto operator=(ConstIterator&& iter) noexcept -> ConstIterator& = default;
inline constexpr auto operator==(const ConstIterator& rhs) const noexcept -> bool {
return m_ptr == rhs.m_ptr;
}
inline constexpr auto operator!=(const ConstIterator& rhs) const noexcept -> bool {
return m_ptr != rhs.m_ptr;
}
inline constexpr auto operator*() const noexcept -> reference {
return *m_ptr;
}
inline constexpr auto operator->() const noexcept -> pointer {
return m_ptr;
}
inline constexpr auto operator++() noexcept -> ConstIterator& {
m_current_index++;
if(m_current_index >= m_container_ptr->capacity()) {
m_current_index = m_container_ptr->capacity();
m_ptr = m_container_ptr->end().m_ptr;
}
else {
m_ptr = &(*m_container_ptr)[m_current_index];
}
return *this;
}
inline constexpr auto operator++(int) noexcept -> ConstIterator {
ConstIterator temp = *this;
++(*this);
return temp;
}
inline constexpr auto operator--() noexcept -> ConstIterator& {
if(m_current_index == 0) {
return *this;
}
m_current_index--;
m_ptr = &(*m_container_ptr)[m_current_index];
return *this;
}
inline constexpr auto operator--(int) noexcept -> ConstIterator {
ConstIterator temp = *this;
--(*this);
return temp;
}
inline constexpr auto
operator+(concepts::Integral auto rhs) const noexcept -> ConstIterator {
const auto diff = static_cast<usize>(rhs);
if(rhs < 0) {
return std::move(*this - -rhs);
}
auto temp = *this;
temp.m_current_index += diff;
if(temp.m_current_index > temp.m_container_ptr->capacity()) {
temp.m_current_index = temp.m_container_ptr->capacity();
temp.m_ptr = temp.m_container_ptr->end().m_ptr;
}
else {
temp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto
operator+=(concepts::Integral auto rhs) noexcept -> ConstIterator& {
*this = std::move(*this + rhs);
return *this;
}
inline constexpr auto
operator-(concepts::Integral auto rhs) const noexcept -> ConstIterator {
const auto diff = static_cast<usize>(rhs);
if(rhs < 0) {
return std::move(*this + -rhs);
}
auto temp = *this;
if(diff > temp.m_current_index) {
temp.m_ptr = temp.m_container_ptr->begin().m_ptr;
temp.m_current_index = 0;
}
else {
temp.m_current_index -= diff;
temp.m_ptr = &(*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto
operator-=(concepts::Integral auto rhs) noexcept -> ConstIterator& {
*this = std::move(*this - rhs);
return *this;
}
inline constexpr auto
operator-(const ConstIterator& rhs) const noexcept -> difference_type {
return static_cast<std::ptrdiff_t>(m_current_index)
- static_cast<std::ptrdiff_t>(rhs.m_current_index);
}
inline constexpr auto
operator[](concepts::Integral auto index) const noexcept -> ConstIterator {
return std::move(*this + index);
}
inline constexpr auto operator>(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index > rhs.m_current_index;
}
inline constexpr auto operator<(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index < rhs.m_current_index;
}
inline constexpr auto operator>=(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index >= rhs.m_current_index;
}
inline constexpr auto operator<=(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index <= rhs.m_current_index;
}
private:
pointer m_ptr;
RingBuffer* m_container_ptr = nullptr;
usize m_current_index = 0;
};
/// @brief Creates a `RingBuffer` with default capacity
constexpr RingBuffer() noexcept = default;
/// @brief Creates a `RingBuffer` with (at least) the given initial capacity
///
/// @param intitial_capacity - The initial capacity of the `RingBuffer`
constexpr explicit RingBuffer(usize intitial_capacity) noexcept
: m_buffer(allocate_unique<T[]>(m_allocator, intitial_capacity + 1)), // NOLINT
m_loop_index(intitial_capacity),
m_capacity(intitial_capacity + 1) {
}
/// @brief Constructs a new `RingBuffer` with the given initial capacity and
/// fills it with `default_value`
///
/// @param intitial_capacity - The initial capacity of the `RingBuffer`
/// @param default_value - The value to fill the `RingBuffer` with
constexpr RingBuffer(
usize intitial_capacity,
const T& default_value) noexcept requires concepts::CopyConstructible<T>
: m_buffer(allocate_unique<T[]>(m_allocator, // NOLINT
intitial_capacity + 1,
default_value)),
m_write_index(intitial_capacity),
m_start_index(0_usize), // NOLINT
m_loop_index(intitial_capacity),
m_capacity(intitial_capacity + 1) {
}
constexpr RingBuffer(
std::initializer_list<T> values) noexcept requires concepts::MoveAssignable<T>
: m_buffer(allocate_unique<T[]>(m_allocator, // NOLINT
values.size() + 1)),
m_loop_index(values.size()),
m_capacity(values.size() + 1) {
for(auto&& val : values) {
push_back(std::move(val));
}
}
constexpr RingBuffer(const RingBuffer& buffer) noexcept requires concepts::CopyAssignable<T>
: m_buffer(allocate_unique<T[]>(m_allocator, buffer.m_capacity)), // NOLINT
m_write_index(0_usize), // NOLINT
m_start_index(0_usize), // NOLINT
m_loop_index(buffer.m_loop_index),
m_capacity(buffer.m_capacity) {
const auto size = m_buffer.size();
for(auto i = 0_usize; i < size; ++i) {
push_back(buffer.m_buffer[i]);
}
// clang-format off
m_start_index = buffer.m_start_index; // NOLINT(cppcoreguidelines-prefer-member-initializer)
m_write_index = buffer.m_write_index; // NOLINT(cppcoreguidelines-prefer-member-initializer)
// clang-format on
}
constexpr RingBuffer(RingBuffer&& buffer) noexcept
: m_allocator(buffer.m_allocator),
m_buffer(std::move(buffer.m_buffer)),
m_write_index(buffer.m_write_index),
m_start_index(buffer.m_start_index),
m_loop_index(buffer.m_loop_index),
m_capacity(buffer.m_capacity) {
buffer.m_capacity = 0_usize;
buffer.m_loop_index = 0_usize;
buffer.m_write_index = 0_usize;
buffer.m_start_index = 0_usize;
buffer.m_buffer = nullptr;
}
~RingBuffer() noexcept = default;
/// @brief Returns the element at the given index.
/// @note This is not checked in the same manner as STL containers:
/// if index >= capacity, the element at capacity - 1 is returned.
///
/// @param index - The index of the desired element
///
/// @return The element at the given index, or at capacity - 1 if index >= capacity
[[nodiscard]] inline constexpr auto at(concepts::Integral auto index) noexcept -> T& {
auto i = get_adjusted_internal_index(index);
return m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Returns the first element in the `RingBuffer`
///
/// @return The first element
[[nodiscard]] inline constexpr auto front() noexcept -> T& {
return m_buffer
[m_start_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Returns the last element in the `RingBuffer`
/// @note If <= 1 elements are in the `RingBuffer`, this will be the same as `front`
///
/// @return The last element
[[nodiscard]] inline constexpr auto back() noexcept -> T& {
const auto index = (m_start_index + size() - 1) % (m_capacity);
return m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Returns a pointer to the underlying data in the `RingBuffer`.
/// @note This is not sorted in any way to match the representation used by the `RingBuffer`
///
/// @return A pointer to the underlying data
[[nodiscard]] inline constexpr auto data() noexcept -> T* {
return m_buffer;
}
/// @brief Returns whether the `RingBuffer` is empty
///
/// @return `true` if the `RingBuffer` is empty, `false` otherwise
[[nodiscard]] inline constexpr auto empty() const noexcept -> bool {
return m_write_index == m_start_index;
}
/// @brief Returns whether the `RingBuffer` is full
///
/// @return `true` if the `RingBuffer` is full, `false` otherwise
[[nodiscard]] inline constexpr auto full() const noexcept -> bool {
return size() == m_capacity - 1;
}
/// @brief Returns the current number of elements in the `RingBuffer`
///
/// @return The current number of elements
[[nodiscard]] inline constexpr auto size() const noexcept -> usize {
return m_write_index >= m_start_index ? (m_write_index - m_start_index) :
(m_capacity - (m_start_index - m_write_index));
}
/// @brief Returns the maximum possible number of elements this `RingBuffer` could store
/// if grown to maximum possible capacity
///
/// @return The maximum possible number of storable elements
[[nodiscard]] inline constexpr auto max_size() const noexcept -> usize {
return allocator_traits::max_size(m_allocator) - 1;
}
/// @brief Returns the current capacity of the `RingBuffer`;
/// the number of elements it can currently store
///
/// @return The current capacity
[[nodiscard]] inline constexpr auto capacity() const noexcept -> usize {
return m_capacity - 1;
}
/// @brief Reserves more storage for the `RingBuffer`. If `new_capacity` is > capacity,
/// then the capacity of the `RingBuffer` will be extended until at least `new_capacity`
/// elements can be stored.
/// @note Memory contiguity is maintained, so no **elements** will be lost or invalidated.
/// However, all iterators and references to elements will be invalidated.
///
/// @param new_capacity - The new capacity of the `RingBuffer`
inline constexpr auto reserve(usize new_capacity) noexcept -> void {
// we only need to do anything if `new_capacity` is actually larger than `m_capacity`
if(new_capacity > m_capacity) {
auto temp
= allocate_unique<T[], Allocator<T[]>>(m_allocator, new_capacity + 1); // NOLINT
auto span = gsl::make_span(&temp[0], new_capacity + 1);
std::copy(begin(), end(), span.begin());
m_buffer = std::move(temp);
m_start_index = 0;
m_write_index = m_loop_index + 1;
m_loop_index = new_capacity;
m_capacity = new_capacity + 1;
}
}
/// @brief Erases all elements from the `RingBuffer`
inline constexpr auto clear() noexcept -> void {
m_start_index = 0;
m_write_index = 0;
}
/// @brief Inserts the given element at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @param value - the element to insert
inline constexpr auto
push_back(const T& value) noexcept -> void requires concepts::CopyAssignable<T> {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
m_buffer[m_write_index] = value;
increment_indices();
}
/// @brief Inserts the given element at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @param value - the element to insert
inline constexpr auto
push_back(T&& value) noexcept -> void requires concepts::MoveAssignable<T> {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
m_buffer[m_write_index] = std::move(value);
increment_indices();
}
/// @brief Constructs the given element in place at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @tparam Args - The types of the element's constructor arguments
/// @param args - The constructor arguments for the element
///
/// @return A reference to the element constructed at the end of the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto emplace_back(Args&&... args) noexcept -> T& {
allocator_traits::template construct<T>(m_allocator,
&m_buffer[m_write_index], // NOLINT
std::forward<Args>(args)...);
auto index = m_write_index;
increment_indices();
return m_buffer[index]; // NOLINT
}
/// @brief Constructs the given element in place at the location
/// indicated by the `Iterator` `position`
///
/// @tparam Args - The types of the element's constructor arguments
/// @param position - `Iterator` indicating where in the `RingBuffer` to construct the
/// element
/// @param args - The constructor arguments for the element
///
/// @return A reference to the element constructed at the location indicated by `position`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto emplace(const Iterator& position, Args&&... args) noexcept -> T& {
auto index = get_adjusted_internal_index(position.get_index());
allocator_traits::template construct<T>(m_allocator,
&m_buffer[index], // NOLINT
std::forward<Args>(args)...);
return m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Constructs the given element in place at the location
/// indicated by the `ConstIterator` `position`
///
/// @tparam Args - The types of the element's constructor arguments
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to construct the
/// element
/// @param args - The constructor arguments for the element
///
/// @return A reference to the element constructed at the location indicated by `position`
template<typename... Args>
inline constexpr auto
emplace(const ConstIterator& position, Args&&... args) noexcept -> T& {
auto index = get_adjusted_internal_index(position.get_index());
allocator_traits::template construct<T>(m_allocator,
&m_buffer[index], // NOLINT
std::forward<Args>(args)...);
return m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Assigns the given element to the position indicated
/// by the `Iterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const Iterator& position, const T& element) noexcept
-> void requires concepts::CopyAssignable<T> {
insert_internal(position.get_index(), element);
}
/// @brief Assigns the given element to the position indicated
/// by the `Iterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const Iterator& position, T&& element) noexcept -> void {
insert_internal(position.get_index(), std::forward<T>(element));
}
/// @brief Assigns the given element to the position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const ConstIterator& position, const T& element) noexcept
-> void requires concepts::CopyAssignable<T> {
insert_internal(position.get_index(), element);
}
/// @brief Assigns the given element to the position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const ConstIterator& position, T&& element) noexcept -> void {
insert_internal(position.get_index(), std::forward<T>(element));
}
/// @brief Constructs the given element at the insertion position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param args - The arguments to the constructor for
/// the element to store in the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto
insert_emplace(const Iterator& position, Args&&... args) noexcept -> T& {
return insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);
}
/// @brief Constructs the given element at the insertion position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param args - The arguments to the constructor for
/// the element to store in the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto
insert_emplace(const ConstIterator& position, Args&&... args) noexcept -> T& {
return insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);
}
/// @brief Erases the element at the given `position`, moving other elements backward
/// in the buffer to maintain contiguity
///
/// @param position - The element to erase
///
/// @return `Iterator` pointing to the element after the one erased
inline constexpr auto erase(const Iterator& position) noexcept -> Iterator {
return erase_internal(position.get_index());
}
/// @brief Erases the element at the given `position`, moving other elements backward
/// in the buffer to maintain contiguity
///
/// @param position - The element to erase
///
/// @return `Iterator` pointing to the element after the one erased
inline constexpr auto erase(const ConstIterator& position) noexcept -> Iterator {
return erase_internal(position.get_index());
}
/// @brief Erases the range of elements in [`first`, `last`)
/// Returns an `Iterator` to the element after the last one erased
/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;
///
/// @param first - The first element in the range to erase
/// @param last - The last element in the range
///
/// @return `Iterator` pointing to the element after the last one erased
inline constexpr auto
erase(const Iterator& first, const Iterator& last) noexcept -> Iterator {
if(first >= last) {
return last;
}
return erase_internal(first.get_index(), last.get_index());
}
/// @brief Erases the range of elements in [`first`, `last`)
/// Returns an `Iterator` to the element after the last one erased
/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;
///
/// @param first - The first element in the range to erase
/// @param last - The last element in the range
///
/// @return `Iterator` pointing to the element after the last one erased
inline constexpr auto
erase(const ConstIterator& first, const ConstIterator& last) noexcept -> Iterator {
if(first >= last) {
return last;
}
return erase_internal(first.get_index(), last.get_index());
}
/// @brief Removes the last element in the `RingBuffer` and returns it
///
/// @return The last element in the `RingBuffer`
[[nodiscard]] inline constexpr auto
pop_back() noexcept -> T requires concepts::Copyable<T> {
T back_ = back();
decrement_write();
return back_;
}
/// @brief Removes the first element in the `RingBuffer` and returns it
///
/// @return The first element in the `RingBuffer`
[[nodiscard]] inline constexpr auto
pop_front() noexcept -> T requires concepts::Copyable<T> {
T front_ = front();
increment_start();
return front_;
}
/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,
/// at the beginning
///
/// @return The iterator, at the beginning
[[nodiscard]] inline constexpr auto begin() -> Iterator {
T* p = &m_buffer
[m_start_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
return Iterator(p, this, 0_usize);
}
/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,
/// at the end
///
/// @return The iterator, at the end
[[nodiscard]] inline constexpr auto end() -> Iterator {
T* p = &m_buffer
[m_write_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
return Iterator(p, this, size());
}
/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,
/// at the beginning
///
/// @return The iterator, at the beginning
[[nodiscard]] inline constexpr auto cbegin() -> ConstIterator {
T* p = &m_buffer
[m_start_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
return ConstIterator(p, this, 0_usize);
}
/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,
/// at the end
///
/// @return The iterator, at the end
[[nodiscard]] inline constexpr auto cend() -> ConstIterator {
T* p = &m_buffer
[m_write_index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
return ConstIterator(p, this, size());
}
/// @brief Unchecked access-by-index operator
///
/// @param index - The index to get the corresponding element for
///
/// @return - The element at index
[[nodiscard]] inline constexpr auto
operator[](concepts::Integral auto index) noexcept -> T& {
auto i = get_adjusted_internal_index(index);
return m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
constexpr auto operator=(const RingBuffer& buffer) noexcept
-> RingBuffer& requires concepts::CopyAssignable<T> {
if(this == &buffer) {
return *this;
}
auto temp = allocate_unique<T[]>(m_allocator, buffer.m_capacity); // NOLINT
const auto size = buffer.size();
for(auto i = 0_usize; i < size; ++i) {
temp[i] = buffer.m_buffer[i];
}
m_buffer = std::move(temp);
m_capacity = buffer.m_capacity;
m_start_index = buffer.m_start_index;
m_write_index = buffer.m_write_index;
m_loop_index = buffer.m_loop_index;
return *this;
}
constexpr auto operator=(RingBuffer&& buffer) noexcept -> RingBuffer& {
m_allocator = buffer.m_allocator;
m_buffer = std::move(buffer.m_buffer);
m_write_index = buffer.m_write_index;
m_start_index = buffer.m_start_index;
m_loop_index = buffer.m_loop_index;
m_capacity = buffer.m_capacity;
buffer.m_buffer = nullptr;
buffer.m_write_index = 0_usize;
buffer.m_start_index = 0_usize;
buffer.m_capacity = 0_usize;
return *this;
}
private:
static const constexpr usize DEFAULT_CAPACITY_INTERNAL = DEFAULT_CAPACITY + 1;
Allocator<T> m_allocator = Allocator<T>();
unique_pointer m_buffer
= allocate_unique<T[]>(m_allocator, DEFAULT_CAPACITY_INTERNAL); // NOLINT
usize m_write_index = 0_usize;
usize m_start_index = 0_usize;
usize m_loop_index = DEFAULT_CAPACITY;
usize m_capacity = DEFAULT_CAPACITY_INTERNAL;
/// @brief Converts the given `RingBuffer` index into the corresponding index into then
/// underlying `T` array
///
/// @param index - The `RingBuffer` index to convert
///
/// @return The corresponding index into the underlying `T` array
[[nodiscard]] inline constexpr auto
get_adjusted_internal_index(concepts::Integral auto index) const noexcept -> usize {
auto i = static_cast<usize>(index);
return (m_start_index + i) % (m_capacity);
}
/// @brief Converts the given index into the underlying `T` array into
/// a using facing index into the `RingBuffer`
///
/// @param index - The internal index
///
/// @return The corresponding user-facing index
[[nodiscard]] inline constexpr auto
get_external_index_from_internal(concepts::Integral auto index) const noexcept -> usize {
auto i = static_cast<usize>(index);
if(i >= m_start_index && i <= m_loop_index) {
return i - m_start_index;
}
else if(i < m_start_index) {
return m_capacity - (m_start_index - i);
}
else {
return m_capacity - 1;
}
}
/// @brief Used to increment the start and write indices into the underlying `T` array,
/// and the size property, after pushing an element at the back,
/// maintaining the logical `RingBuffer` structure
inline constexpr auto increment_indices() noexcept -> void {
m_write_index = (m_write_index + 1) % (m_capacity);
// if write index is at start, we need to push start forward to maintain
// the "invalid" spacer element for this.end()
if(m_write_index == m_start_index) {
m_start_index = (m_start_index + 1) % (m_capacity);
}
}
/// @brief Used to increment the start index into the underlying `T` array
/// and the size property after popping an element from the front,
/// maintaining the logical `RingBuffer` structure
inline constexpr auto increment_start() noexcept -> void {
if(m_start_index != m_write_index) {
m_start_index = (m_start_index + 1) % (m_capacity);
}
}
/// @brief Used to decrement the write index into the underlying `T` array
/// when popping an element from the back
inline constexpr auto decrement_write() noexcept -> void {
if(m_write_index == 0_usize) {
m_write_index = m_capacity - 1;
}
else {
m_write_index--;
}
}
inline constexpr auto
decrement_write_n(concepts::UnsignedIntegral auto n) noexcept -> void {
auto amount_to_decrement = static_cast<usize>(n);
if(amount_to_decrement > m_write_index) {
amount_to_decrement -= m_write_index;
m_write_index = (m_capacity - 1) - amount_to_decrement;
}
else {
m_write_index -= amount_to_decrement;
}
}
/// @brief Inserts the given element at the position indicated
/// by the `external_index`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param external_index - The user-facing index into the `RingBuffer` to insert the
/// element at
/// @param elem - The element to store in the `RingBuffer`
inline constexpr auto
insert_internal(usize external_index, const T& elem) noexcept -> void {
auto index = get_adjusted_internal_index(external_index);
if(index == m_write_index) {
emplace_back(elem);
}
else {
const auto size_ = size();
auto num_to_move = size_ - external_index;
auto j = num_to_move - 1;
// if we're full, drop the last element in the buffer
if(size_ == m_capacity - 1) [[likely]] { // NOLINT
num_to_move--;
j--;
index++;
}
for(auto i = 0_usize; i < num_to_move; ++i, --j) {
if constexpr(concepts::MoveAssignable<T>) {
m_buffer[get_adjusted_internal_index(size_ - i)]
= std::move(m_buffer[get_adjusted_internal_index(external_index + j)]);
}
else {
m_buffer[get_adjusted_internal_index(size_ - i)]
= m_buffer[get_adjusted_internal_index(external_index + j)];
}
}
m_buffer[index] = elem;
increment_indices();
}
}
/// @brief Inserts the given element at the position indicated
/// by the `external_index`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param external_index - The user-facing index into the `RingBuffer` to insert the
/// element at
/// @param elem - The element to store in the `RingBuffer`
inline constexpr auto insert_internal(usize external_index, T&& elem) noexcept -> void {
auto index = get_adjusted_internal_index(external_index);
if(index == m_write_index) {
emplace_back(std::move(elem));
}
else {
const auto size_ = size();
auto num_to_move = size_ - external_index;
auto j = num_to_move - 1;
// if we're full, drop the last element in the buffer
if(size_ == m_capacity - 1) [[likely]] { // NOLINT
num_to_move--;
j--;
index++;
}
for(auto i = 0_usize; i < num_to_move; ++i, --j) {
if constexpr(concepts::MoveAssignable<T>) {
m_buffer[get_adjusted_internal_index(size_ - i)]
= std::move(m_buffer[get_adjusted_internal_index(external_index + j)]);
}
else {
m_buffer[get_adjusted_internal_index(size_ - i)]
= m_buffer[get_adjusted_internal_index(external_index + j)];
}
}
m_buffer[index] = std::move(elem);
increment_indices();
}
}
/// @brief Constructs the given element at the insertion position indicated
/// by the `external_index`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param external_index - The user-facing index into the `RingBuffer` to insert the
/// element at
/// @param args - The arguments to the constructor for
/// the element to store in the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto
insert_emplace_internal(usize external_index, Args&&... args) noexcept -> T& {
auto index = get_adjusted_internal_index(external_index);
if(index == m_write_index) {
return emplace_back(std::forward<Args>(args)...);
}
else {
const auto size_ = size();
auto num_to_move = size_ - external_index;
auto j = num_to_move - 1;
// if we're full, drop the last element in the buffer
if(size_ == m_capacity - 1) [[likely]] { // NOLINT
num_to_move--;
j--;
index++;
}
for(auto i = 0_usize; i < num_to_move; ++i, --j) {
if constexpr(concepts::MoveAssignable<T>) {
m_buffer[get_adjusted_internal_index(size_ - i)]
= std::move(m_buffer[get_adjusted_internal_index(external_index + j)]);
}
else {
m_buffer[get_adjusted_internal_index(size_ - i)]
= m_buffer[get_adjusted_internal_index(external_index + j)];
}
}
allocator_traits::template construct<T>(m_allocator,
&m_buffer[index],
std::forward<Args>(args)...);
increment_indices();
return m_buffer[index];
}
}
/// @brief Erases the element at the given index, returning an `Iterator` to the element
/// after the removed one
///
/// @param external_index - The index to the element to remove. This should be a
/// `RingBuffer` index: IE, not an internal one into the `T` array
///
/// @return `Iterator` pointing to the element after the one removed
[[nodiscard]] inline constexpr auto
erase_internal(usize external_index) noexcept -> Iterator {
const auto index = get_adjusted_internal_index(external_index);
if(index == m_write_index) [[unlikely]] { // NOLINT
return end();
}
else {
const auto size_ = size();
auto num_to_move = (size_ - 1) - external_index;
const auto pos_to_move = external_index + 1;
const auto pos_to_replace = external_index;
for(auto i = 0_usize; i < num_to_move; ++i) {
if constexpr(concepts::MoveAssignable<T>) {
m_buffer[get_adjusted_internal_index(pos_to_replace + i)]
= std::move(m_buffer[get_adjusted_internal_index(pos_to_move + i)]);
}
else {
m_buffer[get_adjusted_internal_index(pos_to_replace + i)]
= m_buffer[get_adjusted_internal_index(pos_to_move + i)];
}
}
decrement_write();
return begin() + external_index;
}
}
/// @brief Erases the range of elements in [`first`, `last`)
/// Returns an `Iterator` to the element after the last one erased
///
/// @param first - The first index in the range to erase. This should be a `RingBuffer`
/// index: IE, not an internal one into the `T` array
/// @param last - The last index` in the range to erase. This should be a `RingBuffer`
/// index: IE, not an internal one into the `T` array
///
/// @return `Iterator` pointing to the element after the last one erased
[[nodiscard]] inline constexpr auto
erase_internal(usize first, usize last) noexcept -> Iterator {
const auto size_ = size();
const auto last_internal = get_adjusted_internal_index(last);
const auto num_to_remove = (last - first);
if(last_internal > m_write_index) {
if(m_write_index > m_start_index) {
decrement_write_n(num_to_remove);
}
else if(m_write_index < m_start_index) {
auto num_after_start_index
= (m_write_index > num_to_remove ? m_write_index - num_to_remove : 0_usize);
auto num_before_start_index = num_to_remove - num_after_start_index;
if(num_after_start_index > 0) {
num_after_start_index--;
m_write_index = (m_capacity - 1) - num_after_start_index;
}
else {
decrement_write_n(num_before_start_index);
}
}
return end();
}
else {
const auto num_to_move = size_ - last;
const auto pos_to_move = last;
const auto pos_to_replace = first;
for(auto i = 0_usize; i < num_to_move; ++i) {
if constexpr(concepts::MoveAssignable<T>) {
m_buffer[get_adjusted_internal_index(pos_to_replace + i)]
= std::move(m_buffer[get_adjusted_internal_index(pos_to_move + i)]);
}
else {
m_buffer[get_adjusted_internal_index(pos_to_replace + i)]
= m_buffer[get_adjusted_internal_index(pos_to_move + i)];
}
}
decrement_write_n(num_to_remove);
return begin() + first;
}
}
};
/// @brief A simple Ring Buffer implementation.
/// Supports resizing, writing, reading, erasing, and provides mutable and immutable
/// random access iterators.
///
/// # Iterator Invalidation
/// * Iterators are lazily evaluated, so will only ever be invalidated at their current state.
/// Performing any mutating operation (mutating the iterator, not the underlying data) on them
/// will re-sync them with their associated `RingBuffer`.
/// The following operations will invalidate an iterator's current state:
/// - Read-only operations: never
/// - clear: always
/// - reserve: only if the `RingBuffer` changed capacity
/// - erase: Erased elements and all following elements
/// - push_back, emplace_back: only `end()` until `capacity()` is reached,
/// then `begin()` and `end()`
/// - insert, emplace: only the element at the position inserted/emplaced
/// - pop_back: the element removed and `end()`
/// - pop_front: the element removed and `begin()`
///
/// @tparam T - The type to store in the `RingBuffer`. Must Be Default Constructible.
/// Does not currently support `T` of array types (eg, `T` = `U[]` or `T` = `U[N]`)
template<concepts::DefaultConstructible T, template<typename ElementType> typename Allocator>
class RingBuffer<T, RingBufferType::ThreadSafe, Allocator> {
public:
using index_type = u32;
/// Default capacity of `RingBuffer`
static const constexpr index_type DEFAULT_CAPACITY = 16;
struct Element {
std::shared_ptr<T> m_element = nullptr;
constexpr Element() noexcept = default;
explicit constexpr Element(const std::shared_ptr<T>& element) noexcept
: m_element(element) {
}
explicit constexpr Element(std::shared_ptr<T> element) noexcept
: m_element(std::move(element)) {
}
explicit constexpr Element(T* element) noexcept : m_element(element) {
}
constexpr Element(Allocator<Element>& alloc, const T& element) noexcept
: m_element(std::allocate_shared<T, Allocator<Element>>(alloc, element)) {
}
constexpr Element(Allocator<Element>& alloc, T&& element) noexcept
: m_element(std::allocate_shared<T, Allocator<Element>>(alloc, element)) {
}
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
explicit constexpr Element(Allocator<Element>& alloc, Args&&... args) noexcept
: m_element(
std::allocate_shared<T, Allocator<Element>>(alloc,
std::forward<Args>(args)...)) {
}
constexpr Element(const Element& element) noexcept = default;
constexpr Element(Element&& element) noexcept = default;
constexpr ~Element() noexcept = default;
inline constexpr auto operator=(const Element& element) noexcept -> Element& = default;
inline constexpr auto operator=(Element&& element) noexcept -> Element& = default;
inline constexpr auto
operator=(const std::shared_ptr<T>& element) noexcept -> Element& {
m_element = element;
return *this;
}
inline constexpr auto operator=(std::shared_ptr<T>&& element) noexcept -> Element& {
m_element = std::move(element);
return *this;
}
// inline constexpr auto operator=(const T& element) noexcept -> Element& {
// m_element = std::make_shared<T>(element);
// return *this;
// }
// inline constexpr auto operator=(T&& element) noexcept -> Element& {
// m_element = std::make_shared<T>(element);
// return *this;
// }
inline constexpr auto operator==(const Element& element) const noexcept -> bool {
return *m_element == *(element.m_element);
}
inline constexpr auto operator!=(const Element& element) const noexcept -> bool {
return *(m_element) != *(element.m_element);
}
// friend inline constexpr auto
// operator==(const Element& lhs, const T& rhs) noexcept -> bool {
// return (*lhs.m_element) == rhs;
// }
// friend inline constexpr auto
// operator!=(const Element& lhs, const T& rhs) noexcept -> bool {
// return (*lhs.m_element) != rhs;
// }
inline constexpr operator T&() noexcept { // NOLINT
return *m_element;
}
inline constexpr operator const T&() const noexcept { // NOLINT
return *m_element;
}
inline constexpr auto operator*() noexcept -> T& {
return *m_element;
}
inline constexpr auto operator*() const noexcept -> const T& {
return *m_element;
}
inline constexpr auto operator->() noexcept -> T* {
return m_element.get();
}
inline constexpr auto operator->() const noexcept -> const T* {
return m_element.get();
}
};
using allocator_traits = std::allocator_traits<Allocator<Element>>;
using unique_pointer
= decltype(allocate_unique<Element[]>(std::declval<Allocator<Element[]>>(), // NOLINT
DEFAULT_CAPACITY));
/// @brief Random-Access Bidirectional iterator for `RingBuffer`
/// @note All navigation operators are checked such that any movement past `begin()` or
/// `end()` is ignored.
class Iterator {
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = Element;
using pointer = Element;
using reference = Element&;
constexpr explicit Iterator(pointer ptr,
RingBuffer* containerPtr,
index_type currentIndex) noexcept
: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {
}
constexpr Iterator(const Iterator& iter) noexcept = default;
constexpr Iterator(Iterator&& iter) noexcept = default;
~Iterator() noexcept = default;
/// @brief Returns the index in the `RingBuffer` that corresponds
/// to the element this iterator points to
///
/// @return The index corresponding with the element this points to
[[nodiscard]] inline constexpr auto get_index() const noexcept -> index_type {
return m_current_index;
}
constexpr auto operator=(const Iterator& iter) noexcept -> Iterator& = default;
constexpr auto operator=(Iterator&& iter) noexcept -> Iterator& = default;
inline constexpr auto operator==(const Iterator& rhs) const noexcept -> bool {
return m_ptr == rhs.m_ptr;
}
inline constexpr auto operator!=(const Iterator& rhs) const noexcept -> bool {
return m_ptr != rhs.m_ptr;
}
inline constexpr auto operator*() noexcept -> reference {
return m_ptr;
}
inline constexpr auto operator->() noexcept -> pointer {
return m_ptr;
}
inline constexpr auto operator++() noexcept -> Iterator& {
m_current_index++;
if(m_current_index >= m_container_ptr->capacity()) {
m_current_index = m_container_ptr->capacity();
m_ptr = m_container_ptr->end().m_ptr;
}
else {
m_ptr = (*m_container_ptr)[m_current_index];
}
return *this;
}
inline constexpr auto operator++(int) noexcept -> Iterator {
Iterator temp = *this;
++(*this);
return temp;
}
inline constexpr auto operator--() noexcept -> Iterator& {
if(m_current_index == 0) {
return *this;
}
else {
m_current_index--;
m_ptr = (*m_container_ptr)[m_current_index];
}
return *this;
}
inline constexpr auto operator--(int) noexcept -> Iterator {
Iterator temp = *this;
--(*this);
return temp;
}
inline constexpr auto
operator+(concepts::Integral auto rhs) const noexcept -> Iterator {
const auto diff = static_cast<index_type>(rhs);
if(rhs < 0) {
return std::move(*this - -rhs);
}
auto temp = *this;
temp.m_current_index += diff;
if(temp.m_current_index > temp.m_container_ptr->capacity()) {
temp.m_current_index = temp.m_container_ptr->capacity();
temp.m_ptr = temp.m_container_ptr->end().m_ptr;
}
else {
temp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto operator+=(concepts::Integral auto rhs) noexcept -> Iterator& {
*this = std::move(*this + rhs);
return *this;
}
inline constexpr auto
operator-(concepts::Integral auto rhs) const noexcept -> Iterator {
const auto diff = static_cast<index_type>(rhs);
if(rhs < 0) {
return std::move(*this + -rhs);
}
auto temp = *this;
if(diff > temp.m_current_index) {
temp.m_ptr = temp.m_container_ptr->begin().m_ptr;
temp.m_current_index = 0;
}
else {
temp.m_current_index -= diff;
temp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto operator-=(concepts::Integral auto rhs) noexcept -> Iterator& {
*this = std::move(*this - rhs);
return *this;
}
inline constexpr auto operator-(const Iterator& rhs) const noexcept -> difference_type {
return static_cast<std::ptrdiff_t>(m_current_index)
- static_cast<std::ptrdiff_t>(rhs.m_current_index);
}
inline constexpr auto operator[](concepts::Integral auto index) noexcept -> Iterator {
return std::move(*this + index);
}
inline constexpr auto operator>(const Iterator& rhs) const noexcept -> bool {
return m_current_index > rhs.m_current_index;
}
inline constexpr auto operator<(const Iterator& rhs) const noexcept -> bool {
return m_current_index < rhs.m_current_index;
}
inline constexpr auto operator>=(const Iterator& rhs) const noexcept -> bool {
return m_current_index >= rhs.m_current_index;
}
inline constexpr auto operator<=(const Iterator& rhs) const noexcept -> bool {
return m_current_index <= rhs.m_current_index;
}
private:
pointer m_ptr;
RingBuffer* m_container_ptr = nullptr;
index_type m_current_index = 0;
};
/// @brief Read-only Random-Access Bidirectional iterator for `RingBuffer`
/// @note All navigation operators are checked such that any movement past `begin()` or
/// `end()` is ignored.
class ConstIterator {
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = Element;
using pointer = const Element;
using reference = const Element&;
constexpr explicit ConstIterator(pointer ptr,
RingBuffer* containerPtr,
index_type currentIndex) noexcept
: m_ptr(ptr), m_container_ptr(containerPtr), m_current_index(currentIndex) {
}
constexpr ConstIterator(const ConstIterator& iter) noexcept = default;
constexpr ConstIterator(ConstIterator&& iter) noexcept = default;
~ConstIterator() noexcept = default;
/// @brief Returns the index in the `RingBuffer` that corresponds
/// to the element this iterator points to
///
/// @return The index corresponding with the element this points to
[[nodiscard]] inline constexpr auto get_index() const noexcept -> index_type {
return m_current_index;
}
constexpr auto
operator=(const ConstIterator& iter) noexcept -> ConstIterator& = default;
constexpr auto operator=(ConstIterator&& iter) noexcept -> ConstIterator& = default;
inline constexpr auto operator==(const ConstIterator& rhs) const noexcept -> bool {
return m_ptr == rhs.m_ptr;
}
inline constexpr auto operator!=(const ConstIterator& rhs) const noexcept -> bool {
return m_ptr != rhs.m_ptr;
}
inline constexpr auto operator*() const noexcept -> reference {
return m_ptr;
}
inline constexpr auto operator->() const noexcept -> pointer {
return m_ptr;
}
inline constexpr auto operator++() noexcept -> ConstIterator& {
m_current_index++;
if(m_current_index >= m_container_ptr->capacity()) {
m_current_index = m_container_ptr->capacity();
m_ptr = m_container_ptr->end().m_ptr;
}
else {
m_ptr = (*m_container_ptr)[m_current_index];
}
return *this;
}
inline constexpr auto operator++(int) noexcept -> ConstIterator {
ConstIterator temp = *this;
++(*this);
return temp;
}
inline constexpr auto operator--() noexcept -> ConstIterator& {
if(m_current_index == 0) {
return *this;
}
else {
m_current_index--;
m_ptr = (*m_container_ptr)[m_current_index];
}
return *this;
}
inline constexpr auto operator--(int) noexcept -> ConstIterator {
ConstIterator temp = *this;
--(*this);
return temp;
}
inline constexpr auto
operator+(concepts::Integral auto rhs) const noexcept -> ConstIterator {
const auto diff = static_cast<index_type>(rhs);
if(rhs < 0) {
return std::move(*this - -rhs);
}
auto temp = *this;
temp.m_current_index += diff;
if(temp.m_current_index > temp.m_container_ptr->capacity()) {
temp.m_current_index = temp.m_container_ptr->capacity();
temp.m_ptr = temp.m_container_ptr->end().m_ptr;
}
else {
temp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto
operator+=(concepts::Integral auto rhs) noexcept -> ConstIterator& {
*this = std::move(*this + rhs);
return *this;
}
inline constexpr auto
operator-(concepts::Integral auto rhs) const noexcept -> ConstIterator {
const auto diff = static_cast<index_type>(rhs);
if(rhs < 0) {
return std::move(*this + -rhs);
}
auto temp = *this;
if(diff > temp.m_current_index) {
temp.m_ptr = temp.m_container_ptr->begin().m_ptr;
temp.m_current_index = 0;
}
else {
temp.m_current_index -= diff;
temp.m_ptr = (*temp.m_container_ptr)[temp.m_current_index];
}
return temp;
}
inline constexpr auto
operator-=(concepts::Integral auto rhs) noexcept -> ConstIterator& {
*this = std::move(*this - rhs);
return *this;
}
inline constexpr auto
operator-(const ConstIterator& rhs) const noexcept -> difference_type {
return static_cast<std::ptrdiff_t>(m_current_index)
- static_cast<std::ptrdiff_t>(rhs.m_current_index);
}
inline constexpr auto
operator[](concepts::Integral auto index) const noexcept -> ConstIterator {
return std::move(*this + index);
}
inline constexpr auto operator>(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index > rhs.m_current_index;
}
inline constexpr auto operator<(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index < rhs.m_current_index;
}
inline constexpr auto operator>=(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index >= rhs.m_current_index;
}
inline constexpr auto operator<=(const ConstIterator& rhs) const noexcept -> bool {
return m_current_index <= rhs.m_current_index;
}
private:
pointer m_ptr;
RingBuffer* m_container_ptr = nullptr;
index_type m_current_index = 0;
};
/// @brief Creates a `RingBuffer` with default capacity
constexpr RingBuffer() noexcept = default;
/// @brief Creates a `RingBuffer` with (at least) the given initial capacity
///
/// @param intitial_capacity - The initial capacity of the `RingBuffer`
constexpr explicit RingBuffer(index_type intitial_capacity) noexcept
: m_buffer(allocate_unique<Element[]>(m_allocator, // NOLINT
intitial_capacity + 1,
m_allocator)),
m_state(intitial_capacity + 1) {
}
/// @brief Constructs a new `RingBuffer` with the given initial capacity and
/// fills it with `default_value`
///
/// @param intitial_capacity - The initial capacity of the `RingBuffer`
/// @param default_value - The value to fill the `RingBuffer` with
constexpr RingBuffer(
index_type intitial_capacity,
const T& default_value) noexcept requires concepts::CopyConstructible<T>
: m_buffer(allocate_unique<Element[]>(m_allocator, // NOLINT
intitial_capacity + 1,
m_allocator,
default_value)),
m_state(intitial_capacity + 1, 0U, intitial_capacity) {
}
constexpr RingBuffer(const RingBuffer& buffer) noexcept requires concepts::CopyAssignable<T>
: m_buffer(allocate_unique<Element[]>(m_allocator, // NOLINT
buffer.m_capacity,
m_allocator)),
m_state(buffer.m_capacity) {
const auto size = buffer.size();
for(auto i = 0_u32; i < size; ++i) {
push_back(buffer.m_buffer[i]);
}
m_state = buffer.m_state;
}
constexpr RingBuffer(RingBuffer&& buffer) noexcept
: m_allocator(buffer.m_allocator),
m_buffer(std::move(buffer.m_buffer)),
m_state(buffer.m_state) {
buffer.m_state.update(0U, 0U, 0U);
buffer.m_buffer = nullptr;
}
~RingBuffer() noexcept = default;
/// @brief Returns the element at the given index.
/// @note This is not checked in the same manner as STL containers:
/// if index >= capacity, the element at capacity - 1 is returned.
///
/// @param index - The index of the desired element
///
/// @return The element at the given index, or at capacity - 1 if index >= capacity
[[nodiscard]] inline constexpr auto at(concepts::Integral auto index) noexcept -> Element {
const auto i = m_state.adjusted_index(static_cast<index_type>(index));
return m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Returns the first element in the `RingBuffer`
///
/// @return The first element
[[nodiscard]] inline constexpr auto front() noexcept -> Element {
return m_buffer
[m_state.start()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Returns the last element in the `RingBuffer`
/// @note If <= 1 elements are in the `RingBuffer`, this will be the same as `front`
///
/// @return The last element
[[nodiscard]] inline constexpr auto back() noexcept -> Element {
const auto index = m_state.back();
return m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Returns a pointer to the underlying data in the `RingBuffer`.
/// @note This is not sorted in any way to match the representation used by the `RingBuffer`
///
/// @return A pointer to the underlying data
[[nodiscard]] inline constexpr auto data() noexcept -> Element* {
return m_buffer;
}
/// @brief Returns whether the `RingBuffer` is empty
///
/// @return `true` if the `RingBuffer` is empty, `false` otherwise
[[nodiscard]] inline constexpr auto empty() const noexcept -> bool {
return m_state.empty();
}
/// @brief Returns whether the `RingBuffer` is full
///
/// @return `true` if the `RingBuffer` is full, `false` otherwise
[[nodiscard]] inline constexpr auto full() const noexcept -> bool {
return m_state.full();
}
/// @brief Returns the current number of elements in the `RingBuffer`
///
/// @return The current number of elements
[[nodiscard]] inline constexpr auto size() const noexcept -> index_type {
return m_state.size();
}
/// @brief Returns the maximum possible number of elements this `RingBuffer` could store
/// if grown to maximum possible capacity
///
/// @return The maximum possible number of storable elements
[[nodiscard]] inline constexpr auto max_size() const noexcept -> index_type {
return m_state.max_size();
}
/// @brief Returns the current capacity of the `RingBuffer`;
/// the number of elements it can currently store
///
/// @return The current capacity
[[nodiscard]] inline constexpr auto capacity() const noexcept -> index_type {
return m_state.capacity() - 1;
}
/// @brief Reserves more storage for the `RingBuffer`. If `new_capacity` is > capacity,
/// then the capacity of the `RingBuffer` will be extended until at least `new_capacity`
/// elements can be stored.
/// @note Memory contiguity is maintained, so no **elements** will be lost or invalidated.
/// However, all iterators and references to elements will be invalidated.
///
/// @param new_capacity - The new capacity of the `RingBuffer`
inline constexpr auto reserve(index_type new_capacity) noexcept -> void {
auto capacity_ = m_state.capacity();
// we only need to do anything if `new_capacity` is actually larger than `m_capacity`
if(new_capacity > capacity_ - 1) {
auto temp = allocate_unique<Element[]>(m_allocator, // NOLINT
new_capacity + 1,
m_allocator);
auto span = gsl::make_span(&temp[0], new_capacity + 1);
std::copy(begin(), end(), span.begin());
m_buffer = std::move(temp);
m_state.update(0U, capacity_, new_capacity + 1);
}
}
/// @brief Erases all elements from the `RingBuffer`
inline constexpr auto clear() noexcept -> void {
m_state.clear();
}
/// @brief Inserts the given element at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @param value - the element to insert
inline constexpr auto
push_back(const T& value) noexcept -> void requires concepts::CopyAssignable<T> {
m_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
= Element(m_allocator, value);
m_state.increment_indices();
}
/// @brief Inserts the given element at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @param value - the element to insert
inline constexpr auto push_back(T&& value) noexcept -> void {
m_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
= Element(m_allocator, std::forward<T>(value));
m_state.increment_indices();
}
/// @brief Inserts the given element at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @param element - the element to insert
inline constexpr auto push_back(const Element& element) noexcept -> void {
m_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
= element;
m_state.increment_indices();
}
/// @brief Inserts the given element at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @param element - the element to insert
inline constexpr auto push_back(Element&& element) noexcept -> void {
m_buffer[m_state.write()] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
= std::forward<Element>(element);
m_state.increment_indices();
}
/// @brief Constructs the given element in place at the end of the `RingBuffer`
/// @note if `size() == capacity()` then this loops and overwrites `front()`
///
/// @tparam Args - The types of the element's constructor arguments
/// @param args - The constructor arguments for the element
///
/// @return A reference to the element constructed at the end of the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto emplace_back(Args&&... args) noexcept -> Element {
const auto index = m_state.write();
allocator_traits::template construct<Element>(
m_allocator,
&m_buffer[index], // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
std::allocate_shared<T, Allocator<Element>>(m_allocator,
std::forward<Args>(args)...));
m_state.increment_indices();
return m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Constructs the given element in place at the location
/// indicated by the `Iterator` `position`
///
/// @tparam Args - The types of the element's constructor arguments
/// @param position - `Iterator` indicating where in the `RingBuffer` to construct the
/// element
/// @param args - The constructor arguments for the element
///
/// @return A reference to the element constructed at the location indicated by `position`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto
emplace(const Iterator& position, Args&&... args) noexcept -> Element {
const auto index = m_state.get_adjusted_internal_index(position.get_index());
allocator_traits::template construct<Element>(
m_allocator,
&m_buffer[index], // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
std::allocate_shared<T, Allocator<Element>>(m_allocator,
std::forward<Args>(args)...));
return m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Constructs the given element in place at the location
/// indicated by the `ConstIterator` `position`
///
/// @tparam Args - The types of the element's constructor arguments
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to construct the
/// element
/// @param args - The constructor arguments for the element
///
/// @return A reference to the element constructed at the location indicated by `position`
template<typename... Args>
inline constexpr auto
emplace(const ConstIterator& position, Args&&... args) noexcept -> Element {
const auto index = m_state.get_adjusted_internal_index(position.get_index());
allocator_traits::template construct<Element>(
m_allocator,
&m_buffer[index], // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
std::allocate_shared<T, Allocator<Element>>(m_allocator,
std::forward<Args>(args)...));
return m_buffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
/// @brief Assigns the given element to the position indicated
/// by the `Iterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const Iterator& position, const T& element) noexcept
-> void requires concepts::CopyAssignable<T> {
insert_internal(position.get_index(), element);
}
/// @brief Assigns the given element to the position indicated
/// by the `Iterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `Iterator` indicating where in the `RingBuffer` to place the element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const Iterator& position, T&& element) noexcept -> void {
insert_internal(position.get_index(), std::forward<T>(element));
}
/// @brief Assigns the given element to the position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const ConstIterator& position, const T& element) noexcept
-> void requires concepts::CopyAssignable<T> {
insert_internal(position.get_index(), element);
}
/// @brief Assigns the given element to the position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param element - The element to store in the `RingBuffer`
inline constexpr auto insert(const ConstIterator& position, T&& element) noexcept -> void {
insert_internal(position.get_index(), std::forward<T>(element));
}
/// @brief Constructs the given element at the insertion position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param args - The arguments to the constructor for
/// the element to store in the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto
insert_emplace(const Iterator& position, Args&&... args) noexcept -> Element {
return insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);
}
/// @brief Constructs the given element at the insertion position indicated
/// by the `ConstIterator` `position`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the
/// element
/// @param args - The arguments to the constructor for
/// the element to store in the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto
insert_emplace(const ConstIterator& position, Args&&... args) noexcept -> Element {
return insert_emplace_internal(position.get_index(), std::forward<Args>(args)...);
}
/// @brief Erases the element at the given `position`, moving other elements backward
/// in the buffer to maintain contiguity
///
/// @param position - The element to erase
///
/// @return `Iterator` pointing to the element after the one erased
inline constexpr auto erase(const Iterator& position) noexcept -> Iterator {
return erase_internal(position.get_index());
}
/// @brief Erases the element at the given `position`, moving other elements backward
/// in the buffer to maintain contiguity
///
/// @param position - The element to erase
///
/// @return `Iterator` pointing to the element after the one erased
inline constexpr auto erase(const ConstIterator& position) noexcept -> Iterator {
return erase_internal(position.get_index());
}
/// @brief Erases the range of elements in [`first`, `last`)
/// Returns an `Iterator` to the element after the last one erased
/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;
///
/// @param first - The first element in the range to erase
/// @param last - The last element in the range
///
/// @return `Iterator` pointing to the element after the last one erased
inline constexpr auto
erase(const Iterator& first, const Iterator& last) noexcept -> Iterator {
if(first >= last) {
return last;
}
return erase_internal(first.get_index(), last.get_index());
}
/// @brief Erases the range of elements in [`first`, `last`)
/// Returns an `Iterator` to the element after the last one erased
/// @note In the case `first` >= `last`, no elements are erased and `last` is returned;
///
/// @param first - The first element in the range to erase
/// @param last - The last element in the range
///
/// @return `Iterator` pointing to the element after the last one erased
inline constexpr auto
erase(const ConstIterator& first, const ConstIterator& last) noexcept -> Iterator {
if(first >= last) {
return last;
}
return erase_internal(first.get_index(), last.get_index());
}
/// @brief Removes the last element in the `RingBuffer` and returns it
///
/// @return The last element in the `RingBuffer`
[[nodiscard]] inline constexpr auto pop_back() noexcept -> Element {
Element back_ = back();
m_state.decrement_write();
return back_;
}
/// @brief Removes the first element in the `RingBuffer` and returns it
///
/// @return The first element in the `RingBuffer`
[[nodiscard]] inline constexpr auto pop_front() noexcept -> Element {
Element front_ = front();
m_state.increment_start();
return front_;
}
/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,
/// at the beginning
///
/// @return The iterator, at the beginning
[[nodiscard]] inline constexpr auto begin() -> Iterator {
// clang-format off
Element p = m_buffer[m_state.start()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
// clang-format on
return Iterator(p, this, 0U);
}
/// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`,
/// at the end
///
/// @return The iterator, at the end
[[nodiscard]] inline constexpr auto end() -> Iterator {
// clang-format off
Element p = m_buffer[m_state.write()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
// clang-format on
return Iterator(p, this, m_state.size());
}
/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,
/// at the beginning
///
/// @return The iterator, at the beginning
[[nodiscard]] inline constexpr auto cbegin() -> ConstIterator {
// clang-format off
Element p = m_buffer[m_state.start()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
// clang-format on
return ConstIterator(p, this, 0U);
}
/// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`,
/// at the end
///
/// @return The iterator, at the end
[[nodiscard]] inline constexpr auto cend() -> ConstIterator {
// clang-format off
Element p = m_buffer[m_state.write()]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
// clang-format on
return ConstIterator(p, this, m_state.size());
}
/// @brief Unchecked access-by-index operator
///
/// @param index - The index to get the corresponding element for
///
/// @return - The element at index
[[nodiscard]] inline constexpr auto
operator[](concepts::Integral auto index) noexcept -> Element {
const auto i = m_state.adjusted_index(static_cast<index_type>(index));
return m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
constexpr auto operator=(const RingBuffer& buffer) noexcept
-> RingBuffer& requires concepts::CopyAssignable<T> {
if(this == &buffer) {
return *this;
}
auto temp = allocate_unique<Element[]>(m_allocator, // NOLINT
buffer.m_capacity,
m_allocator);
const auto size = buffer.size();
for(auto i = 0_u32; i < size; ++i) {
temp[i] // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
= buffer.m_buffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
m_buffer = std::move(temp);
m_state = m_buffer.m_state;
return *this;
}
constexpr auto operator=(RingBuffer&& buffer) noexcept -> RingBuffer& {
m_allocator = buffer.m_allocator;
m_buffer = std::move(buffer.m_buffer);
m_state = m_buffer.m_state;
buffer.m_buffer = nullptr;
buffer.m_state.update(0U, 0U, 0U);
return *this;
}
private:
static const constexpr u32 DEFAULT_CAPACITY_INTERNAL = DEFAULT_CAPACITY + 1;
class State {
public:
using merged_type = uint64_t;
using atomic_index_type = std::atomic<index_type>;
using atomic_merged_type = std::atomic<merged_type>;
constexpr State() noexcept = default;
explicit constexpr State(index_type capacity) noexcept : m_capacity(capacity) {
}
explicit constexpr State(index_type capacity, // NOLINT
index_type start,
index_type write) noexcept
: m_indices(merge_indices(start, write)), m_capacity(capacity) {
}
constexpr State(const State& state) noexcept
: m_indices(state.m_indices.load()), m_capacity(state.m_capacity.load()) {
}
constexpr State(State&& state) noexcept
: m_indices(state.m_indices.load()), m_capacity(state.m_capacity.load()) {
}
constexpr ~State() noexcept = default;
inline constexpr auto
update(index_type start, index_type write, index_type capacity) // NOLINT
noexcept -> void {
auto indices = m_indices.load();
while(!m_indices.compare_exchange_weak(indices, merge_indices(start, write))) {
}
auto capacity_ = m_capacity.load();
while(!m_capacity.compare_exchange_weak(capacity_, capacity)) {
}
}
[[nodiscard]] inline constexpr auto start() const noexcept -> index_type {
return start(m_indices.load());
}
[[nodiscard]] inline constexpr auto write() const noexcept -> index_type {
return write(m_indices.load());
}
[[nodiscard]] inline constexpr auto
indices() const noexcept -> std::tuple<index_type, index_type> {
const auto val = m_indices.load();
return {start(val), write(val)};
}
[[nodiscard]] inline constexpr auto capacity() const noexcept -> index_type {
return m_capacity.load();
}
[[nodiscard]] inline constexpr auto max_size() const noexcept -> index_type {
return std::numeric_limits<index_type>::max() - 1;
}
[[nodiscard]] inline constexpr auto loop_index() const noexcept -> index_type {
return m_capacity.load() - 1;
}
[[nodiscard]] inline constexpr auto size() const noexcept -> index_type {
const auto indices = m_indices.load();
const auto capacity_ = m_capacity.load();
const auto start_ = start(indices);
const auto write_ = write(indices);
return write_ >= start_ ? (write_ - start_) : (capacity_ - (start_ - write_));
}
[[nodiscard]] inline constexpr auto
size(concepts::UnsignedIntegral auto start,
concepts::UnsignedIntegral auto write,
concepts::UnsignedIntegral auto capacity) const noexcept -> index_type {
const auto start_ = static_cast<index_type>(start);
const auto write_ = static_cast<index_type>(write);
const auto capacity_ = static_cast<index_type>(capacity);
return static_cast<index_type>(write_ >= start_ ? (write_ - start_) :
(capacity_ - (start_ - write_)));
}
[[nodiscard]] inline constexpr auto empty() const noexcept -> bool {
return size() == 0_u32;
}
[[nodiscard]] inline constexpr auto full() const noexcept -> bool {
const auto indices = m_indices.load();
const auto capacity_ = m_capacity.load();
const auto start_ = start(indices);
const auto write_ = write(indices);
const auto size_
= write_ >= start_ ? (write_ - start_) : (capacity_ - (start_ - write_));
return size_ == capacity_ - 1;
}
inline constexpr auto clear() noexcept -> void {
auto indices = m_indices.load();
while(!m_indices.compare_exchange_weak(indices, merge_indices(0U, 0U))) {
}
}
[[nodiscard]] inline constexpr auto
adjusted_index(concepts::UnsignedIntegral auto index) const noexcept -> index_type {
const auto i = static_cast<index_type>(index);
return (start() + i) % capacity();
}
[[nodiscard]] inline constexpr auto
adjusted_index(concepts::UnsignedIntegral auto index,
concepts::UnsignedIntegral auto start,
concepts::UnsignedIntegral auto capacity) const noexcept -> index_type {
const auto i = static_cast<index_type>(index);
const auto start_ = static_cast<index_type>(start);
const auto capacity_ = static_cast<index_type>(capacity);
return (start_ + i) % (capacity_);
}
[[nodiscard]] inline constexpr auto back() const noexcept -> index_type {
const auto indices = m_indices.load();
const auto capacity_ = m_capacity.load();
return adjusted_index(size(start(indices), write(indices), capacity_) - 1,
start(indices),
capacity_);
}
inline constexpr auto increment_indices() noexcept -> void {
auto indices = m_indices.load();
const auto capacity_ = m_capacity.load();
if(start(indices) == ((write(indices) + 1) % capacity_)) [[likely]] { // NOLINT
while(!m_indices.compare_exchange_weak(
indices,
merge_indices((start(indices) + 1) % capacity_,
(write(indices) + 1) % capacity_)))
{ }
}
else {
while(!(m_indices.compare_exchange_weak(
indices,
merge_indices(start(indices), (write(indices) + 1) % capacity_))))
{ }
}
}
inline constexpr auto increment_start() noexcept -> void {
auto indices = m_indices.load();
const auto capacity_ = m_capacity.load();
if(start(indices) != (write(indices))) {
while(!(m_indices.compare_exchange_weak(
indices,
merge_indices((start(indices) + 1) % capacity_, write(indices)))))
{ }
}
}
inline constexpr auto decrement_write() noexcept -> void {
auto indices = m_indices.load();
if(write(indices) == 0U) {
const auto capacity_ = m_capacity.load();
while(!m_indices.compare_exchange_weak(
indices,
merge_indices(start(indices), capacity_ - 1))) {
}
}
else {
while(!m_indices.compare_exchange_weak(
indices,
merge_indices(start(indices), write(indices) - 1))) {
}
}
}
inline constexpr auto
decrement_write_n(concepts::UnsignedIntegral auto n) noexcept -> void {
auto indices = m_indices.load();
const auto capacity_ = m_capacity.load();
auto amount_to_decrement = static_cast<index_type>(n);
if(amount_to_decrement > write(indices)) {
amount_to_decrement -= write(indices);
while(!m_indices.compare_exchange_weak(
indices,
merge_indices(start(indices), (capacity_ - 1) - amount_to_decrement)))
{ }
}
else {
while(!m_indices.compare_exchange_weak(
indices,
merge_indices(start(indices), write(indices) - amount_to_decrement)))
{ }
}
}
inline constexpr auto
set_write(concepts::UnsignedIntegral auto index) noexcept -> void {
const auto index_ = static_cast<index_type>(index);
auto indices = m_indices.load();
while(!m_indices.compare_exchange_weak(indices,
merge_indices(start(indices), index_))) {
}
}
constexpr auto operator=(const State& state) noexcept -> State& {
if(&state == this) {
return *this;
}
m_indices.store(state.m_indices);
m_capacity.store(state.m_capacity);
return *this;
}
constexpr auto operator=(State&& state) noexcept -> State& {
m_indices.store(state.m_indices);
m_capacity.store(state.m_capacity);
return *this;
}
private:
static constexpr u32 START_SHIFT = 32_u32;
static constexpr merged_type MASK = 0x0000'0000'FFFF'FFFF_u32;
atomic_merged_type m_indices = 0_usize;
atomic_index_type m_capacity = DEFAULT_CAPACITY_INTERNAL;
[[nodiscard]] inline static constexpr auto
merge_indices(index_type start, index_type write) noexcept -> merged_type {
return (static_cast<merged_type>(start) << START_SHIFT) | write;
}
[[nodiscard]] inline static constexpr auto
start(merged_type indices) noexcept -> index_type {
return static_cast<index_type>((indices >> START_SHIFT) & MASK);
}
[[nodiscard]] inline static constexpr auto
write(merged_type indices) noexcept -> index_type {
return static_cast<index_type>(indices & MASK);
}
};
Allocator<Element> m_allocator = Allocator<Element>();
unique_pointer m_buffer = allocate_unique<Element[]>(m_allocator, // NOLINT
DEFAULT_CAPACITY_INTERNAL,
m_allocator);
State m_state = State();
/// @brief Inserts the given element at the position indicated
/// by the `external_index`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param external_index - The user-facing index into the `RingBuffer` to insert the
/// element at
/// @param elem - The element to store in the `RingBuffer`
inline constexpr auto
insert_internal(index_type external_index, const T& elem) noexcept -> void {
const auto [start, write] = m_state.indices();
const auto capacity_ = m_state.capacity();
auto index = m_state.adjusted_index(external_index, start, capacity_);
if(index == write) {
emplace_back(elem);
}
else {
const auto size_ = m_state.size(start, write, capacity_);
auto num_to_move = size_ - external_index;
auto j = num_to_move - 1;
if(size_ == capacity_ - 1) [[likely]] { // NOLINT
num_to_move--;
j--;
index++;
}
for(auto i = 0_u32; i < num_to_move; ++i, --j) {
m_buffer[m_state.adjusted_index(size_ - i, start, capacity_)] = std::move(
m_buffer[m_state.adjusted_index(external_index + j, start, capacity_)]);
}
m_buffer[index] = Element(m_allocator, elem);
m_state.increment_indices();
}
}
/// @brief Inserts the given element at the position indicated
/// by the `external_index`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param external_index - The user-facing index into the `RingBuffer` to insert the
/// element at
/// @param elem - The element to store in the `RingBuffer`
inline constexpr auto
insert_internal(index_type external_index, T&& elem) noexcept -> void {
const auto [start, write] = m_state.indices();
const auto capacity_ = m_state.capacity();
auto index = m_state.adjusted_index(external_index, start, capacity_);
if(index == write) {
emplace_back(std::forward<T>(elem));
}
else {
const auto size_ = m_state.size(start, write, capacity_);
auto num_to_move = size_ - external_index;
auto j = num_to_move - 1;
if(size_ == capacity_ - 1) [[likely]] { // NOLINT
num_to_move--;
j--;
index++;
}
for(auto i = 0_u32; i < num_to_move; ++i, --j) {
m_buffer[m_state.adjusted_index(size_ - i, start, capacity_)] = std::move(
m_buffer[m_state.adjusted_index(external_index + j, start, capacity_)]);
}
m_buffer[index] = Element(m_allocator, std::forward<T>(elem));
m_state.increment_indices();
}
}
/// @brief Constructs the given element at the insertion position indicated
/// by the `external_index`
/// @note if `size() == capacity()` this drops the last element out of the `RingBuffer`
///
/// @param external_index - The user-facing index into the `RingBuffer` to insert the
/// element at
/// @param args - The arguments to the constructor for
/// the element to store in the `RingBuffer`
template<typename... Args>
requires concepts::ConstructibleFrom<T, Args...>
inline constexpr auto
insert_emplace_internal(index_type external_index, Args&&... args) noexcept -> Element {
const auto [start, write] = m_state.indices();
const auto capacity_ = m_state.capacity();
auto index = m_state.adjusted_index(external_index, start, capacity_);
if(index == write) {
return emplace_back(std::forward<Args>(args)...);
}
else {
const auto size_ = m_state.size(start, write, capacity_);
auto num_to_move = size_ - external_index;
auto j = num_to_move - 1;
if(size_ == capacity_ - 1) [[likely]] { // NOLINT
num_to_move--;
j--;
index++;
}
for(auto i = 0_u32; i < num_to_move; ++i, --j) {
m_buffer[m_state.adjusted_index(size_ - i, start, capacity_)] = std::move(
m_buffer[m_state.adjusted_index(external_index + j, start, capacity_)]);
}
allocator_traits::template construct<Element>(
m_allocator,
&m_buffer[index],
std::allocate_shared<T, Allocator<Element>>(m_allocator,
std::forward<Args>(args)...));
m_state.increment_indices();
return m_buffer[index];
}
}
/// @brief Erases the element at the given index, returning an `Iterator` to the element
/// after the removed one
///
/// @param external_index - The index to the element to remove. This should be a
/// `RingBuffer` index: IE, not an internal one into the `T` array
///
/// @return `Iterator` pointing to the element after the one removed
[[nodiscard]] inline constexpr auto
erase_internal(index_type external_index) noexcept -> Iterator {
const auto [start, write] = m_state.indices();
const auto capacity_ = m_state.capacity();
const auto index = m_state.adjusted_index(external_index, start, capacity_);
if(index == write) [[unlikely]] { // NOLINT
return end();
}
else {
// const auto size_ = size(start, write);
const auto size_ = m_state.size(start, write, capacity_);
const auto num_to_move = (size_ - 1) - external_index;
const auto pos_to_move = external_index + 1;
const auto pos_to_replace = external_index;
for(auto i = 0_u32; i < num_to_move; ++i) {
m_buffer[m_state.adjusted_index(pos_to_replace + i, start, capacity_)]
= m_buffer[m_state.adjusted_index(pos_to_move + i, start, capacity_)];
}
m_state.decrement_write();
return begin() + external_index;
}
}
/// @brief Erases the range of elements in [`first`, `last`)
/// Returns an `Iterator` to the element after the last one erased
///
/// @param first - The first index in the range to erase. This should be a `RingBuffer`
/// index: IE, not an internal one into the `T` array
/// @param last - The last index` in the range to erase. This should be a `RingBuffer`
/// index: IE, not an internal one into the `T` array
///
/// @return `Iterator` pointing to the element after the last one erased
[[nodiscard]] inline constexpr auto
erase_internal(index_type first, index_type last) noexcept -> Iterator { // NOLINT
const auto [start, write] = m_state.indices();
const auto capacity_ = m_state.capacity();
const auto size_ = m_state.size(start, write, capacity_);
const auto last_internal = m_state.adjusted_index(last, start, capacity_);
const auto num_to_remove = (last - first);
if(last_internal == write) {
if(write > start) {
m_state.decrement_write_n(num_to_remove);
}
else if(write < start) {
auto num_after_start_index
= (write > num_to_remove) ? write - num_to_remove : 0_u32;
auto num_before_start_index = num_to_remove - num_after_start_index;
if(num_after_start_index > 0) {
num_after_start_index--;
m_state.set_write(m_state.loop_index() - num_after_start_index);
}
else {
m_state.decrement_write_n(num_before_start_index);
}
}
return end();
}
else {
const auto num_to_move = size_ - last;
const auto pos_to_move = last;
const auto pos_to_replace = first;
for(auto i = 0_u32; i < num_to_move; ++i) {
m_buffer[m_state.adjusted_index(pos_to_replace + i, start, capacity_)]
= m_buffer[m_state.adjusted_index(pos_to_move + i, start, capacity_)];
}
m_state.decrement_write_n(num_to_remove);
return begin() + first;
}
}
};
IGNORE_PADDING_STOP
} // namespace hyperion
| {
"alphanum_fraction": 0.6801577328,
"avg_line_length": 35.6401544402,
"ext": "h",
"hexsha": "8efba2d4a150fcb026a74b07ae958184857a9988",
"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/RingBuffer.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/RingBuffer.h",
"max_line_length": 100,
"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/RingBuffer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 23261,
"size": 92308
} |
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_multifit.h>
double w[] = { 52.21, 53.12, 54.48, 55.84, 57.20,
58.57, 59.93, 61.29, 63.11, 64.47,
66.28, 68.10, 69.92, 72.19, 74.46 };
double h[] = { 1.47, 1.50, 1.52, 1.55, 1.57,
1.60, 1.63, 1.65, 1.68, 1.70,
1.73, 1.75, 1.78, 1.80, 1.83 };
int main()
{
int n = sizeof(h)/sizeof(double);
gsl_matrix *X = gsl_matrix_calloc(n, 3);
gsl_vector *Y = gsl_vector_alloc(n);
gsl_vector *beta = gsl_vector_alloc(3);
for (int i = 0; i < n; i++) {
gsl_vector_set(Y, i, w[i]);
gsl_matrix_set(X, i, 0, 1);
gsl_matrix_set(X, i, 1, h[i]);
gsl_matrix_set(X, i, 2, h[i] * h[i]);
}
double chisq;
gsl_matrix *cov = gsl_matrix_alloc(3, 3);
gsl_multifit_linear_workspace * wspc = gsl_multifit_linear_alloc(n, 3);
gsl_multifit_linear(X, Y, beta, cov, &chisq, wspc);
printf("Beta:");
for (int i = 0; i < 3; i++)
printf(" %g", gsl_vector_get(beta, i));
printf("\n");
gsl_matrix_free(X);
gsl_matrix_free(cov);
gsl_vector_free(Y);
gsl_vector_free(beta);
gsl_multifit_linear_free(wspc);
}
| {
"alphanum_fraction": 0.6298997265,
"avg_line_length": 24.3777777778,
"ext": "c",
"hexsha": "7e35f5e206e0965dfc454a2c6a3d1ef77241c92b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z",
"max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ethansaxenian/RosettaDecode",
"max_forks_repo_path": "lang/C/multiple-regression.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7",
"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": "ethansaxenian/RosettaDecode",
"max_issues_repo_path": "lang/C/multiple-regression.c",
"max_line_length": 72,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ethansaxenian/RosettaDecode",
"max_stars_repo_path": "lang/C/multiple-regression.c",
"max_stars_repo_stars_event_max_datetime": "2017-06-26T18:52:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-10T14:21:53.000Z",
"num_tokens": 466,
"size": 1097
} |
#include <math.h>
#include <stdlib.h>
#if !defined(__APPLE__)
#include <malloc.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <fftw3.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include "../cosmolike_core/theory/basics.c"
#include "../cosmolike_core/theory/structs.c"
#include "../cosmolike_core/theory/parameters.c"
#include "../cosmolike_core/emu17/P_cb/emu.c"
#include "../cosmolike_core/theory/recompute.c"
#include "../cosmolike_core/theory/cosmo3D.c"
#include "../cosmolike_core/theory/redshift_spline.c"
#include "../cosmolike_core/theory/halo.c"
#include "../cosmolike_core/theory/HOD.c"
#include "../cosmolike_core/theory/pt.c"
#include "../cosmolike_core/theory/cosmo2D_fourier.c"
#include "../cosmolike_core/theory/IA.c"
#include "../cosmolike_core/theory/cluster.c"
#include "../cosmolike_core/theory/BAO.c"
#include "../cosmolike_core/theory/external_prior.c"
#include "../cosmolike_core/theory/covariances_3D.c"
#include "../cosmolike_core/theory/covariances_fourier.c"
#include "../cosmolike_core/theory/covariances_cluster.c"
#include "init_emu.c"
void run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start);
void run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start);
void run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start);
void run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster);
void run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);
void run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);
void run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);
void run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);
void run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);
void run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);
void run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);
void run_cov_clustering_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);
void run_cov_clustering_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);
void run_cov_clustering(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);
void run_cov_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);
void run_cov_shear_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);
void run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start)
{
int nN1, nN2,i,j;
double cov;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);
i += Cluster.N200_Nbin*nzc1+nN1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);
j += Cluster.N200_Nbin*nzc2+nN2;
cov =cov_N_N(nzc1,nN1, nzc2, nN2);
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,0.0,0.0, nzc1, nN1, nzc2, nN2,cov,0.0);
}
}
fclose(F1);
}
void run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start)
{
int nN1, nN2, nl1, nzc1, nzs1,i,j;
double cov;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
nzc1 = ZC(N1);
nzs1 = ZSC(N1);
for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){
for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);
j += Cluster.N200_Nbin*nzc2+nN2;
cov =cov_cgl_N(ell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2);
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell_Cluster[nl1], 0., nzc1, nzs1, nzc2, nN2,cov,0.);
}
}
}
fclose(F1);
}
void run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start)
{
int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j;
double c_g, c_ng;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
nzc1 = ZC(N1);
nzs1 = ZSC(N1);
nzc2 = ZC(N2);
nzs2 = ZSC(N2);
for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){
for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;
c_g = 0;
c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2);
if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nzs1, nzc2, nzs2,c_g, c_ng);
}
}
}
}
fclose(F1);
}
void run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster)
{
int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j, N1,N2;
double c_g, c_ng;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s",PATH,OUTFILE);
F1 =fopen(filename,"w");
for (N1 = 0; N1 < tomo.cgl_Npowerspectra; N1 ++){
for (N2 = 0; N2 < tomo.cgl_Npowerspectra; N2 ++){
nzc1 = ZC(N1);
nzs1 = ZSC(N1);
nzc2 = ZC(N2);
nzs2 = ZSC(N2);
for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){
for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;
c_g = 0;
c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2);
if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);}
fprintf(F1,"%d %d %e %e %d %d %d %d %d %d %e %e\n",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nN1,nzs1, nzc2, nN2,nzs2,c_g, c_ng);
}
}
}
}
}
}
fclose(F1);
}
void run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start)
{
int nz1,nz2, nN2, nl1, nzc1, i,j;
double cov;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
nz1 = Z1(N1);
nz2 = Z2(N1);
for( nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
cov = 0.;
i = like.Ncl*N1+nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);
j += Cluster.N200_Nbin*nzc2+nN2;
if (ell[nl1] < like.lmax_shear){cov =cov_shear_N(ell[nl1],nz1,nz2, nzc2, nN2);}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell[nl1], 0., nz1, nz2, nzc2, nN2,cov,0.);
}
}
fclose(F1);
}
void run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)
{
int nN1, nN2, nzs1, nzs2,nl2, nzc2, nzs3,i,j;
double c_g, c_ng;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
nzs1 = Z1(N1);
nzs2 = Z2(N1);
nzc2 = ZC(N2);
nzs3 = ZSC(N2);
for(nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){
i = like.Ncl*N1+nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;
c_g = 0.;
c_ng = 0.;
if (ell[nl1] < like.lmax_shear){
c_ng = cov_NG_shear_cgl(ell[nl1],ell_Cluster[nl2],nzs1, nzs2, nzc2, nN2,nzs3);
if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.001){
c_g =cov_G_shear_cgl(ell[nl1],dell_Cluster[nl2],nzs1,nzs2, nzc2, nN2,nzs3);
}
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], nzs1, nzs2, nzc2, nzs3,c_g, c_ng);
}
}
}
fclose(F1);
}
void run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start)
{
int zl,zs, nN2, nl1, nzc1, i,j;
double cov,weight;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
zl = ZL(N1);
zs = ZS(N1);
for( nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);
j += Cluster.N200_Nbin*nzc2+nN2;
cov = 0.;
weight = test_kmax(ell[nl1],zl);
if (weight){
cov =cov_ggl_N(ell[nl1],zl,zs, nzc2, nN2);
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell[nl1], 0., zl, zs, nzc2, nN2,cov,0.);
}
}
fclose(F1);
}
void run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)
{
int nN2, zl, zs, nzs1, nl2, nzc2, nzs3,i,j;
double c_g, c_ng,weight;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
zl = ZL(N1);
zs = ZS(N1);
nzc2 = ZC(N2);
nzs3 = ZSC(N2);
for(nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;
c_g = 0; c_ng = 0.;
weight = test_kmax(ell[nl1],zl);
if (weight){
c_ng = cov_NG_ggl_cgl(ell[nl1],ell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3);
if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){c_g =cov_G_ggl_cgl(ell[nl1],dell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3);}
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], zl, zs, nzc2, nzs3,c_g, c_ng);
}
}
}
fclose(F1);
}
void run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell,int N1, int nzc2, int start)
{
int zl,zs, nN2, nl1, nzc1, i,j;
double cov,weight;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
for( nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);
j += Cluster.N200_Nbin*nzc2+nN2;
cov = 0.;
weight = test_kmax(ell[nl1],N1);
if (weight){
cov =cov_cl_N(ell[nl1],N1,N1,nzc2,nN2);
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell[nl1], 0., N1, N1, nzc2, nN2,cov,0.);
}
}
fclose(F1);
}
void run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)
{
int nN2,nzc2, nzs3,i,j,nl2;
double c_g, c_ng,weight;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
nzc2 = ZC(N2);
nzs3 = ZSC(N2);
for(nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){
for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){
i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1;
j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;
j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;
c_g = 0; c_ng = 0.;
weight = test_kmax(ell[nl1],N1);
if (weight){
c_ng = cov_NG_cl_cgl(ell[nl1],ell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3);
if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){
c_g =cov_G_cl_cgl(ell[nl1],dell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3);
}
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng);
//printf("%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng);
}
}
}
fclose(F1);
}
void run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)
{
int zl,zs,z3,z4,nl1,nl2,weight;
double c_ng, c_g;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
zl = ZL(n1); zs = ZS(n1);
printf("\nN_ggl = %d (%d, %d)\n", n1,zl,zs);
z3 = Z1(n2); z4 = Z2(n2);
printf("N_shear = %d (%d, %d)\n", n2,z3,z4);
for (nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nl2 = 0; nl2 <like.Ncl; nl2 ++){
c_ng = 0.; c_g = 0.;
weight = test_kmax(ell[nl1],zl);
if (weight && ell[nl2] < like.lmax_shear){
if (test_zoverlap(zl,z3)*test_zoverlap(zl,z4)){
c_ng = cov_NG_gl_shear_tomo(ell[nl1],ell[nl2],zl,zs,z3,z4);
}
if (nl1 == nl2){
c_g = cov_G_gl_shear_tomo(ell[nl1],dell[nl1],zl,zs,z3,z4);
}
}
fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],zl,zs,z3,z4,c_g,c_ng);
}
}
fclose(F1);
}
void run_cov_clustering_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)
{
int z1,z2,z3,z4,nl1,nl2,weight;
double c_ng, c_g;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
z1 = n1; z2 = n1;
printf("\nN_cl = %d \n", n1);
z3 = Z1(n2); z4 = Z2(n2);
printf("N_shear = %d (%d, %d)\n", n2,z3,z4);
for (nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nl2 = 0; nl2 <like.Ncl; nl2 ++){
c_ng = 0.; c_g = 0.;
weight = test_kmax(ell[nl1],z1);
if (weight && ell[nl2] < like.lmax_shear){
if (test_zoverlap(z1,z3)*test_zoverlap(z1,z4)){
c_ng = cov_NG_cl_shear_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4);
}
if (nl1 == nl2){
c_g = cov_G_cl_shear_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4);
}
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);
}
}
fclose(F1);
}
void run_cov_clustering_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)
{
int z1,z2,zl,zs,nl1,nl2,weight;
double c_ng, c_g;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
z1 = n1; z2 = n1;
printf("\nN_cl_1 = %d \n", n1);
zl = ZL(n2); zs = ZS(n2);
printf("N_tomo_2 = %d (%d, %d)\n", n2,zl,zs);
for (nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nl2 = 0; nl2 < like.Ncl; nl2 ++){
c_ng = 0.; c_g = 0.;
if (z1 == zl){
weight = test_kmax(ell[nl1],z1)*test_kmax(ell[nl2],zl);
if (weight){
c_ng = cov_NG_cl_gl_tomo(ell[nl1],ell[nl2],z1,z2,zl,zs);
if (nl1 == nl2){
c_g = cov_G_cl_gl_tomo(ell[nl1],dell[nl1],z1,z2,zl,zs);
}
}
}
fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1,like.Ncl*(tomo.shear_Npowerspectra+n2)+nl2, ell[nl1],ell[nl2],z1,z2,zl,zs,c_g,c_ng);
}
}
fclose(F1);
}
void run_cov_clustering(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)
{
int z1,z2,z3,z4,nl1,nl2,weight;
double c_ng, c_g;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
z1 = n1; z2 = n1;
printf("\nN_cl_1 = %d \n", n1);
z3 = n2; z4 = n2;
printf("N_cl_2 = %d\n", n2);
for (nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nl2 = 0; nl2 < like.Ncl; nl2 ++){
c_ng = 0.; c_g = 0.;
if (z1 == z3){
weight = test_kmax(ell[nl1],z1)*test_kmax(ell[nl2],z3);
if (weight) {
c_ng = cov_NG_cl_cl_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4);
}
if (nl1 == nl2){
c_g = cov_G_cl_cl_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4);
}
}
fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1,like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);
}
}
fclose(F1);
}
void run_cov_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)
{
int zl1,zl2,zs1,zs2,nl1,nl2, weight;
double c_ng, c_g;
double fsky = survey.area/41253.0;
FILE *F1;
char filename[300];
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
zl1 = ZL(n1); zs1 = ZS(n1);
printf("\nN_tomo_1 = %d (%d, %d)\n", n1,zl1,zs1);
zl2 = ZL(n2); zs2 = ZS(n2);
printf("N_tomo_2 = %d (%d, %d)\n", n2,zl2,zs2);
for (nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nl2 = 0; nl2 < like.Ncl; nl2 ++){
c_ng = 0.; c_g = 0.;
weight = test_kmax(ell[nl1],zl1)*test_kmax(ell[nl2],zl2);
if (weight && zl1 == zl2) {
c_ng = cov_NG_gl_gl_tomo(ell[nl1],ell[nl2],zl1,zs1,zl2,zs2);
}
if (nl1 == nl2){
c_g = cov_G_gl_gl_tomo(ell[nl1],dell[nl1],zl1,zs1,zl2,zs2);
}
if (weight ==0 && n2 != n1){
c_g = 0;
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1,like.Ncl*(tomo.shear_Npowerspectra+n2)+nl2, ell[nl1],ell[nl2],zl1,zs1,zl2,zs2,c_g,c_ng);
}
}
fclose(F1);
}
void run_cov_shear_shear(char *OUTFILE, char *PATH, double *ell, double *dell,int n1, int n2,int start)
{
int z1,z2,z3,z4,nl1,nl2,weight;
double c_ng, c_g;
FILE *F1;
char filename[300];
z1 = Z1(n1); z2 = Z2(n1);
printf("N_shear = %d\n", n1);
z3 = Z1(n2); z4 = Z2(n2);
printf("N_shear = %d (%d, %d)\n",n2,z3,z4);
sprintf(filename,"%s%s_%d",PATH,OUTFILE,start);
F1 =fopen(filename,"w");
for (nl1 = 0; nl1 < like.Ncl; nl1 ++){
for (nl2 = 0; nl2 < like.Ncl; nl2 ++){
c_ng = 0.; c_g = 0.;
if (ell[nl1] < like.lmax_shear && ell[nl2] < like.lmax_shear){
c_ng = cov_NG_shear_shear_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4);
}
if (nl1 == nl2){
c_g = cov_G_shear_shear_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4);
if (ell[nl1] > like.lmax_shear && n1!=n2){c_g = 0.;}
}
fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",like.Ncl*n1+nl1,like.Ncl*(n2)+nl2,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);
//printf("%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*n1+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);
}
}
fclose(F1);
}
int main(int argc, char** argv)
{
int i,l,m,n,o,s,p,nl1,t,k;
char OUTFILE[400],filename[400],arg1[400],arg2[400];
int N_scenarios=36;
double area_table[36]={7623.22,14786.3,9931.47,8585.43,17681.8,15126.9,9747.99,8335.08,9533.42,18331.3,12867.8,17418.9,19783.1,12538.8,15260.0,16540.7,19636.8,11112.7,10385.5,16140.2,18920.1,17976.2,11352.0,9214.77,16910.7,11995.6,16199.8,14395.1,8133.86,13510.5,19122.3,15684.5,12014.8,14059.7,10919.3,13212.7};
double nsource_table[36]={13.991,33.3975,17.069,28.4875,35.3643,10.3802,11.1105,29.5904,31.4608,15.7463,13.3066,9.07218,9.58719,16.3234,25.8327,10.7415,38.0412,32.8821,19.8893,27.0369,15.1711,14.2418,19.1851,26.926,22.0012,12.6553,18.6304,11.9787,36.8728,22.5265,17.4381,12.3424,10.0095,23.5979,20.8771,24.8956};
double nlens_table[36]={22.9726 ,61.5948 ,28.7809 ,51.4354 ,65.7226 ,16.3777 ,17.6899 ,53.6984 ,57.562 ,26.266 ,21.703 ,14.0587 ,14.9667 ,27.36 ,46.0364 ,17.0253 ,71.39 ,60.5184 ,34.2283 ,48.4767 ,25.1812 ,23.44 ,32.8578 ,48.2513 ,38.3766 ,20.5029 ,31.783 ,19.2647 ,68.9094 ,39.4168 ,29.4874 ,19.9292 ,15.7162 ,41.5487 ,36.1616 ,44.148};
char source_zfile[36][400]={"wl_redshift_model0_WLz01.880307e-01_WLalpha8.485694e-01.txt", "wl_redshift_model1_WLz01.731166e-01_WLalpha7.662434e-01.txt", "wl_redshift_model2_WLz01.846221e-01_WLalpha8.297540e-01.txt", "wl_redshift_model3_WLz01.758423e-01_WLalpha7.812893e-01.txt", "wl_redshift_model4_WLz01.721357e-01_WLalpha7.608290e-01.txt", "wl_redshift_model5_WLz01.931476e-01_WLalpha8.768147e-01.txt", "wl_redshift_model6_WLz01.919821e-01_WLalpha8.703814e-01.txt", "wl_redshift_model7_WLz01.751912e-01_WLalpha7.776952e-01.txt", "wl_redshift_model8_WLz01.741405e-01_WLalpha7.718958e-01.txt", "wl_redshift_model9_WLz01.860048e-01_WLalpha8.373865e-01.txt", "wl_redshift_model10_WLz01.888904e-01_WLalpha8.533151e-01.txt", "wl_redshift_model11_WLz01.954564e-01_WLalpha8.895592e-01.txt", "wl_redshift_model12_WLz01.945099e-01_WLalpha8.843347e-01.txt", "wl_redshift_model13_WLz01.853877e-01_WLalpha8.339802e-01.txt", "wl_redshift_model14_WLz01.775192e-01_WLalpha7.905458e-01.txt", "wl_redshift_model15_WLz01.925611e-01_WLalpha8.735775e-01.txt", "wl_redshift_model16_WLz01.708849e-01_WLalpha7.539247e-01.txt", "wl_redshift_model17_WLz01.733832e-01_WLalpha7.677150e-01.txt", "wl_redshift_model18_WLz01.820009e-01_WLalpha8.152851e-01.txt", "wl_redshift_model19_WLz01.767381e-01_WLalpha7.862345e-01.txt", "wl_redshift_model20_WLz01.866426e-01_WLalpha8.409073e-01.txt", "wl_redshift_model21_WLz01.877261e-01_WLalpha8.468882e-01.txt", "wl_redshift_model22_WLz01.826188e-01_WLalpha8.186960e-01.txt", "wl_redshift_model23_WLz01.768086e-01_WLalpha7.866234e-01.txt", "wl_redshift_model24_WLz01.802711e-01_WLalpha8.057362e-01.txt", "wl_redshift_model25_WLz01.897506e-01_WLalpha8.580632e-01.txt", "wl_redshift_model26_WLz01.831217e-01_WLalpha8.214720e-01.txt", "wl_redshift_model27_WLz01.906926e-01_WLalpha8.632630e-01.txt", "wl_redshift_model28_WLz01.714197e-01_WLalpha7.568766e-01.txt", "wl_redshift_model29_WLz01.798667e-01_WLalpha8.035040e-01.txt", "wl_redshift_model30_WLz01.842554e-01_WLalpha8.277299e-01.txt", "wl_redshift_model31_WLz01.901797e-01_WLalpha8.604322e-01.txt", "wl_redshift_model32_WLz01.937710e-01_WLalpha8.802561e-01.txt", "wl_redshift_model33_WLz01.790701e-01_WLalpha7.991072e-01.txt", "wl_redshift_model34_WLz01.811701e-01_WLalpha8.106987e-01.txt", "wl_redshift_model35_WLz01.781525e-01_WLalpha7.940419e-01.txt"};
char lens_zfile[36][400]={"LSS_redshift_model0_LSSz02.629496e-01_LSSalpha9.285983e-01.txt","LSS_redshift_model1_LSSz02.852923e-01_LSSalpha8.985943e-01.txt","LSS_redshift_model2_LSSz02.664822e-01_LSSalpha9.186036e-01.txt","LSS_redshift_model3_LSSz02.798758e-01_LSSalpha9.014201e-01.txt","LSS_redshift_model4_LSSz02.873873e-01_LSSalpha8.978683e-01.txt","LSS_redshift_model5_LSSz02.593970e-01_LSSalpha9.470921e-01.txt","LSS_redshift_model6_LSSz02.600213e-01_LSSalpha9.425114e-01.txt","LSS_redshift_model7_LSSz02.811155e-01_LSSalpha9.006370e-01.txt","LSS_redshift_model8_LSSz02.831875e-01_LSSalpha8.995165e-01.txt","LSS_redshift_model9_LSSz02.649368e-01_LSSalpha9.224338e-01.txt","LSS_redshift_model10_LSSz02.622058e-01_LSSalpha9.314128e-01.txt","LSS_redshift_model11_LSSz02.584820e-01_LSSalpha9.568082e-01.txt","LSS_redshift_model12_LSSz02.588053e-01_LSSalpha9.527220e-01.txt","LSS_redshift_model13_LSSz02.656075e-01_LSSalpha9.206866e-01.txt","LSS_redshift_model14_LSSz02.768397e-01_LSSalpha9.037492e-01.txt","LSS_redshift_model15_LSSz02.596975e-01_LSSalpha9.447600e-01.txt","LSS_redshift_model16_LSSz02.901709e-01_LSSalpha8.971658e-01.txt","LSS_redshift_model17_LSSz02.847362e-01_LSSalpha8.988183e-01.txt","LSS_redshift_model18_LSSz02.698330e-01_LSSalpha9.121821e-01.txt","LSS_redshift_model19_LSSz02.782257e-01_LSSalpha9.026084e-01.txt","LSS_redshift_model20_LSSz02.642756e-01_LSSalpha9.243038e-01.txt","LSS_redshift_model21_LSSz02.632273e-01_LSSalpha9.276296e-01.txt","LSS_redshift_model22_LSSz02.689934e-01_LSSalpha9.135968e-01.txt","LSS_redshift_model23_LSSz02.780987e-01_LSSalpha9.027073e-01.txt","LSS_redshift_model24_LSSz02.723464e-01_LSSalpha9.085463e-01.txt","LSS_redshift_model25_LSSz02.615210e-01_LSSalpha9.343470e-01.txt","LSS_redshift_model26_LSSz02.683327e-01_LSSalpha9.147934e-01.txt","LSS_redshift_model27_LSSz02.608392e-01_LSSalpha9.376962e-01.txt","LSS_redshift_model28_LSSz02.889655e-01_LSSalpha8.974355e-01.txt","LSS_redshift_model29_LSSz02.729686e-01_LSSalpha9.077654e-01.txt","LSS_redshift_model30_LSSz02.669178e-01_LSSalpha9.176391e-01.txt","LSS_redshift_model31_LSSz02.612016e-01_LSSalpha9.358553e-01.txt","LSS_redshift_model32_LSSz02.591077e-01_LSSalpha9.496317e-01.txt","LSS_redshift_model33_LSSz02.742326e-01_LSSalpha9.063038e-01.txt","LSS_redshift_model34_LSSz02.710103e-01_LSSalpha9.103760e-01.txt","LSS_redshift_model35_LSSz02.757517e-01_LSSalpha9.047459e-01.txt"};
char survey_designation[1][200]={"LSST"};
char tomo_binning_source[1][200]={"source_std"};
char tomo_binning_lens[1][200]={"LSST_gold"};
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// use this remapping only if files fail !!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// int fail[5]={1134, 259, 497, 623, 718};
// hit=fail[hit-1];
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
int hit=atoi(argv[1]);
Ntable.N_a=20;
k=1;
for(t=0;t<1;t++){
//RUN MODE setup
init_cosmo_runmode("emu");
init_binning_fourier(15,20.0,3000.0,3000.0,21.0,10,10);
init_survey(survey_designation[0],nsource_table[t],nlens_table[t],area_table[t]);
sprintf(arg1,"zdistris/%s",source_zfile[t]);
sprintf(arg2,"zdistris/%s",lens_zfile[t]);
init_galaxies(arg1,arg2,"gaussian","gaussian",tomo_binning_source[0],tomo_binning_lens[0]);
init_IA("none", "GAMA");
init_probes("3x2pt");
//set l-bins for shear, ggl, clustering, clusterWL
double logdl=(log(like.lmax)-log(like.lmin))/like.Ncl;
double *ell, *dell, *ell_Cluster, *dell_Cluster;
ell=create_double_vector(0,like.Ncl-1);
dell=create_double_vector(0,like.Ncl-1);
ell_Cluster=create_double_vector(0,Cluster.lbin-1);
dell_Cluster=create_double_vector(0,Cluster.lbin-1);
int j=0;
for(i=0;i<like.Ncl;i++){
ell[i]=exp(log(like.lmin)+(i+0.5)*logdl);
dell[i]=exp(log(like.lmin)+(i+1)*logdl)-exp(log(like.lmin)+(i*logdl));
if(ell[i]<like.lmax_shear) printf("%le\n",ell[i]);
if(ell[i]>like.lmax_shear){
ell_Cluster[j]=ell[i];
dell_Cluster[j]=dell[i];
printf("%le %le\n",ell[i],ell_Cluster[j]);
j++;
}
}
printf("----------------------------------\n");
survey.area=area_table[t];
survey.n_gal=nsource_table[t];
survey.n_lens=nlens_table[t];
sprintf(survey.name,"%s_area%le_ng%le_nl%le",survey_designation[0],survey.area,survey.n_gal,survey.n_lens);
printf("area: %le n_source: %le n_lens: %le\n",survey.area,survey.n_gal,survey.n_lens);
// sprintf(covparams.outdir,"/home/u17/timeifler/covparallel/");
sprintf(covparams.outdir,"/aurora_nobackup/cosmos/teifler/covparallel/");
printf("----------------------------------\n");
sprintf(OUTFILE,"%s_ssss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Npowerspectra; l++){
for (m=l;m<tomo.shear_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
if (fopen(filename, "r") != NULL){exit(1);}
else {
run_cov_shear_shear(OUTFILE,covparams.outdir,ell,dell,l,m,k);
}
}
k=k+1;
//printf("%d\n",k);
}
}
sprintf(OUTFILE,"%s_lsls_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.ggl_Npowerspectra; l++){
for (m=l;m<tomo.ggl_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
if (fopen(filename, "r") != NULL){exit(1);}
else {
run_cov_ggl(OUTFILE,covparams.outdir,ell,dell,l,m,k);
}
}
//printf("%d\n",k);
k=k+1;
}
}
sprintf(OUTFILE,"%s_llll_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){ //auto bins only for now!
for (m=l;m<tomo.clustering_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
if (fopen(filename, "r") != NULL){exit(1);}
else {
run_cov_clustering(OUTFILE,covparams.outdir,ell,dell,l,m,k);
}
}
k=k+1;
//printf("%d %d %d\n",l,m,k);
}
}
sprintf(OUTFILE,"%s_llss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
if (fopen(filename, "r") != NULL){exit(1);}
else {
run_cov_clustering_shear(OUTFILE,covparams.outdir,ell,dell,l,m,k);
}
}
k=k+1;
//printf("%d\n",k);
}
}
sprintf(OUTFILE,"%s_llls_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=0;m<tomo.ggl_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
if (fopen(filename, "r") != NULL){exit(1);}
else {
run_cov_clustering_ggl(OUTFILE,covparams.outdir,ell,dell,l,m,k);
}
}
k=k+1;
//printf("%d\n",k);
}
}
sprintf(OUTFILE,"%s_lsss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.ggl_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
if (fopen(filename, "r") != NULL){exit(1);}
else {
run_cov_ggl_shear(OUTFILE,covparams.outdir,ell,dell,l,m,k);
}
}
k=k+1;
//printf("%d\n",k);
}
}
//******************************
//******cluster covariance******
//******************************
// sprintf(OUTFILE,"%s_nn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.cluster_Nbin; l++){
// for (m=0;m<tomo.cluster_Nbin; m++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_N_N (OUTFILE,covparams.outdir,l,m,k);
// }
// }
// k=k+1;
// //printf("%d\n",k);
// }
// }
// sprintf(OUTFILE,"%s_cscs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.cgl_Npowerspectra; l++){
// for (m=0;m<tomo.cgl_Npowerspectra; m++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_cgl_cgl (OUTFILE,covparams.outdir,ell_Cluster,dell_Cluster,l,m,k);
// }
// }
// k=k+1;
// }
// }
// sprintf(OUTFILE,"%s_csn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.cgl_Npowerspectra; l++){
// for (m=0;m<tomo.cluster_Nbin; m++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_cgl_N (OUTFILE,covparams.outdir,ell_Cluster,dell_Cluster,l,m,k);
// }
// }
// k=k+1;
// }
// }
// //shear X cluster
// sprintf(OUTFILE,"%s_ssn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.shear_Npowerspectra; l++){
// for (m=0;m<tomo.cluster_Nbin; m++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_shear_N (OUTFILE,covparams.outdir,ell,dell,l,m,k);
// }
// }
// k=k+1;
// }
// }
// sprintf(OUTFILE,"%s_sscs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.shear_Npowerspectra; l++){
// for (m=0;m<tomo.cgl_Npowerspectra; m++){
// //for(nl1 = 0; nl1 < like.Ncl; nl1 ++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_shear_cgl (OUTFILE,covparams.outdir,ell,dell,ell_Cluster,dell_Cluster,l,m,nl1,k);
// }
// }
// k=k+1;
// //}
// }
// }
// // ggl X cluster
// sprintf(OUTFILE,"%s_lsn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.ggl_Npowerspectra; l++){
// for (m=0;m<tomo.cluster_Nbin; m++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_ggl_N (OUTFILE,covparams.outdir,ell,dell,l,m,k);
// }
// }
// k=k+1;
// }
// }
// sprintf(OUTFILE,"%s_lscs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.ggl_Npowerspectra; l++){
// for (m=0;m<tomo.cgl_Npowerspectra; m++){
// //for(nl1 = 0; nl1 < like.Ncl; nl1 ++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_ggl_cgl (OUTFILE,covparams.outdir,ell,dell,ell_Cluster,dell_Cluster,l,m,nl1,k);
// }
// }
// k=k+1;
// //}
// }
// }
// // clustering X cluster
// sprintf(OUTFILE,"%s_lln_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.clustering_Npowerspectra; l++){
// for (m=0;m<tomo.cluster_Nbin; m++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_cl_N (OUTFILE,covparams.outdir,ell,dell,l,m,k);
// }
// }
// //printf("%d\n",k);
// k=k+1;
// }
// }
// sprintf(OUTFILE,"%s_llcs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin);
// for (l=0;l<tomo.clustering_Npowerspectra; l++){
// for (m=0;m<tomo.cgl_Npowerspectra; m++){
// //for(nl1 = 0; nl1 < like.Ncl; nl1 ++){
// if(k==hit){
// sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
// else {
// run_cov_cl_cgl (OUTFILE,covparams.outdir,ell,dell,ell_Cluster,dell_Cluster,l,m,nl1,k);
// }
// }
// k=k+1;
// //}
// }
// }
}
printf("number of cov blocks for parallelization: %d\n",k-1);
printf("-----------------\n");
printf("PROGRAM EXECUTED\n");
printf("-----------------\n");
return 0;
}
| {
"alphanum_fraction": 0.6240910189,
"avg_line_length": 44.3654761905,
"ext": "c",
"hexsha": "a28c089925947bc51078a7ad03c6dc12e5a75a39",
"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": "ed4d26b52ed26172eb35b3a030403c123e29eb2c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CosmoLike/LSST_emu",
"max_forks_repo_path": "compute_covariances_fourier.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "CosmoLike/LSST_emu",
"max_issues_repo_path": "compute_covariances_fourier.c",
"max_line_length": 2395,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CosmoLike/LSST_emu",
"max_stars_repo_path": "compute_covariances_fourier.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 14547,
"size": 37267
} |
#ifndef petscutils_h
#define petscutils_h
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscfe.h>
CeedMemType MemTypeP2C(PetscMemType mtype);
PetscErrorCode ProjectToUnitSphere(DM dm);
PetscErrorCode Kershaw(DM dm_orig, PetscScalar eps);
typedef PetscErrorCode (*BCFunction)(PetscInt dim, PetscReal time,
const PetscReal x[],
PetscInt num_comp_u, PetscScalar *u, void *ctx);
PetscErrorCode SetupDMByDegree(DM dm, PetscInt degree, PetscInt num_comp_u,
PetscInt topo_dim,
bool enforce_bc, BCFunction bc_func);
PetscErrorCode CreateRestrictionFromPlex(Ceed ceed, DM dm, CeedInt P,
CeedInt topo_dim, CeedInt height, DMLabel domain_label, CeedInt value,
CeedElemRestriction *elem_restr);
#endif // petscutils_h
| {
"alphanum_fraction": 0.6776390465,
"avg_line_length": 38.3043478261,
"ext": "h",
"hexsha": "a541f39a3700eba46257d0ca410865f2e8fc9ab4",
"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": "4a63c7da274c5bcaedf5323dad2ae658837a33b1",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "LeilaGhaffari/libCEED",
"max_forks_repo_path": "examples/petsc/include/petscutils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4a63c7da274c5bcaedf5323dad2ae658837a33b1",
"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": "LeilaGhaffari/libCEED",
"max_issues_repo_path": "examples/petsc/include/petscutils.h",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4a63c7da274c5bcaedf5323dad2ae658837a33b1",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "LeilaGhaffari/libCEED",
"max_stars_repo_path": "examples/petsc/include/petscutils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 219,
"size": 881
} |
/* filter/test_gaussian.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_filter.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* compute Gaussian filter by explicitely constructing window and computing weighted sum */
int
slow_gaussian(const gsl_filter_end_t etype, const double alpha, const size_t order, const gsl_vector * x,
gsl_vector * y, const size_t K)
{
const size_t n = x->size;
const size_t H = K / 2;
double *window = malloc(K * sizeof(double));
double *kernel = malloc(K * sizeof(double));
gsl_vector_view k = gsl_vector_view_array(kernel, K);
size_t i;
gsl_filter_gaussian_kernel(alpha, order, 1, &k.vector);
for (i = 0; i < n; ++i)
{
size_t wsize = gsl_movstat_fill(etype, x, i, H, H, window);
double sum = 0.0;
size_t j;
for (j = 0; j < wsize; ++j)
sum += window[j] * kernel[wsize - j - 1];
gsl_vector_set(y, i, sum);
}
free(window);
free(kernel);
return GSL_SUCCESS;
}
static void
fdiff(const gsl_vector * x, gsl_vector * dx)
{
const size_t N = x->size;
size_t i;
for (i = 1; i < N - 1; ++i)
{
double xm1 = gsl_vector_get(x, i - 1);
double xp1 = gsl_vector_get(x, i + 1);
gsl_vector_set(dx, i, 0.5 * (xp1 - xm1));
}
gsl_vector_set(dx, 0, gsl_vector_get(x, 1) - gsl_vector_get(x, 0));
gsl_vector_set(dx, N - 1, gsl_vector_get(x, N - 1) - gsl_vector_get(x, N - 2));
}
static void
test_gaussian_kernel(const double alpha, const size_t K)
{
const size_t max_order = 3;
gsl_vector * kernel = gsl_vector_alloc(K);
gsl_vector * deriv = gsl_vector_alloc(K);
gsl_vector * deriv_fd = gsl_vector_alloc(K);
char buf[2048];
size_t order;
gsl_filter_gaussian_kernel(alpha, 0, 0, kernel);
for (order = 1; order <= max_order; ++order)
{
gsl_filter_gaussian_kernel(alpha, order, 0, deriv);
fdiff(kernel, deriv_fd);
sprintf(buf, "gaussian kernel order=%zu alpha=%g K=%zu", order, alpha, K);
compare_vectors(1.0e-2, deriv_fd, deriv, buf);
gsl_vector_memcpy(kernel, deriv);
}
gsl_vector_free(kernel);
gsl_vector_free(deriv);
gsl_vector_free(deriv_fd);
}
static void
test_gaussian_proc(const double tol, const double alpha, const size_t order, const size_t n, const size_t K,
const gsl_filter_end_t etype, gsl_rng * rng_p)
{
gsl_filter_gaussian_workspace * w = gsl_filter_gaussian_alloc(K);
gsl_vector * x = gsl_vector_alloc(n);
gsl_vector * y = gsl_vector_alloc(n);
gsl_vector * z = gsl_vector_alloc(n);
char buf[2048];
random_vector(x, rng_p);
/* y = filter(x) with slow brute force method */
slow_gaussian(etype, alpha, order, x, y, K);
/* y = filter(x) with fast method */
gsl_filter_gaussian(etype, alpha, order, x, z, w);
/* test y = z */
sprintf(buf, "n=%zu K=%zu endtype=%u alpha=%g order=%zu gaussian random", n, K, etype, alpha, order);
compare_vectors(tol, z, y, buf);
/* z = filter(x) in-place */
gsl_vector_memcpy(z, x);
gsl_filter_gaussian(etype, alpha, order, z, z, w);
sprintf(buf, "n=%zu K=%zu endtype=%u alpha=%g order=%zu gaussian random in-place", n, K, etype, alpha, order);
compare_vectors(tol, z, y, buf);
gsl_filter_gaussian_free(w);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_vector_free(z);
}
static void
test_gaussian_deriv(const double alpha, const size_t n, const size_t K)
{
#if 0
const double f_low = 1.0;
const double f_high = 50.0;
const double gamma = 2.0 * M_PI / (n - 1.0);
const double dt = 1.0 / (n - 1.0);
gsl_vector *x = gsl_vector_alloc(n);
gsl_vector *dx = gsl_vector_alloc(n);
gsl_vector *y1 = gsl_vector_alloc(n);
gsl_vector *y2 = gsl_vector_alloc(n);
gsl_filter_gaussian_workspace *w = gsl_filter_gaussian_alloc(K);
size_t i;
/* make input signal composed of two sine waves at different frequencies */
for (i = 0; i < n; ++i)
{
double xi = sin(gamma * f_low * i) + sin(gamma * f_high * i);
double dxi = gamma * f_low * cos(gamma * f_low * i) +
gamma * f_high * cos(gamma * f_high * i);
gsl_vector_set(x, i, xi);
gsl_vector_set(dx, i, dxi);
}
/* compute y1 = G * dx(t)/dt */
gsl_filter_gaussian(alpha, 0, dx, y1, w);
/* compute y2 = dG/dt * x(t) */
gsl_filter_gaussian(alpha, 1, x, y2, w);
for (i = 0; i < n; ++i)
{
printf("%zu %.12e %.12e %.12e %.12e\n",
i,
gsl_vector_get(x, i),
gsl_vector_get(dx, i),
gsl_vector_get(y1, i),
gsl_vector_get(y2, i));
}
gsl_vector_free(x);
gsl_vector_free(dx);
gsl_vector_free(y1);
gsl_vector_free(y2);
gsl_filter_gaussian_free(w);
#endif
}
static void
test_gaussian(gsl_rng * r)
{
const double tol = 1.0e-10;
size_t order;
test_gaussian_kernel(3.0, 2001);
for (order = 0; order <= 3; ++order)
{
test_gaussian_proc(tol, 2.5, order, 1000, 21, GSL_FILTER_END_PADZERO, r);
test_gaussian_proc(tol, 3.0, order, 500, 11, GSL_FILTER_END_PADZERO, r);
test_gaussian_proc(tol, 1.0, order, 50, 101, GSL_FILTER_END_PADZERO, r);
test_gaussian_proc(tol, 2.0, order, 50, 11, GSL_FILTER_END_PADZERO, r);
test_gaussian_proc(tol, 2.5, order, 1000, 21, GSL_FILTER_END_PADVALUE, r);
test_gaussian_proc(tol, 3.0, order, 500, 11, GSL_FILTER_END_PADVALUE, r);
test_gaussian_proc(tol, 1.0, order, 50, 101, GSL_FILTER_END_PADVALUE, r);
test_gaussian_proc(tol, 2.0, order, 50, 11, GSL_FILTER_END_PADVALUE, r);
test_gaussian_proc(tol, 2.5, order, 1000, 21, GSL_FILTER_END_TRUNCATE, r);
test_gaussian_proc(tol, 3.0, order, 500, 11, GSL_FILTER_END_TRUNCATE, r);
test_gaussian_proc(tol, 1.0, order, 50, 101, GSL_FILTER_END_TRUNCATE, r);
test_gaussian_proc(tol, 2.0, order, 50, 11, GSL_FILTER_END_TRUNCATE, r);
}
}
| {
"alphanum_fraction": 0.6604567308,
"avg_line_length": 30.8148148148,
"ext": "c",
"hexsha": "eb8ef7282926627b0fe7541d81d3865a60c82df0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/filter/test_gaussian.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/filter/test_gaussian.c",
"max_line_length": 112,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/filter/test_gaussian.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": 2042,
"size": 6656
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
#include <petscksp.h>
#include <petscpc.h>
#include "common-driver-utils.h"
#include "pc_GtKG.h"
#include "pc_ScaledGtKG.h"
PetscErrorCode BSSCR_PetscExtStokesSolversInitialize( void )
{
Stg_PCRegister( "gtkg", "Solvers/KSPSolvers/src/BSSCR", "BSSCR_PCCreate_GtKG", BSSCR_PCCreate_GtKG );
//Stg_PCRegister( "bfbt", "Solvers/KSPSolvers/src/BSSCR", "BSSCR_PCCreate_GtKG", BSSCR_PCCreate_GtKG );
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PetscExtStokesSolversFinalize( void )
{
#if ((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=4))
// PCFinalizePackage();
#else
// PCRegisterDestroy();
#endif
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.4989339019,
"avg_line_length": 33.5,
"ext": "c",
"hexsha": "af15d567552560b1fb889d6b53a0b43d074ee756",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/register_stokes_solvers.c",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/register_stokes_solvers.c",
"max_line_length": 105,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/register_stokes_solvers.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 467,
"size": 1407
} |
//
// Encoder.h
// PretendToWork
//
// Created by tqtifnypmb on 08/12/2017.
// Copyright © 2017 tqtifnypmb. All rights reserved.
//
#pragma once
#include "../types.h"
#include <string>
#include <gsl/gsl>
namespace brick
{
struct ASCIIConverter {
typedef std::string result_type;
static detail::CodePointList encode(gsl::span<const char> bytes);
static result_type decode(const detail::CodePointList& cplist);
};
//struct UTF8Converter {
// typedef std::string result_type;
//
// static detail::CodePointList encode(gsl::span<const char> bytes);
// static result_type decode(const detail::CodePointList& cplist);
// static size_t numOfLine(const detail::CodePointList& cplist);
//};
//
} // namespace brick
| {
"alphanum_fraction": 0.6864295125,
"avg_line_length": 21.6857142857,
"ext": "h",
"hexsha": "269df9cd22ac1516a87cb952320a605d94aa62d0",
"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": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tqtifnypmb/brick",
"max_forks_repo_path": "src/converter/Converter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"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": "tqtifnypmb/brick",
"max_issues_repo_path": "src/converter/Converter.h",
"max_line_length": 71,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tqtifnypmb/brick",
"max_stars_repo_path": "src/converter/Converter.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 200,
"size": 759
} |
#include <cblas.h>
#include <clapack.h>
main(int nargs, char **args)
{
double A[1]={1.0}, b[1]={1.0};
int ipiv[1];
clapack_dgesv(CblasColMajor, 1, 1, A, 1, ipiv, b, 1);
}
| {
"alphanum_fraction": 0.5888888889,
"avg_line_length": 20,
"ext": "c",
"hexsha": "e4e35701763a07fc6876230114a6ce55a2dca74a",
"lang": "C",
"max_forks_count": 47,
"max_forks_repo_forks_event_max_datetime": "2021-11-11T20:59:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-27T06:22:57.000Z",
"max_forks_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e",
"max_forks_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_forks_repo_name": "kevleyski/math-atlas",
"max_forks_repo_path": "lib/test_dynlink.c",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e",
"max_issues_repo_issues_event_max_datetime": "2021-06-05T20:00:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-13T15:19:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_issues_repo_name": "kevleyski/math-atlas",
"max_issues_repo_path": "lib/test_dynlink.c",
"max_line_length": 56,
"max_stars_count": 135,
"max_stars_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e",
"max_stars_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_stars_repo_name": "kevleyski/math-atlas",
"max_stars_repo_path": "lib/test_dynlink.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T02:26:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-08T20:35:35.000Z",
"num_tokens": 78,
"size": 180
} |
/* Copyright 2016, Alistair Boyle, 3-clause BSD License */
#include "config.h"
#include <stdio.h>
#include <stdlib.h> /* for exit */
#include <math.h> /* for fabs */
#include <cblas.h> /* for cblas_dgemm */
int
main (void)
{
double const a[] = { 0.11, 0.12, 0.13,
0.21, 0.22, 0.23
};
double const b[] = { 1011.0, 1012.0,
1021.0, 1022.0,
1031.0, 1032.0
};
double c[] = { 0.00, 0.00,
0.00, 0.00
};
/* Compute C = a A B + c C */
cblas_dgemm (CblasRowMajor, CblasNoTrans, CblasNoTrans,
3, 2, 3, /* m, n, k, */
1.0, a, 3, b, 2, /* a, A, m, B, n, */
0.0, c, 2); /* c, C, k */
/* A is m x k, B is k x n, C is m x n */
/* matlab: expect = a*b */
double const expect[] = { 367.7600, 368.1200,
674.0600, 674.7200
};
printf("\tactual\t\t\texpect\n");
printf ("[ %g, %g == [ %g, %g\n", c[0], c[1], expect[0], expect[1]);
printf (" %g, %g ] %g, %g ]\n", c[2], c[3], expect[2], expect[3]);
int i;
for(i = 0; i < 4; i++) {
if ( fabs(expect[i] - c[i]) > 1e-12 ) {
printf("FAIL\n");
return 1;
}
}
printf("PASS\n");
exit(EXIT_SUCCESS);
}
| {
"alphanum_fraction": 0.3974358974,
"avg_line_length": 31.9090909091,
"ext": "c",
"hexsha": "bebbbbd1470cf7a55c3c434d1bd682bf2fe15aa0",
"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": "05a10333eda3b1569a9acd6e8b8fca245f9f012e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "boyle/zedhat",
"max_forks_repo_path": "tests/libcblas_dgemm.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e",
"max_issues_repo_issues_event_max_datetime": "2018-04-12T09:34:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-03-30T02:37:55.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "boyle/zedhat",
"max_issues_repo_path": "tests/libcblas_dgemm.c",
"max_line_length": 78,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "boyle/zedhat",
"max_stars_repo_path": "tests/libcblas_dgemm.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-06T01:26:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-08T16:02:51.000Z",
"num_tokens": 493,
"size": 1404
} |
//
// Created by Harold on 2020/9/16.
//
#ifndef M_MATH_M_CURVEFIT_H
#define M_MATH_M_CURVEFIT_H
#include <map>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <numeric>
#include <vector>
#include <cmath>
namespace M_MATH {
class CurveFit{
public:
enum robust_type {
DEFAULT,
BISQUARE,
CAUCHY,
FAIR,
HUBER,
OLS,
WELSCH
};
public:
bool is_valid() const { return !m_coefficient.empty(); }
bool linearfit(double const* x, double const* y, size_t n);
bool polyfit(double const* x, double const* y, size_t length, unsigned poly_n);
bool robustfit(double const* x, double const* y, size_t length, robust_type type, unsigned poly_n);
double getY(double x) const;
template<typename IT_X, typename IT_Y>
void getYs(IT_X x_begin, IT_X x_end, IT_Y y_begin) const;
double get_coefficient(size_t n) const;
void set_coefficient(size_t n, double c) { m_coefficient[n] = c; };
size_t get_coefficient_size() const { return m_coefficient.size(); };
double get_slope() { return m_coefficient[1]; };
double get_intercept() { return m_coefficient[0]; };
double get_SSR() const { return m_ssr; };
double get_SSE() const { return m_sse; };
double get_SST() const { return m_sst; };
double get_RMSE() const { return m_rmse; };
double get_RSquare() const { return m_RSquare; };
double get_Goodness() const { return m_goodness; };
void clear() {
m_coefficient.clear();
m_err.clear();
}
private:
std::map<size_t, double> m_coefficient; // <index, fitting coefficient>, [0]: slope, [1] intercept
std::map<size_t, double> m_err;
double m_cov; // covariance
double m_ssr; // sum of squares due to regression
double m_sse; // sum of squares error
double m_sst; // m_sst = m_ssr + m_sse
double m_rmse; // RMS error
double m_RSquare; // R-Square
double m_sumsq; // sum of squares
double m_goodness; // fit goodness
static void get_determinate_parameters(double const* y, double const* yf,
size_t length,
double &ssr,
double &sse,
double &sst,
double &rmse,
double &RSquare) {
double y_mean = std::accumulate(y, y+length, 0.0);
ssr = 0.0;
for (auto i = 0; i < length; ++i) {
ssr += (yf[i] - y_mean) * (yf[i] - y_mean);
sse += (y[i] - yf[i]) * (y[i] - yf[i]);
}
sst = ssr + sse;
rmse = std::sqrt(sse/(double)length);
RSquare = 1.0 - ssr/sst;
}
static gsl_multifit_robust_type const* get_robust_type(robust_type type) {
switch (type) {
case DEFAULT:
return gsl_multifit_robust_default;
case BISQUARE:
return gsl_multifit_robust_bisquare;
case CAUCHY:
return gsl_multifit_robust_cauchy;
case FAIR:
return gsl_multifit_robust_fair;
case HUBER:
return gsl_multifit_robust_huber;
case OLS:
return gsl_multifit_robust_ols;
case WELSCH:
return gsl_multifit_robust_welsch;
}
return nullptr;
}
};
inline bool CurveFit::linearfit(const double *x, const double *y, size_t n) {
clear();
m_coefficient[0] = 0;
m_coefficient[1] = 1;
m_err[0] = 0;
m_err[0] = 0;
// double const* x, size_t const x_stride,
// double const* y, size_t const y_stride,
// size_t n,
// double &intercept,
// double &slope,
// double &intercept_err,
// double &slope_err,
// double &cov,
// double &wssr
int ret = gsl_fit_linear(x, 1, y, 1, n,
&m_coefficient[0], &m_coefficient[1],
&m_err[0], &m_err[1],
&m_cov, &m_sumsq);
if (ret != 0)
return false;
// gammaQ function
m_goodness = gsl_cdf_chisq_Q(m_sumsq / 2.0, double(n - 2) / 2.0);
{
std::vector<double> yf(n, 0);
getYs(x, x+n, yf.begin());
get_determinate_parameters(y, &yf[0], n, m_ssr, m_sse, m_sst, m_rmse, m_RSquare);
}
return true;
}
inline bool CurveFit::polyfit(const double *x, const double *y, size_t length, unsigned poly_n) {
gsl_matrix *Xf = gsl_matrix_alloc(length, poly_n+1);
gsl_vector *Yf = gsl_vector_alloc(length);
gsl_vector *c = gsl_vector_alloc(poly_n+1);
gsl_matrix *cov = gsl_matrix_alloc(poly_n+1, poly_n+1);
for (auto i = 0; i < length; i++) {
gsl_matrix_set(Xf, i, 0, 1.0);
gsl_vector_set(Yf, i, y[i]);
for (auto j = 1; j < poly_n + 1; j++)
gsl_matrix_set(Xf, i, j, std::pow(x[i], int(j)));
}
auto *workspace = gsl_multifit_linear_alloc(length, poly_n+1);
double chisq;
// temporary vec to hold computed coefficients
std::vector<double> coe(poly_n+1, 0);
int ret = gsl_multifit_linear(Xf, Yf, c, cov, &chisq, workspace);
gsl_multifit_linear_free(workspace);
for (auto i = 0; i < c->size; i++)
coe[i] = gsl_vector_get(c, i);
gsl_matrix_free(Xf);
gsl_vector_free(Yf);
gsl_vector_free(c);
gsl_matrix_free(cov);
// if not successfully computed, not change former results
if (ret != 0)
return false;
// update results
m_goodness = gsl_cdf_chisq_Q(chisq/2.0, double(length-2)/2.0);
clear();
for (auto i = 0; i < poly_n+1; i++)
m_coefficient[i] = coe[i];
{
std::vector<double> yf(length, 0);
getYs(x, x+length, yf.begin());
get_determinate_parameters(y, &yf[0], length, m_ssr, m_sse, m_sst, m_rmse, m_RSquare);
}
return true;
}
inline double CurveFit::getY(double x) const {
double ret = 0;
for (auto const& it : m_coefficient)
ret += (it.second) * std::pow(x, it.first);
return ret;
}
template<typename IT_X, typename IT_Y>
inline void CurveFit::getYs(IT_X x_begin, IT_X x_end, IT_Y y_begin) const {
for (; x_begin != x_end; ++x_begin, ++y_begin)
*y_begin = getY(*x_begin);
}
inline double CurveFit::get_coefficient(size_t n) const {
auto it = m_coefficient.find(n);
if (it != m_coefficient.end())
return it->second;
return 0.0;
}
// poly_n >= 2
// poly_n = 2: linear fit
bool CurveFit::robustfit(const double *x, const double *y, size_t length, robust_type type, unsigned int poly_n) {
gsl_matrix *Xf = gsl_matrix_alloc(length, poly_n);
gsl_vector *Yf = gsl_vector_alloc(length);
gsl_vector *c = gsl_vector_alloc(poly_n);
gsl_matrix *cov = gsl_matrix_alloc(poly_n, poly_n);
for (auto i = 0; i < length; i++) {
gsl_matrix_set(Xf, i, 0, 1.0);
gsl_vector_set(Yf, i, y[i]);
for (auto j = 1; j < poly_n; j++)
gsl_matrix_set(Xf, i, j, std::pow(x[i], int(j)));
}
auto *workspace = gsl_multifit_robust_alloc(get_robust_type(type), length, poly_n);
// temporary vec to hold computed coefficients
std::vector<double> coe(poly_n, 0);
int ret = gsl_multifit_robust(Xf, Yf, c, cov, workspace);
gsl_multifit_robust_free(workspace);
for (auto i = 0; i < c->size; i++)
coe[i] = gsl_vector_get(c, i);
gsl_matrix_free(Xf);
gsl_vector_free(Yf);
gsl_vector_free(c);
gsl_matrix_free(cov);
// if not successfully computed, not change former results
if (ret != 0)
return false;
// update results
clear();
for (auto i = 0; i < poly_n; i++)
m_coefficient[i] = coe[i];
{
std::vector<double> yf(length, 0);
getYs(x, x+length, yf.begin());
get_determinate_parameters(y, &yf[0], length, m_ssr, m_sse, m_sst, m_rmse, m_RSquare);
}
return true;
}
}
#endif //M_MATH_M_CURVEFIT_H
| {
"alphanum_fraction": 0.5344788859,
"avg_line_length": 35.0551181102,
"ext": "h",
"hexsha": "0287efaded35483edbc4d7b5414267bd1082b471",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z",
"max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Harold2017/m_math",
"max_forks_repo_path": "include/m_curvefit.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495",
"max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Harold2017/m_math",
"max_issues_repo_path": "include/m_curvefit.h",
"max_line_length": 118,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Harold2017/m_math",
"max_stars_repo_path": "include/m_curvefit.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z",
"num_tokens": 2385,
"size": 8904
} |
#pragma once
#include <gsl/gsl>
#include <memory>
#include <list>
#include <chrono>
#include <EASTL/fixed_vector.h>
#include <EASTL/map.h>
#include "../platform/d3d.h"
#include "buffers.h"
#include "shaders.h"
#include "camera.h"
#include "textures.h"
struct ID3D11Texture2D;
namespace gfx {
class RenderingDevice;
class Material;
struct RasterizerSpec;
class RasterizerState;
struct BlendSpec;
class BlendState;
struct DepthStencilSpec;
class DepthStencilState;
struct SamplerSpec;
class SamplerState;
struct MaterialSamplerSpec;
class BufferBinding;
class TextEngine;
using SamplerStatePtr = std::shared_ptr<SamplerState>;
using DepthStencilStatePtr = std::shared_ptr<DepthStencilState>;
using BlendStatePtr = std::shared_ptr<BlendState>;
using RasterizerStatePtr = std::shared_ptr<RasterizerState>;
using ResizeListener = std::function<void(int w, int h)>;
// RAII style listener registration
class ResizeListenerRegistration {
friend class RenderingDevice;
public:
~ResizeListenerRegistration();
NO_COPY(ResizeListenerRegistration);
ResizeListenerRegistration(ResizeListenerRegistration &&o) : mDevice(o.mDevice), mKey(o.mKey) {
o.mKey = 0;
}
ResizeListenerRegistration &operator =(ResizeListenerRegistration &&o) = delete;
private:
ResizeListenerRegistration(gfx::RenderingDevice &device, uint32_t key) : mDevice(device), mKey(key) {}
gfx::RenderingDevice &mDevice;
uint32_t mKey;
};
class ResourceListener {
public:
virtual ~ResourceListener();
virtual void CreateResources(RenderingDevice&) = 0;
virtual void FreeResources(RenderingDevice&) = 0;
};
enum class StandardSlotSemantic {
ViewProjMatrix,
UiProjMatrix
};
// RAII class for managing resource listener registrations
class ResourceListenerRegistration {
public:
explicit ResourceListenerRegistration(RenderingDevice& device, ResourceListener* listener);
~ResourceListenerRegistration();
NO_COPY_OR_MOVE(ResourceListenerRegistration);
private:
RenderingDevice& mDevice;
ResourceListener* mListener;
};
using DynamicTexturePtr = std::shared_ptr<class DynamicTexture>;
using RenderTargetTexturePtr = std::shared_ptr<class RenderTargetTexture>;
using RenderTargetDepthStencilPtr = std::shared_ptr<class RenderTargetDepthStencil>;
// An output of a display device (think: monitor)
struct DisplayDeviceOutput {
// Technical id for use in a configuration or log file
std::string id;
// Name to display to the end user
std::string name;
};
// A display device that can be used to render the game (think: GPU)
struct DisplayDevice {
// Technical id for use in a configuration or log file
size_t id;
// Name to display to the end user
std::string name;
// Outputs associated with this display device
eastl::fixed_vector<DisplayDeviceOutput, 4> outputs;
};
enum class PrimitiveType {
TriangleList,
TriangleStrip,
LineStrip,
LineList,
PointList,
};
enum class BufferFormat {
A8,
A8R8G8B8,
X8R8G8B8
};
enum class MapMode {
Read,
Discard,
NoOverwrite
};
template<typename TBuffer, typename TElement>
class MappedBuffer {
public:
using View = gsl::span<TElement>;
using Iterator = gsl::contiguous_span_iterator<View>;
MappedBuffer(TBuffer &buffer,
RenderingDevice &device,
View data,
uint32_t rowPitch) : mBuffer(buffer), mDevice(device), mData(data), mRowPitch(rowPitch) {}
MappedBuffer(MappedBuffer&& o) : mBuffer(o.mBuffer), mDevice(o.mDevice), mData(o.mData), mRowPitch(o.rowPitch) {
o.mMoved = true;
}
~MappedBuffer();
Iterator begin() {
return mData.begin();
}
Iterator end() {
return mData.end();
}
TElement &operator[](size_t idx) {
assert(!mMoved);
return mData[idx];
}
size_t size() const {
return mData.size();
}
TElement *GetData() const {
return mData.data();
}
// Only relevant for mapped texture buffers
size_t GetRowPitch() const {
return mRowPitch;
}
void Unmap();
private:
TBuffer& mBuffer;
RenderingDevice &mDevice;
View mData;
size_t mRowPitch;
bool mMoved = false;
};
template<typename TElement>
using MappedVertexBuffer = MappedBuffer<VertexBuffer, TElement>;
using MappedIndexBuffer = MappedBuffer<IndexBuffer, uint16_t>;
using MappedTexture = MappedBuffer<DynamicTexture, uint8_t>;
class RenderingDevice {
template<typename T>
friend class Shader;
friend class BufferBinding;
friend class TextureLoader;
friend class DebugUI;
public:
RenderingDevice(HWND mWindowHandle, uint32_t adapterIdx = 0, bool debugDevice = false);
~RenderingDevice();
bool BeginFrame();
bool Present();
void PresentForce();
void Flush();
void ClearCurrentColorTarget(XMCOLOR color);
void ClearCurrentDepthTarget(bool clearDepth = true,
bool clearStencil = true,
float depthValue = 1.0f,
uint8_t stencilValue = 0);
using Clock = std::chrono::high_resolution_clock;
using TimePoint = std::chrono::time_point<Clock>;
TimePoint GetLastFrameStart() const {
return mLastFrameStart;
}
TimePoint GetDeviceCreated() const {
return mDeviceCreated;
}
const eastl::vector<DisplayDevice> &GetDisplayDevices();
// Resize the back buffer
void ResizeBuffers(int w, int h);
Material CreateMaterial(
const BlendSpec &blendSpec,
const DepthStencilSpec &depthStencilSpec,
const RasterizerSpec &rasterizerSpec,
const std::vector<MaterialSamplerSpec> &samplerSpecs,
const VertexShaderPtr &vs,
const PixelShaderPtr &ps
);
BlendStatePtr CreateBlendState(const BlendSpec &spec);
DepthStencilStatePtr CreateDepthStencilState(const DepthStencilSpec &spec);
RasterizerStatePtr CreateRasterizerState(const RasterizerSpec &spec);
SamplerStatePtr CreateSamplerState(const SamplerSpec &spec);
// Changes the current scissor rect to the given rectangle
void SetScissorRect(int x, int y, int width, int height);
// Resets the scissor rect to the current render target's size
void ResetScissorRect();
std::shared_ptr<class IndexBuffer> CreateEmptyIndexBuffer(size_t count);
std::shared_ptr<class VertexBuffer> CreateEmptyVertexBuffer(size_t count, bool forPoints = false);
DynamicTexturePtr CreateDynamicTexture(gfx::BufferFormat format, int width, int height);
DynamicTexturePtr CreateDynamicStagingTexture(gfx::BufferFormat format, int width, int height);
void CopyRenderTarget(gfx::RenderTargetTexture &renderTarget, gfx::DynamicTexture &stagingTexture);
RenderTargetTexturePtr CreateRenderTargetTexture(gfx::BufferFormat format, int width, int height, bool multiSampled = false);
RenderTargetTexturePtr CreateRenderTargetForNativeSurface(ID3D11Texture2D *surface);
RenderTargetTexturePtr CreateRenderTargetForSharedSurface(IUnknown *surface);
RenderTargetDepthStencilPtr CreateRenderTargetDepthStencil(int width, int height, bool multiSampled = false);
template<typename T>
VertexBufferPtr CreateVertexBuffer(gsl::span<T> data, bool immutable = true);
VertexBufferPtr CreateVertexBufferRaw(gsl::span<const uint8_t> data, bool immutable = true);
IndexBufferPtr CreateIndexBuffer(gsl::span<const uint16_t> data, bool immutable = true);
void SetMaterial(const Material &material);
void SetVertexShaderConstant(uint32_t startRegister, StandardSlotSemantic semantic);
void SetPixelShaderConstant(uint32_t startRegister, StandardSlotSemantic semantic);
void SetRasterizerState(const RasterizerState &state);
void SetBlendState(const BlendState &state);
void SetDepthStencilState(const DepthStencilState &state);
void SetSamplerState(int samplerIdx, const SamplerState &state);
void SetTexture(uint32_t slot, gfx::Texture &texture);
void SetIndexBuffer(const gfx::IndexBuffer &indexBuffer);
void Draw(PrimitiveType type, uint32_t vertexCount, uint32_t startVertex = 0);
void DrawIndexed(PrimitiveType type, uint32_t vertexCount, uint32_t indexCount, uint32_t startVertex = 0, uint32_t vertexBase = 0);
/*
Changes the currently used cursor to the given surface.
*/
void SetCursor(int hotspotX, int hotspotY, const gfx::TextureRef &texture);
void ShowCursor();
void HideCursor();
/*
Take a screenshot with the given size. The image will be stretched
to the given size.
*/
void TakeScaledScreenshot(const std::string& filename, int width, int height, int quality = 90);
// Creates a buffer binding for a MDF material that
// is preinitialized with the correct shader
BufferBinding CreateMdfBufferBinding();
Shaders& GetShaders() {
return mShaders;
}
Textures& GetTextures() {
return mTextures;
}
WorldCamera& GetCamera() {
return mCamera;
}
void SetAntiAliasing(bool enable, uint32_t samples, uint32_t quality);
template<typename T>
void UpdateBuffer(VertexBuffer &buffer, gsl::span<T> data) {
UpdateBuffer(buffer, data.data(), data.size_bytes());
}
void UpdateBuffer(VertexBuffer &buffer, const void *data, size_t size);
void UpdateBuffer(IndexBuffer &buffer, gsl::span<uint16_t> data);
template<typename TElement>
MappedVertexBuffer<TElement> Map(VertexBuffer &buffer, gfx::MapMode mode = gfx::MapMode::Discard) {
auto data = MapVertexBufferRaw(buffer, mode);
auto castData = gsl::span<TElement>((TElement*)data.data(), data.size() / sizeof(TElement));
return MappedVertexBuffer<TElement>(buffer, *this, castData, 0);
}
void Unmap(VertexBuffer &buffer);
// Index buffer memory mapping techniques
MappedIndexBuffer Map(IndexBuffer &buffer, gfx::MapMode mode = gfx::MapMode::Discard);
void Unmap(IndexBuffer &buffer);
MappedTexture Map(DynamicTexture &texture, gfx::MapMode mode = gfx::MapMode::Discard);
void Unmap(DynamicTexture &texture);
static constexpr uint32_t MaxVsConstantBufferSize = 2048;
template<typename T>
void SetVertexShaderConstants(uint32_t slot, const T &buffer) {
static_assert(sizeof(T) <= MaxVsConstantBufferSize, "Constant buffer exceeds maximum size");
UpdateResource(mVsConstantBuffer, &buffer, sizeof(T));
VSSetConstantBuffer(slot, mVsConstantBuffer);
}
static constexpr uint32_t MaxPsConstantBufferSize = 512;
template<typename T>
void SetPixelShaderConstants(uint32_t slot, const T &buffer) {
static_assert(sizeof(T) <= MaxPsConstantBufferSize, "Constant buffer exceeds maximum size");
UpdateResource(mPsConstantBuffer, &buffer, sizeof(T));
PSSetConstantBuffer(slot, mPsConstantBuffer);
}
const gfx::Size &GetBackBufferSize() const;
// Pushes the back buffer and it's depth buffer as the current render target
void PushBackBufferRenderTarget();
void PushRenderTarget(
const gfx::RenderTargetTexturePtr &colorBuffer,
const gfx::RenderTargetDepthStencilPtr &depthStencilBuffer
);
void PopRenderTarget();
const gfx::RenderTargetTexturePtr &GetCurrentRederTargetColorBuffer() const {
return mRenderTargetStack.back().colorBuffer;
}
const gfx::RenderTargetDepthStencilPtr &GetCurrentRenderTargetDepthStencilBuffer() const {
return mRenderTargetStack.back().depthStencilBuffer;
}
ResizeListenerRegistration AddResizeListener(ResizeListener listener);
bool IsDebugDevice() const;
/**
* Emits the start of a rendering call group if the debug device is being used.
* This information can be used in the graphic debugger.
*/
template<typename... T>
void BeginPerfGroup(const char *format, const T &... args) const {
if (IsDebugDevice()) {
BeginPerfGroupInternal(fmt::format(format, args...).c_str());
}
}
/**
* Ends a previously started performance group.
*/
void EndPerfGroup() const;
TextEngine& GetTextEngine() const;
private:
friend class ResourceListenerRegistration;
friend class ResizeListenerRegistration;
void BeginPerfGroupInternal(const char *msg) const;
void RemoveResizeListener(uint32_t key);
void AddResourceListener(ResourceListener* resourceListener);
void RemoveResourceListener(ResourceListener* resourceListener);
void UpdateResource(ID3D11Resource *resource, const void *data, size_t size);
CComPtr<ID3D11Buffer> CreateConstantBuffer(const void *initialData, size_t initialDataSize);
void VSSetConstantBuffer(uint32_t slot, ID3D11Buffer *buffer);
void PSSetConstantBuffer(uint32_t slot, ID3D11Buffer *buffer);
gsl::span<uint8_t> MapVertexBufferRaw(VertexBuffer &buffer, MapMode mode);
CComPtr<IDXGIAdapter1> GetAdapter(size_t index);
int mBeginSceneDepth = 0;
HWND mWindowHandle;
CComPtr<IDXGIFactory1> mDxgiFactory;
// The DXGI adapter we use
CComPtr<IDXGIAdapter1> mAdapter;
// D3D11 device and related
CComPtr<ID3D11Device> mD3d11Device;
CComPtr<ID3D11Device1> mD3d11Device1;
DXGI_SWAP_CHAIN_DESC mSwapChainDesc;
CComPtr<IDXGISwapChain> mSwapChain;
CComPtr<ID3D11DeviceContext> mContext;
gfx::RenderTargetTexturePtr mBackBufferNew;
gfx::RenderTargetDepthStencilPtr mBackBufferDepthStencil;
struct RenderTarget {
gfx::RenderTargetTexturePtr colorBuffer;
gfx::RenderTargetDepthStencilPtr depthStencilBuffer;
};
eastl::fixed_vector<RenderTarget, 16> mRenderTargetStack;
D3D_FEATURE_LEVEL mFeatureLevel = D3D_FEATURE_LEVEL_9_1;
eastl::vector<DisplayDevice> mDisplayDevices;
CComPtr<ID3D11Buffer> mVsConstantBuffer;
CComPtr<ID3D11Buffer> mPsConstantBuffer;
eastl::map<uint32_t, ResizeListener> mResizeListeners;
uint32_t mResizeListenersKey = 0;
std::list<ResourceListener*> mResourcesListeners;
bool mResourcesCreated = false;
TimePoint mLastFrameStart = Clock::now();
TimePoint mDeviceCreated = Clock::now();
size_t mUsedSamplers = 0;
Shaders mShaders;
Textures mTextures;
WorldCamera mCamera;
struct Impl;
std::unique_ptr<Impl> mImpl;
};
template <typename T>
VertexBufferPtr RenderingDevice::CreateVertexBuffer(gsl::span<T> data, bool immutable) {
return CreateVertexBufferRaw(gsl::span(reinterpret_cast<const uint8_t*>(&data[0]), data.size_bytes()), immutable);
}
extern RenderingDevice *renderingDevice;
template<typename TBuffer, typename TElement>
inline MappedBuffer<TBuffer, TElement>::~MappedBuffer()
{
if (!mMoved) {
mDevice.Unmap(mBuffer);
}
}
template<typename TBuffer, typename TElement>
inline void MappedBuffer<TBuffer, TElement>::Unmap()
{
assert(!mMoved);
mMoved = true;
mDevice.Unmap(mBuffer);
}
inline ResizeListenerRegistration::~ResizeListenerRegistration() {
mDevice.RemoveResizeListener(mKey);
}
// RAII style demarcation of render call groups for performance debugging
class PerfGroup {
public:
template<typename... T>
PerfGroup(RenderingDevice &device, const char *format, T... args) : mDevice(device) {
device.BeginPerfGroup(format, args...);
}
~PerfGroup() {
mDevice.EndPerfGroup();
}
private:
const RenderingDevice &mDevice;
};
}
| {
"alphanum_fraction": 0.7580819694,
"avg_line_length": 29.3373015873,
"ext": "h",
"hexsha": "c5fb4325206987a91be637a0ea3e015867b98d08",
"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": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/include/graphics/device.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"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": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/include/graphics/device.h",
"max_line_length": 133,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/include/graphics/device.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3743,
"size": 14786
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "tests.h"
void
test_rot (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int N = 1;
float c = 0.0f;
float s = 0.0f;
float X[] = { -0.314f };
int incX = 1;
float Y[] = { -0.406f };
int incY = -1;
float x_expected[] = { 0.0f };
float y_expected[] = { 0.0f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 558)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 559)");
}
};
};
{
int N = 1;
float c = 0.866025403784f;
float s = 0.5f;
float X[] = { -0.314f };
int incX = 1;
float Y[] = { -0.406f };
int incY = -1;
float x_expected[] = { -0.474932f };
float y_expected[] = { -0.194606f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 560)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 561)");
}
};
};
{
int N = 1;
float c = 0.0f;
float s = -1.0f;
float X[] = { -0.314f };
int incX = 1;
float Y[] = { -0.406f };
int incY = -1;
float x_expected[] = { 0.406f };
float y_expected[] = { -0.314f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 562)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 563)");
}
};
};
{
int N = 1;
float c = -1.0f;
float s = 0.0f;
float X[] = { -0.314f };
int incX = 1;
float Y[] = { -0.406f };
int incY = -1;
float x_expected[] = { 0.314f };
float y_expected[] = { 0.406f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 564)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 565)");
}
};
};
{
int N = 1;
double c = 0;
double s = 0;
double X[] = { -0.493 };
int incX = 1;
double Y[] = { -0.014 };
int incY = -1;
double x_expected[] = { 0.0 };
double y_expected[] = { 0.0 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 566)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 567)");
}
};
};
{
int N = 1;
double c = 0.866025403784;
double s = 0.5;
double X[] = { -0.493 };
int incX = 1;
double Y[] = { -0.014 };
int incY = -1;
double x_expected[] = { -0.433950524066 };
double y_expected[] = { 0.234375644347 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 568)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 569)");
}
};
};
{
int N = 1;
double c = 0;
double s = -1;
double X[] = { -0.493 };
int incX = 1;
double Y[] = { -0.014 };
int incY = -1;
double x_expected[] = { 0.014 };
double y_expected[] = { -0.493 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 570)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 571)");
}
};
};
{
int N = 1;
double c = -1;
double s = 0;
double X[] = { -0.493 };
int incX = 1;
double Y[] = { -0.014 };
int incY = -1;
double x_expected[] = { 0.493 };
double y_expected[] = { 0.014 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 572)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 573)");
}
};
};
{
int N = 1;
float c = 0.0f;
float s = 0.0f;
float X[] = { -0.808f };
int incX = -1;
float Y[] = { -0.511f };
int incY = 1;
float x_expected[] = { 0.0f };
float y_expected[] = { 0.0f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 574)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 575)");
}
};
};
{
int N = 1;
float c = 0.866025403784f;
float s = 0.5f;
float X[] = { -0.808f };
int incX = -1;
float Y[] = { -0.511f };
int incY = 1;
float x_expected[] = { -0.955249f };
float y_expected[] = { -0.038539f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 576)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 577)");
}
};
};
{
int N = 1;
float c = 0.0f;
float s = -1.0f;
float X[] = { -0.808f };
int incX = -1;
float Y[] = { -0.511f };
int incY = 1;
float x_expected[] = { 0.511f };
float y_expected[] = { -0.808f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 578)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 579)");
}
};
};
{
int N = 1;
float c = -1.0f;
float s = 0.0f;
float X[] = { -0.808f };
int incX = -1;
float Y[] = { -0.511f };
int incY = 1;
float x_expected[] = { 0.808f };
float y_expected[] = { 0.511f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 580)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 581)");
}
};
};
{
int N = 1;
double c = 0;
double s = 0;
double X[] = { -0.176 };
int incX = -1;
double Y[] = { -0.165 };
int incY = 1;
double x_expected[] = { 0.0 };
double y_expected[] = { 0.0 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 582)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 583)");
}
};
};
{
int N = 1;
double c = 0.866025403784;
double s = 0.5;
double X[] = { -0.176 };
int incX = -1;
double Y[] = { -0.165 };
int incY = 1;
double x_expected[] = { -0.234920471066 };
double y_expected[] = { -0.0548941916244 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 584)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 585)");
}
};
};
{
int N = 1;
double c = 0;
double s = -1;
double X[] = { -0.176 };
int incX = -1;
double Y[] = { -0.165 };
int incY = 1;
double x_expected[] = { 0.165 };
double y_expected[] = { -0.176 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 586)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 587)");
}
};
};
{
int N = 1;
double c = -1;
double s = 0;
double X[] = { -0.176 };
int incX = -1;
double Y[] = { -0.165 };
int incY = 1;
double x_expected[] = { 0.176 };
double y_expected[] = { 0.165 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 588)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 589)");
}
};
};
{
int N = 1;
float c = 0.0f;
float s = 0.0f;
float X[] = { -0.201f };
int incX = -1;
float Y[] = { 0.087f };
int incY = -1;
float x_expected[] = { 0.0f };
float y_expected[] = { 0.0f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 590)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 591)");
}
};
};
{
int N = 1;
float c = 0.866025403784f;
float s = 0.5f;
float X[] = { -0.201f };
int incX = -1;
float Y[] = { 0.087f };
int incY = -1;
float x_expected[] = { -0.130571f };
float y_expected[] = { 0.175844f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 592)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 593)");
}
};
};
{
int N = 1;
float c = 0.0f;
float s = -1.0f;
float X[] = { -0.201f };
int incX = -1;
float Y[] = { 0.087f };
int incY = -1;
float x_expected[] = { -0.087f };
float y_expected[] = { -0.201f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 594)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 595)");
}
};
};
{
int N = 1;
float c = -1.0f;
float s = 0.0f;
float X[] = { -0.201f };
int incX = -1;
float Y[] = { 0.087f };
int incY = -1;
float x_expected[] = { 0.201f };
float y_expected[] = { -0.087f };
cblas_srot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "srot(case 596)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "srot(case 597)");
}
};
};
{
int N = 1;
double c = 0;
double s = 0;
double X[] = { -0.464 };
int incX = -1;
double Y[] = { 0.7 };
int incY = -1;
double x_expected[] = { 0.0 };
double y_expected[] = { 0.0 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 598)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 599)");
}
};
};
{
int N = 1;
double c = 0.866025403784;
double s = 0.5;
double X[] = { -0.464 };
int incX = -1;
double Y[] = { 0.7 };
int incY = -1;
double x_expected[] = { -0.051835787356 };
double y_expected[] = { 0.838217782649 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 600)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 601)");
}
};
};
{
int N = 1;
double c = 0;
double s = -1;
double X[] = { -0.464 };
int incX = -1;
double Y[] = { 0.7 };
int incY = -1;
double x_expected[] = { -0.7 };
double y_expected[] = { -0.464 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 602)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 603)");
}
};
};
{
int N = 1;
double c = -1;
double s = 0;
double X[] = { -0.464 };
int incX = -1;
double Y[] = { 0.7 };
int incY = -1;
double x_expected[] = { 0.464 };
double y_expected[] = { -0.7 };
cblas_drot(N, X, incX, Y, incY, c, s);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "drot(case 604)");
}
};
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "drot(case 605)");
}
};
};
}
| {
"alphanum_fraction": 0.4483826033,
"avg_line_length": 20.3176100629,
"ext": "c",
"hexsha": "d2d6ed330e01e3af94ba187cfea142c6903df910",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_rot.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_rot.c",
"max_line_length": 67,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_rot.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 5146,
"size": 12922
} |
#include <ceed.h>
#include <petsc.h>
#include "../problems/problems.h"
PetscErrorCode RegisterProblems(ProblemFunctions problem_functions) {
PetscErrorCode ierr;
PetscFunctionBegin;
SOLIDS_PROBLEM_REGISTER(problem_functions, "Linear", ElasLinear, NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "SS-NH", ElasSSNH, NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSCurrent-NH1", ElasFSCurrentNH1,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSCurrent-NH2", ElasFSCurrentNH2,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSInitial-NH1", ElasFSInitialNH1,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSInitial-NH2", ElasFSInitialNH2,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSInitial-MR1", ElasFSInitialMR1,
MR);
PetscFunctionReturn(0);
};
| {
"alphanum_fraction": 0.6885245902,
"avg_line_length": 36.6,
"ext": "c",
"hexsha": "01531b6e9423d18d646778c289abff77f8adf86f",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/solids/problems/problems.c",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/solids/problems/problems.c",
"max_line_length": 79,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/solids/problems/problems.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 221,
"size": 915
} |
/**
* Subroutines to calculate the
* various contamination models
*
*/
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_interp.h>
#include "fitsio.h"
#include "inout_aper.h"
#include "aXe_grism.h"
#include "spce_PET.h"
#include "spc_wl_calib.h"
#include "aXe_errors.h"
#include "fringe_conf.h"
#include "spc_resp.h"
#include "spce_pathlength.h"
#include "aper_conf.h"
#include "trace_conf.h"
#include "specmodel_utils.h"
#include "model_utils.h"
#include "spc_fluxcube.h"
#define MAX(x,y) (((x)>(y))?(x):(y))
#define MIN(x,y) (((x)<(y))?(x):(y))
#define SQR(x) ((x)*(x))
/**
* The function creates and loads a new flux_cube structure
* The data is taken from the file specified in the input.
*
* @param fcube_file - the file name of the fluxcube
*
* @return ret - the new flux_cube structure
*/
flux_cube *
load_fluxcube(const char fcube_file[])
{
flux_cube *fcube;
//gsl_matrix *test;
int nflux, n_ext=0;
int i;
// get the number of extensions
n_ext = FITSextnum(fcube_file);
if (n_ext <3)
aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PETCONT: " "the fluxcube file %s has only %i extensions!\n",
fcube_file, n_ext);
// determine the number of flux images and allocate
// the space for the fluxcube structure
nflux = n_ext-2;
fcube = alloc_fluxcube(nflux);
// load XOFFS and YOFFS
load_offsets(fcube_file, fcube);
// load the segmentation image into the structure
fcube->segmentation = load_segmentation(fcube_file);
// gsl_to_FITSimage (fcube->segmentation, "gogo.fits", 1, "MOO");
// load the fluximages
for (i=0; i < nflux; i++)
{
fcube->fluxims[i] = load_fluximage(fcube_file, i+3);
}
// fill the number of fluximages
fcube->n_fimage = nflux;
// order the fluximages and store the
// vector with the ordered indices
fcube->fimage_order = order_fluxims(fcube);
return fcube;
}
/**
* The function allocates space for a new
* fluxcube structure.
*
* @param nflux - the number of fluximages
*
* @return ret - the fluxcube structure
*/
flux_cube *
alloc_fluxcube(const int nflux)
{
flux_cube *fcube;
// allocate space for the flux_cube structure
fcube = (flux_cube *)malloc(sizeof(flux_cube));
// allocate space for the array of fluximages
fcube->fluxims = (flux_image **)malloc(nflux * sizeof(flux_image *));
// return the result
return fcube;
}
/**
* The function fills the keywords XOFFS and YOFFS
* from the primary header of the fitscube file
* into the according items of the fitscube structure.
* In case that those keywords are not present,
* they are set to 0.
*
* @param fcube_file - the file name of the fluxcube
* @param fcube - the fluxcube structure
*
* @return 1 - always true
*/
int
load_offsets(const char fcube_file[], flux_cube *fcube)
{
char tmp[MAXCHAR];
double dtmp=0.0;
// avoid problems with the 'const' declaration
strcpy(tmp, fcube_file);
// read XOFFS from the primary header
dtmp = get_float_from_keyword(tmp, 1, "XOFFS");
// store the keyword value or 0 (if not present) in the fcube structure
if (isnan(dtmp))
fcube->xoffs = 0;
else
fcube->xoffs = (int)dtmp;
// read XOFFS from the primary header
dtmp = get_float_from_keyword(tmp, 1, "YOFFS");
// store the keyword value or 0 (if not present) in the fcube structure
if (isnan(dtmp))
fcube->yoffs = 0;
else
fcube->yoffs = (int)dtmp;
return 1;
}
/**
* The function creates and loads the segmentation image
* of a flux_cube file into a gsl_matrix_int structure.
*
* @param fcube_file - the file name of the fluxcube
*
* @return ret - pointer to the gsl_matrix_int structure
*/
gsl_matrix_int *
load_segmentation(const char fcube_file[])
{
gsl_matrix_int *segmentation;
gsl_matrix *dvals;
int i,j;
double diff;
// load the segmentation image into a gsl_matrix_(double)
dvals = FITSimage_to_gsl(fcube_file, 2, 1);
// add 0.5 to get proper rounding with (int)
gsl_matrix_add_constant (dvals, 0.5);
// allocate space for the integer matrix
segmentation = gsl_matrix_int_alloc(dvals->size1,dvals->size2);
// fill the integer matrix with values from the double matrix
for (i=0; i < (int)dvals->size1; i++)
{
for (j=0; j < (int)dvals->size2; j++)
{
gsl_matrix_int_set(segmentation, i, j, (int)gsl_matrix_get(dvals, i, j));
diff = gsl_matrix_get(dvals, i, j) - (double)gsl_matrix_int_get(segmentation, i, j);
if (diff > 0.6 || diff < 0.4)
fprintf(stdout, "diff %f; %f --> %i, (%i, %i)\n", diff, gsl_matrix_get(dvals, i, j), gsl_matrix_int_get(segmentation, i, j), i, j);
}
}
// free the space for the double matrix
gsl_matrix_free(dvals);
return segmentation;
}
/**
* The function creates and loads a fluximage structure
* from an extention of a fluxcube file.
*
* @param fcube_file - the file name of the fluxcube
* @param hdunum - the extension number to load in a fluximage
*
* @return fimage - pointer to the fluximage structure loaded
*/
flux_image *
load_fluximage(const char fcube_file[], int hdunum)
{
flux_image *fimage;
char tmp[MAXCHAR];
double wavelength;
strcpy(tmp, fcube_file);
// allocate space for the fluximage structure
fimage = (flux_image *)malloc(sizeof(flux_image));
// load the array from the specified extension number
fimage->flux = FITSimage_to_gsl(fcube_file, hdunum, 1);
// get the keyword "WAVELENG' from the specified extension number
wavelength = (double)get_float_from_keyword(tmp, hdunum, "WAVELENG");
// report an error in case that the extension does not have that keyword.
// Otherwise store its content in the fluximage structure
if (isnan(wavelength))
aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PETCONT: " "Missing keyword WAVELENGTH in fluxcube %s, extension %i!\n",
fcube_file, hdunum);
else
fimage->wavelength = wavelength;
return fimage;
}
/**
* The function analyzes the fluximages in a
* fluxcube structure and sorts their indices in
* ascending wavelength. The vector with the
* ordered indices is given back.
*
* @param fcube - the pointer to the fluxcube structure
*
*/
gsl_vector_int *
order_fluxims(flux_cube *fcube)
{
gsl_vector *fimage_wavelength;
gsl_vector_int *fimage_order;
int i, j, k;
// allocate space for the order vector
fimage_order = gsl_vector_int_alloc(fcube->n_fimage);
// put a default order in the vector
for (i=0; i<fcube->n_fimage; i++)
gsl_vector_int_set(fimage_order, i, i);
// order the wavelength
if (fcube->n_fimage > 1)
{
// create a vector for the wavelengths
fimage_wavelength = gsl_vector_alloc(fcube->n_fimage);
// set the first entry for the wavelength
gsl_vector_set(fimage_wavelength, 0, fcube->fluxims[0]->wavelength);
// go over all fluximages
for (i=1; i<fcube->n_fimage; i++)
{
// find the correct position of the fluximage
j=0;
while (j < i && gsl_vector_get(fimage_wavelength, j) <= fcube->fluxims[i]->wavelength)
j++;
// check whether the correct poition of the fluximage is at the end
if (j == i)
{
// append the fluximage at the end
gsl_vector_set(fimage_wavelength, j, fcube->fluxims[i]->wavelength);
gsl_vector_int_set(fimage_order, j, i);
}
else
{
// move all fluximages one index up
for (k=i; k > j; k--)
{
gsl_vector_set(fimage_wavelength, k, gsl_vector_get(fimage_wavelength, k-1));
gsl_vector_int_set(fimage_order, k, gsl_vector_int_get(fimage_order, k-1));
}
// place the flux image at the correct position
gsl_vector_set(fimage_wavelength, j, fcube->fluxims[i]->wavelength);
gsl_vector_int_set(fimage_order, j, i);
}
}
// release the space for the wavelength vector
gsl_vector_free(fimage_wavelength);
}
// return the order vector
return fimage_order;
}
/**
* The function releases the space allocated
* for a fluxcube structure.
*
* @param fcube - the pointer to the fluxcube structure
*
*/
void
free_fluxcube(flux_cube *fcube)
{
int i;
// free the segmentation matrix
gsl_matrix_int_free(fcube->segmentation);
// free the wavelength order vector
gsl_vector_int_free(fcube->fimage_order);
// go over the fluximages, and free them
for (i=0; i < fcube->n_fimage; i++)
free_fluximage(fcube->fluxims[i]);
// free the fluximage vector
free(fcube->fluxims);
// free the fluximage order vector
// gsl_vector_int_free(fcube->fimage_order);
// free the fluxcube
free(fcube);
// set the fluxcube to NULL
fcube=NULL;
}
/**
* The function releases the space allocated
* for a fluximage structure.
*
* @param fimage - the pointer to the fluximage structure
*
*/
void
free_fluximage(flux_image *fimage)
{
// free the flux matrix
gsl_matrix_free(fimage->flux);
// free the fluximage
free(fimage);
// set the fluximage to NULL
fimage=NULL;
}
/**
* The function transforms a pixel coordinate point in a
* flt image into an pixel coordinate point in the associated
* fluxcube image
*
* @param fcube - the fluxcube structure
* @param flt_point - pixel coordinate point in the flt-image
*
* @return fcube_point - the pixel coordinate in the fluxcube
*/
d_point
flt_to_fcube_trans(const flux_cube *fcube, const d_point flt_point)
{
d_point fcube_point;
fcube_point.x = flt_point.x - (double)fcube->xoffs;
fcube_point.y = flt_point.y - (double)fcube->yoffs;
return fcube_point;
}
/**
* The function transforms an image coordinate point in a
* fluxcube into an image coo point in the associated
* flt image
*
* @param fcube - the fluxcube structure
* @param fcube_point - image-coo in the fcube
*
* @return flt_point - the image coo in the flt
*/
d_point
fcube_to_flt_trans(const flux_cube *fcube, const d_point fcube_point)
{
d_point flt_point;
flt_point.x = fcube_point.x + (double)fcube->xoffs;
flt_point.y = fcube_point.y + (double)fcube->yoffs;
return flt_point;
}
/**
* The function converts the information stored in the segmenation
* matrix of a fluxcube and the object list to a list of direct objects
*
* @param fcube - the fluxcube structure
* @param oblist - the object list
*
* @return dirlist - the dirobject list created
*/
dirobject **
fluxcube_to_dirlist(const flux_cube *fcube, object **oblist)
{
dirobject **dirlist;
dirobject *actdir;
//px_point fcube_point;
px_point flt_point;
d_point tmp1, tmp2;
int iact=0;
int nobjects=0;
int ndir=0;
int i, j;
int objindex;
//int itmp=0;
// determine the number of objects in the object list
nobjects = object_list_size(oblist);
// allocate space for the dirobject list
dirlist = (dirobject **) malloc((nobjects+1) * sizeof(dirobject *));
if (dirlist == NULL)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"fluxcube_to_dirlist:" " Could not allocate"
" memory for pointers to %i dirobject objects", nobjects+1);
// initialize the number of direct object
// and set the first item to NULL
ndir=0;
dirlist[ndir]=NULL;
// if (nobjects < 1)
// return dirlist;
// go over each column in the segmentation image
for (i=0; i < (int)fcube->segmentation->size1; i++)
{
// go over each row in the segmentation image
for (j=0; j < (int)fcube->segmentation->size2; j++)
{
// get the pixel value in the segmentation image
iact = gsl_matrix_int_get(fcube->segmentation, i, j);
// do something if the pixel is part of an object
if (iact > 0)
{
// transform the cooridnates from the fcube-system
// into the flt system
tmp1.x = (double)i;
tmp1.y = (double)j;
tmp2 = fcube_to_flt_trans(fcube, tmp1);
flt_point.x = (int)tmp2.x;
flt_point.y = (int)tmp2.y;
// try to get a dirobject for that object (=pixel value)
actdir = get_dirobject_from_list(dirlist, iact);
// check whether a dirobject just exists
if (actdir != NULL)
{
// udate an existing object
update_dirobject(actdir, flt_point);
}
else
{
// find the the object index for a (hypotetical) new dirobject
objindex = find_object_in_object_list(oblist, iact);
// check whether object exists in oblist
if (objindex >-1)
{
// create a new dirobject and enhance the counter
dirlist[ndir++] = dirobject_from_segpoint(flt_point, oblist[objindex]);
// set the actually last dirobject to NULL
// to get a properly closed list at all time
dirlist[ndir]=NULL;
}
}
}
}
}
// return the direct object list
return dirlist;
}
/**
* The function creates a a dirobject on the basis
* of an object and the pixel coos of a point
* which is part of that object.
*
* @param flt_point - the fluxcube structure
* @param actobject - the object list
*
* @return dirobject - the dirobject created
*/
dirobject *
dirobject_from_segpoint(const px_point flt_point, const object *actobject)
{
dirobject *actdir;
// allocate space for the dirobject
actdir = (dirobject *) malloc (sizeof (dirobject));
if (actdir == NULL)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"fill_dirobject:" " Could not allocate"
" memory for a dirobject object");
// transfer refpoint and ID
actdir->ID = actobject->ID;
actdir->refpoint.x = actobject->beams[0].refpoint.x;
actdir->refpoint.y = actobject->beams[0].refpoint.y;
// derive and store min/max in x/y for the corners
actdir->ix_min = flt_point.x;
actdir->ix_max = flt_point.x;
actdir->iy_min = flt_point.y;
actdir->iy_max = flt_point.y;
// derive the distortion scales along the major an minor axis
actdir->drzscale.x = 1.0;
actdir->drzscale.y = 1.0;
// set the variable
actdir->bb_sed = 0;
// make it a dummy
actdir->SED = NULL;
// return the new dirobject
return actdir;
}
/**
* The function updates a dirobject with a point
* belonging to the same object. The new point
* may extend the object size.
*
* @param actdir - the direct object
* @param flt_point - the new coordinate point
*
*/
void
update_dirobject(dirobject *actdir, const px_point flt_point)
{
// check whether the new points extends the
// old min/max values in x or y.
// correct the values if necessary.
actdir->ix_min = MIN(actdir->ix_min, flt_point.x);
actdir->ix_max = MAX(actdir->ix_max, flt_point.x);
actdir->iy_min = MIN(actdir->iy_min, flt_point.y);
actdir->iy_max = MAX(actdir->iy_max, flt_point.y);
}
/**
* The function computes and stores at the according position
* the xy offsets of a direct image. This is only important
* in the fluxcube emission model, since the image coordinates
* in fluxcubes are 'filter' coordinates and do not take into
* account the offsets introduce by the grism.
* For each object and beam those offsets are evaluated
* and stored in the direct object structure.
*
* @param dirlist - the direct object
* @param CONF_file - the new coordinate point
*
*/
void fill_xy_offsets(dirobject **dirlist, char CONF_file[])
{
aperture_conf *conf;
gsl_vector *x_coeffs;
gsl_vector *y_coeffs;
d_point m_point;
//double xoffs, yoffs;
int beamID=0;
int i;
// load the configuration file
conf = get_aperture_descriptor (CONF_file);
// go over each beam defined in the configuration
// file
for (beamID=0; beamID < conf->nbeams; beamID++)
{
// determine the coeeficients for the offsets
// in x and in y
x_coeffs = get_beam_trace_xoff (CONF_file, beamID);
y_coeffs = get_beam_trace_yoff (CONF_file, beamID);
// go over each direct object
i=0;
while (dirlist[i] !=NULL)
{
// get the mean direct object position
m_point = get_dirobject_meanpos(dirlist[i]);
// evaluate the coefficients for the 2D variable offsets
// at the mean position
dirlist[i]->xy_off[beamID].x = eval_trace_off_at_pos (x_coeffs, m_point, beamID);
dirlist[i]->xy_off[beamID].y = eval_trace_off_at_pos (y_coeffs, m_point, beamID);
// iterate the counter
i++;
}
// free the vectors for the coefficients
gsl_vector_free(x_coeffs);
gsl_vector_free(y_coeffs);
}
// release memory
free_aperture_conf(conf);
}
/**
* The function fills the flux information from a point in
* a fluxcube structure into the flux part of a direct object.
*
* @param fcube - the fluxcube structure
* @param point - the position to take the flux from
* @param actdir - the direct object to update
*
*/
void fill_fluxvalues(const flux_cube *fcube, const px_point point,
dirobject *actdir, const int inter_type)
{
energy_distrib *sed;
double *sed_wavs;
double *sed_flux;
int i;
int iact;
sed = (energy_distrib*) malloc(sizeof(energy_distrib));
sed_wavs = (double*) malloc(fcube->n_fimage*sizeof(double));
sed_flux = (double*) malloc(fcube->n_fimage*sizeof(double));
if (actdir->SED)
free_enerdist (actdir->SED);
// go over each fluximage in the fluxcube structure
for (i=0; i < fcube->n_fimage; i++)
{
// determine the index of the next fluximage
iact = gsl_vector_int_get(fcube->fimage_order, i);
// transfer the wavelength and flux from the fluxcube
sed_wavs[i] = fcube->fluxims[iact]->wavelength;
sed_flux[i] = gsl_matrix_get(fcube->fluxims[iact]->flux, point.x, point.y);
}
sed->npoints = fcube->n_fimage;
sed->wavelength = sed_wavs ;
sed->flux = sed_flux;
if (fcube->n_fimage > 1)
{
if (inter_type == 2)
sed->interp = gsl_interp_alloc (gsl_interp_polynomial, (size_t)fcube->n_fimage);
else if (inter_type == 3)
sed->interp = gsl_interp_alloc (gsl_interp_cspline, (size_t)fcube->n_fimage);
else
sed->interp = gsl_interp_alloc (gsl_interp_linear, (size_t)fcube->n_fimage);
sed->accel = gsl_interp_accel_alloc ();
gsl_interp_init (sed->interp, sed->wavelength, sed->flux, (size_t)sed->npoints);
}
else
{
sed->interp = NULL;
sed->accel= NULL;
}
// transfer the SED;
// announce the SED
actdir->SED = sed;
actdir->bb_sed = 1;
}
/**
* The function prints the main properties of a
* fluxcube structure onto the screen.
* This is mostly for debuggin/development
* purposes, and not for production
*
* @param fcube - the fluxcube structure
*
*/
void
print_fluxcube(const flux_cube *fcube)
{
int i;
fprintf(stdout, "XOFFS,YOFFS: %i,%i\n", fcube->xoffs, fcube->yoffs);
fprintf(stdout, "Number of flux-extension: %i\n", fcube->n_fimage);
for (i=0; i<fcube->n_fimage; i++)
fprintf(stdout, "Wavelength for flux extension %i: %f\n", i,
fcube->fluxims[gsl_vector_int_get(fcube->fimage_order,i)]->wavelength);
}
| {
"alphanum_fraction": 0.6505242895,
"avg_line_length": 26.6051212938,
"ext": "c",
"hexsha": "49c9017ada67b082824c8f3ef1450da62862c7d9",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spc_fluxcube.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/spc_fluxcube.c",
"max_line_length": 143,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spc_fluxcube.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5442,
"size": 19741
} |
/*
* gslrandomgen.h
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* Interface to GSL Random Number Generators
*
*/
#ifndef GSLRANDOMGEN_H
#define GSLRANDOMGEN_H
// C++ includes:
#include <cassert>
#include <list>
#include <string>
// Generated includes:
#include "config.h"
// Includes from librandom:
#include "random_datums.h"
#include "randomgen.h"
// Includes from sli:
#include "dictdatum.h"
// essential GSL includes or replacements
// GSL Versions < 1.2 have weak MT seeding
#ifdef HAVE_GSL
// "Real" version in presence of GSL
// External includes:
#include <gsl/gsl_rng.h>
namespace librandom
{
/**
* class GslRandomGen
* C++ wrapper for GSL/GSL-style generators.
* @note
* This class should only be used within librandom.
*
* @ingroup RandomNumberGenerators
*/
class GslRandomGen : public RandomGen
{
friend class GSL_BinomialRandomDev;
public:
explicit GslRandomGen( const gsl_rng_type*, //!< given RNG, given seed
unsigned long );
~GslRandomGen();
//! Add all GSL RNGs to rngdict
static void add_gsl_rngs( Dictionary& );
RngPtr
clone( unsigned long s )
{
return RngPtr( new GslRandomGen( rng_type_, s ) );
}
private:
void seed_( unsigned long );
double drand_( void );
private:
gsl_rng_type const* rng_type_;
gsl_rng* rng_;
};
inline void
GslRandomGen::seed_( unsigned long s )
{
gsl_rng_set( rng_, s );
}
inline double
GslRandomGen::drand_( void )
{
return gsl_rng_uniform( rng_ );
}
//! Factory class for GSL-based random generators
class GslRNGFactory : public GenericRNGFactory
{
public:
GslRNGFactory( gsl_rng_type const* const );
RngPtr create( unsigned long ) const;
private:
//! GSL generator type information
gsl_rng_type const* const gsl_rng_;
};
}
#else
// NO GSL Available---Implement class as empty shell
namespace librandom
{
class GslRandomGen : public RandomGen
{
public:
//! Add all GSL RNGs to rngdict
//! Do nothing if GSL not available
static void
add_gsl_rngs( Dictionary& )
{
}
private:
GslRandomGen()
{
assert( false );
}
~GslRandomGen()
{
assert( false );
}
};
}
#endif
#endif
| {
"alphanum_fraction": 0.7017419125,
"avg_line_length": 18.385620915,
"ext": "h",
"hexsha": "a120dc4accf2293420bf97a5cd2987a3a35ae18e",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z",
"max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_forks_repo_path": "NEST-14.0-FPGA/librandom/gslrandomgen.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster",
"max_issues_repo_path": "NEST-14.0-FPGA/librandom/gslrandomgen.h",
"max_line_length": 72,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_stars_repo_path": "NEST-14.0-FPGA/librandom/gslrandomgen.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z",
"num_tokens": 738,
"size": 2813
} |
// Copyright (c) 2021 Stig Rune Sellevag
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef SCILIB_LINALG_BLAS2_MATRIX_VECTOR_PRODUCT_H
#define SCILIB_LINALG_BLAS2_MATRIX_VECTOR_PRODUCT_H
#ifdef USE_MKL
#include <mkl.h>
#else
#include <cblas.h>
#endif
#include <scilib/mdarray.h>
#include <scilib/linalg_impl/lapack_types.h>
#include <experimental/mdspan>
#include <cassert>
#include <complex>
#include <type_traits>
#include <iostream>
namespace Sci {
namespace Linalg {
namespace stdex = std::experimental;
template <class T_a,
stdex::extents<>::size_type nrows_a,
stdex::extents<>::size_type ncols_a,
class Layout_a,
class Accessor_a,
class T_x,
stdex::extents<>::size_type ext_x,
class Layout_x,
class Accessor_x,
class T_y,
stdex::extents<>::size_type ext_y,
class Layout_y,
class Accessor_y>
requires(!std::is_const_v<T_y>)
inline void matrix_vector_product(
stdex::mdspan<T_a, stdex::extents<nrows_a, ncols_a>, Layout_a, Accessor_a>
a,
stdex::mdspan<T_x, stdex::extents<ext_x>, Layout_x, Accessor_x> x,
stdex::mdspan<T_y, stdex::extents<ext_y>, Layout_y, Accessor_y> y)
{
static_assert(x.static_extent(0) == a.static_extent(1));
using size_type = stdex::extents<>::size_type;
for (size_type i = 0; i < a.extent(0); ++i) {
y(i) = T_y{0};
for (size_type j = 0; j < a.extent(1); ++j) {
y(i) += a(i, j) * x(j);
}
}
}
template <class Layout>
inline void matrix_vector_product(Sci::Matrix_view<double, Layout> a,
Sci::Vector_view<double, Layout> x,
Sci::Vector_view<double, Layout> y)
{
static_assert(x.static_extent(0) == a.static_extent(1));
constexpr double alpha = 1.0;
constexpr double beta = 0.0;
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
const BLAS_INT incx = static_cast<BLAS_INT>(x.stride(0));
const BLAS_INT incy = static_cast<BLAS_INT>(y.stride(0));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
}
cblas_dgemv(matrix_layout, CblasNoTrans, m, n, alpha, a.data(), lda,
x.data(), incx, beta, y.data(), incy);
}
template <class Layout>
inline void matrix_vector_product(Sci::Matrix_view<const double, Layout> a,
Sci::Vector_view<const double, Layout> x,
Sci::Vector_view<double, Layout> y)
{
static_assert(x.static_extent(0) == a.static_extent(1));
constexpr double alpha = 1.0;
constexpr double beta = 0.0;
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
const BLAS_INT incx = static_cast<BLAS_INT>(x.stride(0));
const BLAS_INT incy = static_cast<BLAS_INT>(y.stride(0));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
}
cblas_dgemv(matrix_layout, CblasNoTrans, m, n, alpha, a.data(), lda,
x.data(), incx, beta, y.data(), incy);
}
#ifdef USE_MKL
// Does not work with OpenBLAS version 0.2.14.1
template <class Layout>
inline void
matrix_vector_product(Sci::Matrix_view<std::complex<double>, Layout> a,
Sci::Vector_view<std::complex<double>, Layout> x,
Sci::Vector_view<std::complex<double>, Layout> y)
{
static_assert(x.static_extent(0) == a.static_extent(1));
constexpr std::complex<double> alpha = {1.0, 0.0};
constexpr std::complex<double> beta = {0.0, 0.0};
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
const BLAS_INT incx = static_cast<BLAS_INT>(x.stride(0));
const BLAS_INT incy = static_cast<BLAS_INT>(y.stride(0));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
}
cblas_zgemv(matrix_layout, CblasNoTrans, m, n, &alpha, a.data(), lda,
x.data(), incx, &beta, y.data(), incy);
}
template <class Layout>
inline void
matrix_vector_product(Sci::Matrix_view<const std::complex<double>, Layout> a,
Sci::Vector_view<const std::complex<double>, Layout> x,
Sci::Vector_view<std::complex<double>, Layout> y)
{
static_assert(x.static_extent(0) == a.static_extent(1));
constexpr std::complex<double> alpha = {1.0, 0.0};
constexpr std::complex<double> beta = {0.0, 0.0};
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
const BLAS_INT incx = static_cast<BLAS_INT>(x.stride(0));
const BLAS_INT incy = static_cast<BLAS_INT>(y.stride(0));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
}
cblas_zgemv(matrix_layout, CblasNoTrans, m, n, &alpha, a.data(), lda,
x.data(), incx, &beta, y.data(), incy);
}
#endif
template <class T, class Layout, class Allocator>
inline Sci::Vector<T, Layout, Allocator>
matrix_vector_product(const Sci::Matrix<T, Layout, Allocator>& a,
const Sci::Vector<T, Layout, Allocator>& x)
{
Sci::Vector<T, Layout, Allocator> res(a.extent(0));
matrix_vector_product(a.view(), x.view(), res.view());
return res;
}
template <class T, class Layout, class Allocator>
inline void matrix_vector_product(const Sci::Matrix<T, Layout, Allocator>& a,
const Sci::Vector<T, Layout, Allocator>& x,
Sci::Vector<T, Layout, Allocator>& res)
{
assert(res.size() == a.extent(0));
matrix_vector_product(a.view(), x.view(), res.view());
}
} // namespace Linalg
} // namespace Sci
#endif // SCILIB_LINALG_BLAS2_MATRIX_VECTOR_PRODUCT_H
| {
"alphanum_fraction": 0.6380034209,
"avg_line_length": 33.4947916667,
"ext": "h",
"hexsha": "93ff8d84a9ac44dc701fcaea28a567b77bff0f55",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "stigrs/scilib",
"max_forks_repo_path": "include/scilib/linalg_impl/blas2_matrix_vector_product.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "stigrs/scilib",
"max_issues_repo_path": "include/scilib/linalg_impl/blas2_matrix_vector_product.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stigrs/scilib",
"max_stars_repo_path": "include/scilib/linalg_impl/blas2_matrix_vector_product.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1754,
"size": 6431
} |
/****************************************************************************
* *
* Copyright (C) 2001 ~ 2016 Neutrino International Inc. *
* *
* Author : Brian Lin <lin.foxman@gmail.com>, Skype: wolfram_lin *
* *
* QtFFT acts as an interface between Qt and FFT libraries. *
* Please keep QtFFT as simple as possible. *
* *
* Qt Version : 5.4.1 *
* CIOS Version : 1.6.0 *
* *
****************************************************************************/
#ifndef QT_FFT_H
#define QT_FFT_H
#include <QtCore>
#include <QtNetwork>
#include <QtSql>
#ifndef QT_STATIC
#include <QtScript>
#endif
#include <Essentials>
#ifdef QT_QTGMP_LIB
#include <QtGMP>
#endif
#ifdef QT_QTGSL_LIB
#include <QtGSL>
#endif
#ifdef QT_QTCUDA_LIB
#include <QtCUDA>
#endif
extern "C" {
#include <gsl/gsl_wavelet.h>
#include <gsl/gsl_wavelet2d.h>
#include <gsl/gsl_fft.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_fft_complex_float.h>
#include <gsl/gsl_fft_halfcomplex.h>
#include <gsl/gsl_fft_halfcomplex_float.h>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_real_float.h>
#include <QtFFT/fftw3.h>
}
QT_BEGIN_NAMESPACE
#ifndef QT_STATIC
# if defined(QT_BUILD_QTFFT_LIB)
# define Q_FFT_EXPORT Q_DECL_EXPORT
# else
# define Q_FFT_EXPORT Q_DECL_IMPORT
# endif
#else
# define Q_FFT_EXPORT
#endif
namespace N
{
class Q_FFT_EXPORT Wavelet ;
class Q_FFT_EXPORT Hankel ;
class Q_FFT_EXPORT AbstractFFT ;
class Q_FFT_EXPORT CooleyFFT ;
class Q_FFT_EXPORT KissFFT ;
class Q_FFT_EXPORT GSLFFT ;
class Q_FFT_EXPORT FFTW ;
class Q_FFT_EXPORT AccelerateFFT ;
class Q_FFT_EXPORT Wavelet
{
public:
gsl_wavelet * wavelet ;
gsl_wavelet_workspace * work ;
gsl_wavelet_direction direction ;
explicit Wavelet (void) ;
virtual ~Wavelet (void) ;
bool allocate (const gsl_wavelet_type * T,size_t k) ;
bool workspace (size_t n) ;
QString Name (void) ;
int Transform (double * data,size_t stride,size_t n) ;
int TransformForward (double * data,size_t stride,size_t n) ;
int TransformInverse (double * data,size_t stride,size_t n) ;
int Transform2d (double * data,size_t tda,size_t size1,size_t size2) ;
int Transform2dForward (double * data,size_t tda,size_t size1,size_t size2) ;
int Transform2dInverse (double * data,size_t tda,size_t size1,size_t size2) ;
int TransformMatrix (gsl_matrix * m) ;
int TransformMatrixForward (gsl_matrix * m) ;
int TransformMatrixInverse (gsl_matrix * m) ;
int nsTransform (double * data,size_t tda,size_t size1,size_t size2) ;
int nsTransformForward (double * data,size_t tda,size_t size1,size_t size2) ;
int nsTransformInverse (double * data,size_t tda,size_t size1,size_t size2) ;
int nsTransformMatrix (gsl_matrix * m) ;
int nsTransformMatrixForward (gsl_matrix * m) ;
int nsTransformMatrixInverse (gsl_matrix * m) ;
protected:
private:
};
class Q_FFT_EXPORT Hankel
{
public:
gsl_dht * hankel ;
explicit Hankel (void) ;
explicit Hankel (int size) ;
explicit Hankel (int size,double nu, double xmax) ;
Hankel (const Hankel & hankel) ;
virtual ~Hankel (void) ;
bool Allocate (int size) ;
bool New (int size,double nu, double xmax) ;
int Initialize (double nu,double xmax) ;
int Apply (double * In,double * Out) ;
double x (int n) ;
double k (int n) ;
protected:
private:
};
class Q_FFT_EXPORT AbstractFFT
{
public:
typedef enum {
fftForward = 0 ,
fftBackward = 1 }
TransformDirection ;
TransformDirection direction ;
Cpp::ValueTypes vType ;
int sourceType ; // 0 - Undecided , 1 - Real , 2 - Complex
int targetType ; // 0 - Undecided , 1 - Real , 2 - Complex
int dimension ;
explicit AbstractFFT (void);
virtual ~AbstractFFT (void);
virtual int type (void) const = 0 ;
virtual bool isSupported (Cpp::ValueTypes type,int dimension) const = 0 ;
virtual int AllocateSource (CUIDs elements,QByteArray & Source) = 0 ;
virtual int AllocateTarget (CUIDs elements,QByteArray & Target) = 0 ;
virtual bool Prepare (CUIDs elements ,
VarArgs & Paraments ,
QByteArray & Source ,
QByteArray & Target ) = 0 ;
virtual void Execution (void) = 0 ;
protected:
private:
};
class Q_FFT_EXPORT CooleyFFT : public AbstractFFT
{
public:
explicit CooleyFFT (void) ;
virtual ~CooleyFFT (void) ;
virtual int type (void) const ;
virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;
virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;
virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;
virtual bool Prepare (CUIDs elements ,
VarArgs & Paraments ,
QByteArray & Source ,
QByteArray & Target ) ;
virtual void Execution (void) ;
protected:
private:
};
class Q_FFT_EXPORT KissFFT : public AbstractFFT
{
public:
explicit KissFFT (void) ;
virtual ~KissFFT (void) ;
virtual int type (void) const ;
virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;
virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;
virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;
virtual bool Prepare (CUIDs elements ,
VarArgs & Paraments ,
QByteArray & Source ,
QByteArray & Target ) ;
virtual void Execution (void) ;
protected:
private:
};
class Q_FFT_EXPORT GSLFFT : public AbstractFFT
{
public:
explicit GSLFFT (void) ;
virtual ~GSLFFT (void) ;
virtual int type (void) const ;
virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;
virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;
virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;
virtual bool Prepare (CUIDs elements ,
VarArgs & Paraments ,
QByteArray & Source ,
QByteArray & Target ) ;
virtual void Execution (void) ;
protected:
private:
};
class Q_FFT_EXPORT FFTW : public AbstractFFT
{
public:
explicit FFTW (void) ;
virtual ~FFTW (void) ;
virtual int type (void) const ;
virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;
virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;
virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;
virtual bool Prepare (CUIDs elements ,
VarArgs & Paraments ,
QByteArray & Source ,
QByteArray & Target ) ;
virtual void Execution (void) ;
void Cleanup (void);
fftw_complex * array (int size);
fftw_complex * fromByteArray (int & size,QByteArray & Array);
QByteArray toByteArray (fftw_complex * complex,int size);
void Execute (const fftw_plan plan);
void Destroy (fftw_plan plan);
fftw_plan Frequency (int N,double * data,fftw_complex * dout,unsigned int flags = FFTW_MEASURE) ;
void Retrieve (int component,int index,int length,double * data,fftw_complex * dout) ;
void Execute (const fftwf_plan plan);
void Destroy (fftwf_plan plan);
#ifndef DISABLE_FFTW_LDOUBLE
void Execute (const fftwl_plan plan);
void Destroy (fftwl_plan plan);
#endif
protected:
fftw_plan fftplan ;
fftwf_plan fftfplan ;
#ifndef DISABLE_FFTW_LDOUBLE
fftwl_plan fftlplan ;
#endif
private:
int fftSize (int fft,int length) ;
int fftSize (int fft,CUIDs elements) ;
};
class Q_FFT_EXPORT AccelerateFFT : public AbstractFFT
{ // Apple iPhone OS Accelerate Framework
public:
explicit AccelerateFFT (void) ;
virtual ~AccelerateFFT (void) ;
virtual int type (void) const ;
virtual bool isSupported (Cpp::ValueTypes T,int dimension) const ;
virtual int AllocateSource (CUIDs elements,QByteArray & Source) ;
virtual int AllocateTarget (CUIDs elements,QByteArray & Target) ;
virtual bool Prepare (CUIDs elements ,
VarArgs & Paraments ,
QByteArray & Source ,
QByteArray & Target ) ;
virtual void Execution (void) ;
protected:
private:
};
}
QT_END_NAMESPACE
Q_DECLARE_METATYPE(N::Wavelet)
Q_DECLARE_METATYPE(N::Hankel)
Q_DECLARE_METATYPE(N::CooleyFFT)
Q_DECLARE_METATYPE(N::KissFFT)
Q_DECLARE_METATYPE(N::GSLFFT)
Q_DECLARE_METATYPE(N::FFTW)
Q_DECLARE_METATYPE(N::AccelerateFFT)
Q_DECLARE_INTERFACE(N::AbstractFFT , "com.neutrino.math.fft" )
#endif
| {
"alphanum_fraction": 0.5498985605,
"avg_line_length": 31.0840840841,
"ext": "h",
"hexsha": "d0ce83806b61aaf63d8e15bb19385f557de02e67",
"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": "add93f193c2fcfbd56df8e360cfee6d7ccab6cef",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Vladimir-Lin/QtFFT",
"max_forks_repo_path": "include/QtFFT/qtfft.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "add93f193c2fcfbd56df8e360cfee6d7ccab6cef",
"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": "Vladimir-Lin/QtFFT",
"max_issues_repo_path": "include/QtFFT/qtfft.h",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "add93f193c2fcfbd56df8e360cfee6d7ccab6cef",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Vladimir-Lin/QtFFT",
"max_stars_repo_path": "include/QtFFT/qtfft.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2343,
"size": 10351
} |
/**
* Original Author:
* * author: Jochen K"upper
* * created: April 2002
*
* author: Pierre Schnizer
* created: December 2003
* file: pygsl/src/simanmodule.c
* $Id: simanmodule.c,v 1.9 2008/10/25 20:45:04 schnizer Exp $
*
* Jochen K"upper wrote the original version of this module. In December 2003 I
* rewrote it. Now I only support the variable type as it is more pythonic.
*
*/
#include <Python.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <setjmp.h>
#include <gsl/gsl_siman.h>
#include <gsl/gsl_nan.h>
#include <pygsl/error_helpers.h>
#include <pygsl/general_helpers.h>
#include <pygsl/rng.h>
#include <pygsl/rng_helpers.h>
/*
* Common to all objects of one problem
* Currently the individual method pointers are not used. Instead the method
* is resolved every time. Do you know which method is faster? Is it advicable
* to resolve it once and store it here? Pierre
*/
typedef struct{
/*
PyObject * efunc;
PyObject * step;
PyObject * metric;
PyObject * print;
*/
PyObject * rng;
jmp_buf buffer;
}pygsl_siman_func_t;
/*
* The Linked list keeping the reference to the individual objects.
*
* Necessary as I have to use longjmp as the current implementation does
* not allow error propagation yet!
*/
struct _pygsl_siman_t{
pygsl_siman_func_t *func;
PyObject * x;
struct _pygsl_siman_t * prev;
struct _pygsl_siman_t * next;
};
typedef struct _pygsl_siman_t pygsl_siman_t;
static const char module_doc[] = "C Implementation needed for the siman module.";
static PyObject *module = NULL;
static const char filename[] = __FILE__;
/*
* Naming of the various methods the object has provide as callbacks.
*/
static const char EFunc_name[] = "EFunc";
static const char Metric_name[] = "Metric";
static const char Step_name[] = "Step";
static const char Clone_name[] = "Clone";
static const char Print_name[] = "Print";
/*
* Get a callable method from a object.
*
* Basically it is a flat wrapper around PyObject_GetAttrString but
* checks if the method is callable and adds a Traceback frame
*
* Flag usage:
* flag == 1 Must exist and must be callable
* flag == 2 If it exists it must be callable
*
* For the traceback frame all arguments following the module are needed.
* If you do not know the module, you can pass a NULL pointer.
*/
static PyObject *
PyGSL_get_callable_method(PyObject *o, const char * attr, int flag, PyObject *module,
const char * filename, const char * func_name,
int lineno)
{
PyObject * method = NULL;
FUNC_MESS_BEGIN();
method = PyObject_GetAttrString(o, (char *) attr);
if(method == NULL){
if(flag == 1){
PyGSL_add_traceback(module, filename, func_name, lineno);
}else if(flag == 2){
/* Clear the error otherwise it will show up later on! */
PyErr_Clear();
}
return NULL;
}
if(!(PyCallable_Check(method))) {
/* I must add the method name! I must change it to an more descriptive exception! */
PyGSL_add_traceback(module, (const char *) filename, func_name, lineno);
PyErr_SetString(PyExc_TypeError, "Found a attribute which was not callable!"
"XXX must add the method name!");
return NULL;
}
DEBUG_MESS(2, "Found a method at %p", (void *) method);
FUNC_MESS_END();
return method;
}
/* This function type should return the energy of a configuration XP. */
static double
PyGSL_siman_efunc(void *xp)
{
PyObject *result = NULL, *callback = NULL, *arglist = NULL;
PyGSL_error_info info;
pygsl_siman_t *x;
int flag=GSL_EFAILED;
double value;
/* static char *functionname = __FUNCTION__; */
FUNC_MESS_BEGIN();
assert(xp);
x = (pygsl_siman_t *) xp;
DEBUG_MESS(2, "Found a pygsl_siman_t at %p and a pygsl_siman_func_t at %p and x at %p",
(void *)x, (void *) x->func, (void *) x->x);
assert(x);
assert(x->func);
callback = PyGSL_get_callable_method(x->x, EFunc_name, 1, module, filename, __FUNCTION__, __LINE__);
if(callback == NULL)
goto fail;
info.callback = callback;
info.message = __FUNCTION__;
info.error_description = "and the description ???";
info.argnum = 1;
arglist = PyTuple_New(0);
result = PyEval_CallObject(callback, arglist);
Py_DECREF(arglist);
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 1, &info)) != GSL_SUCCESS){
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
goto fail;
}
if((flag = PyGSL_PYFLOAT_TO_DOUBLE(result, &value, &info)) != GSL_SUCCESS){
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
goto fail;
}
Py_DECREF(result);
FUNC_MESS_END();
return value;
fail:
FUNC_MESS("In Fail");
Py_XDECREF(result);
longjmp(x->func->buffer, flag);
return GSL_NAN;
}
/*
* This function type should modify the configuration XP using a random step
* taken from the generator R, up to a maximum distance of STEP_SIZE.
*/
static void
PyGSL_siman_step(const gsl_rng *r, void *xp, double step_size)
{
PyObject *result = NULL, *arglist = NULL, *callback = NULL;
PyGSL_error_info info;
pygsl_siman_t *x;
int flag=GSL_EFAILED;
/* static const char * functionname = __FUNCTION__; */
FUNC_MESS_BEGIN();
x = (pygsl_siman_t *) xp;
DEBUG_MESS(2, "Found x at %p", xp);
callback = PyGSL_get_callable_method(x->x, Step_name, 1, module, filename, __FUNCTION__, __LINE__);
if(callback == NULL)
goto fail;
info.callback = callback;
info.message = __FUNCTION__;
info.error_description = "???";
info.argnum = 1;
assert(PyGSL_RNG_Check(x->func->rng));
assert(((PyGSL_rng *) x->func->rng)->rng == r);
/* create argument list */
arglist = PyTuple_New(2);
PyTuple_SET_ITEM(arglist, 0, x->func->rng);
Py_INCREF(x->func->rng); /* Don't forget tuple is owner! */
PyTuple_SET_ITEM(arglist, 1, PyFloat_FromDouble(step_size));
result = PyEval_CallObject(callback, arglist);
Py_DECREF(arglist);
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 0, &info)) != GSL_SUCCESS){
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
goto fail;
}
Py_DECREF(result);
FUNC_MESS_END();
return;
fail:
FUNC_MESS("In Fail");
Py_XDECREF(result);
longjmp(x->func->buffer, flag);
return;
}
/* This function type should return the distance between two configurations XP
and YP. */
static double
PyGSL_siman_metric(void *xp, void *yp)
{
PyObject *result = NULL, *arglist = NULL, *callback = NULL;
PyGSL_error_info info;
pygsl_siman_t *x, *y;
int flag=GSL_EFAILED;
double value;
/* static const char * functionname = __FUNCTION__; */
FUNC_MESS_BEGIN();
x = (pygsl_siman_t *) xp;
y = (pygsl_siman_t *) yp;
DEBUG_MESS(2, "Found x at (%p,%p) and y at (%p %p)",
(void *) x, (void *)x->x, (void *) y, (void *) y->x);
assert(x);
assert(y);
assert(x->x);
assert(y->x);
callback = PyGSL_get_callable_method(x->x, Metric_name, 1, module, filename, __FUNCTION__, __LINE__);
if(callback == NULL)
goto fail;
info.callback = callback;
info.message = __FUNCTION__;
info.error_description = "???";
info.argnum = 1;
arglist = PyTuple_New(1);
PyTuple_SET_ITEM(arglist, 0, y->x);
Py_INCREF(y->x); /* Tuple is owner! */
result = PyEval_CallObject(callback, arglist);
Py_XDECREF(arglist);
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 0, &info)) != GSL_SUCCESS){
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
goto fail;
}
if((flag = PyGSL_PYFLOAT_TO_DOUBLE(result, &value, &info)) != GSL_SUCCESS){
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
goto fail;
}
Py_DECREF(result);
FUNC_MESS_END();
return value;
fail:
FUNC_MESS("In Fail");
Py_XDECREF(result);
longjmp(x->func->buffer, flag);
return GSL_NAN;
}
/* This function type should print the contents of the configuration XP. */
static void
PyGSL_siman_print(void *xp)
{
PyObject *result = NULL, *callback=NULL, *arglist=NULL;
PyGSL_error_info info;
pygsl_siman_t *x;
int flag=GSL_EFAILED;
/* static const char * functionname = __FUNCTION__; */
FUNC_MESS_BEGIN();
x = (pygsl_siman_t *) xp;
callback = PyGSL_get_callable_method(x->x, Print_name, 1, module, filename, __FUNCTION__, __LINE__);
if(callback == NULL)
goto fail;
info.callback = callback;
info.message = __FUNCTION__;
info.error_description = "what goes here ???";
info.argnum = 1;
arglist = PyTuple_New(0);
result = PyEval_CallObject(callback, arglist);
Py_DECREF(arglist);
if((flag = PyGSL_CHECK_PYTHON_RETURN(result, 0, &info)) != GSL_SUCCESS){
PyGSL_add_traceback(module, (const char*)filename, __FUNCTION__, __LINE__);
goto fail;
}
Py_DECREF(result);
FUNC_MESS_END();
return;
fail:
FUNC_MESS("In Fail");
Py_XDECREF(result);
longjmp(x->func->buffer, flag);
return;
}
/*
* As Python is generating the new objects I can not skip the reference
* counting, but must add a reference for each object in construct and
* depose it here and in the siman_destroy function.
*
* siman_solve will call siman_release_x anyway at the end to clear up
* all objects. Necessary to non existing error propagation in the siman
* module.
*/
static void
PyGSL_siman_copy(void *src, void *dst)
{
PyObject *callback=NULL, *new = NULL, *arglist = NULL;
PyGSL_error_info info;
pygsl_siman_t *x, *y;
int flag=GSL_EFAILED;
/* static const char * functionname = __FUNCTION__; */
FUNC_MESS_BEGIN();
x = (pygsl_siman_t *) src;
y = (pygsl_siman_t *) dst;
DEBUG_MESS(2, "Got source at %p, Destination at %p", (void *) x, (void *) y);
assert(x->x);
callback = PyGSL_get_callable_method(x->x, Clone_name, 1, module, filename, __FUNCTION__, __LINE__);
if(callback == NULL)
goto fail;
arglist = PyTuple_New(0);
new = PyEval_CallObject(callback, arglist);
Py_DECREF(arglist);
info.callback = callback;
info.message = __FUNCTION__;
info.error_description = "???";
info.argnum = 1;
if((flag = PyGSL_CHECK_PYTHON_RETURN(new, 1, &info)) != GSL_SUCCESS){
PyGSL_add_traceback(module, (const char*)filename, __FUNCTION__, __LINE__);
goto fail;
}
Py_XDECREF(y->x);
/* Py_INCREF(new); Necessary? I don't think so. */
y->x = new;
FUNC_MESS_END();
return;
fail:
FUNC_MESS("Fail");
Py_XDECREF(new);
longjmp(x->func->buffer, flag);
}
static void *
PyGSL_siman_copy_construct(void *new)
{
pygsl_siman_t * ret, * n, *p;
int flag = GSL_ENOMEM;
FUNC_MESS_BEGIN();
n = (pygsl_siman_t *) new;
/* The pointers next and prev are checked against NULL */
ret = (pygsl_siman_t *) calloc(1, sizeof(pygsl_siman_t));
DEBUG_MESS(2, "New was %p, Constructed a new object at %p", new, (void *) ret);
if(ret == NULL){
pygsl_error("Could not allocate the object for the linked list",
filename, __LINE__ - 3, GSL_ENOMEM);
goto fail;
}
/* Put the Link to the old object so that I can clone when I need to copy */
ret->x = n->x;
/* Eventually I will dispose the object */
Py_INCREF(ret->x);
/* Pointer to the func struct. This information is the same for all objects */
ret->func = n->func;
/* Find the first open object in the linked list ... */
p = n;
while(p->next != NULL){
p = p->next;
}
DEBUG_MESS(2, "I found a open object at %p", (void *) p);
/* and connect the links */
p->next = ret;
ret->prev = p;
FUNC_MESS_END();
return ret;
fail:
FUNC_MESS("Fail");
longjmp(n->func->buffer, flag);
return NULL;
}
static void
PyGSL_siman_destroy(void * old)
{
pygsl_siman_t * o;
FUNC_MESS_BEGIN();
o = (pygsl_siman_t *) old;
assert(o);
/* fprintf(stderr, "Destroying: Previous object = %p, Next Object = %p\n",
(void *)o->prev, (void *)o->next); */
/* Reconnect the linked list */
if (o->prev && o->next){
/* Connect the both */
o->prev->next = o->next;
o->next->prev = o->prev;
}
else if (o->prev && o->next == NULL){
/* Prev last element. Terminate the list */
o->prev->next = NULL;
}
else if (o->prev == NULL && o->next == NULL){
/* Last Element, better to leave it */
DEBUG_MESS(2, "I do not dispose the last element %p!", (void *) o);
return;
}
/* Dispose the object */
Py_XDECREF(o->x);
free(o);
FUNC_MESS_END();
}
/* Clean up of the linked list of objects */
int
PyGSL_siman_release_x(pygsl_siman_t * myargs, pygsl_siman_t * x)
{
pygsl_siman_t *p=NULL;
FUNC_MESS_BEGIN();
p = myargs;
/* fprintf(stderr, "Releasing list!\n"); */
while(1){
/* fprintf(stderr, "Previous object = %p, Next Object = %p\n",
(void *)p->prev, (void *)p->next); */
/* Don't delete the object containing the result! */
if(p != x){
/* fprintf(stderr, "Deleting object at %p\n", (void *) p); */
PyGSL_siman_destroy((void *) p);
}
if(p->next == NULL)
break;
p = p->next;
}
FUNC_MESS_END();
return GSL_SUCCESS;
}
static const char pygsl_siman_solve_doc[] =
"Simulated annealing driver.\n\
\n\
Usage:\n\
result = solve(r, x0, ...)\n\
\n\
Input:\n\
r ... a random generator from pygsl.rng\n\
x0 ... a configuration. It must be an object providing the following\n\
methods:\n\
EFunc()\n\
Metric()\n\
Step()\n\
Clone()\n\
If you want to use the print functionality you must provide\n\
the following method:\n\
Print()\n\
\n\
Output:\n\
result ... a object of type x0 with the final value.\n\
\n\
Keywords:\n\
n_tries = 200 ... how many points to try for each step\n\
iters_fixed_T = 10 ... how many iterations at each temperature?\n\
step_size = 10 ... max step size in the random walk\n\
\n\
parameters for the Boltzmann distribution\n\
k = 1.0 ... Boltzmann constant\n\
t_initial = 0.002 ... initial temperature\n\
mu_t = 1.005 ... damping factor for the temperature\n\
t_min = 2.0e-6\n\
\n\
do_print = 0 ... print the status of the annealing process\n\
(== 0: do not print)\n\
( > 0: print)\n\
";
/* wrapper functions */
static PyObject *
PyGSL_siman_solve(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *result = NULL;
PyObject *efunc = NULL, *step = NULL, *metric = NULL, *clone = NULL,
*print = NULL, *r_o = NULL, *x_o=NULL;
gsl_rng *rng = NULL;
gsl_siman_print_t a_print= PyGSL_siman_print;
gsl_siman_params_t params = {200, 10, 10.0, 1.0, 0.002, 1.005, 2.0e-6};
pygsl_siman_func_t myargs_func = {NULL};
pygsl_siman_t myargs = {NULL, NULL, NULL, NULL};
/* static const char * functionname = __FUNCTION__; */
int flag=GSL_EFAILED, do_print=0;
void * x0 = NULL;
static const char * kwlist[] = {"rng", "x0", "n_tries", "iters_fixed_T", "step_size", "k",
"t_initial", "mu_t", "t_min", "do_print", NULL};
FUNC_MESS_BEGIN();
/* python arguments are (rng, x0, settings) */
if(! PyArg_ParseTupleAndKeywords(args, kw, "OO|iidddddi", (char **) kwlist, &r_o, &x_o,
¶ms.n_tries, ¶ms.iters_fixed_T, ¶ms.step_size,
¶ms.k, ¶ms.t_initial, ¶ms.mu_t, ¶ms.t_min, &do_print))
return NULL;
/* The following methods must exist */
efunc = PyGSL_get_callable_method(x_o, EFunc_name, 1, module, filename, __FUNCTION__, __LINE__);
step = PyGSL_get_callable_method(x_o, Step_name, 1, module, filename, __FUNCTION__, __LINE__);
metric = PyGSL_get_callable_method(x_o, Metric_name, 1, module, filename, __FUNCTION__, __LINE__);
clone = PyGSL_get_callable_method(x_o, Clone_name, 1, module, filename, __FUNCTION__, __LINE__);
if( efunc == NULL || step == NULL || metric == NULL || clone == NULL){
return NULL;
}
/* optional print */
if(do_print == 0){
a_print = NULL;
} else {
print = PyGSL_get_callable_method(x_o, Print_name, 1, module, filename, __FUNCTION__, __LINE__);
if(print == NULL){
DEBUG_MESS(2, "Did not get a print method! print = %p", print);
a_print = NULL;
return NULL;
}
}
rng = PyGSL_gsl_rng_from_pyobject(r_o);
if(rng == NULL){
return NULL;
}
/* initialize/assign functions */
Py_INCREF(x_o);
/*
myargs_func.efunc = efunc;
myargs_func.step = step;
myargs_func.metric = metric;
myargs_func.print = print;
*/
myargs_func.rng = r_o;
myargs.func = &myargs_func;
myargs.x = x_o;
myargs.prev = NULL;
myargs.next = NULL;
x0 = (void *) &myargs;
DEBUG_MESS(2, "x0 @ %p; myargs at %p; myargs_func at %p", x0, (void *) &myargs, (void *) &myargs_func);
DEBUG_MESS(2, "Found a pygsl_siman_t at %p and a pygsl_siman_func_t at %p",
(void *) x0,
(void *) (((pygsl_siman_t *) x0)->func));
if((flag = setjmp(myargs_func.buffer)) == 0){
FUNC_MESS("Starting siman");
gsl_siman_solve(rng, x0, PyGSL_siman_efunc, PyGSL_siman_step,
PyGSL_siman_metric, a_print, PyGSL_siman_copy,
PyGSL_siman_copy_construct, PyGSL_siman_destroy,
0, /* Only variable mode supported by this wrapper. */
params);
FUNC_MESS("End siman");
}else{
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
goto fail;
}
Py_DECREF(x_o);
DEBUG_MESS(2, "I found x0 at %p", x0);
result = ((pygsl_siman_t *) x0)->x;
PyGSL_siman_release_x(&myargs, x0);
FUNC_MESS_END();
return result;
fail:
FUNC_MESS("In Fail");
PyGSL_siman_release_x(&myargs, x0);
Py_XDECREF(x_o);
PyGSL_error_flag(flag);
return NULL;
}
/* module initialization */
static PyMethodDef simanMethods[] = {
{"solve", (PyCFunction) PyGSL_siman_solve,
METH_VARARGS | METH_KEYWORDS, (char *) pygsl_siman_solve_doc},
{NULL, NULL} /* Sentinel */
};
DL_EXPORT(void) init_siman(void)
{
PyObject *m = NULL;
FUNC_MESS_BEGIN();
m = Py_InitModule("_siman", simanMethods);
module = m;
init_pygsl();
import_pygsl_rng();
FUNC_MESS_END();
return;
}
/*
* Local Variables:
* mode: C
* c-file-style: "python"
* End:
*/
| {
"alphanum_fraction": 0.6714811668,
"avg_line_length": 26.2332838039,
"ext": "c",
"hexsha": "7accc521496ed465f6bc464e936132f262e97494",
"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/simanmodule.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/simanmodule.c",
"max_line_length": 104,
"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/simanmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5165,
"size": 17655
} |
/////////////////
//example25.5.c
/////////////////
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
#include <math.h>
typedef struct{
double *a; //y=a[0]x[0]+a[1]x[1]+...a[ka]y[ka]+b[0]u[0]+b[1]u[1]+...+b[kb]u[kb]
// double *a; //y[t+1]=a[0]y[t]+a[1]y[t-1]+...a[ka]y[t-ka]+b[0]u[t]+b[1]u[t-1]+...+b[kb]u[t-kb]
double *b;
double *x;
double *u;
int k,kx,ku;
double xmax;
double umax;
double y;
int _dim;
double *_y;
double *_y_err;
// double *_dydt_in;
// double *_dydt_out;
double h;
double _t;
} LINEAR;
//#define dim_linear 4
//int linearfunc (double t, const double y[], double f[], void *params)
//{
// LINEAR *c = (LINEAR *)params;
// f[0] = y[1];
// f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;
// f[2] = y[3];
// f[3] = (c->F+c->T*sin(y[0]))/c->M;
// return GSL_SUCCESS;
//}
////////////////
#define square(x) ((x)*(x))
LINEAR linear;
int PLANT_NO=1;
int initialize()
{
if(PLANT_NO==1){
linear.kx=1;
linear.ku=1;
linear.k=linear.kx+linear.ku;
linear.a=(double*)malloc(sizeof(double)*linear.k);
linear.b=&linear.a[linear.kx];
linear.x=(double*)malloc(sizeof(double)*linear.k+1);
linear.u=&linear.x[linear.kx];
linear.a[0]=0.9;
linear.b[0]=1;
}
else if(PLANT_NO==2){
linear.kx=3;
linear.ku=1;
linear.k=linear.kx+linear.ku;
linear.a=(double*)malloc(sizeof(double)*linear.k);
linear.b=&linear.a[linear.kx];
linear.x=(double*)malloc(sizeof(double)*linear.k+1);
linear.u=&linear.x[linear.kx];
linear.a[0]=1;
linear.a[1]=1;
linear.a[2]=1;
linear.b[0]=1;
}
linear.umax=6.0;//check// linear.Fmax=30;//check
int i;for(i=0;i<linear.kx;i++) linear.x[i]=0;
#ifdef LINEARSUB
// linear.Fmax=_linear_Fmax;//check// linear.Fmax=30;//check
// linear.xmax=20.0;//check// linear.Fmax=30;//check
if(_AP_umax>0) AP_u_max=linear.umax=_AP_umax;
else AP_u_max=linear.umax;
AP_u_min=-AP_u_max;
rr=AP_r=_AP_r;//10
rr_kyoyou=_rr_kyoyou;
C_MODE=11;
#else
linear.h=0.01;
#endif
linear._t=0;
// int i;for(i=0;i<linear._dim;i++) linear._dydt_in[i]=0;
return(0);
}
#ifndef LINEARSUB
char *fn="linear2io.dat";
FILE *fp;
#endif//#ifndef LINEARSUB
double plant(double uu)
{
//store previous x and u
int i;
for(i=0;i<linear.kx-1;i++) linear.x[i+1]=linear.x[i];
for(i=0;i<linear.ku-1;i++) linear.u[i+1]=linear.u[i];
//store former output
linear.x[0]=linear.y;
//current input
if(uu>linear.umax) linear.u[0]=linear.umax;
else if(uu<-linear.umax) linear.u[0]=-linear.umax;
else linear.u[0]=uu;
// current output
linear.y=0;
for(i=0;i<linear.k;i++) linear.y+=linear.a[i]*linear.x[i];
linear._t++;
// fprintf(stdout,"y%g=(%g)*(%g)+(%g)*(%g) %g %g %g\n",linear.y,linear.a[0],linear.x[0],linear.a[1],linear.x[1],uu,linear.u[0],linear.x[1]);
#ifndef LINEARSUB
fprintf(fp,"%g %g %g %g", linear._t,linear.y,linear.u[0],linear.x[0]);//linear.a,linear.da
// fprintf(fp,"%.7e %.7e %.7e %.7e", linear._t,linear.y,linear.x[0],linear.u[0]);//linear.a,linear.da
fprintf(fp,"\n");
#endif
return(linear.y);
// return(linear.X);
}
#ifndef LINEARSUB
int main()
{
////////////////////////////////////////////////////
/// method 1 ///
/// input ddX ///
/// output a,x,y,F ///
////////////////////////////////////////////////////
// double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1;
double t0=5; //stationary
double t1=5.0+t0;//accelerate(speed up)
double t2=2.0+t1;//free run
double t3=5.0+t2;//decelerate(slow down)
double t4=20+t3; //free run
initialize();
linear.h=1;
int M=(t4/linear.h)+1;
double *uu=(double*)malloc(sizeof(double)*M);
double uumax=20;//
int n;
double t;
////////////////////////////////////////////////////
/// set ddX ///
////////////////////////////////////////////////////
int n0 =t0/linear.h+0.5, n4=t4/linear.h+0.5;
for(t=0;t<t4;t+=linear.h){
n=t/linear.h;
if(t<=t0) uu[n]=0; //zero
else if(t<=t1) uu[n]=uumax/(t1-t0); //accelerate
else if(t<=t2) uu[n]=0; //free move
else if(t<=t3) uu[n]=-uumax/(t3-t2);//decelerate
else uu[n]=0; //free move
// fprintf(stdout,"uu[%d]=%e\n",n,uu[n]);
}
////////////////////////////////////////////////////
/// Solve by the Runge Kutta Method of GSL ///
////////////////////////////////////////////////////
fp=fopen(fn,"w");
fprintf(fp,"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,a[0]-a[3]\n",linear.h,n0,n4,linear.a[0],linear.a[1],linear.a[2],linear.a[3]);
fprintf(fp,"#t,y,x,u\n");
for(t=0;t<t4;t+=linear.h){
n=t/linear.h;
plant(uu[n]);
}
fclose(fp);
fprintf(stdout,"Results are stored in '%s'.\n",fn);
return 0;
}
#endif //#ifndef SUB
| {
"alphanum_fraction": 0.5224423777,
"avg_line_length": 27.7865168539,
"ext": "c",
"hexsha": "8db9775ca496da104a34c4d5e777ec5f2f23d46f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z",
"max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_forks_repo_licenses": [
"CECILL-B"
],
"max_forks_repo_name": "Kurogi-Lab/CAN2",
"max_forks_repo_path": "1021/mspc/linear1sub.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CECILL-B"
],
"max_issues_repo_name": "Kurogi-Lab/CAN2",
"max_issues_repo_path": "1021/mspc/linear1sub.c",
"max_line_length": 143,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_stars_repo_licenses": [
"CECILL-B"
],
"max_stars_repo_name": "Kurogi-Lab/CAN2",
"max_stars_repo_path": "1021/mspc/linear1sub.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1771,
"size": 4946
} |
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_cblas.h>
#include "motionControl.h"
void printMatrix(gsl_matrix* m, int row, int col) {
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
printf("%g ", gsl_matrix_get(m, i, j));
}
printf("\n");
}
}
gsl_matrix* measurementMatrix() {
gsl_matrix *m = gsl_matrix_alloc (3, 3);
gsl_matrix_set (m, 0, 0, -.5);
gsl_matrix_set (m, 0, 1, .866);
gsl_matrix_set (m, 0, 2, (.866*6.9282 - -.5*4));
gsl_matrix_set (m, 1, 0, -.5);
gsl_matrix_set (m, 1, 1, -.866);
gsl_matrix_set (m, 1, 2, (.866*6.9282 - -.5*4));
gsl_matrix_set (m, 2, 0, 1);
gsl_matrix_set (m, 2, 1, 0);
gsl_matrix_set (m, 2, 2, 8);
return m;
}
gsl_matrix* rotationMatrix(float omegaWorld, float omegaBody) {
gsl_matrix *m = gsl_matrix_alloc (3, 3);
float theta = omegaWorld - omegaBody; // TODO check if radians or degrees
gsl_matrix_set (m, 0, 0, cos(theta));
gsl_matrix_set (m, 0, 1, sin(theta));
gsl_matrix_set (m, 0, 2, 0);
gsl_matrix_set (m, 1, 0, -sin(theta));
gsl_matrix_set (m, 1, 1, cos(theta));
gsl_matrix_set (m, 1, 2, 0);
gsl_matrix_set (m, 2, 0, 0);
gsl_matrix_set (m, 2, 1, 0);
gsl_matrix_set (m, 2, 2, 1);
return m;
}
gsl_matrix* pointToVelocity(float cX, float cY, float cOmega, float dX, float dY, float dOmega, float time) { //d stands for desired
gsl_matrix *m = gsl_matrix_alloc (3, 1);
float vX = (dX - cX) / time;
float vY = (dY - cY) / time;
float omega = (dOmega - cOmega) / time;
gsl_matrix_set (m, 0, 0, vX);
gsl_matrix_set (m, 1, 0, vY);
gsl_matrix_set (m, 2, 0, omega);
return m;
}
gsl_matrix* linearToAngular(gsl_matrix* R, gsl_matrix* M, gsl_matrix* V) {
gsl_matrix_transpose(R);
int signum;
gsl_matrix * inverseR = gsl_matrix_alloc (3, 3);
gsl_permutation * perm = gsl_permutation_alloc (3);
gsl_linalg_LU_decomp (M, perm, &signum);
gsl_linalg_LU_invert (M, perm, inverseR);
gsl_matrix_mul_elements (inverseR, M);
gsl_matrix* result = inverseR;
float omega1 = rowSum(result, V, 0);
float omega2 = rowSum(result, V, 1);
float omega3 = rowSum(result, V, 2);
gsl_matrix * final = gsl_matrix_alloc (3, 1);
gsl_matrix_set (final, 0, 0, omega1);
gsl_matrix_set (final, 1, 0, omega2);
gsl_matrix_set (final, 2, 0, omega3);
gsl_matrix_free(inverseR);
gsl_permutation_free(perm);
return final;
}
float rowSum(gsl_matrix* result, gsl_matrix* V, int row) {
float sum = 0;
for(int i = 0; i < 3; i++) {
sum += gsl_matrix_get(result, row, i) * gsl_matrix_get(V, i, 0);
}
return sum;
}
int main (void) {
gsl_matrix* M = measurementMatrix();
gsl_matrix* R = rotationMatrix(1, 2);
gsl_matrix* V = pointToVelocity(0, 0, 0, 1, 1, 0, 1);
gsl_matrix* final = linearToAngular(R, M, V);
printMatrix(final, 3, 1);
gsl_matrix_free (M);
gsl_matrix_free (R);
gsl_matrix_free (V);
gsl_matrix_free (final);
return 0;
}
| {
"alphanum_fraction": 0.6122384274,
"avg_line_length": 26.5042016807,
"ext": "c",
"hexsha": "2ee4cef488591f1c53305b995ff28db3136a9119",
"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": "260805b87f3d890cbcb892121261baa5038e65c8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nagneeve/ecen490",
"max_forks_repo_path": "motionControl/motionControl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "260805b87f3d890cbcb892121261baa5038e65c8",
"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": "nagneeve/ecen490",
"max_issues_repo_path": "motionControl/motionControl.c",
"max_line_length": 132,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "260805b87f3d890cbcb892121261baa5038e65c8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nagneeve/ecen490",
"max_stars_repo_path": "motionControl/motionControl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1100,
"size": 3154
} |
/*
* Copyright (c) 2018-2021 Aleksas Mazeliauskas, Stefan Floerchinger,
* Eduardo Grossi, and Derek Teaney
* All rights reserved.
*
* FastReso is distributed under MIT license;
* see the LICENSE file that should be present in the root
* of the source distribution, or alternately available at:
* https://github.com/amazeliauskas/FastReso/
*/
#ifndef FASTFO_TParticle_h
#define FASTFO_TParticle_h
#include <string>
#include <vector>
#include <math.h>
#include <vector>
#include <string>
#include <iostream>
#include <grid_params.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
//! Enum class for deciding on Bose-Einstein, Fermi-Dirac or Botlzmann particle dsitribution
enum class EParticleType : int { kBoson = 1, kFermion = -1, kBoltzman = 0 };
enum class EFjIndex : int {
kFeq1 = 0,
kFeq2 = 1,
kFshear1 = 2,
kFshear2 = 3,
kFshear3 = 4,
kFbulk1 = 5,
kFbulk2 = 6,
kFtemp1 = 7,
kFtemp2 = 8,
kFvel1 = 9,
kFvel2 = 10,
kFvel3 = 11 };
//! Particle class with basic properties and universal decay spectra components
class TParticle {
protected:
//! Particle properties
std::string fParticleName; // particle name
std::string fDescription; // particle name
std::string fDescriptionHeader; // particle name
std::string fHeader = "1:pbar [GeV]\t2:m [GeV]";
std::vector<std::string> fComponentNames = {"Feq 1", "Feq 2","Fshear 1","Fshear 2","Fshear 3","Fbulk 1","Fbulk 2","Ftemp 1","Ftemp 2","Fvel 1","Fvel 2","Fvel 3"};
//std::string fHeader = "1:pbar [GeV]\t2:m [GeV]\t3:feq 1\t4:feq 2\t5:fshear 1\t6:fshear 2\t7:fshear 3\t8:fbulk 1\t9:fbulk 2\t10:ftemperature 1\t11:ftemperature 2\t12:fvelocity 1\t13:fvelocity 2\t14:fvelocity 3";
// particle name
double fMass; // [GeV] resonance mass
double fGamma; // [GeV] resonance width (currently not used)
double fIsospin; // isospin J |J,m>
int fPDGCode; // number code according to PDG
int fNu; // degeneracy of a particle
double fQB; // baryon charge
double fQS; // strange charge
double fQC; // charme charge
EParticleType fParticleType; // particle statistic (bose-einstein, fermi-dirac, boltzmann)
double fTfo;
double fNtotal; //integrated particle number
double fNtotal_buffer;
//! Grid and interpolator for decay spectra components
const gsl_interp_type *fSpline_type = gsl_interp_cspline;
double fPbar_arr[grid_params::fNpbar]; // array of fluid restframe momentum
double fFj_arr[grid_params::fNf][grid_params::fNpbar]; // array of scalar functions Fj
double fFj_arr_buffer[grid_params::fNf][grid_params::fNpbar]; // buffer array of scalar functions Fj
gsl_spline *fSpline_Fj[grid_params::fNf] ;
gsl_interp_accel *fPbar_acc;
//! Bool variables to control data read in/out-put
bool fIsLocked = false; //if true, prevent modifying fFj_arr data
bool fIsModified[grid_params::fNf]; //if true, require initilization of interpolator
//! After any update of the grid, don't forget to reinitialized the interpolator!
//! initiliazes the interpolator
void init_grid(std::string comps="Feq Fshear Fbulk Ftemp Fvel");
void init(int j);
public:
std::vector <EFjIndex> fComponents;
//! Contructor with particle properties
~TParticle() ;
//! return parameters about the particle
std::string getName() {return fParticleName;};
double getM() {return fMass;};
double getGamma() {return fGamma;};
double getQB() {return fQB;};
double getQS() {return fQS;};
double getQC() {return fQC;};
double getIsospin() {return fIsospin;};
double getN() {return fNtotal;};
int getNu() {return fNu;};
int getPDG() {return fPDGCode;};
EParticleType getType() {return fParticleType;};
//! increment integrated particle number
void addN(double n) {
if (fIsLocked){
std::cerr << "\033[1mTParticle.h\033[0m : \033[1;31merror\033[0m : attemped to modify locked "<< fParticleName <<" data" << std::endl;
exit(EXIT_FAILURE);}
else { fNtotal+=n; fNtotal_buffer+=n; }};
//! set initial thermal temperature
void setTfo(double Tfo) {fTfo=Tfo;};
//! set lock on data modification
void lock() {fIsLocked=true;};
bool hasdecayed() {return fIsLocked;};
//! clean the buffer
void clean_buffer() {
for(int i = 0; i <grid_params::fNpbar; i++){
for (int jj=0; jj<grid_params::fNf; jj++){
fFj_arr_buffer[jj][i]=0.0;
}
fNtotal_buffer=0.0; }
};
//! return the energy and momentum of grid point i
double getEbar(int i) {return sqrt(fMass*fMass+getPbar(i)*getPbar(i));};
double getPbar(int i) {return fPbar_arr[i];};
//! Return the number of momentum grid points
int getNpbar() {return grid_params::fNpbar;};
//! Return of the initialization/freeze-out temperature
double getTfo() {return fTfo;};
//! increment Fj array at cite i by F
void addFj(int j, int i, double F) {
if (fIsLocked){
std::cerr << "\033[1mTParticle.h\033[0m : \033[1;31merror\033[0m : attemped to modify locked "<< fParticleName <<" data" << std::endl;
exit(EXIT_FAILURE);}
else {
fFj_arr[j][i]+=F;
fFj_arr_buffer[j][i]+=F;
fIsModified[j]=true;
}
};
//! Returns the universal scalar functions Fj at Ebar
double get_Fj(int j, double Ebar);
//Routines to print the data to screen or file
std::string getDescriptionHeader(){ return fDescriptionHeader;};
std::string getDescription(){return fDescription;};
void print();
void print(std::string tag);
void print_buffer();
void print_buffer(std::string tag);
};
#endif
| {
"alphanum_fraction": 0.6630113142,
"avg_line_length": 37.5490196078,
"ext": "h",
"hexsha": "60d6aa7b5cb720dec9f0c6df02d294b4c721168c",
"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": "a694de368e79e3d21afa5d57b47209d5c9c55ed9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "amazeliauskas/FastReso",
"max_forks_repo_path": "TParticle.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9",
"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": "amazeliauskas/FastReso",
"max_issues_repo_path": "TParticle.h",
"max_line_length": 216,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "amazeliauskas/FastReso",
"max_stars_repo_path": "TParticle.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-22T14:25:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-11T02:48:59.000Z",
"num_tokens": 1737,
"size": 5745
} |
#pragma once
#include <glm/glm.hpp>
#include <gsl/gsl>
#include <optional>
namespace rev {
struct Segment {
glm::vec3 start;
glm::vec3 end;
};
struct Ray {
glm::vec3 origin;
glm::vec3 direction;
};
struct Sphere {
glm::vec3 center;
float radius;
};
template <typename VertexRange, typename SegmentVisitor>
void iteratePolygonVertices(const VertexRange& vertices, SegmentVisitor&& visitor)
{
Expects(vertices.size() >= 3);
auto begin = std::begin(vertices);
auto end = std::end(vertices);
auto segmentStart = begin;
auto segmentEnd = begin + 1;
while (segmentStart != end) {
if (segmentEnd == end) {
segmentEnd = begin;
}
visitor(Segment{ *segmentStart, *segmentEnd });
segmentStart++;
segmentEnd++;
}
}
class NullPolygonBuilder {
public:
void addVertex(const glm::vec3& vertex) {}
};
template <typename IteratorType>
class OutputIteratorPolygonBuilder {
public:
OutputIteratorPolygonBuilder(IteratorType iterator)
: _iter(iterator)
{
}
void addVertex(const glm::vec3& vertex)
{
*_iter = vertex;
_iter++;
}
IteratorType getIterator() const { return _iter; }
private:
IteratorType _iter;
};
struct AxisAlignedPlane {
struct Hit {
glm::vec3 intersectionPoint;
float t;
};
Hit intersect(const Ray& ray) const
{
float boundaryDelta = boundary - ray.origin[dimensionIndex];
float t = boundaryDelta / ray.direction[dimensionIndex];
glm::vec3 intersectPoint = ray.origin + (t * ray.direction);
// Avoid floating point error along the boundary dimension.
intersectPoint[dimensionIndex] = boundary;
return { intersectPoint, t };
}
glm::vec3 intersect(const Segment& segment) const
{
glm::vec3 direction = segment.end - segment.start;
auto [intersectionPoint, t] = intersect(Ray{ segment.start, direction });
if (!(t > 0.0f)) {
return segment.start;
} else if (!(t < 1.0f)) {
return segment.end;
}
for (size_t k = 0; k < 3; k++) {
if (segment.start[k] == segment.end[k]) {
intersectionPoint[k] = segment.start[k];
}
}
return intersectionPoint;
}
template <typename InputVertexRange, typename LeftBuilder, typename RightBuilder>
void splitConvexPolygon(const InputVertexRange& inputVertices, LeftBuilder&& leftBuilder,
RightBuilder&& rightBuilder) const
{
iteratePolygonVertices(
inputVertices, [this, &leftBuilder, &rightBuilder](const Segment& segment) {
float startPosition = segment.start[dimensionIndex];
float endPosition = segment.end[dimensionIndex];
bool emitIntersection = false;
if (startPosition < boundary) {
leftBuilder.addVertex(segment.start);
if (endPosition > boundary) {
emitIntersection = true;
}
} else if (startPosition > boundary) {
rightBuilder.addVertex(segment.start);
if (endPosition < boundary) {
emitIntersection = true;
}
} else {
// Right on the boundary.
leftBuilder.addVertex(segment.start);
rightBuilder.addVertex(segment.start);
}
if (emitIntersection) {
auto intersection = intersect(segment);
leftBuilder.addVertex(intersection);
rightBuilder.addVertex(intersection);
}
});
}
uint8_t dimensionIndex;
float boundary;
};
struct AxisAlignedBoundingBox {
void expandToVertex(const glm::vec3& vertex)
{
for (int k = 0; k < 3; k++) {
if (vertex[k] < minimum[k]) {
minimum[k] = vertex[k];
}
if (vertex[k] > maximum[k]) {
maximum[k] = vertex[k];
}
}
}
void expandToBox(const AxisAlignedBoundingBox& other)
{
for (int k = 0; k < 3; k++) {
if (other.minimum[k] < minimum[k]) {
minimum[k] = other.minimum[k];
}
if (other.maximum[k] > maximum[k]) {
maximum[k] = other.maximum[k];
}
}
}
void reduceToBox(const AxisAlignedBoundingBox& other)
{
for (int k = 0; k < 3; k++) {
if (other.minimum[k] > minimum[k]) {
minimum[k] = other.minimum[k];
}
if (other.maximum[k] < maximum[k]) {
maximum[k] = other.maximum[k];
}
Expects(!(minimum[k] > maximum[k]));
}
}
float getSurfaceArea() const
{
glm::vec3 diagonal = maximum - minimum;
float surfaceArea = 0.0f;
surfaceArea += diagonal.x * diagonal.y;
surfaceArea += diagonal.y * diagonal.z;
surfaceArea += diagonal.z * diagonal.z;
return 2.0f * surfaceArea;
}
float getVolume() const
{
glm::vec3 diagonal = maximum - minimum;
return diagonal.x * diagonal.y * diagonal.z;
}
std::array<AxisAlignedBoundingBox, 2> split(const AxisAlignedPlane& plane) const
{
Expects(!(plane.boundary < minimum[plane.dimensionIndex]));
Expects(!(plane.boundary > maximum[plane.dimensionIndex]));
std::array<AxisAlignedBoundingBox, 2> splitBoxes{ *this, *this };
splitBoxes[0].maximum[plane.dimensionIndex] = plane.boundary;
splitBoxes[1].minimum[plane.dimensionIndex] = plane.boundary;
return splitBoxes;
}
struct Hit {
glm::vec3 intersectionPoint;
float t;
uint8_t planeDimension;
};
bool containsPoint(const glm::vec3& point) const
{
for (int k = 0; k < 3; k++) {
if (point[k] < minimum[k]) {
return false;
}
if (point[k] > maximum[k]) {
return false;
}
}
return true;
}
bool intersectsSphere(const Sphere& sphere) const
{
float r2 = sphere.radius * sphere.radius;
for (size_t k = 0; k < 3; k++) {
if (sphere.center[k] < minimum[k]) {
float diff = minimum[k] - sphere.center[k];
r2 -= diff * diff;
} else if (sphere.center[k] > maximum[k]) {
float diff = sphere.center[k] - maximum[k];
r2 -= diff * diff;
}
}
return r2 > 0.0f;
}
std::optional<Hit> castExternalRay(const Ray& ray) const
{
for (uint8_t k = 0; k < 3; k++) {
float d = ray.direction[k];
if (d < 0.0f) {
float boundary = maximum[k];
if (ray.origin[k] > boundary) {
auto intersection = AxisAlignedPlane{ k, boundary }.intersect(ray);
if (containsPoint(intersection.intersectionPoint)) {
return Hit{ intersection.intersectionPoint, intersection.t, k };
}
}
} else if (d > 0.0f) {
float boundary = minimum[k];
if (ray.origin[k] < boundary) {
auto intersection = AxisAlignedPlane{ k, boundary }.intersect(ray);
if (containsPoint(intersection.intersectionPoint)) {
return Hit{ intersection.intersectionPoint, intersection.t, k };
}
}
}
}
return std::nullopt;
}
Hit castInternalRay(const Ray& ray) const
{
for (uint8_t k = 0; k < 3; k++) {
float d = ray.direction[k];
float boundary;
if (d < 0.0f) {
boundary = minimum[k];
} else if (d > 0.0f) {
boundary = maximum[k];
} else {
continue;
}
auto intersection = AxisAlignedPlane{ k, boundary }.intersect(ray);
if (containsPoint(intersection.intersectionPoint)) {
return Hit{ intersection.intersectionPoint, intersection.t, k };
}
}
throw std::runtime_error("Internal ray intersection not found.");
}
glm::vec3 minimum{ std::numeric_limits<float>::infinity() };
glm::vec3 maximum{ -std::numeric_limits<float>::infinity() };
};
template <typename VertexRange>
AxisAlignedBoundingBox smallestBoxContainingVertices(const VertexRange& range)
{
AxisAlignedBoundingBox box;
for (const auto& vertex : range) {
box.expandToVertex(vertex);
}
return box;
}
} | {
"alphanum_fraction": 0.5358792385,
"avg_line_length": 28.9153094463,
"ext": "h",
"hexsha": "362ae7a4a995f603449732efbbcaf712c98d1b12",
"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": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eyebrowsoffire/rev",
"max_forks_repo_path": "engine/include/rev/geometry/Tools.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "eyebrowsoffire/rev",
"max_issues_repo_path": "engine/include/rev/geometry/Tools.h",
"max_line_length": 93,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eyebrowsoffire/rev",
"max_stars_repo_path": "engine/include/rev/geometry/Tools.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1939,
"size": 8877
} |
#pragma once
#include <unordered_map>
#include <vector>
#include <gsl/gsl>
#include "huffman.h"
#include "interface.h"
#include "minqueue.h"
class statistics {
public:
size_t original;
size_t modified;
};
class huffman_encoder {
// Statistics of the current encoding.
statistics stats;
std::unordered_map<char, std::vector<int>> encoding;
std::unordered_map<char, int> count_chars(std::vector<char> buf);
void evaluate(minqueue_node* root, std::vector<int> encoding);
public:
huffman_encoder();
std::vector<int> encode(std::vector<char> buf);
void display_encoding();
void display_stats();
};
| {
"alphanum_fraction": 0.6854961832,
"avg_line_length": 18.7142857143,
"ext": "h",
"hexsha": "8a010ad971a854658095337e1288897f7a89f68d",
"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": "54660f62c6a7adf7dfb63388ed9e4f4e41306058",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joshleeb/Huffman",
"max_forks_repo_path": "src/huffman.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058",
"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": "joshleeb/Huffman",
"max_issues_repo_path": "src/huffman.h",
"max_line_length": 69,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "54660f62c6a7adf7dfb63388ed9e4f4e41306058",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joshleeb/Huffman",
"max_stars_repo_path": "src/huffman.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 151,
"size": 655
} |
/* roots/demo.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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 <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include "demof.h"
#include "demof.c"
int
main ()
{
int status;
int iterations = 0, max_iterations = 100;
gsl_root_fsolver *s;
double r = 0, r_expected = sqrt (5.0);
double x_lower x = 0.0, x_upper = 5.0;
gsl_function F;
struct quadratic_params params =
{1.0, 0.0, -5.0};
F.function = &quadratic;
F.params = ¶ms;
s = gsl_root_fsolver_alloc (gsl_root_fsolver_bisection);
gsl_root_fsolver_set (s, &F, x);
printf ("using %s method\n", gsl_root_fsolver_name (s));
printf ("%5s [%9s, %9s] %9s %9s %10s %9s\n",
"iter", "lower", "upper", "root", "actual", "err", "err(est)");
do
{
iterations++;
status = gsl_root_fsolver_iterate (s);
r = gsl_root_fsolver_root (s);
x_lower = gsl_root_fsolver_x_lower (s);
x_upper = gsl_root_fsolver_x_upper (s);
status = gsl_root_test_interval (x, 0, 0.001);
if (status == GSL_SUCCESS)
printf ("Converged:\n");
printf ("%5d [%.7f, %.7f] %.7f %.7f %+.7f %.7f\n",
iterations, x_lower, x_upper,
r, r_expected, r - r_expected, x_upper - x_lower);
}
while (status == GSL_CONTINUE && iterations < max_iterations);
}
| {
"alphanum_fraction": 0.660359508,
"avg_line_length": 30.2,
"ext": "c",
"hexsha": "07b0adaa54deb0b1f559df6fa64c294bdefdcbbf",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/demo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/demo.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/demo.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 627,
"size": 2114
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#define N 65536 //the final number of nodes
#define I 2 // the initial number of nodes
#define MI 0 //the initial trial number
#define MF 33 //(the final trial number) - 1
#define RS 35382 //seed of the random number generator
int main()
{
FILE *fp;
double delta=sqrt(1.5);
int tout[]={512,1024,2048,4096,8192,16384,32768,65536,131072};
int i,j,k,l,m,t,tt;
int tmp,flag;
int **nb; //neighbors of each node
int x; //new node
int vdx; //virtual degree of the node x
int *tmparr;
int z;
int nzsize;
int *nz;
int *deg; //degree of each node
double degav; //average degree
double *knn; //average degree of the nearest neighbors of each node
double *cc; //local clustering coefficient of each node
double ccav; //average local clustering coefficient
char filename[100];
const gsl_rng_type * TYPE;
gsl_rng * ran;
gsl_rng_env_setup();
TYPE=gsl_rng_default;
ran=gsl_rng_alloc(TYPE);
gsl_rng_set(ran,RS);
tmparr=malloc(sizeof(int)*N);
nz=malloc(sizeof(int)*N);
deg=malloc(sizeof(int)*N);
knn=malloc(sizeof(double)*N);
cc=malloc(sizeof(double)*N);
nb=malloc(sizeof(int*)*N);
for (i=0;i<N;i++){
nb[i]=malloc(sizeof(int)*N);
}
for (m=MI;m<MF;m++){
//generation of the initial network
for (i=0;i<I;i++){
deg[i]=0;
for (j=0;j<I;j++){
if (j!=i){
nb[i][deg[i]]=j;
deg[i]++;
}
}
}
tt=0;
for (t=I;t<N;t++){
//adding (t+1)-th node: copying degree step
x=(int)(gsl_rng_uniform(ran)*t);
vdx=1+(int)(gsl_rng_uniform(ran)*ceil(delta*deg[x]));
deg[t]=0;
/*//new OPA pre-adjunction rule
j=0;
for (i=0;i<t;i++){
if (vdx<=ceil(delta*deg[i])){
tmparr[j]=i;
j++;
}
}
z=tmparr[(int)(gsl_rng_uniform(ran)*j)];
nzsize=deg[z]+1;
for (i=0;i<nzsize-1;i++){
nz[i]=nb[z][i];
}
nz[nzsize-1]=z;
*/
/*//OPA pre-adjunction rule
nzsize=0;
for (i=0;i<t;i++){
if (vdx<=ceil(delta*deg[i])){
nz[nzsize]=i;
nzsize++;
}
}
*/
//OPA adjunction rule
tmp=t;
for (i=0;i<t;i++){
if (vdx<=ceil(delta*deg[i]) && deg[i]<tmp)tmp=deg[i];
}
nzsize=0;
for (i=0;i<t;i++){
if (deg[i]==tmp){
nz[nzsize]=i;
nzsize++;
}
}
//choosing the targets of the new node x
if (vdx>=nzsize){
for (i=0;i<nzsize;i++){
nb[nz[i]][deg[nz[i]]]=t; deg[nz[i]]++;
nb[t][deg[t]]=nz[i]; deg[t]++;
}
} else{
for (j=0;j<vdx;j++){
i=j+(int)(gsl_rng_uniform(ran)*(nzsize-j));
nb[nz[i]][deg[nz[i]]]=t; deg[nz[i]]++;
nb[t][deg[t]]=nz[i]; deg[t]++;
tmp=nz[j];
nz[j]=nz[i];
nz[i]=tmp;
}
}
//output
if (t+1==tout[tt]){
//degav
degav=0.0;
for (i=0;i<t+1;i++){
degav+=deg[i];
}
degav/=(t+1);
//knn
for (i=0;i<t+1;i++){
knn[i]=0.0;
for (j=0;j<deg[i];j++){
knn[i]+=deg[nb[i][j]];
}
if (deg[i]>0)knn[i]/=deg[i];
}
//cc
ccav=0.0;
for (i=0;i<t+1;i++){
tmp=0;
for (j=0;j<deg[i];j++){
for (k=j+1;k<deg[i];k++){
flag=0;
for (l=0;l<deg[nb[i][j]];l++){
if (nb[nb[i][j]][l]==nb[i][k]){
flag=1;
break;
}
}
if (flag==1)tmp++;
}
}
if (deg[i]>1)cc[i]=2.0*tmp/(deg[i]*(deg[i]-1));
else cc[i]=0.0;
ccav+=cc[i];
}
ccav/=(t+1);
sprintf(filename,"id-deg-knn-cc_t%d_trial%d.txt",t+1,m);
fp=fopen(filename,"w");
for (i=0;i<t+1;i++){
fprintf(fp,"%d %d %.15f %.15f\n",i,deg[i],knn[i],cc[i]);
}
fclose(fp);
printf("m=%d t=%d degav=%f ccav=%f\n",m,t+1,degav,ccav);
tt++;
}//end of output
}//end of t-loop
}//end of m-loop
free(tmparr);
free(nz);
free(deg);
free(knn);
free(cc);
for (i=0;i<N;i++){
free(nb[i]);
}
free(nb);
return 0;
}
| {
"alphanum_fraction": 0.4863493597,
"avg_line_length": 19.6161137441,
"ext": "c",
"hexsha": "9e0bcfd30ea60a0998e4b122374ca6a1db16c151",
"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": "f12494674e95d9b30c672c31e1ea59cfad8c1dea",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "taichiharuna/opa2",
"max_forks_repo_path": "data_opa1adj_delta_sqrt3-2/opa1adj_1.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f12494674e95d9b30c672c31e1ea59cfad8c1dea",
"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": "taichiharuna/opa2",
"max_issues_repo_path": "data_opa1adj_delta_sqrt3-2/opa1adj_1.c",
"max_line_length": 69,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f12494674e95d9b30c672c31e1ea59cfad8c1dea",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "taichiharuna/opa2",
"max_stars_repo_path": "data_opa1adj_delta_sqrt3-2/opa1adj_1.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1492,
"size": 4139
} |
#ifndef CLASS_H
#define CLASS_H
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <algorithm>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
//multivariate normal libraries
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
using namespace std;
int poisson(double lambda);
double expTrunc(double, double);
class Parameters { //store all parameters in one class to stop them being everywhere. Will also make it easier to change parameters when needed.
gsl_rng * rando;
const gsl_rng_type * T;
double lbda_original,v_to_h_original,sig_original; //original parameters stored so when changed from intervention still have in memory.
public:
Parameters(); //imports parameters from text file.
Parameters(int); //imports parameters from text file and use index to seed random number generator.
Parameters(double,double); //bite exposure gamma a, bite exposure gamma b
Parameters(double,double,double); //bite exposure gamma a, bite exposure gamma b, v_to_h ratio.
~Parameters(void);
//functions
void setParameters(void);
void importParameters(void);
void setBR(bool intervention);
void setVH(bool intervention);
void setMu(bool intervention);
double L3Uptake(double);
double readParamLine(ifstream& myfile);
double gamma_dist(double, double);
double normal_dist(double, double);
double uniform_dist(void);
double expTrunc(double, double);
int poisson_dist(double);
int rmvnorm(const gsl_rng *, const int, const gsl_vector *, const gsl_matrix *, gsl_vector *);
int setUB(double *, double *, double *);
double immuneRK4Step(double,double);
//parameters
double a;
double b;
double shapeRisk; //shape of probability distribution for risk.
double riskMu1; //mean of risk for age group less than 16
double riskMu2; //mean of risk for age group 17-29
double riskMu3; //mean of risk for age group 30+
double mu; //death rate of worms
double theta; //immune system response parameter. 0.112
double gamma; //mf death rate
double alpha; //mf birth rate
double v_to_h; //vector to human ratio.
double xi; //constant bite rate (5760.0 / 30.0)
double kappas1; //vector uptake and development
double r1; //vector uptake and development
double tau;
double z; //waning immunity
double nu; //poly-monogamy parameter
//shared state parameters
double L3; //larvae density.
double g; //Proportion of mosquitoes which pick up infection when biting an infected host
double sig; //death rate of mosquitos
double psi1; //Proportion of L3 leaving mosquito per bite
double psi2; //Proportion of L3 leaving mosquito that enter host
double lbda; //bite rate per mosquito per month
double dt;
double lbdaR, v_to_hR, sigR; //reduction in bite-rate and v_to_h ratio.
int nMDA; //number of rounds of MDA.
int mdaFreq;
double covMDA;
double s2;
double mfPropMDA; //proportion of mf killed due to MDA
double wPropMDA; //proportion of worms killed due to MDA
double sysComp,u0Comp, sigComp; //parameters for systematic non-compliance
double sysCompN, u0CompN, sigCompN; //parameters for systematic non-compliance of bed-nets.
double covN; //coverage of bednets.
double rhoCN; //correlation of non-compliance between bed-nets and MDA (Chemotherapy).
int mosquitoSpecies; //species of mosquito 0 - Anopheles, 1 - Culex
double rhoBU; //correlation between non-compliance and bite risk.
int aWol; //using doxycycline as intervention 0- not used. 1- is used.
double sN,dN; //probability of mosquito successfully biting given use of bed nets. prob of death due to bed net.
int IDAControl; //switch to IDA after five rounds of normal MDA treatment. 0- not used, 1 - is used.
} ;
class Host {
//double dt; //time-step for tau.
void initialise(void); //initialise state variables.
public:
Host(double);
Host(void);
void react(void);
void evolve(double);
double mfConc(void);
double biteRate(void);
double repRate(void);
void updateRisk(bool);
//state variables
int W,WM,WF; //number of worms, number of male worms, number of female worms
double I; //immune response (assumed to be deterministic)
double M; //mf produced. //int
double t; //time of host
double a; //age of host.
int aWol; //host is treated with Doxycycline.
int bedNet; //host used bednet.
//host parameters
Parameters *param; //pointer to params.
double b; //risk of infection
double pRisk; //p-value for risk of infection (updates b)
double uComp; //random parameter used to calculate compliance with MDA
double uCompN; //random parameter used to calculate compliance with bed nets.
//const double mu = 0.1/(30.0); //death rate of worms
//double beta = 0.112; //immune system response parameter.
//double gamma = 0.1/(30.0);
//double alpha = 0.2/(30.0);
int births;
int deaths;
//double xi = (5760.0 / 30.0) * 0.414 * 0.32 * 0.2;
//double tau = 0.04 / (365.0); //0.02
//double L3 = 1.0; //keeps track of L3 in total population.
} ;
class Model {
Host *host_pop;
int n;
bool aWolInt; //undergoing aWol intervention.
int bedNetInt; //undergoing bednet intervention.
public:
Model(int,double,double);
Model(int, Parameters*);
Parameters *param;
void react(void);
void evolve(double);
void save(string);
void outputs(void);
void saveOngoing(string); //appends WM,WF,M to the bottom of filename
void evolveAndSaves(double tot_t, string filename); //functionally same as evolve, but saves outputs at regular intervals.
double L3(void);
void MDAEvent(void);
void aWolEvent(bool);
void bedNetEvent(void);
} ;
#endif
| {
"alphanum_fraction": 0.6939322829,
"avg_line_length": 37.2875,
"ext": "h",
"hexsha": "693fee3032eef28fe745d9cfd8d2032d4ceaf5d2",
"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": "2c6200e4b47ad2d830279ac3fc694d1c55d799c9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sempwn/LF-model",
"max_forks_repo_path": "modelclasses.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2c6200e4b47ad2d830279ac3fc694d1c55d799c9",
"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": "sempwn/LF-model",
"max_issues_repo_path": "modelclasses.h",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2c6200e4b47ad2d830279ac3fc694d1c55d799c9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sempwn/LF-model",
"max_stars_repo_path": "modelclasses.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1556,
"size": 5966
} |
#include "openblas_utest.h"
#include <stdio.h>
#include <stdlib.h>
#include <cblas.h>
#define LAPACK_ROW_MAJOR 101
blasint LAPACKE_dgesvd( blasint matrix_layout, char jobu, char jobvt,
blasint m, blasint n, double* a,
blasint lda, double* s, double* u, blasint ldu,
double* vt, blasint ldvt, double* superb );
#define DATASIZE 100
double s[DATASIZE];
double u[DATASIZE*DATASIZE];
double vt[DATASIZE*DATASIZE];
double X[DATASIZE*DATASIZE];
double superb[DATASIZE];
double tmp[DATASIZE*DATASIZE];
double m[DATASIZE*DATASIZE];
CTEST(kernel_regress,skx_avx)
{
#ifdef BUILD_DOUBLE
double norm;
int i, j, info;
srand(0);
for (i = 0; i < DATASIZE*DATASIZE; i++) {
m[i] = (rand()+0.0)/RAND_MAX * 10;
tmp[i] = m[i];
}
info = LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'A', 'A', DATASIZE, DATASIZE, m, DATASIZE,
s, u, DATASIZE, vt, DATASIZE, superb);
for (i = 0; i < DATASIZE; i++) {
for (j = 0; j < DATASIZE; j++) {
u[i*DATASIZE+j] = u[i*DATASIZE+j]*s[j];
}
}
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
DATASIZE, DATASIZE, DATASIZE, 1, u, DATASIZE, vt, DATASIZE, 0, X, DATASIZE);
for (i = 0; i < DATASIZE*DATASIZE; i++) {
X[i] = X[i] - tmp[i];
}
norm = cblas_dnrm2(DATASIZE*DATASIZE, X, 1);
ASSERT_DBL_NEAR_TOL(0.0, norm, 1e-10);
#endif
}
| {
"alphanum_fraction": 0.5524115756,
"avg_line_length": 29.3396226415,
"ext": "c",
"hexsha": "5b131bb2cc30afe05861709ca8e58282808d9081",
"lang": "C",
"max_forks_count": 1564,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T07:12:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-01T01:32:27.000Z",
"max_forks_repo_head_hexsha": "b54b50fe3a5ec921d18ddf5fbdb80092d1b23893",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dnoan/OpenBLAS",
"max_forks_repo_path": "utest/test_kernel_regress.c",
"max_issues_count": 2067,
"max_issues_repo_head_hexsha": "b54b50fe3a5ec921d18ddf5fbdb80092d1b23893",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T18:59:43.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-01T03:50:01.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dnoan/OpenBLAS",
"max_issues_repo_path": "utest/test_kernel_regress.c",
"max_line_length": 92,
"max_stars_count": 4392,
"max_stars_repo_head_hexsha": "b54b50fe3a5ec921d18ddf5fbdb80092d1b23893",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dnoan/OpenBLAS",
"max_stars_repo_path": "utest/test_kernel_regress.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T12:14:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-02T18:15:45.000Z",
"num_tokens": 508,
"size": 1555
} |
/* randist/gauss.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* Of the two methods provided below, I think the Polar method is more
* efficient, but only when you are actually producing two random
* deviates. We don't produce two, because then we'd have to save one
* in a static variable for the next call, and that would screws up
* re-entrant or threaded code, so we only produce one. This makes
* the Ratio method suddenly more appealing. There are further tests
* one can make if the log() is slow. See Knuth for details */
/* Both methods pass the statistical tests; but the polar method
* seems to be a touch faster on my home Pentium, EVEN though we
* are only using half of the available random deviates!
*/
/* Polar (Box-Mueller) method; See Knuth v2, 3rd ed, p122 */
double
gsl_ran_gaussian (const gsl_rng * r, const double sigma)
{
double x, y, r2;
do
{
/* choose x,y in uniform square (-1,-1) to (+1,+1) */
x = -1 + 2 * gsl_rng_uniform (r);
y = -1 + 2 * gsl_rng_uniform (r);
/* see if it is in the unit circle */
r2 = x * x + y * y;
}
while (r2 > 1.0 || r2 == 0);
/* Box-Muller transform */
return sigma * y * sqrt (-2.0 * log (r2) / r2);
}
/* Ratio method (Kinderman-Monahan); see Knuth v2, 3rd ed, p130 */
/* K+M, ACM Trans Math Software 3 (1977) 257-260. */
double
gsl_ran_gaussian_ratio_method (const gsl_rng * r, const double sigma)
{
double u, v, x;
do
{
v = gsl_rng_uniform (r);
do
{
u = gsl_rng_uniform (r);
}
while (u == 0);
/* Const 1.715... = sqrt(8/e) */
x = 1.71552776992141359295 * (v - 0.5) / u;
}
while (x * x > -4.0 * log (u));
return sigma * x;
}
double
gsl_ran_gaussian_pdf (const double x, const double sigma)
{
double u = x / fabs (sigma);
double p = (1 / (sqrt (2 * M_PI) * fabs (sigma))) * exp (-u * u / 2);
return p;
}
double
gsl_ran_ugaussian (const gsl_rng * r)
{
return gsl_ran_gaussian (r, 1.0);
}
double
gsl_ran_ugaussian_ratio_method (const gsl_rng * r)
{
return gsl_ran_gaussian_ratio_method (r, 1.0);
}
double
gsl_ran_ugaussian_pdf (const double x)
{
return gsl_ran_gaussian_pdf (x, 1.0);
}
| {
"alphanum_fraction": 0.6644715179,
"avg_line_length": 27.3603603604,
"ext": "c",
"hexsha": "f30c14273405dec6c77b0f08b5dda9f6e5ddfe1d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/randist/gauss.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/randist/gauss.c",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/randist/gauss.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": 923,
"size": 3037
} |
/* gsl_histogram_stat.c
* Copyright (C) 2000 Simone Piccardi
*
* This library 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 library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/***************************************************************
*
* File gsl_histogram_stat.c:
* Routines for statisticalcomputations on histograms.
* Need GSL library and header.
* Contains the routines:
* gsl_histogram_mean compute histogram mean
* gsl_histogram_sigma compute histogram sigma
*
* Author: S. Piccardi
* Jan. 2000
*
***************************************************************/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.h>
/* FIXME: We skip negative values in the histogram h->bin[i] < 0,
since those correspond to negative weights (BJG) */
double
gsl_histogram_mean (const gsl_histogram * h)
{
const size_t n = h->n;
size_t i;
/* Compute the bin-weighted arithmetic mean M of a histogram using the
recurrence relation
M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n)))
W(n) = W(n-1) + w(n)
*/
long double wmean = 0;
long double W = 0;
for (i = 0; i < n; i++)
{
double xi = (h->range[i + 1] + h->range[i]) / 2;
double wi = h->bin[i];
if (wi > 0)
{
W += wi;
wmean += (xi - wmean) * (wi / W);
}
}
return wmean;
}
double
gsl_histogram_sigma (const gsl_histogram * h)
{
const size_t n = h->n;
size_t i;
long double wvariance = 0 ;
long double wmean = 0;
long double W = 0;
/* Use a two-pass algorithm for stability. Could also use a single
pass formula, as given in N.J.Higham 'Accuracy and Stability of
Numerical Methods', p.12 */
/* Compute the mean */
for (i = 0; i < n; i++)
{
double xi = (h->range[i + 1] + h->range[i]) / 2;
double wi = h->bin[i];
if (wi > 0)
{
W += wi;
wmean += (xi - wmean) * (wi / W);
}
}
/* Compute the variance */
W = 0.0;
for (i = 0; i < n; i++)
{
double xi = ((h->range[i + 1]) + (h->range[i])) / 2;
double wi = h->bin[i];
if (wi > 0) {
const long double delta = (xi - wmean);
W += wi ;
wvariance += (delta * delta - wvariance) * (wi / W);
}
}
{
double sigma = sqrt (wvariance) ;
return sigma;
}
}
/*
sum up all bins of histogram
*/
double
gsl_histogram_sum(const gsl_histogram * h)
{
double sum=0;
size_t i=0;
size_t n;
n=h->n;
while(i < n)
sum += h->bin[i++];
return sum;
}
| {
"alphanum_fraction": 0.5724073497,
"avg_line_length": 22.7730496454,
"ext": "c",
"hexsha": "eab0218fb3de0581c149f4283811c4e1acc1ca41",
"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/histogram/stat.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/histogram/stat.c",
"max_line_length": 74,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/histogram/stat.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": 912,
"size": 3211
} |
/* spmatrix/util.c
*
* Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017, 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spmatrix.h>
/*
gsl_spmatrix_cumsum()
Compute the cumulative sum:
p[j] = Sum_{k=0...j-1} c[k]
0 <= j < n + 1
Alternatively,
p[0] = 0
p[j] = p[j - 1] + c[j - 1]
Inputs: n - length of input array
c - (input/output) array of size n + 1
on input, contains the n values c[k]
on output, contains the n + 1 values p[j]
Return: success or error
*/
void
gsl_spmatrix_cumsum(const size_t n, int * c)
{
int sum = 0;
size_t k;
for (k = 0; k < n; ++k)
{
int ck = c[k];
c[k] = sum;
sum += ck;
}
c[n] = sum;
}
| {
"alphanum_fraction": 0.6559422193,
"avg_line_length": 24.1746031746,
"ext": "c",
"hexsha": "6e5d02e8c6d930a8494513756d3bf2fe7d77f79c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/spmatrix/util.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/spmatrix/util.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/spmatrix/util.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": 455,
"size": 1523
} |
#include <cblas.h>
#include "tasks.h"
void trsm_task_seq(void *ptr)
{
struct trsm_task_arg *arg = (struct trsm_task_arg*) ptr;
int n = arg->n;
int m = arg->m;
double *A21 = arg->A21;
double *A11 = arg->A11;
int ldA = arg->ldA;
// Compute A21 := A21 * inv(A11').
cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit,
m, n,
1.0, A11, ldA,
A21, ldA);
}
| {
"alphanum_fraction": 0.5281837161,
"avg_line_length": 21.7727272727,
"ext": "c",
"hexsha": "6129d37e97014592868cf322b46280e6533d6551",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/pcp-runtime",
"max_forks_repo_path": "src/examples/dpotrf/task-trsm-seq.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/pcp-runtime",
"max_issues_repo_path": "src/examples/dpotrf/task-trsm-seq.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/pcp-runtime",
"max_stars_repo_path": "src/examples/dpotrf/task-trsm-seq.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 156,
"size": 479
} |
#ifndef S3D_CV_IMAGE_OPERATION_INPUT_OUTPUT_ADAPTER_H
#define S3D_CV_IMAGE_OPERATION_INPUT_OUTPUT_ADAPTER_H
#include <s3d/multiview/stan_results.h>
#include <opencv2/core/mat.hpp>
#include <gsl/gsl>
namespace s3d {
namespace image_operation {
class ImageOperations;
class InputOutputAdapter {
public:
InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations);
void setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage);
std::tuple<cv::Mat&, cv::Mat&> getOutputImages();
bool applyAllOperations();
void copyInputToOutputs();
bool canApplyOperations();
StanResults results;
private:
cv::Mat inputLeftImage{};
cv::Mat inputRightImage{};
cv::Mat outputLeftImage{};
cv::Mat outputRightImage{};
ImageOperations* operations_{};
};
} // namespace s3d
} // namespace image_operation
#endif // S3D_CV_IMAGE_OPERATION_INPUT_OUTPUT_ADAPTER_H
| {
"alphanum_fraction": 0.7730337079,
"avg_line_length": 22.25,
"ext": "h",
"hexsha": "b597922c81546126c2e48227e6ae92ada3c75358",
"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/core/cv/include/s3d/cv/image_operation/input_output_adapter.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/core/cv/include/s3d/cv/image_operation/input_output_adapter.h",
"max_line_length": 75,
"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/core/cv/include/s3d/cv/image_operation/input_output_adapter.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": 221,
"size": 890
} |
#include <stdio.h>
#include <math.h>
#include <nlopt.h>
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
//printf("%f\t%f\t", grad[0], grad[1]);
//printf("%f\t%f\n", x[0], x[1]);
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
//printf("%f\n", sqrt(x[1]));
//sleep(1);
return sqrt(x[1]);
}
typedef struct {
double a, b;
} my_constraint_data;
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
my_constraint_data *d = (my_constraint_data *) data;
double a = d->a, b = d->b;
if (grad) {
grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
grad[1] = -1.0;
}
return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}
int main(){
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
//opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
opt = nlopt_create(NLOPT_LN_COBYLA, 2); /* algorithm and dimensionality */
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
my_constraint_data data[2] = { {2,0}, {-1,1} };
nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
//nlopt_set_xtol_rel(opt, 1e-4);
nlopt_set_stopval(opt, (sqrt(8./27.) + 1e-3));
double x[2] = { 1.234, 5.678 }; /* `*`some` `initial` `guess`*` */
double minf; /* `*`the` `minimum` `objective` `value,` `upon` `return`*` */
if (nlopt_optimize(opt, x, &minf) < 0) {
printf("nlopt failed!\n");
}
else {
printf("found minimum at f(%g,%g) = %0.10g\n", x[0], x[1], minf);
}
nlopt_destroy(opt);
}
| {
"alphanum_fraction": 0.56152513,
"avg_line_length": 27.9193548387,
"ext": "c",
"hexsha": "7d37c2d73dc0ce01b173dd166a34305476ed6d5c",
"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": "3833ae907beab3da8151c4d364db37686747c082",
"max_forks_repo_licenses": [
"MIT-0"
],
"max_forks_repo_name": "Vindaar/nimnlopt",
"max_forks_repo_path": "examples/tutorial.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "3833ae907beab3da8151c4d364db37686747c082",
"max_issues_repo_issues_event_max_datetime": "2018-07-19T16:16:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-07-01T23:55:19.000Z",
"max_issues_repo_licenses": [
"MIT-0"
],
"max_issues_repo_name": "Vindaar/nimnlopt",
"max_issues_repo_path": "examples/tutorial.c",
"max_line_length": 79,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "3833ae907beab3da8151c4d364db37686747c082",
"max_stars_repo_licenses": [
"MIT-0"
],
"max_stars_repo_name": "Vindaar/nimnlopt",
"max_stars_repo_path": "examples/tutorial.c",
"max_stars_repo_stars_event_max_datetime": "2021-02-11T07:36:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-22T15:13:54.000Z",
"num_tokens": 636,
"size": 1731
} |
#ifndef CollectorMap_h
#define CollectorMap_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 <cctype>
#include <QString>
#include <map>
#include <algorithm>
#include <functional>
#include <sstream>
#include <iomanip>
#include <exception>
#include "IException.h"
#include "IString.h"
#include <gsl/gsl_math.h>
namespace Isis {
/**
* @brief Provides a simple comparison between two values
*
* This simple comparison function object is provided with no special frills
* that does pretty much exactly what std::less does.
*/
template <typename K> struct SimpleCompare {
/**
* Returns true if v1 is less than v2
*
* @param v1 Input constant
* @param v2 Input constant
*
* @return bool Returns true if v1 is less than v2
*/
bool operator()(const K &v1, const K &v2) const {
return (v1 < v2);
}
};
/**
* @brief Provides a case insensitive string comparison
*
* This string comparison functor object compares two strings ignoring case. Use
* this policy when your key into the collector map is a string and you want to
* ignore case when finding elements in the collection.
*/
template <typename K> struct NoCaseStringCompare {
/**
* Compares v1 and v2 as case insensitive strings, and returns true of v1 is
* less than v2 (as those strings).
*
* @param v1 Input constant
* @param v2 Input constant
*
* @return bool Returns true if v1 is less than v2 in string format
*/
bool operator()(const K &v1, const K &v2) const {
return (IString::DownCase(v1) < IString::DownCase(v2));
}
};
/**
* @brief Provides a robust comparison of double/float values
*
* This functor compares floating point values using a default epsilon of
* 1.0e-6. It can be used for doubles or floats, however floats will be promoted
* to double for the comparison.
*/
template <typename K> struct RobustFloatCompare {
/**
* Compares v1 and v2 as floating point values.
*
* @param v1
* @param v2
*
* @return bool
*/
bool operator()(const K &v1, const K &v2) const {
return (gsl_fcmp(v1, v2, -1.0E-6) < 0);
}
};
/**
* @brief Supplies a NOOP default for removal of a CollectorMap entry
*
* This simple declaration is basically a NOOP that implements removal
* of a CollectionMap entry. It is most useful (and the default behavior)
* when the storage element of the CollectorMap is anything but a pointer.
* Pointers that require deletion should use the PointerRemoval policy unless
* the pointers are owned by another "entity".
*/
template <typename T> struct NoopRemoval {
// defines used for cross platform suppression of unused parameter warning. This will prevent
// distroy() from causing unused parameter warnings in clang. This is done for the purpose
// of porting ISIS to OSX 10.11
// #define MON_Internal_UnusedStringify(macro_arg_string_literal) #macro_arg_string_literal
// #define MONUnusedParameter(macro_arg_parameter) _Pragma(MON_Internal_UnusedStringify(unused(macro_arg_parameter)))
protected:
/**
* Destroys the CollectorMap entry
*
* @param element The CollectorMap to be destroyed
*/
void destroy(T *element) {
// arbitrary cast type to suppress unused parameter warnings generated
// by clang when building on mac
(void)element;
return;
}
};
/**
* @brief Supplies a policy for deleting pointers that CollectorMap owns
*
* Defines a method to delete pointers when removed from a CollectorMap.
* This is necessary to prevent memory leaks and defer the deletion to
* removal from CollectorMap class.
*/
template <typename T> struct PointerRemoval {
protected:
/**
* Destroys the CollectorMap pointer's CollectorMap
*
* @param element The pointer pointing to the CollectorMap to be destroyed
*/
void destroy(T *element) {
delete(*element);
return;
}
};
/**
* @brief Policy for deleting arrays that CollectorMap owns
*
* Defines a method to delete arrays when removed from a CollectorMap.
* This is necessary to prevent memory leaks and defer the deletion to
* removal from CollectorMap class.
*/
template <typename T> struct ArrayRemoval {
protected:
/**
* Destroys the array of CollectorMaps
*
* @param element The array of CollectorMaps to be destroyed
*/
void destroy(T *element) {
delete [](*element);
return;
}
};
/**
* @brief (Default) Policy for copying map elements
*
* Defines a method to copy simple elements from an existing map to a
* destination map. This policy just makes a direct copy of the element to the
* destination.
*
* This policy assumes the assignment operator handles the proper copying of
* each element T in the collection.
*/
template <typename T> struct DefaultCopy {
protected:
/**
* Returns a copy of the input
*
* @param src The map element to be copied
*
* @return const T& The copy of the input
*/
const T ©(const T &src) const {
return (src);
}
};
/**
* @brief Pointer to object policy for copying map elements
*
* Defines a copy method to properly handle pointers to objects (assumed) when
* copying the complete CollectorMap. This implementation assumes the copy
* constructor properly handles the creation of a new element from a different
* one.
*
* This policy assumes the assignment operator handles the proper copying of
* each element T* in the collection.
*
* This employs an intersting technique of redirection. Because the type T is
* actually T*, the templated allocate() method exists to get down to the T
* class base level. Looks strange but it works.
*/
template <typename T> struct PointerCopy {
protected:
/**
* @brief Allocate new object using copy construtor and new pointer
*
* This copy method takes a pointer to a pointer (T is actually a T*) and
* allocates a new object using the copy constructor.
*
* @param src Pointer to pointer of new class to allocate
*
* @return T Pointer to new object type T
*/
T copy(const T &src) const {
return (allocate(*(src)));
}
private:
/**
* @brief Allocate new object using copy constructor
*
* @param obj Source object to create new one from
*
* @return P* Pointer to newly allocated object
*/
template <typename P>
P *allocate(const P &obj) const {
return (new P(obj));
}
};
/**
* @brief Collector/container for arbitrary items
*
* Used to contain types with iterators of const and non-const conditions.
* This is a multimap that contains arbitrary keys with arbitrary elements. It
* is intended to be used for pointers and copyable objects. They should be
* rather efficient in the copy out operation so large objects may not be
* suitable or classes that do not have a good copy operator. During testing
* it was noted that an object is copied up to four times and destroyed three
* times upon an add() operation.
*
* This class is implemented using policies. The ComparePolicy is used to test
* key elements such as strings and double values. The NoCaseStringCompare
* policy is provided that expedites case insensitive string key comparisons.
* The RobustFloatCompare implements the comparison of double or float key
* types. Direct comparisons of floats can be problematic due to round off and
* storage manifestations of these values in conputers. The default policy,
* SimpleCompare, does a simple parameter to key equality test.
*
* The RemovalPolicy is provided when a map value is removed from the list.
* This allows pointers and arrays to be stored in the map as well. To store
* pointers, use PointerRemoval and for arrays there is the ArrayRemoval
* policy. The default is the NoopRemoval policy which simply lets the
* destructor handle removals.
*
* The CopyPolicy is necessary to properly handle the copying of elements.
* This is especially important for pointers and arrays. In order to minimize
* difficult passing strategies, map elements are passed by address and the
* return type is the element type. DefaultCopy simply copies the elements as
* is relying on the element T assigment operator to do the right thing. For
* pointers to objects, the PointerCopy allocates the object using the copy
* constructor. One could provide a similar operator assuming a clone()
* method existed for the type T element. The ArrayCopy policy is left to the
* user to provide their own as it cannot support arrays of varying length.
* (One should use std::vector instead!) Users can supply their own CopyPolicy
* that need only expose a copy(cont T *src) method.
*
* Here are some examples that demonstrate how this policy-based template class
* can be used:
*
* @code
* // Create a unique string key list that stores double floating point values.
* // Use the default removal and copy policies but allow testing for character
* // keys without regard to case via the NoCaseStringCompare.
* #include "CollectorMap.h"
*
* CollectorMap<QString, double, NoCaseStringCompare > dmap;
* cout << "\nSize of double map = " << dmap.size() << endl;
* dmap.add("one", 1.0);
* dmap.add("two", 2.0);
* cout << "Size of double map = " << dmap.size() << endl;
*
* cout << "One = " << dmap.get("one") << endl;
* cout << "Two = " << dmap.get("Two") << endl;
*
* const double &one = dmap.get("one");
* cout << "\nTest Const one = " << one << endl;
*
* dmap.remove("one");
* @endcode
*
* Using this class internal to classes is perhaps where it may be applied more
* frequently. The example below shows how to declare an integer key using
* pointers to classes:
*
* @code
* #include "CollectorMap.h"
*
* class ClassTest {
* public:
* ClassTest(int n = 0) : _n(n) { }
* ~ClassTest() { }
* int Ident() const { return (_n); }
* private:
* int _n;
* };
*
*
* // Typedefs are sometimes convenient in these cases
* typedef CollectorMap<int, ClassTest *, SimpleCompare,
* PointerRemoval, PointerCopy> PointerMap;
*
* PointerMap ctest2;
* ctest2.add(4,new ClassTest(4));
* ctest2.add(5,new ClassTest(5));
* ctest2.add(6,new ClassTest(6));
* ctest2.add(7,new ClassTest(7));
*
* cout << "Remove ClassTest 6\n";
* ctest2.remove(6);
*
* // Creates a copy of ctest2 using the PointerCopy policy
* PointerMap map2(ctest2);
*
* cout << "Find element 7: " << map2.find(7)->Ident() << endl;
*
* @endcode
*
* And, finally, an example of how to use duplicate keys:
*
* @code
* #include "CollectorMap.h"
*
* typedef CollectorMap<int,QString> IntStr;
* IntStr dupstr(IntStr::DuplicateKeys);
* dupstr.add(1,"One");
* dupstr.add(1, "One #2");
* dupstr.add(1,"One #3");
* dupstr.add(2,"Two");
* dupstr.add(2,"Two #2");
* dupstr.add(3,"Three");
*
* cout << "Size of Dup object: " << dupstr.size() << endl;
* cout << "Number Ones: " << dupstr.count(1) << endl;
* cout << "Number Twos: " << dupstr.count(2) << endl;
* cout << "Number Threes: " << dupstr.count(3) << endl;
* cout << "Number Fours: " << dupstr.count(4) << endl;
*
* IntStr::CollectorConstIter isIter;
* int j = 0;
* for (isIter = dupstr.begin() ; isIter != dupstr.end() ; ++isIter, j++) {
* cout << "IntStr[" << j << "] = {" << isIter->first << ", "
* << isIter->second << "}, Index: " << dupstr.index(isIter->first)
* << endl;
* cout << "Nth Test Ident = " << dupstr.getNth(j) << endl;
* }
* @endcode
*
* The output of the above example is:
* @code
* Size of Dup object: 6
* Number Ones: 3
* Number Twos: 2
* Number Threes: 1
* Number Fours: 0
* IntStr[0] = {1, One}, Index: 0
* Nth Test Ident = One
* IntStr[1] = {1, One #2}, Index: 0
* Nth Test Ident = One #2
* IntStr[2] = * {1, One #3}, Index: 0
* Nth Test Ident = One #3
* IntStr[3] * = {2, Two}, Index: 3
* Nth Test Ident = Two
* IntStr[4] = * {2, Two #2}, Index: 3
* Nth Test Ident = Two #2
* IntStr[5] = * {3, Three}, Index: 5
* Nth Test Ident = Three
* @endcode
*
* @ingroup Utility
*
* @author 2006-06-21 Kris Becker
*
* @internal
* @history 2006-07-03 Kris Becker Added the ability to stored duplicate keys
* if needed (using a multimap instead of a map). Initial default
* behavior of unique keys is retained. See KeyPolicy.
* @history 2006-07-28 Kris Becker Fixed a bug in the NoCaseStringCompare
* implementation. Prior to this fix, it would not function
* properly at all for case-insenstive keys.
* @history 2006-08-30 Kris Becker Fixed bug in copy constructors that
* attempted to use a virtual method in the object being created
* when it *must* use the method from the one it is being created
* from. (g++ 4.1 on Suse 10.1 didn't like this bug at all!)
* @history 2008-06-18 Christopher Austin Fixed Documentation
* @history 2017-08-30 Summer Stapleton - Updated documentation. References #4807.
*
*/
template < typename K, typename T,
template <class> class ComparePolicy = SimpleCompare,
template <class> class RemovalPolicy = NoopRemoval,
template <class> class CopyPolicy = DefaultCopy
>
class CollectorMap : public RemovalPolicy<T>, public CopyPolicy<T> {
public:
typedef T CollectorType; //!< Data type
/** A multimap attacking a key to a CollectorType and a ComparePolicy<CollectorType>*/
typedef std::multimap<K, CollectorType, ComparePolicy<K> > CollectorList;
//! CollectorList iterator type declaration
typedef typename CollectorList::iterator CollectorIter;
//! CollectorList constant iterator type declaration
typedef typename CollectorList::const_iterator CollectorConstIter;
/**
* @brief Enumerated selection of key behaviour
*
* Using this enumeration during construction allows the user of this class
* to specify if the keys used to identify elements are unique or can be
* duplicated.
*/
enum KeyPolicy { UniqueKeys, //!< Constrain keys to be unique
DuplicateKeys //!< Allow duplication of keys
};
/** Constructor */
CollectorMap() : _keyPolicy(UniqueKeys) { }
/**
* @brief Allows the user to choose if keys can be duplicated
*
* This constructor is provided to the user that wants to explicity define how
* the keys, namely insertions are managed. The default is unique keys in the
* noop constructor...this one allows instantiation of either policy.
*
* @param keyPolicy Can be UniqueKeys or DuplicateKeys
*/
CollectorMap(const KeyPolicy &keyPolicy) : _keyPolicy(keyPolicy) { }
/** Destructor handles removal of the elements within the collection
*
* This must take into account the removal strategy and apply to any
* remaining elements.
*/
virtual ~CollectorMap() {
selfDestruct();
}
/**
* @brief Copy constructor invokes the copy policy as provided by the users
*
* This copy constructor will transfer the map of an incoming CollectorMap to
* a newly created one. This process employs the user selectable CopyPolicy.
* It invokes the copy() method exposed in the copy policy.
*
* @param cmap The CollectorMap to be copied
*/
CollectorMap(const CollectorMap &cmap) {
_keyPolicy = cmap._keyPolicy;
CollectorConstIter cItr;
for(cItr = cmap._list.begin() ; cItr != cmap._list.end() ; cItr++) {
_list.insert(std::make_pair(cItr->first, cmap.copy(cItr->second)));
}
}
/**
* @brief Assignment operator for the CollectorMap class object
*
* This object assignment operator is provided to properly handle the copying
* of CollectorMap elements to a new instantiation. This implements the
* CopyPolicy for each element in the @b cmap object to the current one. This
* is a two step operation: first destroy any elements that exist in the
* destination object (using the RemovalPolicy) and then copy all elements
* from the @b cmap object to the current one using the copy() method exposed
* in the CopyPolicy.
*
* @param cmap The CollectorMap to be copied
*
* @returns Pointer to this CollectorMap
*/
CollectorMap &operator=(const CollectorMap &cmap) {
if(&cmap != this) {
selfDestruct();
_keyPolicy = cmap._keyPolicy;
CollectorConstIter cItr;
for(cItr = cmap._list.begin() ; cItr != cmap._list.end() ; cItr++) {
_list.insert(std::make_pair(cItr->first, cmap.copy(cItr->second)));
}
}
return (*this);
}
/**
* Returns the size of the collection
*
* @return int Number of elements in collection
*/
int size() const {
return (_list.size());
}
/**
* @brief Returns the number of keys found in the list
*
* For unique keys, this will always be 1. If duplicate keys are allowed,
* this will return the number of keys in the container.
*
* @param key Key to return count for
*
* @return int Number keys in container
*/
int count(const K &key) const {
return (_list.count(key));
}
/**
* Adds the element to the list.
*
* If the element exists and the key policy is restricted to uniqueness, it is
* replaced after the removal strategy is applied. If it doesn't exist, it is
* inserted into the list. For duplicate keys, it is simply inserted.
*
* @param key Key in the associative map for the value
* @param value Value to be associated with the key
*/
void add(const K &key, const T &value) {
if(_keyPolicy == UniqueKeys) remove(key);
_list.insert(std::make_pair(key, value));
return;
}
/**
* Checks the existance of a particular key in the list
* @param key Key to search for in the list
* @return bool True if the key exists, false otherwise
*/
bool exists(const K &key) const {
CollectorConstIter cItr = _list.find(key);
return (cItr != _list.end());
}
/**
* @brief Returns the value associated with the name provided
*
* If the specifed name and value does not exist in the list, an out_of_range
* exception is thrown. Use @b exists to predetermine of the value is in the
* list.
*
* @param key Key to fetch the value for
* @return T Value associated with name
* @throws IException if the value is not found
*/
T &get(const K &key) {
CollectorIter cItr = _list.find(key);
if(cItr == _list.end()) {
QString mess = "Requested value does not exist!";
throw IException(IException::Programmer, mess, _FILEINFO_);
}
return (cItr->second);
}
/**
* @brief Const version returning the value associated with the given name
*
* @param key Key to fetch the value for
*
* @returns The value associated with the given name
*/
const T &get(const K &key) const {
CollectorConstIter cItr = _list.find(key);
if(cItr == _list.end()) {
QString mess = "Requested value does not exist!";
throw IException(IException::Programmer, mess, _FILEINFO_);
}
return (cItr->second);
}
/**
* @brief Returns the index of the first occuring element in the list
*
* This returns the index such that the getNth() methods would retrieve the
* element with key. For duplicate keys, it is garaunteed to return the first
* element. It will return -1 if the element is not in the list.
*
* @param key Key to fetch the value for
*
* @return int Zero-based index of (first) element with key. If it doesn't
* exist, -1 is returned.
*/
int index(const K &key) const {
CollectorConstIter cItr = _list.lower_bound(key);
if(cItr == _list.end()) {
return (-1);
}
else {
return (std::distance(_list.begin(), cItr));
}
}
/**
* @brief Returns the nth value in the collection
*
* If the specifed value does not exist in the list, an out_of_range exception
* is thrown. Use @b size() to predetermine if the range is valid.
*
* @param nth Return the Nth value in the list
*
* @return T Value associated with name
*/
T &getNth(int nth) {
CollectorIter cItr;
int i;
for(cItr = _list.begin(), i = 0 ; cItr != _list.end() ; ++cItr, i++) {
if(i == nth) break;
}
if(cItr == _list.end()) {
std::ostringstream mess;
mess << "Requested index (" << nth << ") out of range" << std::endl;
throw IException(IException::Programmer, mess.str(), _FILEINFO_);
}
return (cItr->second);
}
/**
* @brief Returns the nth value in the collection
*
* If the specifed value does not exist in the list, an out_of_range exception
* is thrown. Use @b size() to predetermine if the range is valid.
*
* @param nth Return the Nth value in the list
*
* @return T Value associated with name
*/
const T &getNth(int nth) const {
CollectorConstIter cItr;
int i;
for(cItr = _list.begin(), i = 0 ; cItr != _list.end() ; ++cItr, i++) {
if(i == nth) break;
}
if(cItr == _list.end()) {
std::ostringstream mess;
mess << "Requested index (" << nth << ") out of range" << std::endl;
throw IException(IException::Programmer, mess.str(), _FILEINFO_);
}
return (cItr->second);
}
/**
* @brief Returns the nth key in the collection
*
* If the specifed key does not exist in the list, an out_of_range exception
* is thrown. Use @b size() to predetermine if the range is valid.
*
* @param nth Return the Nth key in the list
*
* @return K Key associated with name
*/
const K &key(int nth) const {
CollectorConstIter cItr;
int i;
for(cItr = _list.begin(), i = 0 ; cItr != _list.end() ; ++cItr, i++) {
if(i == nth) break;
}
if(cItr == _list.end()) {
std::ostringstream mess;
mess << "Requested key index (" << nth << ") out of range" << std::endl;
throw IException(IException::Programmer, mess.str(), _FILEINFO_);
}
return (cItr->first);
}
/**
* Removes and entry from the list
*
* @param key Name of key/value pair to remove from the list
*
* @return int Number of elements erased
*/
int remove(const K &key) {
CollectorIter Itr1 = _list.lower_bound(key);
if(Itr1 == _list.end()) return (0);
CollectorIter Itr2 = _list.upper_bound(key);
while(Itr1 != Itr2) {
this->destroy(&Itr1->second);
++Itr1;
}
return (_list.erase(key));
}
/**
* Const iterator into list
*
* @return CollectorConstIter Returns a const iterator to the list
*/
CollectorConstIter begin() const {
return _list.begin();
}
/**
* Const iterator to end of list
*
* @return CollectorConstIter Returns the const end of the list
*/
CollectorConstIter end() const {
return _list.end();
}
/**
* Returns the start of the list for iterating purposes
*
* @return CollectorIter Returns an iterator on the collection
*/
CollectorIter begin() {
return _list.begin();
}
/**
* Returns the end of the list
*
* @return CollectorIter Returns the end of the list for determining the end
* of the iteration loop
*/
CollectorIter end() {
return _list.end();
}
private:
KeyPolicy _keyPolicy; //!< Unique or duplicate key constraint
CollectorList _list; //!< The list
/**
* @brief Thourough destruction of list
*
* This method iterates through each element in the list applying the
* RemovalPolicy to each value in the map. It then clears the internal list
* for subsequent reuse if needed.
*/
void selfDestruct() {
CollectorIter itr;
for(itr = _list.begin() ; itr != _list.end() ; itr++) {
this->destroy(&itr->second);
}
_list.clear();
}
};
};
#endif
| {
"alphanum_fraction": 0.6074958188,
"avg_line_length": 34.2998696219,
"ext": "h",
"hexsha": "50fd0a1dae81a492d261d69c95fc3bf4a7d0414b",
"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/CollectorMap/CollectorMap.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/CollectorMap/CollectorMap.h",
"max_line_length": 121,
"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/CollectorMap/CollectorMap.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": 6566,
"size": 26308
} |
#ifndef __LINALG_LIB_WRAPPER_H__
#define __LINALG_LIB_WRAPPER_H__
// Wrapper for linear algebra library (BLAS, LAPACK)
#if !defined(USE_MKL) && !defined(USE_OPENBLAS)
#define USE_OPENBLAS
#endif
#ifdef USE_MKL
#include <mkl.h>
#define BLAS_SET_NUM_THREADS mkl_set_num_threads
#endif
#ifdef USE_OPENBLAS
#include <cblas.h>
#include <lapacke.h>
#define BLAS_SET_NUM_THREADS openblas_set_num_threads
#endif
#endif
| {
"alphanum_fraction": 0.8057553957,
"avg_line_length": 18.1304347826,
"ext": "h",
"hexsha": "492bded893f0c67323fb1f4c0b15f9967dd946fa",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-01-05T23:38:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-24T06:06:38.000Z",
"max_forks_repo_head_hexsha": "421e722712e69e35d2bacf5a23672cf7289317b6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "scalable-matrix/H2Pack",
"max_forks_repo_path": "src/linalg_lib_wrapper.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "421e722712e69e35d2bacf5a23672cf7289317b6",
"max_issues_repo_issues_event_max_datetime": "2020-12-29T23:53:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-13T18:18:02.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "scalable-matrix/H2Pack",
"max_issues_repo_path": "src/linalg_lib_wrapper.h",
"max_line_length": 53,
"max_stars_count": 15,
"max_stars_repo_head_hexsha": "421e722712e69e35d2bacf5a23672cf7289317b6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "scalable-matrix/H2Pack",
"max_stars_repo_path": "src/linalg_lib_wrapper.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T05:13:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-26T03:17:35.000Z",
"num_tokens": 116,
"size": 417
} |
/*
Copyright [2021] [IBM Corporation]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _MCAS_COMMON_BYTE_
#define _MCAS_COMMON_BYTE_
#include <cstddef>
#include <gsl/gsl_byte>
#ifndef MCAS_BYTE_USES_STD
/* For compilation with C++14 use gsl::byte, not C++17 std::byte */
#define MCAS_BYTE_USES_STD 0
#endif
namespace common
{
#if MCAS_BYTE_USES_STD
using byte = std::byte;
#else
using byte = gsl::byte; /* can be std::byte in C++17 */
#endif
}
#endif
| {
"alphanum_fraction": 0.7397119342,
"avg_line_length": 27.7714285714,
"ext": "h",
"hexsha": "579212965336c483dc5decd6c94343bff8e59313",
"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": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "IBM/artemis",
"max_forks_repo_path": "src/lib/common/include/common/byte.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"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": "IBM/artemis",
"max_issues_repo_path": "src/lib/common/include/common/byte.h",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "IBM/artemis",
"max_stars_repo_path": "src/lib/common/include/common/byte.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 239,
"size": 972
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
void read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName)
{
FILE *fp = fopen(input_fileName, "r");
fscanf(fp, "%*[^\n]\n");
for (int ii = 0; ii < N_kw; ii++)
fscanf(fp, "%d,", &((*index)[ii]));
fscanf(fp, "%*[^\n]\n");
int tmp;
for (int ii = 0; ii < N_kw; ii++)
{
for (int jj = 0; jj < N_kw; jj++)
{
fscanf(fp, "%d,", &tmp);
(*matrix)[ii*N_kw + jj] = (int) (scaling * tmp);
}
fscanf(fp, "%*[^\n]\n");
}
fclose(fp);
}
void pad_matrix(int** matrix_padded, int** matrix, int N_kw, int N_doc, int freq_max)
{
// Initialising RNG
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
// perform padding on the keywords
int ii, jj;
#pragma omp parallel for private(ii)
for (int ii = 0; ii < N_kw; ii++)
(*matrix_padded)[ii*N_kw + ii] = 2*freq_max;
// perform padding
#pragma omp parallel for private(ii, jj)
for (ii = 0; ii < N_kw; ii++)
{
for (jj = 0; jj < N_kw; jj++)
{
if (ii > jj)
{
int n1 = 2*freq_max - (*matrix)[ii*N_kw + ii];
int n2 = 2*freq_max - (*matrix)[jj*N_kw + jj];
int x1 = gsl_ran_hypergeometric(r, n1, 2*N_doc-n1, (*matrix_padded)[jj*N_kw + jj]);
int x2 = gsl_ran_hypergeometric(r, n2, 2*N_doc-n2, (*matrix_padded)[ii*N_kw + ii]);
(*matrix_padded)[ii*N_kw + jj] = (*matrix)[ii*N_kw + jj] + x1 + x2;
(*matrix_padded)[jj*N_kw + ii] = (*matrix_padded)[ii*N_kw + jj];
}
}
}
gsl_rng_free(r);
}
void observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw)
{
// perform observed count generation
for (int ii = 0; ii < N_kw; ii++)
for (int jj = 0; jj < N_kw; jj++)
gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj]));
}
void permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, int N_kw, int N_obs)
{
*idx1 = rand() % N_obs;
*idx2 = -1;
int idx_old = (*permutation)[*idx1];
int idx_new = rand() % N_kw;
(*permutation_tmp)[*idx1] = idx_new;
if ((*permutation_inv)[idx_new] >= 0)
{
*idx2 = (*permutation_inv)[idx_new];
(*permutation_tmp)[*idx2] = idx_old;
}
} | {
"alphanum_fraction": 0.5445692884,
"avg_line_length": 27.8125,
"ext": "c",
"hexsha": "5612e876afeed0a5ffdee6a30e68b23e9144e9bb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_forks_repo_path": "FP-EMM/util.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_issues_repo_path": "FP-EMM/util.c",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_stars_repo_path": "FP-EMM/util.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 826,
"size": 2670
} |
//Gets deltas (first order differences) of X,
//which is assumed to be pre-allocated of double size
//so that the appended rows/cols will hold the deltas.
//Thus, for dim==0, C must be even, with C/2 the original ncols of X.
//And, for dim==1, R must be even, with R/2 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_deltas_s (float *X, const int iscolmajor, const int R, const int C, const int dim, const int N);
int add_deltas_d (double *X, const int iscolmajor, const int R, const int C, const int dim, const int N);
int add_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/2;
int r, c, n;
float sc = 1.0f;
//Checks
if (R<1) { fprintf(stderr,"error in add_deltas_s: R (nrows X) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in add_deltas_s: C (ncols X) must be positive\n"); return 1; }
if (N<1) { fprintf(stderr,"error in add_deltas_s: N (delta winlength) must be positive\n"); return 1; }
if (dim==0 && C%2!=0) { fprintf(stderr,"error in add_deltas_s: C (ncols X) must be even for dim==0\n"); return 1; }
if (dim==1 && R%2!=0) { fprintf(stderr,"error in add_deltas_s: R (nrows X) must be even for dim==1\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(No,&z,0,&X[No],1);
for (c=0; c<C/2; 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
}
}
}
else
{
for (c=0; c<C/2; c++)
{
cblas_scopy(R,&z,0,&X[C/2+c],C);
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[c],0,&X[C/2+c],C); //beg edge samps
cblas_saxpy(R-n,-sc*n,&X[c],C,&X[C/2+c+n*C],C); //past samps
cblas_saxpy(R-n,sc*n,&X[c+n*C],C,&X[C/2+c],C); //future samps
cblas_saxpy(n,sc*n,&X[c+C*(R-1)],0,&X[C/2+c+C*(R-n)],C); //end edge samps
}
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R/2; r++)
{
cblas_scopy(C,&z,0,&X[R/2+r],R);
for (n=1; n<=N; n++)
{
cblas_saxpy(n,-sc*n,&X[r],0,&X[R/2+r],R); //beg edge samps
cblas_saxpy(C-n,-sc*n,&X[r],R,&X[R/2+r+n*R],R); //past samps
cblas_saxpy(C-n,sc*n,&X[r+n*R],R,&X[R/2+r],R); //future samps
cblas_saxpy(n,sc*n,&X[r+R*(C-1)],0,&X[R/2+r+R*(C-n)],R); //end edge samps
}
}
}
else
{
cblas_scopy(No,&z,0,&X[No],1);
for (r=0; r<R/2; 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
}
}
}
}
else
{
fprintf(stderr,"error in add_deltas_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int add_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/2;
int r, c, n;
double sc = 1.0;
//Checks
if (R<1) { fprintf(stderr,"error in add_deltas_d: R (nrows X) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in add_deltas_d: C (ncols X) must be positive\n"); return 1; }
if (N<1) { fprintf(stderr,"error in add_deltas_d: N (delta winlength) must be positive\n"); return 1; }
if (dim==0 && C%2!=0) { fprintf(stderr,"error in add_deltas_d: C (ncols X) must be even for dim==0\n"); return 1; }
if (dim==1 && R%2!=0) { fprintf(stderr,"error in add_deltas_d: R (nrows X) must be even for dim==1\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(No,&z,0,&X[No],1);
for (c=0; c<C/2; 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
}
}
}
else
{
for (c=0; c<C/2; c++)
{
cblas_dcopy(R,&z,0,&X[C/2+c],C);
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[c],0,&X[C/2+c],C); //beg edge samps
cblas_daxpy(R-n,-sc*n,&X[c],C,&X[C/2+c+n*C],C); //past samps
cblas_daxpy(R-n,sc*n,&X[c+n*C],C,&X[C/2+c],C); //future samps
cblas_daxpy(n,sc*n,&X[c+C*(R-1)],0,&X[C/2+c+C*(R-n)],C); //end edge samps
}
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R/2; r++)
{
cblas_dcopy(C,&z,0,&X[R/2+r],R);
for (n=1; n<=N; n++)
{
cblas_daxpy(n,-sc*n,&X[r],0,&X[R/2+r],R); //beg edge samps
cblas_daxpy(C-n,-sc*n,&X[r],R,&X[R/2+r+n*R],R); //past samps
cblas_daxpy(C-n,sc*n,&X[r+n*R],R,&X[R/2+r],R); //future samps
cblas_daxpy(n,sc*n,&X[r+R*(C-1)],0,&X[R/2+r+R*(C-n)],R); //end edge samps
}
}
}
else
{
cblas_dcopy(No,&z,0,&X[No],1);
for (r=0; r<R/2; 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
}
}
}
}
else
{
fprintf(stderr,"error in add_deltas_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4542780407,
"avg_line_length": 36.8820754717,
"ext": "c",
"hexsha": "6beb4f4706f482c36f5ffa72a52b957ceb33c285",
"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_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_deltas.c",
"max_line_length": 119,
"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_deltas.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2616,
"size": 7819
} |
#ifndef QDM_ISPLINE_H
#define QDM_ISPLINE_H 1
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
void
qdm_ispline_vector(
gsl_vector *result,
const double tau,
const size_t spline_df,
const gsl_vector *knots
);
void
qdm_ispline_matrix(
gsl_matrix *result,
const gsl_vector *taus,
const size_t spline_df,
const gsl_vector *knots
);
#endif /* QDM_ISPLINE_H */
| {
"alphanum_fraction": 0.7218045113,
"avg_line_length": 16.625,
"ext": "h",
"hexsha": "8b12147a0e12220f6e783d00a89f85adf833ae09",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/ispline.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/ispline.h",
"max_line_length": 27,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/ispline.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 120,
"size": 399
} |
#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>
#pragma comment(lib,"gsl")
int main()
{
printf("%g\n",gsl_sf_bessel_J0(5.0));
return 0;
} | {
"alphanum_fraction": 0.6713286713,
"avg_line_length": 14.3,
"ext": "c",
"hexsha": "dc0fd25f224d5c1827c67512824af0ff6c0b527f",
"lang": "C",
"max_forks_count": 29,
"max_forks_repo_forks_event_max_datetime": "2021-12-24T01:51:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-10T13:25:54.000Z",
"max_forks_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wurui1994/test",
"max_forks_repo_path": "Sources/CLibrary/GSL/gsl_demo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f",
"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": "wurui1994/test",
"max_issues_repo_path": "Sources/CLibrary/GSL/gsl_demo.c",
"max_line_length": 38,
"max_stars_count": 27,
"max_stars_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wurui1994/test",
"max_stars_repo_path": "Sources/CLibrary/GSL/gsl_demo.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-30T13:02:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-19T09:15:36.000Z",
"num_tokens": 49,
"size": 143
} |
#pragma once
#include <Windows.h>
#include <cstdint>
#include <string>
#include <vector>
#include <gsl/span>
#include "hid_handle.h"
namespace hid
{
struct HidOpenFlags
{
enum T : uint32_t
{
none,
exclusive = 1u << 0u,
async = 1u << 1u
};
};
using HidOpenFlags_t = uint32_t;
struct HidCaps
{
uint16_t usage;
uint16_t usagePage;
uint16_t inputReportSize;
uint16_t outputReportSize;
uint16_t featureReportSize;
uint16_t linkCollectionNodes;
uint16_t inputButtonCaps;
uint16_t inputValueCaps;
uint16_t inputDataIndices;
uint16_t outputButtonCaps;
uint16_t outputValueCaps;
uint16_t outputDataIndices;
uint16_t featureButtonCaps;
uint16_t featureValueCaps;
uint16_t featureDataIndices;
};
struct HidAttributes
{
uint16_t vendorId;
uint16_t productId;
uint16_t versionNumber;
};
class HidInstance
{
HidOpenFlags_t flags = 0;
Handle handle = Handle(nullptr, true);
HidCaps caps_ {};
HidAttributes attributes_ {};
OVERLAPPED overlappedIn = {};
OVERLAPPED overlappedOut = {};
bool pendingRead_ = false;
bool pendingWrite_ = false;
size_t nativeError_ = 0;
public:
std::wstring path;
std::wstring instanceId;
std::wstring serialString;
std::vector<uint8_t> inputBuffer;
std::vector<uint8_t> outputBuffer;
HidInstance(const HidInstance&) = delete;
HidInstance& operator=(const HidInstance&) = delete;
HidInstance() = default;
HidInstance(std::wstring path, std::wstring instanceId);
explicit HidInstance(std::wstring path);
HidInstance(HidInstance&& other) noexcept;
~HidInstance();
HidInstance& operator=(HidInstance&& other) noexcept;
bool isOpen() const;
bool isExclusive() const;
bool isAsync() const;
const HidCaps& caps() const;
const HidAttributes& attributes() const;
bool readMetadata();
bool readCaps();
bool readSerial();
bool readAttributes();
bool getFeature(const gsl::span<uint8_t>& buffer) const;
bool setFeature(const gsl::span<uint8_t>& buffer) const;
bool open(HidOpenFlags_t openFlags);
void close();
inline auto nativeError() const
{
return nativeError_;
}
bool read(void* buffer, size_t size) const;
bool read(const gsl::span<uint8_t>& buffer) const;
bool read();
bool readAsync();
bool write(const void* buffer, size_t size) const;
bool write(const gsl::span<const uint8_t>& buffer) const;
bool write() const;
bool writeAsync();
bool asyncReadPending() const;
bool asyncReadInProgress();
bool asyncWritePending() const;
bool asyncWriteInProgress();
void cancelAsyncReadAndWait();
void cancelAsyncWriteAndWait();
bool setOutputReport(const gsl::span<uint8_t>& buffer) const;
bool setOutputReport();
private:
void cancelAsyncAndWait(OVERLAPPED* overlapped);
bool asyncInProgress(OVERLAPPED* overlapped);
bool readCaps(HANDLE h);
bool readSerial(HANDLE h);
bool readAttributes(HANDLE h);
};
}
| {
"alphanum_fraction": 0.724291083,
"avg_line_length": 20.4685314685,
"ext": "h",
"hexsha": "6cca2bbab12f9f6acdac625b72d7f6a67b1386d3",
"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": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SonicFreak94/ds4wizard",
"max_forks_repo_path": "libhid/hid_instance.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SonicFreak94/ds4wizard",
"max_issues_repo_path": "libhid/hid_instance.h",
"max_line_length": 63,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SonicFreak94/ds4wizard",
"max_stars_repo_path": "libhid/hid_instance.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z",
"num_tokens": 801,
"size": 2927
} |
/* interpolation/gsl_interp.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#ifndef __GSL_INTERP_H__
#define __GSL_INTERP_H__
#include <stdlib.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* evaluation accelerator */
typedef struct {
size_t cache; /* cache of index */
size_t miss_count; /* keep statistics */
size_t hit_count;
}
gsl_interp_accel;
/* interpolation object type */
typedef struct {
const char * name;
unsigned int min_size;
void * (*alloc) (size_t size);
int (*init) (void *, const double xa[], const double ya[], size_t size);
int (*eval) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y);
int (*eval_deriv) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_p);
int (*eval_deriv2) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_pp);
int (*eval_integ) (const void *, const double xa[], const double ya[], size_t size, gsl_interp_accel *, double a, double b, double * result);
void (*free) (void *);
} gsl_interp_type;
/* general interpolation object */
typedef struct {
const gsl_interp_type * type;
double xmin;
double xmax;
size_t size;
void * state;
} gsl_interp;
/* available types */
GSL_VAR const gsl_interp_type * gsl_interp_linear;
GSL_VAR const gsl_interp_type * gsl_interp_polynomial;
GSL_VAR const gsl_interp_type * gsl_interp_cspline;
GSL_VAR const gsl_interp_type * gsl_interp_cspline_periodic;
GSL_VAR const gsl_interp_type * gsl_interp_akima;
GSL_VAR const gsl_interp_type * gsl_interp_akima_periodic;
gsl_interp_accel *
gsl_interp_accel_alloc(void);
int
gsl_interp_accel_reset (gsl_interp_accel * a);
void
gsl_interp_accel_free(gsl_interp_accel * a);
gsl_interp *
gsl_interp_alloc(const gsl_interp_type * T, size_t n);
int
gsl_interp_init(gsl_interp * obj, const double xa[], const double ya[], size_t size);
const char * gsl_interp_name(const gsl_interp * interp);
unsigned int gsl_interp_min_size(const gsl_interp * interp);
int
gsl_interp_eval_e(const gsl_interp * obj,
const double xa[], const double ya[], double x,
gsl_interp_accel * a, double * y);
double
gsl_interp_eval(const gsl_interp * obj,
const double xa[], const double ya[], double x,
gsl_interp_accel * a);
int
gsl_interp_eval_deriv_e(const gsl_interp * obj,
const double xa[], const double ya[], double x,
gsl_interp_accel * a,
double * d);
double
gsl_interp_eval_deriv(const gsl_interp * obj,
const double xa[], const double ya[], double x,
gsl_interp_accel * a);
int
gsl_interp_eval_deriv2_e(const gsl_interp * obj,
const double xa[], const double ya[], double x,
gsl_interp_accel * a,
double * d2);
double
gsl_interp_eval_deriv2(const gsl_interp * obj,
const double xa[], const double ya[], double x,
gsl_interp_accel * a);
int
gsl_interp_eval_integ_e(const gsl_interp * obj,
const double xa[], const double ya[],
double a, double b,
gsl_interp_accel * acc,
double * result);
double
gsl_interp_eval_integ(const gsl_interp * obj,
const double xa[], const double ya[],
double a, double b,
gsl_interp_accel * acc);
void
gsl_interp_free(gsl_interp * interp);
INLINE_DECL size_t
gsl_interp_bsearch(const double x_array[], double x,
size_t index_lo, size_t index_hi);
#ifdef HAVE_INLINE
/* Perform a binary search of an array of values.
*
* The parameters index_lo and index_hi provide an initial bracket,
* and it is assumed that index_lo < index_hi. The resulting index
* is guaranteed to be strictly less than index_hi and greater than
* or equal to index_lo, so that the implicit bracket [index, index+1]
* always corresponds to a region within the implicit value range of
* the value array.
*
* Note that this means the relationship of 'x' to x_array[index]
* and x_array[index+1] depends on the result region, i.e. the
* behaviour at the boundaries may not correspond to what you
* expect. We have the following complete specification of the
* behaviour.
* Suppose the input is x_array[] = { x0, x1, ..., xN }
* if ( x == x0 ) then index == 0
* if ( x > x0 && x <= x1 ) then index == 0, and sim. for other interior pts
* if ( x == xN ) then index == N-1
* if ( x > xN ) then index == N-1
* if ( x < x0 ) then index == 0
*/
INLINE_FUN size_t
gsl_interp_bsearch(const double x_array[], double x,
size_t index_lo, size_t index_hi)
{
size_t ilo = index_lo;
size_t ihi = index_hi;
while(ihi > ilo + 1) {
size_t i = (ihi + ilo)/2;
if(x_array[i] > x)
ihi = i;
else
ilo = i;
}
return ilo;
}
#endif
INLINE_DECL size_t
gsl_interp_accel_find(gsl_interp_accel * a, const double x_array[], size_t size, double x);
#ifdef HAVE_INLINE
INLINE_FUN size_t
gsl_interp_accel_find(gsl_interp_accel * a, const double xa[], size_t len, double x)
{
size_t x_index = a->cache;
if(x < xa[x_index]) {
a->miss_count++;
a->cache = gsl_interp_bsearch(xa, x, 0, x_index);
}
else if(x >= xa[x_index + 1]) {
a->miss_count++;
a->cache = gsl_interp_bsearch(xa, x, x_index, len-1);
}
else {
a->hit_count++;
}
return a->cache;
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_INTERP_H__ */
| {
"alphanum_fraction": 0.6527838667,
"avg_line_length": 30.5491071429,
"ext": "h",
"hexsha": "cfc60abc3c46bac3e7a1646599d5107206b8fd4f",
"lang": "C",
"max_forks_count": 30,
"max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z",
"max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gersteinlab/LESSeq",
"max_forks_repo_path": "gsl/include/gsl/gsl_interp.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/interpolation/gsl_interp.h",
"max_line_length": 148,
"max_stars_count": 77,
"max_stars_repo_head_hexsha": "0bd5b3f1e0bc5a02516e7514b2241897337334c2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "iti-luebeck/HANSE2011",
"max_stars_repo_path": "include/gsl/gsl_interp.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z",
"num_tokens": 1716,
"size": 6843
} |
#ifndef RANDOM_H
#define RANDOM_H
extern "C" {
#include <gsl/gsl_rng.h>
#include <gsl/gsl_const_mksa.h>
}
#include <math.h>
#include <mkl.h>
#include <iostream>
#include "matrix.h"
#include "file_IO.h"
// note that the RANDOM package should not has the dependency with lib_traj.h
class RNG_BOOST
{
public:
MKL_LONG N_THREADS_BD;
MKL_LONG N_THREADS_SS;
gsl_rng **BOOST_BD;
gsl_rng **BOOST_SS;
bool INITIALIZATION_BD;
bool INITIALIZATION_SS;
RNG_BOOST()
{
std::cout<< "ERR: basic constructor for RNG_BOOST class is not allowed\n";
}
RNG_BOOST
(COND& given_condition)
{
INITIALIZATION_BD = TRUE;
const gsl_rng_type *T_boost;
N_THREADS_BD = atol(given_condition("N_THREADS_BD").c_str());
BOOST_BD = new gsl_rng* [N_THREADS_BD];
gsl_rng_env_setup();
T_boost = gsl_rng_default;
for(MKL_LONG i=0; i<N_THREADS_BD; i++)
{
BOOST_BD[i] = gsl_rng_alloc(T_boost);
MKL_LONG seed_BD = atol(given_condition("basic_random_seed").c_str());
gsl_rng_set(BOOST_BD[i], seed_BD + i); // it set the seed with index i
}
INITIALIZATION_SS = FALSE; // default
if(given_condition("Method") == "NAPLE_ASSOCIATION")
if(given_condition("Step") != "EQUILIBRATION")
/* given_condition("Step")!="EQUILIBRATION" && given_condition("Method")=="NAPLE_ASSOCIATION") */
// identify the NAPLE_ASSOCIATION topological evolution with equilibration condtion or not
{
INITIALIZATION_SS = TRUE;
N_THREADS_SS = atol(given_condition("N_THREADS_SS").c_str());
/* BOOST_SS = (gsl_rng**)mkl_malloc(N_THREADS_SS*sizeof(gsl_rng*), BIT); */
BOOST_SS = new gsl_rng* [N_THREADS_SS];
for(MKL_LONG i=0; i<N_THREADS_SS; i++)
{
BOOST_SS[i] = gsl_rng_alloc(T_boost);
MKL_LONG seed_SS = atol(given_condition("basic_random_seed_SS").c_str());
gsl_rng_set(BOOST_SS[i], seed_SS + i);
}
}
}
~RNG_BOOST()
{
if(INITIALIZATION_BD)
{
for(MKL_LONG i=0; i<N_THREADS_BD; i++)
{
gsl_rng_free(BOOST_BD[i]);
}
delete[] BOOST_BD;
if(INITIALIZATION_SS)
{
for(MKL_LONG i=0; i<N_THREADS_SS; i++)
{
gsl_rng_free(BOOST_SS[i]);
}
delete[] BOOST_SS;
}
}
}
};
namespace RANDOM
{
MKL_LONG
random_vector_generator
(MATRIX& R_VEC_TRANS);
MKL_LONG
single_random_vector_generator
(MATRIX& given_vec);
MKL_LONG
single_random_vector_generator_variance
(MATRIX& given_vec, double s_2);
MKL_LONG
single_random_vector_generator_boost
(MATRIX& given_vec, gsl_rng* r_boost);
MKL_LONG
single_random_vector_generator_variance_boost
(MATRIX& given_vec, double s_2, gsl_rng* r_boost);
MKL_LONG
single_unit_random_vector_generator
(MATRIX& given_vec);
MKL_LONG
unit_random_vector_generator
(MATRIX& R_VEC_TRANS);
MKL_LONG
unit_random_vector_generator_2D
(MATRIX& R_VEC_TRANS);
MKL_LONG
return_LONG_INT_rand
(MKL_LONG SUP);
MKL_LONG
return_LONG_INT_rand_boost
(gsl_rng* r, MKL_LONG SUP);
double
return_double_rand_SUP1();
double
return_double_rand_SUP1_boost
(gsl_rng* r);
MKL_LONG
get_LONG_ARR_rand_boost
(gsl_rng* r, MKL_LONG SUP, MKL_LONG* given_long_arr, MKL_LONG N_arr);
MKL_LONG
get_DOUBLE_ARR_rand_boost
(gsl_rng* r, double* given_double_arr, MKL_LONG N_arr);
}
#endif
| {
"alphanum_fraction": 0.6562058241,
"avg_line_length": 26.2,
"ext": "h",
"hexsha": "e2ad39d691d9185fc6373dea65d8c80d72ae51be",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gwpark-git/dynamics_of_networks_and_colloids",
"max_forks_repo_path": "lib/random.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gwpark-git/dynamics_of_networks_and_colloids",
"max_issues_repo_path": "lib/random.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gwpark-git/dynamics_of_networks_and_colloids",
"max_stars_repo_path": "lib/random.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 990,
"size": 3537
} |
#ifndef RANDOM_H
#define RANDOM_H
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
extern gsl_rng *rng_state;
void rand_init(int);
int rand_store(void*);
void rand_load(void*, int);
#define SQRT2INV 0.70710678118654752440084436210
#define rand_uniform() gsl_rng_uniform_pos(rng_state)
#define rand_gaussian() gsl_ran_gaussian_ziggurat(rng_state, SQRT2INV)
#define rand_z2() ((rand_uniform() < 0.5) ? SQRT2INV : -SQRT2INV)
#endif
| {
"alphanum_fraction": 0.7790432802,
"avg_line_length": 23.1052631579,
"ext": "h",
"hexsha": "f2ad3709700aa412d7c7e4497031d672b854f0d8",
"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": "73608c26eb096c1fac5213437be2975c0eb7d89b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mrlhansen/YaHMC",
"max_forks_repo_path": "include/random.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73608c26eb096c1fac5213437be2975c0eb7d89b",
"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": "mrlhansen/YaHMC",
"max_issues_repo_path": "include/random.h",
"max_line_length": 70,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "73608c26eb096c1fac5213437be2975c0eb7d89b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mrlhansen/YaHMC",
"max_stars_repo_path": "include/random.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-05T15:09:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-19T13:27:50.000Z",
"num_tokens": 131,
"size": 439
} |
/*
* optimize_tnc.h
*
* Created on: Feb 9, 2010
* Author: smitty
*/
#ifndef _OPTIMIZE_STATE_RECONSTRUCTOR_PERIODS_NLOPT_H_
#define _OPTIMIZE_STATE_RECONSTRUCTOR_PERIODS_NLOPT_H_
#include <nlopt.h>
#include "state_reconstructor.h"
#include "rate_model.h"
#include <armadillo>
using namespace arma;
void optimize_sr_periods_nlopt(vector<RateModel> * _rm,StateReconstructor * _sr,
vector<mat> * _free_mask, int _nfree);
#endif /* _OPTIMIZE_STATE_RECONSTRUCTOR_PERIODS_NLOPT_H_ */
| {
"alphanum_fraction": 0.7730923695,
"avg_line_length": 21.652173913,
"ext": "h",
"hexsha": "11ebc551dc4983a2b60cde6a42cbafb29d52b764",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z",
"max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jlanga/smsk_orthofinder",
"max_forks_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123",
"max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jlanga/smsk_selection",
"max_issues_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.h",
"max_line_length": 80,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jlanga/smsk_selection",
"max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z",
"num_tokens": 141,
"size": 498
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "compearth.h"
#ifdef COMPEARTH_USE_MKL
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#endif
#include <mkl_cblas.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <cblas.h>
#endif
/*!
* @brief Converts v-w coordinates to lune coordinates.
*
* @param[in] nv Number of v coordinates.
* @param[in] v v coordinates s.t. \f$ v \in [-1/3, 1/3] \f$. This
* an array of dimension [nv].
* @param[in] nw Number of w coordinates.
* @param[in] w w coordinates (similar to lune latitudes) s.t.
* \f$ w \in [-3\pi/8, 3/pi/8] \f$. This is an
* array of dimension [nw].
*
* @param[out] gamma Longitude (degrees) \f$ \gamma \in [-30,30] \f$.
* This is an array of dimension [nv].
* @param[out] delta lune latitude (degrees) \f$ \delta \in [-90,90] \f$.
* This is an array of dimension [nw].
*
* @result 0 indicates success.
*
* @author Carl Tape and converted to C by Ben Baker
*
* @date 2016
*
* @copyright MIT
*
*/
int compearth_rect2lune(const int nv, const double *__restrict__ v,
const int nw, const double *__restrict__ w,
double *__restrict__ gamma,
double *__restrict__ delta)
{
double u[CE_CHUNKSIZE] __attribute__((aligned(64)));
int i, j, ierr, nuLoc;
/*
const int maxit = 20;
const int useHalley = 2;
const double tol = 1.e-12;
*/
const double pi38 = 3.0*M_PI/8.0;
const double pi180i = 180.0/M_PI;
ierr = 0;
// convert v -> gamma
compearth_v2gamma(nv, v, gamma);
// convert latitude to colatitude
for (i=0; i<nw; i=i+CE_CHUNKSIZE)
{
nuLoc = MIN(CE_CHUNKSIZE, nw - i);
for (j=0; j<nuLoc; j++)
{
u[j] = pi38 - w[i+j];
}
// convert u -> beta
ierr = compearth_u2beta(nuLoc, u, &delta[i]);
//ierr = compearth_u2beta(nuLoc, maxit, useHalley, u, tol, &delta[i]);
if (ierr != 0)
{
fprintf(stderr, "%s: Computing u2beta\n", __func__);
return -1;
}
}
// convert to gamma to degrees
cblas_dscal(nv, pi180i, gamma, 1);
// convert delta from colatitude to latitude and radians to degrees
#pragma omp simd
for (i=0; i<nw; i++)
{
delta[i] = 90.0 - pi180i*delta[i];
}
return ierr;
}
| {
"alphanum_fraction": 0.5651011837,
"avg_line_length": 29.4269662921,
"ext": "c",
"hexsha": "1ed02eaa2d4c7cacf4d0ad4683f766575b86afb5",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z",
"max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "carltape/mtbeach",
"max_forks_repo_path": "c_src/rect2lune.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "carltape/mtbeach",
"max_issues_repo_path": "c_src/rect2lune.c",
"max_line_length": 78,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OUCyf/mtbeach",
"max_stars_repo_path": "c_src/rect2lune.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z",
"num_tokens": 761,
"size": 2619
} |
/* vector/gsl_vector_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_DOUBLE_H__
#define __GSL_VECTOR_DOUBLE_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_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 *block;
int owner;
}
gsl_vector;
typedef struct
{
gsl_vector vector;
} _gsl_vector_view;
typedef _gsl_vector_view gsl_vector_view;
typedef struct
{
gsl_vector vector;
} _gsl_vector_const_view;
typedef const _gsl_vector_const_view gsl_vector_const_view;
/* Allocation */
GSL_EXPORT gsl_vector *gsl_vector_alloc (const size_t n);
GSL_EXPORT gsl_vector *gsl_vector_calloc (const size_t n);
GSL_EXPORT gsl_vector *gsl_vector_alloc_from_block (gsl_block * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT gsl_vector *gsl_vector_alloc_from_vector (gsl_vector * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT void gsl_vector_free (gsl_vector * v);
/* Views */
GSL_EXPORT
_gsl_vector_view
gsl_vector_view_array (double *v, size_t n);
GSL_EXPORT
_gsl_vector_view
gsl_vector_view_array_with_stride (double *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_const_view
gsl_vector_const_view_array (const double *v, size_t n);
GSL_EXPORT
_gsl_vector_const_view
gsl_vector_const_view_array_with_stride (const double *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_view
gsl_vector_subvector (gsl_vector *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_view
gsl_vector_subvector_with_stride (gsl_vector *v,
size_t i,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_const_view
gsl_vector_const_subvector (const gsl_vector *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_const_view
gsl_vector_const_subvector_with_stride (const gsl_vector *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_EXPORT double gsl_vector_get (const gsl_vector * v, const size_t i);
GSL_EXPORT void gsl_vector_set (gsl_vector * v, const size_t i, double x);
GSL_EXPORT double *gsl_vector_ptr (gsl_vector * v, const size_t i);
GSL_EXPORT const double *gsl_vector_const_ptr (const gsl_vector * v, const size_t i);
GSL_EXPORT void gsl_vector_set_zero (gsl_vector * v);
GSL_EXPORT void gsl_vector_set_all (gsl_vector * v, double x);
GSL_EXPORT int gsl_vector_set_basis (gsl_vector * v, size_t i);
GSL_EXPORT int gsl_vector_fread (FILE * stream, gsl_vector * v);
GSL_EXPORT int gsl_vector_fwrite (FILE * stream, const gsl_vector * v);
GSL_EXPORT int gsl_vector_fscanf (FILE * stream, gsl_vector * v);
GSL_EXPORT int gsl_vector_fprintf (FILE * stream, const gsl_vector * v,
const char *format);
GSL_EXPORT int gsl_vector_memcpy (gsl_vector * dest, const gsl_vector * src);
GSL_EXPORT int gsl_vector_reverse (gsl_vector * v);
GSL_EXPORT int gsl_vector_swap (gsl_vector * v, gsl_vector * w);
GSL_EXPORT int gsl_vector_swap_elements (gsl_vector * v, const size_t i, const size_t j);
GSL_EXPORT double gsl_vector_max (const gsl_vector * v);
GSL_EXPORT double gsl_vector_min (const gsl_vector * v);
GSL_EXPORT void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out);
GSL_EXPORT size_t gsl_vector_max_index (const gsl_vector * v);
GSL_EXPORT size_t gsl_vector_min_index (const gsl_vector * v);
GSL_EXPORT void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax);
GSL_EXPORT int gsl_vector_add (gsl_vector * a, const gsl_vector * b);
GSL_EXPORT int gsl_vector_sub (gsl_vector * a, const gsl_vector * b);
GSL_EXPORT int gsl_vector_mul (gsl_vector * a, const gsl_vector * b);
GSL_EXPORT int gsl_vector_div (gsl_vector * a, const gsl_vector * b);
GSL_EXPORT int gsl_vector_scale (gsl_vector * a, const double x);
GSL_EXPORT int gsl_vector_add_constant (gsl_vector * a, const double x);
GSL_EXPORT int gsl_vector_isnull (const gsl_vector * v);
#ifdef HAVE_INLINE
extern inline
double
gsl_vector_get (const gsl_vector * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
extern inline
void
gsl_vector_set (gsl_vector * v, const size_t i, double x)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
extern inline
double *
gsl_vector_ptr (gsl_vector * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (double *) (v->data + i * v->stride);
}
extern inline
const double *
gsl_vector_const_ptr (const gsl_vector * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const double *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_DOUBLE_H__ */
| {
"alphanum_fraction": 0.6580174927,
"avg_line_length": 29.1914893617,
"ext": "h",
"hexsha": "8aa4af445b8f0a9dd01c678809792e686200681a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_double.h",
"max_line_length": 93,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_double.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1655,
"size": 6860
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.