Search is not available for this dataset
text
string
meta
dict
/* cheb/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_chebyshev.h> double f_T0 (double x, void * p) { p = 0; return 1.0; } double f_T1 (double x, void * p) { p = 0; return x; } double f_T2 (double x, void * p) { p = 0; return 2*x*x - 1; } double f_sin (double x, void * p) { p = 0; return sin(x); } int main(void) { double tol = 100.0 * GSL_DBL_EPSILON; double ftol = 20.0; double x; size_t i; gsl_cheb_series * cs = gsl_cheb_alloc(40); gsl_cheb_series * csd = gsl_cheb_alloc(40); gsl_cheb_series * csi = gsl_cheb_alloc(40); gsl_function F_sin, F_T0, F_T1, F_T2; F_sin.function = f_sin; F_sin.params = 0; F_T0.function = f_T0; F_T0.params = 0; F_T1.function = f_T1; F_T1.params = 0; F_T2.function = f_T2; F_T2.params = 0; gsl_ieee_env_setup(); gsl_cheb_init(cs, &F_T0, -1.0, 1.0); { size_t expected = 40; size_t order = gsl_cheb_order (cs); size_t size = gsl_cheb_size (cs); double * p = gsl_cheb_coeffs (cs); gsl_test(order != expected, "gsl_cheb_order"); gsl_test(size != expected + 1, "gsl_cheb_size"); gsl_test(p != cs->c, "gsl_cheb_coeffs"); } for (i = 0; i<cs->order; i++) { double c_exp = (i == 0) ? 2.0 : 0.0; gsl_test_abs (cs->c[i], c_exp, tol, "c[%d] for T_0(x)", i); } gsl_cheb_init(cs, &F_T1, -1.0, 1.0); for (i = 0; i<cs->order; i++) { double c_exp = (i == 1) ? 1.0 : 0.0; gsl_test_abs (cs->c[i], c_exp, tol, "c[%d] for T_1(x)", i); } gsl_cheb_init(cs, &F_T2, -1.0, 1.0); for (i = 0; i<cs->order; i++) { double c_exp = (i == 2) ? 1.0 : 0.0; gsl_test_abs (cs->c[i], c_exp, tol, "c[%d] for T_2(x)", i); } gsl_cheb_init(cs, &F_sin, -M_PI, M_PI); gsl_test_abs (cs->c[0], 0.0, tol, "c[0] for F_sin(x)"); gsl_test_abs (cs->c[1], 5.69230686359506e-01, tol, "c[1] for F_sin(x)"); gsl_test_abs (cs->c[2], 0.0, tol, "c[2] for F_sin(x)"); gsl_test_abs (cs->c[3], -6.66916672405979e-01, tol, "c[3] for F_sin(x)"); gsl_test_abs (cs->c[4], 0.0, tol, "c[4] for F_sin(x)"); gsl_test_abs (cs->c[5], 1.04282368734237e-01, tol, "c[5] for F_sin(x)"); for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r = gsl_cheb_eval(cs, x); gsl_test_abs(r, sin(x), tol, "gsl_cheb_eval, sin(%.3g)", x); } for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r, e; gsl_cheb_eval_err(cs, x, &r, &e); gsl_test_abs(r, sin(x), tol, "gsl_cheb_eval_err, sin(%.3g)", x); gsl_test_factor(fabs(r-sin(x)) + GSL_DBL_EPSILON, e, ftol, "gsl_cheb_eval_err, error sin(%.3g)", x); } for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r = gsl_cheb_eval_n(cs, 25, x); gsl_test_abs(r, sin(x), tol, "gsl_cheb_eval_n, sin(%.3g)", x); } for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r, e; gsl_cheb_eval_n_err(cs, 25, x, &r, &e); gsl_test_abs(r, sin(x), 100.0 * tol, "gsl_cheb_eval_n_err, deriv sin(%.3g)", x); gsl_test_factor(fabs(r-sin(x)) + GSL_DBL_EPSILON, e, ftol, "gsl_cheb_eval_n_err, error sin(%.3g)", x); } /* Test derivative */ gsl_cheb_calc_deriv(csd, cs); for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r = gsl_cheb_eval(csd, x); gsl_test_abs(r, cos(x), 1600 * tol, "gsl_cheb_eval, deriv sin(%.3g)", x); } #ifdef TEST_DERIVATIVE_ERR for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r, e; gsl_cheb_eval_err(csd, x, &r, &e); gsl_test_abs(r, cos(x), tol, "gsl_cheb_eval_err, deriv sin(%.3g)", x); gsl_test_factor(fabs(r-cos(x)) + GSL_DBL_EPSILON, e, ftol, "gsl_cheb_eval_err, deriv error sin(%.3g)", x); } #endif for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r = gsl_cheb_eval_n(csd, 25, x); gsl_test_abs(r, cos(x), 1600 * tol, "gsl_cheb_eval_n, deriv sin(%.3g)", x); } #ifdef TEST_DERIVATIVE_ERR for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r, e; gsl_cheb_eval_n_err(csd, 25, x, &r, &e); gsl_test_abs(r, cos(x), 100.0 * tol, "gsl_cheb_eval_n_err, deriv sin(%.3g)", x); gsl_test_factor(fabs(r-cos(x)) + GSL_DBL_EPSILON, e, ftol, "gsl_cheb_eval_n_err, deriv error sin(%.3g)", x); } #endif /* Test integral */ gsl_cheb_calc_integ(csi, cs); for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r = gsl_cheb_eval(csi, x); gsl_test_abs(r, -(1+cos(x)), tol, "gsl_cheb_eval, integ sin(%.3g)", x); } #ifdef TEST_INTEGRAL_ERR for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r, e; gsl_cheb_eval_err(csi, x, &r, &e); gsl_test_abs(r, -(1+cos(x)), tol, "gsl_cheb_eval_err, integ sin(%.3g)", x); gsl_test_factor(fabs(r-(-1-cos(x))) + GSL_DBL_EPSILON, e, ftol, "gsl_cheb_eval_err, integ error sin(%.3g)", x); } #endif for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r = gsl_cheb_eval_n(csi, 25, x); gsl_test_abs(r, -(1+cos(x)), tol, "gsl_cheb_eval_n, integ sin(%.3g)", x); } #ifdef TEST_INTEGRAL_ERR for(x=-M_PI; x<M_PI; x += M_PI/100.0) { double r, e; gsl_cheb_eval_n_err(csi, 25, x, &r, &e); gsl_test_abs(r, -(1+cos(x)), 100.0 * tol, "gsl_cheb_eval_n_err, integ sin(%.3g)", x); gsl_test_factor(fabs(r-(-1-cos(x))) + GSL_DBL_EPSILON, e, ftol, "gsl_cheb_eval_n_err, integ error sin(%.3g)", x); } #endif gsl_cheb_free(csi); gsl_cheb_free(csd); gsl_cheb_free(cs); exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.6049578897, "avg_line_length": 28.7351598174, "ext": "c", "hexsha": "1e1a2906f11faf6412ae9de535413bf2a490388f", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cheb/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "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": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cheb/test.c", "max_line_length": 89, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/cheb/test.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 2375, "size": 6293 }
#include <petsc.h> #include <petsc/private/petscimpl.h> #if PETSC_VERSION_LT(3,17,0) #undef SETERRQ #define SETERRQ(comm,ierr,...) return PetscError(comm,__LINE__,PETSC_FUNCTION_NAME,__FILE__,ierr,PETSC_ERROR_INITIAL,__VA_ARGS__) #endif PETSC_EXTERN PetscErrorCode IGA_Partition(PetscInt,PetscInt,PetscInt,const PetscInt[],PetscInt[],PetscInt[]); PETSC_EXTERN PetscErrorCode IGA_Distribute(PetscInt,const PetscInt[],const PetscInt[],const PetscInt[],PetscInt[],PetscInt[]); static inline PetscInt IGA_CUT2D(PetscInt M,PetscInt N, PetscInt m,PetscInt n) {return M*(n-1) + N*(m-1);} static inline PetscInt IGA_CUT3D(PetscInt M,PetscInt N,PetscInt P, PetscInt m,PetscInt n,PetscInt p) {return (N*P*(m-1) + M*P*(n-1) + M*N*(p-1));} static inline PetscInt IGA_PART2D_INNER(PetscInt size, PetscInt M,PetscInt N, PetscInt *_m,PetscInt *_n) { PetscInt m,n; m = (PetscInt)(0.5 + sqrt(((double)M)/((double)N)*((double)size))); if (m == 0) {m = 1;} while (m > 0 && size % m) m--; n = size / m; *_m = m; *_n = n; return IGA_CUT2D(M,N,m,n); } static inline void IGA_PART2D(PetscInt size, PetscInt M,PetscInt N, PetscInt *_m,PetscInt *_n) { PetscInt m,n; PetscInt m1,n1,a; PetscInt m2,n2,b; a = IGA_PART2D_INNER(size,M,N,&m1,&n1); b = IGA_PART2D_INNER(size,N,M,&n2,&m2); if (a<b) {m = m1; n = n1;} else {m = m2; n = n2;} if (M == N && n < m) {PetscInt t = m; m = n; n = t;} *_m = m; *_n = n; } static inline PetscInt IGA_PART3D_INNER(PetscInt size, PetscInt M,PetscInt N,PetscInt P, PetscInt *_m,PetscInt *_n,PetscInt *_p) { PetscInt m,n,p,C; PetscInt mm,nn,pp,CC; /**/ m = (PetscInt)(0.5 + pow(((double)M*(double)M)/((double)N*(double)P)*(double)size,1./3.)); if (m == 0) {m = 1;} while (m > 0 && size % m) m--; /**/ IGA_PART2D(size/m,N,P,&n,&p); C = IGA_CUT3D(M,N,P,m,n,p); /**/ for (mm=m; mm>=1; mm--) { if (size % mm) continue; IGA_PART2D(size/mm,N,P,&nn,&pp); CC = IGA_CUT3D(M,N,P,mm,nn,pp); if (CC < C) {m = mm; n = nn; p = pp; C = CC;} } /**/ for (nn=n; nn>=1; nn--) { if (size % nn) continue; IGA_PART2D(size/nn,M,P,&mm,&pp); CC = IGA_CUT3D(M,N,P,mm,nn,pp); if (CC < C) {m = mm; n = nn; p = pp; C = CC;} } /**/ for (pp=p; pp>=1; pp--) { if (size % pp) continue; IGA_PART2D(size/pp,M,N,&mm,&nn); CC = IGA_CUT3D(M,N,P,mm,nn,pp); if (CC < C) {m = mm; n = nn; p = pp; C = CC;} } /**/ *_m = m; *_n = n; *_p = p; return IGA_CUT3D(M,N,P,m,n,p); } static inline void IGA_PART3D(PetscInt size, PetscInt M,PetscInt N,PetscInt P, PetscInt *_m,PetscInt *_n,PetscInt *_p) { PetscInt m[3],n[3],p[3],C[3],k,i=0,Cmin=PETSC_MAX_INT,t; C[0] = IGA_PART3D_INNER(size,M,N,P,&m[0],&n[0],&p[0]); C[1] = IGA_PART3D_INNER(size,N,M,P,&n[1],&m[1],&p[1]); C[2] = IGA_PART3D_INNER(size,P,M,N,&p[2],&m[2],&n[2]); for (k=0; k<3; k++) if (C[k]<Cmin) {Cmin=C[k]; i=k;} if (M == N && n[i] < m[i]) {t = m[i]; m[i] = n[i]; n[i] = t;} if (M == P && p[i] < m[i]) {t = m[i]; m[i] = p[i]; p[i] = t;} if (N == P && p[i] < n[i]) {t = n[i]; n[i] = p[i]; p[i] = t;} *_m = m[i]; *_n = n[i]; *_p = p[i]; } static inline void IGA_Part2D(PetscInt size, PetscInt M,PetscInt N, PetscInt *_m,PetscInt *_n) { PetscInt m,n; m = *_m; n = *_n; if (m < 1 && n < 1) IGA_PART2D(size,M,N,&m,&n); else if (m < 1) m = size / n; else if (n < 1) n = size / m; *_m = m; *_n = n; } static inline void IGA_Part3D(PetscInt size, PetscInt M,PetscInt N,PetscInt P, PetscInt *_m,PetscInt *_n,PetscInt *_p) { PetscInt m,n,p; m = *_m; n = *_n; p = *_p; if (m < 1 && n < 1 && p < 1) IGA_PART3D(size,M,N,P,&m,&n,&p); else if (m < 1 && n < 1) IGA_PART2D(size/p,M,N,&m,&n); else if (m < 1 && p < 1) IGA_PART2D(size/n,M,P,&m,&p); else if (n < 1 && p < 1) IGA_PART2D(size/m,N,P,&n,&p); else if (m < 1) m = size / (n*p); else if (n < 1) n = size / (m*p); else if (p < 1) p = size / (m*n); *_m = m; *_n = n; *_p = p; } PetscErrorCode IGA_Partition(PetscInt size,PetscInt rank, PetscInt dim,const PetscInt N[], PetscInt n[],PetscInt i[]) { PetscInt k,p=1,m[3]={1,1,1}; PetscFunctionBegin; PetscValidIntPointer(N,4); PetscValidIntPointer(n,5); if (i) PetscValidIntPointer(i,6); if (size < 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Number of partitions %D must be positive",size); if (i && (rank < 0 || rank >= size)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Partition index %D must be in range [0,%D]",rank,size-1); switch (dim) { case 3: IGA_Part3D(size,N[0],N[1],N[2],&n[0],&n[1],&n[2]); break; case 2: IGA_Part2D(size,N[0],N[1],&n[0],&n[1]); break; case 1: if (n[0] < 1) n[0] = size; break; default: SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Number of dimensions %D must be in range [1,3]",dim); } for (k=0; k<dim; k++) p *= (m[k] = n[k]); if (p != size) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Bad partition, prod(%D,%D,%D) != %D",m[0],m[1],m[2],size); for (k=0; k<dim; k++) if (N[k] < n[k]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Partition %D is too fine, %D elements in %D parts",k,N[k],n[k]); if (i) for (k=0; k<dim; k++) { i[k] = rank % n[k]; rank -= i[k]; rank /= n[k]; } PetscFunctionReturn(0); } static inline void IGA_Dist1D(PetscInt size,PetscInt rank, PetscInt N,PetscInt *n,PetscInt *s) { *n = N/size + ((N % size) > rank); *s = rank * (N/size) + (((N % size) > rank) ? rank : (N % size)); } PetscErrorCode IGA_Distribute(PetscInt dim, const PetscInt size[],const PetscInt rank[], const PetscInt N[],PetscInt n[],PetscInt s[]) { PetscInt k; PetscFunctionBegin; PetscValidIntPointer(size,2); PetscValidIntPointer(rank,3); PetscValidIntPointer(N,4); PetscValidIntPointer(n,5); PetscValidIntPointer(s,6); if (dim < 1 || dim > 3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Number of dimensions %D must be in range [1,3]",dim); for (k=0; k<dim; k++) { if (size[k] < 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Number of partitions %D must be positive",size[k]); if (rank[k] < 0 || rank[k] >= size[k]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Partition index %D must be in range [0,%D]",rank[k],size[k]-1); if (N[k] < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Number of elements %D must be non-negative",N[k]); } for (k=0; k<dim; k++) IGA_Dist1D(size[k],rank[k],N[k],&n[k],&s[k]); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.5582733813, "avg_line_length": 34.236453202, "ext": "c", "hexsha": "053f5488c4c41a2925790cd0e16ec663a3bcebbe", "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": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "dalcinl/PetIGA", "max_forks_repo_path": "src/petigapart.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "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": "dalcinl/PetIGA", "max_issues_repo_path": "src/petigapart.c", "max_line_length": 135, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "dalcinl/PetIGA", "max_stars_repo_path": "src/petigapart.c", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:56:49.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-19T17:19:43.000Z", "num_tokens": 2675, "size": 6950 }
#pragma once #include "rev/Utilities.h" #include "rev/geometry/Tools.h" #include <array> #include <glm/glm.hpp> #include <gsl/gsl_assert> #include <iostream> #include <limits> #include <set> #include <unordered_set> #include <variant> #include <vector> namespace rev { template <typename SurfaceData> struct Triangle { std::array<glm::vec3, 3> vertices; SurfaceData data; AxisAlignedBoundingBox getBoundingBox() const { AxisAlignedBoundingBox box; for (const auto& vertex : vertices) { box.expandToVertex(vertex); } return box; } glm::vec3 getNormal() const { auto e1 = vertices[1] - vertices[0]; auto e2 = vertices[2] - vertices[0]; return glm::normalize(glm::cross(e1, e2)); } bool isLeftOfPlane(const AxisAlignedPlane& plane) const { for (const auto& vertex : vertices) { if (vertex[plane.dimensionIndex] < plane.boundary) { return true; } } return false; } bool isRightOfPlane(const AxisAlignedPlane& plane) const { for (const auto& vertex : vertices) { if (vertex[plane.dimensionIndex] > plane.boundary) { return true; } } return false; } std::optional<AxisAlignedBoundingBox> clippedBoundingBox(const AxisAlignedBoundingBox& box) { // Alternate between these two buffers for input and output std::array<glm::vec3, 9> buf1{}; std::array<glm::vec3, 9> buf2{}; // Fill the input buffer for (int i = 0; i < 3; i++) { buf1[i] = vertices[i]; } // Clip the triangle by all sides of our bounding box auto inputIter = buf1.data(); auto inputEnd = inputIter + 3; auto outputIter = buf2.data(); // First the min planes in each dimension for (uint8_t dim = 0; dim < 3; dim++) { gsl::span<glm::vec3> inputRange(inputIter, inputEnd); OutputIteratorPolygonBuilder builder(outputIter); AxisAlignedPlane boundary = { dim, box.minimum[dim] }; boundary.splitConvexPolygon(inputRange, NullPolygonBuilder(), builder); if (std::distance(outputIter, builder.getIterator()) < 3) { return {}; } std::swap(inputIter, outputIter); inputEnd = builder.getIterator(); } // Now the max planes in each dimension for (uint8_t dim = 0; dim < 3; dim++) { gsl::span<glm::vec3> inputRange(inputIter, inputEnd); OutputIteratorPolygonBuilder builder(outputIter); AxisAlignedPlane boundary = { dim, box.maximum[dim] }; boundary.splitConvexPolygon(inputRange, builder, NullPolygonBuilder()); if (std::distance(outputIter, builder.getIterator()) < 3) { return {}; } std::swap(inputIter, outputIter); inputEnd = builder.getIterator(); } gsl::span<glm::vec3> inputRange(inputIter, inputEnd); auto clippedBox = smallestBoxContainingVertices(inputRange); clippedBox.reduceToBox(box); return clippedBox; } struct Hit { glm::vec2 uv; float t; }; std::optional<Hit> castRay(const Ray& ray) const { glm::vec3 edge1 = vertices[1] - vertices[0]; glm::vec3 edge2 = vertices[2] - vertices[0]; glm::vec3 p = glm::cross(ray.direction, edge2); float determinant = glm::dot(edge1, p); if (abs(determinant) < std::numeric_limits<float>::epsilon()) { // The ray is parallel. return std::nullopt; } glm::vec3 fromV0 = ray.origin - vertices[0]; float u = glm::dot(fromV0, p) / determinant; if (u < 0.0f || u > 1.0f) { return std::nullopt; } glm::vec3 q = glm::cross(fromV0, edge1); float v = glm::dot(ray.direction, q) / determinant; if (v < 0.0f || v > 1.0f) { return std::nullopt; } float t = glm::dot(edge2, q) / determinant; if (t < 0.0f) { return std::nullopt; } return Hit{ { u, v }, t }; } glm::vec3 baryCentricToCartesian(glm::vec2 uv) { float u = uv[0]; float v = uv[1]; float w = 1.0f - (u + v); return w * vertices[0] + u * vertices[1] + v * vertices[2]; } glm::vec2 cartesianToBarycentric(glm::vec3 position) { glm::vec3 v0 = vertices[1] - vertices[0]; glm::vec3 v1 = vertices[2] - vertices[0]; glm::vec3 v2 = position - vertices[0]; float d00 = glm::dot(v0, v0); float d01 = glm::dot(v0, v1); float d11 = glm::dot(v1, v1); float d20 = glm::dot(v2, v0); float d21 = glm::dot(v2, v1); float denom = d00 * d11 - d01 * d01; float v = (d11 * d20 - d01 * d21) / denom; float w = (d00 * d21 - d01 * d20) / denom; float u = 1.0f - v - w; return { u, v }; } std::optional<float> intersectsSphere(const Sphere& sphere) { glm::vec3 normal = getNormal(); float t = glm::dot(normal, (vertices[0] - sphere.center)); if (sphere.radius < abs(t)) { // Closest point to the triangle is outside the sphere. return std::nullopt; } glm::vec3 closestPoint = sphere.center - (normal * t); glm::vec2 cpBary = cartesianToBarycentric(closestPoint); size_t outsideCount = 0; glm::bvec3 isOutside{}; if (cpBary[0] < 0.0f) { outsideCount++; isOutside[0] = true; } if (cpBary[1] < 0.0f) { outsideCount++; isOutside[1] = true; } if ((1.0f - (cpBary[0] + cpBary[1])) < 0.0f) { outsideCount++; isOutside[2] = true; } if (outsideCount == 0) { // Closest point is inside the triangle and inside the sphere. return t; } // Calculate the square of the radius of the cross section of the sphere passing through // the triangle's plane. float r2 = (sphere.radius * sphere.radius) - (t * t); if (outsideCount == 1) { // We need to find the distance to the edge (squared) here. glm::vec3 edge; glm::vec3 toVertex; if (isOutside[0]) { edge = vertices[2] - vertices[1]; toVertex = closestPoint - vertices[1]; } else if (isOutside[1]) { edge = vertices[2] - vertices[0]; toVertex = closestPoint - vertices[0]; } else { edge = vertices[1] - vertices[0]; toVertex = closestPoint - vertices[0]; } float toVertexLength = glm::length(toVertex); float legLength = glm::dot(edge, toVertex) / toVertexLength; return ((toVertexLength * toVertexLength) - (legLength * legLength)) < r2; } // Otherwise, one of the vertices is actually the closest point on the triangle. glm::vec3 toVertex; if (!isOutside[0]) { toVertex = closestPoint - vertices[0]; } else if (!isOutside[1]) { toVertex = closestPoint - vertices[1]; } else { toVertex = closestPoint - vertices[2]; } return glm::dot(toVertex, toVertex) < r2; } }; template <typename SurfaceData> struct LeafNode { std::unordered_set<Triangle<SurfaceData>*> triangles; }; template <typename SurfaceData> struct BranchNode; template <typename SurfaceData> using MapNode = std::variant<LeafNode<SurfaceData>, BranchNode<SurfaceData>>; template <typename SurfaceData> struct BranchNode { AxisAlignedPlane split; std::unique_ptr<MapNode<SurfaceData>> left; std::unique_ptr<MapNode<SurfaceData>> right; }; template <typename SurfaceData> class KDTree { public: KDTree(std::vector<std::unique_ptr<Triangle<SurfaceData>>> triangles, std::unique_ptr<MapNode<SurfaceData>> root, const AxisAlignedBoundingBox boundingBox) : _triangles(std::move(triangles)) , _root(std::move(root)) , _boundingBox(boundingBox) { } struct Hit { Triangle<SurfaceData>* triangle; glm::vec2 uv; float t; }; std::optional<Hit> castRay( const Ray& ray, float maxDistance = std::numeric_limits<float>::infinity()) const { if (_boundingBox.containsPoint(ray.origin)) { AxisAlignedBoundingBox::Hit entryPoint{ ray.origin, 0.0f, 0 }; return getHit(*_root, ray, _boundingBox, entryPoint, maxDistance); } else { auto hit = _boundingBox.castExternalRay(ray); if (!hit || (hit->t > maxDistance)) { return std::nullopt; } return getHit(*_root, ray, _boundingBox, *hit, maxDistance); } } template <typename Visitor> void visitTrianglesIntersectingSphere(const Sphere& sphere, Visitor&& visitor) const { std::visit( [this, &sphere, &visitor](const auto& node) { visitTrianglesIntersectingSphereInNode( sphere, std::forward<Visitor>(visitor), _boundingBox, node); }, *_root); } void dump() const { std::cout << "[KDTree]{" << std::endl; printBoundingBox(_boundingBox, 2); std::visit([this](const auto& root) { printNode(_boundingBox, root, 2); }, *_root); std::cout << "}" << std::endl; } private: std::optional<Hit> getHit(const MapNode<SurfaceData>& node, const Ray& ray, const AxisAlignedBoundingBox& box, AxisAlignedBoundingBox::Hit& entryPoint, float maxDistance) const { return std::visit( [this, &ray, &box, &entryPoint, maxDistance]( const auto& node) { return getHit(node, ray, box, entryPoint, maxDistance); }, node); } std::optional<Hit> getHit(const BranchNode<SurfaceData>& node, const Ray& ray, const AxisAlignedBoundingBox& box, AxisAlignedBoundingBox::Hit& entryPoint, float maxDistance) const { auto [leftBox, rightBox] = box.split(node.split); float position = entryPoint.intersectionPoint[node.split.dimensionIndex]; bool goLeft; if (position < node.split.boundary) { goLeft = true; } else if (position > node.split.boundary) { goLeft = false; } else if (ray.direction[node.split.dimensionIndex] < 0.0f) { goLeft = false; } else if (ray.direction[node.split.dimensionIndex] > 0.0f) { goLeft = true; } else { return std::nullopt; } MapNode<SurfaceData>* childNode = goLeft ? node.left.get() : node.right.get(); auto hit = getHit(*childNode, ray, (goLeft ? leftBox : rightBox), entryPoint, maxDistance); if (hit) { return hit; } if (entryPoint.t > maxDistance) { return std::nullopt; } if (entryPoint.planeDimension != node.split.dimensionIndex) { return std::nullopt; } bool shouldTryOtherChild; if (goLeft) { shouldTryOtherChild = (ray.direction[node.split.dimensionIndex] > 0.0f); } else { shouldTryOtherChild = (ray.direction[node.split.dimensionIndex] < 0.0f); } if (shouldTryOtherChild) { childNode = goLeft ? node.right.get() : node.left.get(); return getHit(*childNode, ray, (goLeft ? rightBox : leftBox), entryPoint, maxDistance); } return std::nullopt; } std::optional<Hit> getHit(const LeafNode<SurfaceData>& node, const Ray& ray, const AxisAlignedBoundingBox& box, AxisAlignedBoundingBox::Hit& entryPoint, float maxDistance) const { float t = std::numeric_limits<float>::infinity(); std::optional<Hit> bestHit; for (const auto& triangle : node.triangles) { auto hit = triangle->castRay(ray); if (hit) { if (!bestHit || (hit->t < bestHit->t)) { bestHit = Hit{ triangle, hit->uv, hit->t }; } } } if (bestHit && !(bestHit->t > maxDistance)) { return bestHit; } auto boxHit = box.castInternalRay(ray); entryPoint = boxHit; return std::nullopt; } template <typename Visitor> void visitTrianglesIntersectingSphereInNode(const Sphere& sphere, Visitor&& visitor, const AxisAlignedBoundingBox& box, const LeafNode<SurfaceData>& node) const { if (!box.intersectsSphere(sphere)) { return; } for (const auto& triangle : node.triangles) { auto hit = triangle->intersectsSphere(sphere); if (hit) { visitor(*triangle, *hit); } } } template <typename Visitor> void visitTrianglesIntersectingSphereInNode(const Sphere& sphere, Visitor&& visitor, const AxisAlignedBoundingBox& box, const BranchNode<SurfaceData>& node) const { if (!box.intersectsSphere(sphere)) { return; } auto [leftBox, rightBox] = box.split(node.split); std::visit( [this, leftBox = leftBox, &sphere, &visitor](const auto& node) { visitTrianglesIntersectingSphereInNode( sphere, std::forward<Visitor>(visitor), leftBox, node); }, *node.left); std::visit( [this, rightBox = rightBox, &sphere, &visitor](const auto& node) { visitTrianglesIntersectingSphereInNode( sphere, std::forward<Visitor>(visitor), rightBox, node); }, *node.right); } void printIndent(size_t indent = 0) const { for (size_t i = 0; i < indent; i++) { std::cout << " "; } } void printVertex(const glm::vec3& vertex) const { std::cout << "(" << vertex.x << ", " << vertex.y << ", " << vertex.z << ")"; } void printBoundingBox(const AxisAlignedBoundingBox& box, size_t indent = 0) const { printIndent(indent); std::cout << "[Box]{ Min: "; printVertex(box.minimum); std::cout << " Max: "; printVertex(box.maximum); std::cout << " }" << std::endl; } void printTriangle(const Triangle<SurfaceData>& triangle, size_t indent = 0) const { printIndent(indent); std::cout << "[Triangle]{" << std::endl; for (const auto& vertex : triangle.vertices) { printIndent(indent + 2); printVertex(vertex); std::cout << std::endl; } printIndent(indent); std::cout << "}" << std::endl; } void printNode(const AxisAlignedBoundingBox& box, const LeafNode<SurfaceData>& node, size_t indent = 0) const { printIndent(indent); std::cout << "[Leaf]{" << std::endl; printBoundingBox(box, indent + 2); for (const auto& triangle : node.triangles) { printTriangle(*triangle, indent + 2); } printIndent(indent); std::cout << "}" << std::endl; } void printNode(const AxisAlignedBoundingBox& box, const BranchNode<SurfaceData>& node, size_t indent = 0) const { printIndent(indent); std::cout << "[Branch]{" << std::endl; printBoundingBox(box, indent + 2); auto [leftBox, rightBox] = box.split(node.split); std::visit([this, indent, leftBox = leftBox]( const auto& childNode) { printNode(leftBox, childNode, indent + 2); }, *node.left); std::visit([this, indent, rightBox = rightBox]( const auto& childNode) { printNode(rightBox, childNode, indent + 2); }, *node.right); printIndent(indent); std::cout << "}" << std::endl; } std::vector<std::unique_ptr<Triangle<SurfaceData>>> _triangles; std::unique_ptr<MapNode<SurfaceData>> _root; AxisAlignedBoundingBox _boundingBox; }; template <typename SurfaceData> class KDTreeBuilder { public: void addTriangle(std::array<glm::vec3, 3> vertices, SurfaceData data) { Expects(!glm::any(glm::isnan(vertices[0]))); Expects(!glm::any(glm::isnan(vertices[1]))); Expects(!glm::any(glm::isnan(vertices[2]))); auto triangle = std::make_unique<Triangle<SurfaceData>>(Triangle<SurfaceData>{ vertices, data }); auto boundingBox = smallestBoxContainingVertices(vertices); _boundingBox.expandToBox(boundingBox); for (const auto& event : buildTriangleEvents(boundingBox, triangle.get())) { _events.insert(event); } _triangles.push_back(std::move(triangle)); } KDTree<SurfaceData> build() { Expects(!_triangles.empty()); Expects(!_events.empty()); std::unordered_set<Triangle<SurfaceData>*> triangleSet; for (const auto& triangle : _triangles) { triangleSet.insert(triangle.get()); } auto rootNode = createNode(_boundingBox, std::move(_events), triangleSet); return KDTree<SurfaceData>{ std::move(_triangles), std::move(rootNode), _boundingBox }; } private: static constexpr float kTraversalCost = 15.0f; static constexpr float kIntersectionCost = 20.0f; static constexpr float kEmptySplitDiscount = 0.8f; enum class Side { Left, Right, }; struct Event { enum class Type { Ending = 0, Planar = 1, Starting = 2, }; bool operator<(const Event& other) const { auto tuplify = [](const Event& event) { return std::tie(event.separationPlane.boundary, event.separationPlane.dimensionIndex, event.type, event.triangle); }; return tuplify(*this) < tuplify(other); } Triangle<SurfaceData>* triangle; AxisAlignedPlane separationPlane; Type type; }; std::unique_ptr<MapNode<SurfaceData>> createNode(const AxisAlignedBoundingBox& box, std::set<Event> events, std::unordered_set<Triangle<SurfaceData>*> triangles) { size_t triangleCount = triangles.size(); if (triangleCount > 0) { auto [plane, side, cost] = findBestSplit(box, events, triangleCount); float terminateCost = static_cast<float>(triangleCount) * kIntersectionCost; if (terminateCost > cost) { std::unordered_set<Triangle<SurfaceData>*> leftTriangles; std::unordered_set<Triangle<SurfaceData>*> rightTriangles; for (const auto& event : events) { const auto& eventPlane = event.separationPlane; if (eventPlane.dimensionIndex != plane.dimensionIndex) { continue; } if (eventPlane.boundary < plane.boundary) { if (event.type != Event::Type::Starting) { size_t erased = triangles.erase(event.triangle); Expects(erased == 1); leftTriangles.insert(event.triangle); Expects(event.triangle->isLeftOfPlane(plane)); } } else if (eventPlane.boundary > plane.boundary) { if (event.type != Event::Type::Ending) { size_t erased = triangles.erase(event.triangle); Expects(erased == 1); rightTriangles.insert(event.triangle); Expects(event.triangle->isRightOfPlane(plane)); } } else { // On the boundary size_t erased = triangles.erase(event.triangle); Expects(erased == 1); switch (event.type) { case Event::Type::Starting: rightTriangles.insert(event.triangle); Expects(event.triangle->isRightOfPlane(plane)); break; case Event::Type::Ending: leftTriangles.insert(event.triangle); Expects(event.triangle->isLeftOfPlane(plane)); break; case Event::Type::Planar: if (side == Side::Left) { leftTriangles.insert(event.triangle); } else { rightTriangles.insert(event.triangle); } break; } } } std::set<Event> leftEvents; std::set<Event> rightEvents; for (const auto& event : events) { if (leftTriangles.count(event.triangle)) { leftEvents.insert(event); } else if (rightTriangles.count(event.triangle)) { rightEvents.insert(event); } } auto [leftBox, rightBox] = box.split(plane); // Overlapping triangles remain for (const auto& triangle : triangles) { Expects(triangle->isLeftOfPlane(plane)); Expects(triangle->isRightOfPlane(plane)); auto leftClipBox = triangle->clippedBoundingBox(leftBox); if (leftClipBox) { for (const auto& event : buildTriangleEvents(*leftClipBox, triangle)) { leftEvents.insert(event); } leftTriangles.insert(triangle); } auto rightClipBox = triangle->clippedBoundingBox(rightBox); if (rightClipBox) { for (const auto& event : buildTriangleEvents(*rightClipBox, triangle)) { rightEvents.insert(event); } rightTriangles.insert(triangle); } } triangles.clear(); events.clear(); return std::make_unique<MapNode<SurfaceData>>(BranchNode<SurfaceData>{ plane, createNode(leftBox, std::move(leftEvents), std::move(leftTriangles)), createNode(rightBox, std::move(rightEvents), std::move(rightTriangles)), }); } } return std::make_unique<MapNode<SurfaceData>>( LeafNode<SurfaceData>{ std::move(triangles) }); } std::set<Event> buildTriangleEvents( const AxisAlignedBoundingBox& boundingBox, Triangle<SurfaceData>* triangle) { AxisAlignedBoundingBox actualBox = triangle->getBoundingBox(); std::set<Event> events; for (uint8_t k = 0; k < 3; k++) { float minimum = boundingBox.minimum[k]; float maximum = boundingBox.maximum[k]; Expects(!(minimum < actualBox.minimum[k])); Expects(!(maximum > actualBox.maximum[k])); if (minimum < maximum) { events.insert( Event{ triangle, AxisAlignedPlane{ k, maximum }, Event::Type::Ending }); events.insert( Event{ triangle, AxisAlignedPlane{ k, minimum }, Event::Type::Starting }); } else { events.insert( Event{ triangle, AxisAlignedPlane{ k, minimum }, Event::Type::Planar }); } } return events; } std::tuple<AxisAlignedPlane, Side, float> findBestSplit( const AxisAlignedBoundingBox& box, const std::set<Event>& events, size_t triangleCount) { float bestCost = std::numeric_limits<float>::infinity(); AxisAlignedPlane bestPlane; Side bestSide; std::array<size_t, 3> leftTriangleCounts{ 0 }; std::array<size_t, 3> rightTriangleCounts{ triangleCount, triangleCount, triangleCount }; auto iter = events.begin(); auto eventsEnd = events.end(); while (iter != eventsEnd) { const AxisAlignedPlane& candidatePlane = iter->separationPlane; uint8_t dimension = candidatePlane.dimensionIndex; size_t endingTriangleCount = 0; size_t planarTriangleCount = 0; size_t startingTriangleCount = 0; auto validate = [&eventsEnd, &candidatePlane, dimension](const auto& iter) { return (iter != eventsEnd) && !(iter->separationPlane.boundary > candidatePlane.boundary) && (iter->separationPlane.dimensionIndex == dimension); }; while (validate(iter) && (iter->type == Event::Type::Ending)) { endingTriangleCount++; iter++; } while (validate(iter) && (iter->type == Event::Type::Planar)) { planarTriangleCount++; iter++; } while (validate(iter) && (iter->type == Event::Type::Starting)) { startingTriangleCount++; iter++; } rightTriangleCounts[dimension] -= planarTriangleCount; rightTriangleCounts[dimension] -= endingTriangleCount; auto [side, cost] = surfaceAreaCostHeuristic(box, candidatePlane, leftTriangleCounts[dimension], planarTriangleCount, rightTriangleCounts[dimension]); if (cost < bestCost) { bestCost = cost; bestPlane = candidatePlane; bestSide = side; } leftTriangleCounts[dimension] += planarTriangleCount; leftTriangleCounts[dimension] += startingTriangleCount; } return { bestPlane, bestSide, bestCost }; } std::pair<Side, float> surfaceAreaCostHeuristic(const AxisAlignedBoundingBox& box, const AxisAlignedPlane& splitPlane, size_t leftTriangleCount, size_t planarTriangleCount, size_t rightTriangleCount) { auto [leftBox, rightBox] = box.split(splitPlane); float boxSurfaceArea = box.getSurfaceArea(); float leftArea = leftBox.getSurfaceArea() / boxSurfaceArea; float rightArea = rightBox.getSurfaceArea() / boxSurfaceArea; bool removesVolume = (leftBox.getVolume() > 0.0f) && (rightBox.getVolume() > 0.0f); auto cost = [leftArea, rightArea, removesVolume]( size_t leftTriangleCount, size_t rightTriangleCount) { float cost = static_cast<float>(leftTriangleCount) * leftArea + static_cast<float>(rightTriangleCount) * rightArea; if (removesVolume && (!leftTriangleCount || !rightTriangleCount)) { // We slightly prefer splits that remove empty space. cost *= kEmptySplitDiscount; } return cost; }; float leftCost = cost(leftTriangleCount + planarTriangleCount, rightTriangleCount); float rightCost = cost(leftTriangleCount, planarTriangleCount + rightTriangleCount); if (leftCost < rightCost) { return { Side::Left, (kIntersectionCost * leftCost) + kTraversalCost }; } else { return { Side::Right, (kIntersectionCost * rightCost) + kTraversalCost }; } } AxisAlignedBoundingBox _boundingBox; std::vector<std::unique_ptr<Triangle<SurfaceData>>> _triangles; std::set<Event> _events; }; }
{ "alphanum_fraction": 0.5502468829, "avg_line_length": 35.9527458493, "ext": "h", "hexsha": "b7d1d70a9ead2a0fe18e3804318ab2b14a0bb4d0", "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/KDTree.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/KDTree.h", "max_line_length": 100, "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/KDTree.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6382, "size": 28151 }
// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt) /// \briefFile{Random & related} #ifndef CPPQEDCORE_UTILS_RANDOM_H_REENTRANT #ifndef CPPQEDCORE_UTILS_RANDOM_H_INCLUDED #define CPPQEDCORE_UTILS_RANDOM_H_INCLUDED #include "Pars.h" #include "pcg_random.hpp" #include "XoshiroCpp.hpp" #ifdef CPPQED_HAS_GSL #include <gsl/gsl_rng.h> #endif // CPPQED_HAS_GSL #include <boost/range/algorithm/generate.hpp> #ifdef BZ_HAVE_BOOST_SERIALIZATION #include <boost/serialization/string.hpp> #include <boost/serialization/array.hpp> #endif // BZ_HAVE_BOOST_SERIALIZATION #include <memory> #include <optional> #include <random> #include <stdexcept> #include <sstream> #include <optional> namespace randomutils { template<typename Engine, typename BASE> struct Pars; #ifdef CPPQED_HAS_GSL /// Wraps GSL random number generators into the concept [UniformRandomBitGenerator](http://en.cppreference.com/w/cpp/named_req/UniformRandomBitGenerator) class GSL_Engine { public: using result_type=unsigned long; explicit GSL_Engine(result_type s/*, const gsl_rng_type* ran_gen_type=gsl_rng_taus2*/); void seed(result_type value); result_type operator()(); result_type min() const; result_type max() const; void write(std::ostream& os) const; void read(std::istream& is); private: const std::shared_ptr<gsl_rng> ranGen_; const std::string name_; }; inline std::ostream& operator<<(std::ostream& os, const GSL_Engine& r) {r.write(os); return os;} inline std::istream& operator>>(std::istream& is, GSL_Engine& r) {r.read(is); return is;} #define CPPQEDCORE_UTILS_RANDOM_H_REENTRANT #define CPPQEDCORE_UTILS_RANDOM_H_RANDOMENGINE GSL_Engine #define CPPQEDCORE_UTILS_RANDOM_H_STRING "GSL_Engine state" #include "Random.h" } // randomutils #endif // CPPQED_HAS_GSL namespace randomutils { template<typename Distribution, typename Engine, typename Array, typename... DCP> Engine& fill(Array a, Engine& re, DCP&&... dcp) { Distribution d{std::forward<DCP>(dcp)...}; std::generate(a.begin(),a.end(),[&]() {return d(re);}); return re; } template<typename Distribution, typename Engine, typename Array, typename... DCP> void fill(Array a, unsigned long seed, DCP&&... dcp) { Engine re{seed}; fill<Distribution>(a,re,std::forward<DCP>(dcp)...); } template<typename Engine> constexpr auto EngineID_v = std::nullopt; template<> inline const std::string EngineID_v<GSL_Engine> = "GSL_Taus2"; template<> inline const std::string EngineID_v<std::mt19937_64> = "STD_MT19937_64"; template<> inline const std::string EngineID_v<pcg64> = "PCG64"; template<> inline const std::string EngineID_v<XoshiroCpp::Xoshiro256PlusPlus> = "Xoshiro256pp"; template<typename Engine> struct EngineWithParameters { EngineWithParameters(unsigned long s, unsigned long p) : engine{s,p}, seed{s}, prngStream{p} {} std::ostream& stream(std::ostream& os) const {return os << "Random engine: "<<EngineID_v<Engine><<". Parameters: seed="<<seed<<", streamOrdo=" << prngStream;} Engine engine; const unsigned long seed, prngStream; }; // template<> // inline std::list<pcg64> independentPRNG_Streams<pcg64>(size_t n, pcg64::result_type seed, pcg64::result_type ordoStream) // { // std::list<pcg64> res; // for (size_t i=0; i<n; ++i) res.emplace_back(seed,1001+ordoStream+i); // return res; // } template<typename BASE> struct Pars<pcg64,BASE> : BASE { unsigned long &seed, &prngStream; ///< PCG64 generator seed and ordinal of independent stream Pars(parameters::Table& p, const std::string& mod="") : BASE{p,mod}, seed(p.addTitle("StochasticTrajectory",mod).add("seed",mod,"Random number generator seed",1001ul)), prngStream(p.add("prngStream",mod,"Random number generator independent stream ordinal",1ul)) {} }; #ifndef NDEBUG #pragma GCC warning "TODO: implement nextStream optionally from previousState" #endif // NDEBUG template<typename BASE> pcg64 streamOfOrdo(const Pars<pcg64,BASE>& p/*, std::optional<EngineState> previousState = std::nullopt*/) { return pcg64{p.seed,1001+p.prngStream}; } template<typename BASE> void incrementForNextStream(const Pars<pcg64,BASE>& p) {++p.prngStream;} } // randomutils namespace boost { namespace serialization { template<typename Ar> void load(Ar& ar, XoshiroCpp::Xoshiro256PlusPlus& xpp, unsigned) { XoshiroCpp::Xoshiro256PlusPlus::state_type state; ar & state; xpp.deserialize(state); } template<typename Ar> void save(Ar& ar, XoshiroCpp::Xoshiro256PlusPlus const& xpp, unsigned) { auto state{xpp.serialize()}; ar & state; } template<typename Ar> void serialize(Ar& ar, XoshiroCpp::Xoshiro256PlusPlus& xpp, unsigned version) { if (typename Ar::is_saving()) save(ar, xpp, version); else load(ar, xpp, version); } #define CPPQEDCORE_UTILS_RANDOM_H_REENTRANT #define CPPQEDCORE_UTILS_RANDOM_H_RANDOMENGINE std::mt19937_64 #define CPPQEDCORE_UTILS_RANDOM_H_STRING "mersenne_twister_engine state" #include "Random.h" #define CPPQEDCORE_UTILS_RANDOM_H_REENTRANT #define CPPQEDCORE_UTILS_RANDOM_H_RANDOMENGINE pcg64 #define CPPQEDCORE_UTILS_RANDOM_H_STRING "pcg64 state" #include "Random.h" } } // boost::serialization #endif // CPPQEDCORE_UTILS_RANDOM_H_INCLUDED #else // CPPQEDCORE_UTILS_RANDOM_H_REENTRANT template<typename Ar> void load(Ar& ar, CPPQEDCORE_UTILS_RANDOM_H_RANDOMENGINE& randomEngine, unsigned) { std::string text; ar & text; std::istringstream iss(text); if (!(iss >> randomEngine)) throw std::invalid_argument(CPPQEDCORE_UTILS_RANDOM_H_STRING); } template<typename Ar> void save(Ar& ar, CPPQEDCORE_UTILS_RANDOM_H_RANDOMENGINE const& randomEngine, unsigned) { std::ostringstream oss; if (!(oss << randomEngine)) throw std::invalid_argument(CPPQEDCORE_UTILS_RANDOM_H_STRING); std::string text = oss.str(); ar & text; } template<typename Ar> void serialize(Ar& ar, CPPQEDCORE_UTILS_RANDOM_H_RANDOMENGINE& randomEngine, unsigned version) { if (typename Ar::is_saving()) save(ar, randomEngine, version); else load(ar, randomEngine, version); } #undef CPPQEDCORE_UTILS_RANDOM_H_STRING #undef CPPQEDCORE_UTILS_RANDOM_H_RANDOMENGINE #undef CPPQEDCORE_UTILS_RANDOM_H_REENTRANT #endif // CPPQEDCORE_UTILS_RANDOM_H_REENTRANT
{ "alphanum_fraction": 0.7519429025, "avg_line_length": 25.8401639344, "ext": "h", "hexsha": "6fcfe0db8005d46d6e96069fa4112c60aed2545f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "vukics/cppqed", "max_forks_repo_path": "CPPQEDutils/Random.h", "max_issues_count": 10, "max_issues_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "vukics/cppqed", "max_issues_repo_path": "CPPQEDutils/Random.h", "max_line_length": 160, "max_stars_count": 5, "max_stars_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "vukics/cppqed", "max_stars_repo_path": "CPPQEDutils/Random.h", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "num_tokens": 1708, "size": 6305 }
/*** Some usefull math macros ***/ #define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) static double mnarg1,mnarg2; #define FMAX(a,b) (mnarg1=(a),mnarg2=(b),(mnarg1) > (mnarg2) ?\ (mnarg1) : (mnarg2)) static double mnarg1,mnarg2; #define FMIN(a,b) (mnarg1=(a),mnarg2=(b),(mnarg1) < (mnarg2) ?\ (mnarg1) : (mnarg2)) #define ERFC_NPTS (int) 75 #define ERFC_PARAM_DELTA (float) 0.1 static double log_erfc_table[ERFC_NPTS], erfc_params[ERFC_NPTS]; static gsl_interp_accel *erfc_acc; static gsl_spline *erfc_spline; #define NGaussLegendre 40 //defines the number of points in the Gauss-Legendre quadrature integration #define NMass 300 #define NSFR_high 200 #define NSFR_low 250 #define NGL_SFR 100 // 100 #define NMTURN 50//100 #define LOG10_MTURN_MAX ((double)(10)) #define LOG10_MTURN_MIN ((double)(5.-9e-8)) #define NR_END 1 #define FREE_ARG char* #define MM 7 #define NSTACK 50 #define EPS2 3.0e-11 #define Luv_over_SFR (double)(1./1.15/1e-28) // Luv/SFR = 1 / 1.15 x 10^-28 [M_solar yr^-1/erg s^-1 Hz^-1] // G. Sun and S. R. Furlanetto (2016) MNRAS, 417, 33 #define delta_lnMhalo (double)(5e-6) #define Mhalo_min (double)(1e6) #define Mhalo_max (double)(1e16) float calibrated_NF_min; double *deltaz, *deltaz_smoothed, *NeutralFractions, *z_Q, *Q_value, *nf_vals, *z_vals; int N_NFsamples,N_extrapolated, N_analytic, N_calibrated, N_deltaz; bool initialised_ComputeLF = false; gsl_interp_accel *LF_spline_acc; gsl_spline *LF_spline; gsl_interp_accel *deriv_spline_acc; gsl_spline *deriv_spline; struct CosmoParams *cosmo_params_ps; struct UserParams *user_params_ps; struct FlagOptions *flag_options_ps; //double sigma_norm, R, theta_cmb, omhh, z_equality, y_d, sound_horizon, alpha_nu, f_nu, f_baryon, beta_c, d2fact, R_CUTOFF, DEL_CURR, SIG_CURR; double sigma_norm, theta_cmb, omhh, z_equality, y_d, sound_horizon, alpha_nu, f_nu, f_baryon, beta_c, d2fact, R_CUTOFF, DEL_CURR, SIG_CURR; float MinMass, mass_bin_width, inv_mass_bin_width; double sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias); float *Mass_InterpTable, *Sigma_InterpTable, *dSigmadm_InterpTable; float *log10_overdense_spline_SFR, *log10_Nion_spline, *Overdense_spline_SFR, *Nion_spline; float *prev_log10_overdense_spline_SFR, *prev_log10_Nion_spline, *prev_Overdense_spline_SFR, *prev_Nion_spline; float *Mturns, *Mturns_MINI; float *log10_Nion_spline_MINI, *Nion_spline_MINI; float *prev_log10_Nion_spline_MINI, *prev_Nion_spline_MINI; float *xi_SFR,*wi_SFR, *xi_SFR_Xray, *wi_SFR_Xray; float *overdense_high_table, *overdense_low_table, *log10_overdense_low_table; float **log10_SFRD_z_low_table, **SFRD_z_high_table; float **log10_SFRD_z_low_table_MINI, **SFRD_z_high_table_MINI; double *lnMhalo_param, *Muv_param, *Mhalo_param; double *log10phi, *M_uv_z, *M_h_z; double *lnMhalo_param_MINI, *Muv_param_MINI, *Mhalo_param_MINI; double *log10phi_MINI; *M_uv_z_MINI, *M_h_z_MINI; double *deriv, *lnM_temp, *deriv_temp; double *z_val, *z_X_val, *Nion_z_val, *SFRD_val; double *Nion_z_val_MINI, *SFRD_val_MINI; void initialiseSigmaMInterpTable(float M_Min, float M_Max); void freeSigmaMInterpTable(); void initialiseGL_Nion(int n, float M_Min, float M_Max); void initialiseGL_Nion_Xray(int n, float M_Min, float M_Max); float Mass_limit (float logM, float PL, float FRAC); void bisection(float *x, float xlow, float xup, int *iter); float Mass_limit_bisection(float Mmin, float Mmax, float PL, float FRAC); double sheth_delc(double del, double sig); float dNdM_conditional(float growthf, float M1, float M2, float delta1, float delta2, float sigma2); double dNion_ConditionallnM(double lnM, void *params); double Nion_ConditionalM(double growthf, double M1, double M2, double sigma2, double delta1, double delta2, double MassTurnover, double Alpha_star, double Alpha_esc, double Fstar10, double Fesc10, double Mlim_Fstar, double Mlim_Fesc, bool FAST_FCOLL_TABLES); double dNion_ConditionallnM_MINI(double lnM, void *params); double Nion_ConditionalM_MINI(double growthf, double M1, double M2, double sigma2, double delta1, double delta2, double MassTurnover, double MassTurnover_upper, double Alpha_star, double Alpha_esc, double Fstar10, double Fesc10, double Mlim_Fstar, double Mlim_Fesc, bool FAST_FCOLL_TABLES); float GaussLegendreQuad_Nion(int Type, int n, float growthf, float M2, float sigma2, float delta1, float delta2, float MassTurnover, float Alpha_star, float Alpha_esc, float Fstar10, float Fesc10, float Mlim_Fstar, float Mlim_Fesc, bool FAST_FCOLL_TABLES); float GaussLegendreQuad_Nion_MINI(int Type, int n, float growthf, float M2, float sigma2, float delta1, float delta2, float MassTurnover, float MassTurnover_upper, float Alpha_star, float Alpha_esc, float Fstar7_MINI, float Fesc7_MINI, float Mlim_Fstar_MINI, float Mlim_Fesc_MINI, bool FAST_FCOLL_TABLES); //JBM: Exact integral for power-law indices non zero (for zero it's erfc) double Fcollapprox (double numin, double beta); int n_redshifts_1DTable; double zmin_1DTable, zmax_1DTable, zbin_width_1DTable; double *FgtrM_1DTable_linear; static gsl_interp_accel *Q_at_z_spline_acc; static gsl_spline *Q_at_z_spline; static gsl_interp_accel *z_at_Q_spline_acc; static gsl_spline *z_at_Q_spline; static double Zmin, Zmax, Qmin, Qmax; void Q_at_z(double z, double *splined_value); void z_at_Q(double Q, double *splined_value); static gsl_interp_accel *deltaz_spline_for_photoncons_acc; static gsl_spline *deltaz_spline_for_photoncons; static gsl_interp_accel *NFHistory_spline_acc; static gsl_spline *NFHistory_spline; static gsl_interp_accel *z_NFHistory_spline_acc; static gsl_spline *z_NFHistory_spline; void initialise_NFHistory_spline(double *redshifts, double *NF_estimate, int NSpline); void z_at_NFHist(double xHI_Hist, double *splined_value); void NFHist_at_z(double z, double *splined_value); //int nbin; //double *z_Q, *Q_value, *Q_z, *z_value; double FinalNF_Estimate, FirstNF_Estimate; struct parameters_gsl_FgtrM_int_{ double z_obs; double gf_obs; }; struct parameters_gsl_SFR_General_int_{ double z_obs; double gf_obs; double Mdrop; double Mdrop_upper; double pl_star; double pl_esc; double frac_star; double frac_esc; double LimitMass_Fstar; double LimitMass_Fesc; }; struct parameters_gsl_SFR_con_int_{ double gf_obs; double Mval; double sigma2; double delta1; double delta2; double Mdrop; double Mdrop_upper; double pl_star; double pl_esc; double frac_star; double frac_esc; double LimitMass_Fstar; double LimitMass_Fesc; }; unsigned long *lvector(long nl, long nh); void free_lvector(unsigned long *v, long nl, long nh); float *vector(long nl, long nh); void free_vector(float *v, long nl, long nh); void spline(float x[], float y[], int n, float yp1, float ypn, float y2[]); void splint(float xa[], float ya[], float y2a[], int n, float x, float *y); void gauleg(float x1, float x2, float x[], float w[], int n); /***** FUNCTION PROTOTYPES *****/ double init_ps(); /* initialize global variables, MUST CALL THIS FIRST!!! returns R_CUTOFF */ void free_ps(); /* deallocates the gsl structures from init_ps */ double sigma_z0(double M); //calculates sigma at z=0 (no dicke) double power_in_k(double k); /* Returns the value of the linear power spectrum density (i.e. <|delta_k|^2>/V) at a given k mode at z=0 */ double TFmdm(double k); //Eisenstein & Hu power spectrum transfer function void TFset_parameters(); double TF_CLASS(double k, int flag_int, int flag_dv); //transfer function of matter (flag_dv=0) and relative velocities (flag_dv=1) fluctuations from CLASS double power_in_vcb(double k); /* Returns the value of the DM-b relative velocity power spectrum density (i.e. <|delta_k|^2>/V) at a given k mode at z=0 */ double FgtrM(double z, double M); double FgtrM_wsigma(double z, double sig); double FgtrM_st(double z, double M); double FgtrM_Watson(double growthf, double M); double FgtrM_Watson_z(double z, double growthf, double M); double FgtrM_General(double z, double M); float erfcc(float x); double splined_erfc(double x); double M_J_WDM(); void Broadcast_struct_global_PS(struct UserParams *user_params, struct CosmoParams *cosmo_params){ cosmo_params_ps = cosmo_params; user_params_ps = user_params; } /* this function reads the z=0 matter (CDM+baryons) and relative velocity transfer functions from CLASS (from a file) flag_int = 0 to initialize interpolator, flag_int = -1 to free memory, flag_int = else to interpolate. flag_dv = 0 to output density, flag_dv = 1 to output velocity. similar to built-in function "double T_RECFAST(float z, int flag)" */ double TF_CLASS(double k, int flag_int, int flag_dv) { static double kclass[CLASS_LENGTH], Tmclass[CLASS_LENGTH], Tvclass_vcb[CLASS_LENGTH]; static gsl_interp_accel *acc_density, *acc_vcb; static gsl_spline *spline_density, *spline_vcb; float trash, currk, currTm, currTv; double ans; int i; int gsl_status; FILE *F; char filename[500]; sprintf(filename,"%s/%s",global_params.external_table_path,CLASS_FILENAME); if (flag_int == 0) { // Initialize vectors and read file if (!(F = fopen(filename, "r"))) { LOG_ERROR("Unable to open file: %s for reading.", filename); Throw(IOError); } int nscans; for (i = 0; i < CLASS_LENGTH; i++) { nscans = fscanf(F, "%e %e %e ", &currk, &currTm, &currTv); if (nscans != 3) { LOG_ERROR("Reading CLASS Transfer Function failed."); Throw(IOError); } kclass[i] = currk; Tmclass[i] = currTm; Tvclass_vcb[i] = currTv; if (i > 0 && kclass[i] <= kclass[i - 1]) { LOG_WARNING("Tk table not ordered"); LOG_WARNING("k=%.1le kprev=%.1le", kclass[i], kclass[i - 1]); } } fclose(F); LOG_SUPER_DEBUG("Read CLASS Transfer file"); gsl_set_error_handler_off(); // Set up spline table for densities acc_density = gsl_interp_accel_alloc (); spline_density = gsl_spline_alloc (gsl_interp_cspline, CLASS_LENGTH); gsl_status = gsl_spline_init(spline_density, kclass, Tmclass, CLASS_LENGTH); GSL_ERROR(gsl_status); LOG_SUPER_DEBUG("Generated CLASS Density Spline."); //Set up spline table for velocities acc_vcb = gsl_interp_accel_alloc (); spline_vcb = gsl_spline_alloc (gsl_interp_cspline, CLASS_LENGTH); gsl_status = gsl_spline_init(spline_vcb, kclass, Tvclass_vcb, CLASS_LENGTH); GSL_ERROR(gsl_status); LOG_SUPER_DEBUG("Generated CLASS velocity Spline."); return 0; } else if (flag_int == -1) { gsl_spline_free (spline_density); gsl_interp_accel_free(acc_density); gsl_spline_free (spline_vcb); gsl_interp_accel_free(acc_vcb); return 0; } if (k > kclass[CLASS_LENGTH-1]) { // k>kmax LOG_WARNING("Called TF_CLASS with k=%f, larger than kmax! Returning value at kmax.", k); if(flag_dv == 0){ // output is density return (Tmclass[CLASS_LENGTH]/kclass[CLASS_LENGTH-1]/kclass[CLASS_LENGTH-1]); } else if(flag_dv == 1){ // output is rel velocity return (Tvclass_vcb[CLASS_LENGTH]/kclass[CLASS_LENGTH-1]/kclass[CLASS_LENGTH-1]); } //we just set it to the last value, since sometimes it wants large k for R<<cell_size, which does not matter much. } else { // Do spline if(flag_dv == 0){ // output is density ans = gsl_spline_eval (spline_density, k, acc_density); } else if(flag_dv == 1){ // output is relative velocity ans = gsl_spline_eval (spline_vcb, k, acc_vcb); } else{ ans=0.0; //neither densities not velocities? } } return ans/k/k; //we have to divide by k^2 to agree with the old-fashioned convention. } // FUNCTION sigma_z0(M) // Returns the standard deviation of the normalized, density excess (delta(x)) field, // smoothed on the comoving scale of M (see filter definitions for M<->R conversion). // The sigma is evaluated at z=0, with the time evolution contained in the dicke(z) factor, // i.e. sigma(M,z) = sigma_z0(m) * dicke(z) // normalized so that sigma_z0(M->8/h Mpc) = SIGMA8 in ../Parameter_files/COSMOLOGY.H // NOTE: volume is normalized to = 1, so this is equvalent to the mass standard deviation // M is in solar masses // References: Padmanabhan, pg. 210, eq. 5.107 double dsigma_dk(double k, void *params){ double p, w, T, gamma, q, aa, bb, cc, kR; // get the power spectrum.. choice of 5: if (user_params_ps->POWER_SPECTRUM == 0){ // Eisenstein & Hu T = TFmdm(k); // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function if (global_params.P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v); p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; } else if (user_params_ps->POWER_SPECTRUM == 1){ // BBKS gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb/cosmo_params_ps->OMm)); q = k / (cosmo_params_ps->hlittle*gamma); T = (log(1.0+2.34*q)/(2.34*q)) * pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25); p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; } else if (user_params_ps->POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992) gamma = 0.25; aa = 6.4/(cosmo_params_ps->hlittle*gamma); bb = 3.0/(cosmo_params_ps->hlittle*gamma); cc = 1.7/(cosmo_params_ps->hlittle*gamma); p = pow(k, cosmo_params_ps->POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 ); } else if (user_params_ps->POWER_SPECTRUM == 3){ // Peebles, pg. 626 gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb/cosmo_params_ps->OMm)); aa = 8.0 / (cosmo_params_ps->hlittle*gamma); bb = 4.7 / pow(cosmo_params_ps->hlittle*gamma, 2); p = pow(k, cosmo_params_ps->POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2); } else if (user_params_ps->POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52 gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb/cosmo_params_ps->OMm)); aa = 1.7/(cosmo_params_ps->hlittle*gamma); bb = 9.0/pow(cosmo_params_ps->hlittle*gamma, 1.5); cc = 1.0/pow(cosmo_params_ps->hlittle*gamma, 2); p = pow(k, cosmo_params_ps->POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2); } else if (user_params_ps->POWER_SPECTRUM == 5){ // output of CLASS T = TF_CLASS(k, 1, 0); //read from z=0 output of CLASS. Note, flag_int = 1 here always, since now we have to have initialized the interpolator for CLASS p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; if(user_params_ps->USE_RELATIVE_VELOCITIES) { //jbm:Add average relvel suppression p *= 1.0 - A_VCB_PM*exp( -pow(log(k/KP_VCB_PM),2.0)/(2.0*SIGMAK_VCB_PM*SIGMAK_VCB_PM)); //for v=vrms } } else{ LOG_ERROR("No such power spectrum defined: %i. Output is bogus.", user_params_ps->POWER_SPECTRUM); Throw(ValueError); } double Radius; Radius = *(double *)params; kR = k*Radius; if ( (global_params.FILTER == 0) || (sigma_norm < 0) ){ // top hat if ( (kR) < 1.0e-4 ){ w = 1.0;} // w converges to 1 as (kR) -> 0 else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));} } else if (global_params.FILTER == 1){ // gaussian of width 1/R w = pow(E, -kR*kR/2.0); } else { LOG_ERROR("No such filter: %i. Output is bogus.", global_params.FILTER); Throw(ValueError); } return k*k*p*w*w; } double sigma_z0(double M){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double kstart, kend; double Radius; // R = MtoR(M); Radius = MtoR(M); // now lets do the integral for sigma and scale it with sigma_norm if(user_params_ps->POWER_SPECTRUM == 5){ kstart = fmax(1.0e-99/Radius, KBOT_CLASS); kend = fmin(350.0/Radius, KTOP_CLASS); }//we establish a maximum k of KTOP_CLASS~1e3 Mpc-1 and a minimum at KBOT_CLASS,~1e-5 Mpc-1 since the CLASS transfer function has a max! else{ kstart = 1.0e-99/Radius; kend = 350.0/Radius; } lower_limit = kstart;//log(kstart); upper_limit = kend;//log(kend); F.function = &dsigma_dk; F.params = &Radius; int status; gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("(function argument): lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: M=%e",M); GSL_ERROR(status); } gsl_integration_workspace_free (w); return sigma_norm * sqrt(result); } // FUNCTION TFmdm is the power spectrum transfer function from Eisenstein & Hu ApJ, 1999, 511, 5 double TFmdm(double k){ double q, gamma_eff, q_eff, TF_m, q_nu; q = k*pow(theta_cmb,2)/omhh; gamma_eff=sqrt(alpha_nu) + (1.0-sqrt(alpha_nu))/(1.0+pow(0.43*k*sound_horizon, 4)); q_eff = q/gamma_eff; TF_m= log(E+1.84*beta_c*sqrt(alpha_nu)*q_eff); TF_m /= TF_m + pow(q_eff,2) * (14.4 + 325.0/(1.0+60.5*pow(q_eff,1.11))); q_nu = 3.92*q/sqrt(f_nu/N_nu); TF_m *= 1.0 + (1.2*pow(f_nu,0.64)*pow(N_nu,0.3+0.6*f_nu)) / (pow(q_nu,-1.6)+pow(q_nu,0.8)); return TF_m; } void TFset_parameters(){ double z_drag, R_drag, R_equality, p_c, p_cb, f_c, f_cb, f_nub, k_equality; LOG_DEBUG("Setting Transfer Function parameters."); z_equality = 25000*omhh*pow(theta_cmb, -4) - 1.0; k_equality = 0.0746*omhh/(theta_cmb*theta_cmb); z_drag = 0.313*pow(omhh,-0.419) * (1 + 0.607*pow(omhh, 0.674)); z_drag = 1 + z_drag*pow(cosmo_params_ps->OMb*cosmo_params_ps->hlittle*cosmo_params_ps->hlittle, 0.238*pow(omhh, 0.223)); z_drag *= 1291 * pow(omhh, 0.251) / (1 + 0.659*pow(omhh, 0.828)); y_d = (1 + z_equality) / (1.0 + z_drag); R_drag = 31.5 * cosmo_params_ps->OMb*cosmo_params_ps->hlittle*cosmo_params_ps->hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_drag); R_equality = 31.5 * cosmo_params_ps->OMb*cosmo_params_ps->hlittle*cosmo_params_ps->hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_equality); sound_horizon = 2.0/3.0/k_equality * sqrt(6.0/R_equality) * log( (sqrt(1+R_drag) + sqrt(R_drag+R_equality)) / (1.0 + sqrt(R_equality)) ); p_c = -(5 - sqrt(1 + 24*(1 - f_nu-f_baryon)))/4.0; p_cb = -(5 - sqrt(1 + 24*(1 - f_nu)))/4.0; f_c = 1 - f_nu - f_baryon; f_cb = 1 - f_nu; f_nub = f_nu+f_baryon; alpha_nu = (f_c/f_cb) * (2*(p_c+p_cb)+5)/(4*p_cb+5.0); alpha_nu *= 1 - 0.553*f_nub+0.126*pow(f_nub,3); alpha_nu /= 1-0.193*sqrt(f_nu)+0.169*f_nu; alpha_nu *= pow(1+y_d, p_c-p_cb); alpha_nu *= 1+ (p_cb-p_c)/2.0 * (1.0+1.0/(4.0*p_c+3.0)/(4.0*p_cb+7.0))/(1.0+y_d); beta_c = 1.0/(1.0-0.949*f_nub); } // Returns the value of the linear power spectrum DENSITY (i.e. <|delta_k|^2>/V) // at a given k mode linearly extrapolated to z=0 double power_in_k(double k){ double p, T, gamma, q, aa, bb, cc; // get the power spectrum.. choice of 5: if (user_params_ps->POWER_SPECTRUM == 0){ // Eisenstein & Hu T = TFmdm(k); // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function if (global_params.P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v); p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; //p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05 } else if (user_params_ps->POWER_SPECTRUM == 1){ // BBKS gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb/cosmo_params_ps->OMm)); q = k / (cosmo_params_ps->hlittle*gamma); T = (log(1.0+2.34*q)/(2.34*q)) * pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25); p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; } else if (user_params_ps->POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992) gamma = 0.25; aa = 6.4/(cosmo_params_ps->hlittle*gamma); bb = 3.0/(cosmo_params_ps->hlittle*gamma); cc = 1.7/(cosmo_params_ps->hlittle*gamma); p = pow(k, cosmo_params_ps->POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 ); } else if (user_params_ps->POWER_SPECTRUM == 3){ // Peebles, pg. 626 gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb)/(cosmo_params_ps->OMm)); aa = 8.0 / (cosmo_params_ps->hlittle*gamma); bb = 4.7 / pow(cosmo_params_ps->hlittle*gamma, 2); p = pow(k, cosmo_params_ps->POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2); } else if (user_params_ps->POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52 gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb/cosmo_params_ps->OMm)); aa = 1.7/(cosmo_params_ps->hlittle*gamma); bb = 9.0/pow(cosmo_params_ps->hlittle*gamma, 1.5); cc = 1.0/pow(cosmo_params_ps->hlittle*gamma, 2); p = pow(k, cosmo_params_ps->POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2); } else if (user_params_ps->POWER_SPECTRUM == 5){ // output of CLASS T = TF_CLASS(k, 1, 0); //read from z=0 output of CLASS. Note, flag_int = 1 here always, since now we have to have initialized the interpolator for CLASS p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; if(user_params_ps->USE_RELATIVE_VELOCITIES) { //jbm:Add average relvel suppression p *= 1.0 - A_VCB_PM*exp( -pow(log(k/KP_VCB_PM),2.0)/(2.0*SIGMAK_VCB_PM*SIGMAK_VCB_PM)); //for v=vrms } } else{ LOG_ERROR("No such power spectrum defined: %i. Output is bogus.", user_params_ps->POWER_SPECTRUM); Throw(ValueError); } return p*TWOPI*PI*sigma_norm*sigma_norm; } /* Returns the value of the linear power spectrum of the DM-b relative velocity at kinematic decoupling (which we set at zkin=1010) */ double power_in_vcb(double k){ double p, T, gamma, q, aa, bb, cc; //only works if using CLASS if (user_params_ps->POWER_SPECTRUM == 5){ // CLASS T = TF_CLASS(k, 1, 1); //read from CLASS file. flag_int=1 since we have initialized before, flag_vcb=1 for velocity p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; } else{ LOG_ERROR("Cannot get P_cb unless using CLASS: %i\n Set USE_RELATIVE_VELOCITIES 0 or use CLASS.\n", user_params_ps->POWER_SPECTRUM); Throw(ValueError); } return p*TWOPI*PI*sigma_norm*sigma_norm; } double init_ps(){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double kstart, kend; //we start the interpolator if using CLASS: if (user_params_ps->POWER_SPECTRUM == 5){ LOG_DEBUG("Setting CLASS Transfer Function inits."); TF_CLASS(1.0, 0, 0); } // Set cuttoff scale for WDM (eq. 4 in Barkana et al. 2001) in comoving Mpc R_CUTOFF = 0.201*pow((cosmo_params_ps->OMm-cosmo_params_ps->OMb)*cosmo_params_ps->hlittle*cosmo_params_ps->hlittle/0.15, 0.15)*pow(global_params.g_x/1.5, -0.29)*pow(global_params.M_WDM, -1.15); omhh = cosmo_params_ps->OMm*cosmo_params_ps->hlittle*cosmo_params_ps->hlittle; theta_cmb = T_cmb / 2.7; // Translate Parameters into forms GLOBALVARIABLES form f_nu = global_params.OMn/cosmo_params_ps->OMm; f_baryon = cosmo_params_ps->OMb/cosmo_params_ps->OMm; if (f_nu < TINY) f_nu = 1e-10; if (f_baryon < TINY) f_baryon = 1e-10; TFset_parameters(); sigma_norm = -1; double Radius_8; Radius_8 = 8.0/cosmo_params_ps->hlittle; if(user_params_ps->POWER_SPECTRUM == 5){ kstart = fmax(1.0e-99/Radius_8, KBOT_CLASS); kend = fmin(350.0/Radius_8, KTOP_CLASS); }//we establish a maximum k of KTOP_CLASS~1e3 Mpc-1 and a minimum at KBOT_CLASS,~1e-5 Mpc-1 since the CLASS transfer function has a max! else{ kstart = 1.0e-99/Radius_8; kend = 350.0/Radius_8; } lower_limit = kstart; upper_limit = kend; LOG_DEBUG("Initializing Power Spectrum with lower_limit=%e, upper_limit=%e, rel_tol=%e, radius_8=%g", lower_limit,upper_limit, rel_tol, Radius_8); F.function = &dsigma_dk; F.params = &Radius_8; int status; gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("(function argument): lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); GSL_ERROR(status); } gsl_integration_workspace_free (w); LOG_DEBUG("Initialized Power Spectrum."); sigma_norm = cosmo_params_ps->SIGMA_8/sqrt(result); //takes care of volume factor return R_CUTOFF; } //function to free arrays related to the power spectrum void free_ps(){ //we free the PS interpolator if using CLASS: if (user_params_ps->POWER_SPECTRUM == 5){ TF_CLASS(1.0, -1, 0); } return; } /* FUNCTION dsigmasqdm_z0(M) returns d/dm (sigma^2) (see function sigma), in units of Msun^-1 */ double dsigmasq_dm(double k, void *params){ double p, w, T, gamma, q, aa, bb, cc, dwdr, drdm, kR; // get the power spectrum.. choice of 5: if (user_params_ps->POWER_SPECTRUM == 0){ // Eisenstein & Hu ApJ, 1999, 511, 5 T = TFmdm(k); // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function if (global_params.P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v); p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; //p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05 } else if (user_params_ps->POWER_SPECTRUM == 1){ // BBKS gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb)/(cosmo_params_ps->OMm)); q = k / (cosmo_params_ps->hlittle*gamma); T = (log(1.0+2.34*q)/(2.34*q)) * pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25); p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; } else if (user_params_ps->POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992) gamma = 0.25; aa = 6.4/(cosmo_params_ps->hlittle*gamma); bb = 3.0/(cosmo_params_ps->hlittle*gamma); cc = 1.7/(cosmo_params_ps->hlittle*gamma); p = pow(k, cosmo_params_ps->POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 ); } else if (user_params_ps->POWER_SPECTRUM == 3){ // Peebles, pg. 626 gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb)/(cosmo_params_ps->OMm)); aa = 8.0 / (cosmo_params_ps->hlittle*gamma); bb = 4.7 / (cosmo_params_ps->hlittle*gamma); p = pow(k, cosmo_params_ps->POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2); } else if (user_params_ps->POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52 gamma = cosmo_params_ps->OMm * cosmo_params_ps->hlittle * pow(E, -(cosmo_params_ps->OMb) - (cosmo_params_ps->OMb)/(cosmo_params_ps->OMm)); aa = 1.7/(cosmo_params_ps->hlittle*gamma); bb = 9.0/pow(cosmo_params_ps->hlittle*gamma, 1.5); cc = 1.0/pow(cosmo_params_ps->hlittle*gamma, 2); p = pow(k, cosmo_params_ps->POWER_INDEX) * 19400.0 / pow(1 + aa*k + pow(bb*k, 1.5) + cc*k*k, 2); } else if (user_params_ps->POWER_SPECTRUM == 5){ // JBM: CLASS T = TF_CLASS(k, 1, 0); //read from z=0 output of CLASS p = pow(k, cosmo_params_ps->POWER_INDEX) * T * T; if(user_params_ps->USE_RELATIVE_VELOCITIES) { //jbm:Add average relvel suppression p *= 1.0 - A_VCB_PM*exp( -pow(log(k/KP_VCB_PM),2.0)/(2.0*SIGMAK_VCB_PM*SIGMAK_VCB_PM)); //for v=vrms } } else{ LOG_ERROR("No such power spectrum defined: %i. Output is bogus.", user_params_ps->POWER_SPECTRUM); Throw(ValueError); } double Radius; Radius = *(double *)params; // now get the value of the window function kR = k * Radius; if (global_params.FILTER == 0){ // top hat if ( (kR) < 1.0e-4 ){ w = 1.0; }// w converges to 1 as (kR) -> 0 else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));} // now do d(w^2)/dm = 2 w dw/dr dr/dm if ( (kR) < 1.0e-10 ){ dwdr = 0;} else{ dwdr = 9*cos(kR)*k/pow(kR,3) + 3*sin(kR)*(1 - 3/(kR*kR))/(kR*Radius);} //3*k*( 3*cos(kR)/pow(kR,3) + sin(kR)*(-3*pow(kR, -4) + 1/(kR*kR)) );} // dwdr = -1e8 * k / (R*1e3); drdm = 1.0 / (4.0*PI * cosmo_params_ps->OMm*RHOcrit * Radius*Radius); } else if (global_params.FILTER == 1){ // gaussian of width 1/R w = pow(E, -kR*kR/2.0); dwdr = - k*kR * w; drdm = 1.0 / (pow(2*PI, 1.5) * cosmo_params_ps->OMm*RHOcrit * 3*Radius*Radius); } else { LOG_ERROR("No such filter: %i. Output is bogus.", global_params.FILTER); Throw(ValueError); } // return k*k*p*2*w*dwdr*drdm * d2fact; return k*k*p*2*w*dwdr*drdm; } double dsigmasqdm_z0(double M){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double kstart, kend; double Radius; // R = MtoR(M); Radius = MtoR(M); // now lets do the integral for sigma and scale it with sigma_norm if(user_params_ps->POWER_SPECTRUM == 5){ kstart = fmax(1.0e-99/Radius, KBOT_CLASS); kend = fmin(350.0/Radius, KTOP_CLASS); }//we establish a maximum k of KTOP_CLASS~1e3 Mpc-1 and a minimum at KBOT_CLASS,~1e-5 Mpc-1 since the CLASS transfer function has a max! else{ kstart = 1.0e-99/Radius; kend = 350.0/Radius; } lower_limit = kstart;//log(kstart); upper_limit = kend;//log(kend); if (user_params_ps->POWER_SPECTRUM == 5){ // for CLASS we do not need to renormalize the sigma integral. d2fact=1.0; } else { d2fact = M*10000/sigma_z0(M); } F.function = &dsigmasq_dm; F.params = &Radius; int status; gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("(function argument): lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: M=%e",M); GSL_ERROR(status); } gsl_integration_workspace_free (w); // return sigma_norm * sigma_norm * result /d2fact; return sigma_norm * sigma_norm * result; } /* sheth correction to delta crit */ double sheth_delc(double del, double sig){ return sqrt(SHETH_a)*del*(1. + global_params.SHETH_b*pow(sig*sig/(SHETH_a*del*del), global_params.SHETH_c)); } /* FUNCTION dNdM_st(z, M) Computes the Press_schechter mass function with Sheth-Torman correction for ellipsoidal collapse at redshift z, and dark matter halo mass M (in solar masses). Uses interpolated sigma and dsigmadm to be computed faster. Necessary for mass-dependent ionising efficiencies. The return value is the number density per unit mass of halos in the mass range M to M+dM in units of: comoving Mpc^-3 Msun^-1 Reference: Sheth, Mo, Torman 2001 */ double dNdM_st(double growthf, double M){ double sigma, dsigmadm, nuhat; float MassBinLow; int MassBin; if(user_params_ps->USE_INTERPOLATION_TABLES) { MassBin = (int)floor( (log(M) - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma = Sigma_InterpTable[MassBin] + ( log(M) - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = dSigmadm_InterpTable[MassBin] + ( log(M) - MassBinLow )*( dSigmadm_InterpTable[MassBin+1] - dSigmadm_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = -pow(10.,dsigmadm); } else { sigma = sigma_z0(M); dsigmadm = dsigmasqdm_z0(M); } sigma = sigma * growthf; dsigmadm = dsigmadm * (growthf*growthf/(2.*sigma)); nuhat = sqrt(SHETH_a) * Deltac / sigma; return (-(cosmo_params_ps->OMm)*RHOcrit/M) * (dsigmadm/sigma) * sqrt(2./PI)*SHETH_A * (1+ pow(nuhat, -2*SHETH_p)) * nuhat * pow(E, -nuhat*nuhat/2.0); } /* FUNCTION dNdM_WatsonFOF(z, M) Computes the Press_schechter mass function with Warren et al. 2011 correction for ellipsoidal collapse at redshift z, and dark matter halo mass M (in solar masses). The Universial FOF function (Eq. 12) of Watson et al. 2013 The return value is the number density per unit mass of halos in the mass range M to M+dM in units of: comoving Mpc^-3 Msun^-1 Reference: Watson et al. 2013 */ double dNdM_WatsonFOF(double growthf, double M){ double sigma, dsigmadm, f_sigma; float MassBinLow; int MassBin; if(user_params_ps->USE_INTERPOLATION_TABLES) { MassBin = (int)floor( (log(M) - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma = Sigma_InterpTable[MassBin] + ( log(M) - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = dSigmadm_InterpTable[MassBin] + ( log(M) - MassBinLow )*( dSigmadm_InterpTable[MassBin+1] - dSigmadm_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = -pow(10.,dsigmadm); } else { sigma = sigma_z0(M); dsigmadm = dsigmasqdm_z0(M); } sigma = sigma * growthf; dsigmadm = dsigmadm * (growthf*growthf/(2.*sigma)); f_sigma = Watson_A * ( pow( Watson_beta/sigma, Watson_alpha) + 1. ) * exp( - Watson_gamma/(sigma*sigma) ); return (-(cosmo_params_ps->OMm)*RHOcrit/M) * (dsigmadm/sigma) * f_sigma; } /* FUNCTION dNdM_WatsonFOF_z(z, M) Computes the Press_schechter mass function with Warren et al. 2011 correction for ellipsoidal collapse at redshift z, and dark matter halo mass M (in solar masses). The Universial FOF function, with redshift evolution (Eq. 12 - 15) of Watson et al. 2013. The return value is the number density per unit mass of halos in the mass range M to M+dM in units of: comoving Mpc^-3 Msun^-1 Reference: Watson et al. 2013 */ double dNdM_WatsonFOF_z(double z, double growthf, double M){ double sigma, dsigmadm, A_z, alpha_z, beta_z, Omega_m_z, f_sigma; float MassBinLow; int MassBin; if(user_params_ps->USE_INTERPOLATION_TABLES) { MassBin = (int)floor( (log(M) - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma = Sigma_InterpTable[MassBin] + ( log(M) - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = dSigmadm_InterpTable[MassBin] + ( log(M) - MassBinLow )*( dSigmadm_InterpTable[MassBin+1] - dSigmadm_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = -pow(10.,dsigmadm); } else { sigma = sigma_z0(M); dsigmadm = dsigmasqdm_z0(M); } sigma = sigma * growthf; dsigmadm = dsigmadm * (growthf*growthf/(2.*sigma)); Omega_m_z = (cosmo_params_ps->OMm)*pow(1.+z,3.) / ( (cosmo_params_ps->OMl) + (cosmo_params_ps->OMm)*pow(1.+z,3.) + (global_params.OMr)*pow(1.+z,4.) ); A_z = Omega_m_z * ( Watson_A_z_1 * pow(1. + z, Watson_A_z_2 ) + Watson_A_z_3 ); alpha_z = Omega_m_z * ( Watson_alpha_z_1 * pow(1.+z, Watson_alpha_z_2 ) + Watson_alpha_z_3 ); beta_z = Omega_m_z * ( Watson_beta_z_1 * pow(1.+z, Watson_beta_z_2 ) + Watson_beta_z_3 ); f_sigma = A_z * ( pow(beta_z/sigma, alpha_z) + 1. ) * exp( - Watson_gamma_z/(sigma*sigma) ); return (-(cosmo_params_ps->OMm)*RHOcrit/M) * (dsigmadm/sigma) * f_sigma; } /* FUNCTION dNdM(growthf, M) Computes the Press_schechter mass function at redshift z (using the growth factor), and dark matter halo mass M (in solar masses). Uses interpolated sigma and dsigmadm to be computed faster. Necessary for mass-dependent ionising efficiencies. The return value is the number density per unit mass of halos in the mass range M to M+dM in units of: comoving Mpc^-3 Msun^-1 Reference: Padmanabhan, pg. 214 */ double dNdM(double growthf, double M){ double sigma, dsigmadm; float MassBinLow; int MassBin; if(user_params_ps->USE_INTERPOLATION_TABLES) { MassBin = (int)floor( (log(M) - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma = Sigma_InterpTable[MassBin] + ( log(M) - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = dSigmadm_InterpTable[MassBin] + ( log(M) - MassBinLow )*( dSigmadm_InterpTable[MassBin+1] - dSigmadm_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = -pow(10.,dsigmadm); } else { sigma = sigma_z0(M); dsigmadm = dsigmasqdm_z0(M); } sigma = sigma * growthf; dsigmadm = dsigmadm * (growthf*growthf/(2.*sigma)); return (-(cosmo_params_ps->OMm)*RHOcrit/M) * sqrt(2/PI) * (Deltac/(sigma*sigma)) * dsigmadm * pow(E, -(Deltac*Deltac)/(2*sigma*sigma)); } /* FUNCTION FgtrM(z, M) Computes the fraction of mass contained in haloes with mass > M at redshift z */ double FgtrM(double z, double M){ double del, sig; del = Deltac/dicke(z); //regular spherical collapse delta sig = sigma_z0(M); return splined_erfc(del / (sqrt(2)*sig)); } /* FUNCTION FgtrM_wsigma(z, sigma_z0(M)) Computes the fraction of mass contained in haloes with mass > M at redshift z. Requires sigma_z0(M) rather than M to make certain heating integrals faster */ double FgtrM_wsigma(double z, double sig){ double del; del = Deltac/dicke(z); //regular spherical collapse delta return splined_erfc(del / (sqrt(2)*sig)); } /* FUNCTION FgtrM_Watson(z, M) Computes the fraction of mass contained in haloes with mass > M at redshift z Uses Watson et al (2013) correction */ double dFdlnM_Watson_z (double lnM, void *params){ struct parameters_gsl_FgtrM_int_ vals = *(struct parameters_gsl_FgtrM_int_ *)params; double M = exp(lnM); double z = vals.z_obs; double growthf = vals.gf_obs; return dNdM_WatsonFOF_z(z, growthf, M) * M * M; } double FgtrM_Watson_z(double z, double growthf, double M){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.001; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); F.function = &dFdlnM_Watson_z; struct parameters_gsl_FgtrM_int_ parameters_gsl_FgtrM = { .z_obs = z, .gf_obs = growthf, }; F.params = &parameters_gsl_FgtrM; lower_limit = log(M); upper_limit = log(fmax(global_params.M_MAX_INTEGRAL, M*100)); int status; gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("(function argument): lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: z=%e growthf=%e M=%e",z,growthf,M); GSL_ERROR(status); } gsl_integration_workspace_free (w); return result / (cosmo_params_ps->OMm*RHOcrit); } /* FUNCTION FgtrM_Watson(z, M) Computes the fraction of mass contained in haloes with mass > M at redshift z Uses Watson et al (2013) correction */ double dFdlnM_Watson (double lnM, void *params){ double growthf = *(double *)params; double M = exp(lnM); return dNdM_WatsonFOF(growthf, M) * M * M; } double FgtrM_Watson(double growthf, double M){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.001; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); F.function = &dFdlnM_Watson; F.params = &growthf; lower_limit = log(M); upper_limit = log(fmax(global_params.M_MAX_INTEGRAL, M*100)); int status; gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: growthf=%e M=%e",growthf,M); GSL_ERROR(status); } gsl_integration_workspace_free (w); return result / (cosmo_params_ps->OMm*RHOcrit); } double dFdlnM_General(double lnM, void *params){ struct parameters_gsl_FgtrM_int_ vals = *(struct parameters_gsl_FgtrM_int_ *)params; double M = exp(lnM); double z = vals.z_obs; double growthf = vals.gf_obs; double MassFunction; if(user_params_ps->HMF==0) { MassFunction = dNdM(growthf, M); } if(user_params_ps->HMF==1) { MassFunction = dNdM_st(growthf, M); } if(user_params_ps->HMF==2) { MassFunction = dNdM_WatsonFOF(growthf, M); } if(user_params_ps->HMF==3) { MassFunction = dNdM_WatsonFOF_z(z, growthf, M); } return MassFunction * M * M; } /* FUNCTION FgtrM_General(z, M) Computes the fraction of mass contained in haloes with mass > M at redshift z */ double FgtrM_General(double z, double M){ double del, sig, growthf; int status; growthf = dicke(z); struct parameters_gsl_FgtrM_int_ parameters_gsl_FgtrM = { .z_obs = z, .gf_obs = growthf, }; if(user_params_ps->HMF<4 && user_params_ps->HMF>-1) { double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.001; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); F.function = &dFdlnM_General; F.params = &parameters_gsl_FgtrM; lower_limit = log(M); upper_limit = log(fmax(global_params.M_MAX_INTEGRAL, M*100)); gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: z=%e growthf=%e M=%e",z,growthf,M); GSL_ERROR(status); } gsl_integration_workspace_free (w); return result / (cosmo_params_ps->OMm*RHOcrit); } else { LOG_ERROR("Incorrect HMF selected: %i (should be between 0 and 3).", user_params_ps->HMF); Throw(ValueError); } } double dNion_General(double lnM, void *params){ struct parameters_gsl_SFR_General_int_ vals = *(struct parameters_gsl_SFR_General_int_ *)params; double M = exp(lnM); double z = vals.z_obs; double growthf = vals.gf_obs; double MassTurnover = vals.Mdrop; double Alpha_star = vals.pl_star; double Alpha_esc = vals.pl_esc; double Fstar10 = vals.frac_star; double Fesc10 = vals.frac_esc; double Mlim_Fstar = vals.LimitMass_Fstar; double Mlim_Fesc = vals.LimitMass_Fesc; double Fstar, Fesc, MassFunction; if (Alpha_star > 0. && M > Mlim_Fstar) Fstar = 1./Fstar10; else if (Alpha_star < 0. && M < Mlim_Fstar) Fstar = 1/Fstar10; else Fstar = pow(M/1e10,Alpha_star); if (Alpha_esc > 0. && M > Mlim_Fesc) Fesc = 1./Fesc10; else if (Alpha_esc < 0. && M < Mlim_Fesc) Fesc = 1./Fesc10; else Fesc = pow(M/1e10,Alpha_esc); if(user_params_ps->HMF==0) { MassFunction = dNdM(growthf, M); } if(user_params_ps->HMF==1) { MassFunction = dNdM_st(growthf,M); } if(user_params_ps->HMF==2) { MassFunction = dNdM_WatsonFOF(growthf, M); } if(user_params_ps->HMF==3) { MassFunction = dNdM_WatsonFOF_z(z, growthf, M); } return MassFunction * M * M * exp(-MassTurnover/M) * Fstar * Fesc; } double Nion_General(double z, double M_Min, double MassTurnover, double Alpha_star, double Alpha_esc, double Fstar10, double Fesc10, double Mlim_Fstar, double Mlim_Fesc){ double growthf; growthf = dicke(z); double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.001; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); struct parameters_gsl_SFR_General_int_ parameters_gsl_SFR = { .z_obs = z, .gf_obs = growthf, .Mdrop = MassTurnover, .pl_star = Alpha_star, .pl_esc = Alpha_esc, .frac_star = Fstar10, .frac_esc = Fesc10, .LimitMass_Fstar = Mlim_Fstar, .LimitMass_Fesc = Mlim_Fesc, }; int status; if(user_params_ps->HMF<4 && user_params_ps->HMF>-1) { F.function = &dNion_General; F.params = &parameters_gsl_SFR; lower_limit = log(M_Min); upper_limit = log(fmax(global_params.M_MAX_INTEGRAL, M_Min*100)); gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("(function argument): lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: z=%e growthf=%e MassTurnover=%e Alpha_star=%e Alpha_esc=%e",z,growthf,MassTurnover,Alpha_star,Alpha_esc); LOG_ERROR("data: Fstar10=%e Fesc10=%e Mlim_Fstar=%e Mlim_Fesc=%e",Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc); GSL_ERROR(status); } gsl_integration_workspace_free (w); return result / ((cosmo_params_ps->OMm)*RHOcrit); } else { LOG_ERROR("Incorrect HMF selected: %i (should be between 0 and 3).", user_params_ps->HMF); Throw(ValueError); } } double dNion_General_MINI(double lnM, void *params){ struct parameters_gsl_SFR_General_int_ vals = *(struct parameters_gsl_SFR_General_int_ *)params; double M = exp(lnM); double z = vals.z_obs; double growthf = vals.gf_obs; double MassTurnover = vals.Mdrop; double MassTurnover_upper = vals.Mdrop_upper; double Alpha_star = vals.pl_star; double Alpha_esc = vals.pl_esc; double Fstar7_MINI = vals.frac_star; double Fesc7_MINI = vals.frac_esc; double Mlim_Fstar = vals.LimitMass_Fstar; double Mlim_Fesc = vals.LimitMass_Fesc; double Fstar, Fesc, MassFunction; if (Alpha_star > 0. && M > Mlim_Fstar) Fstar = 1./Fstar7_MINI; else if (Alpha_star < 0. && M < Mlim_Fstar) Fstar = 1/Fstar7_MINI; else Fstar = pow(M/1e7,Alpha_star); if (Alpha_esc > 0. && M > Mlim_Fesc) Fesc = 1./Fesc7_MINI; else if (Alpha_esc < 0. && M < Mlim_Fesc) Fesc = 1./Fesc7_MINI; else Fesc = pow(M/1e7,Alpha_esc); if(user_params_ps->HMF==0) { MassFunction = dNdM(growthf, M); } if(user_params_ps->HMF==1) { MassFunction = dNdM_st(growthf,M); } if(user_params_ps->HMF==2) { MassFunction = dNdM_WatsonFOF(growthf, M); } if(user_params_ps->HMF==3) { MassFunction = dNdM_WatsonFOF_z(z, growthf, M); } return MassFunction * M * M * exp(-MassTurnover/M) * exp(-M/MassTurnover_upper) * Fstar * Fesc; } double Nion_General_MINI(double z, double M_Min, double MassTurnover, double MassTurnover_upper, double Alpha_star, double Alpha_esc, double Fstar7_MINI, double Fesc7_MINI, double Mlim_Fstar, double Mlim_Fesc){ double growthf; int status; growthf = dicke(z); double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.001; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); struct parameters_gsl_SFR_General_int_ parameters_gsl_SFR = { .z_obs = z, .gf_obs = growthf, .Mdrop = MassTurnover, .Mdrop_upper = MassTurnover_upper, .pl_star = Alpha_star, .pl_esc = Alpha_esc, .frac_star = Fstar7_MINI, .frac_esc = Fesc7_MINI, .LimitMass_Fstar = Mlim_Fstar, .LimitMass_Fesc = Mlim_Fesc, }; if(user_params_ps->HMF<4 && user_params_ps->HMF>-1) { F.function = &dNion_General_MINI; F.params = &parameters_gsl_SFR; lower_limit = log(M_Min); upper_limit = log(fmax(global_params.M_MAX_INTEGRAL, M_Min*100)); gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occurred!"); LOG_ERROR("lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: z=%e growthf=%e MassTurnover=%e MassTurnover_upper=%e",z,growthf,MassTurnover,MassTurnover_upper); LOG_ERROR("data: Alpha_star=%e Alpha_esc=%e Fstar7_MINI=%e Fesc7_MINI=%e Mlim_Fstar=%e Mlim_Fesc=%e",Alpha_star,Alpha_esc,Fstar7_MINI,Fesc7_MINI,Mlim_Fstar,Mlim_Fesc); GSL_ERROR(status); } gsl_integration_workspace_free (w); return result / ((cosmo_params_ps->OMm)*RHOcrit); } else { LOG_ERROR("Incorrect HMF selected: %i (should be between 0 and 3).", user_params_ps->HMF); Throw(ValueError); } } /* returns the "effective Jeans mass" in Msun corresponding to the gas analog of WDM ; eq. 10 in Barkana+ 2001 */ double M_J_WDM(){ double z_eq, fudge=60; if (!(global_params.P_CUTOFF)) return 0; z_eq = 3600*(cosmo_params_ps->OMm-cosmo_params_ps->OMb)*cosmo_params_ps->hlittle*cosmo_params_ps->hlittle/0.15; return fudge*3.06e8 * (1.5/global_params.g_x) * sqrt((cosmo_params_ps->OMm-cosmo_params_ps->OMb)*cosmo_params_ps->hlittle*cosmo_params_ps->hlittle/0.15) * pow(global_params.M_WDM, -4) * pow(z_eq/3000.0, 1.5); } float erfcc(float x) { double t,q,ans; q=fabs(x); t=1.0/(1.0+0.5*q); ans=t*exp(-q*q-1.2655122+t*(1.0000237+t*(0.374092+t*(0.0967842+ t*(-0.1862881+t*(0.2788681+t*(-1.13520398+t*(1.4885159+ t*(-0.82215223+t*0.17087277))))))))); return x >= 0.0 ? ans : 2.0-ans; } double splined_erfc(double x){ if (x < 0){ return 1.0; } // TODO: This could be wrapped in a Try/Catch to try the fast way and if it doesn't // work, use the slow way. return erfcc(x); // the interpolation below doesn't seem to be stable in Ts.c if (x > ERFC_PARAM_DELTA*(ERFC_NPTS-1)) return erfcc(x); else return exp(gsl_spline_eval(erfc_spline, x, erfc_acc)); } void gauleg(float x1, float x2, float x[], float w[], int n) //Given the lower and upper limits of integration x1 and x2, and given n, this routine returns arrays x[1..n] and w[1..n] of length n, //containing the abscissas and weights of the Gauss- Legendre n-point quadrature formula. { int m,j,i; double z1,z,xm,xl,pp,p3,p2,p1; m=(n+1)/2; xm=0.5*(x2+x1); xl=0.5*(x2-x1); for (i=1;i<=m;i++) { //High precision is a good idea for this routine. //The roots are symmetric in the interval, so we only have to find half of them. //Loop over the desired roots. z=cos(3.141592654*(i-0.25)/(n+0.5)); //Starting with the above approximation to the ith root, we enter the main loop of refinement by Newton’s method. do { p1=1.0; p2=0.0; for (j=1;j<=n;j++) { //Loop up the recurrence relation to get the Legendre polynomial evaluated at z. p3=p2; p2=p1; p1=((2.0*j-1.0)*z*p2-(j-1.0)*p3)/j; } //p1 is now the desired Legendre polynomial. We next compute pp, its derivative, by a standard relation involving also p2, //the polynomial of one lower order. pp=n*(z*p1-p2)/(z*z-1.0); z1=z; z=z1-p1/pp; } while (fabs(z-z1) > EPS2); x[i]=xm-xl*z; x[n+1-i]=xm+xl*z; w[i]=2.0*xl/((1.0-z*z)*pp*pp); w[n+1-i]=w[i]; } } void initialiseSigmaMInterpTable(float M_Min, float M_Max) { int i; float Mass; if (Mass_InterpTable == NULL){ Mass_InterpTable = calloc(NMass,sizeof(float)); Sigma_InterpTable = calloc(NMass,sizeof(float)); dSigmadm_InterpTable = calloc(NMass,sizeof(float)); } #pragma omp parallel shared(Mass_InterpTable,Sigma_InterpTable,dSigmadm_InterpTable) private(i) num_threads(user_params_ps->N_THREADS) { #pragma omp for for(i=0;i<NMass;i++) { Mass_InterpTable[i] = log(M_Min) + (float)i/(NMass-1)*( log(M_Max) - log(M_Min) ); Sigma_InterpTable[i] = sigma_z0(exp(Mass_InterpTable[i])); dSigmadm_InterpTable[i] = log10(-dsigmasqdm_z0(exp(Mass_InterpTable[i]))); } } for(i=0;i<NMass;i++) { if(isfinite(Mass_InterpTable[i]) == 0 || isfinite(Sigma_InterpTable[i]) == 0 || isfinite(dSigmadm_InterpTable[i])==0) { LOG_ERROR("Detected either an infinite or NaN value in initialiseSigmaMInterpTable"); // Throw(ParameterError); Throw(TableGenerationError); } } MinMass = log(M_Min); mass_bin_width = 1./(NMass-1)*( log(M_Max) - log(M_Min) ); inv_mass_bin_width = 1./mass_bin_width; } void freeSigmaMInterpTable() { free(Mass_InterpTable); free(Sigma_InterpTable); free(dSigmadm_InterpTable); Mass_InterpTable = NULL; } void nrerror(char error_text[]) { LOG_ERROR("Numerical Recipes run-time error..."); LOG_ERROR("%s",error_text); Throw(MemoryAllocError); } float *vector(long nl, long nh) /* allocate a float vector with subscript range v[nl..nh] */ { float *v; v = (float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float))); if(!v) nrerror("allocation failure in vector()"); return v - nl + NR_END; } void free_vector(float *v, long nl, long nh) /* free a float vector allocated with vector() */ { free((FREE_ARG) (v+nl-NR_END)); } void spline(float x[], float y[], int n, float yp1, float ypn, float y2[]) /*Given arrays x[1..n] and y[1..n] containing a tabulated function, i.e., yi = f(xi), with x1 <x2 < :: : < xN, and given values yp1 and ypn for the first derivative of the interpolating function at points 1 and n, respectively, this routine returns an array y2[1..n] that contains the second derivatives of the interpolating function at the tabulated points xi. If yp1 and/or ypn are equal to 1e30 or larger, the routine is signaled to set the corresponding boundary condition for a natural spline, with zero second derivative on that boundary.*/ { int i,k; float p,qn,sig,un,*u; int na,nb,check; u=vector(1,n-1); if (yp1 > 0.99e30) // The lower boundary condition is set either to be "natural" y2[1]=u[1]=0.0; else { // or else to have a specified first derivative. y2[1] = -0.5; u[1]=(3.0/(x[2]-x[1]))*((y[2]-y[1])/(x[2]-x[1])-yp1); } for (i=2;i<=n-1;i++) { //This is the decomposition loop of the tridiagonal algorithm. sig=(x[i]-x[i-1])/(x[i+1]-x[i-1]); //y2 and u are used for temporary na = 1; nb = 1; check = 0; while(((float)(x[i+na*1]-x[i-nb*1])==(float)0.0)) { check = check + 1; if(check%2==0) { na = na + 1; } else { nb = nb + 1; } sig=(x[i]-x[i-1])/(x[i+na*1]-x[i-nb*1]); } p=sig*y2[i-1]+2.0; //storage of the decomposed y2[i]=(sig-1.0)/p; // factors. u[i]=(y[i+1]-y[i])/(x[i+1]-x[i]) - (y[i]-y[i-1])/(x[i]-x[i-1]); u[i]=(6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p; if(((float)(x[i+1]-x[i])==(float)0.0) || ((float)(x[i]-x[i-1])==(float)0.0)) { na = 0; nb = 0; check = 0; while((float)(x[i+na*1]-x[i-nb])==(float)(0.0) || ((float)(x[i+na]-x[i-nb*1])==(float)0.0)) { check = check + 1; if(check%2==0) { na = na + 1; } else { nb = nb + 1; } } u[i]=(y[i+1]-y[i])/(x[i+na*1]-x[i-nb]) - (y[i]-y[i-1])/(x[i+na]-x[i-nb*1]); u[i]=(6.0*u[i]/(x[i+na*1]-x[i-nb*1])-sig*u[i-1])/p; } } if (ypn > 0.99e30) //The upper boundary condition is set either to be "natural" qn=un=0.0; else { //or else to have a specified first derivative. qn=0.5; un=(3.0/(x[n]-x[n-1]))*(ypn-(y[n]-y[n-1])/(x[n]-x[n-1])); } y2[n]=(un-qn*u[n-1])/(qn*y2[n-1]+1.0); for (k=n-1;k>=1;k--) { //This is the backsubstitution loop of the tridiagonal y2[k]=y2[k]*y2[k+1]+u[k]; //algorithm. } free_vector(u,1,n-1); } void splint(float xa[], float ya[], float y2a[], int n, float x, float *y) /*Given the arrays xa[1..n] and ya[1..n], which tabulate a function (with the xai's in order), and given the array y2a[1..n], which is the output from spline above, and given a value of x, this routine returns a cubic-spline interpolated value y.*/ { void nrerror(char error_text[]); int klo,khi,k; float h,b,a; klo=1; // We will find the right place in the table by means of khi=n; //bisection. This is optimal if sequential calls to this while (khi-klo > 1) { //routine are at random values of x. If sequential calls k=(khi+klo) >> 1; //are in order, and closely spaced, one would do better if (xa[k] > x) khi=k; //to store previous values of klo and khi and test if else klo=k; //they remain appropriate on the next call. } // klo and khi now bracket the input value of x. h=xa[khi]-xa[klo]; if (h == 0.0) nrerror("Bad xa input to routine splint"); //The xa's must be distinct. a=(xa[khi]-x)/h; b=(x-xa[klo])/h; //Cubic spline polynomial is now evaluated. *y=a*ya[klo]+b*ya[khi]+((a*a*a-a)*y2a[klo]+(b*b*b-b)*y2a[khi])*(h*h)/6.0; } unsigned long *lvector(long nl, long nh) /* allocate an unsigned long vector with subscript range v[nl..nh] */ { unsigned long *v; v = (unsigned long *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(long))); if(!v) nrerror("allocation failure in lvector()"); return v - nl + NR_END; } void free_lvector(unsigned long *v, long nl, long nh) /* free an unsigned long vector allocated with lvector() */ { free((FREE_ARG) (v+nl-NR_END)); } /* dnbiasdM */ double dnbiasdM(double M, float z, double M_o, float del_o){ double sigsq, del, sig_one, sig_o; if ((M_o-M) < TINY){ LOG_ERROR("In function dnbiasdM: M must be less than M_o!\nAborting...\n"); Throw(ValueError); } del = Deltac/dicke(z) - del_o; if (del < 0){ LOG_ERROR(" In function dnbiasdM: del_o must be less than del_1 = del_crit/dicke(z)!\nAborting...\n"); Throw(ValueError); } sig_o = sigma_z0(M_o); sig_one = sigma_z0(M); sigsq = sig_one*sig_one - sig_o*sig_o; return -(RHOcrit*cosmo_params_ps->OMm)/M /sqrt(2*PI) *del*pow(sigsq,-1.5)*pow(E, -0.5*del*del/sigsq)*dsigmasqdm_z0(M); } /* calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias */ double FgtrM_bias(double z, double M, double del_bias, double sig_bias){ double del, sig, sigsmallR; sigsmallR = sigma_z0(M); if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo! // fprintf(stderr, "FgtrM_bias: Biased region is smaller than halo!\nResult is bogus.\n"); // return 0; return 0.000001; } del = Deltac/dicke(z) - del_bias; sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias); return splined_erfc(del / (sqrt(2)*sig)); } /* Uses sigma parameters instead of Mass for scale */ double sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias){ double del, sig; if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo! // fprintf(stderr, "local_FgtrM_bias: Biased region is smaller than halo!\nResult is bogus.\n"); // return 0; return 0.000001; } del = Deltac/dicke(z) - del_bias; sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias); return splined_erfc(del / (sqrt(2)*sig)); } /* redshift derivative of the growth function at z */ double ddicke_dz(double z){ float dz = 1e-10; double omegaM_z, ddickdz, dick_0, x, x_0, domegaMdz; return (dicke(z+dz)-dicke(z))/dz; } /* compute a mass limit where the stellar baryon fraction and the escape fraction exceed unity */ float Mass_limit (float logM, float PL, float FRAC) { return FRAC*pow(pow(10.,logM)/1e10,PL); } void bisection(float *x, float xlow, float xup, int *iter){ *x=(xlow + xup)/2.; ++(*iter); } float Mass_limit_bisection(float Mmin, float Mmax, float PL, float FRAC){ int i, iter, max_iter=200; float rel_tol=0.001; float logMlow, logMupper, x, x1; iter = 0; logMlow = log10(Mmin); logMupper = log10(Mmax); if (PL < 0.) { if (Mass_limit(logMlow,PL,FRAC) <= 1.) { return Mmin; } } else if (PL > 0.) { if (Mass_limit(logMupper,PL,FRAC) <= 1.) { return Mmax; } } else return 0; bisection(&x, logMlow, logMupper, &iter); do { if((Mass_limit(logMlow,PL,FRAC)-1.)*(Mass_limit(x,PL,FRAC)-1.) < 0.) logMupper = x; else logMlow = x; bisection(&x1, logMlow, logMupper, &iter); if(fabs(x1-x) < rel_tol) { return pow(10.,x1); } x = x1; } while(iter < max_iter); // Got to max_iter without finding a solution. LOG_ERROR("Failed to find a mass limit to regulate stellar fraction/escape fraction is between 0 and 1."); LOG_ERROR(" The solution does not converge or iterations are not sufficient."); // Throw(ParameterError); Throw(MassDepZetaError); return(0.0); } int initialise_ComputeLF(int nbins, struct UserParams *user_params, struct CosmoParams *cosmo_params, struct AstroParams *astro_params, struct FlagOptions *flag_options) { Broadcast_struct_global_PS(user_params,cosmo_params); Broadcast_struct_global_UF(user_params,cosmo_params); lnMhalo_param = calloc(nbins,sizeof(double)); Muv_param = calloc(nbins,sizeof(double)); Mhalo_param = calloc(nbins,sizeof(double)); LF_spline_acc = gsl_interp_accel_alloc(); LF_spline = gsl_spline_alloc(gsl_interp_cspline, nbins); init_ps(); int status; Try initialiseSigmaMInterpTable(0.999*Mhalo_min,1.001*Mhalo_max); Catch(status) { LOG_ERROR("\t...called from initialise_ComputeLF"); return(status); } initialised_ComputeLF = true; return(0); } void cleanup_ComputeLF(){ free(lnMhalo_param); free(Muv_param); free(Mhalo_param); gsl_spline_free (LF_spline); gsl_interp_accel_free(LF_spline_acc); freeSigmaMInterpTable(); initialised_ComputeLF = 0; } int ComputeLF(int nbins, struct UserParams *user_params, struct CosmoParams *cosmo_params, struct AstroParams *astro_params, struct FlagOptions *flag_options, int component, int NUM_OF_REDSHIFT_FOR_LF, float *z_LF, float *M_TURNs, double *M_uv_z, double *M_h_z, double *log10phi) { /* This is an API-level function and thus returns an int status. */ int status; Try{ // This try block covers the whole function. // This NEEDS to be done every time, because the actual object passed in as // user_params, cosmo_params etc. can change on each call, freeing up the memory. initialise_ComputeLF(nbins, user_params,cosmo_params,astro_params,flag_options); int i,i_z; int i_unity, i_smth, mf, nbins_smth=7; double dlnMhalo, lnMhalo_i, SFRparam, Muv_1, Muv_2, dMuvdMhalo; double Mhalo_i, lnMhalo_min, lnMhalo_max, lnMhalo_lo, lnMhalo_hi, dlnM, growthf; double f_duty_upper, Mcrit_atom; float Fstar, Fstar_temp; double dndm; int gsl_status; gsl_set_error_handler_off(); if (astro_params->ALPHA_STAR < -0.5) LOG_WARNING( "ALPHA_STAR is %f, which is unphysical value given the observational LFs.\n"\ "Also, when ALPHA_STAR < -.5, LFs may show a kink. It is recommended to set ALPHA_STAR > -0.5.", astro_params->ALPHA_STAR ); mf = user_params_ps->HMF; lnMhalo_min = log(Mhalo_min*0.999); lnMhalo_max = log(Mhalo_max*1.001); dlnMhalo = (lnMhalo_max - lnMhalo_min)/(double)(nbins - 1); for (i_z=0; i_z<NUM_OF_REDSHIFT_FOR_LF; i_z++) { growthf = dicke(z_LF[i_z]); Mcrit_atom = atomic_cooling_threshold(z_LF[i_z]); i_unity = -1; for (i=0; i<nbins; i++) { // generate interpolation arrays lnMhalo_param[i] = lnMhalo_min + dlnMhalo*(double)i; Mhalo_i = exp(lnMhalo_param[i]); if (component == 1) Fstar = astro_params->F_STAR10*pow(Mhalo_i/1e10,astro_params->ALPHA_STAR); else Fstar = astro_params->F_STAR7_MINI*pow(Mhalo_i/1e7,astro_params->ALPHA_STAR_MINI); if (Fstar > 1.) Fstar = 1; if (i_unity < 0) { // Find the array number at which Fstar crosses unity. if (astro_params->ALPHA_STAR > 0.) { if ( (1.- Fstar) < FRACT_FLOAT_ERR ) i_unity = i; } else if (astro_params->ALPHA_STAR < 0. && i < nbins-1) { if (component == 1) Fstar_temp = astro_params->F_STAR10*pow( exp(lnMhalo_min + dlnMhalo*(double)(i+1))/1e10,astro_params->ALPHA_STAR); else Fstar_temp = astro_params->F_STAR7_MINI*pow( exp(lnMhalo_min + dlnMhalo*(double)(i+1))/1e7,astro_params->ALPHA_STAR_MINI); if (Fstar_temp < 1. && (1.- Fstar) < FRACT_FLOAT_ERR) i_unity = i; } } // parametrization of SFR SFRparam = Mhalo_i * cosmo_params->OMb/cosmo_params->OMm * (double)Fstar * (double)(hubble(z_LF[i_z])*SperYR/astro_params->t_STAR); // units of M_solar/year Muv_param[i] = 51.63 - 2.5*log10(SFRparam*Luv_over_SFR); // UV magnitude // except if Muv value is nan or inf, but avoid error put the value as 10. if ( isinf(Muv_param[i]) || isnan(Muv_param[i]) ) Muv_param[i] = 10.; M_uv_z[i + i_z*nbins] = Muv_param[i]; } gsl_status = gsl_spline_init(LF_spline, lnMhalo_param, Muv_param, nbins); GSL_ERROR(gsl_status); lnMhalo_lo = log(Mhalo_min); lnMhalo_hi = log(Mhalo_max); dlnM = (lnMhalo_hi - lnMhalo_lo)/(double)(nbins - 1); // There is a kink on LFs at which Fstar crosses unity. This kink is a numerical artefact caused by the derivate of dMuvdMhalo. // Most of the cases the kink doesn't appear in magnitude ranges we are interested (e.g. -22 < Muv < -10). However, for some extreme // parameters, it appears. To avoid this kink, we use the interpolation of the derivate in the range where the kink appears. // 'i_unity' is the array number at which the kink appears. 'i_unity-3' and 'i_unity+12' are related to the range of interpolation, // which is an arbitrary choice. // NOTE: This method does NOT work in cases with ALPHA_STAR < -0.5. But, this parameter range is unphysical given that the // observational LFs favour positive ALPHA_STAR in this model. // i_smth = 0: calculates LFs without interpolation. // i_smth = 1: calculates LFs using interpolation where Fstar crosses unity. if (i_unity-3 < 0) i_smth = 0; else if (i_unity+12 > nbins-1) i_smth = 0; else i_smth = 1; if (i_smth == 0) { for (i=0; i<nbins; i++) { // calculate luminosity function lnMhalo_i = lnMhalo_lo + dlnM*(double)i; Mhalo_param[i] = exp(lnMhalo_i); M_h_z[i + i_z*nbins] = Mhalo_param[i]; Muv_1 = gsl_spline_eval(LF_spline, lnMhalo_i - delta_lnMhalo, LF_spline_acc); Muv_2 = gsl_spline_eval(LF_spline, lnMhalo_i + delta_lnMhalo, LF_spline_acc); dMuvdMhalo = (Muv_2 - Muv_1) / (2.*delta_lnMhalo * exp(lnMhalo_i)); if (component == 1) f_duty_upper = 1.; else f_duty_upper = exp(-(Mhalo_param[i]/Mcrit_atom)); if(mf==0) { log10phi[i + i_z*nbins] = log10( dNdM(growthf, exp(lnMhalo_i)) * exp(-(M_TURNs[i_z]/Mhalo_param[i])) * f_duty_upper / fabs(dMuvdMhalo) ); } else if(mf==1) { log10phi[i + i_z*nbins] = log10( dNdM_st(growthf, exp(lnMhalo_i)) * exp(-(M_TURNs[i_z]/Mhalo_param[i])) * f_duty_upper / fabs(dMuvdMhalo) ); } else if(mf==2) { log10phi[i + i_z*nbins] = log10( dNdM_WatsonFOF(growthf, exp(lnMhalo_i)) * exp(-(M_TURNs[i_z]/Mhalo_param[i])) * f_duty_upper / fabs(dMuvdMhalo) ); } else if(mf==3) { log10phi[i + i_z*nbins] = log10( dNdM_WatsonFOF_z(z_LF[i_z], growthf, exp(lnMhalo_i)) * exp(-(M_TURNs[i_z]/Mhalo_param[i])) * f_duty_upper / fabs(dMuvdMhalo) ); } else{ LOG_ERROR("HMF should be between 0-3, got %d", mf); Throw(ValueError); } if (isinf(log10phi[i + i_z*nbins]) || isnan(log10phi[i + i_z*nbins]) || log10phi[i + i_z*nbins] < -30.) log10phi[i + i_z*nbins] = -30.; } } else { lnM_temp = calloc(nbins_smth,sizeof(double)); deriv_temp = calloc(nbins_smth,sizeof(double)); deriv = calloc(nbins,sizeof(double)); for (i=0; i<nbins; i++) { // calculate luminosity function lnMhalo_i = lnMhalo_lo + dlnM*(double)i; Mhalo_param[i] = exp(lnMhalo_i); M_h_z[i + i_z*nbins] = Mhalo_param[i]; Muv_1 = gsl_spline_eval(LF_spline, lnMhalo_i - delta_lnMhalo, LF_spline_acc); Muv_2 = gsl_spline_eval(LF_spline, lnMhalo_i + delta_lnMhalo, LF_spline_acc); dMuvdMhalo = (Muv_2 - Muv_1) / (2.*delta_lnMhalo * exp(lnMhalo_i)); deriv[i] = fabs(dMuvdMhalo); } deriv_spline_acc = gsl_interp_accel_alloc(); deriv_spline = gsl_spline_alloc(gsl_interp_cspline, nbins_smth); // generate interpolation arrays to smooth discontinuity of the derivative causing a kink // Note that the number of array elements and the range of interpolation are made by arbitrary choices. lnM_temp[0] = lnMhalo_param[i_unity - 3]; lnM_temp[1] = lnMhalo_param[i_unity - 2]; lnM_temp[2] = lnMhalo_param[i_unity + 8]; lnM_temp[3] = lnMhalo_param[i_unity + 9]; lnM_temp[4] = lnMhalo_param[i_unity + 10]; lnM_temp[5] = lnMhalo_param[i_unity + 11]; lnM_temp[6] = lnMhalo_param[i_unity + 12]; deriv_temp[0] = deriv[i_unity - 3]; deriv_temp[1] = deriv[i_unity - 2]; deriv_temp[2] = deriv[i_unity + 8]; deriv_temp[3] = deriv[i_unity + 9]; deriv_temp[4] = deriv[i_unity + 10]; deriv_temp[5] = deriv[i_unity + 11]; deriv_temp[6] = deriv[i_unity + 12]; gsl_status = gsl_spline_init(deriv_spline, lnM_temp, deriv_temp, nbins_smth); GSL_ERROR(gsl_status); for (i=0;i<9;i++){ deriv[i_unity + i - 1] = gsl_spline_eval(deriv_spline, lnMhalo_param[i_unity + i - 1], deriv_spline_acc); } for (i=0; i<nbins; i++) { if (component == 1) f_duty_upper = 1.; else f_duty_upper = exp(-(Mhalo_param[i]/Mcrit_atom)); if(mf==0) dndm = dNdM(growthf, Mhalo_param[i]); else if(mf==1) dndm = dNdM_st(growthf, Mhalo_param[i]); else if(mf==2) dndm = dNdM_WatsonFOF(growthf, Mhalo_param[i]); else if(mf==3) dndm = dNdM_WatsonFOF_z(z_LF[i_z], growthf, Mhalo_param[i]); else{ LOG_ERROR("HMF should be between 0-3, got %d", mf); Throw(ValueError); } log10phi[i + i_z*nbins] = log10(dndm * exp(-(M_TURNs[i_z]/Mhalo_param[i])) * f_duty_upper / deriv[i]); if (isinf(log10phi[i + i_z*nbins]) || isnan(log10phi[i + i_z*nbins]) || log10phi[i + i_z*nbins] < -30.) log10phi[i + i_z*nbins] = -30.; } } } cleanup_ComputeLF(); } // End try Catch(status){ return status; } return(0); } void initialiseGL_Nion_Xray(int n, float M_Min, float M_Max){ //calculates the weightings and the positions for Gauss-Legendre quadrature. gauleg(log(M_Min),log(M_Max),xi_SFR_Xray,wi_SFR_Xray,n); } float dNdM_conditional(float growthf, float M1, float M2, float delta1, float delta2, float sigma2){ float sigma1, dsigmadm,dsigma_val; float MassBinLow; int MassBin; if(user_params_ps->USE_INTERPOLATION_TABLES) { MassBin = (int)floor( (M1 - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma1 = Sigma_InterpTable[MassBin] + ( M1 - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; dsigma_val = dSigmadm_InterpTable[MassBin] + ( M1 - MassBinLow )*( dSigmadm_InterpTable[MassBin+1] - dSigmadm_InterpTable[MassBin] )*inv_mass_bin_width; dsigmadm = -pow(10.,dsigma_val); } else { sigma1 = sigma_z0(exp(M1)); dsigmadm = dsigmasqdm_z0(exp(M1)); } M1 = exp(M1); M2 = exp(M2); sigma1 = sigma1*sigma1; sigma2 = sigma2*sigma2; dsigmadm = dsigmadm/(2.0*sigma1); // This is actually sigma1^{2} as calculated above, however, it should just be sigma1. It cancels with the same factor below. Why I have decided to write it like that I don't know! if((sigma1 > sigma2)) { return -(( delta1 - delta2 )/growthf)*( 2.*sigma1*dsigmadm )*( exp( - ( delta1 - delta2 )*( delta1 - delta2 )/( 2.*growthf*growthf*( sigma1 - sigma2 ) ) ) )/(pow( sigma1 - sigma2, 1.5)); } else if(sigma1==sigma2) { return -(( delta1 - delta2 )/growthf)*( 2.*sigma1*dsigmadm )*( exp( - ( delta1 - delta2 )*( delta1 - delta2 )/( 2.*growthf*growthf*( 1.e-6 ) ) ) )/(pow( 1.e-6, 1.5)); } else { return 0.; } } void initialiseGL_Nion(int n, float M_Min, float M_Max){ //calculates the weightings and the positions for Gauss-Legendre quadrature. gauleg(log(M_Min),log(M_Max),xi_SFR,wi_SFR,n); } double dNion_ConditionallnM_MINI(double lnM, void *params) { struct parameters_gsl_SFR_con_int_ vals = *(struct parameters_gsl_SFR_con_int_ *)params; double M = exp(lnM); // linear scale double growthf = vals.gf_obs; double M2 = vals.Mval; // natural log scale double sigma2 = vals.sigma2; double del1 = vals.delta1; double del2 = vals.delta2; double MassTurnover = vals.Mdrop; double MassTurnover_upper = vals.Mdrop_upper; double Alpha_star = vals.pl_star; double Alpha_esc = vals.pl_esc; double Fstar7_MINI = vals.frac_star; double Fesc7_MINI = vals.frac_esc; double Mlim_Fstar = vals.LimitMass_Fstar; double Mlim_Fesc = vals.LimitMass_Fesc; double Fstar,Fesc; if (Alpha_star > 0. && M > Mlim_Fstar) Fstar = 1./Fstar7_MINI; else if (Alpha_star < 0. && M < Mlim_Fstar) Fstar = 1./Fstar7_MINI; else Fstar = pow(M/1e7,Alpha_star); if (Alpha_esc > 0. && M > Mlim_Fesc) Fesc = 1./Fesc7_MINI; else if (Alpha_esc < 0. && M < Mlim_Fesc) Fesc = 1./Fesc7_MINI; else Fesc = pow(M/1e7,Alpha_esc); return M*exp(-MassTurnover/M)*exp(-M/MassTurnover_upper)*Fstar*Fesc*dNdM_conditional(growthf,log(M),M2,del1,del2,sigma2)/sqrt(2.*PI); } double dNion_ConditionallnM(double lnM, void *params) { struct parameters_gsl_SFR_con_int_ vals = *(struct parameters_gsl_SFR_con_int_ *)params; double M = exp(lnM); // linear scale double growthf = vals.gf_obs; double M2 = vals.Mval; // natural log scale double sigma2 = vals.sigma2; double del1 = vals.delta1; double del2 = vals.delta2; double MassTurnover = vals.Mdrop; double Alpha_star = vals.pl_star; double Alpha_esc = vals.pl_esc; double Fstar10 = vals.frac_star; double Fesc10 = vals.frac_esc; double Mlim_Fstar = vals.LimitMass_Fstar; double Mlim_Fesc = vals.LimitMass_Fesc; double Fstar,Fesc; if (Alpha_star > 0. && M > Mlim_Fstar) Fstar = 1./Fstar10; else if (Alpha_star < 0. && M < Mlim_Fstar) Fstar = 1./Fstar10; else Fstar = pow(M/1e10,Alpha_star); if (Alpha_esc > 0. && M > Mlim_Fesc) Fesc = 1./Fesc10; else if (Alpha_esc < 0. && M < Mlim_Fesc) Fesc = 1./Fesc10; else Fesc = pow(M/1e10,Alpha_esc); return M*exp(-MassTurnover/M)*Fstar*Fesc*dNdM_conditional(growthf,log(M),M2,del1,del2,sigma2)/sqrt(2.*PI); } double Nion_ConditionalM_MINI(double growthf, double M1, double M2, double sigma2, double delta1, double delta2, double MassTurnover, double MassTurnover_upper, double Alpha_star, double Alpha_esc, double Fstar10, double Fesc10, double Mlim_Fstar, double Mlim_Fesc, bool FAST_FCOLL_TABLES) { if (FAST_FCOLL_TABLES) { //JBM: Fast tables. Assume sharp Mturn, not exponential cutoff. return GaussLegendreQuad_Nion_MINI(0, 0, (float) growthf, (float) M2, (float) sigma2, (float) delta1, (float) delta2, (float) MassTurnover, (float) MassTurnover_upper, (float) Alpha_star, (float) Alpha_esc, (float) Fstar10, (float) Fesc10, (float) Mlim_Fstar, (float) Mlim_Fesc, FAST_FCOLL_TABLES); } else{ //standard old code double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.01; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); struct parameters_gsl_SFR_con_int_ parameters_gsl_SFR_con = { .gf_obs = growthf, .Mval = M2, .sigma2 = sigma2, .delta1 = delta1, .delta2 = delta2, .Mdrop = MassTurnover, .Mdrop_upper = MassTurnover_upper, .pl_star = Alpha_star, .pl_esc = Alpha_esc, .frac_star = Fstar10, .frac_esc = Fesc10, .LimitMass_Fstar = Mlim_Fstar, .LimitMass_Fesc = Mlim_Fesc }; int status; F.function = &dNion_ConditionallnM_MINI; F.params = &parameters_gsl_SFR_con; lower_limit = M1; upper_limit = M2; gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("(function argument): lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: growthf=%e M2=%e sigma2=%e delta1=%e delta2=%e MassTurnover=%e",growthf,M2,sigma2,delta1,delta2,MassTurnover); LOG_ERROR("data: MassTurnover_upper=%e Alpha_star=%e Alpha_esc=%e Fstar10=%e Fesc10=%e Mlim_Fstar=%e Mlim_Fesc=%e",MassTurnover_upper,Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc); GSL_ERROR(status); } gsl_integration_workspace_free (w); if(delta2 > delta1) { result = 1.; return result; } else { return result; } } } double Nion_ConditionalM(double growthf, double M1, double M2, double sigma2, double delta1, double delta2, double MassTurnover, double Alpha_star, double Alpha_esc, double Fstar10, double Fesc10, double Mlim_Fstar, double Mlim_Fesc, bool FAST_FCOLL_TABLES) { if (FAST_FCOLL_TABLES && global_params.USE_FAST_ATOMIC) { //JBM: Fast tables. Assume sharp Mturn, not exponential cutoff. return GaussLegendreQuad_Nion(0, 0, (float) growthf, (float) M2, (float) sigma2, (float) delta1, (float) delta2, (float) MassTurnover, (float) Alpha_star, (float) Alpha_esc, (float) Fstar10, (float) Fesc10, (float) Mlim_Fstar, (float) Mlim_Fesc, FAST_FCOLL_TABLES); } else{ //standard double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.01; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); struct parameters_gsl_SFR_con_int_ parameters_gsl_SFR_con = { .gf_obs = growthf, .Mval = M2, .sigma2 = sigma2, .delta1 = delta1, .delta2 = delta2, .Mdrop = MassTurnover, .pl_star = Alpha_star, .pl_esc = Alpha_esc, .frac_star = Fstar10, .frac_esc = Fesc10, .LimitMass_Fstar = Mlim_Fstar, .LimitMass_Fesc = Mlim_Fesc }; F.function = &dNion_ConditionallnM; F.params = &parameters_gsl_SFR_con; lower_limit = M1; upper_limit = M2; int status; gsl_set_error_handler_off(); status = gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); if(status!=0) { LOG_ERROR("gsl integration error occured!"); LOG_ERROR("(function argument): lower_limit=%e upper_limit=%e rel_tol=%e result=%e error=%e",lower_limit,upper_limit,rel_tol,result,error); LOG_ERROR("data: growthf=%e M1=%e M2=%e sigma2=%e delta1=%e delta2=%e",growthf,M1,M2,sigma2,delta1,delta2); LOG_ERROR("data: MassTurnover=%e Alpha_star=%e Alpha_esc=%e Fstar10=%e Fesc10=%e Mlim_Fstar=%e Mlim_Fesc=%e",MassTurnover,Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc); GSL_ERROR(status); } gsl_integration_workspace_free (w); if(delta2 > delta1) { result = 1.; return result; } else { return result; } } } float Nion_ConditionallnM_GL_MINI(float lnM, struct parameters_gsl_SFR_con_int_ parameters_gsl_SFR_con){ float M = exp(lnM); float growthf = parameters_gsl_SFR_con.gf_obs; float M2 = parameters_gsl_SFR_con.Mval; float sigma2 = parameters_gsl_SFR_con.sigma2; float del1 = parameters_gsl_SFR_con.delta1; float del2 = parameters_gsl_SFR_con.delta2; float MassTurnover = parameters_gsl_SFR_con.Mdrop; float MassTurnover_upper = parameters_gsl_SFR_con.Mdrop_upper; float Alpha_star = parameters_gsl_SFR_con.pl_star; float Alpha_esc = parameters_gsl_SFR_con.pl_esc; float Fstar7_MINI = parameters_gsl_SFR_con.frac_star; float Fesc7_MINI = parameters_gsl_SFR_con.frac_esc; float Mlim_Fstar = parameters_gsl_SFR_con.LimitMass_Fstar; float Mlim_Fesc = parameters_gsl_SFR_con.LimitMass_Fesc; float Fstar,Fesc; if (Alpha_star > 0. && M > Mlim_Fstar) Fstar = 1./Fstar7_MINI; else if (Alpha_star < 0. && M < Mlim_Fstar) Fstar = 1./Fstar7_MINI; else Fstar = pow(M/1e7,Alpha_star); if (Alpha_esc > 0. && M > Mlim_Fesc) Fesc = 1./Fesc7_MINI; else if (Alpha_esc < 0. && M < Mlim_Fesc) Fesc = 1./Fesc7_MINI; else Fesc = pow(M/1e7,Alpha_esc); return M*exp(-MassTurnover/M)*exp(-M/MassTurnover_upper)*Fstar*Fesc*dNdM_conditional(growthf,log(M),M2,del1,del2,sigma2)/sqrt(2.*PI); } float Nion_ConditionallnM_GL(float lnM, struct parameters_gsl_SFR_con_int_ parameters_gsl_SFR_con){ float M = exp(lnM); float growthf = parameters_gsl_SFR_con.gf_obs; float M2 = parameters_gsl_SFR_con.Mval; float sigma2 = parameters_gsl_SFR_con.sigma2; float del1 = parameters_gsl_SFR_con.delta1; float del2 = parameters_gsl_SFR_con.delta2; float MassTurnover = parameters_gsl_SFR_con.Mdrop; float Alpha_star = parameters_gsl_SFR_con.pl_star; float Alpha_esc = parameters_gsl_SFR_con.pl_esc; float Fstar10 = parameters_gsl_SFR_con.frac_star; float Fesc10 = parameters_gsl_SFR_con.frac_esc; float Mlim_Fstar = parameters_gsl_SFR_con.LimitMass_Fstar; float Mlim_Fesc = parameters_gsl_SFR_con.LimitMass_Fesc; float Fstar,Fesc; if (Alpha_star > 0. && M > Mlim_Fstar) Fstar = 1./Fstar10; else if (Alpha_star < 0. && M < Mlim_Fstar) Fstar = 1./Fstar10; else Fstar = pow(M/1e10,Alpha_star); if (Alpha_esc > 0. && M > Mlim_Fesc) Fesc = 1./Fesc10; else if (Alpha_esc < 0. && M < Mlim_Fesc) Fesc = 1./Fesc10; else Fesc = pow(M/1e10,Alpha_esc); return M*exp(-MassTurnover/M)*Fstar*Fesc*dNdM_conditional(growthf,log(M),M2,del1,del2,sigma2)/sqrt(2.*PI); } //JBM: Same as above but for minihaloes. Has two cutoffs, lower and upper. float GaussLegendreQuad_Nion_MINI(int Type, int n, float growthf, float M2, float sigma2, float delta1, float delta2, float MassTurnover, float MassTurnover_upper, float Alpha_star, float Alpha_esc, float Fstar7_MINI, float Fesc7_MINI, float Mlim_Fstar_MINI, float Mlim_Fesc_MINI, bool FAST_FCOLL_TABLES) { double result, nu_lower_limit, nu_higher_limit, nupivot; int i; double integrand, x; integrand = 0.; struct parameters_gsl_SFR_con_int_ parameters_gsl_SFR_con = { .gf_obs = growthf, .Mval = M2, .sigma2 = sigma2, .delta1 = delta1, .delta2 = delta2, .Mdrop = MassTurnover, .Mdrop_upper = MassTurnover_upper, .pl_star = Alpha_star, .pl_esc = Alpha_esc, .frac_star = Fstar7_MINI, .frac_esc = Fesc7_MINI, .LimitMass_Fstar = Mlim_Fstar_MINI, .LimitMass_Fesc = Mlim_Fesc_MINI }; if(delta2 > delta1*0.9999) { result = 1.; return result; } if(FAST_FCOLL_TABLES){ //JBM: Fast tables. Assume sharp Mturn, not exponential cutoff. if(MassTurnover_upper <= MassTurnover){ return 1e-40; //in sharp cut it's zero } double delta_arg = pow( (delta1 - delta2)/growthf , 2.); double LogMass=log(MassTurnover); int MassBin = (int)floor( (LogMass - MinMass )*inv_mass_bin_width ); double MassBinLow = MinMass + mass_bin_width*(double)MassBin; double sigmaM1 = Sigma_InterpTable[MassBin] + ( LogMass - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; nu_lower_limit = delta_arg/(sigmaM1 * sigmaM1 - sigma2 * sigma2); LogMass = log(MassTurnover_upper); MassBin = (int)floor( (LogMass - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(double)MassBin; double sigmaM2 = Sigma_InterpTable[MassBin] + ( LogMass - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; nu_higher_limit = delta_arg/(sigmaM2*sigmaM2-sigma2*sigma2); //note we keep nupivot1 just in case very negative delta makes it reach that nu LogMass = log(MPIVOT1); //jbm could be done outside and it'd be even faster int MassBinpivot = (int)floor( (LogMass - MinMass )*inv_mass_bin_width ); double MassBinLowpivot = MinMass + mass_bin_width*(double)MassBinpivot; double sigmapivot1 = Sigma_InterpTable[MassBinpivot] + ( LogMass - MassBinLowpivot )*( Sigma_InterpTable[MassBinpivot+1] - Sigma_InterpTable[MassBinpivot] )*inv_mass_bin_width; double nupivot1 = delta_arg/(sigmapivot1*sigmapivot1); //note, it does not have the sigma2 on purpose. LogMass = log(MPIVOT2); //jbm could be done outside and it'd be even faster MassBinpivot = (int)floor( (LogMass - MinMass )*inv_mass_bin_width ); MassBinLowpivot = MinMass + mass_bin_width*(double)MassBinpivot; double sigmapivot2 = Sigma_InterpTable[MassBinpivot] + ( LogMass - MassBinLowpivot )*( Sigma_InterpTable[MassBinpivot+1] - Sigma_InterpTable[MassBinpivot] )*inv_mass_bin_width; double nupivot2 = delta_arg/(sigmapivot2*sigmapivot2); double beta1 = (Alpha_star+Alpha_esc) * AINDEX1 * (0.5); //exponent for Fcollapprox for nu>nupivot1 (large M) double beta2 = (Alpha_star+Alpha_esc) * AINDEX2 * (0.5); //exponent for Fcollapprox for nupivot1>nu>nupivot2 (small M) double beta3 = (Alpha_star+Alpha_esc) * AINDEX3 * (0.5); //exponent for Fcollapprox for nu<nupivot2 (smallest M) //beta2 fixed by continuity. // // 3PLs double fcollres=0.0; double fcollres_high=0.0; //for the higher threshold to subtract // re-written for further speedups if (nu_higher_limit <= nupivot2){ //if both are below pivot2 don't bother adding and subtracting the high contribution fcollres=(Fcollapprox(nu_lower_limit,beta3))*pow(nupivot2,-beta3); fcollres_high=(Fcollapprox(nu_higher_limit,beta3))*pow(nupivot2,-beta3); } else { fcollres_high=(Fcollapprox(nu_higher_limit,beta2))*pow(nupivot1,-beta2); if (nu_lower_limit > nupivot2){ fcollres=(Fcollapprox(nu_lower_limit,beta2))*pow(nupivot1,-beta2); } else { fcollres=(Fcollapprox(nupivot2,beta2))*pow(nupivot1,-beta2); fcollres+=(Fcollapprox(nu_lower_limit,beta3)-Fcollapprox(nupivot2,beta3) )*pow(nupivot2,-beta3); } } if (fcollres < fcollres_high){ return 1e-40; } return (fcollres-fcollres_high); } else{ for(i=1; i<(n+1); i++){ if(Type==1) { x = xi_SFR_Xray[i]; integrand += wi_SFR_Xray[i]*Nion_ConditionallnM_GL_MINI(x,parameters_gsl_SFR_con); } if(Type==0) { x = xi_SFR[i]; integrand += wi_SFR[i]*Nion_ConditionallnM_GL_MINI(x,parameters_gsl_SFR_con); } } return integrand; } } //JBM: Added the approximation if user_params->FAST_FCOLL_TABLES==True float GaussLegendreQuad_Nion(int Type, int n, float growthf, float M2, float sigma2, float delta1, float delta2, float MassTurnover, float Alpha_star, float Alpha_esc, float Fstar10, float Fesc10, float Mlim_Fstar, float Mlim_Fesc, bool FAST_FCOLL_TABLES) { //Performs the Gauss-Legendre quadrature. int i; double result, nu_lower_limit, nupivot; if(delta2 > delta1*0.9999) { result = 1.; return result; } double integrand, x; integrand = 0.; struct parameters_gsl_SFR_con_int_ parameters_gsl_SFR_con = { .gf_obs = growthf, .Mval = M2, .sigma2 = sigma2, .delta1 = delta1, .delta2 = delta2, .Mdrop = MassTurnover, .pl_star = Alpha_star, .pl_esc = Alpha_esc, .frac_star = Fstar10, .frac_esc = Fesc10, .LimitMass_Fstar = Mlim_Fstar, .LimitMass_Fesc = Mlim_Fesc }; if (FAST_FCOLL_TABLES && global_params.USE_FAST_ATOMIC){ //JBM: Fast tables. Assume sharp Mturn, not exponential cutoff. double delta_arg = pow( (delta1 - delta2)/growthf , 2.0); double LogMass=log(MassTurnover); int MassBin = (int)floor( (LogMass - MinMass )*inv_mass_bin_width ); double MassBinLow = MinMass + mass_bin_width*(double)MassBin; double sigmaM1 = Sigma_InterpTable[MassBin] + ( LogMass - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; nu_lower_limit = delta_arg/(sigmaM1*sigmaM1-sigma2*sigma2); LogMass = log(MPIVOT1); //jbm could be done outside and it'd be even faster int MassBinpivot = (int)floor( (LogMass - MinMass )*inv_mass_bin_width ); double MassBinLowpivot = MinMass + mass_bin_width*(double)MassBinpivot; double sigmapivot1 = Sigma_InterpTable[MassBinpivot] + ( LogMass - MassBinLowpivot )*( Sigma_InterpTable[MassBinpivot+1] - Sigma_InterpTable[MassBinpivot] )*inv_mass_bin_width; double nupivot1 = delta_arg/(sigmapivot1*sigmapivot1); //note, it does not have the sigma2 on purpose. LogMass = log(MPIVOT2); //jbm could be done outside and it'd be even faster MassBinpivot = (int)floor( (LogMass - MinMass )*inv_mass_bin_width ); MassBinLowpivot = MinMass + mass_bin_width*(double)MassBinpivot; double sigmapivot2 = Sigma_InterpTable[MassBinpivot] + ( LogMass - MassBinLowpivot )*( Sigma_InterpTable[MassBinpivot+1] - Sigma_InterpTable[MassBinpivot] )*inv_mass_bin_width; double nupivot2 = delta_arg/(sigmapivot2*sigmapivot2); double beta1 = (Alpha_star+Alpha_esc) * AINDEX1 * (0.5); //exponent for Fcollapprox for nu>nupivot1 (large M) double beta2 = (Alpha_star+Alpha_esc) * AINDEX2 * (0.5); //exponent for Fcollapprox for nupivot2<nu<nupivot1 (small M) double beta3 = (Alpha_star+Alpha_esc) * AINDEX3 * (0.5); //exponent for Fcollapprox for nu<nupivot2 (smallest M) //beta2 fixed by continuity. double nucrit_sigma2 = delta_arg*pow(sigma2+1e-10,-2.0); //above this nu sigma2>sigma1, so HMF=0. eps added to avoid infinities // // 3PLs double fcollres=0.0; if(nu_lower_limit >= nucrit_sigma2){ //fully in the flat part of sigma(nu), M^alpha is nu-independent. return 1e-40; } else{ //we subtract the contribution from high nu, since the HMF is set to 0 if sigma2>sigma1 fcollres -= Fcollapprox(nucrit_sigma2,beta1)*pow(nupivot1,-beta1); } if(nu_lower_limit >= nupivot1){ fcollres+=Fcollapprox(nu_lower_limit,beta1)*pow(nupivot1,-beta1); } else{ fcollres+=Fcollapprox(nupivot1,beta1)*pow(nupivot1,-beta1); if (nu_lower_limit > nupivot2){ fcollres+=(Fcollapprox(nu_lower_limit,beta2)-Fcollapprox(nupivot1,beta2))*pow(nupivot1,-beta2); } else { fcollres+=(Fcollapprox(nupivot2,beta2)-Fcollapprox(nupivot1,beta2) )*pow(nupivot1,-beta2); fcollres+=(Fcollapprox(nu_lower_limit,beta3)-Fcollapprox(nupivot2,beta3) )*pow(nupivot2,-beta3); } } if (fcollres<=0.0){ LOG_DEBUG("Negative fcoll? fc=%.1le Mt=%.1le \n",fcollres, MassTurnover); fcollres=1e-40; } return fcollres; } else{ for(i=1; i<(n+1); i++){ if(Type==1) { x = xi_SFR_Xray[i]; integrand += wi_SFR_Xray[i]*Nion_ConditionallnM_GL(x,parameters_gsl_SFR_con); } if(Type==0) { x = xi_SFR[i]; integrand += wi_SFR[i]*Nion_ConditionallnM_GL(x,parameters_gsl_SFR_con); } } return integrand; } } #include <gsl/gsl_sf_gamma.h> //JBM: Integral of a power-law times exponential for EPS: \int dnu nu^beta * exp(-nu/2)/sqrt(nu) from numin to infty. double Fcollapprox (double numin, double beta){ //nu is deltacrit^2/sigma^2, corrected by delta(R) and sigma(R) double gg = gsl_sf_gamma_inc(0.5+beta,0.5*numin); return gg*pow(2,0.5+beta)*pow(2.0*PI,-0.5); } void initialise_Nion_General_spline(float z, float min_density, float max_density, float Mmax, float MassTurnover, float Alpha_star, float Alpha_esc, float Fstar10, float Fesc10, float Mlim_Fstar, float Mlim_Fesc, bool FAST_FCOLL_TABLES){ float Mmin = MassTurnover/50.; double overdense_val, growthf, sigma2; double overdense_large_high = Deltac, overdense_large_low = global_params.CRIT_DENS_TRANSITION*0.999; double overdense_small_high, overdense_small_low; int i; float ln_10; if(max_density > global_params.CRIT_DENS_TRANSITION*1.001) { overdense_small_high = global_params.CRIT_DENS_TRANSITION*1.001; } else { overdense_small_high = max_density; } overdense_small_low = min_density; ln_10 = log(10); float MassBinLow; int MassBin; growthf = dicke(z); Mmin = log(Mmin); Mmax = log(Mmax); MassBin = (int)floor( ( Mmax - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma2 = Sigma_InterpTable[MassBin] + ( Mmax - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; #pragma omp parallel shared(log10_overdense_spline_SFR,log10_Nion_spline,overdense_small_low,overdense_small_high,growthf,Mmax,sigma2,MassTurnover,Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc) private(i,overdense_val) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<NSFR_low; i++){ overdense_val = log10(1. + overdense_small_low) + (double)i/((double)NSFR_low-1.)*(log10(1.+overdense_small_high)-log10(1.+overdense_small_low)); log10_overdense_spline_SFR[i] = overdense_val; log10_Nion_spline[i] = GaussLegendreQuad_Nion(0,NGL_SFR,growthf,Mmax,sigma2,Deltac,pow(10.,overdense_val)-1.,MassTurnover,Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc, FAST_FCOLL_TABLES); if(fabs(log10_Nion_spline[i]) < 1e-38) { log10_Nion_spline[i] = 1e-38; } log10_Nion_spline[i] = log10(log10_Nion_spline[i]); if(log10_Nion_spline[i] < -40.){ log10_Nion_spline[i] = -40.; } log10_Nion_spline[i] *= ln_10; } } for (i=0; i<NSFR_low; i++){ if(!isfinite(log10_Nion_spline[i])) { LOG_ERROR("Detected either an infinite or NaN value in log10_Nion_spline"); // Throw(ParameterError); Throw(TableGenerationError); } } #pragma omp parallel shared(Overdense_spline_SFR,Nion_spline,overdense_large_low,overdense_large_high,growthf,Mmin,Mmax,sigma2,MassTurnover,Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc) private(i) num_threads(user_params_ps->N_THREADS) { #pragma omp for for(i=0;i<NSFR_high;i++) { Overdense_spline_SFR[i] = overdense_large_low + (float)i/((float)NSFR_high-1.)*(overdense_large_high - overdense_large_low); Nion_spline[i] = Nion_ConditionalM(growthf,Mmin,Mmax,sigma2,Deltac,Overdense_spline_SFR[i],MassTurnover,Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc, FAST_FCOLL_TABLES); if(Nion_spline[i]<0.) { Nion_spline[i]=pow(10.,-40.0); } } } for(i=0;i<NSFR_high;i++) { if(!isfinite(Nion_spline[i])) { LOG_ERROR("Detected either an infinite or NaN value in log10_Nion_spline"); // Throw(ParameterError); Throw(TableGenerationError); } } } void initialise_Nion_General_spline_MINI(float z, float Mcrit_atom, float min_density, float max_density, float Mmax, float Mmin, float log10Mturn_min, float log10Mturn_max, float log10Mturn_min_MINI, float log10Mturn_max_MINI, float Alpha_star, float Alpha_star_mini, float Alpha_esc, float Fstar10, float Fesc10, float Mlim_Fstar, float Mlim_Fesc, float Fstar7_MINI, float Fesc7_MINI, float Mlim_Fstar_MINI, float Mlim_Fesc_MINI, bool FAST_FCOLL_TABLES){ double growthf, sigma2; double overdense_large_high = Deltac, overdense_large_low = global_params.CRIT_DENS_TRANSITION*0.999; double overdense_small_high, overdense_small_low; int i,j; float ln_10; if(max_density > global_params.CRIT_DENS_TRANSITION*1.001) { overdense_small_high = global_params.CRIT_DENS_TRANSITION*1.001; } else { overdense_small_high = max_density; } overdense_small_low = min_density; ln_10 = log(10); float MassBinLow; int MassBin; growthf = dicke(z); Mmin = log(Mmin); Mmax = log(Mmax); MassBin = (int)floor( ( Mmax - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma2 = Sigma_InterpTable[MassBin] + ( Mmax - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; for (i=0; i<NSFR_low; i++){ log10_overdense_spline_SFR[i] = log10(1. + overdense_small_low) + (double)i/((double)NSFR_low-1.)*(log10(1.+overdense_small_high)-log10(1.+overdense_small_low)); } for (i=0;i<NSFR_high;i++) { Overdense_spline_SFR[i] = overdense_large_low + (float)i/((float)NSFR_high-1.)*(overdense_large_high - overdense_large_low); } for (i=0;i<NMTURN;i++){ Mturns[i] = pow(10., log10Mturn_min + (float)i/((float)NMTURN-1.)*(log10Mturn_max-log10Mturn_min)); Mturns_MINI[i] = pow(10., log10Mturn_min_MINI + (float)i/((float)NMTURN-1.)*(log10Mturn_max_MINI-log10Mturn_min_MINI)); } #pragma omp parallel shared(log10_Nion_spline,growthf,Mmax,sigma2,log10_overdense_spline_SFR,Mturns,Mturns_MINI,\ Alpha_star,Alpha_star_mini,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc,ln_10,log10_Nion_spline_MINI,Mcrit_atom,\ Fstar7_MINI,Fesc7_MINI,Mlim_Fstar_MINI,Mlim_Fesc_MINI) \ private(i,j) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<NSFR_low; i++){ for (j=0; j<NMTURN; j++){ log10_Nion_spline[i+j*NSFR_low] = log10(GaussLegendreQuad_Nion(0,NGL_SFR,growthf,Mmax,sigma2,Deltac,\ pow(10.,log10_overdense_spline_SFR[i])-1.,Mturns[j],Alpha_star,\ Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc, FAST_FCOLL_TABLES)); if(log10_Nion_spline[i+j*NSFR_low] < -40.){ log10_Nion_spline[i+j*NSFR_low] = -40.; } log10_Nion_spline[i+j*NSFR_low] *= ln_10; log10_Nion_spline_MINI[i+j*NSFR_low] = log10(GaussLegendreQuad_Nion_MINI(0,NGL_SFR,growthf,Mmax,sigma2,Deltac,\ pow(10.,log10_overdense_spline_SFR[i])-1.,Mturns_MINI[j],Mcrit_atom,\ Alpha_star_mini,Alpha_esc,Fstar7_MINI,Fesc7_MINI,Mlim_Fstar_MINI,Mlim_Fesc_MINI, FAST_FCOLL_TABLES)); if(log10_Nion_spline_MINI[i+j*NSFR_low] < -40.){ log10_Nion_spline_MINI[i+j*NSFR_low] = -40.; } log10_Nion_spline_MINI[i+j*NSFR_low] *= ln_10; } } } for (i=0; i<NSFR_low; i++){ for (j=0; j<NMTURN; j++){ if(isfinite(log10_Nion_spline[i+j*NSFR_low])==0) { LOG_ERROR("Detected either an infinite or NaN value in log10_Nion_spline"); // Throw(ParameterError); Throw(TableGenerationError); } if(isfinite(log10_Nion_spline_MINI[i+j*NSFR_low])==0) { LOG_ERROR("Detected either an infinite or NaN value in log10_Nion_spline_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } #pragma omp parallel shared(Nion_spline,growthf,Mmin,Mmax,sigma2,Overdense_spline_SFR,Mturns,Alpha_star,Alpha_star_mini,\ Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc,Nion_spline_MINI,Mturns_MINI,Mcrit_atom,\ Fstar7_MINI,Fesc7_MINI,Mlim_Fstar_MINI,Mlim_Fesc_MINI) \ private(i,j) num_threads(user_params_ps->N_THREADS) { #pragma omp for for(i=0;i<NSFR_high;i++) { for (j=0; j<NMTURN; j++){ Nion_spline[i+j*NSFR_high] = Nion_ConditionalM( growthf,Mmin,Mmax,sigma2,Deltac,Overdense_spline_SFR[i], Mturns[j],Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc, FAST_FCOLL_TABLES ); if(Nion_spline[i+j*NSFR_high]<0.) { Nion_spline[i+j*NSFR_high]=pow(10.,-40.0); } Nion_spline_MINI[i+j*NSFR_high] = Nion_ConditionalM_MINI( growthf,Mmin,Mmax,sigma2,Deltac,Overdense_spline_SFR[i], Mturns_MINI[j],Mcrit_atom,Alpha_star_mini,Alpha_esc,Fstar7_MINI,Fesc7_MINI, Mlim_Fstar_MINI,Mlim_Fesc_MINI, FAST_FCOLL_TABLES ); if(Nion_spline_MINI[i+j*NSFR_high]<0.) { Nion_spline_MINI[i+j*NSFR_high]=pow(10.,-40.0); } } } } for(i=0;i<NSFR_high;i++) { for (j=0; j<NMTURN; j++){ if(isfinite(Nion_spline[i+j*NSFR_high])==0) { LOG_ERROR("Detected either an infinite or NaN value in Nion_spline"); // Throw(ParameterError); Throw(TableGenerationError); } if(isfinite(Nion_spline_MINI[i+j*NSFR_high])==0) { LOG_ERROR("Detected either an infinite or NaN value in Nion_spline_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } } void initialise_Nion_General_spline_MINI_prev(float z, float Mcrit_atom, float min_density, float max_density, float Mmax, float Mmin, float log10Mturn_min, float log10Mturn_max, float log10Mturn_min_MINI, float log10Mturn_max_MINI, float Alpha_star, float Alpha_star_mini, float Alpha_esc, float Fstar10, float Fesc10, float Mlim_Fstar, float Mlim_Fesc, float Fstar7_MINI, float Fesc7_MINI, float Mlim_Fstar_MINI, float Mlim_Fesc_MINI, bool FAST_FCOLL_TABLES){ double growthf, sigma2; double overdense_large_high = Deltac, overdense_large_low = global_params.CRIT_DENS_TRANSITION*0.999; double overdense_small_high, overdense_small_low; int i,j; float ln_10; if(max_density > global_params.CRIT_DENS_TRANSITION*1.001) { overdense_small_high = global_params.CRIT_DENS_TRANSITION*1.001; } else { overdense_small_high = max_density; } overdense_small_low = min_density; ln_10 = log(10); float MassBinLow; int MassBin; growthf = dicke(z); Mmin = log(Mmin); Mmax = log(Mmax); MassBin = (int)floor( ( Mmax - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma2 = Sigma_InterpTable[MassBin] + ( Mmax - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; for (i=0; i<NSFR_low; i++){ prev_log10_overdense_spline_SFR[i] = log10(1. + overdense_small_low) + (double)i/((double)NSFR_low-1.)*(log10(1.+overdense_small_high)-log10(1.+overdense_small_low)); } for (i=0;i<NSFR_high;i++) { prev_Overdense_spline_SFR[i] = overdense_large_low + (float)i/((float)NSFR_high-1.)*(overdense_large_high - overdense_large_low); } for (i=0;i<NMTURN;i++){ Mturns[i] = pow(10., log10Mturn_min + (float)i/((float)NMTURN-1.)*(log10Mturn_max-log10Mturn_min)); Mturns_MINI[i] = pow(10., log10Mturn_min_MINI + (float)i/((float)NMTURN-1.)*(log10Mturn_max_MINI-log10Mturn_min_MINI)); } #pragma omp parallel shared(prev_log10_Nion_spline,growthf,Mmax,sigma2,prev_log10_overdense_spline_SFR,Mturns,Alpha_star,Alpha_star_mini,\ Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc,prev_log10_Nion_spline_MINI,Mturns_MINI,Mcrit_atom,\ Fstar7_MINI,Fesc7_MINI,Mlim_Fstar_MINI,Mlim_Fesc_MINI) \ private(i,j) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<NSFR_low; i++){ for (j=0; j<NMTURN; j++){ prev_log10_Nion_spline[i+j*NSFR_low] = log10(GaussLegendreQuad_Nion(0,NGL_SFR,growthf,Mmax,sigma2,Deltac,\ pow(10.,prev_log10_overdense_spline_SFR[i])-1.,Mturns[j],\ Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc, FAST_FCOLL_TABLES)); if(prev_log10_Nion_spline[i+j*NSFR_low] < -40.){ prev_log10_Nion_spline[i+j*NSFR_low] = -40.; } prev_log10_Nion_spline[i+j*NSFR_low] *= ln_10; prev_log10_Nion_spline_MINI[i+j*NSFR_low] = log10(GaussLegendreQuad_Nion_MINI(0,NGL_SFR,growthf,Mmax,sigma2,Deltac,\ pow(10.,prev_log10_overdense_spline_SFR[i])-1.,Mturns_MINI[j],Mcrit_atom,\ Alpha_star_mini,Alpha_esc,Fstar7_MINI,Fesc7_MINI,Mlim_Fstar_MINI,Mlim_Fesc_MINI, FAST_FCOLL_TABLES)); if(prev_log10_Nion_spline_MINI[i+j*NSFR_low] < -40.){ prev_log10_Nion_spline_MINI[i+j*NSFR_low] = -40.; } prev_log10_Nion_spline_MINI[i+j*NSFR_low] *= ln_10; } } } for (i=0; i<NSFR_low; i++){ for (j=0; j<NMTURN; j++){ if(isfinite(prev_log10_Nion_spline[i+j*NSFR_low])==0) { LOG_ERROR("Detected either an infinite or NaN value in prev_log10_Nion_spline"); // Throw(ParameterError); Throw(TableGenerationError); } if(isfinite(prev_log10_Nion_spline_MINI[i+j*NSFR_low])==0) { LOG_ERROR("Detected either an infinite or NaN value in prev_log10_Nion_spline_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } #pragma omp parallel shared(prev_Nion_spline,growthf,Mmin,Mmax,sigma2,prev_Overdense_spline_SFR,Mturns,\ Alpha_star,Alpha_star_mini,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc,prev_Nion_spline_MINI,Mturns_MINI,\ Mcrit_atom,Fstar7_MINI,Fesc7_MINI,Mlim_Fstar_MINI,Mlim_Fesc_MINI) \ private(i,j) num_threads(user_params_ps->N_THREADS) { #pragma omp for for(i=0;i<NSFR_high;i++) { for (j=0; j<NMTURN; j++){ prev_Nion_spline[i+j*NSFR_high] = Nion_ConditionalM(growthf,Mmin,Mmax,sigma2,Deltac,prev_Overdense_spline_SFR[i],\ Mturns[j],Alpha_star,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc, FAST_FCOLL_TABLES); if(prev_Nion_spline[i+j*NSFR_high]<0.) { prev_Nion_spline[i+j*NSFR_high]=pow(10.,-40.0); } prev_Nion_spline_MINI[i+j*NSFR_high] = Nion_ConditionalM_MINI(growthf,Mmin,Mmax,sigma2,Deltac,\ prev_Overdense_spline_SFR[i],Mturns_MINI[j],Mcrit_atom,Alpha_star_mini,\ Alpha_esc,Fstar7_MINI,Fesc7_MINI,Mlim_Fstar_MINI,Mlim_Fesc_MINI, FAST_FCOLL_TABLES); if(prev_Nion_spline_MINI[i+j*NSFR_high]<0.) { prev_Nion_spline_MINI[i+j*NSFR_high]=pow(10.,-40.0); } } } } for(i=0;i<NSFR_high;i++) { for (j=0; j<NMTURN; j++){ if(isfinite(prev_Nion_spline[i+j*NSFR_high])==0) { LOG_ERROR("Detected either an infinite or NaN value in prev_Nion_spline"); // Throw(ParameterError); Throw(TableGenerationError); } if(isfinite(prev_Nion_spline_MINI[i+j*NSFR_high])==0) { LOG_ERROR("Detected either an infinite or NaN value in prev_Nion_spline_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } } void initialise_Nion_Ts_spline( int Nbin, float zmin, float zmax, float MassTurn, float Alpha_star, float Alpha_esc, float Fstar10, float Fesc10 ){ int i; float Mmin = MassTurn/50., Mmax = global_params.M_MAX_INTEGRAL; float Mlim_Fstar, Mlim_Fesc; if (z_val == NULL){ z_val = calloc(Nbin,sizeof(double)); Nion_z_val = calloc(Nbin,sizeof(double)); } Mlim_Fstar = Mass_limit_bisection(Mmin, Mmax, Alpha_star, Fstar10); Mlim_Fesc = Mass_limit_bisection(Mmin, Mmax, Alpha_esc, Fesc10); #pragma omp parallel shared(z_val,Nion_z_val,zmin,zmax, MassTurn, Alpha_star, Alpha_esc, Fstar10, Fesc10, Mlim_Fstar, Mlim_Fesc) private(i) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<Nbin; i++){ z_val[i] = zmin + (double)i/((double)Nbin-1.)*(zmax - zmin); Nion_z_val[i] = Nion_General(z_val[i], Mmin, MassTurn, Alpha_star, Alpha_esc, Fstar10, Fesc10, Mlim_Fstar, Mlim_Fesc); } } for (i=0; i<Nbin; i++){ if(isfinite(Nion_z_val[i])==0) { LOG_ERROR("Detected either an infinite or NaN value in Nion_z_val"); // Throw(ParameterError); Throw(TableGenerationError); } } } void initialise_Nion_Ts_spline_MINI( int Nbin, float zmin, float zmax, float Alpha_star, float Alpha_star_mini, float Alpha_esc, float Fstar10, float Fesc10, float Fstar7_MINI, float Fesc7_MINI ){ int i,j; float Mmin = global_params.M_MIN_INTEGRAL, Mmax = global_params.M_MAX_INTEGRAL; float Mlim_Fstar, Mlim_Fesc, Mlim_Fstar_MINI, Mlim_Fesc_MINI, Mcrit_atom_val; if (z_val == NULL){ z_val = calloc(Nbin,sizeof(double)); Nion_z_val = calloc(Nbin,sizeof(double)); Nion_z_val_MINI = calloc(Nbin*NMTURN,sizeof(double)); } Mlim_Fstar = Mass_limit_bisection(Mmin, Mmax, Alpha_star, Fstar10); Mlim_Fesc = Mass_limit_bisection(Mmin, Mmax, Alpha_esc, Fesc10); Mlim_Fstar_MINI = Mass_limit_bisection(Mmin, Mmax, Alpha_star_mini, Fstar7_MINI * pow(1e3, Alpha_star_mini)); Mlim_Fesc_MINI = Mass_limit_bisection(Mmin, Mmax, Alpha_esc, Fesc7_MINI * pow(1e3, Alpha_esc)); float MassTurnover[NMTURN]; for (i=0;i<NMTURN;i++){ MassTurnover[i] = pow(10., LOG10_MTURN_MIN + (float)i/((float)NMTURN-1.)*(LOG10_MTURN_MAX-LOG10_MTURN_MIN)); } #pragma omp parallel shared(z_val,Nion_z_val,Nbin,zmin,zmax,Mmin,Alpha_star,Alpha_star_mini,Alpha_esc,Fstar10,Fesc10,Mlim_Fstar,Mlim_Fesc,\ Nion_z_val_MINI,MassTurnover,Fstar7_MINI, Fesc7_MINI, Mlim_Fstar_MINI, Mlim_Fesc_MINI) \ private(i,j,Mcrit_atom_val) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<Nbin; i++){ z_val[i] = zmin + (double)i/((double)Nbin-1.)*(zmax - zmin); Mcrit_atom_val = atomic_cooling_threshold(z_val[i]); Nion_z_val[i] = Nion_General(z_val[i], Mmin, Mcrit_atom_val, Alpha_star, Alpha_esc, Fstar10, Fesc10, Mlim_Fstar, Mlim_Fesc); for (j=0; j<NMTURN; j++){ Nion_z_val_MINI[i+j*Nbin] = Nion_General_MINI(z_val[i], Mmin, MassTurnover[j], Mcrit_atom_val, Alpha_star_mini, Alpha_esc, Fstar7_MINI, Fesc7_MINI, Mlim_Fstar_MINI, Mlim_Fesc_MINI); } } } for (i=0; i<Nbin; i++){ if(isfinite(Nion_z_val[i])==0) { i = Nbin; LOG_ERROR("Detected either an infinite or NaN value in Nion_z_val"); // Throw(ParameterError); Throw(TableGenerationError); } for (j=0; j<NMTURN; j++){ if(isfinite(Nion_z_val_MINI[i+j*Nbin])==0){ j = NMTURN; LOG_ERROR("Detected either an infinite or NaN value in Nion_z_val_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } } void initialise_SFRD_spline(int Nbin, float zmin, float zmax, float MassTurn, float Alpha_star, float Fstar10){ int i; float Mmin = MassTurn/50., Mmax = global_params.M_MAX_INTEGRAL; float Mlim_Fstar; if (z_X_val == NULL){ z_X_val = calloc(Nbin,sizeof(double)); SFRD_val = calloc(Nbin,sizeof(double)); } Mlim_Fstar = Mass_limit_bisection(Mmin, Mmax, Alpha_star, Fstar10); #pragma omp parallel shared(z_X_val,SFRD_val,zmin,zmax, MassTurn, Alpha_star, Fstar10, Mlim_Fstar) private(i) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<Nbin; i++){ z_X_val[i] = zmin + (double)i/((double)Nbin-1.)*(zmax - zmin); SFRD_val[i] = Nion_General(z_X_val[i], Mmin, MassTurn, Alpha_star, 0., Fstar10, 1.,Mlim_Fstar,0.); } } for (i=0; i<Nbin; i++){ if(isfinite(SFRD_val[i])==0) { LOG_ERROR("Detected either an infinite or NaN value in SFRD_val"); // Throw(ParameterError); Throw(TableGenerationError); } } } void initialise_SFRD_spline_MINI(int Nbin, float zmin, float zmax, float Alpha_star, float Alpha_star_mini, float Fstar10, float Fstar7_MINI){ int i,j; float Mmin = global_params.M_MIN_INTEGRAL, Mmax = global_params.M_MAX_INTEGRAL; float Mlim_Fstar, Mlim_Fstar_MINI, Mcrit_atom_val; if (z_X_val == NULL){ z_X_val = calloc(Nbin,sizeof(double)); SFRD_val = calloc(Nbin,sizeof(double)); SFRD_val_MINI = calloc(Nbin*NMTURN,sizeof(double)); } Mlim_Fstar = Mass_limit_bisection(Mmin, Mmax, Alpha_star, Fstar10); Mlim_Fstar_MINI = Mass_limit_bisection(Mmin, Mmax, Alpha_star_mini, Fstar7_MINI * pow(1e3, Alpha_star_mini)); float MassTurnover[NMTURN]; for (i=0;i<NMTURN;i++){ MassTurnover[i] = pow(10., LOG10_MTURN_MIN + (float)i/((float)NMTURN-1.)*(LOG10_MTURN_MAX-LOG10_MTURN_MIN)); } #pragma omp parallel shared(z_X_val,zmin,zmax,Nbin,SFRD_val,Mmin, Alpha_star,Alpha_star_mini,Fstar10,Mlim_Fstar,\ SFRD_val_MINI,MassTurnover,Fstar7_MINI,Mlim_Fstar_MINI) \ private(i,j,Mcrit_atom_val) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<Nbin; i++){ z_X_val[i] = zmin + (double)i/((double)Nbin-1.)*(zmax - zmin); Mcrit_atom_val = atomic_cooling_threshold(z_X_val[i]); SFRD_val[i] = Nion_General(z_X_val[i], Mmin, Mcrit_atom_val, Alpha_star, 0., Fstar10, 1.,Mlim_Fstar,0.); for (j=0; j<NMTURN; j++){ SFRD_val_MINI[i+j*Nbin] = Nion_General_MINI(z_X_val[i], Mmin, MassTurnover[j], Mcrit_atom_val, Alpha_star_mini, 0., Fstar7_MINI, 1.,Mlim_Fstar_MINI,0.); } } } for (i=0; i<Nbin; i++){ if(isfinite(SFRD_val[i])==0) { i = Nbin; LOG_ERROR("Detected either an infinite or NaN value in SFRD_val"); // Throw(ParameterError); Throw(TableGenerationError); } for (j=0; j<NMTURN; j++){ if(isfinite(SFRD_val_MINI[i+j*Nbin])==0) { j = NMTURN; LOG_ERROR("Detected either an infinite or NaN value in SFRD_val_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } } void initialise_SFRD_Conditional_table( int Nfilter, float min_density[], float max_density[], float growthf[], float R[], float MassTurnover, float Alpha_star, float Fstar10, bool FAST_FCOLL_TABLES ){ double overdense_val; double overdense_large_high = Deltac, overdense_large_low = global_params.CRIT_DENS_TRANSITION; double overdense_small_high, overdense_small_low; float Mmin,Mmax,Mlim_Fstar,sigma2; int i,j,k,i_tot; float ln_10; ln_10 = log(10); Mmin = MassTurnover/50.; Mmax = RtoM(R[Nfilter-1]); Mlim_Fstar = Mass_limit_bisection(Mmin, Mmax, Alpha_star, Fstar10); Mmin = log(Mmin); for (i=0; i<NSFR_high;i++) { overdense_high_table[i] = overdense_large_low + (float)i/((float)NSFR_high-1.)*(overdense_large_high - overdense_large_low); } float MassBinLow; int MassBin; for (j=0; j < Nfilter; j++) { Mmax = RtoM(R[j]); initialiseGL_Nion_Xray(NGL_SFR, MassTurnover/50., Mmax); Mmax = log(Mmax); MassBin = (int)floor( ( Mmax - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma2 = Sigma_InterpTable[MassBin] + ( Mmax - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; if(min_density[j]*growthf[j] < -1.) { overdense_small_low = -1. + global_params.MIN_DENSITY_LOW_LIMIT; } else { overdense_small_low = min_density[j]*growthf[j]; } overdense_small_high = max_density[j]*growthf[j]; if(overdense_small_high > global_params.CRIT_DENS_TRANSITION) { overdense_small_high = global_params.CRIT_DENS_TRANSITION; } for (i=0; i<NSFR_low; i++) { overdense_val = log10(1. + overdense_small_low) + (float)i/((float)NSFR_low-1.)*(log10(1.+overdense_small_high)-log10(1.+overdense_small_low)); overdense_low_table[i] = pow(10.,overdense_val); } #pragma omp parallel shared(log10_SFRD_z_low_table,growthf,Mmax,sigma2,overdense_low_table,MassTurnover,Alpha_star,Fstar10,Mlim_Fstar) private(i) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<NSFR_low; i++){ log10_SFRD_z_low_table[j][i] = GaussLegendreQuad_Nion(1,NGL_SFR,growthf[j],Mmax,sigma2,Deltac,overdense_low_table[i]-1.,MassTurnover,Alpha_star,0.,Fstar10,1.,Mlim_Fstar,0., FAST_FCOLL_TABLES); if(fabs(log10_SFRD_z_low_table[j][i]) < 1e-38) { log10_SFRD_z_low_table[j][i] = 1e-38; } log10_SFRD_z_low_table[j][i] = log10(log10_SFRD_z_low_table[j][i]); log10_SFRD_z_low_table[j][i] += 10.0; log10_SFRD_z_low_table[j][i] *= ln_10; } } for (i=0; i<NSFR_low; i++){ if(isfinite(log10_SFRD_z_low_table[j][i])==0) { LOG_ERROR("Detected either an infinite or NaN value in log10_SFRD_z_low_table"); // Throw(ParameterError); Throw(TableGenerationError); } } #pragma omp parallel shared(SFRD_z_high_table,growthf,Mmin,Mmax,sigma2,overdense_high_table,MassTurnover,Alpha_star,Fstar10,Mlim_Fstar) private(i) num_threads(user_params_ps->N_THREADS) { #pragma omp for for(i=0;i<NSFR_high;i++) { SFRD_z_high_table[j][i] = Nion_ConditionalM(growthf[j],Mmin,Mmax,sigma2,Deltac,overdense_high_table[i],MassTurnover,Alpha_star,0.,Fstar10,1.,Mlim_Fstar,0., FAST_FCOLL_TABLES); SFRD_z_high_table[j][i] *= pow(10., 10.0); } } for(i=0;i<NSFR_high;i++) { if(isfinite(SFRD_z_high_table[j][i])==0) { LOG_ERROR("Detected either an infinite or NaN value in SFRD_z_high_table"); // Throw(ParameterError); Throw(TableGenerationError); } } } } void initialise_SFRD_Conditional_table_MINI( int Nfilter, float min_density[], float max_density[], float growthf[], float R[], float Mcrit_atom[], float Alpha_star, float Alpha_star_mini, float Fstar10, float Fstar7_MINI, bool FAST_FCOLL_TABLES ){ double overdense_val; double overdense_large_high = Deltac, overdense_large_low = global_params.CRIT_DENS_TRANSITION; double overdense_small_high, overdense_small_low; float Mmin,Mmax,Mlim_Fstar,sigma2,Mlim_Fstar_MINI; int i,j,k,i_tot; float ln_10; ln_10 = log(10); Mmin = global_params.M_MIN_INTEGRAL; Mmax = RtoM(R[Nfilter-1]); Mlim_Fstar = Mass_limit_bisection(Mmin, Mmax, Alpha_star, Fstar10); Mlim_Fstar_MINI = Mass_limit_bisection(Mmin, Mmax, Alpha_star_mini, Fstar7_MINI * pow(1e3, Alpha_star_mini)); float MassTurnover[NMTURN]; for (i=0;i<NMTURN;i++){ MassTurnover[i] = pow(10., LOG10_MTURN_MIN + (float)i/((float)NMTURN-1.)*(LOG10_MTURN_MAX-LOG10_MTURN_MIN)); } Mmin = log(Mmin); for (i=0; i<NSFR_high;i++) { overdense_high_table[i] = overdense_large_low + (float)i/((float)NSFR_high-1.)*(overdense_large_high - overdense_large_low); } float MassBinLow; int MassBin; for (j=0; j < Nfilter; j++) { Mmax = RtoM(R[j]); initialiseGL_Nion_Xray(NGL_SFR, global_params.M_MIN_INTEGRAL, Mmax); Mmax = log(Mmax); MassBin = (int)floor( ( Mmax - MinMass )*inv_mass_bin_width ); MassBinLow = MinMass + mass_bin_width*(float)MassBin; sigma2 = Sigma_InterpTable[MassBin] + ( Mmax - MassBinLow )*( Sigma_InterpTable[MassBin+1] - Sigma_InterpTable[MassBin] )*inv_mass_bin_width; if(min_density[j]*growthf[j] < -1.) { overdense_small_low = -1. + global_params.MIN_DENSITY_LOW_LIMIT; } else { overdense_small_low = min_density[j]*growthf[j]; } overdense_small_high = max_density[j]*growthf[j]; if(overdense_small_high > global_params.CRIT_DENS_TRANSITION) { overdense_small_high = global_params.CRIT_DENS_TRANSITION; } for (i=0; i<NSFR_low; i++) { overdense_val = log10(1. + overdense_small_low) + (float)i/((float)NSFR_low-1.)*(log10(1.+overdense_small_high)-log10(1.+overdense_small_low)); overdense_low_table[i] = pow(10.,overdense_val); } #pragma omp parallel shared(log10_SFRD_z_low_table,growthf,Mmax,sigma2,overdense_low_table,Mcrit_atom,Alpha_star,Alpha_star_mini,Fstar10,Mlim_Fstar,\ log10_SFRD_z_low_table_MINI,MassTurnover,Fstar7_MINI,Mlim_Fstar_MINI,ln_10) \ private(i,k) num_threads(user_params_ps->N_THREADS) { #pragma omp for for (i=0; i<NSFR_low; i++){ log10_SFRD_z_low_table[j][i] = log10(GaussLegendreQuad_Nion(1,NGL_SFR,growthf[j],Mmax,sigma2,Deltac,overdense_low_table[i]-1.,Mcrit_atom[j],Alpha_star,0.,Fstar10,1.,Mlim_Fstar,0., FAST_FCOLL_TABLES)); if(log10_SFRD_z_low_table[j][i] < -50.){ log10_SFRD_z_low_table[j][i] = -50.; } log10_SFRD_z_low_table[j][i] += 10.0; log10_SFRD_z_low_table[j][i] *= ln_10; for (k=0; k<NMTURN; k++){ log10_SFRD_z_low_table_MINI[j][i+k*NSFR_low] = log10(GaussLegendreQuad_Nion_MINI(1,NGL_SFR,growthf[j],Mmax,sigma2,Deltac,overdense_low_table[i]-1.,MassTurnover[k], Mcrit_atom[j],Alpha_star_mini,0.,Fstar7_MINI,1.,Mlim_Fstar_MINI, 0., FAST_FCOLL_TABLES)); if(log10_SFRD_z_low_table_MINI[j][i+k*NSFR_low] < -50.){ log10_SFRD_z_low_table_MINI[j][i+k*NSFR_low] = -50.; } log10_SFRD_z_low_table_MINI[j][i+k*NSFR_low] += 10.0; log10_SFRD_z_low_table_MINI[j][i+k*NSFR_low] *= ln_10; } } } for (i=0; i<NSFR_low; i++){ if(isfinite(log10_SFRD_z_low_table[j][i])==0) { LOG_ERROR("Detected either an infinite or NaN value in log10_SFRD_z_low_table"); // Throw(ParameterError); Throw(TableGenerationError); } for (k=0; k<NMTURN; k++){ if(isfinite(log10_SFRD_z_low_table_MINI[j][i+k*NSFR_low])==0) { LOG_ERROR("Detected either an infinite or NaN value in log10_SFRD_z_low_table_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } #pragma omp parallel shared(SFRD_z_high_table,growthf,Mmin,Mmax,sigma2,overdense_high_table,Mcrit_atom,Alpha_star,Alpha_star_mini,Fstar10,\ Mlim_Fstar,SFRD_z_high_table_MINI,MassTurnover,Fstar7_MINI,Mlim_Fstar_MINI) \ private(i,k) num_threads(user_params_ps->N_THREADS) { #pragma omp for for(i=0;i<NSFR_high;i++) { SFRD_z_high_table[j][i] = Nion_ConditionalM(growthf[j],Mmin,Mmax,sigma2,Deltac,overdense_high_table[i],\ Mcrit_atom[j],Alpha_star,0.,Fstar10,1.,Mlim_Fstar,0., FAST_FCOLL_TABLES); if (SFRD_z_high_table[j][i] < 1e-50){ SFRD_z_high_table[j][i] = 1e-50; } SFRD_z_high_table[j][i] *= pow(10., 10.0); for (k=0; k<NMTURN; k++){ SFRD_z_high_table_MINI[j][i+k*NSFR_high] = Nion_ConditionalM_MINI(growthf[j],Mmin,Mmax,sigma2,Deltac,\ overdense_high_table[i],MassTurnover[k],Mcrit_atom[j],\ Alpha_star_mini,0.,Fstar7_MINI,1.,Mlim_Fstar_MINI, 0., FAST_FCOLL_TABLES); if (SFRD_z_high_table_MINI[j][i+k*NSFR_high] < 1e-50){ SFRD_z_high_table_MINI[j][i+k*NSFR_high] = 1e-50; } } } } for(i=0;i<NSFR_high;i++) { if(isfinite(SFRD_z_high_table[j][i])==0) { LOG_ERROR("Detected either an infinite or NaN value in SFRD_z_high_table"); // Throw(ParameterError); Throw(TableGenerationError); } for (k=0; k<NMTURN; k++){ if(isfinite(SFRD_z_high_table_MINI[j][i+k*NSFR_high])==0) { LOG_ERROR("Detected either an infinite or NaN value in SFRD_z_high_table_MINI"); // Throw(ParameterError); Throw(TableGenerationError); } } } } } // The volume filling factor at a given redshift, Q(z), or find redshift at a given Q, z(Q). // // The evolution of Q can be written as // dQ/dt = n_{ion}/dt - Q/t_{rec}, // where n_{ion} is the number of ionizing photons per baryon. The averaged recombination time is given by // t_{rec} ~ 0.93 Gyr * (C_{HII}/3)^-1 * (T_0/2e4 K)^0.7 * ((1+z)/7)^-3. // We assume the clumping factor of C_{HII}=3 and the IGM temperature of T_0 = 2e4 K, following // Section 2.1 of Kuhlen & Faucher-Gigue`re (2012) MNRAS, 423, 862 and references therein. // 1) initialise interpolation table // -> initialise_Q_value_spline(NoRec, M_TURN, ALPHA_STAR, ALPHA_ESC, F_STAR10, F_ESC10) // NoRec = 0: Compute dQ/dt with the recombination time. // NoRec = 1: Ignore recombination. // 2) find Q value at a given z -> Q_at_z(z, &(Q)) // or find z at a given Q -> z_at_Q(Q, &(z)). // 3) free memory allocation -> free_Q_value() // Set up interpolation table for the volume filling factor, Q, at a given redshift z and redshift at a given Q. int InitialisePhotonCons(struct UserParams *user_params, struct CosmoParams *cosmo_params, struct AstroParams *astro_params, struct FlagOptions *flag_options) { /* This is an API-level function for initialising the photon conservation. */ int status; Try{ // this try wraps the whole function. Broadcast_struct_global_PS(user_params,cosmo_params); Broadcast_struct_global_UF(user_params,cosmo_params); init_ps(); // To solve differentail equation, uses Euler's method. // NOTE: // (1) With the fiducial parameter set, // when the Q value is < 0.9, the difference is less than 5% compared with accurate calculation. // When Q ~ 0.98, the difference is ~25%. To increase accuracy one can reduce the step size 'da', but it will increase computing time. // (2) With the fiducial parameter set, // the difference for the redshift where the reionization end (Q = 1) is ~0.2 % compared with accurate calculation. float ION_EFF_FACTOR,M_MIN,M_MIN_z0,M_MIN_z1,Mlim_Fstar, Mlim_Fesc; double a_start = 0.03, a_end = 1./(1. + global_params.PhotonConsEndCalibz); // Scale factors of 0.03 and 0.17 correspond to redshifts of ~32 and ~5.0, respectively. double C_HII = 3., T_0 = 2e4; double reduce_ratio = 1.003; double Q0,Q1,Nion0,Nion1,Trec,da,a,z0,z1,zi,dadt,ans,delta_a,zi_prev,Q1_prev; double *z_arr,*Q_arr; int Nmax = 2000; // This is the number of step, enough with 'da = 2e-3'. If 'da' is reduced, this number should be checked. int cnt, nbin, i, istart; int fail_condition, not_mono_increasing, num_fails; int gsl_status; z_arr = calloc(Nmax,sizeof(double)); Q_arr = calloc(Nmax,sizeof(double)); //set the minimum source mass if (flag_options->USE_MASS_DEPENDENT_ZETA) { ION_EFF_FACTOR = global_params.Pop2_ion * astro_params->F_STAR10 * astro_params->F_ESC10; M_MIN = astro_params->M_TURN/50.; Mlim_Fstar = Mass_limit_bisection(M_MIN, global_params.M_MAX_INTEGRAL, astro_params->ALPHA_STAR, astro_params->F_STAR10); Mlim_Fesc = Mass_limit_bisection(M_MIN, global_params.M_MAX_INTEGRAL, astro_params->ALPHA_ESC, astro_params->F_ESC10); if(user_params->FAST_FCOLL_TABLES){ initialiseSigmaMInterpTable(fmin(MMIN_FAST,M_MIN),1e20); } else{ initialiseSigmaMInterpTable(M_MIN,1e20); } } else { ION_EFF_FACTOR = astro_params->HII_EFF_FACTOR; } fail_condition = 1; num_fails = 0; // We are going to come up with the analytic curve for the photon non conservation correction // This can be somewhat numerically unstable and as such we increase the sampling until it works // If it fails to produce a monotonically increasing curve (for Q as a function of z) after 10 attempts we crash out while(fail_condition!=0) { a = a_start; if(num_fails < 3) { da = 3e-3 - ((double)num_fails)*(1e-3); } else { da = 1e-3 - ((double)num_fails - 2.)*(1e-4); } delta_a = 1e-7; zi_prev = Q1_prev = 0.; not_mono_increasing = 0; if(num_fails>0) { for(i=0;i<Nmax;i++) { z_arr[i] = 0.; Q_arr[i] = 0.; } } cnt = 0; Q0 = 0.; while (a < a_end) { zi = 1./a - 1.; z0 = 1./(a+delta_a) - 1.; z1 = 1./(a-delta_a) - 1.; // Ionizing emissivity (num of photons per baryon) if (flag_options->USE_MASS_DEPENDENT_ZETA) { Nion0 = ION_EFF_FACTOR*Nion_General(z0, astro_params->M_TURN/50., astro_params->M_TURN, astro_params->ALPHA_STAR, astro_params->ALPHA_ESC, astro_params->F_STAR10, astro_params->F_ESC10, Mlim_Fstar, Mlim_Fesc); Nion1 = ION_EFF_FACTOR*Nion_General(z1, astro_params->M_TURN/50., astro_params->M_TURN, astro_params->ALPHA_STAR, astro_params->ALPHA_ESC, astro_params->F_STAR10, astro_params->F_ESC10, Mlim_Fstar, Mlim_Fesc); } else { //set the minimum source mass if (astro_params->ION_Tvir_MIN < 9.99999e3) { // neutral IGM M_MIN_z0 = (float)TtoM(z0, astro_params->ION_Tvir_MIN, 1.22); M_MIN_z1 = (float)TtoM(z1, astro_params->ION_Tvir_MIN, 1.22); } else { // ionized IGM M_MIN_z0 = (float)TtoM(z0, astro_params->ION_Tvir_MIN, 0.6); M_MIN_z1 = (float)TtoM(z1, astro_params->ION_Tvir_MIN, 0.6); } if(M_MIN_z0 < M_MIN_z1) { if(user_params->FAST_FCOLL_TABLES){ initialiseSigmaMInterpTable(fmin(MMIN_FAST,M_MIN_z0),1e20); } else{ initialiseSigmaMInterpTable(M_MIN_z0,1e20); } } else { if(user_params->FAST_FCOLL_TABLES){ initialiseSigmaMInterpTable(fmin(MMIN_FAST,M_MIN_z1),1e20); } else{ initialiseSigmaMInterpTable(M_MIN_z1,1e20); } } Nion0 = ION_EFF_FACTOR*FgtrM_General(z0,M_MIN_z0); Nion1 = ION_EFF_FACTOR*FgtrM_General(z1,M_MIN_z1); freeSigmaMInterpTable(); } // With scale factor a, the above equation is written as dQ/da = n_{ion}/da - Q/t_{rec}*(dt/da) if (!global_params.RecombPhotonCons) { Q1 = Q0 + ((Nion0-Nion1)/2/delta_a)*da; // No Recombination } else { dadt = Ho*sqrt(cosmo_params_ps->OMm/a + global_params.OMr/a/a + cosmo_params_ps->OMl*a*a); // da/dt = Ho*a*sqrt(OMm/a^3 + OMr/a^4 + OMl) Trec = 0.93 * 1e9 * SperYR * pow(C_HII/3.,-1) * pow(T_0/2e4,0.7) * pow((1.+zi)/7.,-3); Q1 = Q0 + ((Nion0-Nion1)/2./delta_a - Q0/Trec/dadt)*da; } // Curve is no longer monotonically increasing, we are going to have to exit and start again if(Q1 < Q1_prev) { not_mono_increasing = 1; break; } zi_prev = zi; Q1_prev = Q1; z_arr[cnt] = zi; Q_arr[cnt] = Q1; cnt = cnt + 1; if (Q1 >= 1.0) break; // if fully ionized, stop here. // As the Q value increases, the bin size decreases gradually because more accurate calculation is required. if (da < 7e-5) da = 7e-5; // set minimum bin size. else da = pow(da,reduce_ratio); Q0 = Q1; a = a + da; } // A check to see if we ended up with a monotonically increasing function if(not_mono_increasing==0) { fail_condition = 0; } else { num_fails += 1; if(num_fails>10) { LOG_ERROR("Failed too many times."); // Throw ParameterError; Throw(PhotonConsError); } } } cnt = cnt - 1; istart = 0; for (i=1;i<cnt;i++){ if (Q_arr[i-1] == 0. && Q_arr[i] != 0.) istart = i-1; } nbin = cnt - istart; N_analytic = nbin; // initialise interploation Q as a function of z z_Q = calloc(nbin,sizeof(double)); Q_value = calloc(nbin,sizeof(double)); Q_at_z_spline_acc = gsl_interp_accel_alloc (); Q_at_z_spline = gsl_spline_alloc (gsl_interp_cspline, nbin); for (i=0; i<nbin; i++){ z_Q[i] = z_arr[cnt-i]; Q_value[i] = Q_arr[cnt-i]; } gsl_set_error_handler_off(); gsl_status = gsl_spline_init(Q_at_z_spline, z_Q, Q_value, nbin); GSL_ERROR(gsl_status); Zmin = z_Q[0]; Zmax = z_Q[nbin-1]; Qmin = Q_value[nbin-1]; Qmax = Q_value[0]; // initialise interpolation z as a function of Q double *Q_z = calloc(nbin,sizeof(double)); double *z_value = calloc(nbin,sizeof(double)); z_at_Q_spline_acc = gsl_interp_accel_alloc (); z_at_Q_spline = gsl_spline_alloc (gsl_interp_linear, nbin); for (i=0; i<nbin; i++){ Q_z[i] = Q_value[nbin-1-i]; z_value[i] = z_Q[nbin-1-i]; } gsl_status = gsl_spline_init(z_at_Q_spline, Q_z, z_value, nbin); GSL_ERROR(gsl_status); free(z_arr); free(Q_arr); if (flag_options->USE_MASS_DEPENDENT_ZETA) { freeSigmaMInterpTable; } LOG_DEBUG("Initialised PhotonCons."); } // End of try Catch(status){ return status; } return(0); } // Function to construct the spline for the calibration curve of the photon non-conservation int PhotonCons_Calibration(double *z_estimate, double *xH_estimate, int NSpline){ int status; Try{ if(xH_estimate[NSpline-1] > 0.0 && xH_estimate[NSpline-2] > 0.0 && xH_estimate[NSpline-3] > 0.0 && xH_estimate[0] <= global_params.PhotonConsStart) { initialise_NFHistory_spline(z_estimate,xH_estimate,NSpline); } } Catch(status){ return status; } return(0); } // Function callable from Python to know at which redshift to start sampling the calibration curve (to minimise function calls) int ComputeZstart_PhotonCons(double *zstart) { int status; double temp; Try{ if((1.-global_params.PhotonConsStart) > Qmax) { // It is possible that reionisation never even starts // Just need to arbitrarily set a high redshift to perform the algorithm temp = 20.; } else { z_at_Q(1. - global_params.PhotonConsStart,&(temp)); // Multiply the result by 10 per-cent to fix instances when this isn't high enough temp *= 1.1; } } Catch(status){ return(status); // Use the status to determine if something went wrong. } *zstart = temp; return(0); } void determine_deltaz_for_photoncons() { int i, j, increasing_val, counter, smoothing_int; double temp; float z_cal, z_analytic, NF_sample, returned_value, NF_sample_min, gradient_analytic, z_analytic_at_endpoint, const_offset, z_analytic_2, smoothing_width; float bin_width, delta_NF, val1, val2, extrapolated_value; LOG_DEBUG("Determining deltaz for photon cons."); // Number of points for determine the delta z correction of the photon non-conservation N_NFsamples = 100; // Determine the change in neutral fraction to calculate the gradient for the linear extrapolation of the photon non-conservation correction delta_NF = 0.025; // A width (in neutral fraction data points) in which point we average over to try and avoid sharp features in the correction (removes some kinks) // Effectively acts as filtering step smoothing_width = 35.; // The photon non-conservation correction has a threshold (in terms of neutral fraction; global_params.PhotonConsEnd) for which we switch // from using the exact correction between the calibrated (21cmFAST all flag options off) to analytic expression to some extrapolation. // This threshold is required due to the behaviour of 21cmFAST at very low neutral fractions, which cause extreme behaviour with recombinations on // A lot of the steps and choices are not completely rubust, just chosed to smooth/average the data to have smoother resultant reionisation histories // Determine the number of extrapolated points required, if required at all. if(calibrated_NF_min < global_params.PhotonConsEnd) { // We require extrapolation, set minimum point to the threshold, and extrapolate beyond. NF_sample_min = global_params.PhotonConsEnd; // Determine the number of extrapolation points (to better smooth the correction) between the threshod (global_params.PhotonConsEnd) and a // point close to zero neutral fraction (set by global_params.PhotonConsAsymptoteTo) // Choice is to get the delta neutral fraction between extrapolated points to be similar to the cadence in the exact correction if(calibrated_NF_min > global_params.PhotonConsAsymptoteTo) { N_extrapolated = ((float)N_NFsamples - 1.)*(NF_sample_min - calibrated_NF_min)/( global_params.PhotonConsStart - NF_sample_min ); } else { N_extrapolated = ((float)N_NFsamples - 1.)*(NF_sample_min - global_params.PhotonConsAsymptoteTo)/( global_params.PhotonConsStart - NF_sample_min ); } N_extrapolated = (int)floor( N_extrapolated ) - 1; // Minus one as the zero point is added below } else { // No extrapolation required, neutral fraction never reaches zero NF_sample_min = calibrated_NF_min; N_extrapolated = 0; } // Determine the bin width for the sampling of the neutral fraction for the correction bin_width = ( global_params.PhotonConsStart - NF_sample_min )/((float)N_NFsamples - 1.); // allocate memory for arrays required to determine the photon non-conservation correction deltaz = calloc(N_NFsamples + N_extrapolated + 1,sizeof(double)); deltaz_smoothed = calloc(N_NFsamples + N_extrapolated + 1,sizeof(double)); NeutralFractions = calloc(N_NFsamples + N_extrapolated + 1,sizeof(double)); // Go through and fill the data points (neutral fraction and corresponding delta z between the calibrated and analytic curves). for(i=0;i<N_NFsamples;i++) { NF_sample = NF_sample_min + bin_width*(float)i; // Determine redshift given a neutral fraction for the calibration curve z_at_NFHist(NF_sample,&(temp)); z_cal = temp; // Determine redshift given a neutral fraction for the analytic curve z_at_Q(1. - NF_sample,&(temp)); z_analytic = temp; deltaz[i+1+N_extrapolated] = fabs( z_cal - z_analytic ); NeutralFractions[i+1+N_extrapolated] = NF_sample; } // Determining the end-point (lowest neutral fraction) for the photon non-conservation correction if(calibrated_NF_min >= global_params.PhotonConsEnd) { increasing_val = 0; counter = 0; // Check if all the values of delta z are increasing for(i=0;i<(N_NFsamples-1);i++) { if(deltaz[i+1+N_extrapolated] >= deltaz[i+N_extrapolated]) { counter += 1; } } // If all the values of delta z are increasing, then some of the smoothing of the correction done below cannot be performed if(counter==(N_NFsamples-1)) { increasing_val = 1; } // Since we never have reionisation, need to set an appropriate end-point for the correction // Take some fraction of the previous point to determine the end-point NeutralFractions[0] = 0.999*NF_sample_min; if(increasing_val) { // Values of delta z are always increasing with decreasing neutral fraction thus make the last point slightly larger deltaz[0] = 1.001*deltaz[1]; } else { // Values of delta z are always decreasing with decreasing neutral fraction thus make the last point slightly smaller deltaz[0] = 0.999*deltaz[1]; } } else { // Ok, we are going to be extrapolating the photon non-conservation (delta z) beyond the threshold // Construct a linear curve for the analytic function to extrapolate to the new endpoint // The choice for doing so is to ensure the corrected reionisation history is mostly smooth, and doesn't // artificially result in kinks due to switching between how the delta z should be calculated z_at_Q(1. - (NeutralFractions[1+N_extrapolated] + delta_NF),&(temp)); z_analytic = temp; z_at_Q(1. - NeutralFractions[1+N_extrapolated],&(temp)); z_analytic_2 = temp; // determine the linear curve // Multiplitcation by 1.1 is arbitrary but effectively smooths out most kinks observed in the resultant corrected reionisation histories gradient_analytic = 1.1*( delta_NF )/( z_analytic - z_analytic_2 ); const_offset = ( NeutralFractions[1+N_extrapolated] + delta_NF ) - gradient_analytic * z_analytic; // determine the extrapolation end point if(calibrated_NF_min > global_params.PhotonConsAsymptoteTo) { extrapolated_value = calibrated_NF_min; } else { extrapolated_value = global_params.PhotonConsAsymptoteTo; } // calculate the delta z for the extrapolated end point z_at_NFHist(extrapolated_value,&(temp)); z_cal = temp; z_analytic_at_endpoint = ( extrapolated_value - const_offset )/gradient_analytic ; deltaz[0] = fabs( z_cal - z_analytic_at_endpoint ); NeutralFractions[0] = extrapolated_value; // If performing extrapolation, add in all the extrapolated points between the end-point and the threshold to end the correction (global_params.PhotonConsEnd) for(i=0;i<N_extrapolated;i++) { if(calibrated_NF_min > global_params.PhotonConsAsymptoteTo) { NeutralFractions[i+1] = calibrated_NF_min + (NF_sample_min - calibrated_NF_min)*(float)(i+1)/((float)N_extrapolated + 1.); } else { NeutralFractions[i+1] = global_params.PhotonConsAsymptoteTo + (NF_sample_min - global_params.PhotonConsAsymptoteTo)*(float)(i+1)/((float)N_extrapolated + 1.); } deltaz[i+1] = deltaz[0] + ( deltaz[1+N_extrapolated] - deltaz[0] )*(float)(i+1)/((float)N_extrapolated + 1.); } } // We have added the extrapolated values, now check if they are all increasing or not (again, to determine whether or not to try and smooth the corrected curve increasing_val = 0; counter = 0; for(i=0;i<(N_NFsamples-1);i++) { if(deltaz[i+1+N_extrapolated] >= deltaz[i+N_extrapolated]) { counter += 1; } } if(counter==(N_NFsamples-1)) { increasing_val = 1; } // For some models, the resultant delta z for extremely high neutral fractions ( > 0.95) seem to oscillate or sometimes drop in value. // This goes through and checks if this occurs, and tries to smooth this out // This doesn't occur very often, but can cause an artificial drop in the reionisation history (neutral fraction value) connecting the // values before/after the photon non-conservation correction starts. for(i=0;i<(N_NFsamples+N_extrapolated);i++) { val1 = deltaz[i]; val2 = deltaz[i+1]; counter = 0; // Check if we have a neutral fraction above 0.95, that the values are decreasing (val2 < val1), that we haven't sampled too many points (counter) // and that the NF_sample_min is less than around 0.8. That is, if a reasonable fraction of the reionisation history is sampled. while( NeutralFractions[i+1] > 0.95 && val2 < val1 && NF_sample_min < 0.8 && counter < 100) { NF_sample = global_params.PhotonConsStart - 0.001*(counter+1); // Determine redshift given a neutral fraction for the calibration curve z_at_NFHist(NF_sample,&(temp)); z_cal = temp; // Determine redshift given a neutral fraction for the analytic curve z_at_Q(1. - NF_sample,&(temp)); z_analytic = temp; // Determine the delta z val2 = fabs( z_cal - z_analytic ); deltaz[i+1] = val2; counter += 1; // If after 100 samplings we couldn't get the value to increase (like it should), just modify it from the previous point. if(counter==100) { deltaz[i+1] = deltaz[i] * 1.01; } } } // Store the data in its intermediate state before averaging for(i=0;i<(N_NFsamples+N_extrapolated+1);i++) { deltaz_smoothed[i] = deltaz[i]; } // If we are not increasing for all values, we can smooth out some features in delta z when connecting the extrapolated delta z values // compared to those from the exact correction (i.e. when we cross the threshold). if(!increasing_val) { for(i=0;i<(N_NFsamples+N_extrapolated);i++) { val1 = deltaz[0]; val2 = deltaz[i+1]; counter = 0; // Try and find a point which can be used to smooth out any dip in delta z as a function of neutral fraction. // It can be flat, then drop, then increase. This smooths over this drop (removes a kink in the resultant reionisation history). // Choice of 75 is somewhat arbitrary while(val2 < val1 && (counter < 75 || (1+(i+1)+counter) > (N_NFsamples+N_extrapolated))) { counter += 1; val2 = deltaz[i+1+counter]; deltaz_smoothed[i+1] = ( val1 + deltaz[1+(i+1)+counter] )/2.; } if(counter==75 || (1+(i+1)+counter) > (N_NFsamples+N_extrapolated)) { deltaz_smoothed[i+1] = deltaz[i+1]; } } } // Here we effectively filter over the delta z as a function of neutral fraction to try and minimise any possible kinks etc. in the functional curve. for(i=0;i<(N_NFsamples+N_extrapolated+1);i++) { // We are at the end-points, cannot smooth if(i==0 || i==(N_NFsamples+N_extrapolated)) { deltaz[i] = deltaz_smoothed[i]; } else { deltaz[i] = 0.; // We are symmetrically smoothing, making sure we have the same number of data points either side of the point we are filtering over // This determins the filter width when close to the edge of the data ranges if( (i - (int)floor(smoothing_width/2.) ) < 0) { smoothing_int = 2*( i ) + (int)((int)smoothing_width%2); } else if( (i - (int)floor(smoothing_width/2.) + ((int)smoothing_width - 1) ) > (N_NFsamples + N_extrapolated) ) { smoothing_int = ((int)smoothing_width - 1) - 2*((i - (int)floor(smoothing_width/2.) + ((int)smoothing_width - 1) ) - (N_NFsamples + N_extrapolated) ) + (int)((int)smoothing_width%2); } else { smoothing_int = (int)smoothing_width; } // Average (filter) over the delta z values to smooth the result counter = 0; for(j=0;j<(int)smoothing_width;j++) { if(((i - (int)floor((float)smoothing_int/2.) + j)>=0) && ((i - (int)floor((float)smoothing_int/2.) + j) <= (N_NFsamples + N_extrapolated + 1)) && counter < smoothing_int ) { deltaz[i] += deltaz_smoothed[i - (int)floor((float)smoothing_int/2.) + j]; counter += 1; } } deltaz[i] /= (float)counter; } } N_deltaz = N_NFsamples + N_extrapolated + 1; // Now, we can construct the spline of the photon non-conservation correction (delta z as a function of neutral fraction) deltaz_spline_for_photoncons_acc = gsl_interp_accel_alloc (); deltaz_spline_for_photoncons = gsl_spline_alloc (gsl_interp_linear, N_NFsamples + N_extrapolated + 1); gsl_set_error_handler_off(); int gsl_status; gsl_status = gsl_spline_init(deltaz_spline_for_photoncons, NeutralFractions, deltaz, N_NFsamples + N_extrapolated + 1); GSL_ERROR(gsl_status); } float adjust_redshifts_for_photoncons( struct AstroParams *astro_params, struct FlagOptions *flag_options, float *redshift, float *stored_redshift, float *absolute_delta_z ) { int i, new_counter; double temp; float required_NF, adjusted_redshift, future_z, gradient_extrapolation, const_extrapolation, temp_redshift, check_required_NF; LOG_DEBUG("Adjusting redshifts for photon cons."); if(*redshift < global_params.PhotonConsEndCalibz) { LOG_ERROR( "You have passed a redshift (z = %f) that is lower than the enpoint of the photon non-conservation correction "\ "(global_params.PhotonConsEndCalibz = %f). If this behaviour is desired then set global_params.PhotonConsEndCalibz "\ "to a value lower than z = %f.",*redshift,global_params.PhotonConsEndCalibz,*redshift ); // Throw(ParameterError); Throw(PhotonConsError); } // Determine the neutral fraction (filling factor) of the analytic calibration expression given the current sampled redshift Q_at_z(*redshift, &(temp)); required_NF = 1.0 - (float)temp; // Find which redshift we need to sample in order for the calibration reionisation history to match the analytic expression if(required_NF > global_params.PhotonConsStart) { // We haven't started ionising yet, so keep redshifts the same adjusted_redshift = *redshift; *absolute_delta_z = 0.; } else if(required_NF<=global_params.PhotonConsEnd) { // We have gone beyond the threshold for the end of the photon non-conservation correction // Deemed to be roughly where the calibration curve starts to approach the analytic expression if(FirstNF_Estimate <= 0. && required_NF <= 0.0) { // Reionisation has already happened well before the calibration adjusted_redshift = *redshift; } else { // We have crossed the NF threshold for the photon conservation correction so now set to the delta z at the threshold if(required_NF < global_params.PhotonConsAsymptoteTo) { // This counts the number of times we have exceeded the extrapolated point and attempts to modify the delta z // to try and make the function a little smoother *absolute_delta_z = gsl_spline_eval(deltaz_spline_for_photoncons, global_params.PhotonConsAsymptoteTo, deltaz_spline_for_photoncons_acc); new_counter = 0; temp_redshift = *redshift; check_required_NF = required_NF; // Ok, find when in the past we exceeded the asymptote threshold value using the global_params.ZPRIME_STEP_FACTOR // In doing it this way, co-eval boxes will be the same as lightcone boxes with regard to redshift sampling while( check_required_NF < global_params.PhotonConsAsymptoteTo ) { temp_redshift = ((1. + temp_redshift)*global_params.ZPRIME_STEP_FACTOR - 1.); Q_at_z(temp_redshift, &(temp)); check_required_NF = 1.0 - (float)temp; new_counter += 1; } // Now adjust the final delta_z by some amount to smooth if over successive steps if(deltaz[1] > deltaz[0]) { *absolute_delta_z = pow( 0.96 , (new_counter - 1) + 1. ) * ( *absolute_delta_z ); } else { *absolute_delta_z = pow( 1.04 , (new_counter - 1) + 1. ) * ( *absolute_delta_z ); } // Check if we go into the future (z < 0) and avoid it adjusted_redshift = (*redshift) - (*absolute_delta_z); if(adjusted_redshift < 0.0) { adjusted_redshift = 0.0; } } else { *absolute_delta_z = gsl_spline_eval(deltaz_spline_for_photoncons, required_NF, deltaz_spline_for_photoncons_acc); adjusted_redshift = (*redshift) - (*absolute_delta_z); } } } else { // Initialise the photon non-conservation correction curve if(!photon_cons_allocated) { determine_deltaz_for_photoncons(); photon_cons_allocated = true; } // We have exceeded even the end-point of the extrapolation // Just smooth ever subsequent point // Note that this is deliberately tailored to light-cone quantites, but will still work with co-eval cubes // Though might produce some very minor discrepancies when comparing outputs. if(required_NF < NeutralFractions[0]) { new_counter = 0; temp_redshift = *redshift; check_required_NF = required_NF; // Ok, find when in the past we exceeded the asymptote threshold value using the global_params.ZPRIME_STEP_FACTOR // In doing it this way, co-eval boxes will be the same as lightcone boxes with regard to redshift sampling while( check_required_NF < NeutralFractions[0] ) { temp_redshift = ((1. + temp_redshift)*global_params.ZPRIME_STEP_FACTOR - 1.); Q_at_z(temp_redshift, &(temp)); check_required_NF = 1.0 - (float)temp; new_counter += 1; } if(new_counter > 5) { LOG_WARNING( "The photon non-conservation correction has employed an extrapolation for\n"\ "more than 5 consecutive snapshots. This can be unstable, thus please check "\ "resultant history. Parameters are:\n" ); #if LOG_LEVEL >= LOG_WARNING writeAstroParams(flag_options, astro_params); #endif } // Now adjust the final delta_z by some amount to smooth if over successive steps if(deltaz[1] > deltaz[0]) { *absolute_delta_z = pow( 0.998 , (new_counter - 1) + 1. ) * ( *absolute_delta_z ); } else { *absolute_delta_z = pow( 1.002 , (new_counter - 1) + 1. ) * ( *absolute_delta_z ); } // Check if we go into the future (z < 0) and avoid it adjusted_redshift = (*redshift) - (*absolute_delta_z); if(adjusted_redshift < 0.0) { adjusted_redshift = 0.0; } } else { // Find the corresponding redshift for the calibration curve given the required neutral fraction (filling factor) from the analytic expression *absolute_delta_z = gsl_spline_eval(deltaz_spline_for_photoncons, (double)required_NF, deltaz_spline_for_photoncons_acc); adjusted_redshift = (*redshift) - (*absolute_delta_z); } } // keep the original sampled redshift *stored_redshift = *redshift; // This redshift snapshot now uses the modified redshift following the photon non-conservation correction *redshift = adjusted_redshift; } void Q_at_z(double z, double *splined_value){ float returned_value; if (z >= Zmax) { *splined_value = 0.; } else if (z <= Zmin) { *splined_value = 1.; } else { returned_value = gsl_spline_eval(Q_at_z_spline, z, Q_at_z_spline_acc); *splined_value = returned_value; } } void z_at_Q(double Q, double *splined_value){ float returned_value; if (Q < Qmin) { LOG_ERROR("The minimum value of Q is %.4e",Qmin); // Throw(ParameterError); Throw(PhotonConsError); } else if (Q > Qmax) { LOG_ERROR("The maximum value of Q is %.4e. Reionization ends at ~%.4f.",Qmax,Zmin); LOG_ERROR("This error can occur if global_params.PhotonConsEndCalibz is close to "\ "the final sampled redshift. One can consider a lower value for "\ "global_params.PhotonConsEndCalibz to mitigate this"); // Throw(ParameterError); Throw(PhotonConsError); } else { returned_value = gsl_spline_eval(z_at_Q_spline, Q, z_at_Q_spline_acc); *splined_value = returned_value; } } void free_Q_value() { gsl_spline_free (Q_at_z_spline); gsl_interp_accel_free (Q_at_z_spline_acc); gsl_spline_free (z_at_Q_spline); gsl_interp_accel_free (z_at_Q_spline_acc); } void initialise_NFHistory_spline(double *redshifts, double *NF_estimate, int NSpline){ int i, counter, start_index, found_start_index; // This takes in the data for the calibration curve for the photon non-conservation correction counter = 0; start_index = 0; found_start_index = 0; FinalNF_Estimate = NF_estimate[0]; FirstNF_Estimate = NF_estimate[NSpline-1]; // Determine the point in the data where its no longer zero (basically to avoid too many zeros in the spline) for(i=0;i<NSpline-1;i++) { if(NF_estimate[i+1] > NF_estimate[i]) { if(found_start_index == 0) { start_index = i; found_start_index = 1; } } counter += 1; } counter = counter - start_index; N_calibrated = (counter+1); // Store the data points for determining the photon non-conservation correction nf_vals = calloc((counter+1),sizeof(double)); z_vals = calloc((counter+1),sizeof(double)); calibrated_NF_min = 1.; // Store the data, and determine the end point of the input data for estimating the extrapolated results for(i=0;i<(counter+1);i++) { nf_vals[i] = NF_estimate[start_index+i]; z_vals[i] = redshifts[start_index+i]; // At the extreme high redshift end, there can be numerical issues with the solution of the analytic expression if(i>0) { while(nf_vals[i] <= nf_vals[i-1]) { nf_vals[i] += 0.000001; } } if(nf_vals[i] < calibrated_NF_min) { calibrated_NF_min = nf_vals[i]; } } NFHistory_spline_acc = gsl_interp_accel_alloc (); // NFHistory_spline = gsl_spline_alloc (gsl_interp_cspline, (counter+1)); NFHistory_spline = gsl_spline_alloc (gsl_interp_linear, (counter+1)); gsl_set_error_handler_off(); int gsl_status; gsl_status = gsl_spline_init(NFHistory_spline, nf_vals, z_vals, (counter+1)); GSL_ERROR(gsl_status); z_NFHistory_spline_acc = gsl_interp_accel_alloc (); // z_NFHistory_spline = gsl_spline_alloc (gsl_interp_cspline, (counter+1)); z_NFHistory_spline = gsl_spline_alloc (gsl_interp_linear, (counter+1)); gsl_status = gsl_spline_init(z_NFHistory_spline, z_vals, nf_vals, (counter+1)); GSL_ERROR(gsl_status); } void z_at_NFHist(double xHI_Hist, double *splined_value){ float returned_value; returned_value = gsl_spline_eval(NFHistory_spline, xHI_Hist, NFHistory_spline_acc); *splined_value = returned_value; } void NFHist_at_z(double z, double *splined_value){ float returned_value; returned_value = gsl_spline_eval(z_NFHistory_spline, z, NFHistory_spline_acc); *splined_value = returned_value; } int ObtainPhotonConsData( double *z_at_Q_data, double *Q_data, int *Ndata_analytic, double *z_cal_data, double *nf_cal_data, int *Ndata_calibration, double *PhotonCons_NFdata, double *PhotonCons_deltaz, int *Ndata_PhotonCons) { int i; *Ndata_analytic = N_analytic; *Ndata_calibration = N_calibrated; *Ndata_PhotonCons = N_deltaz; for(i=0;i<N_analytic;i++) { z_at_Q_data[i] = z_Q[i]; Q_data[i] = Q_value[i]; } for(i=0;i<N_calibrated;i++) { z_cal_data[i] = z_vals[i]; nf_cal_data[i] = nf_vals[i]; } for(i=0;i<N_deltaz;i++) { PhotonCons_NFdata[i] = NeutralFractions[i]; PhotonCons_deltaz[i] = deltaz[i]; } return(0); } void FreePhotonConsMemory() { LOG_DEBUG("Freeing some photon cons memory."); free(deltaz); free(deltaz_smoothed); free(NeutralFractions); free(z_Q); free(Q_value); free(nf_vals); free(z_vals); free_Q_value(); gsl_spline_free (NFHistory_spline); gsl_interp_accel_free (NFHistory_spline_acc); gsl_spline_free (z_NFHistory_spline); gsl_interp_accel_free (z_NFHistory_spline_acc); gsl_spline_free (deltaz_spline_for_photoncons); gsl_interp_accel_free (deltaz_spline_for_photoncons_acc); LOG_DEBUG("Done Freeing photon cons memory."); photon_cons_allocated = false; } void FreeTsInterpolationTables(struct FlagOptions *flag_options) { LOG_DEBUG("Freeing some interpolation table memory."); freeSigmaMInterpTable(); if (flag_options->USE_MASS_DEPENDENT_ZETA) { free(z_val); z_val = NULL; free(Nion_z_val); free(z_X_val); z_X_val = NULL; free(SFRD_val); if (flag_options->USE_MINI_HALOS){ free(Nion_z_val_MINI); free(SFRD_val_MINI); } } else{ free(FgtrM_1DTable_linear); } LOG_DEBUG("Done Freeing interpolation table memory."); interpolation_tables_allocated = false; }
{ "alphanum_fraction": 0.6358573758, "avg_line_length": 39.551338766, "ext": "c", "hexsha": "8c1d7299ee4945b55692b74e0336a44afd47885f", "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": "b9f396ea5605440be419b7cf005fc4286ef1fd00", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "debanjan-cosmo/21cmFAST", "max_forks_repo_path": "src/py21cmfast/src/ps.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b9f396ea5605440be419b7cf005fc4286ef1fd00", "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": "debanjan-cosmo/21cmFAST", "max_issues_repo_path": "src/py21cmfast/src/ps.c", "max_line_length": 461, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f36885a813ace72f34c881d80473208d06e3829a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "daviesje/21cmFAST", "max_stars_repo_path": "src/py21cmfast/src/ps.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T20:07:30.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-29T20:07:30.000Z", "num_tokens": 50354, "size": 169873 }
/* * Copyright 2021-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #include <mcbp/protocol/status.h> #include <cstdint> #include <functional> #include <gsl/gsl> struct EngineIface; /** * Callback for any function producing stats. * * @param key the stat's key * @param value the stat's value in an ascii form (e.g. text form of a number) * @param cookie magic callback cookie */ using AddStatFn = std::function<void(std::string_view key, std::string_view value, gsl::not_null<const void*> cookie)>; /** * Callback for adding a response backet * @param key The key to put in the response * @param extras The data to put in the extended field in the response * @param body The data body * @param datatype This is currently not used and should be set to 0 * @param status The status code of the return packet (see in protocol_binary * for the legal values) * @param cas The cas to put in the return packet * @param cookie The cookie provided by the frontend * @return true if return message was successfully created, false if an * error occured that prevented the message from being sent */ using AddResponseFn = std::function<bool(std::string_view key, std::string_view extras, std::string_view body, uint8_t datatype, cb::mcbp::Status status, uint64_t cas, const void* cookie)>;
{ "alphanum_fraction": 0.6084126189, "avg_line_length": 39.1568627451, "ext": "h", "hexsha": "de1a2e0a56efe0b43e794f82f853657dfd2fac3b", "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": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_path": "include/memcached/engine_common.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_path": "include/memcached/engine_common.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_path": "include/memcached/engine_common.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 414, "size": 1997 }
/*This program evaluates the differential equations for a photon's geodesic in a perturbed spacetime in SPHERICAL coordinates and restricted to RADIAL MOTION with a Runge-Kutta-Fehlberg 45 method.*/ /*This program solves the particular case for flat FRW perturbed spacetime with metric: $g_{ab} = {[g]}_{ab} + h_{ab}$. Where ${[g]}_{ab}$ corresponds to the flat FRW metric and $h_{ab}$ corresponds to the perturbation in the conformal Newtonian gauge. A Plummer potential with adequate parameters have been used to simulate the perturbation. The equations are written in the form $\frac{d(x or p)^{\alpha}}{d\lambda}=f(x^{\alpha},p^{\beta})$ and the indices $\alpha$ and $\beta$ run from 0 to 1 since the motion is only radial. Where $p^{\alpha}={\dot{x}}^{\alpha}$. The coordinates for the photon's geodesics are then: (ct,r) = (x0,x1).*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> //GSL error management module #include <gsl/gsl_spline.h> //GSL interpolation module /* PHYSICAL CONSTANTS AND PARAMETERS */ #define A 10.0 //Distance parameter of the perturbations #define G 43007.01 //Gravitational constant #define M 0.0 //Mass of the perturbation #define C 299792.458 //Speed of light /* PROGRAM PARAMETERS (ONLY USING NLINES FRW) */ #define NLINES 100000 //Number of lines in geodesic_solution.dat file #define NSTEPS 75000000 //Number of steps for solving geodesics #define NLINESFRW 10000 //Number of lines in frw.dat file #define DLAMBDA 0.01 //Geodesics parameter step //We define mydbl as a generic variable type which can be changed when needed to: float, double, long double typedef long double mydbl; /* RUNGE-KUTTA-FEHLBERG METHOD CONSTANTS */ const mydbl c2 = 0.25, c3 = 3.0/8.0, c4 = 12.0/13.0, c5 = 1.0, c6 = 0.5; //Multiplying increment in t const mydbl a21 = 0.25, a31 = 3.0/32.0, a32 = 9.0/32.0, a41 = 1932.0/2197.0, a42 = -7200.0/2197.0, a43 = 7296.0/2197.0, a51 = 439.0/216.0, a52 = -8.0, a53 = 3680.0/513.0, a54 = -845.0/4104.0, a61 = -8.0/27.0, a62 = 2.0, a63 = -3544.0/2565.0, a64 = 1859.0/4104.0, a65 = -11.0/40.0; //This adds to the approximated solution in step i. First script means K value and second which K is multiplying const mydbl r1 = 1.0/360.0, r3 = -128.0/4275.0, r4 = -2197.0/75240.0, r5 = 1.0/50.0, r6 = 2.0/55.0; //Coefficients to calculate R const mydbl b1 = 25.0/216.0, b3 = 1408.0/2565.0, b4 = 2197.0/4104.0, b5 = -1.0/5.0; /* FUNCTIONS OF THE PROGRAM */ /*Find and return the maximum value for objects in a vector*/ mydbl maxValue(mydbl arr[], size_t size) { size_t i; mydbl maxValue = arr[0]; for(i = 1; i < size; i++) { if(arr[i] > maxValue) { maxValue = arr[i]; } } return maxValue; } /*Interpolation of function inside *spline object evaluated at an abscisa 'x'. Argument *spline is a pointer to a spline object which stores the type of interpolation to be made. x is the independent variable where the function is evaluated. *acc is a pointer to a lookup object for interpolations.*/ double interpolator(gsl_spline *spline, double x, gsl_interp_accel *acc) { double a = gsl_spline_eval(spline, x, acc); //Interpolates data to abcisa x using method in spline and acceleration object acc return a; //Return value of interpolated function at x } /*Function for the gravitational potential to be used. Potential for Plummer model.*/ mydbl potential(mydbl r) { return -G*M/(sqrtl(A*A + r*r)); } /*Derivative of potential respecto to radial coordinate.*/ mydbl der_potential(mydbl r) { return G*M*r/(powl(A*A+r*r, 1.5)); } /*Function of the 0th momentum component differential equation for the geodesics. ${p0}^{dot} = f0(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_0(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl f = -2.0*der_potential(r)*p0*pr/(C*C + 2.0*potential(r)) - (1.0 - 2.0*potential(r)/(C*C))*(a*adot)*(pr*pr)/(C + 2.0*potential(r)/C); return f; } /*Function of the 1th (radial) momentum component differential equation for the geodesics. ${p1}^{dot} = f1(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_r(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl f = - (der_potential(r)*p0*p0)/(a*a*(C*C - 2.0*potential(r))) - (2.0*adot*p0*pr)/(C*a) + der_potential(r)*(pr*pr)/(C*C - 2.0*potential(r)); return f; } /*To set the initial value of pr, it must hold $g_{\mu\nu}p^{\mu}p^{\nu} = 0$. This factor multiplies p0 to guarantee that p1 fulfill the null geodesic condition.*/ mydbl condition_factor(mydbl r, double a) { return (mydbl)(1.0/a)*sqrtl((1.0+2.0*potential(r)/(C*C))/(1.0 - 2.0*potential(r)/(C*C))); } /*$cp^{0}$ multiplied by this factor allows to obtain the energy for a local inertial observer in this spacetime.*/ mydbl energy_factor(mydbl r) { mydbl g = sqrtl(1.0 + 2.0*potential(r)/(C*C)); return g; } /*Violation of null geodesics condition $g_{\mu\nu}p^{\mu}p^{\nu} = 0$.*/ mydbl violation(mydbl r, mydbl p0, mydbl pr, double a) { mydbl f = -(1.0+2.0*potential(r)/(C*C))*p0*p0 + (mydbl)(1.0*a*a)*(1.0-2.0*potential(r)/(C*C))*pr*pr; return f; } /*Function for solving the geodesic's differential equations using a Runge-Kutta-Fehlber method with adaptative stepsize. Arguments are pointer so variables in that memory addresses are changed every time this function is called. There is no need to define auxiliary variables to store the results of computations.*/ void runge_kutta_fehlberg(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl *x0, mydbl *x1, mydbl *p0, mydbl *p1, mydbl *lambda, mydbl *dlambda, mydbl lambda_endpoint, mydbl tol, mydbl dlambda_max, mydbl dlambda_min, FILE *fp, double aem, mydbl energy1) { /*Define the k quantities for all the variables*/ mydbl k1x0, k1x1, k1p0, k1p1; mydbl k2x0, k2x1, k2p0, k2p1; mydbl k3x0, k3x1, k3p0, k3p1; mydbl k4x0, k4x1, k4p0, k4p1; mydbl k5x0, k5x1, k5p0, k5p1; mydbl k6x0, k6x1, k6p0, k6p1; /*Define a vector that carries the errors for each differential equation and a variable for storing the biggest error*/ mydbl r[4], rmax; /*Define the increments for the values to be solved in the differential equations*/ mydbl dp0, dp1, dx0, dx1; /*Define some relevant quantities to be printed in a file*/ mydbl energy, difft, t, v, difference; double aobs, difftfrw; /*Relevant quantity to determine the new stepsize*/ mydbl delta; while(*lambda < lambda_endpoint) { /*Check if the independent variable plus the actual stepsize is still in the desired interval*/ if((*lambda + *dlambda) > lambda_endpoint) { *dlambda = lambda_endpoint - *lambda; } /*Calculate the k quantities for all the variables*/ /*This section calculates the k1 quantities*/ k1x0 = (*dlambda)*(*p0); k1x1 = (*dlambda)*(*p1); k1p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1); k1p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1); /*This section calculates the k2 quantities*/ k2x0 = *dlambda*(*p0 + a21*k1p0); k2x1 = *dlambda*(*p1 + a21*k1p1); k2p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a21*k1p0, *p1 + a21*k1p1, *x0 + a21*k1x0, *x1 + a21*k1x1); k2p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a21*k1p0, *p1 + a21*k1p1, *x0 + a21*k1x0, *x1 + a21*k1x1); /*This section calculates the k3 quantities*/ k3x0 = *dlambda*(*p0 + a31*k1p0 + a32*k2p0); k3x1 = *dlambda*(*p1 + a31*k1p1 + a32*k2p1); k3p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a31*k1p0 + a32*k2p0, *p1 + a31*k1p1 + a32*k2p1, *x0 + a31*k1x0 + a32*k2x0, *x1 + a31*k1x1 + a32*k2x1); k3p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a31*k1p0 + a32*k2p0, *p1 + a31*k1p1 + a32*k2p1, *x0 + a31*k1x0 + a32*k2x0, *x1 + a31*k1x1 + a32*k2x1); /*This section calculates the k4 quantities*/ k4x0 = *dlambda*(*p0 + a41*k1p0 + a42*k2p0 + a43*k3p0); k4x1 = *dlambda*(*p1 + a41*k1p1 + a42*k2p1 + a43*k3p1); k4p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a41*k1p0 + a42*k2p0 + a43*k3p0, *p1 + a41*k1p1 + a42*k2p1 + a43*k3p1, *x0 + a41*k1x0 + a42*k2x0 + a43*k3x0, *x1 + a41*k1x1 + a42*k2x1 + a43*k3x1); k4p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a41*k1p0 + a42*k2p0 + a43*k3p0, *p1 + a41*k1p1 + a42*k2p1 + a43*k3p1, *x0 + a41*k1x0 + a42*k2x0 + a43*k3x0, *x1 + a41*k1x1 + a42*k2x1 + a43*k3x1); /*This section calculates the k5 quantities*/ k5x0 = *dlambda*(*p0 + a51*k1p0 + a52*k2p0 + a53*k3p0 + a54*k4p0); k5x1 = *dlambda*(*p1 + a51*k1p1 + a52*k2p1 + a53*k3p1 + a54*k4p1); k5p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a51*k1p0 + a52*k2p0 + a53*k3p0 + a54*k4p0, *p1 + a51*k1p1 + a52*k2p1 + a53*k3p1 + a54*k4p1, *x0 + a51*k1x0 + a52*k2x0 + a53*k3x0 + a54*k4x0, *x1 + a51*k1x1 + a52*k2x1 + a53*k3x1 + a54*k4x1); k5p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a51*k1p0 + a52*k2p0 + a53*k3p0 + a54*k4p0, *p1 + a51*k1p1 + a52*k2p1 + a53*k3p1 + a54*k4p1, *x0 + a51*k1x0 + a52*k2x0 + a53*k3x0 + a54*k4x0, *x1 + a51*k1x1 + a52*k2x1 + a53*k3x1 + a54*k4x1); /*This section calculates the k6 quantities*/ k6x0 = *dlambda*(*p0 + a61*k1p0 + a62*k2p0 + a63*k3p0 + a64*k4p0 + a65*k5p0); k6x1 = *dlambda*(*p1 + a61*k1p1 + a62*k2p1 + a63*k3p1 + a64*k4p1 + a65*k5p1); k6p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a61*k1p0 + a62*k2p0 + a63*k3p0 + a64*k4p0 + a65*k5p0, *p1 + a61*k1p1 + a62*k2p1 + a63*k3p1 + a64*k4p1 + a65*k5p1, *x0 + a61*k1x0 + a62*k2x0 + a63*k3x0 + a64*k4x0 + a65*k5x0, *x1 + a61*k1x1 + a62*k2x1 + a63*k3x1 + a64*k4x1 + a65*k5x1); k6p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a61*k1p0 + a62*k2p0 + a63*k3p0 + a64*k4p0 + a65*k5p0, *p1 + a61*k1p1 + a62*k2p1 + a63*k3p1 + a64*k4p1 + a65*k5p1, *x0 + a61*k1x0 + a62*k2x0 + a63*k3x0 + a64*k4x0 + a65*k5x0, *x1 + a61*k1x1 + a62*k2x1 + a63*k3x1 + a64*k4x1 + a65*k5x1); /*Determination of the biggest error between the errors for each differential equation*/ r[0] = fabsl(r1*k1p0 + r3*k3p0 + r4*k4p0 + r5*k5p0 + r6*k6p0)/(*dlambda); r[1] = fabsl(r1*k1p1 + r3*k3p1 + r4*k4p1 + r5*k5p1 + r6*k6p1)/(*dlambda); r[2] = fabsl(r1*k1x0 + r3*k3x0 + r4*k4x0 + r5*k5x0 + r6*k6x0)/(*dlambda); r[3] = fabsl(r1*k1x1 + r3*k3x1 + r4*k4x1 + r5*k5x1 + r6*k6x1)/(*dlambda); rmax = maxValue(r, 4); /*Check whether the worst approximation is less than the introduced tolerance*/ if(rmax <= tol) { *lambda = *lambda + *dlambda; dp0 = b1*k1p0 + b3*k3p0 + b4*k4p0 + b5*k5p0; dp1 = b1*k1p1 + b3*k3p1 + b4*k4p1 + b5*k5p1; dx0 = b1*k1x0 + b3*k3x0 + b4*k4x0 + b5*k5x0; dx1 = b1*k1x1 + b3*k3x1 + b4*k4x1 + b5*k5x1; *p0 = *p0 + dp0; *p1 = *p1 + dp1; *x0 = *x0 + dx0; *x1 = *x1 + dx1; /*Relevant quantities to save in the .dat file. These only are calculated if the approximation is accepted*/ energy = C*energy_factor(*x1)*(*p0); difft = (energy - energy1)/energy1; t = *x0/C; aobs = interpolator(spline1, (double)(1.0*t), acc1); v = violation(*x1, *p0, *p1, aobs); difftfrw = (aem/aobs) - 1.0; difference = difft - (mydbl)(1.0*difftfrw); fprintf(fp, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le %16.8Le\n", *lambda, *dlambda, *x0, *x1, *p0, *p1, energy, v, difft, difftfrw, difference, rmax); } /*Calculate a new stepsize*/ delta = 0.84*powl(tol/rmax, 0.25); if(delta <= 0.1) { *dlambda = *dlambda*0.1; } else if(delta >= 4.0) { *dlambda = *dlambda*4.0; } else { *dlambda = *dlambda*delta; } /*Check whether the stepsize is too big or too small*/ if(*dlambda > dlambda_max) { *dlambda = dlambda_max; } else if(*dlambda < dlambda_min) { printf("Minimum value for stepsize dlambda exceeded.\n"); break; } } } int main(void) { /***READ SCALE FACTOR DATA AND PREPARE OBJECTS FOR INTERPOLATION ***/ int i; //For array manipulation /*Pointer to scale_factor.data file*/ FILE *frw; frw = fopen("../scale_factor.dat","r"); /*Variables and arrays to read the data*/ double cosmictime[NLINESFRW], conftime, scale_factor[NLINESFRW], der_scale_factor[NLINESFRW]; /*Reading the data*/ for(i=0; i<NLINESFRW; i++) { fscanf(frw,"%lf %lf %lf %lf", &cosmictime[i], &conftime, &scale_factor[i], &der_scale_factor[i]); } /*Free space in memory*/ fclose(frw); /*** Initializes objects for interpolation. 1 is for interpolation of scale factor, 2 is for interpolation of derivative of scale factor ***/ /*Allocate space in memory*/ gsl_interp_accel *acc1 = gsl_interp_accel_alloc(); //Acceleration type object (for index lookup) gsl_interp_accel *acc2 = gsl_interp_accel_alloc(); gsl_spline *spline1 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW); //Spline type object (define interpolation type and space in memory, works for both) gsl_spline *spline2 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW); /*Initializes objects for interpolation*/ gsl_spline_init(spline1, cosmictime, scale_factor, NLINESFRW); //Initializes spline object for data cosmictime, scale_factor of size NLINES gsl_spline_init(spline2, cosmictime, der_scale_factor, NLINESFRW); //Initializes spline object for data cosmictime, der_scale_factor of size NLINES /************************************************************************************/ /***SOLVES GEODESIC EQUATIONS FOR PERTURBED FRW UNIVERSE WITH STATIC PLUMMER POTENTIAL ***/ /*Parameters for RKF method*/ mydbl dlambda_max = 1.0e-01, dlambda_min = 1.0e-05, tol = 1.0e-10, lambdaEndPoint = 1.0e+05; /*Initial conditions*/ mydbl ti = 7.0 ,x0, r = -500.0, p0 = 1.0e-3, pr, lambda = 0.0, energy1, energy, v, difft, difference, dlambda = dlambda_max; double difftfrw, aem, aobs; x0 = C*ti; aem = interpolator(spline1, (double)(1.0*ti), acc1); pr = condition_factor(r, aem)*p0; energy1 = C*energy_factor(r)*p0; v = violation(r, p0, pr, aem); difft = (energy1 - energy1)/energy1; difftfrw = (aem/aem) - 1.0; difference = difft - (mydbl)(1.0*difftfrw); /*Pointer to file where solution of differential equation will be saved.*/ FILE *geodesic; geodesic = fopen("geodesic_solution.dat","w"); /*Write line of initial values in file*/ fprintf(geodesic, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le %16.8Le\n", lambda, dlambda, x0, r, p0, pr, energy1, v, difft, difftfrw, difference, (mydbl)0.0); /*Solution of the differential equation*/ runge_kutta_fehlberg(spline1, acc1, spline2, acc2, &x0, &r, &p0, &pr, &lambda, &dlambda, lambdaEndPoint, tol, dlambda_max, dlambda_min, geodesic, aem, energy1); /************************************************************************************/ /***RELEASING ALL SPACE USED IN MEMORY***/ fclose(geodesic); //Close file storing the results gsl_spline_free(spline1); //Free memory of spline object gsl_spline_free(spline2); gsl_interp_accel_free(acc1); //Free memory of accel object gsl_interp_accel_free(acc2); }
{ "alphanum_fraction": 0.6630372856, "avg_line_length": 50.9580645161, "ext": "c", "hexsha": "f3a686ad231070dd5be506b7f3493b3082c3abb0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_forks_repo_path": "frw/frw_perturbed_spherical_radial_motion_rkf.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_issues_repo_issues_event_max_datetime": "2016-09-19T20:33:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-26T05:36:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_issues_repo_path": "frw/frw_perturbed_spherical_radial_motion_rkf.c", "max_line_length": 393, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_stars_repo_path": "frw/frw_perturbed_spherical_radial_motion_rkf.c", "max_stars_repo_stars_event_max_datetime": "2015-10-21T03:59:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-21T03:59:02.000Z", "num_tokens": 6090, "size": 15797 }
/** * Copyright 2016 BitTorrent 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 <scraps/config.h> #include <scraps/base64.h> #include <scraps/Byte.h> #include <scraps/hex.h> #include <scraps/Temp.h> #include <scraps/random.h> #include <scraps/hash.h> #include <stdts/optional.h> #include <gsl.h> #include <cerrno> #include <vector> #include <iterator> #include <random> #include <chrono> namespace scraps { constexpr double kPi = 3.1415926535897932385; /** * Returns a string escaped according to RFC 4627. * * @param the string to be escaped * @return the string escaped according to RFC 4627 */ std::string JSONEscape(const char* str); /** * Returns a string in which all non-alphanumeric characters except dashes, underscores, * spaces, and periods are replaced with a percent sign followed by their hexadecimal * value. Spaces are replaced with plus signs. * * @return the url-encoded string */ std::string URLEncode(const char* str); inline std::string URLEncode(const std::string& str) { return URLEncode(str.c_str()); } /** * Returns a string in which the effects of URLEncode have been reversed. * * @return the url-decoded string */ std::string URLDecode(const char* str); inline std::string URLDecode(const std::string& str) { return URLDecode(str.c_str()); } /** * Clamp a value between min and max, inclusive. */ template <typename T, typename MinT, typename MaxT> constexpr auto Clamp(const T& value, const MinT& min, const MaxT& max) { return std::max<std::common_type_t<T, MinT, MaxT>>(min, std::min<std::common_type_t<T, MinT, MaxT>>(value, max)); } /** * Parse out an address and port from the given host string. If a port is not found, the * defaultPort is returned. */ std::tuple<std::string, uint16_t> ParseAddressAndPort(const std::string& host, uint16_t defaultPort); /** * @return the amount of physical memory that the system has, or 0 on error */ size_t PhysicalMemory(); /** * Iterates over a container, allowing for safe modification of the container at any point. */ template <typename T, typename F> void NonatomicIteration(T&& iterable, F&& function) { auto copy = iterable; for (auto& element : copy) { auto it = std::find(iterable.begin(), iterable.end(), element); if (it == iterable.end()) { continue; } function(element); } } template <typename T, std::ptrdiff_t N> gsl::basic_string_span<T> TrimLeft(gsl::basic_string_span<T, N> str) { decltype(str.size()) i = 0; while(i < str.size() && isspace(str[i])) { ++i; }; return {str.data() + i, static_cast<std::ptrdiff_t>(str.size() - i)}; } template <typename T, std::ptrdiff_t N> gsl::basic_string_span<T> TrimRight(gsl::basic_string_span<T, N> str) { decltype(str.size()) i = str.size(); while(i > 0 && isspace(str[i - 1])) { --i; }; return {str.data(), static_cast<std::ptrdiff_t>(i)}; } template <typename T, std::ptrdiff_t N> auto Trim(gsl::basic_string_span<T, N> str) { return TrimLeft(TrimRight(str)); } stdts::optional<std::vector<Byte>> BytesFromFile(const std::string& path); /** * Sets the given file descriptor to blocking or non-blocking. * * @param fd the file descriptor * @param blocking true if the file descriptor should be set to blocking. false if it should be set to non-blocking * @return true on success */ bool SetBlocking(int fd, bool blocking = true); /** * Returns a demangled symbol name. If demangling is not supported, returns original mangled name. */ std::string Demangle(const char* name); /** * Returns whether two strings are equal disregarding case */ inline bool CaseInsensitiveEquals(stdts::string_view l, stdts::string_view r) { return l.size() == r.size() && std::equal(l.begin(), l.end(), r.begin(), [](char a, char b){ return tolower(a) == tolower(b); }); } /** * Split a sequence on a delimiter. The SequenceType template argument should be * specified to the type of container OutputIt should accept. By default, it is * set OutputIt::container_type::value_type. * * @param begin beginning of input sequence * @param end end of input sequence * @param out output iterator to a container of Sequence types * @param delimiter a single element element in the sequence */ template <typename InputIt, typename OutputIt, typename Delimiter, typename SequenceType = typename OutputIt::container_type::value_type> void Split(InputIt&& begin, InputIt&& end, OutputIt&& out, Delimiter&& delimiter) { SequenceType current; auto inserter = std::back_inserter(current); for (auto it = begin; it != end; ++it) { if (*it == delimiter) { *(out++) = std::move(current); current = {}; inserter = std::back_inserter(current); } else { inserter = *it; } } *out = std::move(current); } } // namespace scraps
{ "alphanum_fraction": 0.696879088, "avg_line_length": 31.2923976608, "ext": "h", "hexsha": "304cf324257501f2322ec7f57eadfb325a65a1d6", "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": "78925a738540415ec04b9cbe23cb319421f44978", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "carlbrown/scraps", "max_forks_repo_path": "include/scraps/utility.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "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": "carlbrown/scraps", "max_issues_repo_path": "include/scraps/utility.h", "max_line_length": 137, "max_stars_count": null, "max_stars_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "carlbrown/scraps", "max_stars_repo_path": "include/scraps/utility.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1337, "size": 5351 }
/* integration/gsl_integration.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_INTEGRATION_H__ #define __GSL_INTEGRATION_H__ #include <stdlib.h> #include <gsl/gsl_math.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* Workspace for adaptive integrators */ typedef struct { size_t limit; size_t size; size_t nrmax; size_t i; size_t maximum_level; double *alist; double *blist; double *rlist; double *elist; size_t *order; size_t *level; } gsl_integration_workspace; gsl_integration_workspace * gsl_integration_workspace_alloc (const size_t n); void gsl_integration_workspace_free (gsl_integration_workspace * w); /* Workspace for QAWS integrator */ typedef struct { double alpha; double beta; int mu; int nu; double ri[25]; double rj[25]; double rg[25]; double rh[25]; } gsl_integration_qaws_table; gsl_integration_qaws_table * gsl_integration_qaws_table_alloc (double alpha, double beta, int mu, int nu); int gsl_integration_qaws_table_set (gsl_integration_qaws_table * t, double alpha, double beta, int mu, int nu); void gsl_integration_qaws_table_free (gsl_integration_qaws_table * t); /* Workspace for QAWO integrator */ enum gsl_integration_qawo_enum { GSL_INTEG_COSINE, GSL_INTEG_SINE }; typedef struct { size_t n; double omega; double L; double par; enum gsl_integration_qawo_enum sine; double *chebmo; } gsl_integration_qawo_table; gsl_integration_qawo_table * gsl_integration_qawo_table_alloc (double omega, double L, enum gsl_integration_qawo_enum sine, size_t n); int gsl_integration_qawo_table_set (gsl_integration_qawo_table * t, double omega, double L, enum gsl_integration_qawo_enum sine); int gsl_integration_qawo_table_set_length (gsl_integration_qawo_table * t, double L); void gsl_integration_qawo_table_free (gsl_integration_qawo_table * t); /* Definition of an integration rule */ typedef void gsl_integration_rule (const gsl_function * f, double a, double b, double *result, double *abserr, double *defabs, double *resabs); void gsl_integration_qk15 (const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc); void gsl_integration_qk21 (const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc); void gsl_integration_qk31 (const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc); void gsl_integration_qk41 (const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc); void gsl_integration_qk51 (const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc); void gsl_integration_qk61 (const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc); void gsl_integration_qcheb (gsl_function * f, double a, double b, double *cheb12, double *cheb24); /* The low-level integration rules in QUADPACK are identified by small integers (1-6). We'll use symbolic constants to refer to them. */ enum { GSL_INTEG_GAUSS15 = 1, /* 15 point Gauss-Kronrod rule */ GSL_INTEG_GAUSS21 = 2, /* 21 point Gauss-Kronrod rule */ GSL_INTEG_GAUSS31 = 3, /* 31 point Gauss-Kronrod rule */ GSL_INTEG_GAUSS41 = 4, /* 41 point Gauss-Kronrod rule */ GSL_INTEG_GAUSS51 = 5, /* 51 point Gauss-Kronrod rule */ GSL_INTEG_GAUSS61 = 6 /* 61 point Gauss-Kronrod rule */ }; void gsl_integration_qk (const int n, const double xgk[], const double wg[], const double wgk[], double fv1[], double fv2[], const gsl_function *f, double a, double b, double * result, double * abserr, double * resabs, double * resasc); int gsl_integration_qng (const gsl_function * f, double a, double b, double epsabs, double epsrel, double *result, double *abserr, size_t * neval); 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 gsl_integration_qagi (gsl_function * f, double epsabs, double epsrel, size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr); int gsl_integration_qagiu (gsl_function * f, double a, double epsabs, double epsrel, size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr); int gsl_integration_qagil (gsl_function * f, double b, double epsabs, double epsrel, size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr); int gsl_integration_qags (const gsl_function * f, double a, double b, double epsabs, double epsrel, size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr); int gsl_integration_qagp (const gsl_function * f, double *pts, size_t npts, double epsabs, double epsrel, size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr); int gsl_integration_qawc (gsl_function *f, const double a, const double b, const double c, const double epsabs, const double epsrel, const size_t limit, gsl_integration_workspace * workspace, double * result, double * abserr); int gsl_integration_qaws (gsl_function * f, const double a, const double b, gsl_integration_qaws_table * t, const double epsabs, const double epsrel, const size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr); int gsl_integration_qawo (gsl_function * f, const double a, const double epsabs, const double epsrel, const size_t limit, gsl_integration_workspace * workspace, gsl_integration_qawo_table * wf, double *result, double *abserr); int gsl_integration_qawf (gsl_function * f, const double a, const double epsabs, const size_t limit, gsl_integration_workspace * workspace, gsl_integration_workspace * cycle_workspace, gsl_integration_qawo_table * wf, double *result, double *abserr); /* Workspace for fixed-order Gauss-Legendre integration */ typedef struct { size_t n; /* number of points */ double *x; /* Gauss abscissae/points */ double *w; /* Gauss weights for each abscissae */ int precomputed; /* high precision abscissae/weights precomputed? */ } gsl_integration_glfixed_table; gsl_integration_glfixed_table * gsl_integration_glfixed_table_alloc (size_t n); void gsl_integration_glfixed_table_free (gsl_integration_glfixed_table * t); /* Routine for fixed-order Gauss-Legendre integration */ double gsl_integration_glfixed (const gsl_function *f, double a, double b, const gsl_integration_glfixed_table * t); /* Routine to retrieve the i-th Gauss-Legendre point and weight from t */ int gsl_integration_glfixed_point (double a, double b, size_t i, double *xi, double *wi, const gsl_integration_glfixed_table * t); /* Cquad integration - Pedro Gonnet */ /* Data of a single interval */ typedef struct { double a, b; double c[64]; double fx[33]; double igral, err; int depth, rdepth, ndiv; } gsl_integration_cquad_ival; /* The workspace is just a collection of intervals */ typedef struct { size_t size; gsl_integration_cquad_ival *ivals; size_t *heap; } gsl_integration_cquad_workspace; gsl_integration_cquad_workspace * gsl_integration_cquad_workspace_alloc (const size_t n); void gsl_integration_cquad_workspace_free (gsl_integration_cquad_workspace * w); int gsl_integration_cquad (const gsl_function * f, double a, double b, double epsabs, double epsrel, gsl_integration_cquad_workspace * ws, double *result, double *abserr, size_t * nevals); /* Romberg integration workspace and routines */ typedef struct { size_t n; /* maximum number of steps */ double *work1; /* workspace for a row of R matrix, size n */ double *work2; /* workspace for a row of R matrix, size n */ } gsl_integration_romberg_workspace; gsl_integration_romberg_workspace *gsl_integration_romberg_alloc(const size_t n); void gsl_integration_romberg_free(gsl_integration_romberg_workspace * w); int gsl_integration_romberg(const gsl_function * f, const double a, const double b, const double epsabs, const double epsrel, double * result, size_t * neval, gsl_integration_romberg_workspace * w); /* IQPACK related structures and routines */ typedef struct { double alpha; double beta; double a; double b; double zemu; double shft; double slp; double al; double be; } gsl_integration_fixed_params; typedef struct { int (*check)(const size_t n, const gsl_integration_fixed_params * params); int (*init)(const size_t n, double * diag, double * subdiag, gsl_integration_fixed_params * params); } gsl_integration_fixed_type; typedef struct { size_t n; /* number of nodes/weights */ double *weights; /* quadrature weights */ double *x; /* quadrature nodes */ double *diag; /* diagonal of Jacobi matrix */ double *subdiag; /* subdiagonal of Jacobi matrix */ const gsl_integration_fixed_type * type; } gsl_integration_fixed_workspace; /* IQPACK integral types */ GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_legendre; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_chebyshev; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_gegenbauer; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_jacobi; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_laguerre; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_hermite; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_exponential; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_rational; GSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_chebyshev2; gsl_integration_fixed_workspace * gsl_integration_fixed_alloc(const gsl_integration_fixed_type * type, const size_t n, const double a, const double b, const double alpha, const double beta); void gsl_integration_fixed_free(gsl_integration_fixed_workspace * w); size_t gsl_integration_fixed_n(const gsl_integration_fixed_workspace * w); double *gsl_integration_fixed_nodes(const gsl_integration_fixed_workspace * w); double *gsl_integration_fixed_weights(const gsl_integration_fixed_workspace * w); int gsl_integration_fixed(const gsl_function * func, double * result, const gsl_integration_fixed_workspace * w); __END_DECLS #endif /* __GSL_INTEGRATION_H__ */
{ "alphanum_fraction": 0.6292313244, "avg_line_length": 35.4347826087, "ext": "h", "hexsha": "1e8b38ac4cb3826cc627917637f5a9b101902574", "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_integration.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_integration.h", "max_line_length": 102, "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_integration.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": 2970, "size": 13855 }
/* specfunc/test_sincos_pi.c * * Copyright (C) 2017 Konrad Griessinger * * 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: Konrad Griessinger */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_test.h> #include <gsl/gsl_sf.h> #include "test_sf.h" /* Any double precision number bigger than this is automatically an even integer. */ #define BIGDBL (2.0 / GSL_DBL_EPSILON) int test_sincos_pi(void) { gsl_sf_result r; int s = 0; int k = 0, kmax = 12; double x = 0.0, ix = 0.0, fx = 0.0, exact = 0.0; /* sin_pi tests */ fx = 0.5; exact = 1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -0.5; exact = -1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 1.5; exact = -1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -1.5; exact = 1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 2.5; exact = 1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -2.5; exact = -1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 3.5; exact = -1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -3.5; exact = 1.0; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 0.375; exact = 0.923879532511286756128183189397; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -0.375; exact = -0.923879532511286756128183189397; TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 0.0; exact = 0.0; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.5; exact = 1.0; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.03125; exact = 0.0980171403295606019941955638886; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.0625; exact = 0.195090322016128267848284868477; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.75; exact = 0.707106781186547524400844362105; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.0078125; exact = 0.0245412285229122880317345294593; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } /* sin_pi tests for very large arguments */ fx = 0.0625; exact = 0.195090322016128267848284868477; ix = LONG_MAX + 1.0; ix += fabs(fmod(ix,2.0)); /* make sure of even number */ for (k=0; k<kmax; k++) { x = ix + fx; x -= ix; /* careful with compiler optimization */ if ( ( x != fx ) || ( fabs(ix+fx) >= BIGDBL ) ) break; printf("ix+fx= %.18e\n", ix+fx); TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix += 101.0; exact = -exact; } fx = -0.0625; exact = -0.195090322016128267848284868477; ix = LONG_MIN - 1.0; ix -= fabs(fmod(ix,2.0)); /* make sure of even number */ for (k=0; k<kmax; k++) { x = ix + fx; x -= ix; /* careful with compiler optimization */ if ( ( x != fx ) || ( fabs(ix+fx) >= BIGDBL ) ) break; printf("ix+fx= %.18e\n", ix+fx); TEST_SF(s, gsl_sf_sin_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix -= 101.0; exact = -exact; } /* cos_pi tests */ ix = 0.0; fx = 0.0; exact = 1.0; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 1.0; exact = -1.0; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -1.0; exact = -1.0; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 2.0; exact = 1.0; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -2.0; exact = 1.0; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 3.0; exact = -1.0; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -3.0; exact = -1.0; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 0.375; exact = 0.382683432365089771728459984030; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = -0.375; exact = 0.382683432365089771728459984030; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); fx = 0.0; exact = 1.0; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.5; exact = 0.0; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.0625; exact = 0.980785280403230449126182236134; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.4375; exact = 0.195090322016128267848284868477; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } fx = 0.4921875; exact = 0.0245412285229122880317345294593; ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(3.0,k+1); if (k==0) exact = -exact; } exact = fabs(exact); ix = 0.0; for (k=0; k<kmax; k++) { TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix = pow(10.0,k+1); } /* cos_pi tests for very large arguments */ fx = 0.0625; exact = 0.980785280403230449126182236134; ix = LONG_MAX + 1.0; ix += fabs(fmod(ix,2.0)); /* make sure of even number */ for (k=0; k<kmax; k++) { x = ix + fx; x -= ix; /* careful with compiler optimization */ if ( ( x != fx ) || ( fabs(ix+fx) >= BIGDBL ) ) break; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix += 101.0; exact = -exact; } fx = -0.0625; exact = 0.980785280403230449126182236134; ix = LONG_MIN - 1.0; ix -= fabs(fmod(ix,2.0)); /* make sure of even number */ for (k=0; k<kmax; k++) { x = ix + fx; x -= ix; /* careful with compiler optimization */ if ( ( x != fx ) || ( fabs(ix+fx) >= BIGDBL ) ) break; TEST_SF(s, gsl_sf_cos_pi_e, (ix+fx, &r), exact, TEST_TOL0, GSL_SUCCESS); ix -= 101.0; exact = -exact; } return s; }
{ "alphanum_fraction": 0.5888946015, "avg_line_length": 24.5580808081, "ext": "c", "hexsha": "c650903db12129c2bb0f7d5a7c1e6a8a56545f29", "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/specfunc/test_sincos_pi.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/specfunc/test_sincos_pi.c", "max_line_length": 84, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/test_sincos_pi.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": 3879, "size": 9725 }
#pragma once #include <cstring> #include <string> #include <sstream> #include <iomanip> #include <array> #include <string_view> #include <iterator> #include <random> #include <memory> #include <functional> #include <type_traits> #include <assert.h> #include <gsl/span> #ifdef _WIN32 #include <objbase.h> #elif defined(__linux__) || defined(__unix__) #include <uuid/uuid.h> #elif defined(__APPLE__) #include <CoreFoundation/CFUUID.h> #endif namespace uuids { namespace detail { template <typename TChar> constexpr inline unsigned char hex2char(TChar const ch) { if (ch >= static_cast<TChar>('0') && ch <= static_cast<TChar>('9')) return static_cast<unsigned char>(ch - static_cast<TChar>('0')); if (ch >= static_cast<TChar>('a') && ch <= static_cast<TChar>('f')) return static_cast<unsigned char>(10 + ch - static_cast<TChar>('a')); if (ch >= static_cast<TChar>('A') && ch <= static_cast<TChar>('F')) return static_cast<unsigned char>(10 + ch - static_cast<TChar>('A')); return 0; } template <typename TChar> constexpr inline bool is_hex(TChar const ch) { return (ch >= static_cast<TChar>('0') && ch <= static_cast<TChar>('9')) || (ch >= static_cast<TChar>('a') && ch <= static_cast<TChar>('f')) || (ch >= static_cast<TChar>('A') && ch <= static_cast<TChar>('F')); } template <typename TChar> constexpr inline unsigned char hexpair2char(TChar const a, TChar const b) { return static_cast<unsigned char>((hex2char(a) << 4) | hex2char(b)); } class sha1 { public: using digest32_t = uint32_t[5]; using digest8_t = uint8_t[20]; static constexpr unsigned int block_bytes = 64; inline static uint32_t left_rotate(uint32_t value, size_t const count) { return (value << count) ^ (value >> (32 - count)); } sha1() { reset(); } void reset() { m_digest[0] = 0x67452301; m_digest[1] = 0xEFCDAB89; m_digest[2] = 0x98BADCFE; m_digest[3] = 0x10325476; m_digest[4] = 0xC3D2E1F0; m_blockByteIndex = 0; m_byteCount = 0; } void process_byte(uint8_t octet) { this->m_block[this->m_blockByteIndex++] = octet; ++this->m_byteCount; if (m_blockByteIndex == block_bytes) { this->m_blockByteIndex = 0; process_block(); } } void process_block(void const * const start, void const * const end) { const uint8_t* begin = static_cast<const uint8_t*>(start); const uint8_t* finish = static_cast<const uint8_t*>(end); while (begin != finish) { process_byte(*begin); begin++; } } void process_bytes(void const * const data, size_t const len) { const uint8_t* block = static_cast<const uint8_t*>(data); process_block(block, block + len); } uint32_t const * get_digest(digest32_t digest) { size_t const bitCount = this->m_byteCount * 8; process_byte(0x80); if (this->m_blockByteIndex > 56) { while (m_blockByteIndex != 0) { process_byte(0); } while (m_blockByteIndex < 56) { process_byte(0); } } else { while (m_blockByteIndex < 56) { process_byte(0); } } process_byte(0); process_byte(0); process_byte(0); process_byte(0); process_byte(static_cast<unsigned char>((bitCount >> 24) & 0xFF)); process_byte(static_cast<unsigned char>((bitCount >> 16) & 0xFF)); process_byte(static_cast<unsigned char>((bitCount >> 8) & 0xFF)); process_byte(static_cast<unsigned char>((bitCount) & 0xFF)); memcpy(digest, m_digest, 5 * sizeof(uint32_t)); return digest; } uint8_t const * get_digest_bytes(digest8_t digest) { digest32_t d32; get_digest(d32); size_t di = 0; digest[di++] = (uint8_t)((d32[0] >> 24) & 0xFF); digest[di++] = (uint8_t)((d32[0] >> 16) & 0xFF); digest[di++] = (uint8_t)((d32[0] >> 8) & 0xFF); digest[di++] = (uint8_t)((d32[0]) & 0xFF); digest[di++] = (uint8_t)((d32[1] >> 24) & 0xFF); digest[di++] = (uint8_t)((d32[1] >> 16) & 0xFF); digest[di++] = (uint8_t)((d32[1] >> 8) & 0xFF); digest[di++] = (uint8_t)((d32[1]) & 0xFF); digest[di++] = (uint8_t)((d32[2] >> 24) & 0xFF); digest[di++] = (uint8_t)((d32[2] >> 16) & 0xFF); digest[di++] = (uint8_t)((d32[2] >> 8) & 0xFF); digest[di++] = (uint8_t)((d32[2]) & 0xFF); digest[di++] = (uint8_t)((d32[3] >> 24) & 0xFF); digest[di++] = (uint8_t)((d32[3] >> 16) & 0xFF); digest[di++] = (uint8_t)((d32[3] >> 8) & 0xFF); digest[di++] = ((d32[3]) & 0xFF); digest[di++] = (uint8_t)((d32[4] >> 24) & 0xFF); digest[di++] = (uint8_t)((d32[4] >> 16) & 0xFF); digest[di++] = (uint8_t)((d32[4] >> 8) & 0xFF); digest[di++] = (uint8_t)((d32[4]) & 0xFF); return digest; } private: void process_block() { uint32_t w[80]; for (size_t i = 0; i < 16; i++) { w[i] = (m_block[i * 4 + 0] << 24); w[i] |= (m_block[i * 4 + 1] << 16); w[i] |= (m_block[i * 4 + 2] << 8); w[i] |= (m_block[i * 4 + 3]); } for (size_t i = 16; i < 80; i++) { w[i] = left_rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1); } uint32_t a = m_digest[0]; uint32_t b = m_digest[1]; uint32_t c = m_digest[2]; uint32_t d = m_digest[3]; uint32_t e = m_digest[4]; for (std::size_t i = 0; i < 80; ++i) { uint32_t f = 0; uint32_t k = 0; if (i < 20) { f = (b & c) | (~b & d); k = 0x5A827999; } else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; } else { f = b ^ c ^ d; k = 0xCA62C1D6; } uint32_t temp = left_rotate(a, 5) + f + e + k + w[i]; e = d; d = c; c = left_rotate(b, 30); b = a; a = temp; } m_digest[0] += a; m_digest[1] += b; m_digest[2] += c; m_digest[3] += d; m_digest[4] += e; } private: digest32_t m_digest; uint8_t m_block[64]; size_t m_blockByteIndex; size_t m_byteCount; }; } // UUID format https://tools.ietf.org/html/rfc4122 // Field NDR Data Type Octet # Note // -------------------------------------------------------------------------------------------------------------------------- // time_low unsigned long 0 - 3 The low field of the timestamp. // time_mid unsigned short 4 - 5 The middle field of the timestamp. // time_hi_and_version unsigned short 6 - 7 The high field of the timestamp multiplexed with the version number. // clock_seq_hi_and_reserved unsigned small 8 The high field of the clock sequence multiplexed with the variant. // clock_seq_low unsigned small 9 The low field of the clock sequence. // node character 10 - 15 The spatially unique node identifier. // -------------------------------------------------------------------------------------------------------------------------- // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | time_low | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | time_mid | time_hi_and_version | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |clk_seq_hi_res | clk_seq_low | node (0-1) | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | node (2-5) | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // indicated by a bit pattern in octet 8, marked with N in xxxxxxxx-xxxx-xxxx-Nxxx-xxxxxxxxxxxx enum class uuid_variant { // NCS backward compatibility (with the obsolete Apollo Network Computing System 1.5 UUID format) // N bit pattern: 0xxx // > the first 6 octets of the UUID are a 48-bit timestamp (the number of 4 microsecond units of time since 1 Jan 1980 UTC); // > the next 2 octets are reserved; // > the next octet is the "address family"; // > the final 7 octets are a 56-bit host ID in the form specified by the address family ncs, // RFC 4122/DCE 1.1 // N bit pattern: 10xx // > big-endian byte order rfc, // Microsoft Corporation backward compatibility // N bit pattern: 110x // > little endian byte order // > formely used in the Component Object Model (COM) library microsoft, // reserved for possible future definition // N bit pattern: 111x reserved }; struct uuid_error : public std::runtime_error { explicit uuid_error(std::string_view message) : std::runtime_error(message.data()) { } explicit uuid_error(char const * message) : std::runtime_error(message) { } }; // indicated by a bit pattern in octet 6, marked with M in xxxxxxxx-xxxx-Mxxx-xxxx-xxxxxxxxxxxx enum class uuid_version { none = 0, // only possible for nil or invalid uuids time_based = 1, // The time-based version specified in RFC 4122 dce_security = 2, // DCE Security version, with embedded POSIX UIDs. name_based_md5 = 3, // The name-based version specified in RFS 4122 with MD5 hashing random_number_based = 4, // The randomly or pseudo-randomly generated version specified in RFS 4122 name_based_sha1 = 5 // The name-based version specified in RFS 4122 with SHA1 hashing }; struct uuid { struct uuid_const_iterator { using self_type = uuid_const_iterator; using value_type = uint8_t; using reference = uint8_t const &; using pointer = uint8_t const *; using iterator_category = std::random_access_iterator_tag; using difference_type = ptrdiff_t; protected: pointer ptr = nullptr; size_t index = 0; bool compatible(self_type const & other) const noexcept { return ptr == other.ptr; } public: constexpr explicit uuid_const_iterator(pointer ptr, size_t const index) : ptr(ptr), index(index) { } uuid_const_iterator(uuid_const_iterator const & o) = default; uuid_const_iterator& operator=(uuid_const_iterator const & o) = default; ~uuid_const_iterator() = default; self_type & operator++ () { if (index >= 16) throw std::out_of_range("Iterator cannot be incremented past the end of the data."); ++index; return *this; } self_type operator++ (int) { self_type tmp = *this; ++*this; return tmp; } bool operator== (self_type const & other) const { assert(compatible(other)); return index == other.index; } bool operator!= (self_type const & other) const { return !(*this == other); } reference operator* () const { if (ptr == nullptr) throw std::bad_function_call(); return *(ptr + index); } reference operator-> () const { if (ptr == nullptr) throw std::bad_function_call(); return *(ptr + index); } uuid_const_iterator() = default; self_type & operator--() { if (index <= 0) throw std::out_of_range("Iterator cannot be decremented past the beginning of the data."); --index; return *this; } self_type operator--(int) { self_type tmp = *this; --*this; return tmp; } self_type operator+(difference_type offset) const { self_type tmp = *this; return tmp += offset; } self_type operator-(difference_type offset) const { self_type tmp = *this; return tmp -= offset; } difference_type operator-(self_type const & other) const { assert(compatible(other)); return (index - other.index); } bool operator<(self_type const & other) const { assert(compatible(other)); return index < other.index; } bool operator>(self_type const & other) const { return other < *this; } bool operator<=(self_type const & other) const { return !(other < *this); } bool operator>=(self_type const & other) const { return !(*this < other); } self_type & operator+=(difference_type const offset) { if (static_cast<difference_type>(index) + offset < 0 || static_cast<difference_type>(index) + offset > 16) throw std::out_of_range("Iterator cannot be incremented outside data bounds."); index += offset; return *this; } self_type & operator-=(difference_type const offset) { return *this += -offset; } value_type const & operator[](difference_type const offset) const { return (*(*this + offset)); } }; using value_type = uint8_t; public: constexpr uuid() noexcept : data({}) {}; explicit uuid(gsl::span<value_type, 16> bytes) { std::copy(std::cbegin(bytes), std::cend(bytes), std::begin(data)); } template<typename ForwardIterator> explicit uuid(ForwardIterator first, ForwardIterator last) { if (std::distance(first, last) == 16) std::copy(first, last, std::begin(data)); } constexpr uuid_variant variant() const noexcept { if ((data[8] & 0x80) == 0x00) return uuid_variant::ncs; else if ((data[8] & 0xC0) == 0x80) return uuid_variant::rfc; else if ((data[8] & 0xE0) == 0xC0) return uuid_variant::microsoft; else return uuid_variant::reserved; } constexpr uuid_version version() const noexcept { if ((data[6] & 0xF0) == 0x10) return uuid_version::time_based; else if ((data[6] & 0xF0) == 0x20) return uuid_version::dce_security; else if ((data[6] & 0xF0) == 0x30) return uuid_version::name_based_md5; else if ((data[6] & 0xF0) == 0x40) return uuid_version::random_number_based; else if ((data[6] & 0xF0) == 0x50) return uuid_version::name_based_sha1; else return uuid_version::none; } constexpr std::size_t size() const noexcept { return 16; } constexpr bool is_nil() const noexcept { for (size_t i = 0; i < data.size(); ++i) if (data[i] != 0) return false; return true; } void swap(uuid & other) noexcept { data.swap(other.data); } constexpr uuid_const_iterator begin() const noexcept { return uuid_const_iterator(&data[0], 0); } constexpr uuid_const_iterator end() const noexcept { return uuid_const_iterator(&data[0], 16); } inline gsl::span<std::byte const, 16> as_bytes() const { return gsl::span<std::byte const, 16>(reinterpret_cast<std::byte const*>(data.data()), 16); } template <typename TChar> static uuid from_string(TChar const * const str, size_t const size) { TChar digit = 0; bool firstDigit = true; int hasBraces = 0; size_t index = 0; std::array<uint8_t, 16> data{ { 0 } }; if (str == nullptr || size == 0) throw uuid_error{ "Wrong uuid format" }; if (str[0] == static_cast<TChar>('{')) hasBraces = 1; if (hasBraces && str[size - 1] != static_cast<TChar>('}')) throw uuid_error{ "Wrong uuid format" }; for (size_t i = hasBraces; i < size - hasBraces; ++i) { if (str[i] == static_cast<TChar>('-')) continue; if (index >= 16 || !detail::is_hex(str[i])) { throw uuid_error{ "Wrong uuid format" }; } if (firstDigit) { digit = str[i]; firstDigit = false; } else { data[index++] = detail::hexpair2char(digit, str[i]); firstDigit = true; } } if (index < 16) { throw uuid_error{ "Wrong uuid format" }; } return uuid{ std::cbegin(data), std::cend(data) }; } static uuid from_string(std::string_view str) { return from_string(str.data(), str.size()); } static uuid from_string(std::wstring_view str) { return from_string(str.data(), str.size()); } private: std::array<value_type, 16> data{ { 0 } }; friend bool operator==(uuid const & lhs, uuid const & rhs) noexcept; friend bool operator<(uuid const & lhs, uuid const & rhs) noexcept; template <class Elem, class Traits> friend std::basic_ostream<Elem, Traits> & operator<<(std::basic_ostream<Elem, Traits> &s, uuid const & id); }; inline bool operator== (uuid const& lhs, uuid const& rhs) noexcept { return lhs.data == rhs.data; } inline bool operator!= (uuid const& lhs, uuid const& rhs) noexcept { return !(lhs == rhs); } inline bool operator< (uuid const& lhs, uuid const& rhs) noexcept { return lhs.data < rhs.data; } template <class Elem, class Traits> std::basic_ostream<Elem, Traits> & operator<<(std::basic_ostream<Elem, Traits> &s, uuid const & id) { return s << std::hex << std::setfill(static_cast<Elem>('0')) << std::setw(2) << (int)id.data[0] << std::setw(2) << (int)id.data[1] << std::setw(2) << (int)id.data[2] << std::setw(2) << (int)id.data[3] << '-' << std::setw(2) << (int)id.data[4] << std::setw(2) << (int)id.data[5] << '-' << std::setw(2) << (int)id.data[6] << std::setw(2) << (int)id.data[7] << '-' << std::setw(2) << (int)id.data[8] << std::setw(2) << (int)id.data[9] << '-' << std::setw(2) << (int)id.data[10] << std::setw(2) << (int)id.data[11] << std::setw(2) << (int)id.data[12] << std::setw(2) << (int)id.data[13] << std::setw(2) << (int)id.data[14] << std::setw(2) << (int)id.data[15]; } inline std::string to_string(uuid const & id) { std::stringstream sstr; sstr << id; return sstr.str(); } inline std::wstring to_wstring(uuid const & id) { std::wstringstream sstr; sstr << id; return sstr.str(); } inline void swap(uuids::uuid & lhs, uuids::uuid & rhs) { lhs.swap(rhs); } class uuid_system_generator { public: using result_type = uuid; uuid operator()() { #ifdef _WIN32 GUID newId; ::CoCreateGuid(&newId); std::array<uint8_t, 16> bytes = { { (unsigned char)((newId.Data1 >> 24) & 0xFF), (unsigned char)((newId.Data1 >> 16) & 0xFF), (unsigned char)((newId.Data1 >> 8) & 0xFF), (unsigned char)((newId.Data1) & 0xFF), (unsigned char)((newId.Data2 >> 8) & 0xFF), (unsigned char)((newId.Data2) & 0xFF), (unsigned char)((newId.Data3 >> 8) & 0xFF), (unsigned char)((newId.Data3) & 0xFF), newId.Data4[0], newId.Data4[1], newId.Data4[2], newId.Data4[3], newId.Data4[4], newId.Data4[5], newId.Data4[6], newId.Data4[7] } }; return uuid{ std::begin(bytes), std::end(bytes) }; #elif defined(__linux__) || defined(__unix__) uuid_t id; uuid_generate(id); std::array<uint8_t, 16> bytes = { { id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11], id[12], id[13], id[14], id[15] } }; return uuid{ std::begin(bytes), std::end(bytes) }; #elif defined(__APPLE__) auto newId = CFUUIDCreate(NULL); auto bytes = CFUUIDGetUUIDBytes(newId); CFRelease(newId); std::array<uint8_t, 16> arrbytes = { { bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, bytes.byte4, bytes.byte5, bytes.byte6, bytes.byte7, bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11, bytes.byte12, bytes.byte13, bytes.byte14, bytes.byte15 } }; return uuid{ std::begin(arrbytes), std::end(arrbytes) }; #elif return uuid{}; #endif } }; template <typename UniformRandomNumberGenerator> class basic_uuid_random_generator { public: using result_type = uuid; basic_uuid_random_generator() :generator(new UniformRandomNumberGenerator) { std::random_device rd; generator->seed(rd()); } explicit basic_uuid_random_generator(UniformRandomNumberGenerator& gen) : generator(&gen, [](auto) {}) {} explicit basic_uuid_random_generator(UniformRandomNumberGenerator* gen) : generator(gen, [](auto) {}) {} uuid operator()() { uint8_t bytes[16]; for (int i = 0; i < 16; i += 4) *reinterpret_cast<uint32_t*>(bytes + i) = distribution(*generator); // variant must be 10xxxxxx bytes[8] &= 0xBF; bytes[8] |= 0x80; // version must be 0100xxxx bytes[6] &= 0x4F; bytes[6] |= 0x40; return uuid{std::begin(bytes), std::end(bytes)}; } private: std::uniform_int_distribution<uint32_t> distribution; std::shared_ptr<UniformRandomNumberGenerator> generator; }; using uuid_random_generator = basic_uuid_random_generator<std::mt19937>; class uuid_name_generator { public: using result_type = uuid; explicit uuid_name_generator(uuid const& namespace_uuid) noexcept : nsuuid(namespace_uuid) {} uuid operator()(std::string_view name) { reset(); process_characters(name.data(), name.size()); return make_uuid(); } uuid operator()(std::wstring_view name) { reset(); process_characters(name.data(), name.size()); return make_uuid(); } private: void reset() { hasher.reset(); uint8_t bytes[16]; std::copy(std::begin(nsuuid), std::end(nsuuid), bytes); hasher.process_bytes(bytes, 16); } template <typename char_type, typename = std::enable_if_t<std::is_integral<char_type>::value>> void process_characters(char_type const * const characters, size_t const count) { for (size_t i = 0; i < count; i++) { uint32_t c = characters[i]; hasher.process_byte(static_cast<unsigned char>((c >> 0) & 0xFF)); hasher.process_byte(static_cast<unsigned char>((c >> 8) & 0xFF)); hasher.process_byte(static_cast<unsigned char>((c >> 16) & 0xFF)); hasher.process_byte(static_cast<unsigned char>((c >> 24) & 0xFF)); } } void process_characters(const char * const characters, size_t const count) { hasher.process_bytes(characters, count); } uuid make_uuid() { detail::sha1::digest8_t digest; hasher.get_digest_bytes(digest); // variant must be 0b10xxxxxx digest[8] &= 0xBF; digest[8] |= 0x80; // version must be 0b0101xxxx digest[6] &= 0x5F; digest[6] |= 0x50; return uuid{ digest, digest + 16 }; } private: uuid nsuuid; detail::sha1 hasher; }; } namespace std { template <> struct hash<uuids::uuid> { using argument_type = uuids::uuid; using result_type = std::size_t; result_type operator()(argument_type const &uuid) const { std::hash<std::string> hasher; return static_cast<result_type>(hasher(uuids::to_string(uuid))); } }; }
{ "alphanum_fraction": 0.4908955502, "avg_line_length": 30.7265446224, "ext": "h", "hexsha": "23c82c09c067e2bf151a90c7540ac38a9c1641e3", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-03-23T23:47:21.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-20T02:42:10.000Z", "max_forks_repo_head_hexsha": "c3089d2827938d450d2d2b1391ff57aee82eddd3", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "cogment/cogment-orchestrator", "max_forks_repo_path": "third_party/uuid.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c3089d2827938d450d2d2b1391ff57aee82eddd3", "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": "cogment/cogment-orchestrator", "max_issues_repo_path": "third_party/uuid.h", "max_line_length": 130, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c3089d2827938d450d2d2b1391ff57aee82eddd3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "cogment/cogment-orchestrator", "max_stars_repo_path": "third_party/uuid.h", "max_stars_repo_stars_event_max_datetime": "2021-07-08T15:05:27.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-20T01:32:43.000Z", "num_tokens": 6735, "size": 26855 }
#pragma once #include <boost/variant.hpp> //#include <gsl/span> #include <gsl/gsl> #include <boost/system/system_error.hpp> #include <boost/asio/read.hpp> #include <boost/asio/write.hpp> namespace mothbus { template<class ...T> using variant = boost::variant<T...>; template<class T>//, std::ptrdiff_t Extent=gsl::dynamic_extent> using span = gsl::span<T>;//, Extent>; using byte = gsl::byte; template <typename SyncWriteStream, typename ConstBufferSequence> inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers) { return boost::asio::write(s, buffers); } template <typename SyncWriteStream, typename ConstBufferSequence, typename ErrorCode> inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, ErrorCode& ec) { return boost::asio::write(s, buffers, ec); } template <typename SyncReadStream, typename MutableBufferSequence> inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers) { return boost::asio::read(s, buffers); } template <typename SyncReadStream, typename MutableBufferSequence, typename ErrorCode> inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, ErrorCode& ec) { return boost::asio::read(s, buffers, ec); } template <typename SyncReadStream, typename MutableBufferSequence, typename ReadHandler> inline void async_read(SyncReadStream& s, const MutableBufferSequence& buffers, ReadHandler&& handler) { boost::asio::async_read(s, buffers, std::forward<ReadHandler>(handler)); } class modbus_exception// : public std::runtime_error { public: modbus_exception(int error_code): error_code(error_code) {} int error_code; }; }
{ "alphanum_fraction": 0.7530791789, "avg_line_length": 27.5, "ext": "h", "hexsha": "f34f0930f2ee4b33eaa1b17122bc711112fcbfc9", "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": "0bd94c2878b4be04c968c2a60835b6aa3a085516", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ChrisBFX/mothbus", "max_forks_repo_path": "include/mothbus/mothbus.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0bd94c2878b4be04c968c2a60835b6aa3a085516", "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": "ChrisBFX/mothbus", "max_issues_repo_path": "include/mothbus/mothbus.h", "max_line_length": 103, "max_stars_count": 5, "max_stars_repo_head_hexsha": "0bd94c2878b4be04c968c2a60835b6aa3a085516", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ChrisBFX/mothbus", "max_stars_repo_path": "include/mothbus/mothbus.h", "max_stars_repo_stars_event_max_datetime": "2021-12-07T14:32:25.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-02T10:39:24.000Z", "num_tokens": 410, "size": 1705 }
#pragma once #include <gsl/gsl> #include "halley/utils/utils.h" #include "halley/data_structures/vector.h" #include "halley/file/path.h" #include "halley/data_structures/maybe.h" 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 void writeFile(const Path& path, const String& data); static Bytes readFile(const Path& path); static 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); }; class ScopedTemporaryFile final { public: ScopedTemporaryFile(); ScopedTemporaryFile(const String& extension); ~ScopedTemporaryFile(); ScopedTemporaryFile(const ScopedTemporaryFile& other) = delete; ScopedTemporaryFile(ScopedTemporaryFile&& other) noexcept; ScopedTemporaryFile& operator=(const ScopedTemporaryFile& other) = delete; ScopedTemporaryFile& operator=(ScopedTemporaryFile&& other) noexcept; const Path& getPath() const; private: std::optional<Path> path; }; }
{ "alphanum_fraction": 0.7478991597, "avg_line_length": 26.8709677419, "ext": "h", "hexsha": "f9d8dc6c2dee2aa3f762ac3a8a1ac440940b53db", "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": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "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": "amrezzd/halley", "max_issues_repo_path": "src/tools/tools/include/halley/tools/file/filesystem.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "amrezzd/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": 390, "size": 1666 }
/** */ #ifndef _INOUT_APER_H #define _INOUT_APER_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include <gsl/gsl_vector.h> #include "aXe_grism.h" #include "aXe_utils.h" #include "aXe_errors.h" #include "spc_cfg.h" #include "spc_trace_functions.h" #define APER_MAXLINE 14 extern int nbeams_from_char_array2 (char **apers, int num); extern gsl_vector_int * nbeams_from_char_array (char **apers, int num); extern int object_list_to_file (object * const *oblist, char *filename, int leaveout_ignored); extern int get_beam_from_aper_file (char *filename, int aperID, int beamID,beam * b); extern gsl_vector_int * aper_file_aperlist (char *filename); extern int aper_file_apernum (char *filename); extern object * get_aperture_from_aper_file (char *filename, int aperID); extern object ** file_to_object_list (char filename[], observation * obs); extern char ** return_next_aperture(FILE *input); extern object ** file_to_object_list_seq (char filename[], observation * obs); extern int find_object_in_object_list(object **oblist, const int ID); extern beam find_beam_in_object_list(object **oblist, const int objID, const int beamID); extern beam * find_beamptr_in_object_list(object **oblist, const int objID, const int beamID); extern void refurbish_object_list(object **oblist, const int new_default, const int old_value, const int new_value); extern int object_list_size(object **oblist); extern int get_beamspec_size(object **oblist); #endif
{ "alphanum_fraction": 0.727216367, "avg_line_length": 22.095890411, "ext": "h", "hexsha": "0dec138306cedb0be5dec3bd65262a25bfe19ef6", "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/inout_aper.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/inout_aper.h", "max_line_length": 74, "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/inout_aper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 402, "size": 1613 }
// // Copyright (c) 2017 Michele Segata <msegata@disi.unitn.it> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // #ifndef MATRIX_UTILS_H #define MATRIX_UTILS_H #include "Array.hh" #include <vector> #ifdef ENABLE_DISCRETIZATION #include <gsl/gsl_matrix.h> #endif /** * Copies the values of a matrix over a portion of another * @param dst destination matrix * @param src source matrix * @param row row index of the destination matrix * @param col column index of the destination matrix */ void set_submatrix(Matrix<double> &dst, const Matrix<double> &src, int row, int col); /** * Copies the values of a vector over a portion of another * @param dst destination vector * @param src source vector * @param pos index of the destination vector */ void set_subvector(Vector<double> &dst, const Vector<double> &src, int pos); /** * Generates a diagonal matrix by using a vector as the diagonal * @param src vector to use as the diagonal * @return the diagonal matrix */ Matrix<double> diag(const Vector<double> &src); /** * Returns a diagonal square matrix * @param n square matrix size * @param v value to put on the diagonal * @return the diagonal matrix */ Matrix<double> diag(int n, double v = 1); /** * Returns an identity matrix * @param n square matrix size * @return the identity matrix */ Matrix<double> identity(int n); /** * Given a list of comma separated values, returns a vector * @param v string of comma separated values * @param length number of elements in the string * @return the vector including the parsed values */ Vector<double> get_vector(const std::string &v, int length); /** * Returns a vector of all zeros * @param length length of the vector * @return a zero vector of the specified length */ Vector<double> zero_vector(int length); /** * Given a string of comma separated values, returns a matrix of the parsed * values * @param m string of comma separated values. the number of elements must be * nrow * ncol * @param nrow number of rows * @param ncol number of columns * @return the matrix of parsed values */ Matrix<double> get_matrix(const std::string &m, int nrow, int ncol); /** * Matrix transpose * @param m the matrix to be transposed * @return the transposed matrix */ Matrix<double> transpose(const Matrix<double> &m); /** * Given a matrix of a particular size, changes the size of the matrix * without touching the existing values. New matrix values are initialized * with zeros * @param m matrix to be enlarged in place * @param r new number of rows * @param c new number of columns */ void extend_matrix(Matrix<double> &m, int r, int c); /** * Given a vector of a particular size, changes the size of the vector * without touching the existing values. New vector values are initialized * with zeros * @param v vector to be enlarged in place * @param n new size */ void extend_vector(Vector<double> &v, int n); /** * Merges two matrices together by appending the rows of the second matrix to * the rows of the first * @param a first matrix * @param b second matrix * @return a matrix where a and b are merged by rows */ Matrix<double> bind_matrices(const Matrix<double> &a, const Matrix<double> &b); /** * Merges two vectors together * @param a first vector * @param b second vector * @return a vector composed by a and b */ Vector<double> bind_vectors(const Vector<double> &a, const Vector<double> &b); /** * Performs the product of two matrices * @param a first matrix * @param b second matrix * @return the matrix product between a and b if the matrices are compatible, * an empty matrix otherwise */ Matrix<double> multiply(const Matrix<double> &a, const Matrix<double> &b); /** * Performs the product of a matrix and a vector * @param a matrix * @param b vector * @return the product between a and b if the matrices are compatible, * an empty matrix otherwise */ Matrix<double> multiply(const Matrix<double> &a, const Vector<double> &b); /** * Performs the product of a matrix and a vector * @param a matrix * @param b vector * @return the product between a and b if the matrices are compatible, * an empty matrix otherwise */ Matrix<double> multiply(const Matrix<double> &a, const double *b); /** * Given a matrix, the function computes the powers of such a matrix and * stores it in a vector of matrices, where the index is the exponent. The * results is thus a vector v[i] = A^i for i = 0 ... n * @param a input matrix * @param n maximum exponent * @return the vector of matrices A^i */ std::vector<Matrix<double> > get_powers(const Matrix<double> &a, int n); /** * Pretty prints a matrix to stdout * @param a the matrix to print * @param name optional name to print */ void pretty_print_matrix(const Matrix<double_t> &a, const std::string &name=""); /** * Copies a vector inside another. If the sizes don't match, then the source * vector is repeated multiple time in the destination vector. For example, * if the source vector is [1, 2, 3] and the destination vector has length 8, * then the destination will be filled with [1, 2, 3, 1, 2, 3, 1, 2] * @param dst destination vector * @param src source vector */ void copy_vector(Vector<double>& dst, const Vector<double> &src); /** * Copies a vector inside another. The size of the destination vector must be * larger or equal than the one of the source vector * @param dst destination vector * @param src source vector */ void copy_vector(double *dst, const Vector<double> &src); /** * Copies a vector inside another. The size of the destination vector must be * larger or equal than the one of the source vector * @param dst destination vector * @param src source vector */ void copy_vector(double *dst, const Matrix<double> &src); /** * Returns a portion of a vector * @param src source vector * @param from start index * @param length elements to copy * @return the subvector of elements going from src[from] to src[from+length-1] */ Vector<double> subvector(const Vector<double> &src, int from, int length); #ifdef ENABLE_DISCRETIZATION /** * Converts a gsl matrix into a Matrix<double> object * @param m pointer to gsl_matrix * @return converted matrix */ Matrix<double> from_gsl(const gsl_matrix *m); /** * Converts a Matrix<double> object into a gsl matrix. This function allocates * the memory for the gsl matrix and it is a duty of the user to free the * memory via the gsl_matrix_free() method * @param m matrix object * @return converted matrix */ gsl_matrix *to_gsl(const Matrix<double> &m); #endif #endif //MATRIX_UTILS_H
{ "alphanum_fraction": 0.7203706265, "avg_line_length": 30.6398305085, "ext": "h", "hexsha": "7d471a1b8658b95ca2a618f1f4d435de9234a108", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-03-12T11:16:32.000Z", "max_forks_repo_forks_event_min_datetime": "2018-02-03T15:22:44.000Z", "max_forks_repo_head_hexsha": "a030421cbbcca8d3eb5e50b7cd0335bac0057fb0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "michele-segata/mpclib", "max_forks_repo_path": "src/matrix_utils.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a030421cbbcca8d3eb5e50b7cd0335bac0057fb0", "max_issues_repo_issues_event_max_datetime": "2018-07-22T13:19:19.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-03T15:23:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "michele-segata/mpclib", "max_issues_repo_path": "src/matrix_utils.h", "max_line_length": 80, "max_stars_count": 22, "max_stars_repo_head_hexsha": "a030421cbbcca8d3eb5e50b7cd0335bac0057fb0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "michele-segata/mpclib", "max_stars_repo_path": "src/matrix_utils.h", "max_stars_repo_stars_event_max_datetime": "2022-01-16T17:50:54.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:20:31.000Z", "num_tokens": 1734, "size": 7231 }
/* Copyright [2017-2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef MCAS_HSTORE_HEAP_MM_EPHEMERAL_H #define MCAS_HSTORE_HEAP_MM_EPHEMERAL_H #include "heap_ephemeral.h" #include "hstore_config.h" #include "histogram_log2.h" #include "hop_hash_log.h" #include <mm_plugin_itf.h> #include "persistent.h" #include <ccpm/interfaces.h> /* ownership_callback, (IHeap_expandable, region_vector_t) */ #include <common/byte_span.h> #include <common/string_view.h> #include <nupm/region_descriptor.h> #include <gsl/span> #include <algorithm> /* min, swap */ #include <cstddef> /* size_t */ #include <vector> struct heap_mm_ephemeral : private heap_ephemeral { private: using byte_span = common::byte_span; /* Although the mm heap tracks managed regions, its definition of a managed * region probably differs from what hstore needs: * * The hstore managed region must include the hstore metadata area, as that * must be include in the "maanged regions" returned through the kvstore * interface. * * The mm heap managed region cannot include the hstore metadata area, as * that would allow the allocator to use the area for memory allocation. * * Therefore, heap_mr_ephemeral keeps its own copy of the managed regions. */ nupm::region_descriptor _managed_regions; protected: using heap_ephemeral::_alloc_mutex; protected: using hist_type = util::histogram_log2<std::size_t>; hist_type _hist_alloc; hist_type _hist_inject; hist_type _hist_free; private: /* Rca_LB seems not to allocate at or above about 2GiB. Limit reporting to 16 GiB. */ static constexpr unsigned hist_report_upper_bound = 24U; static constexpr unsigned log_min_alignment = 3U; /* log (sizeof(void *)) */ static_assert(sizeof(void *) == 1U << log_min_alignment, "log_min_alignment does not match sizeof(void *)"); protected: virtual void add_managed_region_to_heap(byte_span r_heap) = 0; public: template <bool B> void write_hist(const byte_span pool_) const { static bool suppress = false; if ( ! suppress ) { hop_hash_log<B>::write(LOG_LOCATION, "pool ", ::base(pool_)); std::size_t lower_bound = 0; auto limit = std::min(std::size_t(hist_report_upper_bound), _hist_alloc.data().size()); for ( unsigned i = log_min_alignment; i != limit; ++i ) { const std::size_t upper_bound = 1ULL << i; hop_hash_log<B>::write(LOG_LOCATION , "[", lower_bound, "..", upper_bound, "): " , _hist_alloc.data()[i], " ", _hist_inject.data()[i], " ", _hist_free.data()[i] , " " ); lower_bound = upper_bound; } suppress = true; } } using common::log_source::debug_level; explicit heap_mm_ephemeral( unsigned debug_level , nupm::region_descriptor managed_regions ); virtual ~heap_mm_ephemeral() {} virtual std::size_t allocated() const = 0; virtual std::size_t capacity() const = 0; virtual void allocate(persistent_t<void *> &p, std::size_t sz, std::size_t alignment) = 0; virtual std::size_t free(persistent_t<void *> &p_, std::size_t sz_) = 0; virtual void free_tracked(const void *p, std::size_t sz) = 0; nupm::region_descriptor get_managed_regions() const { return _managed_regions; } nupm::region_descriptor set_managed_regions(nupm::region_descriptor n) { using std::swap; swap(n, _managed_regions); return n; } void add_managed_region(byte_span r_full, byte_span r_heap); void reconstitute_managed_region( const byte_span r_full , const byte_span r_heap , ccpm::ownership_callback_t f ); virtual void reconstitute_managed_region_to_heap(byte_span r_heap, ccpm::ownership_callback_t f) = 0; virtual bool is_crash_consistent() const = 0; virtual bool can_reconstitute() const = 0; }; #endif
{ "alphanum_fraction": 0.7328298324, "avg_line_length": 33.3622047244, "ext": "h", "hexsha": "0709690f47969b99c824ab37e8e937ab4bbeba0c", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_path": "src/components/store/hstore/src/heap_mm_ephemeral.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_path": "src/components/store/hstore/src/heap_mm_ephemeral.h", "max_line_length": 109, "max_stars_count": 60, "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_path": "src/components/store/hstore/src/heap_mm_ephemeral.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "num_tokens": 1105, "size": 4237 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C header for the geometric coefficients entering the response for LIGO-VIRGO detectors. * * */ #ifndef _LLVGEOMETRY_H #define _LLVGEOMETRY_H #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" /********************************************************/ /**************** Type definitions **********************/ /* Enumerator for the detector selector and network selector */ typedef enum {LHO, LLO, VIRGO} Detectortag; typedef enum {L, H, V, LH, LV, HV, LHV} Networktag; /*************************************************************/ /**************** Geometrical constants **********************/ /** * \name LIGO Hanford Observatory 4km Interferometric Detector constants * The following constants describe the location and geometry of the * LIGO Hanford Observatory 4km Interferometric Detector. */ #define LAL_LHO_4K_DETECTOR_NAME "LHO_4k" /**< LHO_4k detector name string */ #define LAL_LHO_4K_DETECTOR_PREFIX "H1" /**< LHO_4k detector prefix string */ #define LAL_LHO_4K_DETECTOR_LONGITUDE_RAD -2.08405676917 /**< LHO_4k vertex longitude (rad) */ #define LAL_LHO_4K_DETECTOR_LATITUDE_RAD 0.81079526383 /**< LHO_4k vertex latitude (rad) */ #define LAL_LHO_4K_DETECTOR_ELEVATION_SI 142.554 /**< LHO_4k vertex elevation (m) */ #define LAL_LHO_4K_DETECTOR_ARM_X_AZIMUTH_RAD 5.65487724844 /**< LHO_4k x arm azimuth (rad) */ #define LAL_LHO_4K_DETECTOR_ARM_Y_AZIMUTH_RAD 4.08408092164 /**< LHO_4k y arm azimuth (rad) */ #define LAL_LHO_4K_DETECTOR_ARM_X_ALTITUDE_RAD -0.00061950000 /**< LHO_4k x arm altitude (rad) */ #define LAL_LHO_4K_DETECTOR_ARM_Y_ALTITUDE_RAD 0.00001250000 /**< LHO_4k y arm altitude (rad) */ #define LAL_LHO_4K_DETECTOR_ARM_X_MIDPOINT_SI 1997.54200000000 /**< LHO_4k x arm midpoint (m) */ #define LAL_LHO_4K_DETECTOR_ARM_Y_MIDPOINT_SI 1997.52200000000 /**< LHO_4k y arm midpoint (m) */ #define LAL_LHO_4K_VERTEX_LOCATION_X_SI -2.16141492636e+06 /**< LHO_4k x-component of vertex location in Earth-centered frame (m) */ #define LAL_LHO_4K_VERTEX_LOCATION_Y_SI -3.83469517889e+06 /**< LHO_4k y-component of vertex location in Earth-centered frame (m) */ #define LAL_LHO_4K_VERTEX_LOCATION_Z_SI 4.60035022664e+06 /**< LHO_4k z-component of vertex location in Earth-centered frame (m) */ #define LAL_LHO_4K_ARM_X_DIRECTION_X -0.22389266154 /**< LHO_4k x-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_LHO_4K_ARM_X_DIRECTION_Y 0.79983062746 /**< LHO_4k y-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_LHO_4K_ARM_X_DIRECTION_Z 0.55690487831 /**< LHO_4k z-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_LHO_4K_ARM_Y_DIRECTION_X -0.91397818574 /**< LHO_4k x-component of unit vector pointing along y arm in Earth-centered frame */ #define LAL_LHO_4K_ARM_Y_DIRECTION_Y 0.02609403989 /**< LHO_4k y-component of unit vector pointing along y arm in Earth-centered frame */ #define LAL_LHO_4K_ARM_Y_DIRECTION_Z -0.40492342125 /**< LHO_4k z-component of unit vector pointing along y arm in Earth-centered frame */ /** * \name LIGO Livingston Observatory 4km Interferometric Detector constants * The following constants describe the location and geometry of the * LIGO Livingston Observatory 4km Interferometric Detector. */ #define LAL_LLO_4K_DETECTOR_NAME "LLO_4k" /**< LLO_4k detector name string */ #define LAL_LLO_4K_DETECTOR_PREFIX "L1" /**< LLO_4k detector prefix string */ #define LAL_LLO_4K_DETECTOR_LONGITUDE_RAD -1.58430937078 /**< LLO_4k vertex longitude (rad) */ #define LAL_LLO_4K_DETECTOR_LATITUDE_RAD 0.53342313506 /**< LLO_4k vertex latitude (rad) */ #define LAL_LLO_4K_DETECTOR_ELEVATION_SI -6.574 /**< LLO_4k vertex elevation (m) */ #define LAL_LLO_4K_DETECTOR_ARM_X_AZIMUTH_RAD 4.40317772346 /**< LLO_4k x arm azimuth (rad) */ #define LAL_LLO_4K_DETECTOR_ARM_Y_AZIMUTH_RAD 2.83238139666 /**< LLO_4k y arm azimuth (rad) */ #define LAL_LLO_4K_DETECTOR_ARM_X_ALTITUDE_RAD -0.00031210000 /**< LLO_4k x arm altitude (rad) */ #define LAL_LLO_4K_DETECTOR_ARM_Y_ALTITUDE_RAD -0.00061070000 /**< LLO_4k y arm altitude (rad) */ #define LAL_LLO_4K_DETECTOR_ARM_X_MIDPOINT_SI 1997.57500000000 /**< LLO_4k x arm midpoint (m) */ #define LAL_LLO_4K_DETECTOR_ARM_Y_MIDPOINT_SI 1997.57500000000 /**< LLO_4k y arm midpoint (m) */ #define LAL_LLO_4K_VERTEX_LOCATION_X_SI -7.42760447238e+04 /**< LLO_4k x-component of vertex location in Earth-centered frame (m) */ #define LAL_LLO_4K_VERTEX_LOCATION_Y_SI -5.49628371971e+06 /**< LLO_4k y-component of vertex location in Earth-centered frame (m) */ #define LAL_LLO_4K_VERTEX_LOCATION_Z_SI 3.22425701744e+06 /**< LLO_4k z-component of vertex location in Earth-centered frame (m) */ #define LAL_LLO_4K_ARM_X_DIRECTION_X -0.95457412153 /**< LLO_4k x-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_LLO_4K_ARM_X_DIRECTION_Y -0.14158077340 /**< LLO_4k y-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_LLO_4K_ARM_X_DIRECTION_Z -0.26218911324 /**< LLO_4k z-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_LLO_4K_ARM_Y_DIRECTION_X 0.29774156894 /**< LLO_4k x-component of unit vector pointing along y arm in Earth-centered frame */ #define LAL_LLO_4K_ARM_Y_DIRECTION_Y -0.48791033647 /**< LLO_4k y-component of unit vector pointing along y arm in Earth-centered frame */ #define LAL_LLO_4K_ARM_Y_DIRECTION_Z -0.82054461286 /**< LLO_4k z-component of unit vector pointing along y arm in Earth-centered frame */ /** * \name VIRGO 3km Interferometric Detector constants * The following constants describe the location and geometry of the * VIRGO 3km Interferometric Detector. */ #define LAL_VIRGO_DETECTOR_NAME "VIRGO" /**< VIRGO detector name string */ #define LAL_VIRGO_DETECTOR_PREFIX "V1" /**< VIRGO detector prefix string */ #define LAL_VIRGO_DETECTOR_LONGITUDE_RAD 0.18333805213 /**< VIRGO vertex longitude (rad) */ #define LAL_VIRGO_DETECTOR_LATITUDE_RAD 0.76151183984 /**< VIRGO vertex latitude (rad) */ #define LAL_VIRGO_DETECTOR_ELEVATION_SI 51.884 /**< VIRGO vertex elevation (m) */ #define LAL_VIRGO_DETECTOR_ARM_X_AZIMUTH_RAD 0.33916285222 /**< VIRGO x arm azimuth (rad) */ #define LAL_VIRGO_DETECTOR_ARM_Y_AZIMUTH_RAD 5.05155183261 /**< VIRGO y arm azimuth (rad) */ #define LAL_VIRGO_DETECTOR_ARM_X_ALTITUDE_RAD 0.00000000000 /**< VIRGO x arm altitude (rad) */ #define LAL_VIRGO_DETECTOR_ARM_Y_ALTITUDE_RAD 0.00000000000 /**< VIRGO y arm altitude (rad) */ #define LAL_VIRGO_DETECTOR_ARM_X_MIDPOINT_SI 1500.00000000000 /**< VIRGO x arm midpoint (m) */ #define LAL_VIRGO_DETECTOR_ARM_Y_MIDPOINT_SI 1500.00000000000 /**< VIRGO y arm midpoint (m) */ #define LAL_VIRGO_VERTEX_LOCATION_X_SI 4.54637409900e+06 /**< VIRGO x-component of vertex location in Earth-centered frame (m) */ #define LAL_VIRGO_VERTEX_LOCATION_Y_SI 8.42989697626e+05 /**< VIRGO y-component of vertex location in Earth-centered frame (m) */ #define LAL_VIRGO_VERTEX_LOCATION_Z_SI 4.37857696241e+06 /**< VIRGO z-component of vertex location in Earth-centered frame (m) */ #define LAL_VIRGO_ARM_X_DIRECTION_X -0.70045821479 /**< VIRGO x-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_VIRGO_ARM_X_DIRECTION_Y 0.20848948619 /**< VIRGO y-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_VIRGO_ARM_X_DIRECTION_Z 0.68256166277 /**< VIRGO z-component of unit vector pointing along x arm in Earth-centered frame */ #define LAL_VIRGO_ARM_Y_DIRECTION_X -0.05379255368 /**< VIRGO x-component of unit vector pointing along y arm in Earth-centered frame */ #define LAL_VIRGO_ARM_Y_DIRECTION_Y -0.96908180549 /**< VIRGO y-component of unit vector pointing along y arm in Earth-centered frame */ #define LAL_VIRGO_ARM_Y_DIRECTION_Z 0.24080451708 /**< VIRGO z-component of unit vector pointing along y arm in Earth-centered frame */ #if 0 { /* so that editors will match succeeding brace */ #elif defined(__cplusplus) } #endif #endif /* _LLVGEOMETRY_H */
{ "alphanum_fraction": 0.7263982103, "avg_line_length": 66.2222222222, "ext": "h", "hexsha": "603a15f6760a287f3389f34c866f23ce37c291a8", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "LLVsim/LLVgeometry.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_path": "LLVsim/LLVgeometry.h", "max_line_length": 149, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "LLVsim/LLVgeometry.h", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 2654, "size": 8940 }
/* igraph library headers */ #include <igraph/igraph.h> /* gsl headers */ #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_histogram2d.h> /*headers for hashing */ #include "uthash.h" /* hash table macros */ #include <stddef.h> /* offset of */ /* headers for argument parsing */ #include <stdlib.h> #include <error.h> #include <argp.h> /* errno.h has declaration of errno variable */ #include <errno.h> /** more stuff for argument parsing **/ const char *argp_program_version = "dynet 0.2"; const char *argp_program_bug_address = "<ebo@mail.utexas.edu>"; static char doc[] = "DyNet -- simulator for disease spreading\ on dynamic networks\ \vThe simulator allows the network to relax from an initial\ degree distribuion toward a target degree distribution. The\ condition that degree correlations are close to zero is used\ to determine the types of edges that are added and deleted.\ No further documentation is available yet."; /* A description of the arguments we accept. */ static char args_doc[] = " "; /* Keys for options without short-options */ #define OPT_ABORT 1 /* macros and functions for network generation*/ #define DYNET_EXP (int) 1 #define DYNET_REG (int) 2 #define DYNET_PARETO (int) 3 #define DYNET_ER (int) 4 /* The options we understand. */ static struct argp_option options[] = { {0, 0, 0, 0, "General Options"}, {"verbose", 'v', 0, 0, "Produce verbose output"}, {"quiet", 'q', 0, 0, "Don't produce any outpu"}, {"silent", 's', 0, OPTION_ALIAS}, {"output", 'o', "FILE", 0, "Output to FILE instead of standard output"}, {0, 0, 0, 0, "Network Model Options"}, {"network_rate", 'n', "RATE", 0, "Network degree distribution approaches equilibirium " "at rate RATE (default 0.4)"}, {"network_tension", 'k', "RATE", 0, "Network degree correlations are removed in proportion to " "thier size at rate RATE (default 50)"}, {"network_size", 'N', "COUNT", 0, "the network is made to have about COUNT (default 10000) nodes "}, {"network_type", 'y', "INTEGER_CODE", 0, "INTEGER_CODE (default 2) determines the limiting degree distribution:" " 1==exponential, 2==regular, 3==Pareto, 4==Poisson"}, {"par1", 'm', "RATIONAL", 0, "If network_type is in {1, 2, 4}, RATIONAL (default 4) is " " the mean of the degree distribution. If network_type is 3," " RATIONAL is A in definition of Pareto pdf. in GSL " "documentation"}, {"par2", 'b', "RATIONAL", 0, "If network_type is PARETO, RATIONAL is B in the definition of" " the Pareto pdf in the GSL documentation"}, {0, 0, 0, 0, "Disease Model Options"}, {"trans_rate", 't', "RATE", 0, "Disease moves at rate RATE (default 2) across an edge"}, {"recov_rate", 'r', "RATE", 0, "Infected nodes reacover at rate RATE (default 1)"}, {"interval", 'i', "LENGTH", 0, "State variables are printed to output at every LENGTH\ (default 0.05) time units"}, {"epsilon", 'e', "FRACTION", 0, "Initial fraction FRACTION " "(default 0.1) of edges from suscetible nodes pointing " "to infected nodes"}, {"finish_time", 'f', "LENGTH", 0, "Simulation time will start " "at zero and run LENGTH (default 5) time units"}, {0, 0, 0, 0, "Evolutionary Model Options"}, {"sample_fraction", 'p', "FRACTION", 0, "FRACTION (default 0.001) nodes in virus gene tree are selected" "for inclusion in newick output"}, {0} }; /* maximum rate allowed in arguments */ #define MAX_RATE 10000. /* Used by `main' to communicate with `parse_opt'. */ struct arguments { int silent, verbose; /* `-s', `-v' */ char *output_file; /* FILE arg to `--output' */ double trans_rate; /* RATE arg to `--trans_rate' */ double recov_rate; /* RATE arg to `--recov_rate' */ double interval; /* LENGTH arg to `--interval' */ double epsilon; /* FRACTION arg to `--epsilon' */ double finish_time; /* LENGTH arg to `--finish_time' */ double network_rate; /* RATE arg to `--network_rate' */ double network_tension; /* RATE arg to `--network_tension' */ int network_size; /* COUNT arg to `--network_size' */ int network_type; /* INTEGER_CODE arg to `--network_type' */ double par1; /* RATIONAL arg to `--par1' */ double par2; /* RATIONAL arg to `--par2' */ double sample_fraction; /* FRACTION arg to `--sample_fraction' */ }; /* Parse a single option. */ static error_t parse_opt (int key, char *arg, struct argp_state *state) { /* Get the INPUT argument from `argp_parse', which we know is a pointer to our arguments structure. */ struct arguments *arguments = (struct arguments *) state->input; switch (key) { case 'q': case 's': arguments->silent = 1; break; case 'v': arguments->verbose = 1; break; case 'o': arguments->output_file = arg; break; case 't': arguments->trans_rate = strtod (arg, NULL); if (arguments->trans_rate < 0 || arguments->trans_rate > MAX_RATE) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "trans_rate=%g, should be in [0, %g]", arguments->trans_rate, MAX_RATE); } break; case 'r': arguments->recov_rate = strtod (arg, NULL); if (arguments->recov_rate < 0 || arguments->recov_rate > MAX_RATE) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "recov_rate=%g, should be in [0, %g]", arguments->recov_rate, MAX_RATE); } break; case 'i': arguments->interval = strtod (arg, NULL); if (arguments->interval <= 0 || arguments->interval > 1e2) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "interval=%g, should be in [0, %g]", arguments->recov_rate, 1e2); } break; case 'e': arguments->epsilon = strtod (arg, NULL); if (arguments->epsilon < 0 || arguments->epsilon > 1) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "epsilon=%g, should be in [0, 1]", arguments->epsilon); } break; case 'f': arguments->finish_time = strtod (arg, NULL); if (arguments->finish_time < 0 || arguments->finish_time > 100) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "finish_time=%g, should be in [0, 100]", arguments->finish_time); } break; case 'n': arguments->network_rate = strtod (arg, NULL); if (arguments->network_rate < 0 || arguments->network_rate > MAX_RATE) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "network_rate=%g, should be in [0, %g]", arguments->network_rate, MAX_RATE); } break; case 'k': arguments->network_tension = strtod (arg, NULL); if (arguments->network_tension < 0 || arguments->network_tension > MAX_RATE) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "network_tension=%g, should be in [0, %g]", arguments->network_tension, MAX_RATE); } break; case 'N': arguments->network_size = atoi (arg); if (arguments->network_size < 1 || arguments->network_size > 1e6) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "network_size=%d, should be in [1, %d]", arguments->network_size, (int) 1e6); } break; case 'p': arguments->sample_fraction = strtod (arg, NULL); if (arguments->sample_fraction < 0 || arguments->sample_fraction > 1) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "sample_fraction =%g, should be in [0, 1]", arguments->sample_fraction); } break; case 'y': arguments->network_type = atoi (arg); if (arguments->network_type != DYNET_REG && arguments->network_type != DYNET_ER && arguments->network_type != DYNET_PARETO && arguments->network_type != DYNET_EXP) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "network type =%d, should be in {%d, %d, %d, %d}", arguments->network_type, DYNET_EXP, DYNET_REG, DYNET_PARETO, DYNET_ER); } break; case 'm': arguments->par1 = strtod (arg, NULL); if (arguments->par1< 0 || arguments->par1 > 100) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "par1 =%g, should be in [0, 100]", arguments->par1); } break; case 'b': arguments->par2 = strtod (arg, NULL); if (arguments->par2< 1 || arguments->par2 > 100) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "par2 =%g, should be in [1, 100]", arguments->par2); } break; case ARGP_KEY_ARG: /* Too many arguments. */ argp_usage (state); break; default: return ARGP_ERR_UNKNOWN; } return 0; } /* Our argp parser. */ static struct argp argp = { options, parse_opt, args_doc, doc }; /*structure for events in simulation */ #define MUTATE (char) 'm' #define INFECT (char) 'i' #define RECOVER (char) 'r' #define EDGE_ADD (char) 'a' #define EDGE_DEL (char) 'd' struct event { /* key is an aggregate of event code, ego_id, and alter_id */ /* TODO use separate structures for different event_codes */ char event_code; int ego_id; /* The type of the last part of the key must be consistent * with the keylen calculation below */ int alter_id; int i_deg; int j_deg; int N_ij; /* number of edges between degree i and j nodes */ double rate; int strain_id; int phylo_id; /* UT_hash_handle member makes structure a hashtable */ UT_hash_handle hh; }; /** genealogy struct **/ struct node { int abv; int ndes; float time; int flag; }; /*hash table */ struct event *event_table = NULL; /*keylen holds the size of the hash key */ unsigned keylen; /* sum of rate of all events in hash table */ double rate_sum; /* array to track state of the each node */ char *node_states; /* arrays to track states of nodes of each degree class */ int *S_k; int *I_k; /* maximum number of stochastic sim steps */ #define STEPMAX 50000 /*maximum degree correlations allowed */ #define MAXREDGE 0.05 /* SIR model parameters */ double trans_rate; double recov_rate; /* OUTSIDE is the ID of any host outside of population that transmit * the initial infections */ #define OUTSIDE -99 /* rounding doubles to nearest integer */ /* source http://www.cs.tut.fi/~jkorpela/round.html */ #define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) /** function prototypes **/ int infect (int infector_id, int infectee_id, igraph_t *g, igraph_vector_t *degree); int recover (int recoverer_id, igraph_t *g, igraph_vector_t *degree); void delete_all_events (); void delete_event (struct event *ev); void delete_event_by_key (char event_code, int ego_id, int alter_id); void print_rates (struct event *event_table); int check_event_by_key (char event_code, int ego_id, int alter_id); int check_infector_events (int infector_id, igraph_t *g); double get_rate_sum (); double get_infection_rate_sum (); int neighbor_state_count (int susceptible_id, int *num_S_nb, int *num_I_nb, igraph_t *g); int get_num_infected (int max_degree); int get_approx_case_prod_variance (double trans, double gen_time, int num_infected, double *icpm, double *icpv, igraph_t *g); double get_approx_case_prod_mean (double gen_time, int num_infected); FILE *open_output (const char *filename); int close_file (FILE *f); void prtree3 (struct node *ptree, int num_nodes, FILE** f_tree, FILE** f_coal_times, FILE** f_samp_times); int sequence_to_graph(int *sequence, int num_nodes, igraph_t *g); int get_degree_seq (int *resulting_degree_seq, int num_nodes, double par1, double par2, int net_type); /** functions **/ void delete_all_events () { struct event *current_event; while (event_table) { current_event = event_table; HASH_DEL (event_table, current_event); free (current_event); } } void print_rates (struct event *event_table) { struct event *ev; unsigned z = 0; for (ev = event_table; ev != NULL; ev = (struct event *) ev->hh.next) { printf ("rate is %g\n", ev->rate); } } void delete_event (struct event *ev) { HASH_DEL (event_table, ev); free (ev); } int check_event_by_key (char event_code, int ego_id, int alter_id) { struct event *ev1, ev2; memset (&ev2, 0, sizeof (struct event)); ev2.event_code = event_code; ev2.ego_id = ego_id; ev2.alter_id = alter_id; HASH_FIND (hh, event_table, &ev2.event_code, keylen, ev1); if (!ev1) { error_at_line (0, errno, __FILE__, __LINE__, "failed to find hash with key %c_%d_%d", event_code, ego_id, alter_id); } else if (event_code == INFECT && ev1->rate != trans_rate) { error_at_line (0, 0, __FILE__, __LINE__, "infection event with rate %g, should be %g", ev1->rate, trans_rate); } else if (event_code == RECOVER && ev1->rate != recov_rate) { error_at_line (0, 0, __FILE__, __LINE__, "recovery event with rate %g, should be %g", ev1->rate, recov_rate); } return 0; } void delete_event_by_key (char event_code, int ego_id, int alter_id) { struct event *ev1, ev2; memset (&ev2, 0, sizeof (struct event)); ev2.event_code = event_code; ev2.ego_id = ego_id; ev2.alter_id = alter_id; HASH_FIND (hh, event_table, &ev2.event_code, keylen, ev1); if (!ev1) { fprintf (stderr, "error: %s: %d: failed to find hash key \n", __FILE__, __LINE__); exit (1); } HASH_DEL (event_table, ev1); free (ev1); } int main (int argc, char *argv[]) { /* index for loops */ size_t i; /* value returned by functions called */ int ret = 0; /* contact network */ igraph_t g; /* number of hosts of degree i*/ int N_i; /* vector with degree of each host */ igraph_vector_t degree; /* maximum degree of nodes in contact network */ int max_degree; /* initial degree sequence of nodes in contact network */ int *initial_degree_seq; /* element I of degree_dist contains the number of nodes * with degree I */ gsl_histogram *degree_dist; /* counter of number of errors */ errno = 0; /* epsilon is the initial fraction of infected nodes */ double epsilon; /* I_initial holds the number of initially infected hosts in * based on epsilon */ int I_initial; /* array holding IDS of initially infected hosts */ int *I_initial_IDs; int *all_nodes_IDs; /* time in simulation */ double time = 0; /* count of steps in simulation */ int step_count = 0; double rand; double cum_density, p_I, p_S; struct arguments arguments; /* Default values for variable set by arguments */ arguments.silent = 0; arguments.verbose = 0; arguments.output_file = (char *) "-"; arguments.trans_rate = 2; arguments.recov_rate = 1; arguments.interval = 0.05; arguments.epsilon = 0.1; arguments.finish_time = 5; arguments.network_rate = 0.4; arguments.network_tension = 50; arguments.network_size = 10000; arguments.network_type = DYNET_REG; arguments.par1 = 4; arguments.par2 = 1; arguments.sample_fraction = 0.001; /*TODO add option to use high tension to eliminate degree correlations * in initial network before beginning simulation */ struct event *ev, *ev1, ev2; unsigned z; argp_parse (&argp, argc, argv, 0, 0, &arguments); fprintf (stdout, "trans_rate = %g\nrecov_rate = %g\ninterval = %g\n" "epsilon = %g\nfinish_time = %g\nnetwork_rate = %g\n" "network_tension = %g\nnetwork_size = %d\nnetwork_type = %d\n" "par1 = %g\npar2 = %g\n" "sample_fraction= %g\nOUTPUT_FILE = %s\nVERBOSE = %s\nSILENT = %s\n", arguments.trans_rate, arguments.recov_rate, arguments.interval, arguments.epsilon, arguments.finish_time, arguments.network_rate, arguments.network_tension, arguments.network_size, arguments.network_type, arguments.par1, arguments.par2, arguments.sample_fraction, arguments.output_file, arguments.verbose ? "yes" : "no", arguments.silent ? "yes" : "no"); #ifdef DYNET_DEBUG fprintf (stdout, "dynet debugging level = %d\n", DYNET_DEBUG); #endif /* node_hoste[I] contains the id of the genealogy node in host with id I having the greatest time */ int *node_host; struct node *ptree; ptree = (struct node *) calloc ((unsigned) (2 * arguments.network_size), sizeof (struct node)); if (!ptree) { fprintf (stderr, "Error: %s: %d: Malloc of array failed\n", __FILE__, __LINE__); return (1); } node_host = (int *) calloc ((unsigned) (arguments.network_size), sizeof (int)); if (!node_host) { fprintf (stderr, "Error: %s: %d: Malloc of array failed\n", __FILE__, __LINE__); return (1); } int gen_ind = 0; trans_rate = arguments.trans_rate; recov_rate = arguments.recov_rate; epsilon = arguments.epsilon; keylen = offsetof (struct event, alter_id) + sizeof (int) - offsetof (struct event, event_code); initial_degree_seq = (int *) malloc ((arguments.network_size) * sizeof (int)); if (!initial_degree_seq) { fprintf (stderr, "Error: %s: %d: Malloc failed\n", __FILE__, __LINE__); return (1); } if (arguments.network_type != DYNET_ER) { get_degree_seq (initial_degree_seq, arguments.network_size, arguments.par1, arguments.par2, arguments.network_type); sequence_to_graph (initial_degree_seq, arguments.network_size, &g); } else { igraph_erdos_renyi_game (&g, IGRAPH_ERDOS_RENYI_GNM, arguments.network_size, round (arguments.network_size * arguments.par1 /2), 0, 0); } /* get the degree distribution */ igraph_vector_init (&degree, 0); igraph_degree (&g, &degree, igraph_vss_all(), IGRAPH_ALL, IGRAPH_LOOPS); max_degree = (int) igraph_vector_max (&degree); degree_dist = gsl_histogram_alloc (max_degree + 1); gsl_histogram_set_ranges_uniform (degree_dist, -0.5, max_degree + 0.5); for (i = 0; i < igraph_vector_size (&degree); i++) { gsl_histogram_increment (degree_dist, VECTOR (degree)[i]); } // open filestreams and print headers FILE *fp, *of; if (arguments.output_file == "-") { of = stdout; } else { of = open_output (arguments.output_file); } fprintf (of, " time "); for (i = 0; i <= max_degree; i++) { N_i = round(gsl_histogram_get (degree_dist, i)); if (N_i) { fprintf (of, "N_%05u S_%05u I_%05u ", i + 1, i + 1, i + 1); } } fprintf (of, " incidence num_infected gen_time icpv icpm vm_ratio\n"); /* fprintf (of, "r_edge p_I p_S\n"); */ const gsl_rng_type *T; gsl_rng *rng; /* create a generator by the environment variable * GSL_RNG_TYPE */ gsl_rng_env_setup (); T = gsl_rng_default; rng = gsl_rng_alloc (T); double write_point = 0; /* put intial infection and recovery event into table */ node_states = (char *) malloc ((arguments.network_size + 1) * sizeof (char)); if (!node_states) { fprintf (stderr, "Error: %s: %d: Malloc of array failed\n", __FILE__, __LINE__); return (1); } memset (node_states, 's', arguments.network_size * sizeof (char)); node_states[arguments.network_size * sizeof (char)] = '\0'; S_k = (int *) malloc ((max_degree + 1) * sizeof (int)); if (!S_k) { fprintf (stderr, "Error: %s: %d: Malloc of array failed\n", __FILE__, __LINE__); return (1); } for (i = 0; i <= max_degree; i++) { S_k[i] = gsl_histogram_get (degree_dist, i); } I_k = (int *) calloc ((max_degree + 1), sizeof (int)); if (!I_k) { fprintf (stderr, "Error: %s: %d: Malloc of array failed\n", __FILE__, __LINE__); return (1); } /* TODO select host at random from network */ infect (OUTSIDE, 0, &g, &degree); ptree->time = 0; node_host[0] = 0; gen_ind++; while (time < arguments.finish_time && rate_sum > 0) { step_count++; #if DYNET_DEBUG > 0 /* check that rate sum is being updated correctly */ if (fabs (get_rate_sum () - rate_sum) > 1e-6) { error_at_line (EXIT_FAILURE, 0, __FILE__, __LINE__, "rate_sum - get_rate_sum ()= %g\n", rate_sum - get_rate_sum ()); } /* check that counts of susceptibles and infecteds are * correct when summed over all degree classes */ int Scount, Icount, Scount2, Icount2; Scount = Icount = Scount2 = Icount2 = 0; for (i = 0; node_states[i] != 0; i++) { if (node_states[i] == 's') Scount++; else if (node_states[i] == 'i') Icount++; } for (i = 0; i <= max_degree; i++) { Scount2 += S_k[i]; Icount2 += I_k[i]; } if (Scount != Scount2 || Icount != Icount2) { fprintf (stderr, "Debug: %s: %d: counts don't match\n", __FILE__, __LINE__); fprintf (stderr, "\tSc=%d Sc2=%d, Ic=%d, Ic2=%d\n", Scount, Scount2, Icount, Icount2); } /* Check that counts of Susceptiable and infecteds by degree * class are being updated correctly. */ int deg, *I_k_check, *S_k_check; I_k_check = (int *) calloc ((max_degree + 1), sizeof (int)); if (!I_k_check) { error_at_line (EXIT_FAILURE, errno, __FILE__, __LINE__, "I_k_check"); } S_k_check = (int *) calloc ((max_degree + 1), sizeof (int)); if (!S_k_check) { error_at_line (EXIT_FAILURE, errno, __FILE__, __LINE__, "S_k_check"); } for (i = 0; i < arguments.network_size; i++) { if (node_states[i] == 's') { deg = VECTOR (degree)[i]; S_k_check[deg]++; } if (node_states[i] == 'i') { deg = VECTOR (degree)[i]; I_k_check[deg]++; } } error_message_count = 0; for (i = 0; i <= max_degree; i++) { if (S_k_check[i] != S_k[i]) { error_at_line (0, 0, __FILE__, __LINE__, "S_k[%d] = %d, should be %d", i, S_k[i], S_k_check[i]); } if (I_k_check[i] != I_k[i]) { error_at_line (0, 0, __FILE__, __LINE__, "I_k[%d] = %d, should be %d", i, I_k[i], I_k_check[i]); } } if (error_message_count != 0) { error (EXIT_FAILURE, 0, "%u errors found", error_message_count); } free (I_k_check); free (S_k_check); /* calculate p.I, i.e. fraction of arcs from susctpibles * going to infecteds */ int num_S_nb, num_I_nb, sum_S_nb, sum_I_nb, sum_nb, susceptible_id; sum_nb = sum_S_nb = sum_I_nb = 0; for (i = 0; i < arguments.network_size; i++) { if (node_states[i] == 's') { num_S_nb = num_I_nb = 0; sum_nb += VECTOR (degree)[i]; susceptible_id = i; neighbor_state_count (susceptible_id, &num_S_nb, &num_I_nb, &g); sum_S_nb += num_S_nb; sum_I_nb += num_I_nb; } } p_S = (double) sum_S_nb / sum_nb; p_I = (double) sum_I_nb / sum_nb; #endif #if DYNET_DEBUG > 1 /* Check for all events in the hash table, making sure the * hash table is consistent with the current state of the network. */ error_message_count = 0; int infector_id; int event_count = 0; /*first check for and count one edge addition or deletion event that * can always happen */ memset (&ev2, 0, sizeof (struct event)); ev2.event_code = EDGE_ADD; HASH_FIND (hh, event_table, &ev2.event_code, keylen, ev1); if (ev1) { event_count++; } else { ev2.event_code = EDGE_DEL; HASH_FIND (hh, event_table, &ev2.event_code, keylen, ev1); if (ev1) { event_count++; } } for (i = 0; i < arguments.network_size; i++) { if (node_states[i] == 'i') { infector_id = i; event_count += check_infector_events (infector_id, &g); } } int hash_count = HASH_COUNT (event_table); if (error_message_count != 0) { error (EXIT_FAILURE, 0, "%u events are missing in hash table " "or are present but occuring at the wrong rate", error_message_count); } if (hash_count != event_count) { error (EXIT_FAILURE, 0, "%d extra events in hash table\n", hash_count - event_count); } #endif #if DYNET_DEBUG_TEST == 1 if (step_count == 10) { /* set the rate of the first event in the table to 0 */ fprintf (stderr, "Changing the rate of an event to test debugging tests\n"); event_table->rate = 0; } #endif #if DYNET_DEBUG_TEST == 2 if (step_count == 70) { /* add an extra event to the table */ fprintf (stderr, "Adding an event to test debugging tests\n"); ev1 = (struct event *) malloc (sizeof (struct event)); if (!ev1) { fprintf (stderr, "Error: %s: %d: malloc failed\n", __FILE__, __LINE__); return (1); } memset (ev1, 0, sizeof (struct event)); ev1->event_code = INFECT; ev1->rate = 0; HASH_ADD (hh, event_table, event_code, keylen, ev1); } #endif #if DYNET_DEBUG_TEST == 3 if (step_count == 50) { /* remove an event at beginning of the table */ fprintf (stderr, "Removing an event to test debugging tests\n"); delete_event (event_table); } #endif #if DYNET_DEBUG_TEST == 4 if (step_count == 50) { /* give two events rates with compensating erros */ fprintf (stderr, "Swapping event rates to test debugging tests\n"); ev = event_table; ev->rate += 0.001; ev = (struct event *) ev->hh.next; ev->rate -= 0.001; } #endif #if DYNET_DEBUG_TEST == 5 if (step_count == 50) { /* change event code */ fprintf (stderr, "Changing event code of an event to test debugging tests\n"); ev = event_table; ev->event_code = 'Z'; } #endif if (step_count > STEPMAX) { fprintf (stderr, "Warning: %s: %d: reached STEPMAX, breaking\n", __FILE__, __LINE__); break; } /* determine time of next event */ time += gsl_ran_exponential (rng, 1 / rate_sum); if (time > write_point) { fprintf (of, "%9e ", write_point); write_point += arguments.interval; for (i = 0; i <= max_degree; i++) { int N_i = round(gsl_histogram_get (degree_dist, i)); if (N_i) { fprintf (of, "%7ld %7d %7d ", N_i, S_k[i], I_k[i]); } } double incidence = get_infection_rate_sum(); int num_infected = get_num_infected(max_degree); double gen_time = (double) num_infected / incidence; /* double icpm = get_approx_case_prod_mean (gen_time, num_infected);*/ double icpm; double icpv; get_approx_case_prod_variance (arguments.trans_rate, gen_time, num_infected, &icpm, &icpv, &g); double vm_ratio = icpv / icpm; fprintf (of, "%9e %12d %9e %9e %9e %9e\n", incidence, num_infected, gen_time, icpv, icpm, vm_ratio ); /* fprintf (of, " %g %g\n", p_I, p_S); */ } /* select one event to be next proportionally to it's rate */ rand = rate_sum * gsl_rng_uniform (rng); cum_density = 0; for (ev = event_table; ev != NULL; ev = (struct event *) ev->hh.next) { cum_density += ev->rate; if (cum_density > rand) { break; } } switch (ev->event_code) { case RECOVER: (ptree + gen_ind)->time = time; (ptree + gen_ind)->abv = node_host[ev->ego_id]; node_host[ev->ego_id] = gen_ind; gen_ind++; recover (ev->ego_id, &g, &degree); break; case INFECT: (ptree + gen_ind)->time = time; if (gen_ind > 0) { (ptree + gen_ind)->abv = node_host[ev->ego_id]; } node_host[ev->ego_id] = gen_ind; node_host[ev->alter_id] = gen_ind; gen_ind++; infect (ev->ego_id, ev->alter_id, &g, &degree); break; default: fprintf (stderr, "Error: %s: %d: Illegal event code\n", __FILE__, __LINE__); ret = 1; } if (ret == 1) { break; } } /* end while() */ delete_all_events (); close_file (of); free (node_states); free (S_k); free (I_k); FILE *f_tree = open_output ("tree"); FILE *f_coal_times = open_output ("coal_times"); FILE *f_samp_times = open_output ("samp_times"); int *sampled_pnode_IDs, *all_pnode_IDs; int sample_size = round (arguments.sample_fraction * gen_ind); if (sample_size == 0) { sample_size = 1; } sampled_pnode_IDs = (int *) malloc (sample_size * sizeof (int)); all_pnode_IDs = (int *) malloc (gen_ind * sizeof (int)); if (!sampled_pnode_IDs || !all_pnode_IDs) { fprintf (stderr, "Error: %s: %d: Malloc of array failed\n", __FILE__, __LINE__); return (1); } for (i = 0; i < gen_ind; i++) { all_pnode_IDs[i] = i; (ptree + i)->flag = 0; } gsl_ran_choose (rng, sampled_pnode_IDs, sample_size, all_pnode_IDs, gen_ind, sizeof (int)); for (i = 0; i < sample_size; i++) { int w = sampled_pnode_IDs[i]; (ptree + w)->flag = 1; while (w != 0) { w = (ptree + w)->abv; (ptree + w)->flag = 1; } } prtree3 (ptree, gen_ind, &f_tree, &f_coal_times, &f_samp_times); gsl_rng_free (rng); free (all_pnode_IDs); free (sampled_pnode_IDs); free (ptree); free (initial_degree_seq); gsl_histogram_free (degree_dist); igraph_destroy (&g); close_file (f_tree); close_file (f_coal_times); close_file (f_samp_times); return 0; } int infect (int infector_id, int infectee_id, igraph_t *g, igraph_vector_t *degree) { igraph_vector_t neighbors; int neighbor_id; int infectee_id_deg; struct event *ev1; size_t i; /* update system dynamic variable */ node_states[infectee_id] = 'i'; infectee_id_deg = round (igraph_vector_e (degree, infectee_id)); S_k[infectee_id_deg]--; I_k[infectee_id_deg]++; /* add event of infectee recovering from the table */ ev1 = (struct event *) malloc (sizeof (struct event)); if (!ev1) { fprintf (stderr, "Error: %s: %d: malloc failed\n", __FILE__, __LINE__); return (1); } memset (ev1, 0, sizeof (struct event)); ev1->ego_id = infectee_id; ev1->rate = recov_rate; ev1->event_code = RECOVER; HASH_ADD (hh, event_table, event_code, keylen, ev1); rate_sum += recov_rate; /* add events of infectee infecting susceptible neighbors and * remove events of infected host getting infeced by infectious * neighbors */ igraph_vector_init (&neighbors, 0); igraph_neighbors (g, &neighbors, (igraph_integer_t) infectee_id, IGRAPH_ALL); for (i = 0; i < igraph_vector_size (&neighbors); i++) { neighbor_id = VECTOR (neighbors)[i]; switch (node_states[neighbor_id]) { case 's': ev1 = (struct event *) malloc (sizeof (struct event)); if (!ev1) { fprintf (stderr, "Error: %s: %d: malloc failed\n", __FILE__, __LINE__); return (1); } memset (ev1, 0, sizeof (struct event)); ev1->ego_id = infectee_id; ev1->alter_id = neighbor_id; ev1->rate = trans_rate; ev1->event_code = INFECT; HASH_ADD (hh, event_table, event_code, keylen, ev1); rate_sum += trans_rate; break; case 'i': delete_event_by_key (INFECT, neighbor_id, infectee_id); rate_sum -= trans_rate; break; case 'r': break; default: fprintf (stderr, "Error: %s: %d: invalid state for node\n", __FILE__, __LINE__); exit (1); } } igraph_vector_destroy (&neighbors); return 0; } int neighbor_state_count (int susceptible_id, int *num_S_nb, int *num_I_nb, igraph_t *g) { int neighbor_id; igraph_vector_t neighbors; size_t i; *num_S_nb = 0; *num_I_nb = 0; /* check for event of infector infecting neighbors */ igraph_vector_init (&neighbors, 0); igraph_neighbors (g, &neighbors, susceptible_id, IGRAPH_ALL); for (i = 0; i < igraph_vector_size (&neighbors); i++) { neighbor_id = VECTOR (neighbors)[i]; switch (node_states[neighbor_id]) { case 's': ++*num_S_nb; break; case 'i': ++*num_I_nb; break; case 'r': break; default: fprintf (stderr, "Error: %s: %d: invalid state for node\n", __FILE__, __LINE__); exit (1); } } igraph_vector_destroy (&neighbors); return 0; } int check_infector_events (int infector_id, igraph_t *g) { int neighbor_id, event_count = 0; struct event *ev1; igraph_vector_t neighbors; size_t i; /* check for recovery event */ check_event_by_key (RECOVER, infector_id, 0); event_count++; /* check for event of infector infecting neighbors */ igraph_vector_init (&neighbors, 0); igraph_neighbors (g, &neighbors, infector_id, IGRAPH_ALL); for (i = 0; i < igraph_vector_size (&neighbors); i++) { neighbor_id = VECTOR (neighbors)[i]; switch (node_states[neighbor_id]) { case 's': check_event_by_key (INFECT, infector_id, neighbor_id); event_count++; break; case 'i': break; case 'r': break; default: fprintf (stderr, "Error: %s: %d: invalid state for node\n", __FILE__, __LINE__); exit (1); } } igraph_vector_destroy (&neighbors); return event_count; } int recover (int recoverer_id, igraph_t *g, igraph_vector_t *degree) { int recoverer_id_deg, neighbor_id; struct event *ev1; igraph_vector_t neighbors; size_t i; /* update system dynamic variable */ node_states[recoverer_id] = 'r'; recoverer_id_deg = round (igraph_vector_e (degree, recoverer_id)); I_k[recoverer_id_deg]--; /* remove event of recoverer recovering again */ delete_event_by_key (RECOVER, recoverer_id, 0); rate_sum -= recov_rate; /* remove event of recoverer infecting neighbors */ igraph_vector_init (&neighbors, 0); igraph_neighbors (g, &neighbors, recoverer_id, IGRAPH_ALL); for (i = 0; i < igraph_vector_size (&neighbors); i++) { neighbor_id = VECTOR (neighbors)[i]; switch (node_states[neighbor_id]) { case 's': delete_event_by_key (INFECT, recoverer_id, neighbor_id); rate_sum -= trans_rate; break; case 'i': break; case 'r': break; default: fprintf (stderr, "Error: %s: %d: invalid state for node\n", __FILE__, __LINE__); exit (1); } } igraph_vector_destroy (&neighbors); return 0; } double get_infection_rate_sum () { struct event *ev; double infection_rate_sum = 0; for (ev = event_table; ev != NULL; ev = (struct event *) ev->hh.next) { if ( ev->event_code == INFECT) { infection_rate_sum += ev->rate; } } return infection_rate_sum; } int get_num_infected (int max_degree) { int i; int num_infected = 0; for (i = 0; i <= max_degree; i++) { num_infected += I_k[i]; } return num_infected; } double get_approx_case_prod_mean (double gen_time, int num_infected) { struct event *ev; double mean_sum = 0; /* probability of transmission over edge within GEN_TIME */ double p; /* individual case production mean */ double icpm; for (ev = event_table; ev != NULL; ev = (struct event *) ev->hh.next) { if ( ev->event_code == INFECT) { p = 1 - exp (-ev->rate * gen_time); mean_sum += p; } } icpm = mean_sum / num_infected; return icpm; } int get_approx_case_prod_variance (double trans, double gen_time, int num_infected, double *icpm, double *icpv, igraph_t *g) { int num_S_nb; int num_I_nb; int i; double p; double np; double E_y = 0; double E_y_sq = 0; p = 1 - exp (-trans * gen_time ); for (i = 0; node_states[i] != 0; i++) { if (node_states[i] == 'i') { neighbor_state_count (i, &num_S_nb, &num_I_nb, g); np = num_S_nb * p; E_y += np; E_y_sq += np * (np - p + 1); } } *icpm = (double) E_y / num_infected; *icpv = (double) E_y_sq / num_infected - (*icpm) * (*icpm); return 0; } double get_rate_sum () { struct event *ev; double rate_sum_check = 0; for (ev = event_table; ev != NULL; ev = (struct event *) ev->hh.next) { rate_sum_check += ev->rate; } return rate_sum_check; } void prtree3 (struct node *ptree, int num_nodes, FILE** f_tree, FILE** f_coal_times, FILE** f_samp_times) /* print genealogy tree in Newick format */ /* after Hudson's ms code */ { double t; int i, *descl, *descr, w, tmp; void parens (struct node *ptree, int *descl, int *descr, int noden, FILE** f_tree, FILE** f_coal_times, FILE** f_samp_times); descl = (int *) malloc ((unsigned) (num_nodes) * sizeof (int)); descr = (int *) malloc ((unsigned) (num_nodes) * sizeof (int)); for (i = 0; i < num_nodes; i++) descl[i] = descr[i] = -1; for (i = 1; i < num_nodes; i++) { if (descl[(ptree + i)->abv] == -1 && (ptree + i)->flag == 1) descl[(ptree + i)->abv] = i; else if ((ptree + i)->flag == 1) descr[(ptree + i)->abv] = i; } for (i = 1; i < num_nodes; i++) { if (descl[i] != -1 && descr[i] == -1) { w = descl[i]; while (descr[w] == -1) { tmp = descl[w]; descl[w] = -1; if (tmp == -1) { break; } w = tmp; } if (tmp != -1) { descl[i] = descl[w]; descr[i] = descr[w]; (ptree + descl[i])->abv = i; (ptree + descr[i])->abv = i; (ptree + i)->time = (ptree + w)->time; descl[w] = -1; descr[w] = -1; } if (tmp == -1) { descl[i] = -1; tmp = 0; while (descl[tmp] != i && descr[tmp] != i) { tmp++; } if (descl[tmp] == i) { descl[tmp] = w; (ptree + w)->abv = tmp; } if (descr[tmp] == i) { descr[tmp] = w; (ptree + w)->abv = tmp; } } } } parens (ptree, descl, descr, 1, f_tree, f_coal_times, f_samp_times); fprintf (*f_coal_times, "\n"); fprintf (*f_samp_times, "\n"); free (descl); free (descr); } void parens (struct node *ptree, int *descl, int *descr, int noden, FILE** f_tree, FILE** f_coal_times, FILE** f_samp_times) /* print genealogy tree in Newick format */ /* after Hudson's ms code */ { double time; if (descl[noden] == -1) { time = (ptree + (ptree + noden)->abv)->time - (ptree + noden)->time; fprintf (*f_tree, "%d_%g:%g", noden + 1, (ptree + noden)->time, -1*time); fprintf (*f_samp_times, "%g ", (ptree + noden)->time); } else { fprintf (*f_coal_times, "%g ", (ptree + noden)->time); fprintf (*f_tree, "("); parens (ptree, descl, descr, descl[noden], f_tree, f_coal_times, f_samp_times); fprintf (*f_tree, ","); parens (ptree, descl, descr, descr[noden], f_tree, f_coal_times, f_samp_times); if ((ptree + noden)->abv == 0) { fprintf (*f_tree, ");\n"); } else { time = (ptree + (ptree + noden)->abv)->time - (ptree + noden)->time; fprintf (*f_tree, "):%g", -1*time); } } } int get_degree_seq (int *resulting_degree_seq, int num_nodes, double par1, double par2, int net_type) { int i, degree_sum; double mean_degree; const gsl_rng_type * T; gsl_rng *r; if (net_type == DYNET_PARETO) { gsl_rng_env_setup (); T = gsl_rng_default; r = gsl_rng_alloc (T); degree_sum = 0; for (i = 0; i < num_nodes; i++) { resulting_degree_seq[i] = gsl_ran_pareto (r, par1, par2); degree_sum += resulting_degree_seq[i]; } if (degree_sum % 2 != 0) { fprintf (stderr, "Warning: adjusting degree sequence so that it's even\n"); resulting_degree_seq[i-1]++; } gsl_rng_free (r); } if (net_type == DYNET_EXP) { mean_degree = par1; gsl_rng_env_setup (); T = gsl_rng_default; r = gsl_rng_alloc (T); degree_sum = 0; for (i = 0; i < num_nodes; i++) { resulting_degree_seq[i] = round(gsl_ran_exponential (r, mean_degree)); if (resulting_degree_seq[i] == 0) { resulting_degree_seq[i]++; } degree_sum += resulting_degree_seq[i]; } if (degree_sum % 2 != 0) { fprintf (stderr, "Warning: adjusting degree sequence so that it's even\n"); resulting_degree_seq[i-1]++; } gsl_rng_free (r); } if (net_type == DYNET_REG) { mean_degree = par1; if (mean_degree - (int) mean_degree > 0 || (int) mean_degree *num_nodes % 2 !=0) { fprintf (stderr, "Error: %s: %d:\ mean degree impossible for regular net\n", __FILE__, __LINE__); return 1; } for (i = 0; i <num_nodes; i++) { resulting_degree_seq[i] = (int) mean_degree; } } return 0; } int sequence_to_graph(int *sequence, int num_nodes, igraph_t* g) { /* construct a graph from a degree sequence*/ igraph_vector_t v; size_t i; igraph_vector_init(&v, 0); igraph_vector_resize(&v, num_nodes); for (i=0; i<num_nodes; i++) { VECTOR(v)[i]=sequence[i]; } igraph_degree_sequence_game(g, &v, NULL, IGRAPH_DEGSEQ_VL); /* TODO * figure out how to use these function so that initial graph can have multiple components and isolates igraph_degree_sequence_game(g, &v, NULL, IGRAPH_DEGSEQ_SIMPLE); igraph_simplify (g, 1, 1); */ igraph_vector_destroy(&v); return 0; } FILE * open_output (const char *filename) /* open filename for output; return NULL if problem */ /* after p. 367, C A Reference Manual 5e */ { FILE *f; errno = 0; /* Functions below might choke on a NULL filename. */ if (filename == NULL) filename = ""; f = fopen (filename, "w"); if (f == NULL) { error_at_line (EXIT_FAILURE, errno, __FILE__, __LINE__, "Failed to open file %s", filename); } return f; } int close_file (FILE *f) /* Close file f */ /* after p. 367, C A Reference Manual 5e */ { int s = 0; if (f == NULL) { return 0; } errno = 0; s = fclose (f); if (s == EOF) perror ("Close failed"); return s; }
{ "alphanum_fraction": 0.6085786455, "avg_line_length": 26.1326341764, "ext": "c", "hexsha": "b1245edae049abfb0513e7da0d891f070c9945de", "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": "8e7e5425680a71868edf6ccb02ffb58a857f5c05", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "e3bo/dynet", "max_forks_repo_path": "src/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8e7e5425680a71868edf6ccb02ffb58a857f5c05", "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": "e3bo/dynet", "max_issues_repo_path": "src/main.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "8e7e5425680a71868edf6ccb02ffb58a857f5c05", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "e3bo/dynet", "max_stars_repo_path": "src/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 12431, "size": 42361 }
/* VEGAS_TABLE Version 1. 5/27/16 report issues to Tim Waters, waters@lanl.gov **** Basic code description: Input: An ascii table with entries on a uniform grid of (x,y) values and a (x,y) value for which an interpolated value is sought Output: The interpolated value corresponding to that (x,y) pair **** Detailed description: >> Step 1. Instantiation: The class constructor calls a method to parse an ascii text file which contains an (N+1)x(M+1) table: The first row contains the M values of x. The first column contains the N values of y. The remainder of the table contains the NxM values of z. Here is a simple example of an input file: 4 1e0 1e1 1e2 1e3 1e4 1e-20 2e-20 3e-20 4e-20 1e5 5e-20 6e-20 7e-20 8e-20 1e6 1e-19 2e-19 3e-19 4e-19 1e7 5e-19 6e-19 7e-19 8e-19 1e8 1e-18 2e-18 3e-18 4e-18 In this example, N = 5 and M = 4. M must be specified as the first element. The remaining elements in row 1 are values of the photoionization parameter, xi. The left column below M are the temperature values. The remaining elements are net heating rates that are functions of T and xi. By default, the input file is limited to size 1000 x 1000. To increase this size limit, increase Nmax in the default constructor. >> Step 2. Table initialization: The file parsed above is read into a table, but this is not the actual table used. The actual table is made upon calling an initialization function, and optionally array arguments can be passed specifying the min/max of both T and xi. This may be useful when combining multiple overlapping tables and will allow for flexibility if tables generated from non-uniform grids are needed, although a table-search algorithm has not been implemented. The input table is then reduced to a size that contains only the values between these limits. >> Step 3. Invocation: The code returns the interpolated value of whatever rate was in the input file. The code uses the bicubic and bilinear interpolation algorithms from the GSL library. By default, bicubic is used. Importantly, the code assumes that a nearly uniform grid was produced via x = j*(xmax-xmin)/(M-1) + xmin y = i*(ymax-ymin)/(N-1) + ymin This allows avoiding an expensive table search for the lookup operation. For a uniform grid generated from the above formulas, the table indices for a desired value of (x,y) are i_x = (M-1)*(x - xmin)/(xmax - xmin) i_y = (N-1)*(y - ymin)/(ymax - ymin) Since xstar may slightly modify the grid locations (x,y) originally specified, our lookup operation consists of first guessing that the lookup value indices are (i_x,i_y) and then allowing for some wiggle room by searching 1 index left, right, above, and below upon finding that our guess was incorrect. The code will terminate if this search fails. **** Example usages: 1. Bicubic interpolation on a table that was generated from a log-log spaced grid VEGAS_LUT hc_xstar("input_table.tab","bicubic"); hc_xstar.initialize_table(); hc_rate = hc_xstar.get_rate(T,xi); 1a. If lin-lin spacing was used instead, use VEGAS_LUT hc_xstar("input_table.tab","bicubic",false,false); 1c. To apply a bounding box, use instead const double T_bbox[2] = {1e5,1e7}; const double xi_bbox[2] = {1e1,5e2}; hc_xstar.initialize_table(T_bbox,xi_bbox); */ #ifndef H_VEGAS_TABLE #define H_VEGAS_TABLE #include <iostream> // std::cout, std::endl #include <iomanip> // std::setprecision #include <fstream> // std::ifstream #include <string> #include <vector> #include <time.h> #include <cmath> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> class VEGAS_LUT { public: //default constructor will parse the input file //log-log spacing for (T,xi) is assumed by default VEGAS_LUT( const std::string a="VEGAS_table.tab", const std::string b="bicubic", bool c=true, bool d=true): filename(a),gsl_routine(b),logT(c),logxi(d) { // allocate a (Nmax x Nmax) table for reading in the file int Nmax = 1000; input_table = new double*[Nmax]; for (int i = 0; i < Nmax; i++) input_table[i] = new double[Nmax]; xivals = new double[Nmax]; Tvals = new double[Nmax]; gsl_init(); parse_file(); } ~VEGAS_LUT() { free_memory(); } //user must call the initialize_table method void initialize_table(const double*, const double*); //user function that returns an interpolated value double get_rate(double, double); // actual table (T,xi) bounds: // hydro code needs to know Temp bounds when doing implicit root finding double y_min,y_max,x_min,x_max; private: bool logT,logxi; // determines log gridding double* xlim; // input table xi bounds double* ylim; // input table T bounds const double* T_bounds; // user specified T bounds const double* xi_bounds; // user specified xi bounds double** input_table; // pointer to input table double** table; // pointer to actual table double* xivals; // xi-vals from input table double* Tvals; // T-vals from input table double* xvals; // xi-vals for actual table double* yvals; // T-vals for actual table unsigned int NT, // # rows of input table (# of Ts) Nxi, // # cols of input table (# of xis) N, // # rows of actual table (# of Ts) M, // # cols of actual table (# of xis) i_T, // T-offset between the input and actual tables i_xi; // xi-offset between the input and actual tables typedef std::vector<double> array_t; //dynamic array data type std::string filename, gsl_routine; //input strings //member functions for handling the input file void parse_file(); bool read_value(std::ifstream&, const int, array_t&); void free_input_table(); void free_memory(); //other member functions void reduce_input_table(); void make_table(unsigned int, unsigned int); void determine_box_indices(double, double, unsigned int&, unsigned int&); //GSL variables and member functions bool use_gsl_bicubic; const gsl_interp2d_type *gsl_scheme; typedef gsl_spline2d* spline_t; spline_t **spline_table; gsl_interp_accel *xacc, *yacc; size_t nx,ny; void gsl_init(); void make_spline_table(); }; void VEGAS_LUT::gsl_init() { if (gsl_routine == "bilinear") { gsl_scheme = gsl_interp2d_bilinear; use_gsl_bicubic = false; nx = 2; ny = 2; } else if (gsl_routine == "bicubic") { gsl_scheme = gsl_interp2d_bicubic; use_gsl_bicubic = true; nx = 4; ny = 4; } else { std::cout << "ERROR: GSL interpolation scheme " << gsl_routine << " not recognized. Choose from:\n" << "bilinear\n" << "bicubic\n" << std::endl; exit(0); } } bool VEGAS_LUT::read_value(std::ifstream& fin, const int j, array_t& input_data) { double value; if (fin >> value) { input_data[j]=value; return true; } else return false; } void VEGAS_LUT::parse_file() { std::ifstream fin(filename.c_str()); if (!fin) { std::cout << "File " << filename << " does not exist!" << std::endl; exit(0); } bool file_is_open = false; bool end_of_line = false; // read in first value: Nxi array_t val1(1); file_is_open = read_value(fin,0,val1); Nxi = (unsigned int) val1[0]; // read in remainder of first row: all xi-values array_t this_row(Nxi+1); int i=1,j; while(!end_of_line) { file_is_open = read_value(fin,i,this_row); xivals[i-1] = this_row[i]; if( i!=0 && i%Nxi == 0 ) end_of_line = true; else i++; //next row element } // read in 1st element of 2nd row: the 1st T value file_is_open = read_value(fin,0,this_row); Tvals[0] = this_row[0]; // read in the rest of the file end_of_line = false; i = 1; j=0; while(file_is_open) { file_is_open = read_value(fin,i,this_row); if( i!=0 && i%Nxi == 0 ) { end_of_line = true; i=0; // j++; //reset column, increment row } else i++; //next row element if(end_of_line) { // 1st element of this_row is T Tvals[j] = this_row[0]; // remaining elements are rates for (int ii=0; ii<Nxi; ii++) //std::cout << "this_row[" << ii << "] = " << this_row[ii] << std::endl; input_table[j][ii] = this_row[ii+1]; j++; } end_of_line = false; } NT = j; //number of temperature values fin.close(); if (Nxi < 2 || NT < 2) { std::cout << "ERROR: Table dimensions must be at least 2x2!" << std::endl; exit(0); } } void VEGAS_LUT::make_table(unsigned int i0, unsigned int j0) { // allocate memory table = new double*[N]; for (int j = 0; j < N; j++) table[j] = new double[M]; // assign values for (int j = 0; j < N; j++) for (int i = 0; i < M; i++) table[j][i] = input_table[j0+j][i0+i]; } void VEGAS_LUT::make_spline_table() { // allocate memory for spline_table spline_table = new spline_t*[N]; for (int j = 0; j < N; j++) spline_table[j] = new spline_t[M]; /* Each location in our table is to be thought of as a 4-corner box. * The corners have locations (xb[], yb[]) and function values (zb[]) * and this data is collected ahead of time so that GSL only needs to * access it to carry out the interpolation. For the case of bicubic * interpolation, GSL will also take numerical derivatives and store * all that data, so a lot of expense is saved by collecting this at * initialization. */ double *xb = new double[nx]; double *yb = new double[ny]; double *zb = new double[nx*ny]; /* Associations: T = y(j), with j from (0,N-1) xi = x(i), with i from (0,M-1) */ for (int j=1; j < (N-2); j++) for (int i=1; i < (M-2); i++) { // allocate storage for interpolation data gsl_spline2d *spline = gsl_spline2d_alloc(gsl_scheme, nx, ny); // evaluate position data (xb[],yb[]) and store function values (zb[]) to spline for (int jb=0; jb < nx; jb++) for (int ib=0; ib < ny; ib++) { if (use_gsl_bicubic) { xb[ib] = xvals[i+ib-1]; yb[jb] = yvals[j+jb-1]; gsl_spline2d_set(spline, zb, ib, jb, table[j+jb-1][i+ib-1]); } else { xb[ib] = xvals[i+ib]; yb[jb] = yvals[j+jb]; gsl_spline2d_set(spline, zb, ib, jb, table[j+jb][i+ib]); } } /* add position data * In the case of bicubic, this also internally calculates * derivative data and stores that as well. */ gsl_spline2d_init(spline, xb, yb, zb, nx, ny); // store this interpolation data in our spline table spline_table[j][i] = spline; } //end loop /* The above loop excludes all boxes on table edges, which always require * doing bilinear interpolation, so add that data now */ int j_edges[2] = {0, N-2}; int i_edges[2] = {0, M-2}; int i,j; for (int jj=0; jj < 2; jj++) for (int i=0; i < (M-1); i++) { j = j_edges[jj]; gsl_spline2d *spline = gsl_spline2d_alloc(gsl_interp2d_bilinear, 2, 2); // evaluate position data (xb[],yb[]) and store function values (zb[]) to spline for (int jb=0; jb < 2; jb++) for (int ib=0; ib < 2; ib++) { xb[ib] = xvals[i+ib]; yb[jb] = yvals[j+jb]; gsl_spline2d_set(spline, zb, ib, jb, table[j+jb][i+ib]); } /* add position data * In the case of bicubic, this also internally calculates * derivative data and stores that as well. */ gsl_spline2d_init(spline, xb, yb, zb, 2, 2); // store this interpolation data in our spline table //std::cout<< "(i,j) = (" << i << ", " << j << ")" << std::endl; spline_table[j][i] = spline; } for (int j=0; j < (N-1); j++) for (int ii=0; ii < 2; ii++) { i = i_edges[ii]; gsl_spline2d *spline = gsl_spline2d_alloc(gsl_interp2d_bilinear, 2, 2); // evaluate position data (xb[],yb[]) and store function values (zb[]) to spline for (int jb=0; jb < 2; jb++) for (int ib=0; ib < 2; ib++) { xb[ib] = xvals[i+ib]; yb[jb] = yvals[j+jb]; gsl_spline2d_set(spline, zb, ib, jb, table[j+jb][i+ib]); } /* add position data * In the case of bicubic, this also internally calculates * derivative data and stores that as well. */ gsl_spline2d_init(spline, xb, yb, zb, 2, 2); // store this interpolation data in our spline table //std::cout<< "(i,j) = (" << i << ", " << j << ")" << std::endl; spline_table[j][i] = spline; } // These I think are used when a lookup table must be searched // but since we know the lookup locations there is no point xacc = NULL; //gsl_interp_accel_alloc(); yacc = NULL; //gsl_interp_accel_alloc(); } void VEGAS_LUT::free_memory() { for (int i = 0; i < N; i++) { delete[] table[i]; delete[] spline_table[i]; } //gsl_interp_accel_free(xacc); //gsl_interp_accel_free(yacc); } void VEGAS_LUT::free_input_table() { for (int i = 0; i < N; i++) delete[] input_table[i]; } void VEGAS_LUT::reduce_input_table() { double Tmin,Tmax,ximin,ximax; Tmin = T_bounds[0]; Tmax = T_bounds[1]; ximin = xi_bounds[0]; ximax = xi_bounds[1]; if (Tmin < Tvals[0] || Tmax > Tvals[NT-1]) { std::cout << "ERROR: Tmin or Tmax is not contained within file " << filename << "!" << std::endl; exit(0); } if (ximin < xivals[0] || ximax > xivals[Nxi-1]) { std::cout << "ERROR: x_min or x_max is not contained within file " << filename << "!" << std::endl; exit(0); } // find the indices of the table corresponding to input min/max values int i = 0; while (Tvals[i] < Tmax && i < NT) i++; y_max = Tvals[i]; //so y_max is slightly greater than Tmax int ii = 0; while (Tvals[ii] <= Tmin && ii < i) ii++; y_min = Tvals[ii-1]; //so y_min is slightly less than Tmin // assign private variables i_T = ii-1; // start position in input table N = i - ii + 2; // # of T-vals in desired table i = 0; while (xivals[i] < ximax && i < Nxi) i++; x_max = xivals[i]; //so x_max is slightly greater than ximax ii = 0; while (xivals[ii] <= ximin && ii < i) ii++; x_min = xivals[ii-1]; //so x_min is slightly less than ximin // assign private variables i_xi = ii-1; // start position in input table M = i - ii + 2; // # of xi-vals in desired table } void VEGAS_LUT::initialize_table(const double * T_bbox = NULL, const double * xi_bbox = NULL) { int i0,j0; if (T_bbox != NULL || xi_bbox != NULL) { T_bounds = T_bbox; xi_bounds = xi_bbox; reduce_input_table(); // this sets i_xi, i_T, N, M, y_min, Tmax, x_min, x_max i0 = i_xi; j0 = i_T; } else // the actual table will be the same size as the input table { y_min = Tvals[0]; y_max = Tvals[NT-1]; x_min = xivals[0]; x_max = xivals[Nxi-1]; N = NT; M = Nxi; i0 = 0; j0 = 0; } // store the values of xi and T that will be used // they way they will be used (i.e. log or lin) xvals = new double[M]; yvals = new double[N]; double x,y; for (int i=0; i<M; i++) { if(logxi) x = log10(xivals[i0+i]); else x = xivals[i0+i]; xvals[i] = x; } for (int j=0; j<N; j++) { if (logT) y = log10(Tvals[j0+j]); else y = Tvals[j0+j]; yvals[j] = y; } // generate the actual table of H/C rates make_table(i0,j0); // alloc storage for max/min vals of T,xi xlim = new double[2]; // xi limits ylim = new double[2]; // T limits // set any log gridding: use limits of input table if (logT) { ylim[0] = log10(Tvals[0]); ylim[1] = log10(Tvals[NT-1]); } else { ylim[0] = Tvals[0]; ylim[1] = Tvals[NT-1]; } if (logxi) { xlim[0] = log10(xivals[0]); xlim[1] = log10(xivals[Nxi-1]); } else { xlim[0] = xivals[0]; xlim[1] = xivals[Nxi-1]; } // generate the spline table for GSL make_spline_table(); // delete input_table free_input_table(); } void VEGAS_LUT::determine_box_indices(double x, double y, unsigned int &i_x, unsigned int &i_y) { unsigned int i,j; bool correct_guess = false; /* First guess the indices assuming the input table was * generated from a uniform grid: the actual xi and T values * that xstar produces data for may be slightly different * as xstar's stopping criteria algorithms may slightly adjust * the input values. On rare occasions this guess can be off * by 1 index, so here we allow for that. */ i = (Nxi-1) * (x - xlim[0]) / (xlim[1] - xlim[0]) - i_xi; j = (NT-1) * (y - ylim[0]) / (ylim[1] - ylim[0]) - i_T ; /* now we check our guess in x and if needed, adjust one box left/right */ if (x > xvals[i] && x < xvals[i+1]) //then we guessed right { i_x = i; correct_guess = true; } if (!correct_guess) { if (i==0 || i==(M-1)) { if (i==0 && x < xvals[2]) i_x = 1; else if (i==(M-1) && x > xvals[M-2]) i_x = M-2; } else if (x < xvals[i]) //then move to the left 1 i_x = i-1; else if (x > xvals[i+1]) //then move to the right 1 i_x = i+1; else // we give up { std::cout << "ERROR: search for the table xi-index failed!" << "\nDouble check inputs or try debugging " << "function determine_box_indices()" << std::endl; exit(0); } } /* now we check our guess in y and if needed, adjust one box up/down */ correct_guess = false; // reset if (y > yvals[j] && y < yvals[j+1]) //then we guessed right { i_y = j; correct_guess = true; } if (!correct_guess) { if (j==0 || j==(N-1)) { if (j==0 && y < yvals[2]) i_y = 1; else if (j==(N-1) && y > yvals[N-2]) i_y = N-2; } else if (y < yvals[j]) //then move down 1 i_y = j-1; else if (y > yvals[j+1]) //then move up 1 i_y = j+1; else // we give up { std::cout << "ERROR: search for the table T-index failed!" << "\nDouble check inputs or try debugging " << "function determine_box_indices()" << std::endl; exit(0); } } } double VEGAS_LUT::get_rate(double y_val, double x_val) { unsigned int i_x,i_y; double x,y; /* terminate program if values exceed bounding box if (y_val < y_min || y_val > y_max || x_val < x_min || x_val > x_max) { std::cout << "\nFATAL ERROR: (y_val,x_val) = (" << y_val << ", " << x_val << ") " << "lies outside of table's bounding box!\n" << ">> Bounding Box:\n" << "(y_min,y_max) = (" << y_min << ", " << y_max << ")\n" << "(x_min,x_max) = (" << x_min << ", " << x_max << ")\n" << std::endl; exit(0); } */ /* use boundary rates for values outside bounding box */ double eps = 1e-10; if (y_val < y_min) y_val = y_min*(1. + eps); if (y_val > y_max) y_val = y_max*(1. - eps); if (x_val < x_min) x_val = x_min*(1. + eps); if (x_val > x_max) x_val = x_max*(1. - eps); // apply any log scaling if (logT) y = log10(y_val); else y = y_val; if (logxi) x = log10(x_val); else x = x_val; determine_box_indices(x,y,i_x,i_y); return gsl_spline2d_eval(spline_table[i_y][i_x], x, y, xacc, yacc); } #endif //H_VEGAS_TABLE
{ "alphanum_fraction": 0.601525941, "avg_line_length": 27.8470254958, "ext": "h", "hexsha": "20f20398ada1208dafa8b12d98014be85c92b013", "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": "115a9e71f8727d9ad45a21087af4959bb23082ce", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "twaters/VegasTables", "max_forks_repo_path": "vegas_tables.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "115a9e71f8727d9ad45a21087af4959bb23082ce", "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": "twaters/VegasTables", "max_issues_repo_path": "vegas_tables.h", "max_line_length": 95, "max_stars_count": null, "max_stars_repo_head_hexsha": "115a9e71f8727d9ad45a21087af4959bb23082ce", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "twaters/VegasTables", "max_stars_repo_path": "vegas_tables.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6154, "size": 19660 }
#ifndef TAYLORSERIES_H #include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <common/refcount.h> #include "common/jexception.h" #include <list> #include <vector> using namespace std; double LogAdd(double x, double y); double LogSub(double x, double y); double logFactorial( unsigned int n ); #define NO_FILE_SYMBOL "NONE" class nonamePdf { protected: vector<float> _points; /* @note it must be positive and sorted. */ int _maxCoeffs; double **_coeffs; /* [_points.size()][nCoeffs] */ double **_coeffsLog; protected: void clear(); public: nonamePdf(); ~nonamePdf(); bool loadCoeffDescFile( const String &coefDescfn ); private: bool loadCoeffFiles( char *coeffn, char *logCoeffn, float a ); int loadCoeffFile( char *coeffn, int preNPoints, int idx, bool logProb ); }; class gammaPdf : public nonamePdf { public: gammaPdf( int numberOfVariate = 2 ); ~gammaPdf(); double calcLog( double x, int N ); double calcDerivative1( double x, int N ); void bi( int printLevel = 0); void four( int printLevel = 0 ); void printCoeff(); private: void allocate(); int indexOfCoeffArray( double x ); bool interpolate( int printLevel ); }; typedef refcount_ptr<nonamePdf> nonamePdfPtr; typedef Inherit<gammaPdf, nonamePdfPtr> gammaPdfPtr; #endif
{ "alphanum_fraction": 0.7044836957, "avg_line_length": 23, "ext": "h", "hexsha": "b97bf8ad661ff5bb2c951521420ad88708dc5b44", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/beamformer/taylorseries.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/beamformer/taylorseries.h", "max_line_length": 77, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/beamformer/taylorseries.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 417, "size": 1472 }
/* * dgl.c -- Loesung einer DGL mit der GNU scientific library * * (c) 2016 Prof Dr Andreas Mueller, Hochschule Rapperswil */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> static long evalcounter = 0; int f(double x, const double y[], double f[], void *params) { evalcounter++; double omega = *(double *)params; f[0] = y[1]; f[1] = -y[0] + sin(omega * x); return GSL_SUCCESS; } static inline double sqr(double x) { return x * x; } int main(int argc, char *argv[]) { double omega = 0.1; gsl_odeiv2_system sys = { f, NULL, 2, &omega }; gsl_odeiv2_driver *driver = gsl_odeiv2_driver_alloc_y_new(&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0); double x = 0.0; double y[2] = { 0.0, 0.0 }; long lastcounter = evalcounter; for (int i = 1; i <= 10000; i++) { double xnext = i; int status = gsl_odeiv2_driver_apply(driver, &x, xnext, y); if (status != GSL_SUCCESS) { fprintf(stderr, "error: return value = %d\n", status); } double yexakt = (omega * sin(x) - sin(omega * x)) / (sqr(omega) - 1); double delta = y[0] - yexakt; long evaldensity = evalcounter - lastcounter; lastcounter = evalcounter; if ((i < 10) || ((i < 100) && (0 == i % 10)) || ((i < 1000) && (0 == i % 100)) || ((i < 10000) && (0 == i % 1000)) || ((i < 100000) && (0 == i % 10000))) { printf("%5.0f& %12.8f& %12.8f& %12.8f&%ld\\\\\n", x, y[0], yexakt, delta, evaldensity); } } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5944148936, "avg_line_length": 27.3454545455, "ext": "c", "hexsha": "c6876c45e060b26bb1449cb65051646d1729ae45", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "MatthiasRubin/SeminarDGL", "max_forks_repo_path": "skript/chapters/examples/dgl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "MatthiasRubin/SeminarDGL", "max_issues_repo_path": "skript/chapters/examples/dgl.c", "max_line_length": 62, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "MatthiasRubin/SeminarDGL", "max_stars_repo_path": "skript/chapters/examples/dgl.c", "max_stars_repo_stars_event_max_datetime": "2021-01-05T07:48:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-05T07:48:28.000Z", "num_tokens": 565, "size": 1504 }
#ifndef __MATH_VECTOROPS_INCLUDED #define __MATH_VECTOROPS_INCLUDED #include <cmath> #include <limits> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> <<<<<<< vectorops.h #include <gsl/gsl_cblas.h> #include "math/specialfunc.h" ======= #include <gsl/gsl_blas.h> #include "specialfunc.h" >>>>>>> 1.27 #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef isnan # define isnan(x) ((x) != (x)) #endif /* * take the exponent of a vector * * If the exponent is infinite, then we replace the value with a * suitably large max_val */ void vexp(const gsl_vector* v, gsl_vector* exp_v, double max_val = std::numeric_limits<double>::infinity()) { assert(exp_v->size >= v->size); for (unsigned int ii = 0; ii < v->size; ++ii) { double val = exp(gsl_vector_get(v, ii)); if (val == std::numeric_limits<double>::infinity() || val > max_val) { val = max_val; } gsl_vector_set(exp_v, ii, val); } } /* take the exponent of a matrix */ void mexp(const gsl_matrix* m, gsl_matrix* exp_m) { for (unsigned int ii = 0; ii < m->size1; ++ii) { for (unsigned int jj = 0; jj < m->size2; ++jj) { double val = exp(gsl_matrix_get(m, ii, jj)); assert(!isnan(val)); gsl_matrix_set(exp_m, ii, jj, val); } } } /* like vexp except that it also computes sum x log x */ double vexp_entropy(const gsl_vector* v, gsl_vector* exp_v) { double entropy = 0.0; for (unsigned int ii = 0; ii < v->size; ++ii) { double logval = gsl_vector_get(v, ii); double val = exp(logval); assert(!isnan(val)); gsl_vector_set(exp_v, ii, val); if (val != 0) { entropy -= val * logval; } } return entropy; } double ventropy(const gsl_vector* v) { double entropy = 0.0; for (unsigned int ii = 0; ii < v->size; ++ii) { double val = gsl_vector_get(v, ii); if (val != 0) { entropy -= val * log(val); } } return entropy; } double lgamma(double x) { double x0,x2,xp,gl,gl0; int n=0,k=0; static double a[] = { 8.333333333333333e-02, -2.777777777777778e-03, 7.936507936507937e-04, -5.952380952380952e-04, 8.417508417508418e-04, -1.917526917526918e-03, 6.410256410256410e-03, -2.955065359477124e-02, 1.796443723688307e-01, -1.39243221690590}; x0 = x; if (x <= 0.0) return 1e308; else if ((x == 1.0) || (x == 2.0)) return 0.0; else if (x <= 7.0) { n = (int)(7-x); x0 = x+n; } x2 = 1.0/(x0*x0); xp = 2.0*M_PI; gl0 = a[9]; for (k=8;k>=0;k--) { gl0 = gl0*x2 + a[k]; } gl = gl0/x0+0.5*log(xp)+(x0-0.5)*log(x0)-x0; if (x <= 7.0) { for (k=1;k<=n;k++) { gl -= log(x0-1.0); x0 -= 1.0; } } return gl; } void mlog(const gsl_matrix* m, gsl_matrix* log_m) { for (unsigned int ii = 0; ii < m->size1; ++ii) { for (unsigned int jj = 0; jj < m->size2; ++jj) { gsl_matrix_set(log_m, ii, jj, log(gsl_matrix_get(m, ii, jj))); } } } void vlog(const gsl_vector* v, gsl_vector* log_v) { for (unsigned int ii = 0; ii < v->size; ++ii) gsl_vector_set(log_v, ii, log(gsl_vector_get(v, ii))); } void vlogit(const gsl_vector* v, gsl_vector* log_v) { for (unsigned int ii = 0; ii < v->size; ++ii) { double p = gsl_vector_get(v, ii); assert(p >= 0.0); assert(p <= 1.0); gsl_vector_set(log_v, ii, log(p / (1 - p))); } } void vsigmoid(const gsl_vector* v, gsl_vector* sig_v) { for (unsigned int ii = 0; ii < v->size; ++ii) { double p = gsl_vector_get(v, ii); gsl_vector_set(sig_v, ii, 1. / (1. + exp(-p))); } } double vlog_entropy(const gsl_vector* v, gsl_vector* log_v) { double entropy = 0; for (unsigned int ii = 0; ii < v->size; ++ii) { double val = gsl_vector_get(v, ii); entropy -= val * log(val); gsl_vector_set(log_v, ii, log(val)); } return entropy; } double entropy(const gsl_vector* v) { double entropy = 0; for (unsigned int ii = 0; ii < v->size; ++ii) { double val = gsl_vector_get(v, ii); entropy -= val * log(val); } return entropy; } void vdigamma(const gsl_vector* v, gsl_vector* digamma_v) { for (unsigned int ii = 0; ii < v->size; ++ii) // gsl_sf_psi throws an error when its argument is 0, whereas digamma returns inf. // gsl_vector_set(digamma_v, ii, gsl_sf_psi(gsl_vector_get(v, ii))); gsl_vector_set(digamma_v, ii, digamma(gsl_vector_get(v, ii))); } void vlgamma(const gsl_vector* v, gsl_vector* lgamma_v) { for (unsigned int ii = 0; ii < v->size; ++ii) gsl_vector_set(lgamma_v, ii, lgamma(gsl_vector_get(v, ii))); } double gsl_blas_dsum(const gsl_vector* v) { double sum = 0; for (unsigned int ii = 0; ii < v->size; ++ii) { sum += gsl_vector_get(v, ii); } return sum; } double gsl_blas_dsum(const gsl_matrix* v) { double sum = 0; for (unsigned int ii = 0; ii < v->size1; ++ii) { for (unsigned int jj = 0; jj < v->size2; ++jj) { sum += gsl_matrix_get(v, ii, jj); } } return sum; } double gsl_matrix_rowsum(const gsl_matrix* m, const int row) { double sum = 0; for(unsigned int i=0; i < m->size2; i++) { sum += gsl_matrix_get(m, row, i); } return sum; } double dot_product(const gsl_vector* a, const gsl_vector* b) { assert(a->size == b->size); double val = 0; for(unsigned i=0; i<a->size; i++) { val += gsl_vector_get(a, i) * gsl_vector_get(b, i); } return val; } void uniform(gsl_vector* v) { gsl_vector_set_all(v, 1.0 / (double)v->size); } double normalize(gsl_vector* v) { double sum = gsl_blas_dsum(v); gsl_blas_dscal(1 / sum, v); return sum; } /* This function takes as input a multinomial parameter vector and computes the "total" variance, i.e., the sum of the diagonal of the covariance matrix. If the multinomial parameter is unnormalized, then the variance of the normalized multinomial vector will be computed and then multiplied by the scale of the vector. */ double MultinomialTotalVariance(const gsl_vector* v) { double scale = gsl_blas_dsum(v); double variance = 0.0; for (size_t ii = 0; ii < v->size; ++ii) { double val = gsl_vector_get(v, ii) / scale; variance += val * (1. - val); } return variance * scale; } /* Computes covariance using the renormalization above and adds it to an existing matrix. */ void MultinomialCovariance(double alpha, const gsl_vector* v, gsl_matrix* m) { double scale = gsl_blas_dsum(v); gsl_blas_dger(-alpha / scale, v, v, m); gsl_vector_view diag = gsl_matrix_diagonal(m); gsl_blas_daxpy(alpha, v, &diag.vector); } double MatrixProductSum(const gsl_matrix* m1, const gsl_matrix* m2) { double val = 0; assert(m1->size1 == m2->size1); assert(m1->size2 == m2->size2); for (size_t ii = 0; ii < m1->size1; ++ii) { for (size_t jj = 0; jj < m2->size2; ++jj) { val += gsl_matrix_get(m1, ii, jj) * gsl_matrix_get(m2, ii, jj); } } return val; } double MatrixProductProductSum(const gsl_matrix* m1, const gsl_matrix* m2, const gsl_matrix* m3) { double val = 0; assert(m1->size1 == m2->size1); assert(m1->size2 == m2->size2); assert(m1->size1 == m3->size1); assert(m1->size2 == m3->size2); for (size_t ii = 0; ii < m1->size1; ++ii) { for (size_t jj = 0; jj < m2->size2; ++jj) { for (size_t kk = 0; kk < m3->size2; ++kk) { val += gsl_matrix_get(m1, ii, jj) * gsl_matrix_get(m2, ii, jj) * gsl_matrix_get(m3, ii, jj); } } } return val; } double SumLGamma(const gsl_vector* v) { double s = 0.0; for (size_t ii = 0; ii < v->size; ++ii) { s += lgamma(gsl_vector_get(v, ii)); } return s; } void mtx_fprintf(const char* filename, const gsl_matrix * m) { FILE* fileptr; fileptr = fopen(filename, "w"); gsl_matrix_fprintf(fileptr, m, "%20.17e"); fclose(fileptr); } void mtx_fscanf(const char* filename, gsl_matrix * m) { FILE* fileptr; fileptr = fopen(filename, "r"); gsl_matrix_fscanf(fileptr, m); fclose(fileptr); } double mtx_accum(const int i, const int j, const double contribution, gsl_matrix* m) { double new_val = gsl_matrix_get(m, i, j) + contribution; gsl_matrix_set(m, i, j, new_val); return new_val; } void vct_fscanf(const char* filename, gsl_vector* v) { FILE* fileptr; fileptr = fopen(filename, "r"); gsl_vector_fscanf(fileptr, v); fclose(fileptr); } void vct_fprintf(const char* filename, gsl_vector* v) { FILE* fileptr; fileptr = fopen(filename, "w"); gsl_vector_fprintf(fileptr, v, "%20.17e"); fclose(fileptr); } #endif
{ "alphanum_fraction": 0.6082997118, "avg_line_length": 25.2915451895, "ext": "h", "hexsha": "e31484893d4d9004c4e2ffc6063869de6fabdae0", "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": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "boomsbloom/dtm-fmri", "max_forks_repo_path": "DTM/dtm-master/lib/math/vectorops.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "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": "boomsbloom/dtm-fmri", "max_issues_repo_path": "DTM/dtm-master/lib/math/vectorops.h", "max_line_length": 86, "max_stars_count": 4, "max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "boomsbloom/dtm-fmri", "max_stars_repo_path": "DTM/dtm-master/lib/math/vectorops.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": 2839, "size": 8675 }
/* This file is part of the KDE project Copyright (C) 2006 Stefan Nikolaus <stefan.nikolaus@kdemail.net> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KSPREAD_SOLVER #define KSPREAD_SOLVER #include <gsl/gsl_multimin.h> #include <kxmlguiclient.h> #include <Cell.h> #include <QObject> #include <QVariantList> namespace Calligra { namespace Sheets { namespace Plugins { /** * \class Solver Function Optimizer * \author Stefan Nikolaus <stefan.nikolaus@kdemail.net> */ class Solver : public QObject, public KXMLGUIClient { Q_OBJECT public: struct Parameters { QList<Cell> cells; }; /** * Constructor. */ Solver(QObject* parent, const QVariantList& args); /** * Destructor. */ ~Solver(); double evaluate(const gsl_vector* vector, void* parameters); protected Q_SLOTS: /** * Called when the Solver action is triggered. * Opens the dialog. */ void showDialog(); /** * This method does the real work. * Uses the parameters of the dialog to optimize the given function. */ void optimize(); private: Q_DISABLE_COPY(Solver) class Private; Private * const d; }; } // namespace Plugins } // namespace Sheets } // namespace Calligra #endif
{ "alphanum_fraction": 0.696151924, "avg_line_length": 22.4831460674, "ext": "h", "hexsha": "9898b18d723cad768eda093e82574c2e94ae10ca", "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": "6d5ef3418238e9402c5a263a6f499557cc7215bf", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "afarcat/QtSheetView", "max_forks_repo_path": "src/3rdparty/sheets/plugins/solver/Solver.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d5ef3418238e9402c5a263a6f499557cc7215bf", "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": "afarcat/QtSheetView", "max_issues_repo_path": "src/3rdparty/sheets/plugins/solver/Solver.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d5ef3418238e9402c5a263a6f499557cc7215bf", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "afarcat/QtSheetView", "max_stars_repo_path": "src/3rdparty/sheets/plugins/solver/Solver.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 472, "size": 2001 }
#pragma once #include "Cesium3DTiles/BoundingVolume.h" #include "Cesium3DTiles/Library.h" #include "Cesium3DTiles/Tile.h" #include "Cesium3DTiles/TileContext.h" #include "Cesium3DTiles/TileID.h" #include "Cesium3DTiles/TileRefine.h" #include <gsl/span> #include <spdlog/fwd.h> #include <cstddef> #include <memory> namespace Cesium3DTiles { /** * @brief The information that is passed to a {@link TileContentLoader} to * create a {@link TileContentLoadResult}. * * For many types of tile content, only the `data` field is required. The other * members are used for content that can generate child tiles, like external * tilesets or composite tiles. These members are usually initialized from * the corresponding members of the {@link Tile} that the content belongs to. */ struct CESIUM3DTILES_API TileContentLoadInput { /** * @brief Creates a new, uninitialized instance for the given tile. * * The `data`, `contentType` and `url` will have default values, * and have to be initialized before this instance is passed to * one of the loader functions. * * @param pLogger_ The logger that will be used * @param tile_ The {@link Tile} that the content belongs to */ TileContentLoadInput( const std::shared_ptr<spdlog::logger> pLogger_, const Tile& tile_) : pLogger(pLogger_), data(), contentType(), url(), tileID(tile_.getTileID()), tileBoundingVolume(tile_.getBoundingVolume()), tileContentBoundingVolume(tile_.getContentBoundingVolume()), tileRefine(tile_.getRefine()), tileGeometricError(tile_.getGeometricError()), tileTransform(tile_.getTransform()) {} /** * @brief Creates a new instance for the given tile. * * @param pLogger_ The logger that will be used * @param data_ The actual data that the tile content will be created from * @param contentType_ The content type, if the data was received via a * network response * @param url_ The URL that the data was loaded from * @param tile_ The {@link Tile} that the content belongs to */ TileContentLoadInput( const std::shared_ptr<spdlog::logger> pLogger_, const gsl::span<const std::byte>& data_, const std::string& contentType_, const std::string& url_, const Tile& tile_) : pLogger(pLogger_), data(data_), contentType(contentType_), url(url_), tileID(tile_.getTileID()), tileBoundingVolume(tile_.getBoundingVolume()), tileContentBoundingVolume(tile_.getContentBoundingVolume()), tileRefine(tile_.getRefine()), tileGeometricError(tile_.getGeometricError()), tileTransform(tile_.getTransform()) {} /** * @brief Creates a new instance. * * For many types of tile content, only the `data` field is required. The * other parameters are used for content that can generate child tiles, like * external tilesets or composite tiles. * * @param pLogger_ The logger that will be used * @param data_ The actual data that the tile content will be created from * @param contentType_ The content type, if the data was received via a * network response * @param url_ The URL that the data was loaded from * @param context_ The {@link TileContext} * @param tileID_ The {@link TileID} * @param tileBoundingVolume_ The tile {@link BoundingVolume} * @param tileContentBoundingVolume_ The tile content {@link BoundingVolume} * @param tileRefine_ The {@link TileRefine} strategy * @param tileGeometricError_ The geometric error of the tile * @param tileTransform_ The tile transform */ TileContentLoadInput( const std::shared_ptr<spdlog::logger> pLogger_, const gsl::span<const std::byte>& data_, const std::string& contentType_, const std::string& url_, const TileID& tileID_, const BoundingVolume& tileBoundingVolume_, const std::optional<BoundingVolume>& tileContentBoundingVolume_, TileRefine tileRefine_, double tileGeometricError_, const glm::dmat4& tileTransform_) : pLogger(pLogger_), data(data_), contentType(contentType_), url(url_), tileID(tileID_), tileBoundingVolume(tileBoundingVolume_), tileContentBoundingVolume(tileContentBoundingVolume_), tileRefine(tileRefine_), tileGeometricError(tileGeometricError_), tileTransform(tileTransform_) {} /** * @brief The logger that receives details of loading errors and warnings. */ std::shared_ptr<spdlog::logger> pLogger; /** * @brief The raw input data. * * The {@link TileContentFactory} will try to determine the type of the * data using the first four bytes (i.e. the "magic header"). If this * does not succeed, it will try to determine the type based on the * `contentType` field. */ gsl::span<const std::byte> data; /** * @brief The content type. * * If the data was obtained via a HTTP response, then this will be * the `Content-Type` of that response. The {@link TileContentFactory} * will try to interpret the data based on this content type. * * If the data was not directly obtained from an HTTP response, then * this may be the empty string. */ std::string contentType; /** * @brief The source URL. */ std::string url; /** * @brief The {@link TileID}. */ TileID tileID; /** * @brief The tile {@link BoundingVolume}. */ BoundingVolume tileBoundingVolume; /** * @brief Tile content {@link BoundingVolume}. */ std::optional<BoundingVolume> tileContentBoundingVolume; /** * @brief The {@link TileRefine}. */ TileRefine tileRefine; /** * @brief The geometric error. */ double tileGeometricError; /** * @brief The tile transform */ glm::dmat4 tileTransform; }; } // namespace Cesium3DTiles
{ "alphanum_fraction": 0.6851820491, "avg_line_length": 32.0923913043, "ext": "h", "hexsha": "215ebd26dfba6d8db39030d49c7eaea2336b7b40", "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": "18a295f47b3118cc2edfc22354d93b938a68069c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "MAPSWorks/cesium-native", "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentLoadInput.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "18a295f47b3118cc2edfc22354d93b938a68069c", "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": "MAPSWorks/cesium-native", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentLoadInput.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b824699d3dd9503a5943007247f683b6adc132d4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "TJKoury/cesium-native", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/TileContentLoadInput.h", "max_stars_repo_stars_event_max_datetime": "2021-05-27T04:47:23.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-27T04:47:23.000Z", "num_tokens": 1458, "size": 5905 }
/* cheb/eval.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_chebyshev.h> /* For efficiency there are separate implementations of each of these functions */ double gsl_cheb_eval (const gsl_cheb_series * cs, const double x) { size_t i; double d1 = 0.0; double d2 = 0.0; double y = (2.0 * x - cs->a - cs->b) / (cs->b - cs->a); double y2 = 2.0 * y; for (i = cs->order; i >= 1; i--) { double temp = d1; d1 = y2 * d1 - d2 + cs->c[i]; d2 = temp; } return y * d1 - d2 + 0.5 * cs->c[0]; } double gsl_cheb_eval_n (const gsl_cheb_series * cs, const size_t n, const double x) { size_t i; double d1 = 0.0; double d2 = 0.0; size_t eval_order = GSL_MIN (n, cs->order); double y = (2.0 * x - cs->a - cs->b) / (cs->b - cs->a); double y2 = 2.0 * y; for (i = eval_order; i >= 1; i--) { double temp = d1; d1 = y2 * d1 - d2 + cs->c[i]; d2 = temp; } return y * d1 - d2 + 0.5 * cs->c[0]; } int gsl_cheb_eval_err (const gsl_cheb_series * cs, const double x, double *result, double *abserr) { size_t i; double d1 = 0.0; double d2 = 0.0; double y = (2. * x - cs->a - cs->b) / (cs->b - cs->a); double y2 = 2.0 * y; double absc = 0.0; for (i = cs->order; i >= 1; i--) { double temp = d1; d1 = y2 * d1 - d2 + cs->c[i]; d2 = temp; } *result = y * d1 - d2 + 0.5 * cs->c[0]; /* Estimate cumulative numerical error */ for (i = 0; i <= cs->order; i++) { absc += fabs(cs->c[i]); } /* Combine truncation error and numerical error */ *abserr = fabs (cs->c[cs->order]) + absc * GSL_DBL_EPSILON; return GSL_SUCCESS; } int gsl_cheb_eval_n_err (const gsl_cheb_series * cs, const size_t n, const double x, double *result, double *abserr) { size_t i; double d1 = 0.0; double d2 = 0.0; double y = (2. * x - cs->a - cs->b) / (cs->b - cs->a); double y2 = 2.0 * y; double absc = 0.0; size_t eval_order = GSL_MIN (n, cs->order); for (i = eval_order; i >= 1; i--) { double temp = d1; d1 = y2 * d1 - d2 + cs->c[i]; d2 = temp; } *result = y * d1 - d2 + 0.5 * cs->c[0]; /* Estimate cumulative numerical error */ for (i = 0; i <= eval_order; i++) { absc += fabs(cs->c[i]); } /* Combine truncation error and numerical error */ *abserr = fabs (cs->c[eval_order]) + absc * GSL_DBL_EPSILON; return GSL_SUCCESS; } int gsl_cheb_eval_mode_e (const gsl_cheb_series * cs, const double x, gsl_mode_t mode, double *result, double *abserr) { size_t i; double d1 = 0.0; double d2 = 0.0; double y = (2. * x - cs->a - cs->b) / (cs->b - cs->a); double y2 = 2.0 * y; double absc = 0.0; size_t eval_order; if (GSL_MODE_PREC (mode) == GSL_PREC_DOUBLE) eval_order = cs->order; else eval_order = cs->order_sp; for (i = eval_order; i >= 1; i--) { double temp = d1; d1 = y2 * d1 - d2 + cs->c[i]; d2 = temp; } *result = y * d1 - d2 + 0.5 * cs->c[0]; /* Estimate cumulative numerical error */ for (i = 0; i <= eval_order; i++) { absc += fabs(cs->c[i]); } /* Combine truncation error and numerical error */ *abserr = fabs (cs->c[eval_order]) + absc * GSL_DBL_EPSILON; return GSL_SUCCESS; } double gsl_cheb_eval_mode (const gsl_cheb_series * cs, const double x, gsl_mode_t mode) { double result, abserr; int status = gsl_cheb_eval_mode_e (cs, x, mode, &result, &abserr); if (status != GSL_SUCCESS) { GSL_ERROR_VAL("gsl_cheb_eval_mode", status, result); }; return result; }
{ "alphanum_fraction": 0.5759507584, "avg_line_length": 21.9758454106, "ext": "c", "hexsha": "9d5acda57961ecf493a59c2c0a7811d86c91f970", "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/cheb/eval.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/cheb/eval.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/cheb/eval.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": 1535, "size": 4549 }
///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation // NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == getrs.h // // getrs function in native C++. // /* * Automatically Tuned Linear Algebra Software v3.8.4 * (C) Copyright 1999 R. Clint Whaley * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the ATLAS group or the names of its contributers may * not be used to endorse or promote products derived from this * software without specific 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 ATLAS GROUP OR ITS 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 GETRS_H #define GETRS_H extern "C" { #if defined HAVE_CBLAS_H #include <cblas.h> #elif defined HAVE_ATLAS_CBLAS_H #include <atlas/cblas.h> #endif } namespace nm { namespace math { /* * Solves a system of linear equations A*X = B with a general NxN matrix A using the LU factorization computed by GETRF. * * From ATLAS 3.8.0. */ template <typename DType> int getrs(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE Trans, const int N, const int NRHS, const DType* A, const int lda, const int* ipiv, DType* B, const int ldb) { // enum CBLAS_DIAG Lunit, Uunit; // These aren't used. Not sure why they're declared in ATLAS' src. if (!N || !NRHS) return 0; const DType ONE = 1; if (Order == CblasColMajor) { if (Trans == CblasNoTrans) { nm::math::laswp<DType>(NRHS, B, ldb, 0, N, ipiv, 1); nm::math::trsm<DType>(Order, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, N, NRHS, ONE, A, lda, B, ldb); nm::math::trsm<DType>(Order, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb); } else { nm::math::trsm<DType>(Order, CblasLeft, CblasUpper, Trans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb); nm::math::trsm<DType>(Order, CblasLeft, CblasLower, Trans, CblasUnit, N, NRHS, ONE, A, lda, B, ldb); nm::math::laswp<DType>(NRHS, B, ldb, 0, N, ipiv, -1); } } else { if (Trans == CblasNoTrans) { nm::math::trsm<DType>(Order, CblasRight, CblasLower, CblasTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb); nm::math::trsm<DType>(Order, CblasRight, CblasUpper, CblasTrans, CblasUnit, NRHS, N, ONE, A, lda, B, ldb); nm::math::laswp<DType>(NRHS, B, ldb, 0, N, ipiv, -1); } else { nm::math::laswp<DType>(NRHS, B, ldb, 0, N, ipiv, 1); nm::math::trsm<DType>(Order, CblasRight, CblasUpper, CblasNoTrans, CblasUnit, NRHS, N, ONE, A, lda, B, ldb); nm::math::trsm<DType>(Order, CblasRight, CblasLower, CblasNoTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb); } } return 0; } /* * Function signature conversion for calling LAPACK's getrs functions as directly as possible. * * For documentation: http://www.netlib.org/lapack/double/dgetrs.f * * This function should normally go in math.cpp, but we need it to be available to nmatrix.cpp. */ template <typename DType> inline int clapack_getrs(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE trans, const int n, const int nrhs, const void* a, const int lda, const int* ipiv, void* b, const int ldb) { return getrs<DType>(order, trans, n, nrhs, reinterpret_cast<const DType*>(a), lda, ipiv, reinterpret_cast<DType*>(b), ldb); } } } // end nm::math #endif // GETRS_H
{ "alphanum_fraction": 0.6843944099, "avg_line_length": 39.6307692308, "ext": "h", "hexsha": "8a6ddb268a7ee32a374b73b9691cc7e8cb834648", "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": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "blackwinter-attic/nmatrix", "max_forks_repo_path": "ext/nmatrix/math/getrs.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "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": "blackwinter-attic/nmatrix", "max_issues_repo_path": "ext/nmatrix/math/getrs.h", "max_line_length": 125, "max_stars_count": null, "max_stars_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "blackwinter-attic/nmatrix", "max_stars_repo_path": "ext/nmatrix/math/getrs.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1445, "size": 5152 }
#ifndef FILE_PROCESSINGUNIT #define FILE_PROCESSINGUNIT #include "../devicedata/memorymanager.h" #include "timer.h" #ifndef CPU_ONLY #include "gpu_handle.h" #ifdef MAGMA #include "GpuMagma_queue.h" #include "magma_v2.h" #endif #else #pragma message("Cpu only mode is activated. Gpu suppport is disabled. If you wish to activate Gpu support, remove compiler flag CPU_ONLY") #endif #ifdef __INTEL_CLANG_COMPILER #pragma message("Intel Math Kernel Library is used for acceleration of linear algebra operations.") #include <mkl.h> #else #pragma message("CBLAS/LAPACK/LAPACKE are used for acceleration of linear algebra operations.") #include <cblas.h> #include <lapacke.h> #endif #include <map> #include <type_traits> #include <iostream> #include <memory> #include <string> template<class floating> class ProcessingUnitDevice; template<class floating> using ProcessingUnit = std::shared_ptr<ProcessingUnitDevice<floating>>; /** * Class OperationType is used for choosing the matrix operation * type in several operations of interface ProcessingUnitDevice. */ enum class OperationType { Identical, //!< taking the matrix without any changes Transposed, //!< taking the transposition of the matrix Hermitian //!< taking the complex conjugate of the matrix }; /** * Class ProcessingUnitDevice is an abstract interface for easy calls to * BLAS/LAPACK/LAPACKE-like function calls on a certain device, * e.g. for CUDA/cuSOLVER on a Gpu, or for MAGMA on a Gpu. * * The floating point type is passed as a template parameter. * * @tparam floating floating point type */ template<class floating> class ProcessingUnitDevice { public: /** * Constructor. */ ProcessingUnitDevice(); /** * Destructor. */ virtual ~ProcessingUnitDevice() = default; /** * Creates a new instance of a Timer stopwatch on the current device. * @return new Timer instance */ virtual Timer create_timer() const = 0; /** * Returns the MemoryManager associated with the current device. * @return MemoryManager */ virtual MemoryManager get_memory_manager() const = 0; /** * Returns the subclass's name in a human-readable format as a string * @return subclass's human-readable name */ virtual std::string display() const = 0; /** * Function ixamax is an abstraction of calls isamax/idamax/etc. * It returns the index of the first element having maximum absolute value. * * See also * https://www.netlib.org/lapack/explore-html/d0/d73/group__aux__blas_ga285793254ff0adaf58c605682efb880c.html * * @param[in] n number of elements of input vector * @param[in] x a C-style array containing (1 + (@param n-1) * abs(@param incx) elements of type @tparam floating * @param[in] incx storage spacing between elements of @param x * @return index of first element having maximum absolute value */ virtual int ixamax(const int n, const floating * const x, const int incx) const = 0; /** * Function xaxpy is an abstraction of calls saxpy/daxpy/etc. * It performs the calculation y := alpha * x + y * * See also * https://www.netlib.org/lapack/explore-html/de/da4/group__double__blas__level1_ga8f99d6a644d3396aa32db472e0cfc91c.html * * @param[in] n number of elements in input vectors * @param[in] alpha scalar alpha * @param[in] x a C-style array containing (1 + (@param n-1) * abs(@param incx) elements of type @tparam floating * @param[in] incx storage spacing between elements of @param x * @param[in,out] y a C-style array containing (1 + (@param n-1) * abs(@param incy) elements of type @tparam floating * @param[in] incy storage spacing between elements of @param y */ virtual void xaxpy(const int n, const floating alpha, const floating * const x, const int incx, floating * const y, const int incy) const = 0; /** * Function xcopy is an abstraction of calls scopy/dcopy/etc. * It performs the copy operation dest := source * * See also * https://www.netlib.org/lapack/explore-html/de/da4/group__double__blas__level1_ga21cdaae1732dea58194c279fca30126d.html * @param[in] n number of elements in input vectors * @param[in] source a C-style array containing (1 + (@param n-1) * abs(@param inc_source) elements of type @tparam floating * @param[in] inc_source storage spacing between elements of @param source * @param[out] dest a C-style array containing (1 + (@param n-1) * abs(@param inc_dest) elements of type @tparam floating * @param[in] inc_dest storage spacing between elements of @param dest */ virtual void xcopy(const int n, const floating * const source, const int inc_source, floating * const dest, const int inc_dest) const = 0; /** * Function xdot is an abstraction of calls sdot/ddot/etc. * It performs the dot product <x, y> * * See also * http://www.netlib.org/lapack/explore-html/de/da4/group__double__blas__level1_ga75066c4825cb6ff1c8ec4403ef8c843a.html * * @param[in] n number of elements in input vectors * @param[in] x a C-style array containing (1 + (@param n-1) * abs(@param incx) elements of type @tparam floating * @param[in] incx spacing between elements of @param x * @param[in,out] y a C-style array containing (1 + (@param n-1) * abs(@param incy) elements of type @tparam floating * @param[in] incy spacing between elements of @param y * @return the value of the dot product <x, y> */ virtual floating xdot(const int n, const floating * const x, const int incx, const floating * const y, const int incy) const = 0; /** * Function xgemm is an abstraction of calls sgemm/dgemm/etc. * It performs the matrix product operation C := alpha * trans_A(A) * trans_B(B) + beta * C * * See also * http://www.netlib.org/lapack/explore-html/d1/d54/group__double__blas__level3_gaeda3cbd99c8fb834a60a6412878226e1.html * * @param[in] trans_A defines the transformation applied to matrix A (see enum class OperationType) * @param[in] trans_B defines the transformation applied to matrix B (see enum class OperationType) * @param[in] m the number of rows of matrix trans_A(A) and C * @param[in] n the number of columns of matrix trans_B(B) and C * @param[in] k the number of columns of matrix C * @param[in] alpha scalar applied to A * @param[in] A matrix stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] lda the first dimension of A * @param[in] B matrix stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] ldb the first dimension of B * @param[in] beta scalar applied to C * @param[in,out] C matrix stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] ldc the first dimension of C */ virtual void xgemm(const OperationType trans_A, const OperationType trans_B, const int m, const int n, const int k, const floating alpha, const floating * const A, const int lda, const floating * const B, const int ldb, const floating beta, floating * const C, const int ldc) const = 0; /** * Function xgemv is an abstraction of calls sgemv/dgemv/etc. * It performs the matrix times vector operation y := alpha * trans(A) * x + beta * y * * See also * http://www.netlib.org/lapack/explore-html/d7/d15/group__double__blas__level2_gadd421a107a488d524859b4a64c1901a9.html * * @param[in] trans defines the transformation applied to matrix A (see enum class OperationType) * @param[in] m the number of rows of matrix A * @param[in] n the number of columns of matrix A * @param[in] alpha scalar applied to A * @param[in] A matrix stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] lda the first dimension of matrix A * @param[in] x A C-style array containing (1 + (@param DIM-1) * abs(@param incx) elements of type @tparam floating. DIM is @param n if trans is OperationType::Identical, and @param m else. * @param[in] incx storage spacing between elements of @param x * @param[in] beta scalar applied to @param y * @param[in,out] y A C-style array containing (1 + (@param DIM-1) * abs(@param incy) elements of type @tparam floating. DIM is @param n if trans is OperationType::Identical, and @param m else. * @param[in] incy storage spacing between elements of @param y */ virtual void xgemv(const OperationType trans, const int m, const int n, const floating alpha, floating const * const A, const int lda, floating const * const x, const int incx, const floating beta, floating * const y, const int incy) const = 0; /** * Function xgetrf is an abstraction of calls sgetrf/dgetrf/etc. * It computes the PLU factorization of A general M-by-N matrix A. A is overwritten by L and U, * and L has unit diagonal elements. * * See also * http://www.netlib.org/lapack/explore-html/dd/d9a/group__double_g_ecomputational_ga0019443faea08275ca60a734d0593e60.html * * @param[in] m the number of rows of matrix A * @param[in] n the number of columns of matrix A * @param[in,out] A matrix stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] lda the first dimension of matrix A * @param[out] ipiv permutation array, row i of matrix A is interchanged with row ipiv[i] * @param[out] info If == 0, successful exit. If < 0, the i-th argument had illegal value. If > 0, U(i, i) is exactly 0 and cannot be used to solve A system of equations. */ virtual void xgetrf(int * const m, int * const n, floating * const A, int * const lda, int * const ipiv, int * const info) const = 0; /** * Function xgetri is an abstraction of calls sgetri/dgetri/etc. * It computes the inverse of A square matrix using its PLU factorization as calculated by xgetrf. * * See also * http://www.netlib.org/lapack/explore-html/dd/d9a/group__double_g_ecomputational_ga56d9c860ce4ce42ded7f914fdb0683ff.html * * @param[in] n order of square matrix A * @param[in,out] A LU-factorization matrix (as calculated by xgetrf) stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] lda the first dimension of matrix A * @param[in] ipiv permutation array from xgetrf * @param[out] work is temporary working space in form of A C-style array containing elements of type floating. On exit, if info == 0, work[1] returns optimal @param lwork * @param[in] lwork dimension of array @param work. If == -1, the routine calculates the optimal size of array @param work. * @param[out] info If == 0, successful exit. If < 0, the i-th argument had illegal value. If > 0, U(i, i) is exactly 0 and cannot be used to solve A system of equations. */ virtual void xgetri(const int * const n, floating * const A, const int * const lda, const int * const ipiv, floating * const work, const int * const lwork, int * const info) const = 0; /** * Function xgetrs is an abstraction of calls sgetrs/dgetrs/etc. * It solves A system of linear equations trans(A) * X = B using its PLU factorization as calculated by xgetrf. * Matrix A has to be square, and the result is stored in B. * * See also * http://www.netlib.org/lapack/explore-html/dd/d9a/group__double_g_ecomputational_ga58e332cb1b8ab770270843221a48296d.html * * @param[in] trans defines the transformation applied to matrix A (see enum class OperationType) * @param[in] n order of square matrix A * @param[in] nrhs number of right hand sides, i.e. the number of columns of B * @param[in] A LU-factorization matrix (as calculated by xgetrf) stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] lda the first dimension of matrix A * @param[in] ipiv permutation array from xgetrf * @param[in,out] B matrix of right hand sides stored as A column-wise C-style array containing elements of type @tparam floating * @param[in] ldb the first dimension of matrix B * @param[out] info If == 0, successful exit. If < 0, the i-th argument had illegal value. */ virtual void xgetrs(const OperationType trans, const int * const n, const int * const nrhs, const floating * const A, const int * const lda, const int * const ipiv, floating * const B, const int * const ldb, int * const info) const = 0; /** * Function xscal is an abstraction of calls sscal/dscal/etc. * It performs the scaling operation x := alpha * x. * * See also * http://www.netlib.org/lapack/explore-html/de/da4/group__double__blas__level1_ga793bdd0739bbd0e0ec8655a0df08981a.html * * @param n number of elements in input vectors * @param alpha scalar alpha * @param x a C-style array containing (1 + (@param n-1) * abs(@param incx) elements of type @tparam floating * @param incx storage spacing between elements of @param x */ virtual void xscal(const int n, const floating alpha, floating * const x, const int incx) const = 0; /** * Returns true if @tparam floating is float. * @return true if @tparam floating is float */ constexpr static bool isFloat(); /** * Returns true if @tparam floating is double. * @return true if @tparam floating is double */ constexpr static bool isDouble(); }; /** * Class Cpu provides linear algebra operations on the Cpu using * BLAS/LAPACK/LAPACKE. All memory allocations also take place in * ordinary RAM. * * @tparam floating floating point type, either float or double */ template<class floating> class Cpu : public ProcessingUnitDevice<floating> { public: using ProcessingUnitDevice<floating>::isFloat; using ProcessingUnitDevice<floating>::isDouble; /** * Constructor */ Cpu() = default; /** * Destructor */ ~Cpu() override = default; Timer create_timer() const override; MemoryManager get_memory_manager() const override; std::string display() const override; int ixamax(const int n, const floating * const x, const int incx) const override; void xaxpy(const int n, const floating alpha, const floating * const x, const int incx, floating * const y, const int incy) const override; void xcopy(const int n, const floating * const source, const int inc_source, floating * const dest, const int inc_dest) const override; floating xdot(const int n, const floating * const x, const int incx, const floating * const y, const int incy) const override; void xgemm(const OperationType trans_A, const OperationType trans_B, const int M, const int N, const int K, const floating alpha, const floating * const A, const int lda, const floating * const B, const int ldb, const floating beta, floating * const C, const int ldc) const override; void xgemv(const OperationType trans, const int m, const int n, const floating alpha, floating const * const A, const int lda, floating const * const x, const int incx, const floating beta, floating * const y, const int incy) const override; void xgetrf(int * const m, int * const n, floating * const A, int * const lda, int * const ipiv, int * const info) const override; void xgetri(const int * const n, floating * const A, const int * const lda, const int * const ipiv, floating * const work, const int * const lwork, int * const info) const override; void xgetrs(const OperationType trans, const int * const n, const int * const nrhs, const floating * const A, const int * const lda, const int * const ipiv, floating * const B, const int * const ldb, int * const info) const override; void xscal(const int N, const floating alpha, floating * const x, const int incx) const override; private: static std::map<OperationType, CBLAS_TRANSPOSE> to_internal_operation_blas; //!< Converts the OperationType to the corresponding CBLAS_TRANSPOSE type static std::map<OperationType, const char * const> to_internal_operation_lapack; //!< Converts the OperationType to the corresponding LAPACK transposition type static MemoryManager _device_manager; //!< Memory manager associated with Cpu memory }; #ifndef CPU_ONLY /** * Class Gpu provides linear algebra operations on the Gpu using * cuBLAS/cuSOLVER. All memory allocations also take place in * Gpu RAM. * * @tparam floating floating point type, either float or double */ template<class floating> class Gpu : public ProcessingUnitDevice<floating> { public: using ProcessingUnitDevice<floating>::isFloat; using ProcessingUnitDevice<floating>::isDouble; /** * Constructor */ Gpu() = default; /** * Destructor */ ~Gpu() override = default; Timer create_timer() const override; MemoryManager get_memory_manager() const override; std::string display() const override; /** * Returns the instance's cuBLAS handle. * @return cuBLAS handle */ auto get_cublas_handle() const; /** * Returns the instance's cuSOLVER handle. * @return cuSOLVER handle */ auto get_cusolver_handle() const; int ixamax(const int n, const floating * const x, const int incx) const override; void xaxpy(const int n, const floating alpha, const floating * const x, const int incx, floating * const y, const int incy) const override; void xcopy(const int n, const floating * const source, const int inc_source, floating * const dest, const int inc_dest) const override; floating xdot(const int n, const floating * const x, const int incx, const floating * const y, const int incy) const override; void xgemm(const OperationType trans_A, const OperationType trans_B, const int M, const int N, const int K, const floating alpha, const floating * const A, const int lda, const floating * const B, const int ldb, const floating beta, floating * const C, const int ldc) const override; void xgemv(const OperationType trans, const int m, const int n, const floating alpha, floating const * const A, const int lda, floating const * const x, const int incx, const floating beta, floating * const y, const int incy) const override; void xgetrf(int * const m, int * const n, floating * const A, int * const lda, int * const ipiv, int * const info) const override; void xgetri(const int * const n, floating * const A, const int * const lda, const int * const ipiv, floating * const work, const int * const lwork, int * const info) const override; void xgetrs(const OperationType trans, const int * const n, const int * const nrhs, const floating * const A, const int * const lda, const int * const ipiv, floating * const B, const int * const ldb, int * const info) const override; void xscal(const int N, const floating alpha, floating * const x, const int incx) const override; private: static std::map<OperationType, cublasOperation_t> to_internal_operation; //!< Converts the OperationType to the corresponding cuBLAS operation type static GpuHandle _handle; //!< Gpu handle for cuBLAS/cuSOLVER operations static MemoryManager _deviceManager; //!< Memory manager associated with CUDA memory }; #ifdef MAGMA /** * Class GpuMagma provides linear algebra operations on the Gpu using * MAGMA. All memory allocations also take place in Gpu RAM. * * @tparam floating floating point type, either float or double */ template<class floating> class GpuMagma : public ProcessingUnitDevice<floating> { public: using ProcessingUnitDevice<floating>::isFloat; using ProcessingUnitDevice<floating>::isDouble; /** * Constructor */ GpuMagma() = default; /** * Destructor */ ~GpuMagma() override = default; Timer create_timer() const override; MemoryManager get_memory_manager() const override; std::string display() const override; /** * Returns the instance's magma queue. */ auto get_magma_queue() const; int ixamax(const int n, const floating * const x, const int incx) const override; void xaxpy(const int n, const floating alpha, const floating * const x, const int incx, floating * const y, const int incy) const override; void xcopy(const int n, const floating * const source, const int inc_source, floating * const dest, const int inc_dest) const override; floating xdot(const int n, const floating * const x, const int incx, const floating * const y, const int incy) const override; void xgemm(const OperationType trans_A, const OperationType trans_B, const int M, const int N, const int K, const floating alpha, const floating * const A, const int lda, const floating * const B, const int ldb, const floating beta, floating * const C, const int ldc) const override; void xgemv(const OperationType trans, const int m, const int n, const floating alpha, floating const * const A, const int lda, floating const * const x, const int incx, const floating beta, floating * const y, const int incy) const override; void xgetrf(int * const m, int * const n, floating * const A, int * const lda, int * const ipiv, int * const info) const override; void xgetri(const int * const n, floating * const A, const int * const lda, const int * const ipiv, floating * const work, const int * const lwork, int * const info) const override; void xgetrs(const OperationType trans, const int * const n, const int * const nrhs, const floating * const A, const int * const lda, const int * const ipiv, floating * const B, const int * const ldb, int * const info) const override; void xscal(const int N, const floating alpha, floating * const x, const int incx) const override; private: static std::map<OperationType, magma_trans_t> to_internal_operation; //!< Converts the OperationType to the corresponding MAGMA transposition type static GpuMagmaQueue _queue; //!< MAGMA queue for MAGMA operations static MemoryManager _device_manager; //!< Memory manager associated with CUDA memory }; /** * Class ReplacementNumber is used for passing the operation to GpuMixed, which is then calculated via * GpuMagma instead of ordinary Gpu processing unit. */ enum class ReplacementNumber { IXAMAX, XAXPY, XCOPY, XDOT, XGEMM, XGEMV, XGETRF, XGETRS, XSCAL }; /** * Class GpuMixed provides linear algebra operations on the Gpu using * cuBLAS/cuSOLVER, except for the one operation specified by replacementNumber, * which is calculated using MAGMA. * All memory allocations also take place in Gpu RAM. * * @tparam floating floating point type, either float or double */ template<class floating> class GpuMixed : public ProcessingUnitDevice<floating> { public: /** * Constructor */ GpuMixed(const ReplacementNumber replacementNumber = ReplacementNumber::XGETRF); /** * Destructor */ ~GpuMixed() override = default; Timer create_timer() const override; MemoryManager get_memory_manager() const override; std::string display() const override; int ixamax(const int n, const floating * const x, const int incx) const override; void xaxpy(const int n, const floating alpha, const floating * const x, const int incx, floating * const y, const int incy) const override; void xcopy(const int n, const floating * const source, const int inc_source, floating * const dest, const int inc_dest) const override; floating xdot(const int n, const floating * const x, const int incx, const floating * const y, const int incy) const override; void xgemm(const OperationType trans_A, const OperationType trans_B, const int M, const int N, const int K, const floating alpha, const floating * const A, const int lda, const floating * const B, const int ldb, const floating beta, floating * const C, const int ldc) const override; void xgemv(const OperationType trans, const int m, const int n, const floating alpha, floating const * const A, const int lda, floating const * const x, const int incx, const floating beta, floating * const y, const int incy) const override; void xgetrf(int * const m, int * const n, floating * const A, int * const lda, int * const ipiv, int * const info) const override; void xgetri(const int * const n, floating * const A, const int * const lda, const int * const ipiv, floating * const work, const int * const lwork, int * const info) const override; void xgetrs(const OperationType trans, const int * const n, const int * const nrhs, const floating * const A, const int * const lda, const int * const ipiv, floating * const B, const int * const ldb, int * const info) const override; void xscal(const int N, const floating alpha, floating * const x, const int incx) const override; ReplacementNumber get_replacement_number() const; private: static Gpu<floating> _gpu; //!< Gpu processing unit static GpuMagma<floating> _gpu_magma; //!< MAGMA processing unit ReplacementNumber _replacementNumber; //!< current instance's operation which should be exectued on MAGMA instead of cuBLAS/cuSOLVER }; #endif #endif #include "processingunit.hpp" #include "processingunit_cpu.hpp" #ifndef CPU_ONLY #include "processingunit_gpu.hpp" #ifdef MAGMA #include "processingunit_gpu_magma.hpp" #include "processingunit_gpu_mixed.hpp" #endif #endif #endif
{ "alphanum_fraction": 0.6896774684, "avg_line_length": 48.0658135283, "ext": "h", "hexsha": "266c7db1d6dc847bb3ab05b2c2b4c4309acdbe14", "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": "a740e3d5c88ed68bb57cb15b420d2b7e2d8a52c6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "meteoritenhagel/fractional-pde", "max_forks_repo_path": "src/processingunit/processingunit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a740e3d5c88ed68bb57cb15b420d2b7e2d8a52c6", "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": "meteoritenhagel/fractional-pde", "max_issues_repo_path": "src/processingunit/processingunit.h", "max_line_length": 197, "max_stars_count": null, "max_stars_repo_head_hexsha": "a740e3d5c88ed68bb57cb15b420d2b7e2d8a52c6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "meteoritenhagel/fractional-pde", "max_stars_repo_path": "src/processingunit/processingunit.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6560, "size": 26292 }
#pragma once #include <list> #include <vector> #include <optional> #include <memory> #include <functional> #include <gsl/gsl-lite.hpp> #include "UtilMacros.Namespace.h" #include "util.std_aliases.h" #include "zstring_view.h" NAMESPACE_BEGIN( cpp ) using vlr::string; using vlr::wstring; using vlr::tstring; using vlr::zstring_view; using vlr::wzstring_view; using vlr::tzstring_view; using std::shared_ptr; using std::weak_ptr; using std::make_shared; using std::function; using gsl::span; NAMESPACE_END //( cpp )
{ "alphanum_fraction": 0.7456978967, "avg_line_length": 15.8484848485, "ext": "h", "hexsha": "33e48bd391399197aa1ca96027d0f659a4347f9f", "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": "937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91", "max_forks_repo_licenses": [ "Artistic-2.0" ], "max_forks_repo_name": "nick42/vlr-util", "max_forks_repo_path": "vlr-util/cpp_namespace.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Artistic-2.0" ], "max_issues_repo_name": "nick42/vlr-util", "max_issues_repo_path": "vlr-util/cpp_namespace.h", "max_line_length": 33, "max_stars_count": null, "max_stars_repo_head_hexsha": "937f53dd4d3e15b23d615b085f5bf4a8e6b9cd91", "max_stars_repo_licenses": [ "Artistic-2.0" ], "max_stars_repo_name": "nick42/vlr-util", "max_stars_repo_path": "vlr-util/cpp_namespace.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 136, "size": 523 }
/* * Copyright (C) 2021 FISCO BCOS. * SPDX-License-Identifier: Apache-2.0 * 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. * * @brief interface of Table * @file Table.h * @author: xingqiangbai * @date: 2021-04-07 */ #pragma once #include "../../interfaces/protocol/ProtocolTypeDef.h" #include "../../libutilities/Error.h" #include "boost/algorithm/string.hpp" #include "tbb/spin_mutex.h" #include "tbb/spin_rw_mutex.h" #include <boost/throw_exception.hpp> #include <algorithm> #include <any> #include <cstdlib> #include <gsl/span> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #define STORAGE_LOG(LEVEL) BCOS_LOG(LEVEL) << "[STORAGE]" namespace bcos { namespace storage { enum StorageError { UnknownError = -60000, TableNotExists, SystemTableNotExists, TableExists, UnknownEntryType, ReadError, WriteError, EmptyStorage, ReadOnly, }; struct Condition { Condition() = default; ~Condition() = default; void NE(const std::string& value) { m_conditions.emplace_back(Comparator::NE, value); } // string compare, "2" > "12" void GT(const std::string& value) { m_conditions.emplace_back(Comparator::GT, value); } void GE(const std::string& value) { m_conditions.emplace_back(Comparator::GE, value); } // string compare, "12" < "2" void LT(const std::string& value) { m_conditions.emplace_back(Comparator::LT, value); } void LE(const std::string& value) { m_conditions.emplace_back(Comparator::LE, value); } void limit(size_t start, size_t end) { m_limit = std::pair<size_t, size_t>(start, end); } std::pair<size_t, size_t> getLimit() const { return m_limit; } bool isValid(const std::string_view& key) const { // all conditions must be satisfied for (auto& cond : m_conditions) { // conditions should few, so not parallel check for now switch (cond.cmp) { case Comparator::NE: if (key == cond.value) { return false; } break; case Comparator::GT: if (key <= cond.value) { return false; } break; case Comparator::GE: if (key < cond.value) { return false; } break; case Comparator::LT: if (key >= cond.value) { return false; } break; case Comparator::LE: if (key > cond.value) { return false; } break; default: // undefined Comparator break; } } return true; } enum class Comparator { EQ, NE, GT, GE, LT, LE, }; struct cond { cond(Comparator _cmp, const std::string& _value) : cmp(_cmp), value(_value) {} Comparator cmp; std::string value; }; std::vector<cond> m_conditions; std::pair<size_t, size_t> m_limit; }; class TableInfo { public: using Ptr = std::shared_ptr<TableInfo>; using ConstPtr = std::shared_ptr<const TableInfo>; TableInfo(std::string name, std::vector<std::string> fields) : m_name(std::move(name)), m_fields(std::move(fields)) { m_order.reserve(m_fields.size()); for (size_t i = 0; i < m_fields.size(); ++i) { m_order.push_back({m_fields[i], i}); } std::sort(m_order.begin(), m_order.end(), [](auto&& lhs, auto&& rhs) { return std::get<0>(lhs) < std::get<0>(rhs); }); } std::string_view name() const { return m_name; } const std::vector<std::string>& fields() const { return m_fields; } size_t fieldIndex(const std::string_view& field) const { auto it = std::lower_bound(m_order.begin(), m_order.end(), field, [](auto&& lhs, auto&& rhs) { return std::get<0>(lhs) < rhs; }); if (it != m_order.end() && std::get<0>(*it) == field) { return std::get<1>(*it); } else { BOOST_THROW_EXCEPTION( BCOS_ERROR(-1, std::string("Can't find field: ") + std::string(field))); } } private: std::string m_name; std::vector<std::string> m_fields; std::vector<std::tuple<std::string_view, size_t>> m_order; private: void* operator new(size_t s) { return malloc(s); }; void operator delete(void* p) { free(p); }; }; } // namespace storage } // namespace bcos
{ "alphanum_fraction": 0.5655316721, "avg_line_length": 28.2634408602, "ext": "h", "hexsha": "18c411a922791d42b4731d958a66f792422c596b", "lang": "C", "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.000Z", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_path": "bcos-framework/interfaces/storage/Common.h", "max_issues_count": 267, "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_path": "bcos-framework/interfaces/storage/Common.h", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_path": "bcos-framework/interfaces/storage/Common.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1261, "size": 5257 }
#include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_ntuple.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> struct data { int num; double x; double y; double z; }; int sel_func (void *ntuple_data, void * params); double val_func (void *ntuple_data, void * params); int main (void) { struct data ntuple_row; int i; double x[1000], y[1000], z[1000], f[100]; gsl_ntuple_select_fn S; gsl_ntuple_value_fn V; double scale = 1.5; gsl_ieee_env_setup (); /* zero struct including padding bytes to avoid valgrind errors */ memset(&ntuple_row, 0, sizeof(struct data)); S.function = &sel_func; S.params = &scale; V.function = &val_func; V.params = &scale; { gsl_ntuple *ntuple = gsl_ntuple_create ("test.dat", &ntuple_row, sizeof (ntuple_row)); int status = 0; for (i = 0; i < 100; i++) f[i] = 0; for (i = 0; i < 1000; i++) { double xi = 1.0 / (i + 1.5); double yi = xi * xi ; double zi = xi * xi * xi; ntuple_row.x = xi; ntuple_row.y = yi; ntuple_row.z = zi; ntuple_row.num = i; x[i] = xi; y[i] = yi; z[i] = zi; if (xi * scale < 0.1) { double v = xi + yi + zi; int k = (int)(100.0*v*scale); f[k]++; } /* printf ("x,y,z = %f,%f,%f; n=%x \n", ntuple_row.x, ntuple_row.y, ntuple_row.z, ntuple_row.num); */ { int s = gsl_ntuple_bookdata (ntuple); if (s != GSL_SUCCESS) { status = 1; } } } gsl_ntuple_close (ntuple); gsl_test (status, "writing ntuples"); } { gsl_ntuple *ntuple = gsl_ntuple_open ("test.dat", &ntuple_row, sizeof (ntuple_row)); int status = 0; for (i = 0; i < 1000; i++) { gsl_ntuple_read (ntuple); status = (ntuple_row.num != i); status |= (ntuple_row.x != x[i]); status |= (ntuple_row.y != y[i]); status |= (ntuple_row.z != z[i]); /* printf ("x,y,z = %f,%f,%f; n=%d\n", ntuple_row.x, ntuple_row.y, ntuple_row.z, ntuple_row.num); */ } gsl_ntuple_close (ntuple); gsl_test (status, "reading ntuples"); } { int status = 0; gsl_ntuple *ntuple = gsl_ntuple_open ("test.dat", &ntuple_row, sizeof (ntuple_row)); gsl_histogram *h = gsl_histogram_calloc_uniform (100, 0., 1.); gsl_ntuple_project (h, ntuple, &V, &S); gsl_ntuple_close (ntuple); /* gsl_histogram_fprintf (stdout, h, "%f", "%f"); */ for (i = 0; i < 100; i++) { /* printf ("h %g f %g\n", h->bin[i], f[i]); */ if (h->bin[i] != f[i]) { status = 1; } } gsl_test (status, "histogramming ntuples"); gsl_histogram_free (h); } exit (gsl_test_summary()); } int sel_func (void *ntuple_data, void * params) { double x, y, z, scale; scale = *(double *)params; x = ((struct data *) ntuple_data)->x; y = ((struct data *) ntuple_data)->y; z = ((struct data *) ntuple_data)->z; return (x*scale < 0.1); } double val_func (void *ntuple_data, void * params) { double x, y, z, scale; scale = *(double *)params; x = ((struct data *) ntuple_data)->x; y = ((struct data *) ntuple_data)->y; z = ((struct data *) ntuple_data)->z; return (x + y + z) * scale; }
{ "alphanum_fraction": 0.5078299776, "avg_line_length": 21.4131736527, "ext": "c", "hexsha": "0827c131c162be8e6bc811797914b0023579faa0", "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/ntuple/test.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/ntuple/test.c", "max_line_length": 69, "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/ntuple/test.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": 1089, "size": 3576 }
#include <math.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_randist.h> double t_test(const double *data1, int n1, const double *data2, int n2) { double mean1, mean2, var1, var2, num, sp, denom, t, dof, p; mean1 = gsl_stats_mean(data1, 1, n1); mean2 = gsl_stats_mean(data2, 1, n2); var1 = gsl_stats_variance(data1, 1, n1); var2 = gsl_stats_variance(data2, 1, n2); num = mean1 - mean2; sp = sqrt((((n1 - 1) * var1) + ((n2 - 1) * var2)) / (n1 + n2 - 2)); denom = sp * sqrt((1 / (double) n1) + (1 / (double) n2)); t = fabs(num / denom); dof = (double) n1 + n2 - 2; p = (1 - gsl_cdf_tdist_P(t, dof)) * 2; return p; }
{ "alphanum_fraction": 0.5916666667, "avg_line_length": 32.7272727273, "ext": "c", "hexsha": "3b360ddc5e11c2fa16d74e6344068ef0500b6637", "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": "96a89cf9ee32a074185ffce842a999975ba0de19", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kgoettler/python-c-ext", "max_forks_repo_path": "python-c-api/v2/ttest.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "96a89cf9ee32a074185ffce842a999975ba0de19", "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": "kgoettler/python-c-ext", "max_issues_repo_path": "python-c-api/v2/ttest.c", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "96a89cf9ee32a074185ffce842a999975ba0de19", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kgoettler/python-c-ext", "max_stars_repo_path": "python-c-api/v2/ttest.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 277, "size": 720 }
/* siman/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_siman.h> #include <gsl/gsl_ieee_utils.h> #include <stdio.h> /* set up parameters for this simulated annealing run */ #define N_TRIES 200 /* how many points do we try before stepping */ #define ITERS_FIXED_T 1000 /* how many iterations for each T? */ #define STEP_SIZE 1.0 /* max step size in random walk */ #define K 1.0 /* Boltzmann constant */ #define T_INITIAL 0.008 /* initial temperature */ #define MU_T 1.003 /* damping factor for temperature */ #define T_MIN 2.0e-6 gsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN}; double square (double x) ; double square (double x) { return x * x ; } double E1(void *xp); double M1(void *xp, void *yp); void S1(const gsl_rng * r, void *xp, double step_size); void P1(void *xp); /* now some functions to test in one dimension */ double E1(void *xp) { double x = * ((double *) xp); return exp(-square(x-1))*sin(8*x) - exp(-square(x-1000))*0.89; } double M1(void *xp, void *yp) { double x = *((double *) xp); double y = *((double *) yp); return fabs(x - y); } void S1(const gsl_rng * r, void *xp, double step_size) { double old_x = *((double *) xp); double new_x; new_x = gsl_rng_uniform(r)*2*step_size - step_size + old_x; memcpy(xp, &new_x, sizeof(new_x)); } void P1(void *xp) { printf(" %12g ", *((double *) xp)); } int main(void) { double x_min = 1.36312999455315182 ; double x ; gsl_rng * r = gsl_rng_alloc (gsl_rng_env_setup()) ; gsl_ieee_env_setup (); /* The function tested here has multiple mimima. The global minimum is at x = 1.36312999, (f = -0.87287) There is a local minimum at x = 0.60146196, (f = -0.84893) */ x = -10.0 ; gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL, sizeof(double), params); gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=-10") ; x = +10.0 ; gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL, sizeof(double), params); gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=10") ; /* Start at the false minimum */ x = +0.6 ; gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL, sizeof(double), params); gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.6") ; x = +0.5 ; gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL, sizeof(double), params); gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.5") ; x = +0.4 ; gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL, sizeof(double), params); gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.4") ; gsl_rng_free(r); exit (gsl_test_summary ()); #ifdef JUNK x0.D1 = 12.0; printf("#one dimensional problem, x0 = %f\n", x0.D1); gsl_siman_Usolve(r, &x0, test_E_1D, test_step_1D, distance_1D, print_pos_1D, params); x0.D2[0] = 12.0; x0.D2[1] = 5.5; printf("#two dimensional problem, (x0,y0) = (%f,%f)\n", x0.D2[0], x0.D2[1]); gsl_siman_Usolve(r, &x0, test_E_2D, test_step_2D, distance_2D, print_pos_2D, params); x0.D3[0] = 12.2; x0.D3[1] = 5.5; x0.D3[2] = -15.5; printf("#three dimensional problem, (x0,y0,z0) = (%f,%f,%f)\n", x0.D3[0], x0.D3[1], x0.D3[2]); gsl_siman_Usolve(r, &x0, test_E_3D, test_step_3D, distance_3D, print_pos_3D, params); x0.D2[0] = 12.2; x0.D2[1] = 5.5; gsl_siman_solve(r, &x0, test_E_2D, test_step_2D, distance_2D, print_pos_2D, params); x0.D3[0] = 12.2; x0.D3[1] = 5.5; x0.D3[2] = -15.5; gsl_siman_solve(r, &x0, test_E_3D, test_step_3D, distance_3D, print_pos_3D, params); return 0; #endif }
{ "alphanum_fraction": 0.6146249212, "avg_line_length": 29.1963190184, "ext": "c", "hexsha": "e7c5e02a440369e1ae07c0849867d5cb4cae8238", "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/siman/test.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/siman/test.c", "max_line_length": 86, "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/siman/test.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": 1652, "size": 4759 }
#ifndef SYNAPSE_H_ #define SYNAPSE_H_ #include "spike_train.h" #include <gsl/gsl_rng.h> namespace neurophys { class DynamicSynapse { public: virtual SpikeTrain filter(const SpikeTrain& in) = 0; }; class FDSynapse: public DynamicSynapse { public: static const int STATIC = 0; static const int DEPRESSING = 1; static const int FACILITATING = 2; static const int GENERAL = DEPRESSING | FACILITATING; static const int KEEP_STATE_VARIABLES = 4; // no reset between trials FDSynapse(double F0, double tau_f, double tau_d, double delta, int flags): F0_(F0), tau_f_(tau_f), tau_d_(tau_d), delta_(delta), flags_(flags), FC0_(0), t_(0) {}; protected: const double F0_; const double tau_f_; const double tau_d_; const double delta_; const int flags_; double FC0_; double t_; }; class DeterministicFDSynapse: public FDSynapse { public: DeterministicFDSynapse(double F0, double tau_f, double tau_d, double delta, int flags): FDSynapse(F0, tau_f, tau_d, delta, flags), D0_(0) {}; virtual SpikeTrain filter(const SpikeTrain& in); private: double D0_; }; // rng in constructor is not so nice -- make explicit as param of filter and // screw poplymorphism? class StochasticFDSynapse: public FDSynapse { public: StochasticFDSynapse(double F0, double tau_f, double tau_d, double delta, int flags, gsl_rng* rng, unsigned int n_release_sites): FDSynapse(F0, tau_f, tau_d, delta, flags), rng_(rng), n_release_sites_(n_release_sites), n_ves_present_(n_release_sites) {}; virtual SpikeTrain filter(const SpikeTrain& in); private: gsl_rng* rng_; const unsigned int n_release_sites_; unsigned int n_ves_present_; }; } #endif // SYNAPSE_H_
{ "alphanum_fraction": 0.7330981775, "avg_line_length": 26.1692307692, "ext": "h", "hexsha": "46308e04d7644a31b60c292ae8805c28ec59ceed", "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": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ModelDBRepository/228604", "max_forks_repo_path": "simulation/neurophys/synapse.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "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": "ModelDBRepository/228604", "max_issues_repo_path": "simulation/neurophys/synapse.h", "max_line_length": 126, "max_stars_count": null, "max_stars_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ModelDBRepository/228604", "max_stars_repo_path": "simulation/neurophys/synapse.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 470, "size": 1701 }
static char help[] = "Broker for DYNHELICS\n"; #include <stdio.h> #include <unistd.h> #include <helics.h> #include <petsc.h> int main(int argc,char **argv) { helics_broker broker; const char* helicsversion; int isconnected; char initstring[PETSC_MAX_PATH_LEN]; PetscInt nfederates=0; PetscErrorCode ierr; PetscInitialize(&argc,&argv,"petscopt",help); helicsversion = helicsGetVersion(); printf("BROKER: Helics version = %s\n",helicsversion); printf("%s",help); ierr = PetscOptionsGetInt(NULL,NULL,"-nfeds",&nfederates,NULL);CHKERRQ(ierr); if(!nfederates) { SETERRQ(PETSC_COMM_SELF,0,"Number of federates need to be given with option -nfeds"); } ierr = PetscSNPrintf(initstring,PETSC_MAX_PATH_LEN-1,"%d",nfederates); ierr = PetscStrcat(initstring," --name=mainbroker"); /* Create broker */ broker = helicsCreateBroker("zmq","",initstring); isconnected = helicsBrokerIsConnected(broker); if(isconnected) { printf("BROKER: Created and connected\n"); } while(helicsBrokerIsConnected(broker)) { usleep(1000); /* Sleep for 1 millisecond */ } printf("BROKER: disconnected\n"); helicsBrokerFree(broker); helicsCloseLibrary(); printf("Helics library closed\n"); PetscFinalize(); return 0; }
{ "alphanum_fraction": 0.6911764706, "avg_line_length": 24.3773584906, "ext": "c", "hexsha": "d6940b2bc7d1eed59dc92a46f6b8ce3674692668", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z", "max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "GMLC-TDC/Use-Cases", "max_forks_repo_path": "ANL-TD-Iterative-Pflow/helics-broker.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "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": "GMLC-TDC/Use-Cases", "max_issues_repo_path": "ANL-TD-Iterative-Pflow/helics-broker.c", "max_line_length": 89, "max_stars_count": 1, "max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "GMLC-TDC/Use-Cases", "max_stars_repo_path": "ANL-TD-Iterative-Pflow/helics-broker.c", "max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z", "num_tokens": 361, "size": 1292 }
/** * * @file qwrapper_cgemm.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @author Mathieu Faverge * @author Jakub Kurzak * @date 2010-11-15 * @generated c Tue Jan 7 11:44:56 2014 * **/ #include <cblas.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_cgemm(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda, const PLASMA_Complex32_t *B, int ldb, PLASMA_Complex32_t beta, PLASMA_Complex32_t *C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_cgemm_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex32_t), &alpha, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex32_t), &beta, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, C, INOUT, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ void QUARK_CORE_cgemm2( Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda, const PLASMA_Complex32_t *B, int ldb, PLASMA_Complex32_t beta, PLASMA_Complex32_t *C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_cgemm_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex32_t), &alpha, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex32_t), &beta, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, C, INOUT | LOCALITY | GATHERV, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cgemm_quark = PCORE_cgemm_quark #define CORE_cgemm_quark PCORE_cgemm_quark #endif void CORE_cgemm_quark(Quark *quark) { PLASMA_enum transA; PLASMA_enum transB; int m; int n; int k; PLASMA_Complex32_t alpha; PLASMA_Complex32_t *A; int lda; PLASMA_Complex32_t *B; int ldb; PLASMA_Complex32_t beta; PLASMA_Complex32_t *C; int ldc; quark_unpack_args_13(quark, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); cblas_cgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, m, n, k, CBLAS_SADDR(alpha), A, lda, B, ldb, CBLAS_SADDR(beta), C, ldc); } /***************************************************************************//** * **/ void QUARK_CORE_cgemm_f2(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda, const PLASMA_Complex32_t *B, int ldb, PLASMA_Complex32_t beta, PLASMA_Complex32_t *C, int ldc, PLASMA_Complex32_t *fake1, int szefake1, int flag1, PLASMA_Complex32_t *fake2, int szefake2, int flag2) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_cgemm_f2_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex32_t), &alpha, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex32_t), &beta, VALUE, sizeof(PLASMA_Complex32_t)*nb*nb, C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, sizeof(PLASMA_Complex32_t)*szefake1, fake1, flag1, sizeof(PLASMA_Complex32_t)*szefake2, fake2, flag2, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cgemm_f2_quark = PCORE_cgemm_f2_quark #define CORE_cgemm_f2_quark PCORE_cgemm_f2_quark #endif void CORE_cgemm_f2_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex32_t alpha; PLASMA_Complex32_t *A; int LDA; PLASMA_Complex32_t *B; int LDB; PLASMA_Complex32_t beta; PLASMA_Complex32_t *C; int LDC; void *fake1, *fake2; quark_unpack_args_15(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC, fake1, fake2); cblas_cgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), C, LDC); } /***************************************************************************//** * **/ void QUARK_CORE_cgemm_p2(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda, const PLASMA_Complex32_t **B, int ldb, PLASMA_Complex32_t beta, PLASMA_Complex32_t *C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_cgemm_p2_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex32_t), &alpha, VALUE, sizeof(PLASMA_Complex32_t)*lda*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex32_t*), B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex32_t), &beta, VALUE, sizeof(PLASMA_Complex32_t)*ldc*nb, C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cgemm_p2_quark = PCORE_cgemm_p2_quark #define CORE_cgemm_p2_quark PCORE_cgemm_p2_quark #endif void CORE_cgemm_p2_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex32_t alpha; PLASMA_Complex32_t *A; int LDA; PLASMA_Complex32_t **B; int LDB; PLASMA_Complex32_t beta; PLASMA_Complex32_t *C; int LDC; quark_unpack_args_13(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC); cblas_cgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, *B, LDB, CBLAS_SADDR(beta), C, LDC); } /***************************************************************************//** * **/ void QUARK_CORE_cgemm_p3(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda, const PLASMA_Complex32_t *B, int ldb, PLASMA_Complex32_t beta, PLASMA_Complex32_t **C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_cgemm_p3_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex32_t), &alpha, VALUE, sizeof(PLASMA_Complex32_t)*lda*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex32_t)*ldb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex32_t), &beta, VALUE, sizeof(PLASMA_Complex32_t*), C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cgemm_p3_quark = PCORE_cgemm_p3_quark #define CORE_cgemm_p3_quark PCORE_cgemm_p3_quark #endif void CORE_cgemm_p3_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex32_t alpha; PLASMA_Complex32_t *A; int LDA; PLASMA_Complex32_t *B; int LDB; PLASMA_Complex32_t beta; PLASMA_Complex32_t **C; int LDC; quark_unpack_args_13(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC); cblas_cgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), *C, LDC); } /***************************************************************************//** * **/ void QUARK_CORE_cgemm_p2f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda, const PLASMA_Complex32_t **B, int ldb, PLASMA_Complex32_t beta, PLASMA_Complex32_t *C, int ldc, PLASMA_Complex32_t *fake1, int szefake1, int flag1) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_cgemm_p2f1_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex32_t), &alpha, VALUE, sizeof(PLASMA_Complex32_t)*lda*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex32_t*), B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex32_t), &beta, VALUE, sizeof(PLASMA_Complex32_t)*ldc*nb, C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, sizeof(PLASMA_Complex32_t)*szefake1, fake1, flag1, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cgemm_p2f1_quark = PCORE_cgemm_p2f1_quark #define CORE_cgemm_p2f1_quark PCORE_cgemm_p2f1_quark #endif void CORE_cgemm_p2f1_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex32_t alpha; PLASMA_Complex32_t *A; int LDA; PLASMA_Complex32_t **B; int LDB; PLASMA_Complex32_t beta; PLASMA_Complex32_t *C; int LDC; void *fake1; quark_unpack_args_14(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC, fake1); cblas_cgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, *B, LDB, CBLAS_SADDR(beta), C, LDC); }
{ "alphanum_fraction": 0.4855321587, "avg_line_length": 38.3571428571, "ext": "c", "hexsha": "7e43294973da722db6102826aeaba3140a5d5d8f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_cgemm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_cgemm.c", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_cgemm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3822, "size": 13962 }
#ifndef TETRA_DOS_ELHAMILTONIAN_H #define TETRA_DOS_ELHAMILTONIAN_H #include <gsl/gsl_math.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "environment.h" void ElHamiltonian_Recip(Environment *env, double k[3], gsl_matrix_complex *H); void ElHamiltonian(Environment *env, double k[3], gsl_matrix_complex *H); gsl_complex EpsilonAE(Environment *env, double k[3]); gsl_complex EpsilonBE(Environment *env, double k[3]); gsl_complex EpsilonAO(Environment *env, double k[3]); gsl_complex EpsilonBO(Environment *env, double k[3]); #endif // TETRA_DOS_ELHAMILTONIAN_H
{ "alphanum_fraction": 0.7826725404, "avg_line_length": 27.24, "ext": "h", "hexsha": "eeae60fd78a29af10873c7151eae0d22acc02905", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-18T15:11:23.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-18T15:11:23.000Z", "max_forks_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/vo2mft", "max_forks_repo_path": "tetra_dos/elHamiltonian.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "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/vo2mft", "max_issues_repo_path": "tetra_dos/elHamiltonian.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/vo2mft", "max_stars_repo_path": "tetra_dos/elHamiltonian.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 203, "size": 681 }
/* rng/ranlux.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 <stdlib.h> #include <gsl/gsl_rng.h> /* This is a lagged fibonacci generator with skipping developed by Luescher. The sequence is a series of 24-bit integers, x_n, x_n = d_n + b_n where d_n = x_{n-10} - x_{n-24} - c_{n-1}, b_n = 0 if d_n >= 0 and b_n = 2^24 if d_n < 0, c_n = 0 if d_n >= 0 and c_n = 1 if d_n < 0, where after 24 samples a group of p integers are "skipped", to reduce correlations. By default p = 199, but can be increased to 365. The period of the generator is around 10^171. From: M. Luescher, "A portable high-quality random number generator for lattice field theory calculations", Computer Physics Communications, 79 (1994) 100-110. Available on the net as hep-lat/9309020 at http://xxx.lanl.gov/ See also, F. James, "RANLUX: A Fortran implementation of the high-quality pseudo-random number generator of Luscher", Computer Physics Communications, 79 (1994) 111-114 Kenneth G. Hamilton, F. James, "Acceleration of RANLUX", Computer Physics Communications, 101 (1997) 241-248 Kenneth G. Hamilton, "Assembler RANLUX for PCs", Computer Physics Communications, 101 (1997) 249-253 */ static inline unsigned long int ranlux_get (void *vstate); static double ranlux_get_double (void *vstate); static void ranlux_set_lux (void *state, unsigned long int s, unsigned int luxury); static void ranlux_set (void *state, unsigned long int s); static void ranlux389_set (void *state, unsigned long int s); static const unsigned long int mask_lo = 0x00ffffffUL; /* 2^24 - 1 */ static const unsigned long int mask_hi = ~0x00ffffffUL; static const unsigned long int two24 = 16777216; /* 2^24 */ typedef struct { unsigned int i; unsigned int j; unsigned int n; unsigned int skip; unsigned int carry; unsigned long int u[24]; } ranlux_state_t; static inline unsigned long int increment_state (ranlux_state_t * state); static inline unsigned long int increment_state (ranlux_state_t * state) { unsigned int i = state->i; unsigned int j = state->j; long int delta = state->u[j] - state->u[i] - state->carry; if (delta & mask_hi) { state->carry = 1; delta &= mask_lo; } else { state->carry = 0; } state->u[i] = delta; if (i == 0) { i = 23; } else { i--; } state->i = i; if (j == 0) { j = 23; } else { j--; } state->j = j; return delta; } static inline unsigned long int ranlux_get (void *vstate) { ranlux_state_t *state = (ranlux_state_t *) vstate; const unsigned int skip = state->skip; unsigned long int r = increment_state (state); state->n++; if (state->n == 24) { unsigned int i; state->n = 0; for (i = 0; i < skip; i++) increment_state (state); } return r; } static double ranlux_get_double (void *vstate) { return ranlux_get (vstate) / 16777216.0; } static void ranlux_set_lux (void *vstate, unsigned long int s, unsigned int luxury) { ranlux_state_t *state = (ranlux_state_t *) vstate; int i; long int seed; if (s == 0) s = 314159265; /* default seed is 314159265 */ seed = s; /* This is the initialization algorithm of F. James, widely in use for RANLUX. */ for (i = 0; i < 24; i++) { unsigned long int k = seed / 53668; seed = 40014 * (seed - k * 53668) - k * 12211; if (seed < 0) { seed += 2147483563; } state->u[i] = seed % two24; } state->i = 23; state->j = 9; state->n = 0; state->skip = luxury - 24; if (state->u[23] & mask_hi) { state->carry = 1; } else { state->carry = 0; } } static void ranlux_set (void *vstate, unsigned long int s) { ranlux_set_lux (vstate, s, 223); } static void ranlux389_set (void *vstate, unsigned long int s) { ranlux_set_lux (vstate, s, 389); } static const gsl_rng_type ranlux_type = {"ranlux", /* name */ 0x00ffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (ranlux_state_t), &ranlux_set, &ranlux_get, &ranlux_get_double}; static const gsl_rng_type ranlux389_type = {"ranlux389", /* name */ 0x00ffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (ranlux_state_t), &ranlux389_set, &ranlux_get, &ranlux_get_double}; const gsl_rng_type *gsl_rng_ranlux = &ranlux_type; const gsl_rng_type *gsl_rng_ranlux389 = &ranlux389_type;
{ "alphanum_fraction": 0.6558603491, "avg_line_length": 23.3766816143, "ext": "c", "hexsha": "8628579ae543427c73cf0df526bf9ab15a391b79", "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/rng/ranlux.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/rng/ranlux.c", "max_line_length": 83, "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/rng/ranlux.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": 1598, "size": 5213 }
#ifndef HYPER_CONST #define HYPER_CONST #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> class Hyper_Const { public : static const int dim0 = 120; // max_clause static const int dim1 = 20; // max_var static const int dim2 = 2; // nc static const int nact = 40; // nact static const float c_act; // c_act is a hyperparameter for MCTS (decide the level of exploration) static const gsl_rng *r; // random generater static const double alpha[nact]; // alpha parameter static void generate_dirichlet(double*); // function used to generate dirichlet noise static const int MCTS_size_lim; // the size of MCT we want to achieve. }; #endif
{ "alphanum_fraction": 0.6360153257, "avg_line_length": 31.32, "ext": "h", "hexsha": "aad59f792b17b912ae8eeb5ffc9572a1d8831014", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-07-12T16:13:25.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-01T16:09:28.000Z", "max_forks_repo_head_hexsha": "27554fef12b9200ea94caa136f0fc4d3c329126d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dmeoli/MCTSminisat", "max_forks_repo_path": "minisat/core/Const.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "27554fef12b9200ea94caa136f0fc4d3c329126d", "max_issues_repo_issues_event_max_datetime": "2019-01-05T02:16:42.000Z", "max_issues_repo_issues_event_min_datetime": "2019-01-04T19:01:15.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dmeoli/MCTSminisat", "max_issues_repo_path": "minisat/core/Const.h", "max_line_length": 114, "max_stars_count": 3, "max_stars_repo_head_hexsha": "27554fef12b9200ea94caa136f0fc4d3c329126d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dmeoli/MCTSminisat", "max_stars_repo_path": "minisat/core/Const.h", "max_stars_repo_stars_event_max_datetime": "2022-01-04T12:25:56.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-16T10:03:47.000Z", "num_tokens": 205, "size": 783 }
#include <stdlib.h> #include <stdio.h> #include <math.h> /*#include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlin.h>*/ #include "ral_nlls.h" /* define the usertype */ struct usertype { double y_data[67]; double x_data[67]; }; void generate_data_example ( double *x_data, double *y_data, const int m); // prototype int eval_F ( const int n, const int m, void *params, const double *X, double *f); int eval_J ( const int n, const int m, void *params, const double *X, double *f); int eval_HF ( const int n, const int m, void *params, const double *X, const double *f, double *hf); /* A c driver for the ral_nlls program */ int main(void) { /* Problem data */ const int n = 2; const int m = 67; /* Derived types */ struct ral_nlls_options options; struct ral_nlls_inform status; struct usertype params; printf("===============\n"); printf("RAL NLLS driver\n"); printf("~ C version ~\n"); printf("===============\n"); /* Generate the data... */ generate_data_example(params.x_data,params.y_data,m); double x[n]; x[0] = 1.0; x[1] = 2.0; ral_nlls_default_options(&options); options.print_level = 3; nlls_solve(n, m, x, eval_F, eval_J, eval_HF, &params, &options, &status, NULL, NULL, NULL, NULL ); int i; printf("\nX = \n"); for(i=0; i < n; i++) { printf(" %5.4f \n",x[i]); } return 0; /* success */ } /* Do a function evaluation */ int eval_F(int n, int m, void *params, const double *X, double *f){ struct usertype *myparams = (struct usertype *) params; int i; for(i=0; i<m; i++) { f[i] = myparams->y_data[i] - exp( X[0] * myparams->x_data[i] + X[1] ); } return 0; } /* Evaluate the Jacobian */ int eval_J( const int n, const int m, void *params, const double *X, double *J){ struct usertype *myparams = (struct usertype *) params; int i; for(i=0; i<m; i++) { J[i] = -myparams->x_data[i] * exp( X[0] * myparams->x_data[i] + X[1] ); J[m + i] = - exp( X[0] * myparams->x_data[i] + X[1] ); } return 0; } /* Evaluate the Hessian */ int eval_HF( const int n, const int m, void *params, const double *X, const double *f, double *hf){ struct usertype *myparams = (struct usertype *) params; int i; for(i=0; i<n*n; i++) { hf[i] = 0.0; } return 0; } /* Generate some example data... */ void generate_data_example( double *x_data, double *y_data, const int m ) { int i; /* Note the 67 here needs to be hard-coded, and you can't initialize an array with a variable length in C */ double tempx[67] = { 0.0, 0.075000000000000, 0.150000000000000, 0.225000000000000, 0.300000000000000, 0.375000000000000, 0.450000000000000, 0.525000000000000, 0.600000000000000, 0.675000000000000, 0.750000000000000, 0.825000000000000, 0.900000000000000, 0.975000000000000, 1.050000000000000, 1.125000000000000, 1.200000000000000, 1.275000000000000, 1.350000000000000, 1.425000000000000, 1.500000000000000, 1.575000000000000, 1.650000000000000, 1.725000000000000, 1.800000000000000, 1.875000000000000, 1.950000000000000, 2.025000000000000, 2.100000000000000, 2.175000000000000, 2.250000000000000, 2.325000000000000, 2.400000000000000, 2.475000000000000, 2.550000000000000, 2.625000000000000, 2.700000000000000, 2.775000000000000, 2.850000000000000, 2.925000000000000, 3.000000000000000, 3.075000000000000, 3.150000000000000, 3.225000000000001, 3.300000000000000, 3.375000000000000, 3.450000000000000, 3.525000000000000, 3.600000000000001, 3.675000000000000, 3.750000000000000, 3.825000000000000, 3.900000000000000, 3.975000000000000, 4.050000000000001, 4.125000000000000, 4.200000000000000, 4.275000000000000, 4.350000000000001, 4.425000000000000, 4.500000000000000, 4.575000000000000, 4.650000000000000, 4.725000000000001, 4.800000000000000, 4.875000000000000, 4.950000000000000}; double tempy[67] = {0.907946872110432, 1.199579396036134, 1.060092431384317, 1.298370500472354, 0.952768858414788, 1.209665290655204, 1.256912538155493, 1.163922146095987, 1.004877938808100, 1.205944250961060, 0.952693297695969, 1.449662692280761, 1.402015259144406, 1.378094012325746, 1.560882147577552, 1.437185539058121, 1.559853079888265, 1.877814947316832, 1.818781749024682, 1.375546045112591, 1.233967904388409, 1.887793124397751, 1.610237096463521, 1.787032484792262, 1.850015127982676, 2.120553361509177, 1.942913663511919, 2.106517132599766, 2.271787117356578, 1.727554346001754, 2.002909500898113, 1.975837413903495, 2.337446525801909, 1.960190841677278, 2.447097025572309, 2.161663720225506, 2.748798529374621, 2.507814238594416, 2.423769408403069, 2.578119353028746, 2.460310096221557, 2.638362783992324, 2.765540456237868, 2.837165966564409, 3.179711963042789, 3.245315453091675, 3.289631922410174, 3.360995198615834, 3.470489725998371, 3.169513520153466, 3.363740517933189, 3.665288099084969, 3.620334359722351, 4.018911445550667, 3.512715166706162, 3.874661411575566, 4.197746303653517, 3.703511523106007, 4.076351488309604, 4.056340365649961, 4.297751562451419, 4.373076571153739, 4.577093065941748, 4.856619059058190, 4.927350280596274, 4.703122139742729, 4.870205182453842}; for(i=0;i<m;i++){ x_data[i] = tempx[i]; y_data[i] = tempy[i]; } }
{ "alphanum_fraction": 0.6049697356, "avg_line_length": 24.0536398467, "ext": "c", "hexsha": "aff76f638cfff6a4afa5b21496eb6d75825e1661", "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": "1d54007935733016fec4029c355fe76d3e18c744", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ralna/RALFit", "max_forks_repo_path": "libRALFit/test/cdriver.c", "max_issues_count": 95, "max_issues_repo_head_hexsha": "1d54007935733016fec4029c355fe76d3e18c744", "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": "ralna/RALFit", "max_issues_repo_path": "libRALFit/test/cdriver.c", "max_line_length": 87, "max_stars_count": 25, "max_stars_repo_head_hexsha": "1d54007935733016fec4029c355fe76d3e18c744", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ralna/RALFit", "max_stars_repo_path": "libRALFit/test/cdriver.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": 2396, "size": 6278 }
/* chii - CHIsq test integers belonging to a given contiguous range. C * not R because a) a second opinion is good and b) I'm too lazy to * figure out how to make R honor sparse input, where a particular * bucket might have no values. otherwise, use the "chisq.test" in R or * the "equichisq" arlet of my r-fu script * * the following should fail, as there are six buckets (implicit 0 for * minimum through 5, inclusive) and the Perl only produces numbers for * five of those buckets (0..4) * * perl -E 'for (1..1000) { say int rand 5}' | chii -M 5 * * (it could also fail for reasons unrelated to the missing bucket, or * it could pass if there are not enough trials to reveal the lack) * * if you are actually testing the fitness of non-cryptographic hash * functions, consider instead the "smhasher" project */ #include <ctype.h> #include <err.h> #include <errno.h> #include <getopt.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sysexits.h> #include <unistd.h> // https://github.com/thrig/goptfoo #include <goptfoo.h> // GNU Science Library #include <gsl/gsl_cdf.h> double Flag_Fitness = 0.05; // -F @ 95% confidence by default long long Flag_Min; // -m long long Flag_Max; // -M double chisq(long long valuec, long long *values, long long minv, long long maxv, long long sum); void emit_help(void); int main(int argc, char *argv[]) { int ch; char *ep; long long number_of_nums = 0; long long range, *numstore, value; char *line = NULL; char *lp; FILE *fh; size_t linesize = 0; ssize_t linelen; ssize_t lineno = 1; double pvalue; #ifdef __OpenBSD__ if (pledge("stdio", NULL) == -1) err(1, "pledge failed"); #endif setlocale(LC_ALL, "C"); while ((ch = getopt(argc, argv, "F:h?m:M:")) != -1) { switch (ch) { case 'F': Flag_Fitness = flagtod(ch, optarg, 0.0, 1.0); break; case 'm': Flag_Min = flagtoll(ch, optarg, LLONG_MIN, LLONG_MAX); break; case 'M': Flag_Max = flagtoll(ch, optarg, LLONG_MIN, LLONG_MAX); break; case 'h': case '?': default: emit_help(); /* NOTREACHED */ } } argc -= optind; argv += optind; if ((Flag_Min == 0 && Flag_Max == 0) || Flag_Min == Flag_Max || Flag_Min > Flag_Max) emit_help(); if (argc == 0 || strncmp(*argv, "-", (size_t) 2) == 0) { fh = stdin; } else { if (!(fh = fopen(*argv, "r"))) err(EX_IOERR, "could not open '%s'", *argv); } // inclusive, need buckets for all possible numbers range = Flag_Max - Flag_Min + 1; if (!(numstore = calloc((size_t) range, sizeof(long long)))) err(EX_OSERR, "could not calloc() for %lld long longs", range); while ((linelen = getline(&line, &linesize, fh)) != -1) { // so can parse multiple numbers per line, assuming they are // isspace(3) delimited (downside: complicates the parsing) lp = line; while (*lp != '\0') { errno = 0; value = strtoll(lp, &ep, 10); if (*lp == '\0') errx(EX_DATAERR, "could not parse long long at line %ld", lineno); if (errno == ERANGE && (value == LLONG_MIN || value == LLONG_MAX)) errx(EX_DATAERR, "value out of range at line %ld", lineno); if (value < Flag_Min || value > Flag_Max) errx(EX_DATAERR, "value beyond bounds at line %ld", lineno); numstore[value - Flag_Min]++; number_of_nums++; // nom up not-strtoll() material so parser does not get wedged // on trailing material such as `echo -n 0 1 2 3 4" "` while (*ep != '+' && *ep != '-' && !isdigit(*ep)) { if (*ep == '\0' || *ep == '\n') { *ep = '\0'; break; } ep++; } lp = ep; } lineno++; } if (number_of_nums == 0) errx(EX_DATAERR, "could not parse any numbers"); if (ferror(fh)) err(EX_IOERR, "ferror() reading input"); pvalue = chisq(range, numstore, Flag_Min, Flag_Max, number_of_nums); printf("p-value %.6g%s\n", pvalue, pvalue <= Flag_Fitness ? " FAIL" : ""); exit(EXIT_SUCCESS); } double chisq(long long valuec, long long *values, long long minv, long long maxv, long long sum) { unsigned long delta, v; double expected, sum_of_squares; delta = maxv - minv + 1; expected = sum / (double) delta; sum_of_squares = 0.0; for (v = 0; v < valuec; v++) { sum_of_squares += pow(values[v] - expected, 2.0) / expected; } return gsl_cdf_chisq_Q(sum_of_squares, (double) delta - 1.0); } void emit_help(void) { fputs("Usage: chii [-F fit] -m min -M max [file|-]\n", stderr); exit(EX_USAGE); }
{ "alphanum_fraction": 0.5585960738, "avg_line_length": 29.8402366864, "ext": "c", "hexsha": "ae8732378a621c9699c24abac5090bdf0d82ea36", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-17T09:25:48.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-03T15:58:46.000Z", "max_forks_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "thrig/scripts", "max_forks_repo_path": "math/chii.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_issues_repo_issues_event_max_datetime": "2020-01-04T08:43:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-04T08:43:07.000Z", "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "thrig/scripts", "max_issues_repo_path": "math/chii.c", "max_line_length": 78, "max_stars_count": 17, "max_stars_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "thrig/scripts", "max_stars_repo_path": "math/chii.c", "max_stars_repo_stars_event_max_datetime": "2021-11-14T06:31:45.000Z", "max_stars_repo_stars_event_min_datetime": "2017-01-30T18:00:47.000Z", "num_tokens": 1402, "size": 5043 }
// 2019-05-16 by Liya Ding #include <string> #include <math.h> #include <gsl/gsl_poly.h> #include <algorithm> #include <stdlib.h> #include <iostream> //#include "convolver.h" static double approxZero(double n); static double opposite(double theta); static int getTemplateN(int M); double* getWeights(int M, double sigma); void computeBaseTemplates(double* input, int nx, int ny, int M, int borderCondition, double sigma, double** templates); double pointRespM1(int i, double angle, double* alpha, double** templates); double pointRespM2(int i, double angle, double* alpha, double** templates); double pointRespM3(int i, double angle, double* alpha, double** templates); double pointRespM4(int i, double angle, double* alpha, double** templates); double pointRespM5(int i, double angle, double* alpha, double** templates); int getRealRoots(double* z, int nz, double* roots); void filterM1(double** templates, int nx, int ny, double* alpha, double* response, double* orientation); void filterM2(double** templates, int nx, int ny, double* alpha, double* response, double* orientation); void filterM3(double** templates, int nx, int ny, double* alpha, double* response, double* orientation); void filterM4(double** templates, int nx, int ny, double* alpha, double* response, double* orientation); void filterM5(double** templates, int nx, int ny, double* alpha, double* response, double* orientation); int mirror(int x, int nx); double interp(double* image, int nx, int ny, double x, double y); void computeNMS(double* response, double* orientation, double* nms, int nx, int ny); void steerablefilter2Dcore(double * input, long* in_sz, int M, double sigma,double* &response, double* &orientation, double* &nms);
{ "alphanum_fraction": 0.7457922229, "avg_line_length": 55.5806451613, "ext": "h", "hexsha": "0b36b33f7f3418c411dca805d1cd9a8572a119d3", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "hackathon/liyad/steerablefilter2D/steerableDetector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "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": "zzhmark/vaa3d_tools", "max_issues_repo_path": "hackathon/liyad/steerablefilter2D/steerableDetector.h", "max_line_length": 131, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "hackathon/liyad/steerablefilter2D/steerableDetector.h", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 449, "size": 1723 }
#ifndef __STATS_H__ #define __STATS_H__ #include <stdint.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <inttypes.h> #include <gsl/gsl_rstat.h> typedef uint64_t word; #define TIMER_STACK 8 enum Timer{MutTimer, Gen0Timer, Gen1Timer, MiscTimer, MaxTimer}; typedef struct { uint64_t allocated; uint64_t nursery_n_collections; uint64_t nursery_time_max; uint64_t nursery_copied; uint64_t gen1_collections; uint64_t gen1_copied; uint64_t max_heap; uint64_t max_residency; uint64_t start_time; enum Timer active_timer[TIMER_STACK]; uint64_t n_timers; uint64_t timers[MaxTimer]; gsl_rstat_quantile_workspace *latency_50; gsl_rstat_quantile_workspace *latency_90; gsl_rstat_quantile_workspace *latency_99; } Stats; void stats_init(Stats *s); void stats_pprint(Stats *s); static uint64_t clock_gettime_nsec(clockid_t clk_id) { struct timespec t; clock_gettime(clk_id,&t); return (uint64_t)t.tv_sec*1e9 + t.tv_nsec; } static char *pp_time(uint64_t time) { static int i=0; static char buffer[10][128]; i = (i+1) % 10; if(time < 1000000) { snprintf(buffer[i], 128, "%4.0f us", ((double)time)/1000); } else if(time < 10000000) { snprintf(buffer[i], 128, "%4.2f ms", ((double)time)/1000000); } else if(time < 100000000) { snprintf(buffer[i], 128, "%4.1f ms", ((double)time)/1000000); } else if(time < 1000000000) { snprintf(buffer[i], 128, "%4.0f ms", ((double)time)/1000000); } else { snprintf(buffer[i], 128, "%4.2f s", ((double)time)/1000000000); } return buffer[i]; } static char *pp_speed(uint64_t words, uint64_t time) { static int i=0; static char buffer[10][128]; uint64_t rate = words*8/1024 / (time/1e9); i = (i+1) % 10; if(rate < 1024) { snprintf(buffer[i], 128, "%4" PRIu64 " KB/s", rate); } if(rate < 1024*1024*10) { // Less than 10000 MB/s snprintf(buffer[i], 128, "%4" PRIu64 " MB/s", rate/1024); } else { snprintf(buffer[i], 128, "%4.1f GB/s", (double)rate/1024/1024); } return buffer[i]; } static char *pp_bytes(uint64_t words) { static int i=0; static char buffer[10][128]; uint64_t bytes = words * 8; i = (i+1) % 10; if(bytes < 1024) { snprintf(buffer[i], 128, "%4" PRIu64 " B", bytes); } else if(bytes < 1024*1024) { snprintf(buffer[i], 128, "%4" PRIu64 " KB", bytes/1024); } else if(bytes < (uint64_t)1024*1024*1024*10) { snprintf(buffer[i], 128, "%4" PRIu64 " MB", bytes/1024/1024); } else { snprintf(buffer[i], 128, "%4.1f GB", ((double)bytes)/1024/1024/1024); } return buffer[i]; } #define CLOCK_ID CLOCK_PROCESS_CPUTIME_ID static void stats_timer_begin(Stats *s, enum Timer t) { uint64_t now = clock_gettime_nsec(CLOCK_ID); assert(s->n_timers < TIMER_STACK); s->active_timer[s->n_timers] = t; if(s->n_timers > 0) { s->timers[s->active_timer[s->n_timers-1]] += now - s->start_time; } s->n_timers++; s->start_time = now; } static void stats_timer_end(Stats *s) { uint64_t now = clock_gettime_nsec(CLOCK_ID); uint64_t t = now - s->start_time; assert(s->n_timers > 0); if(s->active_timer[s->n_timers-1] == Gen0Timer) { gsl_rstat_quantile_add((double)t, s->latency_50); gsl_rstat_quantile_add((double)t, s->latency_90); gsl_rstat_quantile_add((double)t, s->latency_99); if(t > s->nursery_time_max) { s->nursery_time_max = t; } } s->timers[s->active_timer[s->n_timers-1]] += t; s->start_time = now; s->n_timers--; } #endif
{ "alphanum_fraction": 0.6674201752, "avg_line_length": 26.6090225564, "ext": "h", "hexsha": "e04d814d7f906a629701bf7fb91dde7a3c206d72", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2021-02-13T21:01:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-05-12T13:25:29.000Z", "max_forks_repo_head_hexsha": "53bfa57b9b7275b7737dcf9dd620533d0261be66", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "lemmih/lhc", "max_forks_repo_path": "experiments/gc/stats.h", "max_issues_count": 9, "max_issues_repo_head_hexsha": "53bfa57b9b7275b7737dcf9dd620533d0261be66", "max_issues_repo_issues_event_max_datetime": "2019-06-27T06:30:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-25T04:10:33.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "lemmih/lhc", "max_issues_repo_path": "experiments/gc/stats.h", "max_line_length": 73, "max_stars_count": 193, "max_stars_repo_head_hexsha": "53bfa57b9b7275b7737dcf9dd620533d0261be66", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "Lemmih/lhc", "max_stars_repo_path": "experiments/gc/stats.h", "max_stars_repo_stars_event_max_datetime": "2022-01-07T13:52:13.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-07T01:25:13.000Z", "num_tokens": 1209, "size": 3539 }
/*This program evaluates the differential equations for a photon's geodesic in Minkowski spacetime. The equations are written in the form $\frac{d(x or p)^{\alpha}}{d\lambda}=f(x^{\alpha},p^{\alpha})$. Where $p^{\alpha}={\dot{x}}^{\alpha}$*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> //GSL error management module #define C 299792.458 //Speed of light in velocity units #define DLAMBDA 0.001 //Geodesics parameter step /*Function for solving the differential equations of Minkowski geodesics.*/ void euler1(double *x0, double *x1, double *x2, double *x3, double *p0, double *p1, double *p2, double *p3, double *lambda) { /*Increment in the variables of the differential equation we want to solve*/ double dx0, dx1, dx2, dx3, dp0, dp1, dp2, dp3; /*Calculation of the increments*/ dx0 = *p0*DLAMBDA; dx1 = *p1*DLAMBDA; dx2 = *p2*DLAMBDA; dx3 = *p3*DLAMBDA; dp0 = 0.0; dp1 = 0.0; dp2 = 0.0; dp3 = 0.0; /*New values of the variables of the differential equation. Since we are using pointers, when called the routine the value of variable change.*/ *x0 = *x0 + dx0; *x1 = *x1 + dx1; *x2 = *x2 + dx2; *x3 = *x3 + dx3; *p0 = *p0 + dp0; *p1 = *p1 + dp1; *p2 = *p2 + dp2; *p3 = *p3 + dp3; /*Increment of parameter of geodesics*/ *lambda = *lambda + DLAMBDA; } int main(void) { int i; //For array manipulation /*Initial conditions*/ double x0 = 0.0, x1 = 0.0, x2 = 0.0, x3 = 0.0, p1 = 0.1*C, p2 = 0.9*C, p3 = 0.0, lambda = 0.0; double p0 = sqrt(pow(p1,2) + pow(p2,2) + pow(p3,2))/C; /*Pointer to file where solution of differential equation will be saved.*/ FILE *geodesic; geodesic = fopen("geodesic_solution.dat","w"); /*Write line of initial values in file*/ fprintf(geodesic, "%.12lf %.12lf %.12lf %.12lf %.12lf %.12lf %.12lf %.12lf %.12lf\n", lambda, x0, x1, x2, x3, p0, p1, p2, p3); /*Solution of the differential equation*/ for(i=0; i<1000; i++) { euler1(&x0, &x1, &x2, &x3, &p0, &p1, &p2, &p3, &lambda); fprintf(geodesic, "%12lf %12lf %12lf %12lf %12lf %12lf %12lf %12lf %12lf\n", lambda, x0, x1, x2, x3, p0, p1, p2, p3); } /** Releasing all used space in memory **/ fclose(geodesic); //Close file storing the results /*GNUPLOT*/ FILE *plot; plot = popen("gnuplot -persist","w"); fprintf(plot, "set terminal x11 0\n"); fprintf(plot, "set multiplot layout 1,3\n"); fprintf(plot, "plot 'geodesic_solution.dat' using 1:2 not\n"); fprintf(plot, "plot 'geodesic_solution.dat' using 1:3 not\n"); fprintf(plot, "plot 'geodesic_solution.dat' using 1:4 not\n"); fprintf(plot, "unset multiplot\n"); fprintf(plot, "reset\n"); fprintf(plot, "set terminal x11 1\n"); fprintf(plot, "set multiplot layout 1,3\n"); fprintf(plot, "plot 'geodesic_solution.dat' using 1:6 not\n"); fprintf(plot, "plot 'geodesic_solution.dat' using 1:7 not\n"); fprintf(plot, "plot 'geodesic_solution.dat' using 1:8 not\n"); fprintf(plot, "unset multiplot\n"); fprintf(plot, "set terminal x11 2\n"); fprintf(plot, "splot 'geodesic_solution.dat' using 2:3:1\n"); pclose(plot); //system("rm geodesic_solution.dat"); }
{ "alphanum_fraction": 0.6464837591, "avg_line_length": 39.6375, "ext": "c", "hexsha": "e628338802c6966aff1826a3bdd06744280cc9bc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_forks_repo_path": "secondary_files/minkowski.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_issues_repo_issues_event_max_datetime": "2016-09-19T20:33:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-26T05:36:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_issues_repo_path": "secondary_files/minkowski.c", "max_line_length": 146, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_stars_repo_path": "secondary_files/minkowski.c", "max_stars_repo_stars_event_max_datetime": "2015-10-21T03:59:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-21T03:59:02.000Z", "num_tokens": 1130, "size": 3171 }
static char help[] = "Solve a 2-variable polynomial optimization problem.\n" "Implements an objective function and its gradient (the residual). The \n" "Jacobian (Hessian) is not implemented. Usage is either objective-only\n" " ./cartoon -snes_[fd|mf] -snes_fd_function\n" "or with gradient\n" " ./cartoon -snes_[fd|mf]\n\n"; #include <petsc.h> PetscErrorCode FormObjective(SNES snes, Vec x, PetscReal *Phi, void *ctx) { PetscErrorCode ierr; const PetscReal *ax; ierr = VecGetArrayRead(x,&ax); CHKERRQ(ierr); *Phi = 0.25 * (pow(ax[0],4.0) + pow(ax[1],4.0)) - 2.0 * ax[0] + 2.0 * ax[1]; ierr = VecRestoreArrayRead(x,&ax); CHKERRQ(ierr); return 0; } // residual F = grad Phi PetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) { PetscErrorCode ierr; const PetscReal *ax; PetscReal *aF; ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr); ierr = VecGetArray(F,&aF);CHKERRQ(ierr); aF[0] = ax[0]*ax[0]*ax[0] - 2.0; aF[1] = ax[1]*ax[1]*ax[1] + 2.0; ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr); ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr); return 0; } int main(int argc,char **argv) { PetscErrorCode ierr; SNES snes; Vec x, r, xexact; const PetscInt ix[2] = {0,1}; PetscReal iv[2], err; PetscInitialize(&argc,&argv,NULL,help); ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr); ierr = VecSetSizes(x,PETSC_DECIDE,2); CHKERRQ(ierr); ierr = VecSetFromOptions(x); CHKERRQ(ierr); iv[0] = 0.5; iv[1] = 0.5; // initial iterate corresponds to nonsingular Hessian ierr = VecSetValues(x,2,ix,iv,INSERT_VALUES); CHKERRQ(ierr); ierr = VecAssemblyBegin(x); CHKERRQ(ierr); ierr = VecAssemblyEnd(x); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetObjective(snes,FormObjective,NULL); CHKERRQ(ierr); ierr = VecDuplicate(x,&r); CHKERRQ(ierr); ierr = SNESSetFunction(snes,r,FormFunction,NULL); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); ierr = SNESSolve(snes,NULL,x); CHKERRQ(ierr); iv[0] = pow(2.0,1.0/3.0); iv[1] = - iv[0]; // exact soln ierr = VecDuplicate(x,&xexact); CHKERRQ(ierr); ierr = VecSetValues(xexact,2,ix,iv,ADD_VALUES); CHKERRQ(ierr); // note ADD_VALUES ierr = VecAssemblyBegin(xexact); CHKERRQ(ierr); ierr = VecAssemblyEnd(xexact); CHKERRQ(ierr); ierr = VecAXPY(x,-1.0,xexact); CHKERRQ(ierr); // x <-- x + (-1.0) xexact ierr = VecNorm(x,NORM_INFINITY,&err); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"numerical error |x-x_exact|_inf = %g\n",err); CHKERRQ(ierr); VecDestroy(&x); VecDestroy(&r); VecDestroy(&xexact); SNESDestroy(&snes); PetscFinalize(); return 0; }
{ "alphanum_fraction": 0.6451612903, "avg_line_length": 37.2, "ext": "c", "hexsha": "2fcd0aa4a1f4cf8f47e4c2327473768fc12fe4db", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch9/solns/cartoon.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch9/solns/cartoon.c", "max_line_length": 101, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch9/solns/cartoon.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 899, "size": 2790 }
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* */ /* Linear Algebra Data and Routines File */ /* */ /* Generated by KPP-2.2 symbolic chemistry Kinetics PreProcessor */ /* (http://www.cs.vt.edu/~asandu/Software/KPP) */ /* KPP is distributed under GPL, the general public licence */ /* (http://www.gnu.org/copyleft/gpl.html) */ /* (C) 1995-1997, V. Damian & A. Sandu, CGRER, Univ. Iowa */ /* (C) 1997-2005, A. Sandu, Michigan Tech, Virginia Tech */ /* With important contributions from: */ /* M. Damian, Villanova University, USA */ /* R. Sander, Max-Planck Institute for Chemistry, Mainz, Germany */ /* */ /* File : saprc99_LinearAlgebra.c */ /* Time : Wed Jun 11 10:09:48 2008 */ /* Working directory : /Users/jlinford/workspace/saprc99 */ /* Equation file : saprc99.kpp */ /* Output root filename : saprc99 */ /* */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #define USE_SDK_BLAS 0 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "saprc99_Parameters.h" #include "saprc99_Global.h" #include "saprc99_Sparse.h" #if DO_CHEMISTRY == 1 /* For SPU-optimized BLAS */ #if USE_SDK_BLAS == 1 #include <blas.h> #endif /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* */ /* SPARSE_UTIL - SPARSE utility functions */ /* Arguments : */ /* */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int KppDecomp( double *JVS ) { double W[74]; double a; int k, kk, j, jj; for( k = 0; k < 74; k++ ) { if( JVS[ LU_DIAG[k] ] == 0.0 ) return k+1; for( kk = LU_CROW[k]; kk < LU_CROW[k+1]; kk++ ) W[ LU_ICOL[kk] ] = JVS[kk]; for( kk = LU_CROW[k]; kk < LU_DIAG[k]; kk++ ) { j = LU_ICOL[kk]; a = -W[j] / JVS[ LU_DIAG[j] ]; W[j] = -a; for( jj = LU_DIAG[j]+1; jj < LU_CROW[j+1]; jj++ ) W[ LU_ICOL[jj] ] += a*JVS[jj]; } for( kk = LU_CROW[k]; kk < LU_CROW[k+1]; kk++ ) JVS[kk] = W[ LU_ICOL[kk] ]; } return 0; } /* End of SPARSE_UTIL function */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* */ /* KppSolve - sparse back substitution */ /* Arguments : */ /* JVS - sparse Jacobian of variables */ /* X - Vector for variables */ /* */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ void KppSolve( double JVS[], /* sparse Jacobian of variables */ double X[] /* Vector for variables */ ) { X[21] = X[21]-JVS[91]*X[20]; X[31] = X[31]-JVS[125]*X[23]-JVS[126]*X[30]; X[32] = X[32]-JVS[129]*X[23]-JVS[130]*X[30]; X[33] = X[33]-JVS[133]*X[23]-JVS[134]*X[30]; X[34] = X[34]-JVS[138]*X[23]-JVS[139]*X[30]; X[35] = X[35]-JVS[143]*X[27]; X[37] = X[37]-JVS[154]*X[23]-JVS[155]*X[30]; X[38] = X[38]-JVS[161]*X[30]; X[39] = X[39]-JVS[167]*X[19]-JVS[168]*X[29]-JVS[169]*X[31]-JVS[170] *X[32]-JVS[171]*X[34]; X[40] = X[40]-JVS[190]*X[23]-JVS[191]*X[30]-JVS[192]*X[31]-JVS[193] *X[32]-JVS[194]*X[33]; X[41] = X[41]-JVS[202]*X[19]-JVS[203]*X[20]-JVS[204]*X[21]-JVS[205] *X[22]-JVS[206]*X[29]; X[42] = X[42]-JVS[216]*X[17]-JVS[217]*X[33]-JVS[218]*X[35]-JVS[219] *X[37]-JVS[220]*X[38]-JVS[221]*X[40]; X[44] = X[44]-JVS[242]*X[19]-JVS[243]*X[23]-JVS[244]*X[30]-JVS[245] *X[31]-JVS[246]*X[32]-JVS[247]*X[34]-JVS[248]*X[38]-JVS[249] *X[43]; X[45] = X[45]-JVS[259]*X[33]-JVS[260]*X[38]; X[47] = X[47]-JVS[276]*X[20]-JVS[277]*X[22]-JVS[278]*X[29]-JVS[279] *X[31]-JVS[280]*X[32]-JVS[281]*X[41]-JVS[282]*X[46]; X[49] = X[49]-JVS[310]*X[46]; X[51] = X[51]-JVS[322]*X[46]; X[53] = X[53]-JVS[334]*X[46]-JVS[335]*X[52]; X[54] = X[54]-JVS[341]*X[10]-JVS[342]*X[20]-JVS[343]*X[22]-JVS[344] *X[29]-JVS[345]*X[43]-JVS[346]*X[50]-JVS[347]*X[51]-JVS[348] *X[52]; X[55] = X[55]-JVS[363]*X[19]-JVS[364]*X[20]-JVS[365]*X[22]-JVS[366] *X[25]-JVS[367]*X[26]-JVS[368]*X[28]-JVS[369]*X[29]-JVS[370] *X[41]-JVS[371]*X[43]-JVS[372]*X[44]-JVS[373]*X[45]-JVS[374] *X[46]-JVS[375]*X[48]-JVS[376]*X[49]-JVS[377]*X[50]-JVS[378] *X[51]-JVS[379]*X[52]-JVS[380]*X[53]; X[56] = X[56]-JVS[399]*X[21]-JVS[400]*X[48]-JVS[401]*X[50]-JVS[402] *X[51]-JVS[403]*X[52]; X[57] = X[57]-JVS[412]*X[9]-JVS[413]*X[43]-JVS[414]*X[46]-JVS[415] *X[48]-JVS[416]*X[49]-JVS[417]*X[50]-JVS[418]*X[52]-JVS[419] *X[53]; X[58] = X[58]-JVS[426]*X[19]-JVS[427]*X[20]-JVS[428]*X[22]-JVS[429] *X[29]-JVS[430]*X[31]-JVS[431]*X[32]-JVS[432]*X[34]-JVS[433] *X[36]-JVS[434]*X[43]-JVS[435]*X[48]-JVS[436]*X[49]-JVS[437] *X[50]-JVS[438]*X[51]-JVS[439]*X[52]-JVS[440]*X[53]-JVS[441] *X[56]-JVS[442]*X[57]; X[59] = X[59]-JVS[454]*X[20]-JVS[455]*X[22]-JVS[456]*X[29]-JVS[457] *X[49]-JVS[458]*X[50]-JVS[459]*X[51]-JVS[460]*X[52]-JVS[461] *X[53]-JVS[462]*X[56]-JVS[463]*X[57]; X[60] = X[60]-JVS[474]*X[22]-JVS[475]*X[29]-JVS[476]*X[30]-JVS[477] *X[46]-JVS[478]*X[48]-JVS[479]*X[50]-JVS[480]*X[51]-JVS[481] *X[52]-JVS[482]*X[53]-JVS[483]*X[56]-JVS[484]*X[57]; X[61] = X[61]-JVS[497]*X[34]-JVS[498]*X[43]-JVS[499]*X[46]-JVS[500] *X[48]-JVS[501]*X[49]-JVS[502]*X[50]-JVS[503]*X[51]-JVS[504] *X[52]-JVS[505]*X[53]-JVS[506]*X[57]; X[62] = X[62]-JVS[517]*X[8]-JVS[518]*X[16]-JVS[519]*X[18]-JVS[520] *X[19]-JVS[521]*X[23]-JVS[522]*X[24]-JVS[523]*X[25]-JVS[524] *X[26]-JVS[525]*X[27]-JVS[526]*X[28]-JVS[527]*X[30]-JVS[528] *X[31]-JVS[529]*X[32]-JVS[530]*X[34]-JVS[531]*X[35]-JVS[532] *X[36]-JVS[533]*X[39]-JVS[534]*X[40]-JVS[535]*X[43]-JVS[536] *X[44]-JVS[537]*X[45]-JVS[538]*X[46]-JVS[539]*X[48]-JVS[540] *X[49]-JVS[541]*X[50]-JVS[542]*X[51]-JVS[543]*X[52]-JVS[544] *X[53]-JVS[545]*X[54]-JVS[546]*X[55]-JVS[547]*X[56]-JVS[548] *X[57]-JVS[549]*X[58]-JVS[550]*X[59]-JVS[551]*X[60]-JVS[552] *X[61]; X[63] = X[63]-JVS[565]*X[19]-JVS[566]*X[20]-JVS[567]*X[22]-JVS[568] *X[23]-JVS[569]*X[29]-JVS[570]*X[30]-JVS[571]*X[46]-JVS[572] *X[48]-JVS[573]*X[50]-JVS[574]*X[51]-JVS[575]*X[52]-JVS[576] *X[53]-JVS[577]*X[56]-JVS[578]*X[57]-JVS[579]*X[58]-JVS[580] *X[59]-JVS[581]*X[60]-JVS[582]*X[61]-JVS[583]*X[62]; X[64] = X[64]-JVS[595]*X[15]-JVS[596]*X[46]-JVS[597]*X[49]-JVS[598] *X[51]-JVS[599]*X[52]-JVS[600]*X[53]-JVS[601]*X[57]-JVS[602] *X[61]-JVS[603]*X[62]-JVS[604]*X[63]; X[65] = X[65]-JVS[615]*X[21]-JVS[616]*X[25]-JVS[617]*X[29]-JVS[618] *X[41]-JVS[619]*X[43]-JVS[620]*X[46]-JVS[621]*X[48]-JVS[622] *X[50]-JVS[623]*X[52]-JVS[624]*X[53]-JVS[625]*X[54]-JVS[626] *X[56]-JVS[627]*X[57]-JVS[628]*X[58]-JVS[629]*X[59]-JVS[630] *X[60]-JVS[631]*X[61]-JVS[632]*X[62]-JVS[633]*X[63]-JVS[634] *X[64]; X[66] = X[66]-JVS[644]*X[14]-JVS[645]*X[37]-JVS[646]*X[52]-JVS[647] *X[57]-JVS[648]*X[61]-JVS[649]*X[62]-JVS[650]*X[63]-JVS[651] *X[64]-JVS[652]*X[65]; X[67] = X[67]-JVS[661]*X[10]-JVS[662]*X[19]-JVS[663]*X[20]-JVS[664] *X[22]-JVS[665]*X[23]-JVS[666]*X[29]-JVS[667]*X[30]-JVS[668] *X[31]-JVS[669]*X[32]-JVS[670]*X[33]-JVS[671]*X[34]-JVS[672] *X[36]-JVS[673]*X[38]-JVS[674]*X[43]-JVS[675]*X[45]-JVS[676] *X[46]-JVS[677]*X[48]-JVS[678]*X[49]-JVS[679]*X[50]-JVS[680] *X[51]-JVS[681]*X[52]-JVS[682]*X[53]-JVS[683]*X[56]-JVS[684] *X[57]-JVS[685]*X[58]-JVS[686]*X[59]-JVS[687]*X[60]-JVS[688] *X[61]-JVS[689]*X[62]-JVS[690]*X[63]-JVS[691]*X[64]-JVS[692] *X[65]-JVS[693]*X[66]; X[68] = X[68]-JVS[701]*X[18]-JVS[702]*X[26]-JVS[703]*X[47]-JVS[704] *X[48]-JVS[705]*X[50]-JVS[706]*X[52]-JVS[707]*X[53]-JVS[708] *X[55]-JVS[709]*X[56]-JVS[710]*X[57]-JVS[711]*X[59]-JVS[712] *X[60]-JVS[713]*X[61]-JVS[714]*X[62]-JVS[715]*X[63]-JVS[716] *X[64]-JVS[717]*X[65]-JVS[718]*X[66]-JVS[719]*X[67]; X[69] = X[69]-JVS[726]*X[12]-JVS[727]*X[13]-JVS[728]*X[14]-JVS[729] *X[15]-JVS[730]*X[17]-JVS[731]*X[18]-JVS[732]*X[21]-JVS[733] *X[24]-JVS[734]*X[26]-JVS[735]*X[27]-JVS[736]*X[35]-JVS[737] *X[42]-JVS[738]*X[44]-JVS[739]*X[45]-JVS[740]*X[46]-JVS[741] *X[47]-JVS[742]*X[48]-JVS[743]*X[49]-JVS[744]*X[50]-JVS[745] *X[51]-JVS[746]*X[52]-JVS[747]*X[53]-JVS[748]*X[54]-JVS[749] *X[55]-JVS[750]*X[56]-JVS[751]*X[57]-JVS[752]*X[58]-JVS[753] *X[59]-JVS[754]*X[60]-JVS[755]*X[61]-JVS[756]*X[62]-JVS[757] *X[63]-JVS[758]*X[64]-JVS[759]*X[65]-JVS[760]*X[66]-JVS[761] *X[67]-JVS[762]*X[68]; X[70] = X[70]-JVS[768]*X[17]-JVS[769]*X[24]-JVS[770]*X[33]-JVS[771] *X[35]-JVS[772]*X[37]-JVS[773]*X[38]-JVS[774]*X[40]-JVS[775] *X[42]-JVS[776]*X[43]-JVS[777]*X[44]-JVS[778]*X[45]-JVS[779] *X[46]-JVS[780]*X[47]-JVS[781]*X[48]-JVS[782]*X[49]-JVS[783] *X[50]-JVS[784]*X[51]-JVS[785]*X[52]-JVS[786]*X[53]-JVS[787] *X[54]-JVS[788]*X[55]-JVS[789]*X[56]-JVS[790]*X[57]-JVS[791] *X[58]-JVS[792]*X[59]-JVS[793]*X[60]-JVS[794]*X[61]-JVS[795] *X[62]-JVS[796]*X[63]-JVS[797]*X[64]-JVS[798]*X[65]-JVS[799] *X[66]-JVS[800]*X[67]-JVS[801]*X[68]-JVS[802]*X[69]; X[71] = X[71]-JVS[807]*X[11]-JVS[808]*X[12]-JVS[809]*X[23]-JVS[810] *X[29]-JVS[811]*X[31]-JVS[812]*X[32]-JVS[813]*X[40]-JVS[814] *X[41]-JVS[815]*X[48]-JVS[816]*X[49]-JVS[817]*X[50]-JVS[818] *X[51]-JVS[819]*X[52]-JVS[820]*X[53]-JVS[821]*X[54]-JVS[822] *X[56]-JVS[823]*X[57]-JVS[824]*X[58]-JVS[825]*X[59]-JVS[826] *X[60]-JVS[827]*X[61]-JVS[828]*X[62]-JVS[829]*X[63]-JVS[830] *X[64]-JVS[831]*X[65]-JVS[832]*X[66]-JVS[833]*X[67]-JVS[834] *X[68]-JVS[835]*X[69]-JVS[836]*X[70]; X[72] = X[72]-JVS[840]*X[13]-JVS[841]*X[44]-JVS[842]*X[45]-JVS[843] *X[48]-JVS[844]*X[49]-JVS[845]*X[51]-JVS[846]*X[52]-JVS[847] *X[53]-JVS[848]*X[57]-JVS[849]*X[58]-JVS[850]*X[59]-JVS[851] *X[60]-JVS[852]*X[61]-JVS[853]*X[62]-JVS[854]*X[63]-JVS[855] *X[64]-JVS[856]*X[65]-JVS[857]*X[66]-JVS[858]*X[67]-JVS[859] *X[68]-JVS[860]*X[69]-JVS[861]*X[70]-JVS[862]*X[71]; X[73] = X[73]-JVS[865]*X[8]-JVS[866]*X[9]-JVS[867]*X[10]-JVS[868] *X[16]-JVS[869]*X[18]-JVS[870]*X[19]-JVS[871]*X[20]-JVS[872] *X[22]-JVS[873]*X[23]-JVS[874]*X[24]-JVS[875]*X[25]-JVS[876] *X[28]-JVS[877]*X[29]-JVS[878]*X[30]-JVS[879]*X[31]-JVS[880] *X[32]-JVS[881]*X[33]-JVS[882]*X[34]-JVS[883]*X[36]-JVS[884] *X[37]-JVS[885]*X[38]-JVS[886]*X[39]-JVS[887]*X[40]-JVS[888] *X[41]-JVS[889]*X[42]-JVS[890]*X[43]-JVS[891]*X[44]-JVS[892] *X[45]-JVS[893]*X[46]-JVS[894]*X[48]-JVS[895]*X[49]-JVS[896] *X[50]-JVS[897]*X[51]-JVS[898]*X[52]-JVS[899]*X[53]-JVS[900] *X[54]-JVS[901]*X[55]-JVS[902]*X[56]-JVS[903]*X[57]-JVS[904] *X[58]-JVS[905]*X[59]-JVS[906]*X[60]-JVS[907]*X[61]-JVS[908] *X[62]-JVS[909]*X[63]-JVS[910]*X[64]-JVS[911]*X[65]-JVS[912] *X[66]-JVS[913]*X[67]-JVS[914]*X[68]-JVS[915]*X[69]-JVS[916] *X[70]-JVS[917]*X[71]-JVS[918]*X[72]; X[73] = X[73]/JVS[919]; X[72] = (X[72]-JVS[864]*X[73])/(JVS[863]); X[71] = (X[71]-JVS[838]*X[72]-JVS[839]*X[73])/(JVS[837]); X[70] = (X[70]-JVS[804]*X[71]-JVS[805]*X[72]-JVS[806]*X[73]) /(JVS[803]); X[69] = (X[69]-JVS[764]*X[70]-JVS[765]*X[71]-JVS[766]*X[72]-JVS[767] *X[73])/(JVS[763]); X[68] = (X[68]-JVS[721]*X[69]-JVS[722]*X[70]-JVS[723]*X[71]-JVS[724] *X[72]-JVS[725]*X[73])/(JVS[720]); X[67] = (X[67]-JVS[695]*X[68]-JVS[696]*X[69]-JVS[697]*X[70]-JVS[698] *X[71]-JVS[699]*X[72]-JVS[700]*X[73])/(JVS[694]); X[66] = (X[66]-JVS[654]*X[67]-JVS[655]*X[68]-JVS[656]*X[69]-JVS[657] *X[70]-JVS[658]*X[71]-JVS[659]*X[72]-JVS[660]*X[73]) /(JVS[653]); X[65] = (X[65]-JVS[636]*X[66]-JVS[637]*X[67]-JVS[638]*X[68]-JVS[639] *X[69]-JVS[640]*X[70]-JVS[641]*X[71]-JVS[642]*X[72]-JVS[643] *X[73])/(JVS[635]); X[64] = (X[64]-JVS[606]*X[65]-JVS[607]*X[66]-JVS[608]*X[67]-JVS[609] *X[68]-JVS[610]*X[69]-JVS[611]*X[70]-JVS[612]*X[71]-JVS[613] *X[72]-JVS[614]*X[73])/(JVS[605]); X[63] = (X[63]-JVS[585]*X[64]-JVS[586]*X[65]-JVS[587]*X[66]-JVS[588] *X[67]-JVS[589]*X[68]-JVS[590]*X[69]-JVS[591]*X[70]-JVS[592] *X[71]-JVS[593]*X[72]-JVS[594]*X[73])/(JVS[584]); X[62] = (X[62]-JVS[554]*X[63]-JVS[555]*X[64]-JVS[556]*X[65]-JVS[557] *X[66]-JVS[558]*X[67]-JVS[559]*X[68]-JVS[560]*X[69]-JVS[561] *X[70]-JVS[562]*X[71]-JVS[563]*X[72]-JVS[564]*X[73]) /(JVS[553]); X[61] = (X[61]-JVS[508]*X[62]-JVS[509]*X[64]-JVS[510]*X[66]-JVS[511] *X[68]-JVS[512]*X[69]-JVS[513]*X[70]-JVS[514]*X[71]-JVS[515] *X[72]-JVS[516]*X[73])/(JVS[507]); X[60] = (X[60]-JVS[486]*X[61]-JVS[487]*X[63]-JVS[488]*X[65]-JVS[489] *X[66]-JVS[490]*X[67]-JVS[491]*X[68]-JVS[492]*X[69]-JVS[493] *X[70]-JVS[494]*X[71]-JVS[495]*X[72]-JVS[496]*X[73]) /(JVS[485]); X[59] = (X[59]-JVS[465]*X[60]-JVS[466]*X[61]-JVS[467]*X[63]-JVS[468] *X[65]-JVS[469]*X[67]-JVS[470]*X[68]-JVS[471]*X[69]-JVS[472] *X[70]-JVS[473]*X[73])/(JVS[464]); X[58] = (X[58]-JVS[444]*X[59]-JVS[445]*X[60]-JVS[446]*X[61]-JVS[447] *X[62]-JVS[448]*X[63]-JVS[449]*X[67]-JVS[450]*X[68]-JVS[451] *X[69]-JVS[452]*X[70]-JVS[453]*X[73])/(JVS[443]); X[57] = (X[57]-JVS[421]*X[61]-JVS[422]*X[68]-JVS[423]*X[69]-JVS[424] *X[70]-JVS[425]*X[73])/(JVS[420]); X[56] = (X[56]-JVS[405]*X[57]-JVS[406]*X[61]-JVS[407]*X[63]-JVS[408] *X[68]-JVS[409]*X[69]-JVS[410]*X[70]-JVS[411]*X[73]) /(JVS[404]); X[55] = (X[55]-JVS[382]*X[56]-JVS[383]*X[57]-JVS[384]*X[59]-JVS[385] *X[60]-JVS[386]*X[61]-JVS[387]*X[62]-JVS[388]*X[63]-JVS[389] *X[64]-JVS[390]*X[65]-JVS[391]*X[66]-JVS[392]*X[67]-JVS[393] *X[68]-JVS[394]*X[69]-JVS[395]*X[70]-JVS[396]*X[71]-JVS[397] *X[72]-JVS[398]*X[73])/(JVS[381]); X[54] = (X[54]-JVS[350]*X[56]-JVS[351]*X[57]-JVS[352]*X[58]-JVS[353] *X[59]-JVS[354]*X[60]-JVS[355]*X[61]-JVS[356]*X[64]-JVS[357] *X[66]-JVS[358]*X[68]-JVS[359]*X[70]-JVS[360]*X[71]-JVS[361] *X[72]-JVS[362]*X[73])/(JVS[349]); X[53] = (X[53]-JVS[337]*X[57]-JVS[338]*X[61]-JVS[339]*X[70]-JVS[340] *X[73])/(JVS[336]); X[52] = (X[52]-JVS[330]*X[57]-JVS[331]*X[61]-JVS[332]*X[70]-JVS[333] *X[73])/(JVS[329]); X[51] = (X[51]-JVS[324]*X[52]-JVS[325]*X[57]-JVS[326]*X[61]-JVS[327] *X[70]-JVS[328]*X[73])/(JVS[323]); X[50] = (X[50]-JVS[318]*X[57]-JVS[319]*X[61]-JVS[320]*X[70]-JVS[321] *X[73])/(JVS[317]); X[49] = (X[49]-JVS[312]*X[52]-JVS[313]*X[57]-JVS[314]*X[61]-JVS[315] *X[70]-JVS[316]*X[73])/(JVS[311]); X[48] = (X[48]-JVS[306]*X[57]-JVS[307]*X[61]-JVS[308]*X[70]-JVS[309] *X[73])/(JVS[305]); X[47] = (X[47]-JVS[284]*X[48]-JVS[285]*X[50]-JVS[286]*X[52]-JVS[287] *X[53]-JVS[288]*X[56]-JVS[289]*X[57]-JVS[290]*X[59]-JVS[291] *X[60]-JVS[292]*X[61]-JVS[293]*X[62]-JVS[294]*X[63]-JVS[295] *X[64]-JVS[296]*X[65]-JVS[297]*X[66]-JVS[298]*X[67]-JVS[299] *X[68]-JVS[300]*X[69]-JVS[301]*X[70]-JVS[302]*X[71]-JVS[303] *X[72]-JVS[304]*X[73])/(JVS[283]); X[46] = (X[46]-JVS[272]*X[57]-JVS[273]*X[61]-JVS[274]*X[70]-JVS[275] *X[73])/(JVS[271]); X[45] = (X[45]-JVS[262]*X[62]-JVS[263]*X[64]-JVS[264]*X[66]-JVS[265] *X[68]-JVS[266]*X[69]-JVS[267]*X[70]-JVS[268]*X[71]-JVS[269] *X[72]-JVS[270]*X[73])/(JVS[261]); X[44] = (X[44]-JVS[251]*X[45]-JVS[252]*X[48]-JVS[253]*X[51]-JVS[254] *X[57]-JVS[255]*X[61]-JVS[256]*X[62]-JVS[257]*X[70]-JVS[258] *X[73])/(JVS[250]); X[43] = (X[43]-JVS[238]*X[57]-JVS[239]*X[61]-JVS[240]*X[70]-JVS[241] *X[73])/(JVS[237]); X[42] = (X[42]-JVS[223]*X[44]-JVS[224]*X[45]-JVS[225]*X[49]-JVS[226] *X[51]-JVS[227]*X[52]-JVS[228]*X[53]-JVS[229]*X[54]-JVS[230] *X[55]-JVS[231]*X[58]-JVS[232]*X[61]-JVS[233]*X[62]-JVS[234] *X[69]-JVS[235]*X[70]-JVS[236]*X[73])/(JVS[222]); X[41] = (X[41]-JVS[208]*X[48]-JVS[209]*X[50]-JVS[210]*X[52]-JVS[211] *X[56]-JVS[212]*X[61]-JVS[213]*X[69]-JVS[214]*X[70]-JVS[215] *X[73])/(JVS[207]); X[40] = (X[40]-JVS[196]*X[49]-JVS[197]*X[51]-JVS[198]*X[53]-JVS[199] *X[61]-JVS[200]*X[70]-JVS[201]*X[73])/(JVS[195]); X[39] = (X[39]-JVS[173]*X[40]-JVS[174]*X[43]-JVS[175]*X[44]-JVS[176] *X[46]-JVS[177]*X[48]-JVS[178]*X[49]-JVS[179]*X[50]-JVS[180] *X[51]-JVS[181]*X[52]-JVS[182]*X[53]-JVS[183]*X[54]-JVS[184] *X[55]-JVS[185]*X[57]-JVS[186]*X[58]-JVS[187]*X[61]-JVS[188] *X[70]-JVS[189]*X[73])/(JVS[172]); X[38] = (X[38]-JVS[163]*X[45]-JVS[164]*X[62]-JVS[165]*X[70]-JVS[166] *X[73])/(JVS[162]); X[37] = (X[37]-JVS[157]*X[52]-JVS[158]*X[61]-JVS[159]*X[70]-JVS[160] *X[73])/(JVS[156]); X[36] = (X[36]-JVS[150]*X[62]-JVS[151]*X[63]-JVS[152]*X[67]-JVS[153] *X[73])/(JVS[149]); X[35] = (X[35]-JVS[145]*X[45]-JVS[146]*X[62]-JVS[147]*X[69]-JVS[148] *X[70])/(JVS[144]); X[34] = (X[34]-JVS[141]*X[61]-JVS[142]*X[73])/(JVS[140]); X[33] = (X[33]-JVS[136]*X[70]-JVS[137]*X[73])/(JVS[135]); X[32] = (X[32]-JVS[132]*X[73])/(JVS[131]); X[31] = (X[31]-JVS[128]*X[73])/(JVS[127]); X[30] = (X[30]-JVS[124]*X[73])/(JVS[123]); X[29] = (X[29]-JVS[122]*X[73])/(JVS[121]); X[28] = (X[28]-JVS[117]*X[63]-JVS[118]*X[65]-JVS[119]*X[67]-JVS[120] *X[73])/(JVS[116]); X[27] = (X[27]-JVS[112]*X[35]-JVS[113]*X[62]-JVS[114]*X[69]-JVS[115] *X[70])/(JVS[111]); X[26] = (X[26]-JVS[108]*X[55]-JVS[109]*X[62]-JVS[110]*X[68]) /(JVS[107]); X[25] = (X[25]-JVS[104]*X[62]-JVS[105]*X[65]-JVS[106]*X[73]) /(JVS[103]); X[24] = (X[24]-JVS[100]*X[62]-JVS[101]*X[69]-JVS[102]*X[73]) /(JVS[99]); X[23] = (X[23]-JVS[98]*X[73])/(JVS[97]); X[22] = (X[22]-JVS[96]*X[73])/(JVS[95]); X[21] = (X[21]-JVS[93]*X[69]-JVS[94]*X[73])/(JVS[92]); X[20] = (X[20]-JVS[90]*X[73])/(JVS[89]); X[19] = (X[19]-JVS[88]*X[73])/(JVS[87]); X[18] = (X[18]-JVS[85]*X[68]-JVS[86]*X[73])/(JVS[84]); X[17] = (X[17]-JVS[82]*X[69]-JVS[83]*X[70])/(JVS[81]); X[16] = (X[16]-JVS[79]*X[62]-JVS[80]*X[73])/(JVS[78]); X[15] = (X[15]-JVS[76]*X[64]-JVS[77]*X[69])/(JVS[75]); X[14] = (X[14]-JVS[73]*X[66]-JVS[74]*X[69])/(JVS[72]); X[13] = (X[13]-JVS[70]*X[69]-JVS[71]*X[72])/(JVS[69]); X[12] = (X[12]-JVS[67]*X[69]-JVS[68]*X[71])/(JVS[66]); X[11] = (X[11]-JVS[62]*X[23]-JVS[63]*X[48]-JVS[64]*X[61]-JVS[65] *X[73])/(JVS[61]); X[10] = (X[10]-JVS[60]*X[73])/(JVS[59]); X[9] = (X[9]-JVS[58]*X[61])/(JVS[57]); X[8] = (X[8]-JVS[56]*X[73])/(JVS[55]); X[7] = (X[7]-JVS[52]*X[27]-JVS[53]*X[37]-JVS[54]*X[69])/(JVS[51]); X[6] = (X[6]-JVS[49]*X[27]-JVS[50]*X[69])/(JVS[48]); X[5] = (X[5]-JVS[44]*X[62]-JVS[45]*X[64]-JVS[46]*X[66]-JVS[47]*X[72]) /(JVS[43]); X[4] = (X[4]-JVS[41]*X[62]-JVS[42]*X[71])/(JVS[40]); X[3] = (X[3]-JVS[27]*X[46]-JVS[28]*X[48]-JVS[29]*X[50]-JVS[30]*X[51] -JVS[31]*X[52]-JVS[32]*X[61]-JVS[33]*X[62]-JVS[34]*X[63] -JVS[35]*X[64]-JVS[36]*X[65]-JVS[37]*X[66]-JVS[38]*X[67] -JVS[39]*X[72])/(JVS[26]); X[2] = (X[2]-JVS[18]*X[50]-JVS[19]*X[52]-JVS[20]*X[61]-JVS[21]*X[62] -JVS[22]*X[63]-JVS[23]*X[65]-JVS[24]*X[67]-JVS[25]*X[71]) /(JVS[17]); X[1] = (X[1]-JVS[4]*X[19]-JVS[5]*X[26]-JVS[6]*X[43]-JVS[7]*X[46] -JVS[8]*X[48]-JVS[9]*X[49]-JVS[10]*X[50]-JVS[11]*X[51]-JVS[12] *X[52]-JVS[13]*X[53]-JVS[14]*X[61]-JVS[15]*X[68]-JVS[16]*X[73]) /(JVS[3]); X[0] = (X[0]-JVS[1]*X[8]-JVS[2]*X[73])/(JVS[0]); } /* End of KppSolve function */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* */ /* BLAS_UTIL - BLAS-LIKE utility functions */ /* Arguments : */ /* */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /*-------------------------------------------------------------- BLAS/LAPACK-like subroutines used by the integration algorithms It is recommended to replace them by calls to the optimized BLAS/LAPACK library for your machine (C) Adrian Sandu, Aug. 2004 --------------------------------------------------------------*/ #define ZERO (double)0.0 #define ONE (double)1.0 #define HALF (double)0.5 #define TWO (double)2.0 #define MOD(A,B) (int)((A)%(B)) /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ void WCOPY(int N, double X[], int incX, volatile double Y[], int incY) /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ copies a vector, x, to a vector, y: y <- x only for incX=incY=1 after BLAS replace this by the function from the optimized BLAS implementation: CALL SCOPY(N,X,1,Y,1) or CALL DCOPY(N,X,1,Y,1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ { #if USE_SDK_BLAS == 1 dcopy_spu(X, Y, N); #else int i, M; if (N <= 0) return; M = MOD(N,8); if( M != 0 ) { for ( i = 0; i < M; i++ ) Y[i] = X[i]; if( N < 8 ) return; } for ( i = M; i<N; i+=8 ) { Y[i] = X[i]; Y[i + 1] = X[i + 1]; Y[i + 2] = X[i + 2]; Y[i + 3] = X[i + 3]; Y[i + 4] = X[i + 4]; Y[i + 5] = X[i + 5]; Y[i + 6] = X[i + 6]; Y[i + 7] = X[i + 7]; } #endif } /* end function WCOPY */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ void WAXPY(int N, double Alpha, double X[], int incX, double Y[], int incY ) /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ constant times a vector plus a vector: y <- y + Alpha*x only for incX=incY=1 after BLAS replace this by the function from the optimized BLAS implementation: CALL SAXPY(N,Alpha,X,1,Y,1) or CALL DAXPY(N,Alpha,X,1,Y,1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ { #if USE_SDK_BLAS == 1 daxpy_spu(X, Y, Alpha, N); #else int i, M; if (Alpha == ZERO) return; if (N <= 0) return; M = MOD(N,4); if( M != 0 ) { for ( i = 0; i < M; i++ ) Y[i] = Y[i] + Alpha*X[i]; if ( N < 4 ) return; } for ( i = M; i < N; i += 4 ) { Y[i] = Y[i] + Alpha*X[i]; Y[i + 1] = Y[i + 1] + Alpha*X[i + 1]; Y[i + 2] = Y[i + 2] + Alpha*X[i + 2]; Y[i + 3] = Y[i + 3] + Alpha*X[i + 3]; } #endif } /* end function WAXPY */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ void WSCAL(int N, double Alpha, double X[], int incX) /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ constant times a vector: x(1:N) <- Alpha*x(1:N) only for incX=incY=1 after BLAS replace this by the function from the optimized BLAS implementation: CALL SSCAL(N,Alpha,X,1) or CALL DSCAL(N,Alpha,X,1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ { #if USE_SDK_BLAS == 1 dscal_spu(X, Alpha, N); #else int i, M; if (Alpha == ONE) return; if (N <= 0) return; M = MOD(N,5); if( M != 0 ) { if (Alpha == (-ONE)) for ( i = 0; i < M; i++ ) X[i] = -X[i]; else { if (Alpha == ZERO) for ( i = 0; i < M; i++ ) X[i] = ZERO; else for ( i = 0; i < M; i++ ) X[i] = Alpha*X[i]; } // end else if( N < 5 ) return; } // end if if (Alpha == (-ONE)) for ( i = M; i<N; i+=5 ) { X[i] = -X[i]; X[i + 1] = -X[i + 1]; X[i + 2] = -X[i + 2]; X[i + 3] = -X[i + 3]; X[i + 4] = -X[i + 4]; } // end for else { if (Alpha == ZERO) for ( i = M; i < N; i += 5 ) { X[i] = ZERO; X[i + 1] = ZERO; X[i + 2] = ZERO; X[i + 3] = ZERO; X[i + 4] = ZERO; } // end for else for ( i = M; i < N; i += 5 ) { X[i] = Alpha*X[i]; X[i + 1] = Alpha*X[i + 1]; X[i + 2] = Alpha*X[i + 2]; X[i + 3] = Alpha*X[i + 3]; X[i + 4] = Alpha*X[i + 4]; } // end for } // else #endif } /* end function WSCAL */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ double WLAMCH( char C ) /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ returns epsilon machine after LAPACK replace this by the function from the optimized LAPACK implementation: CALL SLAMCH('E') or CALL DLAMCH('E') ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ { int i; double Suma; static double Eps; static char First = 1; if (First) { First = 0; Eps = pow(HALF,16); for ( i = 17; i <= 80; i++ ) { Eps = Eps*HALF; Suma = ONE + Eps; if (Suma <= ONE) break; } /* end for */ if (i==80) { printf("\nERROR IN WLAMCH. Very small EPS = %g\n",Eps); return (double)2.2e-16; } Eps *= TWO; i--; } /* end if First */ return Eps; } /* end function WLAMCH */ #endif
{ "alphanum_fraction": 0.4348082814, "avg_line_length": 46.6385542169, "ext": "c", "hexsha": "834fa20bc8b6718b139fe68f065637ee8cd30ba0", "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": "90147defe10a0d3c03a7c97207caea66928f4fbb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "jlinford/fixedgrid", "max_forks_repo_path": "3D/cuda/trunk/saprc99/saprc99_LinearAlgebra.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "90147defe10a0d3c03a7c97207caea66928f4fbb", "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": "jlinford/fixedgrid", "max_issues_repo_path": "3D/cuda/trunk/saprc99/saprc99_LinearAlgebra.c", "max_line_length": 94, "max_stars_count": 1, "max_stars_repo_head_hexsha": "90147defe10a0d3c03a7c97207caea66928f4fbb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "jlinford/fixedgrid", "max_stars_repo_path": "2D/cell/branches/dma_mailbox/spu/saprc99/saprc99_LinearAlgebra.c", "max_stars_repo_stars_event_max_datetime": "2019-07-26T19:59:01.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-26T19:59:01.000Z", "num_tokens": 12005, "size": 27097 }
/******************************************************************************* NAME: diffimage ALGORITHM DESCRIPTION: Calculates statistics in each input file Calculates PSNR between the two input files Performs an fftMatch between the two input files Checks for differences in stats, a PSNR that is too low, and for shifts in geolocation ISSUES: The images must have at least 75% overlap. diffimage will occasionally fail to find the correct offset especially with noisy images or images with flat topography (low non-noise spatial frequency.) *******************************************************************************/ #include "asf.h" #include "asf_nan.h" #include <unistd.h> #include <math.h> #include <ctype.h> #include "fft.h" #include "fft2d.h" #include "ddr.h" #include "asf_raster.h" #include "typlim.h" #include "float_image.h" #include "uint8_image.h" #include "proj.h" #include "libasf_proj.h" #include "asf_jpeg.h" #include "asf_tiff.h" #include "geo_tiffp.h" #include "geo_keyp.h" #include <png.h> #include <gsl/gsl_math.h> #include "diffimage_tolerances.h" #include "geotiff_support.h" #include "asf_complex.h" #ifndef png_jmpbuf # define png_jmpbuf (png_ptr) ((png_ptr)->jmpbuf) #endif #define MISSING_PSNR -32000 #define FILE1_FFTFILE "tmp_file1.img" #define FILE1_FFTFILE_META "tmp_file1.meta" #define FILE2_FFTFILE "tmp_file2.img" #define FILE2_FFTFILE_META "tmp_file2.meta" #define CORR_FILE "tmp_corr" /**** PROTOTYPES ****/ void usage(char *name); int main(int argc, char **argv) { char *inFile1,*inFile2; char *outputFile = NULL; extern int optind; /* argv index of the next argument */ extern char *optarg; /* current argv[] */ int c; /* option letter from getopt() */ char ch; extern FILE *fLog; /* output file descriptor, stdout or log file */ FILE *fError; /* Error log, stderr or log file */ extern int logflag, quietflag; int outputflag=0; int bandflag=0; int strictflag=0; int band=0; char msg[1024]; fLog = NULL; logflag = quietflag=0; /* process command line */ // FIXME: Might want to add -band1 and -band2 flags that would allow comparing // any arbitrary band in file1 to any arbitrary band in file2 while ((c=getopt(argc,argv,"o:l:b:s:")) != EOF) { ch = (char)c; switch (ch) { case 'l':/* -log <filename>, get logfile; this is sorta hacked */ if (0==strncmp(optarg,"og",2)) { sscanf(argv[optind++], "%s", logFile); logflag=1; fLog = FOPEN(logFile, "w"); } else { FREE(outputFile); usage(argv[0]); } break; case 'o':/* -output <filename>, get output filename ... empty if no differences */ if (0==strncmp(optarg,"utput",5)) { outputFile= (char*) CALLOC(1024, sizeof(char)); sscanf(argv[optind++], "%s", outputFile); outputflag=1; } else { strcpy(outputFile, ""); outputflag=0; } break; case 'b':/* -band flag */ if (0==strncmp(optarg,"and",3)) { sscanf(argv[optind++], "%d", &band); bandflag=1; } else { FREE(outputFile); usage(argv[0]); } break; case 's': /* -strict flag */ if (0==strncmp(optarg,"trict",5)) { strictflag=1; } else { FREE(outputFile); usage(argv[0]); } break; default: FREE(outputFile); usage(argv[0]); break; } } asfSplashScreen(argc, argv); // After parsing out the command line arguments, there should be 2 arguments // left... the two files to compare if ((argc-optind) != 2) { if ((argc-optind) > 2) { printf("\n => Too many inputs.\n"); } if ((argc-optind) < 2) { printf("\n => Too few inputs.\n"); } FREE(outputFile); usage(argv[0]); } else { // Grab the file names inFile1=argv[optind]; inFile2=argv[optind+1]; } if (strcmp(inFile1, inFile2) == 0) { asfPrintError("inFile1 and inFile2 must be different files\n"); } // Set up output redirection for error and log messages if (logflag == 0) { fLog = NULL; fError = NULL; } else { fError = fLog; } if (!outputflag) { sprintf(msg, "Missing output file name ...file differences will be " "directed to stderr (only)\n"); printf("** Warning: ********\n%s** End of warning **\n\n", msg); } if (outputflag && strcmp(logFile, outputFile) == 0) { sprintf(msg, "Log file cannot be the same as the output file:\n" " Log file: %s\n Output file: %s\n", logFile, outputFile); if (outputFile) FREE(outputFile); asfPrintError(msg); } char **bands1 = NULL, **bands2 = NULL; int num_bands1, num_bands2, complex = 0; stats_t *stats1 = NULL, *stats2 = NULL; complex_stats_t *complex_stats1 = NULL, *complex_stats2 = NULL; psnr_t *psnrs = NULL; complex_psnr_t *complex_psnr = NULL; shift_data_t *data_shift = NULL; diffimage(inFile1, inFile2, outputFile, logFile, &bands1, &bands2, &num_bands1, &num_bands2, &complex, &stats1, &stats2, &complex_stats1, &complex_stats2, &psnrs, &complex_psnr, &data_shift); return (0); } void usage(char *name) { printf("\nUSAGE:\n" " %s [-output <diff_output_file>] [-log <file>] [-band <band number>]\n" " [-strict] <img1.ext> <img2.ext>\n" "\nOPTIONS:\n" " -output <diff_output_file>: output to write image differencing\n" " results to (required.)\n" " -log <file>: allows the output to be written to a log file\n" " in addition to stdout (not required but strongly suggested.)\n" " -band <band number>: allows comparing one selected band from within\n" " multi-banded image files, including the separate color bands\n" " found within color images. Default is to compare all\n" " available bands.\n" " -strict: forces statistics comparison to utilize all available\n" " fields (min, max, mean, sdev, PSNR). Without the -strict\n" " option specified, only mean, sdev, and PSNR are utilized.\n" " default is non-strict.\n" "\nINPUTS:\n" " <img1.ext>: any supported single-banded graphics file image.\n" " supported types include TIFF, GEOTIFF, PNG, PGM, PPM,\n" " JPEG, and ASF IMG. File extension is REQUIRED.\n" " <img2.ext>: an image to line up with the first.\n" " image 2 should be the same graphics file type and not\n" " be bigger than image 1. File extension is REQUIRED.\n" "\nDESCRIPTION:\n" " 1. diffimage calculates image statistics within each input image\n" " and calculates the peak signal-to-noise (PSNR) between the two\n" " images.\n" " 2. diffimage then lines up the two images, to slightly better\n" " than single-pixel precision, and determines if any geolocation\n" " shift has occurred between the two and the size of the shift.\n" " Because an fft-based match is utilized it will work with images of\n" " any size, but is most efficient when the image dimensions are\n" " near a power of 2. The images need not be square.\n" " 3. diffimage then compares image statistics and geolocation shift\n" " (if it occurred) and determines if the two images are different from\n" " each other or not.\n" " 4. If there are no differences, the output file will exist but will be\n" " of zero length. Otherwise, a summary of the differences will be placed\n" " in both the output file and the log file (if specified.)\n\n" "Version:\n " SVN_REV " (part of " TOOL_SUITE_NAME " "MAPREADY_VERSION_STRING ")\n\n", name); exit(1); }
{ "alphanum_fraction": 0.5832417247, "avg_line_length": 34.8382978723, "ext": "c", "hexsha": "5f0e2cbf3b5b227c67a5d2970ca2b6592e2777db", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/diffimage/diffimage.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/diffimage/diffimage.c", "max_line_length": 98, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/diffimage/diffimage.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 2161, "size": 8187 }
/* dwt_undec.h * Paul Demorest, 2007/10 */ #ifndef _DWT_UNDEC_H_ #define _DWT_UNDEC_H_ #include <gsl/gsl_wavelet.h> #ifdef __cplusplus extern "C" { #endif int dwt_undec_transform(double *in, double *out, size_t n, const gsl_wavelet *w); int dwt_undec_inverse(double *in, double *out, size_t n, const gsl_wavelet *w); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7514124294, "avg_line_length": 22.125, "ext": "h", "hexsha": "c4ae43b6e164049c3a278481a164c70bb901cc21", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-02-13T20:08:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-13T20:08:14.000Z", "max_forks_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_forks_repo_licenses": [ "AFL-2.1" ], "max_forks_repo_name": "rwharton/psrchive_dsn", "max_forks_repo_path": "Util/genutil/dwt_undec.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "AFL-2.1" ], "max_issues_repo_name": "rwharton/psrchive_dsn", "max_issues_repo_path": "Util/genutil/dwt_undec.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_stars_repo_licenses": [ "AFL-2.1" ], "max_stars_repo_name": "rwharton/psrchive_dsn", "max_stars_repo_path": "Util/genutil/dwt_undec.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 118, "size": 354 }
/** * * @file core_csetvar.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 Mark Gates * @date 2010-11-15 * @generated c Tue Jan 7 11:44:49 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex32_t * * CORE_csetvar sets a single variable, x := alpha. * ******************************************************************************* * * @param[in] alpha * Scalar to set x to, passed by pointer so it can depend on runtime value. * * @param[out] x * On exit, x = alpha. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_csetvar = PCORE_csetvar #define CORE_csetvar PCORE_csetvar #endif void CORE_csetvar(const PLASMA_Complex32_t *alpha, PLASMA_Complex32_t *x) { *x = *alpha; }
{ "alphanum_fraction": 0.5204178538, "avg_line_length": 25.6829268293, "ext": "c", "hexsha": "be849ee98ba23a66a78388726fdeaf20138636e8", "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_csetvar.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_csetvar.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_csetvar.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 264, "size": 1053 }
/*****************************************************************\ __ / / / / __ __ / /______ _______ / / / / ________ __ __ / ______ \ /_____ \ / / / / / _____ | / / / / / / | / _______| / / / / / / /____/ / / / / / / / / / / _____ / / / / / / _______/ / / / / / / / / / /____/ / / / / / / |______ / |______/ / /_/ /_/ |________/ / / / / \_______/ \_______ / /_/ /_/ / / / / High Level Game Framework /_/ --------------------------------------------------------------- Copyright (c) 2007-2011 - Rodrigo Braz Monteiro. This file is subject to the terms of halley_license.txt. \*****************************************************************/ #pragma once #include <cmath> #include <iostream> #include "angle.h" #include <halley/utils/utils.h> #include "halley/text/string_converter.h" #include <gsl/gsl> #ifdef min #undef min #endif #ifdef max #undef max #endif namespace Halley { ////////////////////////////// // Vector2D class declaration template <typename T=float, class U=Angle<float>> class Vector2D { private: constexpr T mod(T a, T b) const { return a % b; } public: T x,y; // Constructors constexpr Vector2D () : x(0), y(0) {} constexpr Vector2D (T _x, T _y) : x(_x), y(_y) {} template <typename V> constexpr explicit Vector2D (Vector2D<V> vec) : x(T(vec.x)), y(T(vec.y)) {} Vector2D (T length, U angle) { float s, c; angle.sincos(s, c); x = s*length; y = c*length; } // Getter constexpr inline T& operator[](size_t n) { Expects(n <= 1); return (&x)[n]; } constexpr inline T operator[](size_t n) const { Expects(n <= 1); return (&x)[n]; } // Assignment and comparison constexpr inline Vector2D& operator = (Vector2D param) { x = param.x; y = param.y; return *this; } constexpr inline Vector2D& operator = (T param) { x = param; y = param; return *this; } constexpr inline bool operator == (Vector2D param) const { return x == param.x && y == param.y; } constexpr inline bool operator != (Vector2D param) const { return x != param.x || y != param.y; } constexpr inline bool operator < (Vector2D param) const { return y != param.y ? y < param.y : x < param.x; } // Basic algebra constexpr inline Vector2D operator + (Vector2D param) const { return Vector2D(x + param.x,y + param.y); } constexpr inline Vector2D operator - (Vector2D param) const { return Vector2D(x - param.x,y - param.y); } constexpr inline Vector2D operator * (Vector2D param) const { return Vector2D(x * param.x,y * param.y); } constexpr inline Vector2D operator / (Vector2D param) const { return Vector2D(x / param.x,y / param.y); } constexpr inline Vector2D operator % (Vector2D param) const { return Vector2D(mod(x, param.x), mod(y, param.y)); } constexpr inline Vector2D modulo(Vector2D param) const { return Vector2D(Halley::modulo<T>(x, param.x), Halley::modulo<T>(y, param.y)); } constexpr inline Vector2D floorDiv(Vector2D param) const { return Vector2D(Halley::floorDiv(x, param.x), Halley::floorDiv(y, param.y)); } constexpr inline Vector2D operator - () const { return Vector2D(-x,-y); } template <typename V> constexpr inline Vector2D operator * (V param) const { return Vector2D(T(x * param), T(y * param)); } template <typename V> constexpr inline Vector2D operator / (V param) const { return Vector2D(T(x / param), T(y / param)); } // In-place operations constexpr inline Vector2D& operator += (Vector2D param) { x += param.x; y += param.y; return *this; } constexpr inline Vector2D& operator -= (Vector2D param) { x -= param.x; y -= param.y; return *this; } constexpr inline Vector2D& operator *= (const T param) { x *= param; y *= param; return *this; } constexpr inline Vector2D& operator /= (const T param) { x /= param; y /= param; return *this; } // Get the normalized vector (unit vector) constexpr inline Vector2D unit () const { float len = length(); if (len != 0) { return (*this) / len; } else { return Vector2D(0, 0); } } constexpr inline Vector2D normalized() const { return unit(); } constexpr inline void normalize() { *this = unit(); } // Get the orthogonal vector constexpr inline Vector2D orthoLeft () const { return Vector2D(-y, x); } constexpr inline Vector2D orthoRight () const { return Vector2D(y, -x); } // Cross product (the Z component of it) constexpr inline T cross (Vector2D param) const { return x * param.y - y * param.x; } // Dot product constexpr inline T dot (Vector2D param) const { return (x * param.x) + (y * param.y); } // Length constexpr inline T length () const { return static_cast<T>(std::sqrt(squaredLength())); } constexpr inline T len () const { return length(); } constexpr inline T manhattanLength() const { return std::abs(x) + std::abs(y); } // Squared length, often useful and much faster constexpr inline T squaredLength () const { return x*x+y*y; } // Projection on another vector inline Vector2D projection (Vector2D param) const { Vector2D unit = param.unit(); return this->dot(unit) * unit; } inline T projectionLength (Vector2D param) const { return this->dot(param.unit()); } // Rounding constexpr inline Vector2D floor() const { return Vector2D(std::floor(x), std::floor(y)); } constexpr inline Vector2D ceil() const { return Vector2D(std::ceil(x), std::ceil(y)); } constexpr inline Vector2D round() const { return Vector2D(std::round(x), std::round(y)); } // Gets the angle that this vector is pointing to inline U angle () const { U angle; angle.setRadians(atan2(y, x)); return angle; } // Rotates vector by an angle inline Vector2D rotate (U angle) const { T cos, sin; angle.sincos(sin, cos); return Vector2D(x*cos - y*sin, x*sin + y*cos); } // Rotates vector by sine and cosine inline Vector2D rotate (T sine, T cosine) const { return Vector2D(x*cosine - y*sine, x*sine + y*cosine); } // Removes the length of the vector along the given axis constexpr inline Vector2D neutralize (Vector2D param) const { return *this - dot(param)*param; } String toString() const { return String("(") + x + ", " + y + ")"; } constexpr Vector2D abs() const { return Vector2D(std::abs(x), std::abs(y)); } constexpr inline static Vector2D<T,U> min(Vector2D<T,U> a, Vector2D<T,U> b) { return Vector2D<T,U>(std::min(a.x, b.x), std::min(a.y, b.y)); } constexpr inline static Vector2D<T,U> max(Vector2D<T,U> a, Vector2D<T,U> b) { return Vector2D<T,U>(std::max(a.x, b.x), std::max(a.y, b.y)); } }; //////////////////// // Global operators template <typename T,class U,typename V> inline Vector2D<T,U> operator * (V f, const Vector2D<T,U> &v) { return Vector2D<T,U>(T(v.x * f),T(v.y * f)); } template <typename T,class U> std::ostream& operator<< (std::ostream& ostream, const Vector2D<T, U>& v) { ostream << "(" << v.x << "," << v.y << ")" ; return ostream; } //////////// // Typedefs typedef Vector2D<double,Angle<double> > Vector2d; typedef Vector2D<> Vector2f; typedef Vector2D<int> Vector2i; typedef Vector2D<short> Vector2s; typedef Vector2D<char> Vector2c; typedef Vector2f Position; typedef Vector2f Size; } namespace std { template<> struct hash<Halley::Vector2i> { size_t operator()(const Halley::Vector2i& v) const { return std::hash<long long>()(*reinterpret_cast<const long long*>(&v)); } }; template<> struct hash<Halley::Vector2f> { size_t operator()(const Halley::Vector2f& v) const { return std::hash<long long>()(*reinterpret_cast<const long long*>(&v)); } }; }
{ "alphanum_fraction": 0.60236822, "avg_line_length": 30.6796875, "ext": "h", "hexsha": "32529e8d6908379a563faca0ef64b3f4bb0bf981", "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": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "lye/halley", "max_forks_repo_path": "src/engine/utils/include/halley/maths/vector2.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "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": "lye/halley", "max_issues_repo_path": "src/engine/utils/include/halley/maths/vector2.h", "max_line_length": 139, "max_stars_count": null, "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "lye/halley", "max_stars_repo_path": "src/engine/utils/include/halley/maths/vector2.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2298, "size": 7854 }
/* ferrers.c Ferrers bar model. */ #include <stddef.h> #include <stdlib.h> #include <math.h> #include "utils.h" #include "potential.h" #include <gsl/gsl_sf.h> #include "ferrers.h" #define Sq(X) ((X) * (X)) double _lambda(double x_sq, double y_sq, double z_sq, double a_sq, double b_sq, double c_sq) { #define EQS(u) (x_sq / (a_sq + u) + y_sq / (b_sq + u) + z_sq / (c_sq + u) - 1.) double J = 0, K = 0., L = (x_sq + y_sq + z_sq); for(;EQS(L) > 0;) L *= 2.;//, printf("doubled!\n"); // solve the eqs using bisection method. for(;L - J > 1.e-8;) { K = (L + J) / 2.; //printf("%f, %f, %f\n", J, K, L); if(EQS(K) > 0) J = K; else L = K; } return K; #undef EQS } int _orbita_potential_ferrers2_evaluate_wijk(double x, double y, double z, double a, double b, double c, double * W, int init, struct orbita_potential_ferrers2_paramset * ws) { double a_sq = a * a, b_sq = b * b, c_sq = c * c, x_sq = x * x, y_sq = y * y, z_sq = z * z; // outside the bar region? if(x_sq / a_sq + y_sq / b_sq + z_sq / c_sq >= 1 || init) { // using the root-finding eqs. this is NOT the unique positive root. // now use bisection method instead. /* double A = (a_sq + b_sq + c_sq) - (x_sq + y_sq + z_sq), B = (a_sq * b_sq + b_sq * c_sq + c_sq * a_sq) - (x_sq * (b_sq + c_sq) + y_sq * (c_sq + a_sq) + z_sq * (a_sq + b_sq)), C = (a_sq * b_sq * c_sq) - (x_sq * b_sq * c_sq + a_sq * y_sq * c_sq + a_sq * b_sq * z_sq); double A_sq = A * A, B_sq = B * B, C_sq = C * C; double A_cb = A_sq * A, B_cb = B_sq * B; double CBR_2 = pow(2., 1. / 3.); double lambda = pow(-2. * A_cb + 3. * sqrt(3.) * sqrt(4. * A_cb * C - A_sq * B_sq - 18. * A * B * C + 4. * B_cb + 27. * C_sq) + 9. * A * B - 27. * C, 1. / 3.) / (3. * CBR_2) - (CBR_2 * (2187. * B - 729. * A_sq)) / (2187. * pow(-2. * A_cb + 3. * sqrt(3.) * sqrt(4. * A_cb * C - A_sq * B_sq - 18. * A * B * C + 4. * B_cb + 27. * C_sq) + 9. * A * B - 27. * C, 1. / 3.)) - A / 3.; */ double lambda = _lambda(x_sq, y_sq, z_sq, a_sq, b_sq, c_sq); if(init) lambda = 0.; double p = asin(sqrt((a_sq - c_sq) / (a_sq + lambda))), k = sqrt((a_sq - b_sq) / (a_sq - c_sq)); /* double F = gsl_sf_ellint_F(p, k, GSL_PREC_DOUBLE), E = gsl_sf_ellint_E(p, k, GSL_PREC_DOUBLE); */ double F = gsl_sf_ellint_F(p, k, GSL_PREC_SINGLE), E = gsl_sf_ellint_E(p, k, GSL_PREC_SINGLE); double delta_lambda = sqrt((a_sq + lambda) * (b_sq + lambda) * (c_sq + lambda)); /* W_000 */ W[ 0] = 2. * F / sqrt(a_sq - c_sq), /* W_100 */ W[ 1] = 2. * (F - E) / ((a_sq - b_sq) * sqrt(a_sq - c_sq)), /* W_001 */ W[ 3] = (2. / (b_sq - c_sq)) * sqrt((b_sq + lambda) / ((a_sq + lambda) * (c_sq + lambda))) -2. * E / ((b_sq - c_sq) * sqrt(a_sq - c_sq)), /* W_010 */ W[ 2] = 2. / delta_lambda - W[1] - W[3], /* W_110 */ W[ 4] = (W[2] - W[1]) / (a_sq - b_sq), /* W_011 */ W[ 5] = (W[3] - W[2]) / (b_sq - c_sq), /* W_101 */ W[ 6] = (W[1] - W[3]) / (c_sq - a_sq), /* W_200 */ W[ 7] = (2. / (delta_lambda * (a_sq + lambda)) - W[4] - W[6]) / 3., /* W_020 */ W[ 8] = (2. / (delta_lambda * (b_sq + lambda)) - W[5] - W[4]) / 3., /* W_002 */ W[ 9] = (2. / (delta_lambda * (c_sq + lambda)) - W[6] - W[5]) / 3., /* W_111 */ W[10] = (W[4] - W[5]) / (c_sq - a_sq), /* W_120 */ W[11] = (W[8] - W[4]) / (a_sq - b_sq), /* W_012 */ W[12] = (W[9] - W[5]) / (b_sq - c_sq), /* W_201 */ W[13] = (W[7] - W[6]) / (c_sq - a_sq), /* W_210 */ W[14] = (W[7] - W[4]) / (b_sq - a_sq), // NOTE Fixed. Nov. 15, 2015 /* W_021 */ W[15] = (W[8] - W[5]) / (c_sq - b_sq), // /* W_102 */ W[16] = (W[9] - W[6]) / (a_sq - c_sq), // /* W_300 */ W[17] = (2. / (delta_lambda * Sq(a_sq + lambda)) - W[14] - W[13]) / 5., /* W_030 */ W[18] = (2. / (delta_lambda * Sq(b_sq + lambda)) - W[15] - W[11]) / 5., /* W_003 */ W[19] = (2. / (delta_lambda * Sq(c_sq + lambda)) - W[16] - W[12]) / 5.; } else { int i_ijk; for(i_ijk = 0; i_ijk < 20; ++ i_ijk) W[i_ijk] = (ws -> W_i)[i_ijk]; } return 0; } double _orbita_potential_ferrers2_psi(const void * par, const double * pos) { struct orbita_potential_ferrers2_paramset * ws = (struct orbita_potential_ferrers2_paramset *) par; double W[20]; _orbita_potential_ferrers2_evaluate_wijk( pos[0], pos[1], pos[2], ws -> a, ws -> b, ws -> c, W, 0, ws); double x_sq = pos[0] * pos[0], y_sq = pos[1] * pos[1], z_sq = pos[2] * pos[2]; /* return (-(ws -> C) / 6.) * ( W[0] - 6. * x_sq * y_sq * z_sq * W[10] + x_sq * (x_sq * (3. * W[7] - x_sq * W[17]) + 3. * (y_sq * (2 * W[4] - y_sq * W[11] - x_sq * W[14]) - W[1])) + y_sq * (y_sq * (3. * W[8] - y_sq * W[18]) + 3. * (z_sq * (2 * W[5] - z_sq * W[12] - y_sq * W[15]) - W[2])) + z_sq * (z_sq * (3. * W[9] - z_sq * W[19]) + 3. * (x_sq * (2 * W[6] - x_sq * W[13] - z_sq * W[16]) - W[3])) ); */ // This is to test if Del^2 Psi == 4 Pi G rho. Returns rho from W_jkl. return ((ws -> a) * (ws -> b) * (ws -> c) * (ws -> rho) / 2.) * ( (W[1] + W[2] + W[3]) - 2. * ((y_sq + x_sq) * W[4] + (z_sq + y_sq) * W[5] + (x_sq + z_sq) * W[6]) - 6. * (x_sq * W[7] + y_sq * W[8] + z_sq * W[9]) + 2. * (x_sq * y_sq + y_sq * z_sq + z_sq * x_sq) * W[10] + (y_sq * y_sq + 6. * x_sq * y_sq) * W[11] + (z_sq * z_sq + 6. * y_sq * z_sq) * W[12] + (x_sq * x_sq + 6. * z_sq * x_sq) * W[13] + (6. * x_sq * y_sq + x_sq * x_sq) * W[14] + (6. * y_sq * z_sq + y_sq * y_sq) * W[15] + (6. * z_sq * x_sq + z_sq * z_sq) * W[16] + 5. * (x_sq * x_sq * W[17] + y_sq * y_sq * W[18] + z_sq * z_sq * W[19]) ); } int _orbita_potential_ferrers2_f(const void * par, const double * pos, double * F) { struct orbita_potential_ferrers2_paramset * ws = (struct orbita_potential_ferrers2_paramset *) par; double W[20]; _orbita_potential_ferrers2_evaluate_wijk( pos[0], pos[1], pos[2], ws -> a, ws -> b, ws -> c, W, 0, ws); double x_sq = pos[0] * pos[0], y_sq = pos[1] * pos[1], z_sq = pos[2] * pos[2]; // F[0] = -pos[0] * (ws -> C) * // ( W[1] + x_sq * (x_sq * W[17] + 2. * (y_sq * W[14] - W[7])) + y_sq * (y_sq * W[11] + 2. * (z_sq * W[10] - W[4])) + z_sq * (z_sq * W[16] + 2. * (x_sq * W[13] - W[6])) ), F[1] = -pos[1] * (ws -> C) * // ( W[2] + x_sq * (x_sq * W[14] + 2. * (y_sq * W[11] - W[4])) + y_sq * (y_sq * W[18] + 2. * (z_sq * W[15] - W[8])) + z_sq * (z_sq * W[12] + 2. * (x_sq * W[10] - W[5])) ), F[2] = -pos[2] * (ws -> C) * // ( W[3] + x_sq * (x_sq * W[13] + 2. * (y_sq * W[10] - W[6])) + y_sq * (y_sq * W[15] + 2. * (z_sq * W[12] - W[5])) + z_sq * (z_sq * W[19] + 2. * (x_sq * W[16] - W[9])) ); return 0; } double _orbita_potential_ferrers2_rho(const void * par, const double * pos) { struct orbita_potential_ferrers2_paramset * ws = (struct orbita_potential_ferrers2_paramset *) par; double m_sq = Sq(pos[0]) / Sq(ws -> a) + Sq(pos[1]) / Sq(ws -> b) + Sq(pos[2]) / Sq(ws -> c); if(m_sq < 1.) return (ws -> rho) * Sq(1 - m_sq); else return 0.; } double _orbita_potential_ferrers2_Mr(const void * par, const double R) { orbita_err("Method not supported."); return 0.; } double _orbita_potential_ferrers2_Mt(const void * par) { struct orbita_potential_ferrers2_paramset * ws = (struct orbita_potential_ferrers2_paramset *) par; return (ws -> rho) * (ws -> a) * (ws -> b) * (ws -> c) * (32. * Pi / 105.); } int _orbita_potential_ferrers2_kill(struct orbita_potential * psi) { free(psi -> param); return 0; } struct orbita_potential * orbita_potential_ferrers2(double rho, double a, double b, double c) { struct orbita_potential * psi = (struct orbita_potential *) malloc(sizeof(struct orbita_potential)); struct orbita_potential_ferrers2_paramset * ws = (struct orbita_potential_ferrers2_paramset *) malloc(sizeof(struct orbita_potential_ferrers2_paramset)); psi -> param = (void *)ws; // initialize w_i _orbita_potential_ferrers2_evaluate_wijk(0., 0., 0., a, b, c, ws -> W_i, 1, ws); ws -> C = 2. * Pi * rho * a * b * c; ws -> a = a, ws -> b = b, ws -> c = c, ws -> rho = rho; // set other parameters psi -> symmetry = 0, psi -> coordinates = ORBITA_COORD_CARTESIAN; psi -> rho = & _orbita_potential_ferrers2_rho, psi -> psi = & _orbita_potential_ferrers2_psi, psi -> f = & _orbita_potential_ferrers2_f, psi -> Mr = & _orbita_potential_ferrers2_Mr, psi -> Mt = & _orbita_potential_ferrers2_Mt; psi -> is_variable = 0, psi -> init_param = NULL, psi -> param_func = NULL; psi -> kill = & _orbita_potential_ferrers2_kill; psi -> is_composite = 0; return psi; }
{ "alphanum_fraction": 0.4810960068, "avg_line_length": 35.265917603, "ext": "c", "hexsha": "41fdda9d420d9453972356e0668add0bef3adeb0", "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": "98cc210922d123e7570ec40c4145190e1876cc69", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "shiaki/orbita", "max_forks_repo_path": "src/ferrers.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "98cc210922d123e7570ec40c4145190e1876cc69", "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": "shiaki/orbita", "max_issues_repo_path": "src/ferrers.c", "max_line_length": 108, "max_stars_count": 3, "max_stars_repo_head_hexsha": "98cc210922d123e7570ec40c4145190e1876cc69", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "shiaki/orbita", "max_stars_repo_path": "src/ferrers.c", "max_stars_repo_stars_event_max_datetime": "2019-03-20T02:06:46.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-06T18:45:10.000Z", "num_tokens": 3701, "size": 9416 }
/*==================BEGIN ASF DOCUMENTATION==================*/ /* ABOUT EDITING THIS DOCUMENTATION: If you wish to edit the documentation for this program, you need to change the following defines. */ #define ASF_NAME_STRING \ "asf_export" #define ASF_USAGE_STRING \ " "ASF_NAME_STRING" [-format <output_format>] [-byte <sample mapping option>]\n"\ " [-rgb <red> <green> <blue>] [-band <band_id | all>]\n"\ " [-lut <look up table file>] [-truecolor] [-falsecolor]\n"\ " [-log <log_file>] [-quiet] [-license] [-version] [-help]\n"\ " <in_base_name> <out_full_name>\n" #define ASF_DESCRIPTION_STRING \ " This program ingests ASF internal format data and exports said data to a\n"\ " number of graphics file formats (TIFF/GEOTIFF, JPEG, PGM, PNG, POlSARPRO,\n"\ " HDF5 and netCDF).\n"\ " If the input data was geocoded and the ouput format supports geocoding,\n"\ " that information will be included. Optionally, you may apply look-up tables,\n"\ " assign color bands (-rgb, -truecolor, -falsecolor).\n" #define ASF_INPUT_STRING \ " A file set in the ASF internal data format.\n" #define ASF_OUTPUT_STRING \ " The converted data in the output file, with the requested format.\n" #define ASF_OPTIONS_STRING \ " -format <format>\n"\ " Format to export to. Must be one of the following:\n"\ " tiff - Tagged Image File Format, with byte valued pixels\n"\ " geotiff - GeoTIFF file, with floating point or byte valued pixels\n"\ " jpeg - Lossy compressed image, with byte valued pixels\n"\ " pgm - Portable graymap image, with byte valued pixels\n"\ " png - Portable network graphic, with byte valued pixels\n"\ " polsarpro - Flat binary floating point files in PolSARPro format\n"\ " hdf5 - HDF5 format, with floating point or byte valued pixels\n"\ " netcdf - netCDF format compliant to the CF conventions\n"\ " NOTE: When exporting to a GeoTIFF format file, all map-projection\n"\ " information is included in GeoKeys as specified in the GeoTIFF\n"\ " standard. The other graphics file formats do not support the\n"\ " storing of map-projection parameters in the output file. If you\n"\ " wish to maintain the map-projection and/or georeference (corner\n"\ " point) information in the output, you should choose the GeoTIFF\n"\ " output format.\n\n"\ " NOTE: When exporting to a GeoTIFF format file, the data format (floating\n"\ " point, byte, 16-bit integer, etc) will be maintained. Many viewers\n"\ " cannot view non-integer data. Leaving the data format the same as\n"\ " the original produces the most accurate export, but remapping it to\n"\ " byte range (0-255) with the -byte option will result in the greatest\n"\ " compatibility with viewers and GIS software packages.\n\n"\ " -byte <sample mapping option>\n"\ " Converts output image to byte using the following options:\n"\ " truncate\n"\ " values less than 0 are mapped to 0, values greater than 255\n"\ " are mapped to 255, and values in between are converted to\n"\ " whole numbers (the fractional part of the values are truncated,\n"\ " not rounded.)\n"\ " minmax\n"\ " determines the minimum and maximum values of the input image\n"\ " and linearly maps those values to the byte range of 0 to 255.\n"\ " The remapping is accomplished using real (floating point)\n"\ " numbers then the result is converted to a whole number by\n"\ " truncating the fractional part.\n"\ " sigma\n"\ " determines the mean and standard deviation of an image and\n"\ " defines a range of +/- two standard deviations (2-sigma)\n"\ " around the mean value, and maps this buffer to the byte range\n"\ " 0 to 255 as described for minmax above. The range limits are\n"\ " adjusted if the either of the 2-sigma range limits lie outside\n"\ " the range of the original values. As with the other remapping\n"\ " methods, the calculation of values are made with real numbers\n"\ " and the result is converted to a whole number by truncating\n"\ " any fractional part.\n"\ " histogram_equalize\n"\ " develops a look-up table by integrating the (no-adaptation)\n"\ " whole-image histogram and then normalizing the result to the\n"\ " 0-255 range. The result is that areas of low contrast, i.e.\n"\ " flat topography, have a stronger contrast expansion applied\n"\ " while areas of high contrast, i.e. non-flat topography, will\n"\ " receive less contrast expansion. Histogram equalization\n"\ " is a useful transform for making hard-to-see detail more\n"\ " visible for the the viewer but is likewise a nonlinear\n"\ " transform that results in minor (apparent) topography shifts\n"\ " within the image. Since shifts occur the most in areas where\n"\ " the contrast is expanded the most, i.e. flat topography, and\n"\ " less in areas of more interesting topography, the pragmatic\n"\ " conclusion is that the nonlinear shifts are quite\n"\ " insignificant for the majority of users ...only important\n"\ " if performing precision geography measurements or overlays.\n"\ " -rgb <red> <green> <blue>\n"\ " Converts output image into a color RGB image.\n"\ " <red>, <green>, and <blue> specify which band (channel)\n"\ " is assigned to color planes red, green, or blue,\n"\ " ex) '-rgb HH VH VV', or '-rgb 3 2 1'. If the word 'ignore' is\n"\ " provided as one or more bands, then the associated color plane\n"\ " will not be exported, e.g. '-rgb ignore 2 1' will result in an\n"\ " RGB file that has a zero in each RGB pixel's red component, band 2\n"\ " assigned to the green channel, and band 1 assigned to the blue.\n"\ " The result will be an image with only greens and blues in it.\n"\ " Currently implemented for GeoTIFF, TIFF, JPEG and PNG.\n"\ " Cannot be used together with the -band option.\n"\ " -lut <look up table file>\n"\ " Applies a color look up table to the image while exporting.\n"\ " Only allowed for single-band images. Images must contain byte (8-bit)\n"\ " data (except for data deriving from PolSARpro classifications.) Some\n"\ " look-up table files are in the look_up_tables subdirectory in\n"\ " the asf_tools share directory. The tool will look in\n"\ " this directory for the specified file if it isn't found\n"\ " in the current directory.\n"\ " -truecolor\n"\ " For 3 or 4 band optical satellite images where the first band is the\n"\ " the blue band, the second green, and the third red. This option will\n"\ " export the third band as the red element, the second band as the green\n"\ " element, and the first band as the blue element. Performs a 2-sigma\n"\ " constrast expansion on each individual band during the export (similar\n"\ " to most GIS software packages.) To export a true-color image WITHOUT\n"\ " the contrast expansion associated with the truecolor option, use the\n"\ " -rgb option instead. The rgb option will directly assign the\n"\ " available bands, unaltered, to the RGB color channels in the output\n"\ " file, e.g.\n\n"\ " 'asf_export -rgb 03 02 01 <infile> <outfile>'.\n\n"\ " Only allowed for multi-band images with 3 or more bands.\n"\ " The truecolor option cannot be used together with any of the\n"\ " following options: -rgb, -band, or -falsecolor.\n"\ " -falsecolor\n"\ " For 4 band optical satellite images where the second band is green,\n"\ " the third red, and the fourth is the near-infrared band. Exports\n"\ " the fourth (IR) band as the red element, the third band as the green\n"\ " element, and the second band as the blue element. Performs a 2-sigma\n"\ " constrast expansion on the individual bands during the export. To\n"\ " export a falsecolor image WITHOUT the contrast expansion, use the\n"\ " -rgb flag to directly assign the available bands to the RGB color\n"\ " channels, e.g.\n\n"\ " 'asf_export -rgb 04 03 02 <infile> <outfile>'.\n\n"\ " Only allowed for multi-band images with 4 bands.\n"\ " Cannot be used together with any of the following: -rgb, -band,\n"\ " or -truecolor.\n"\ " -band <band_id | all>\n"\ " If the data contains multiple data files, one for each band (channel)\n"\ " then export the band identified by 'band_id' (only). If 'all' is\n"\ " specified rather than a band_id, then export all available bands into\n"\ " individual files, one for each band. Default is '-band all'.\n"\ " Cannot be chosen together with the -rgb option.\n"\ " -log <logFile>\n"\ " Output will be written to a specified log file.\n"\ " -quiet\n"\ " Supresses all non-essential output.\n"\ " -license\n"\ " Print copyright and license for this software then exit.\n"\ " -version\n"\ " Print version and copyright then exit.\n"\ " -help\n"\ " Print a help page and exit.\n" #define ASF_EXAMPLES_STRING \ " To export to the default GeoTIFF format from file1.img and file1.meta\n"\ " to file1.tif:\n"\ " example> "ASF_NAME_STRING" file1 file1\n\n"\ " NOTE: When exporting to a GeoTIFF format file, all map-projection\n"\ " information is included in GeoKeys as specified in the GeoTIFF\n"\ " standard.\n\n"\ " NOTE: When exporting to a GeoTIFF format file, the data format (floating\n"\ " point, byte, 16-bit integer, etc) will be maintained. Many viewers\n"\ " cannot view non-integer data. Leaving the data format the same as\n"\ " the original produces the most accurate export, but remapping it to\n"\ " byte range (0-255) with the -byte option will result in the greatest\n"\ " compatibility with viewers and GIS software packages.\n"\ "\n"\ " To export to file2.jpg in the jpeg format:\n"\ " example> "ASF_NAME_STRING" -format jpeg file1 file2\n"\ "\n" #define ASF_LIMITATIONS_STRING \ " Currently supports ingest of ASF format floating point and byte data (only).\n"\ "\n"\ " Floating-point image formats (i.e., geotiff) are not supported in many\n"\ " image viewing programs.\n" #define ASF_SEE_ALSO_STRING \ " asf_mapready, asf_import\n" /*===================END ASF DOCUMENTATION===================*/ #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <limits.h> #include <cla.h> #include <envi.h> #include <esri.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_statistics.h> #include <asf.h> #include <asf_endian.h> #include <asf_meta.h> #include <asf_raster.h> #include <asf_export.h> #include <asf_contact.h> #include <asf_license.h> // Local prototypes int is_numeric(char *str); // Print minimalistic usage info & exit static void print_usage(void) { asfPrintStatus("\n" "Usage:\n" ASF_USAGE_STRING "\n"); exit(EXIT_FAILURE); } // Print the help info & exit static void print_help(void) { asfPrintStatus( "\n" "Tool name:\n " ASF_NAME_STRING "\n\n" "Usage:\n" ASF_USAGE_STRING "\n" "Description:\n" ASF_DESCRIPTION_STRING "\n" "Input:\n" ASF_INPUT_STRING "\n" "Output:\n"ASF_OUTPUT_STRING "\n" "Options:\n" ASF_OPTIONS_STRING "\n" "Examples:\n" ASF_EXAMPLES_STRING "\n" "Limitations:\n" ASF_LIMITATIONS_STRING "\n" "See also:\n" ASF_SEE_ALSO_STRING "\n" "Contact:\n" ASF_CONTACT_STRING "\n" "Version:\n " SVN_REV " (part of " TOOL_SUITE_NAME " " MAPREADY_VERSION_STRING ")\n\n"); exit(EXIT_FAILURE); } int checkForOption (char *key, int argc, char *argv[]) { int ii = 0; while ( ii < argc ) { if ( strmatch (key, argv[ii]) ) return ii; ++ii; } return FLAG_NOT_SET; } static const char *sigma_str(int with_sigma) { return with_sigma ? "w/sigma" : ""; } // Main program body. int main (int argc, char *argv[]) { output_format_t format = 0; meta_parameters *md; char *in_base_name, *output_name; char **band_names=NULL; int rgb=0; int true_color; int false_color; int num_bands_found; int ignored[3] = {0, 0, 0}; int num_ignored = 0; in_base_name = (char *) MALLOC(sizeof(char)*255); output_name = (char *) MALLOC(sizeof(char)*255); /**********************BEGIN COMMAND LINE PARSING STUFF**********************/ // Command line input goes in it's own structure. command_line_parameters_t command_line; strcpy (command_line.format, ""); command_line.size = NO_MAXIMUM_OUTPUT_SIZE; strcpy (command_line.in_data_name, ""); strcpy (command_line.in_meta_name, ""); strcpy (command_line.output_name, ""); command_line.verbose = FALSE; command_line.quiet = FALSE; strcpy (command_line.leader_name, ""); strcpy (command_line.cal_params_file, ""); strcpy (command_line.cal_comment, ""); command_line.sample_mapping = 0; strcpy(command_line.red_channel, ""); strcpy(command_line.green_channel, ""); strcpy(command_line.blue_channel, ""); strcpy(command_line.band, ""); strcpy(command_line.look_up_table_name, ""); int formatFlag, logFlag, quietFlag, byteFlag, rgbFlag, bandFlag, lutFlag; int truecolorFlag, falsecolorFlag; int needed_args = 3; //command & argument & argument int ii; char sample_mapping_string[25]; //Check to see which options were specified if ( (checkForOption("--help", argc, argv) != FLAG_NOT_SET) || (checkForOption("-h", argc, argv) != FLAG_NOT_SET) || (checkForOption("-help", argc, argv) != FLAG_NOT_SET) ) { print_help(); } get_asf_share_dir_with_argv0(argv[0]); handle_license_and_version_args(argc, argv, ASF_NAME_STRING); formatFlag = checkForOption ("-format", argc, argv); logFlag = checkForOption ("-log", argc, argv); quietFlag = checkForOption ("-quiet", argc, argv); byteFlag = checkForOption ("-byte", argc, argv); rgbFlag = checkForOption ("-rgb", argc, argv); bandFlag = checkForOption ("-band", argc, argv); lutFlag = checkForOption ("-lut", argc, argv); truecolorFlag = checkForOption("-truecolor", argc, argv); falsecolorFlag = checkForOption("-falsecolor", argc, argv); if ( formatFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( quietFlag != FLAG_NOT_SET ) { needed_args += 1; // Option & parameter. } if ( logFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( byteFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( rgbFlag != FLAG_NOT_SET ) { needed_args += 4; // Option & 3 parameters. } if ( bandFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( lutFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( truecolorFlag != FLAG_NOT_SET ) { needed_args += 1; // Option only } if ( falsecolorFlag != FLAG_NOT_SET ) { needed_args += 1; // Option only } if ( argc != needed_args ) { print_usage (); // This exits with a failure. } // We also need to make sure the last three options are close to // what we expect. if ( argv[argc - 1][0] == '-' || argv[argc - 2][0] == '-' ) { print_usage (); // This exits with a failure. } // Make sure any options that have parameters are followed by // parameters (and not other options) Also make sure options' // parameters don't bleed into required arguments. if ( formatFlag != FLAG_NOT_SET ) { if ( argv[formatFlag + 1][0] == '-' || formatFlag >= argc - 3 ) { print_usage (); } } if ( byteFlag != FLAG_NOT_SET ) { if ( argv[byteFlag + 1][0] == '-' || byteFlag >= argc - 3 ) { print_usage (); } } if ( rgbFlag != FLAG_NOT_SET ) { if (( argv[rgbFlag + 1][0] == '-' && argv[rgbFlag + 2][0] == '-' && argv[rgbFlag + 3][0] == '-' ) || rgbFlag >= argc - 5 ) { print_usage (); } } if ( bandFlag != FLAG_NOT_SET ) { if ( argv[bandFlag + 1][0] == '-' || bandFlag >= argc - 3 ) { print_usage (); } } if ( lutFlag != FLAG_NOT_SET ) { if ( argv[lutFlag + 1][0] == '-' || lutFlag >= argc - 3 ) { print_usage (); } } if ( logFlag != FLAG_NOT_SET ) { if ( argv[logFlag + 1][0] == '-' || logFlag >= argc - 3 ) { print_usage (); } } // Make sure there are no flag incompatibilities if ( (rgbFlag != FLAG_NOT_SET && (bandFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET)) || (bandFlag != FLAG_NOT_SET && (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET)) || (truecolorFlag != FLAG_NOT_SET && (bandFlag != FLAG_NOT_SET || rgbFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET)) || (falsecolorFlag != FLAG_NOT_SET && (bandFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || rgbFlag != FLAG_NOT_SET)) ) { asfPrintWarning("The following options may only be used one at a time:\n" " %s\n %s\n %s\n %s\n %s\n %s\n", "-rgb", "-truecolor", "-falsecolor", "-band"); print_help(); } if ( (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) && lutFlag != FLAG_NOT_SET ) asfPrintError("Look up table option can only be used on single-band " "images.\n"); if( logFlag != FLAG_NOT_SET ) { strcpy(logFile, argv[logFlag+1]); } else { sprintf(logFile, "tmp%i.log", (int)getpid()); } logflag = TRUE; // Since we always log, set the old school logflag to true fLog = FOPEN (logFile, "a"); // Set old school quiet flag (for use in our libraries) quietflag = ( quietFlag != FLAG_NOT_SET ) ? TRUE : FALSE; // We're good enough at this point... print the splash screen. asfSplashScreen (argc, argv); // Grab the input and output name strcpy (in_base_name, argv[argc - 2]); strcpy (output_name, argv[argc - 1]); strcpy (command_line.output_name, output_name); // If user added ".img", strip it. char *ext = findExt(in_base_name); if (ext && strcmp(ext, ".img") == 0) *ext = '\0'; // Set default output type if( formatFlag != FLAG_NOT_SET ) { strcpy (command_line.format, argv[formatFlag + 1]); } else { // Default behavior: produce a geotiff. strcpy (command_line.format, "geotiff"); } // Compose input metadata name strcpy (command_line.in_meta_name, in_base_name); strcat (command_line.in_meta_name, ".meta"); // for some validation, need the metadata md = meta_read (command_line.in_meta_name); // Convert the string to upper case. for ( ii = 0 ; ii < strlen (command_line.format) ; ++ii ) { command_line.format[ii] = toupper (command_line.format[ii]); } if (strcmp (command_line.format, "PGM") == 0 && (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) ) { asfPrintWarning("Greyscale PGM output is not compatible with color options:\n" "(RGB, True Color, False Color, color look-up tables, etc\n)" "...Defaulting to producing separate greyscale PGM files for available band.\n"); rgbFlag = FLAG_NOT_SET; truecolorFlag = FLAG_NOT_SET; falsecolorFlag = FLAG_NOT_SET; } // Set the default byte scaling mechanisms if (md->optical) { // for optical data, default sample mapping is NONE command_line.sample_mapping = NONE; } // for other data, default is based on the output type else if (strcmp (command_line.format, "TIFF") == 0 || strcmp (command_line.format, "TIF") == 0 || strcmp (command_line.format, "JPEG") == 0 || strcmp (command_line.format, "JPG") == 0 || strcmp (command_line.format, "PNG") == 0 || strcmp (command_line.format, "PGM") == 0 || strcmp (command_line.format, "PNG_ALPHA") == 0 || strcmp (command_line.format, "PNG_GE") == 0) { command_line.sample_mapping = SIGMA; } else if (strcmp (command_line.format, "GEOTIFF") == 0) { command_line.sample_mapping = NONE; } if ( quietFlag != FLAG_NOT_SET ) command_line.quiet = TRUE; else command_line.quiet = FALSE; // Set rgb combination if ( rgbFlag != FLAG_NOT_SET ) { int i; for (i=0, num_ignored = 0; i<3; i++) { ignored[i] = strncmp("IGNORE", uc(argv[rgbFlag + i + 1]), 6) == 0 ? 1 : 0; num_ignored += ignored[i] ? 1 : 0; } asfRequire(num_ignored < 3, "Cannot ignore all bands. Exported image would be blank.\n"); strcpy (command_line.red_channel, ignored[0] ? "Ignored" : argv[rgbFlag + 1]); strcpy (command_line.green_channel, ignored[1] ? "Ignored" : argv[rgbFlag + 2]); strcpy (command_line.blue_channel, ignored[2] ? "Ignored" : argv[rgbFlag + 3]); // Check to see if the bands are numeric and in range int r_channel = atoi(command_line.red_channel); int g_channel = atoi(command_line.green_channel); int b_channel = atoi(command_line.blue_channel); /////////// Numeric channel case //////////// // Remove trailing non-numeric characters from the channel number // string and pad front end nicely with a zero if (!ignored[0] && is_numeric(command_line.red_channel) && r_channel >= 1 && r_channel <= MAX_BANDS) { sprintf(command_line.red_channel, "%02d", atoi(command_line.red_channel)); } if (!ignored[1] && is_numeric(command_line.green_channel) && g_channel >= 1 && g_channel <= MAX_BANDS) { sprintf(command_line.green_channel, "%02d", atoi(command_line.green_channel)); } if (!ignored[2] && is_numeric(command_line.blue_channel) && b_channel >= 1 && b_channel <= MAX_BANDS) { sprintf(command_line.blue_channel, "%02d", atoi(command_line.blue_channel)); } } // Set up the bands for true or false color optical data true_color = false_color = 0; int with_sigma = FALSE; if (truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) { int ALOS_optical = (md->optical && strncmp(md->general->sensor, "ALOS", 4) == 0) ? 1 : 0; if (md->optical && truecolorFlag != FLAG_NOT_SET) { if (ALOS_optical) { with_sigma = TRUE; strcpy(command_line.red_channel, "03"); strcpy(command_line.green_channel, "02"); strcpy(command_line.blue_channel, "01"); true_color = 1; asfPrintStatus("Applying True Color contrast expansion to following channels:"); } else { char **bands = extract_band_names(md->general->bands, 3); asfRequire(bands != NULL, "-truecolor option specified for non-true color optical image.\n"); asfPrintWarning("Attempting to use the -truecolor option with non-ALOS\n" "optical data.\n"); strcpy(command_line.red_channel, bands[2]); strcpy(command_line.green_channel, bands[1]); strcpy(command_line.blue_channel, bands[0]); int i; for (i=0; i<3; i++) { FREE(bands[i]); } FREE(bands); } } if (md->optical && falsecolorFlag != FLAG_NOT_SET) { if (ALOS_optical) { with_sigma = TRUE; strcpy(command_line.red_channel, "04"); strcpy(command_line.green_channel, "03"); strcpy(command_line.blue_channel, "02"); false_color = 1; asfPrintStatus("Applying False Color contrast expansion to the following channels:"); } else { char **bands = extract_band_names(md->general->bands, 4); asfRequire(bands != NULL, "-falsecolor option specified for an optical image with fewer than 4 bands.\n"); asfPrintWarning("Attempting to use the -falsecolor option with non-ALOS\n" "optical data.\n"); strcpy(command_line.red_channel, bands[3]); strcpy(command_line.green_channel, bands[2]); strcpy(command_line.blue_channel, bands[1]); int i; for (i=0; i<3; i++) { FREE(bands[i]); } FREE(bands); } } if (!ALOS_optical && !md->optical) { asfPrintError("-truecolor or -falsecolor option selected with non-optical data\n"); } } if (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) { char red_band[16], green_band[16], blue_band[16]; asfPrintStatus("\nRed channel : %s %s\n", command_line.red_channel, sigma_str(with_sigma)); asfPrintStatus("Green channel: %s %s\n", command_line.green_channel, sigma_str(with_sigma)); asfPrintStatus("Blue channel : %s %s\n\n", command_line.blue_channel, sigma_str(with_sigma)); if (is_numeric(command_line.red_channel) && is_numeric(command_line.green_channel) && is_numeric(command_line.blue_channel)) { sprintf(red_band, "%02d", atoi(command_line.red_channel)); sprintf(green_band, "%02d", atoi(command_line.green_channel)); sprintf(blue_band, "%02d", atoi(command_line.blue_channel)); band_names = find_bands(in_base_name, rgbFlag, red_band, green_band, blue_band, &num_bands_found); } else { band_names = find_bands(in_base_name, rgbFlag, command_line.red_channel, command_line.green_channel, command_line.blue_channel, &num_bands_found); } } // Set band if ( bandFlag != FLAG_NOT_SET) { strcpy (command_line.band, argv[bandFlag + 1]); band_names = find_single_band(in_base_name, command_line.band, &num_bands_found); } else if (rgbFlag == FLAG_NOT_SET && truecolorFlag == FLAG_NOT_SET && falsecolorFlag == FLAG_NOT_SET && bandFlag == FLAG_NOT_SET) { bandFlag=1; // For proper messaging to the user strcpy (command_line.band, "all"); band_names = find_single_band(in_base_name, command_line.band, &num_bands_found); } // Read look up table name if ( lutFlag != FLAG_NOT_SET) { strcpy(command_line.look_up_table_name, argv[lutFlag + 1]); rgb = 1; } // Set scaling mechanism if ( byteFlag != FLAG_NOT_SET ) { strcpy (sample_mapping_string, argv[byteFlag + 1]); for ( ii = 0; ii < strlen(sample_mapping_string); ii++) { sample_mapping_string[ii] = toupper (sample_mapping_string[ii]); } if ( strcmp (sample_mapping_string, "TRUNCATE") == 0 ) command_line.sample_mapping = TRUNCATE; else if ( strcmp(sample_mapping_string, "MINMAX") == 0 ) command_line.sample_mapping = MINMAX; else if ( strcmp(sample_mapping_string, "SIGMA") == 0 ) command_line.sample_mapping = SIGMA; else if ( strcmp(sample_mapping_string, "HISTOGRAM_EQUALIZE") == 0 ) command_line.sample_mapping = HISTOGRAM_EQUALIZE; else if ( strcmp(sample_mapping_string, "NONE") == 0 ) { asfPrintWarning("Sample remapping method (-byte option) is set to NONE\n" "which doesn't make sense. Defaulting to TRUNCATE...\n"); command_line.sample_mapping = TRUNCATE; } else asfPrintError("Unrecognized byte scaling method '%s'.\n", sample_mapping_string); } int is_polsarpro = (md->general->bands && strstr(md->general->bands, "POLSARPRO") != NULL) ? 1 : 0; if ( !is_polsarpro && lutFlag != FLAG_NOT_SET && bandFlag == FLAG_NOT_SET && md->general->band_count > 1) { asfPrintError("Look up tables can only be applied to single band" " images\n"); } if ( !is_polsarpro && lutFlag != FLAG_NOT_SET && command_line.sample_mapping == NONE && md->general->data_type != BYTE && md->general->band_count == 1) { asfPrintError("Look up tables can only be applied to byte output" " images\n"); } // Report what is going to happen if (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) { if (num_bands_found >= 3) { asfPrintStatus("Exporting multiband image ...\n\n"); rgb = 1; } else { asfPrintError("Not all RGB channels found.\n"); } } else if (bandFlag != FLAG_NOT_SET) { if (strcmp_case(command_line.band, "ALL") == 0) { if (multiband(command_line.format, extract_band_names(md->general->bands, md->general->band_count), md->general->band_count)) asfPrintStatus("Exporting multiband image ...\n\n"); else if (num_bands_found > 1) asfPrintStatus("Exporting each band into individual greyscale files ...\n\n"); } else if (num_bands_found == 1) { if (lutFlag != FLAG_NOT_SET) asfPrintStatus("Exporting band '%s' applying look up table ...\n\n", command_line.band); else asfPrintStatus("Exporting band '%s' as greyscale ...\n\n", command_line.band); } else asfPrintError("Band could not be found in the image.\n"); } else if (lutFlag != FLAG_NOT_SET) asfPrintStatus("Exporting applying look up table.\n\n"); else asfPrintStatus("Exporting as greyscale.\n\n"); //If user added ".img", strip it. ext = findExt(in_base_name); if (ext && strcmp(ext, ".img") == 0) *ext = '\0'; meta_free(md); /***********************END COMMAND LINE PARSING STUFF***********************/ if ( strcmp (command_line.format, "ENVI") == 0 ) { format = ENVI; } else if ( strcmp (command_line.format, "ESRI") == 0 ) { format = ESRI; } else if ( strcmp (command_line.format, "GEOTIFF") == 0 || strcmp (command_line.format, "GEOTIF") == 0) { format = GEOTIFF; } else if ( strcmp (command_line.format, "TIFF") == 0 || strcmp (command_line.format, "TIF") == 0) { format = TIF; } else if ( strcmp (command_line.format, "JPEG") == 0 || strcmp (command_line.format, "JPG") == 0) { format = JPEG; } else if ( strcmp (command_line.format, "PGM") == 0 ) { format = PGM; } else if ( strcmp (command_line.format, "PNG") == 0 ) { format = PNG; } else if ( strcmp (command_line.format, "PNG_ALPHA") == 0 ) { format = PNG_ALPHA; } else if ( strcmp (command_line.format, "PNG_GE") == 0 ) { format = PNG_GE; } else if ( strcmp (command_line.format, "KML") == 0 ) { format = KML; } else if ( strcmp (command_line.format, "POLSARPRO") == 0 ) { format = POLSARPRO_HDR; } else if ( strcmp (command_line.format, "HDF5") == 0 ) { format = HDF; } else if ( strcmp (command_line.format, "NETCDF") == 0 ) { format = NC; } else { asfPrintError("Unrecognized output format specified\n"); } /* Complex data generally can't be output into meaningful images, so we refuse to deal with it. */ /* md = meta_read (command_line.in_meta_name); asfRequire ( md->general->data_type == BYTE || md->general->data_type == INTEGER16 || md->general->data_type == INTEGER32 || md->general->data_type == REAL32 || md->general->data_type == REAL64, "Cannot cope with complex data, exiting...\n"); meta_free (md); */ // Do that exporting magic! asf_export_bands(format, command_line.sample_mapping, rgb, true_color, false_color, command_line.look_up_table_name, in_base_name, command_line.output_name, band_names, NULL, NULL); // If the user didn't ask for a log file then nuke the one that's been kept // since everything has finished successfully if (logFlag == FLAG_NOT_SET) { fclose (fLog); remove(logFile); } for (ii = 0; ii<num_bands_found; ii++) { FREE(band_names[ii]); } FREE(band_names); FREE(in_base_name); FREE(output_name); exit (EXIT_SUCCESS); } int is_numeric(char *str) { char *s = str; int numericness = 1; while (*s != '\0') { if (!isdigit(*s)) numericness = 0; s++; } return numericness; }
{ "alphanum_fraction": 0.6148048048, "avg_line_length": 38.9929742389, "ext": "c", "hexsha": "741e84e43cace25509e3e19cd433309d5192387c", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/asf_export/asf_export.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/asf_export/asf_export.c", "max_line_length": 101, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/asf_export/asf_export.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 8551, "size": 33300 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "funcs.h" #include "initial.h" #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_ieee_utils.h> int main ( int argc, char* argv[] ) { gsl_ieee_env_setup () ; /* read GSL_IEEE_MODE */ printf("Temperature: %g\n\n", T*HBAR*Delta/BOLTZ) ; double beta = 1.0/T ; /* Boltzmann factor: beta */ double omega_1 = gsl_hypot(OMEGA,D) ; /* omega' */ struct f_params params; params.omega_c = omega_c ; params.beta = beta ; params.Omega = OMEGA ; params.omega_1 = omega_1 ; params.alpha = alpha ; int status1 = save_integrals ( &params ) ; int status2 = save_matrices ( &params ) ; /* read the Redfield matrix from a file */ gsl_matrix* red_m = gsl_matrix_calloc ( 4, 4 ) ; int status3 = mat_read ( red_m, "REDFIELD_MATRIX" ) ; /* read the CP matrix from a file */ gsl_matrix* cp_m = gsl_matrix_calloc ( 4, 4 ) ; int status4 = mat_read ( cp_m, "CP_MATRIX" ) ; /* Hamiltonian generator */ const double om[] = { 0 , 0 , 0 , omega_1/2 } ; gsl_matrix* H = gsl_matrix_calloc ( 4, 4 ) ; int status5 = ham_gen ( H, om ) ; /* * Find the stationary state by solving the linear systems * and the associated stationary currents */ gsl_vector* req_red = gsl_vector_calloc (4) ; gsl_vector* req_cp = gsl_vector_calloc (4) ; printf("REDFIELD DYNAMICS\n") ; int status6 = stationary ( red_m , req_red ) ; printf("Stationary state: ( %.1f , %.9f , %.9f , %.9f )\n", VECTOR(req_red,0), VECTOR(req_red,1), VECTOR(req_red,2), VECTOR(req_red,3) ) ; printf("Stationary normalized (I/I0) DC current: %.9f\n\n", -VECTOR(req_red,3)*OMEGA/omega_1) ; printf("CP DYNAMICS\n") ; int status7 = stationary ( cp_m , req_cp ) ; printf("Stationary state: ( %.1f , %.9f , %.9f , %.9f )\n", VECTOR(req_cp,0), VECTOR(req_cp,1), VECTOR(req_cp,2), VECTOR(req_cp,3) ) ; printf("Stationary normalized (I/I0) DC current: %.9f\n\n", -VECTOR(req_cp,3)*OMEGA/omega_1) ; /* Save the stationary states into files */ FILE* f = fopen ( "RED_STATIONARY.dat", "w" ) ; gsl_vector_fprintf ( f, req_red, "%.9f" ) ; FILE* g = fopen ( "CP_STATIONARY.dat", "w" ) ; gsl_vector_fprintf ( g, req_cp, "%.9f" ) ; fclose (f) ; fclose (g) ; /* polarization */ double D30 = gsl_matrix_get(cp_m,3,0) ; double D33 = gsl_matrix_get(cp_m,3,3) ; double pol = -D30/D33 ; printf("n-Polarization of the CP dynamics -D30/D33: %.9f\n", pol ) ; /* polarization through the formula (for checking) */ double P = polarization ( &params, omega_c ) ; printf("\n") ; printf("n-Polarization through the given formula: %.9f\n", P ) ; printf("Stationary normalized (I/I0) DC current: %.9f\n", -P*OMEGA/omega_1 ) ; /* free memory for matrices */ gsl_matrix_free(red_m) ; gsl_matrix_free(cp_m) ; return status1 + status2 + status3 + status4 + status5 + status6 + status7 ; }
{ "alphanum_fraction": 0.6896149358, "avg_line_length": 35.4132231405, "ext": "c", "hexsha": "875761b0097b56b6bd6b311a553cf29a027db0ad", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "asymptotic.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "asymptotic.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "asymptotic.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1225, "size": 4285 }
/* * Copyright (c) 1997-1999 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Sun Nov 7 20:43:55 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -real2hc 12 */ /* * This function contains 38 FP additions, 8 FP multiplications, * (or, 34 additions, 4 multiplications, 4 fused multiply/add), * 18 stack variables, and 24 memory accesses */ static const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627); static const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000); /* * Generator Id's : * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $ * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $ * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $ */ void fftw_real2hc_12(const fftw_real *input, fftw_real *real_output, fftw_real *imag_output, int istride, int real_ostride, int imag_ostride) { fftw_real tmp5; fftw_real tmp25; fftw_real tmp11; fftw_real tmp23; fftw_real tmp30; fftw_real tmp35; fftw_real tmp10; fftw_real tmp26; fftw_real tmp12; fftw_real tmp18; fftw_real tmp29; fftw_real tmp34; fftw_real tmp31; fftw_real tmp32; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp1; fftw_real tmp2; fftw_real tmp3; fftw_real tmp4; ASSERT_ALIGNED_DOUBLE; tmp1 = input[0]; tmp2 = input[4 * istride]; tmp3 = input[8 * istride]; tmp4 = tmp2 + tmp3; tmp5 = tmp1 + tmp4; tmp25 = tmp1 - (K500000000 * tmp4); tmp11 = tmp3 - tmp2; } { fftw_real tmp19; fftw_real tmp20; fftw_real tmp21; fftw_real tmp22; ASSERT_ALIGNED_DOUBLE; tmp19 = input[9 * istride]; tmp20 = input[istride]; tmp21 = input[5 * istride]; tmp22 = tmp20 + tmp21; tmp23 = tmp19 - (K500000000 * tmp22); tmp30 = tmp19 + tmp22; tmp35 = tmp21 - tmp20; } { fftw_real tmp6; fftw_real tmp7; fftw_real tmp8; fftw_real tmp9; ASSERT_ALIGNED_DOUBLE; tmp6 = input[6 * istride]; tmp7 = input[10 * istride]; tmp8 = input[2 * istride]; tmp9 = tmp7 + tmp8; tmp10 = tmp6 + tmp9; tmp26 = tmp6 - (K500000000 * tmp9); tmp12 = tmp8 - tmp7; } { fftw_real tmp14; fftw_real tmp15; fftw_real tmp16; fftw_real tmp17; ASSERT_ALIGNED_DOUBLE; tmp14 = input[3 * istride]; tmp15 = input[7 * istride]; tmp16 = input[11 * istride]; tmp17 = tmp15 + tmp16; tmp18 = tmp14 - (K500000000 * tmp17); tmp29 = tmp14 + tmp17; tmp34 = tmp16 - tmp15; } real_output[3 * real_ostride] = tmp5 - tmp10; imag_output[3 * imag_ostride] = tmp29 - tmp30; tmp31 = tmp5 + tmp10; tmp32 = tmp29 + tmp30; real_output[6 * real_ostride] = tmp31 - tmp32; real_output[0] = tmp31 + tmp32; { fftw_real tmp37; fftw_real tmp38; fftw_real tmp33; fftw_real tmp36; ASSERT_ALIGNED_DOUBLE; tmp37 = tmp34 + tmp35; tmp38 = tmp11 + tmp12; imag_output[2 * imag_ostride] = K866025403 * (tmp37 - tmp38); imag_output[4 * imag_ostride] = K866025403 * (tmp38 + tmp37); tmp33 = tmp25 - tmp26; tmp36 = K866025403 * (tmp34 - tmp35); real_output[5 * real_ostride] = tmp33 - tmp36; real_output[real_ostride] = tmp33 + tmp36; } { fftw_real tmp27; fftw_real tmp28; fftw_real tmp13; fftw_real tmp24; ASSERT_ALIGNED_DOUBLE; tmp27 = tmp25 + tmp26; tmp28 = tmp18 + tmp23; real_output[2 * real_ostride] = tmp27 - tmp28; real_output[4 * real_ostride] = tmp27 + tmp28; tmp13 = K866025403 * (tmp11 - tmp12); tmp24 = tmp18 - tmp23; imag_output[imag_ostride] = tmp13 - tmp24; imag_output[5 * imag_ostride] = -(tmp13 + tmp24); } } fftw_codelet_desc fftw_real2hc_12_desc = { "fftw_real2hc_12", (void (*)()) fftw_real2hc_12, 12, FFTW_FORWARD, FFTW_REAL2HC, 266, 0, (const int *) 0, };
{ "alphanum_fraction": 0.6625922023, "avg_line_length": 28.7575757576, "ext": "c", "hexsha": "bb229553ae6cf37364ef585adeae52c8dbdc4380", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_12.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_12.c", "max_line_length": 141, "max_stars_count": 9, "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_12.c", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "num_tokens": 1552, "size": 4745 }
/* * PIXON * A Pixon-based method for reconstructing velocity-delay map in reverberation mapping. * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * */ /*! * \file mathfun.c * \brief mathematic functions. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <lapacke.h> #include <cblas.h> #include "mathfun.h" #define EPS (DBL_MIN) /*! * This function calculates matrix multiply C(nxn) = A(nxn) * B(nxn). */ void multiply_mat(double * a, double *b, double *c, int n) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0f , a, n, b, n, 0.0f, c, n); } /*! * This function calculates matrix multiply C(nxn) = A^T(nxn) * B(nxn). */ void multiply_mat_transposeA(double * a, double *b, double *c, int n) { cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, n, 1.0f , a, n, b, n, 0.0f, c, n); } /*! * This function calculates matrix multiply C(nxn) = A(nxn) * B^T(nxn). */ void multiply_mat_transposeB(double * a, double *b, double *c, int n) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0f , a, n, b, n, 0.0f, c, n); } /*! * This function calculates matrix multiply Y(n) = A^T(nxn) * X(n). */ void multiply_matvec_transposeA(double *a, double *x, int n, double *y) { cblas_dgemv(CblasRowMajor, CblasTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1); } /*! * This function calculates matrix multiply Y(n) = A(nxn) * X(n). */ void multiply_matvec(double *a, double *x, int n, double *y) { cblas_dgemv(CblasRowMajor, CblasNoTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1); } /*! * This function calculates Y(m) = A(m, n) * X(n). */ void multiply_matvec_MN(double * a, int m, int n, double *x, double *y) { cblas_dgemv(CblasRowMajor, CblasNoTrans, m, n, 1.0f, a, n, x, 1, 0.0f, y, 1); } /* C(m*n) = A(m*k) * B(k*n) */ void multiply_mat_MN(double * a, double *b, double *c, int m, int n, int k) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f , a, k, b, n, 0.0f, c, n); } /* C(m*n) = A^T(m*k) * B(k*n) */ void multiply_mat_MN_transposeA(double * a, double *b, double *c, int m, int n, int k) { cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, k, 1.0f , a, m, b, n, 0.0f, c, n); } /* C(m*n) = A(m*k) * B^T(k*n) */ void multiply_mat_MN_transposeB(double * a, double *b, double *c, int m, int n, int k) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0f , a, k, b, k, 0.0f, c, n); } /* A(mxm)^-1 * B(mxn), store the output in B * note that A will be changed on exit. */ int multiply_mat_MN_inverseA(double * a, double *b, int m, int n) { int * ipiv, info; ipiv=malloc(m*sizeof(int)); info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, m, a, m, ipiv); if(info!=0) { printf("multiply_mat_MN_inverseA 1.\n this usually caused by improper nc.\n increase the low limit of nc"); exit(0); return info; } info = LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', m, n, a, m, ipiv, b, n); if(info!=0) { printf("multiply_mat_MN_inverseA 2\n this usually caused by improper nc.\n increase the low limit of nc"); exit(0); return info; } free(ipiv); return info; } /*! * This functions calculate A^-1(nxn). * A is a generic matrix. */ void inverse_mat(double * a, int n, int *info) { int * ipiv; ipiv=malloc(n*sizeof(int)); // dgetrf_(&n, &n, a, &n, ipiv, info); // dgetri_(&n, a, &n, ipiv, work, &lwork, info); LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv); LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, a, n, ipiv); free(ipiv); return; } /*! * This functions calculate A^-1(nxn). * A is a symmetric matrix. */ void inverse_symat(double * a, int n, int *info) { int * ipiv, i, j; ipiv=malloc(n*sizeof(int)); LAPACKE_dsytrf(LAPACK_ROW_MAJOR, 'U', n, a, n, ipiv); LAPACKE_dsytri(LAPACK_ROW_MAJOR, 'U', n, a, n, ipiv); /* fill up the lower triangle */ for(i=0; i<n; i++) for(j=0; j<i; j++) a[i*n+j] = a[j*n+i]; free(ipiv); return; } /*! * This functions calculate A^-1(nxn). * A is a postive-definite symmetrix matrix. */ void inverse_pomat(double * a, int n, int *info) { int i, j; LAPACKE_dpotrf(LAPACK_ROW_MAJOR, 'U', n, a, n); LAPACKE_dpotri(LAPACK_ROW_MAJOR, 'U', n, a, n); /* fill up the lower triangle */ for(i=0; i<n; i++) for(j=0; j<i; j++) a[i*n+j] = a[j*n+i]; return; } /*! * This function calculate eigenvectors and eigenvalues of matrix. */ void eigen_sym_mat(double *a, int n, double *val, int *info) { char jobz='V', uplo='U'; /* store the eigenvectors in a by rows. * store the eigenvalues in val in ascending order. */ // dsyev_(&jobz, &uplo, &n, a, &n, val, work, &lwork, info); /* store the eigenvectors in a by columns. * store the eigenvalues in val in ascending order. */ LAPACKE_dsyev(LAPACK_ROW_MAJOR, jobz, uplo, n, a, n, val); return; } /*! * This function calculate A(nxn) = X^T(1xn)*X(1xn) */ void multiply_vec2mat(double * x, double * a, int n) { // cblas_dsyr(CblasRowMajor, CblasUpper, n, 1.0f, x, 1, a, n); int i, j; for(i=0; i<n; i++) for(j=0; j<=i; j++) { a[i*n+j] = a[j*n+i] = x[i]*x[j]; } } /*! * This function calculates determinant of matrix A. \n * There are two versions in the internet, the main difference lies at dealing with the sign of det. \n * The version II is verifed to be \b INCORRECT. \n * Note that LAPACK is written in Fortran, the indix diffes by 1 with that in C. * LAPACK version 3.5.0 * ******************************** * Version I: * \code{.sh} * det = 1.0; * for(i=0; i<n; i++) * { * det *= a[i*n+i]; * if (ipiv[i] != i+1) * { * det = -det; * } * } * \endcode * ******************************** * Version II: * \code{.sh} * det = 1.0; * for(i=0; i<n; i++) * { * det *= a[i*n+i]; * if (ipiv[i] != i+1) * { * ipiv[ipiv[i]-1] = ipiv[i]; * det = -det; * } * } * \endcode * ******************************** */ double det_mat(double *a, int n, int *info) { int * ipiv; int i; double det; ipiv=malloc(n*sizeof(int)); /* LU decomposition */ // dgetrf_(&n, &n, a, &n, ipiv, info); *info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv); if(*info!=0) { printf("# Error, Wrong in det_mat!\n"); exit(-1); } det = 1.0; for(i=0; i<n; i++) { printf("%d\n", ipiv[i]); det *= a[i*n+i]; if (ipiv[i] != i+1) // note that LAPACK is written in C, the indix diffes by 1 with C. { det = -det; } } //det=fabs(det); free(ipiv); return det; } /*! * This function calculates logarithm determinant of matrix. */ double lndet_mat(double *a, int n, int *info) { int * ipiv; int i; double lndet; ipiv=malloc(n*sizeof(int)); /* LU factorization */ // dgetrf_(&n, &n, a, &n, ipiv, info); *info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv); if(*info!=0) { printf("Wrong!\n"); exit(-1); } lndet = 0.0; for(i=0; i<n; i++) { lndet += log(a[i*n+i]); } free(ipiv); return lndet; } /*! * This function performs Cholesky decomposition of matrix into upper triangle matrixs */ void Chol_decomp_U(double *a, int n, int *info) { int i,j; char uplo = 'U'; // decomposite as A = U^T*U, i.e., upper triangle matrix. // dpotrf_(&uplo, &n, a, &n, info); *info=LAPACKE_dpotrf(LAPACK_ROW_MAJOR, uplo, n, a, n); if(*info<0) { fprintf(stderr, "The %d-th argument had an illegal value!\n", *info); // exit(-1); return; } else if (*info>0) { fprintf(stderr, "The leading minor of order %d is not positive definite, and the factorization could not be completed.\n", *info); // exit(-1); return; } // only the upper triangle is referenced by dpotrf output, // so the strictly lower triangle must be set to zero for(i=0;i<n;i++) for(j=0;j<i;j++) a[i*n+j] = 0.0; return; } /*! * This function performs Cholesky decomposition of matrix into lower triangle matrixs */ void Chol_decomp_L(double *a, int n, int *info) { int i,j; char uplo = 'L'; // decomposite as A = L*L^T, i.e., lower triangle matrix. // dpotrf_(&uplo, &n, a, &n, info); *info=LAPACKE_dpotrf(LAPACK_ROW_MAJOR, uplo, n, a, n); if(*info<0) { fprintf(stderr, "The %d-th argument had an illegal value!\n", *info); // exit(-1); return; } else if (*info>0) { fprintf(stderr, "The leading minor of order %d is not positive definite, and the factorization could not be completed.\n", *info); // exit(-1); return; } // only the lower triangle is referenced by dpotrf output, // so the strictly upper triangle must be set to zero for(i=0;i<n;i++) for(j=i+1;j<n;j++) a[i*n+j] = 0.0; return; } /* * semiseparable matrix */ void compute_semiseparable_drw(double *t, int n, double a1, double c1, double *sigma, double syserr, double *W, double *D, double *phi) { int i; double S, A; phi[0] = 0.0; for(i=1; i<n; i++) { phi[i] = exp(-c1 * (t[i] - t[i-1])); } S = 0.0; A = sigma[0]*sigma[0] + syserr*syserr + a1; D[0] = A; W[0] = 1.0/D[0]; for(i=1; i<n; i++) { S = phi[i]*phi[i] * (S + D[i-1]*W[i-1]*W[i-1]); A = sigma[i]*sigma[i] + syserr*syserr + a1; D[i] = A - a1 * a1 * S; W[i] = 1.0/D[i] * (1.0 - a1*S); } } /* * z = C^-1 x y * * y is a vector */ void multiply_matvec_semiseparable_drw(double *y, double *W, double *D, double *phi, int n, double a1, double *z) { int i; double f, g; // forward substitution f = 0.0; z[0] = y[0]; for(i=1; i<n;i++) { f = phi[i] * (f + W[i-1] * z[i-1]); z[i] = y[i] - a1*f; } //backward substitution g = 0.0; z[n-1] = z[n-1]/D[n-1]; for(i=n-2; i>=0; i--) { g = phi[i+1] *(g + a1*z[i+1]); z[i] = z[i]/D[i] - W[i]*g; } } /* * Z = C^-1 x Y * * Y is an (nxm) matrix. * Note that Y is row-major */ void multiply_mat_semiseparable_drw(double *Y, double *W, double *D, double *phi, int n, int m, double a1, double *Z) { int i, j; double f, g; // forward substitution for(j=0; j<m; j++) { f = 0.0; Z[0*m+j] = Y[0*m+j]; for(i=1; i<n;i++) { f = phi[i] * (f + W[i-1] * Z[(i-1)*m + j]); Z[i*m+j] = Y[i*m+j] - a1*f; } } //backward substitution for(j=0; j<m; j++) { g = 0.0; Z[(n-1)*m+j] = Z[(n-1)*m+j]/D[n-1]; for(i=n-2; i>=0; i--) { g = phi[i+1] *(g + a1*Z[(i+1)*m+j]); Z[i*m+j] = Z[i*m+j]/D[i] - W[i]*g; } } } /* * Z = C^-1 x Y^T * * Y is an (mxn) matrix. * Note that Y is row-major */ void multiply_mat_transposeB_semiseparable_drw(double *Y, double *W, double *D, double *phi, int n, int m, double a1, double *Z) { int i, j; double f, g; // forward substitution for(j=0; j<m; j++) { f = 0.0; Z[0*m+j] = Y[0+j*n]; for(i=1; i<n;i++) { f = phi[i] * (f + W[i-1] * Z[(i-1)*m + j]); Z[i*m+j] = Y[i+j*n] - a1*f; } } //backward substitution for(j=0; j<m; j++) { g = 0.0; Z[(n-1)*m+j] = Z[(n-1)*m+j]/D[n-1]; for(i=n-2; i>=0; i--) { g = phi[i+1] *(g + a1*Z[(i+1)*m+j]); Z[i*m+j] = Z[i*m+j]/D[i] - W[i]*g; } } } /** * calculate A^-1. * * A = LxDxL^T, L = I + tril(UxW^T), D is a diagonal matrix. * * M = LxD^1/2, A = MxM^T, A^-1 = (M^T)^-1xM^-1. */ void inverse_semiseparable(double *t, int n, double a1, double c1, double *sigma, double syserr, double *W, double *D, double *phi, double *A, double *lndet) { int i, j; compute_semiseparable_drw(t, n, a1, c1, sigma, syserr, W, D, phi); *lndet = 0.0; for(i=0; i<n; i++) { A[i*n + i] = 1.0 * sqrt(D[i]); for(j=0; j<i; j++) { A[i*n + j] = a1 * (exp(-c1*(t[i]-t[j]))*W[j]) * sqrt(D[j]); } *lndet += log(D[i]); } LAPACKE_dtrtri(LAPACK_ROW_MAJOR, 'L', 'N', n, A, n); LAPACKE_dlauum(LAPACK_ROW_MAJOR, 'L', n, A, n); /* fill up upper triangle */ for(i=0; i<n; i++) for(j=i+1; j<n; j++) A[i*n+j] = A[j*n+i]; return; } /** * caclulate inverse of a DRW semiseparable matrix, which * is a tridiagonal matrix. */ void inverse_semiseparable_uv(double *t, int n, double a1, double c1, double *A) { int i, j; double b1, b2, dt; dt = t[1] - t[0]; b1 = 1.0/( a1 * (exp(-c1*dt) - exp(c1*dt)) ); A[0] = - b1 * exp(c1*dt); A[1] = A[1*n+0] = b1; for(i=2; i<n; i++) A[i] = 0.0; for(i=1; i<n-1; i++) { for(j=0; j<i-1; j++) A[i*n+j] = A[j*n+i] = 0.0; for(j=i+1; j<n; j++) A[i*n+j] = A[j*n+i] = 0.0; dt = t[i+1] - t[i]; b2 = 1.0/( a1 * (exp(-c1*dt) - exp(c1*dt)) ); dt = t[i+1] - t[i-1]; A[i*n+i] = -b1 * b2 * a1 * (exp(-c1*dt) - exp(c1*dt)); A[i*n+(i+1)] = A[(i+1)*n + i] = b2; b1 = b2; } i = n-1; dt = t[i] - t[i-1]; A[i*n+i] = - b1 * exp(c1 * dt); for(j=0; j<n-2; j++) A[i*n+j] = 0.0; return; } /** * calculate Q = [S^-1+N^-1]^-1, where S is a DRW symmetric semiseparable matrix * and N is a diagonal matrix. * * S^-1 + N^-1 is a tridiagonal symmetric matrix. * * [S^-1 + N^-1]^-1 is a semiseparable symmetric matrix. * */ void compute_inverse_semiseparable_plus_diag(double *t, int n, double a1, double c1, double *sigma, double syserr, double *u, double *v, double *W, double *D, double *phi, double *work) { int i; double *a, *b, f1, f2; a = work; b = work + n; phi[0] = 0.0; for(i=1; i<n; i++) { phi[i] = exp(-c1 * (t[i] - t[i-1])); } /* first S^-1 + N^-1 */ f1 = (phi[1]*phi[1] - 1.0) + EPS; b[0] = phi[1]/( a1 * f1); a[0] = - 1.0/( a1 * f1) + 1.0/(sigma[0]*sigma[0] + syserr*syserr); for(i=1; i<n-1; i++) { f2 = (phi[i+1]*phi[i+1] -1.0) + EPS; b[i] = phi[i+1]/( a1 * f2); a[i] = -1.0/a1 * (1.0 + 1.0/f1 + 1.0/f2) + 1.0/(sigma[i]*sigma[i] + syserr*syserr); f1 = f2; } i = n-1; a[i] = - 1.0 / (a1 * f1) + 1.0/(sigma[i]*sigma[i] + syserr*syserr);; /* now inverse [S^-1+N^-1]^-1*/ v[0] = 1.0 ; v[1] = -a[0]/b[0] * phi[1]; for(i=2; i<n; i++) { v[i] = -(a[i-1]*v[i-1] * phi[i] + b[i-2]*v[i-2] * phi[i]*phi[i-1] )/b[i-1]; } u[n-1] = 1.0/(b[n-2]*v[n-2] * phi[n-1] + a[n-1]*v[n-1]); for(i=n-2; i>0; i--) { u[i] = (1.0 - b[i]*v[i]*u[i+1] * phi[i+1] )/(a[i]*v[i]+b[i-1]*v[i-1]*phi[i]); } u[0] = (1.0-b[0]*v[0]*u[1] * phi[1] )/(a[0]*v[0]); /* calculate W, D */ D[0] = u[0]*v[0]; W[0] = 1.0/D[0]; for(i=1; i<n; i++) { /*S = phi[i]*phi[i]*(S + D[i-1]*W[i-1]*W[i-1]); A = u[i]*v[i]; D[i] = A - u[i]*u[i] * S; W[i] = 1.0/D[i] * (v[i] - u[i]*S);*/ D[i] = -u[i]/u[i-1]/b[i-1] * phi[i]; W[i] = 1.0/u[i]; //printf("%e %e %e %e %e %e\n", u[i], v[i], D[i], W[i], a[i], b[i]); } return; } /* * z = C^1/2 x y * * C is a semiseparable matrix with (u,v) representation, y is a vector * * C = LxDxL^T, L=I + tril(UxW^T) * C^1/2 = LxD^1/2 */ void multiply_matvec_semiseparable_uv(double *y, double *u, double *W, double *D, double *phi, int n, double *z) { int i; double f; f = 0.0; z[0] = sqrt(D[0]) * y[0]; for(i=1; i<n; i++) { f = phi[i] * (f + W[i-1] * sqrt(D[i-1]) * y[i-1]); z[i] = sqrt(D[i]) * y[i] + u[i] * f; } return; } /*! * This function display matrix on the screen. */ void display_mat(double *a, int m, int n) { int i, j; for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("%e\t", a[i*n+j]); } printf("\n"); } } /*! * This function allocates memory for matrix. */ double ** matrix_malloc(int n1, int n2) { double ** mat; int i; if(!(mat = malloc(n1*sizeof(double*)))) { fprintf(stderr, "Unable to allocate the matrix!\n"); exit(-1); } for(i=0; i<n1; i++) { if(!(mat[i] = malloc(n2*sizeof(double)))) { fprintf(stderr, "Unable to allocate the matrix!\n"); exit(-1); } } return mat; } /*! * This function allocates memory for array. */ double * array_malloc(int n) { double *array; if(!(array = malloc(n*sizeof(double)))) { fprintf(stderr, "Unable to allocate the matrix!\n"); exit(-1); } return array; } /*! * This function is to test the functions defined in mathfun.c. */ void test_mathfun() { double *A, det; int n = 3, info; A = malloc(n*n*sizeof(double)); A[0*n+0] = 1.0; A[0*n+1] = 10.3; A[0*n+2] = 6.3; A[1*n+0] = -8.3; A[1*n+1] = -8.0; A[1*n+2] = 5.3; A[2*n+0] = 0.3; A[2*n+1] = -9.3; A[2*n+2] = -3.0; det = det_mat(A, n, &info); printf("%f\n", det); } /* used for qsort sorting, ascending order */ int compare(const void* a, const void* b) { if (*(double *)a > *(double *)b) return 1; else if (*(double *)a < *(double *)b) return -1; return 0; }
{ "alphanum_fraction": 0.5244817199, "avg_line_length": 22.2776315789, "ext": "c", "hexsha": "4c5941e10e9d5849f5c5d41c7bba68056b1dc26e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z", "max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/pyCALI", "max_forks_repo_path": "src/pycali/pycali/mathfun.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/pyCALI", "max_issues_repo_path": "src/pycali/pycali/mathfun.c", "max_line_length": 135, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/PyCALI", "max_stars_repo_path": "src/pycali/pycali/mathfun.c", "max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z", "num_tokens": 6660, "size": 16931 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <Eigen/Geometry> #include <gsl/gsl> namespace mage { inline void ToEuler(const Eigen::Quaternionf& quat, float& xRad, float& yRad, float& zRad) { Eigen::Matrix3f eigenMat = quat.toRotationMatrix(); Eigen::Vector3f eulerAngles = eigenMat.eulerAngles(0, 1, 2); xRad = eulerAngles.x(); yRad = eulerAngles.y(); zRad = eulerAngles.z(); } inline Eigen::Quaternionf FromEuler(float xRad, float yRad, float zRad) { return Eigen::AngleAxisf(xRad, Eigen::Vector3f::UnitX()) * Eigen::AngleAxisf(yRad, Eigen::Vector3f::UnitY()) * Eigen::AngleAxisf(zRad, Eigen::Vector3f::UnitZ()); } template<int N> inline Eigen::Map<const Eigen::Matrix<float, N, 1>> ToCMap(gsl::span<const float, N> values) { return Eigen::Map<const Eigen::Matrix<float, N, 1>>{ values.data() }; } template<int N> inline Eigen::Map<Eigen::Matrix<float, N, 1>> ToMap(gsl::span<float, N> values) { return Eigen::Map<const Eigen::Matrix<float, N, 1>>{ values.data() }; } template<typename T> inline typename T::ConstMapType ToCMap(const T& element) { return T::ConstMapType{ element.data() }; } template<typename T> inline typename T::MapType ToMap(T& element) { return T::MapType{ element.data() }; } }
{ "alphanum_fraction": 0.6199312715, "avg_line_length": 27.9807692308, "ext": "h", "hexsha": "2e3488fa2d1b01077bcdb8a280d0f8418bb43cb6", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Utils/eigen.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Utils/eigen.h", "max_line_length": 96, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Utils/eigen.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": 398, "size": 1455 }
//This takes the output of STFT, X, and a transform matrix, T, //and outputs a T*X or X*T', depending on orientation of X. //X is either WxF or FxW. //T must be BxF, as from get_spectrogram_T_mat. //Y is either WxB or BxW. #include <stdio.h> #include <math.h> #include <cblas.h> //#include <time.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int apply_spectrogram_T_mat_s (float *Y, const float *X, const float *T, const size_t W, const size_t F, const size_t B); int apply_spectrogram_T_mat_d (double *Y, const double *X, const double *T, const size_t W, const size_t F, const size_t B); int apply_spectrogram_T_mat_s (float *Y, const float *X, const float *T, const size_t W, const size_t F, const size_t B) { if (B<1u) { fprintf(stderr,"error in apply_spectrogram_T_mat_s: B (num output freq bands) must be positive\n"); return 1; } if (F<1u) { fprintf(stderr,"error in apply_spectrogram_T_mat_s: F (num STFT freqs) must be positive\n"); return 1; } if (B*W<1200000u) { //struct timespec tic, toc; clock_gettime(CLOCK_REALTIME,&tic); for (size_t w=W; w>0u; --w, X+=F, T-=B*F) { for (size_t b=B; b>0u; --b, X-=F, ++Y) { float sm = 0.0f; //size_t f = 0u; //while (f<F && *T==0.0f) { ++f; } //X += f; T += f; //while (f<F) { sm += *X * *T; ++X; ++T; ++f; } for (size_t f=F; f>0u; --f, ++X, ++T) { sm += *X * *T; } *Y = sm; } } //clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,"fmaf: elapsed time = %.6f ms\n",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6); } else { //struct timespec tic, toc; clock_gettime(CLOCK_REALTIME,&tic); cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,(int)W,(int)B,(int)F,1.0f,X,(int)F,T,(int)F,0.0f,Y,(int)B); //clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,"sgemm: elapsed time = %.6f ms\n",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6); } return 0; } int apply_spectrogram_T_mat_d (double *Y, const double *X, const double *T, const size_t W, const size_t F, const size_t B) { if (B<1u) { fprintf(stderr,"error in apply_spectrogram_T_mat_d: B (num output freq bands) must be positive\n"); return 1; } if (F<1u) { fprintf(stderr,"error in apply_spectrogram_T_mat_d: F (num STFT freqs) must be positive\n"); return 1; } if (B*W<12000u) { for (size_t w=W; w>0u; --w, X+=F, T-=B*F) { for (size_t b=B; b>0u; --b, X-=F, ++Y) { double sm = 0.0; //size_t f = F; //while (*T==0.0f && f>0u) { ++X; ++T; --f; } //while (*T!=0.0f && f>0u) { sm += *X**T; ++X; ++T; --f; } //X -= f; T -= f; //for (size_t f=F; f>0u; --f, ++X, ++T) { sm = fma(*X,*T,sm); } for (size_t f=F; f>0u; --f, ++X, ++T) { sm += *X * *T; } *Y = sm; } } } else { cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasTrans,(int)W,(int)B,(int)F,1.0,X,(int)F,T,(int)F,0.0,Y,(int)B); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.5403669725, "avg_line_length": 35.9340659341, "ext": "c", "hexsha": "cd4141f15620bc3474c9ddf8bcb30d59b6e7428e", "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/apply_spectrogram_T_mat.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/apply_spectrogram_T_mat.c", "max_line_length": 154, "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/apply_spectrogram_T_mat.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1121, "size": 3270 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include "sphere.h" #include <petsc.h> #undef __FUNCT__ #define __FUNCT__ "CartesianToSpherical" PetscErrorCode CartesianToSpherical(Vec xyz, Vec sph) { PetscErrorCode ierr; PetscScalar *xyzPt, *sphPt; PetscInt size; PetscReal x, y, z, r, theta, phi; PetscFunctionBegin; //get size of xyz vec ierr = VecGetSize(xyz, &size);CHKERRQ(ierr); ierr = VecGetArrayRead(xyz, &xyzPt);CHKERRQ(ierr); ierr = VecGetArray(sph, &sphPt);CHKERRQ(ierr); for(PetscInt k=0; k<size/3; ++k) { //get xyz points x = xyzPt[3*k+0]; y = xyzPt[3*k+1]; z = xyzPt[3*k+2]; //compute transformation r = sqrt(x*x + y*y + z*z); theta = acos(z/r); phi = atan2(y,x); //set values in sph vec sphPt[3*k+0] = r; sphPt[3*k+1] = 0; sphPt[3*k+2] = phi; if(r>0) sphPt[3*k+1] = theta; } ierr = VecRestoreArray(sph, &sphPt);CHKERRQ(ierr); ierr = VecRestoreArrayRead(xyz, &xyzPt);CHKERRQ(ierr); PetscFunctionReturn(0); } void cartesianToSpherical(SPoint *point) { double r, theta, phi; r = sqrt((point->x1)*(point->x1) + (point->x2)*(point->x2) + (point->x3)*(point->x3)); theta = acos(point->x3/r); phi = atan2((point->x2),(point->x1)); point->x1 = r; point->x2 = 0; point->x3 = phi; if(r > 0) point->x2 = theta; point->type = 's'; } void sphericalToCartesian(SPoint *point) { double r = point->x1; double theta = point->x2; double phi = point->x3; double x = r*sin(theta)*cos(phi); double y = r*sin(theta)*sin(phi); double z = r*cos(theta); point->x1 = x; point->x2 = y; point->x3 = z; }
{ "alphanum_fraction": 0.6108735492, "avg_line_length": 23.3857142857, "ext": "c", "hexsha": "479dbfaaf5234ce91d0eeaa974e85e2b57e44888", "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": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_path": "src/sphere/sphere.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "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": "tom-klotz/ellipsoid-solvation", "max_issues_repo_path": "src/sphere/sphere.c", "max_line_length": 90, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_path": "src/sphere/sphere.c", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "num_tokens": 581, "size": 1637 }
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef VRNA_WITH_GSL #include <gsl/gsl_multimin.h> #endif #include "ViennaRNA/eval.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/constraints/hard.h" #include "ViennaRNA/constraints/soft.h" #include "ViennaRNA/fold.h" #include "ViennaRNA/part_func.h" #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/perturbation_fold.h" static void calculate_probability_unpaired(vrna_fold_compound_t *vc, double *probability) { int length = vc->length; FLT_OR_DBL *probs = vc->exp_matrices->probs; int *iidx = vc->iindx; int i, j; for (i = 0; i <= length; ++i) probability[i] = 1; for (i = 1; i <= length; ++i) for (j = i + 1; j <= length; ++j) { probability[i] -= probs[iidx[i] - j]; probability[j] -= probs[iidx[i] - j]; } } #if 0 static double calculate_norm(double *vector, int length) { double sum = 0; int i; for (i = 1; i <= length; ++i) sum += vector[i] * vector[i]; return sqrt(sum); } #endif static void addSoftConstraint(vrna_fold_compound_t *vc, const double *epsilon, int length) { /* remove previous soft constraints */ vrna_sc_init(vc); /* prepare vector of unpaired constraints in kcal/mol */ FLT_OR_DBL *constraints = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL) * (length + 1)); memcpy(constraints + 1, epsilon + 1, sizeof(FLT_OR_DBL) * length); /* add new soft constraints */ vrna_sc_set_up(vc, (const FLT_OR_DBL *)constraints, VRNA_OPTION_DEFAULT); free(constraints); } static double evaluate_objective_function_contribution(double value, int objective_function) { if (objective_function == VRNA_OBJECTIVE_FUNCTION_QUADRATIC) return value * value; if (objective_function == VRNA_OBJECTIVE_FUNCTION_ABSOLUTE) return fabs(value); assert(0); return 0; } static double evaluate_perturbation_vector_score(vrna_fold_compound_t *vc, const double *epsilon, const double *q_prob_unpaired, double sigma_squared, double tau_squared, int objective_function) { double ret = 0; double ret2 = 0.; double *p_prob_unpaired; int i; int length = vc->length; /* calculate pairing probabilty in the pertubated energy model */ p_prob_unpaired = vrna_alloc(sizeof(double) * (length + 1)); addSoftConstraint(vc, epsilon, length); vc->params->model_details.compute_bpp = 1; vc->exp_params->model_details.compute_bpp = 1; /* get new (constrained) MFE to scale pf computations properly */ double mfe = (double)vrna_mfe(vc, NULL); vrna_exp_params_rescale(vc, &mfe); vrna_pf(vc, NULL); calculate_probability_unpaired(vc, p_prob_unpaired); vrna_sc_remove(vc); for (i = 1; i <= length; ++i) { /* add penalty for pertubation energies */ ret += evaluate_objective_function_contribution(epsilon[i], objective_function) / tau_squared; /* add penalty for mismatches between observed and predicted probabilities */ if (q_prob_unpaired[i] >= 0) /* ignore positions with missing data */ ret2 += evaluate_objective_function_contribution(p_prob_unpaired[i] - q_prob_unpaired[i], objective_function) / sigma_squared; } vrna_message_info(stderr, "Score: pertubation: %g\tdiscrepancy: %g", ret, ret2); free(p_prob_unpaired); return ret + ret2; } static void pairing_probabilities_from_restricted_pf(vrna_fold_compound_t *vc, const double *epsilon, double *prob_unpaired, double **conditional_prob_unpaired) { int length = vc->length; int i; addSoftConstraint(vc, epsilon, length); vc->params->model_details.compute_bpp = 1; vc->exp_params->model_details.compute_bpp = 1; /* get new (constrained) MFE to scale pf computations properly */ double mfe = (double)vrna_mfe(vc, NULL); vrna_exp_params_rescale(vc, &mfe); vrna_pf(vc, NULL); calculate_probability_unpaired(vc, prob_unpaired); #ifdef _OPENMP #pragma omp parallel for private(i) #endif for (i = 1; i <= length; ++i) { vrna_fold_compound_t *restricted_vc; char *hc_string; unsigned int constraint_options = VRNA_CONSTRAINT_DB | VRNA_CONSTRAINT_DB_PIPE | VRNA_CONSTRAINT_DB_DOT | VRNA_CONSTRAINT_DB_X | VRNA_CONSTRAINT_DB_ANG_BRACK | VRNA_CONSTRAINT_DB_RND_BRACK; hc_string = vrna_alloc(sizeof(char) * (length + 1)); memset(hc_string, '.', length); hc_string[i - 1] = 'x'; restricted_vc = vrna_fold_compound(vc->sequence, &(vc->exp_params->model_details), VRNA_OPTION_DEFAULT); vrna_constraints_add(restricted_vc, hc_string, constraint_options); free(hc_string); vrna_exp_params_subst(restricted_vc, vc->exp_params); vrna_pf(restricted_vc, NULL); calculate_probability_unpaired(restricted_vc, conditional_prob_unpaired[i]); restricted_vc->sc = NULL; vrna_fold_compound_free(restricted_vc); } vrna_sc_remove(vc); } static void pairing_probabilities_from_sampling(vrna_fold_compound_t *vc, const double *epsilon, int sample_size, double *prob_unpaired, double **conditional_prob_unpaired, unsigned int options) { char **samples, **ptr; int length, i, j; double mfe; length = vc->length; addSoftConstraint(vc, epsilon, length); vc->params->model_details.compute_bpp = 0; vc->exp_params->model_details.compute_bpp = 0; /* get new (constrained) MFE to scale pf computations properly */ mfe = (double)vrna_mfe(vc, NULL); vrna_exp_params_rescale(vc, &mfe); vrna_pf(vc, NULL); samples = vrna_pbacktrack_num(vc, (unsigned int)sample_size, options); for (ptr = samples; (*ptr); ptr++) { for (i = length; i > 0; i--) { if ((*ptr)[i - 1] == '.') { ++prob_unpaired[i]; for (j = length; j > 0; j--) if ((*ptr)[j - 1] == '.') ++conditional_prob_unpaired[i][j]; } } free(*ptr); } free(samples); for (i = 1; i <= length; ++i) { if (prob_unpaired[i]) for (j = 1; j <= length; ++j) conditional_prob_unpaired[i][j] /= prob_unpaired[i]; prob_unpaired[i] /= sample_size; assert(prob_unpaired[i] >= 0 && prob_unpaired[i] <= 1); } vrna_sc_remove(vc); } static void allocateProbabilityArrays(double **unpaired, double ***conditional_unpaired, int length) { int i; *unpaired = vrna_alloc(sizeof(double) * (length + 1)); *conditional_unpaired = vrna_alloc(sizeof(double *) * (length + 1)); for (i = 1; i <= length; ++i) (*conditional_unpaired)[i] = vrna_alloc(sizeof(double) * (length + 1)); } static void freeProbabilityArrays(double *unpaired, double **conditional_unpaired, int length) { int i; free(unpaired); for (i = 1; i <= length; ++i) free(conditional_unpaired[i]); free(conditional_unpaired); } static void evaluate_perturbation_vector_gradient(vrna_fold_compound_t *vc, const double *epsilon, const double *q_prob_unpaired, double sigma_squared, double tau_squared, int objective_function, int sample_size, double *gradient) { double *p_prob_unpaired; double **p_conditional_prob_unpaired; int i, mu; int length = vc->length; double kT = vc->exp_params->kT / 1000; allocateProbabilityArrays(&p_prob_unpaired, &p_conditional_prob_unpaired, length); if (sample_size > 0) { pairing_probabilities_from_sampling(vc, epsilon, sample_size, p_prob_unpaired, p_conditional_prob_unpaired, VRNA_PBACKTRACK_DEFAULT); } else if (sample_size < 0) { pairing_probabilities_from_sampling(vc, epsilon, -sample_size, p_prob_unpaired, p_conditional_prob_unpaired, VRNA_PBACKTRACK_NON_REDUNDANT); } else { pairing_probabilities_from_restricted_pf(vc, epsilon, p_prob_unpaired, p_conditional_prob_unpaired); } for (mu = 1; mu <= length; ++mu) { double sum = 0; if (objective_function == VRNA_OBJECTIVE_FUNCTION_QUADRATIC) { for (i = 1; i <= length; ++i) { if (q_prob_unpaired[i] < 0) /* ignore positions with missing data */ continue; sum += (p_prob_unpaired[i] - q_prob_unpaired[i]) * p_prob_unpaired[i] * (p_prob_unpaired[mu] - p_conditional_prob_unpaired[i][mu]) / sigma_squared; } gradient[mu] = 2 * (epsilon[mu] / tau_squared + sum / kT); } else if (objective_function == VRNA_OBJECTIVE_FUNCTION_ABSOLUTE) { for (i = 1; i <= length; ++i) if (q_prob_unpaired[i] >= 0 && p_prob_unpaired[i] != q_prob_unpaired[i]) { sum += (p_prob_unpaired[i] * (p_prob_unpaired[mu] - p_conditional_prob_unpaired[i][mu])) / kT / sigma_squared * (p_prob_unpaired[i] > q_prob_unpaired[i] ? 1. : -1.); } if (epsilon[mu]) sum += (epsilon[mu] > 0 ? 1. : -1.) / tau_squared; gradient[mu] = sum; } } freeProbabilityArrays(p_prob_unpaired, p_conditional_prob_unpaired, length); } #ifdef VRNA_WITH_GSL typedef struct parameters_gsl { vrna_fold_compound_t *vc; const double *q_prob_unpaired; double sigma_squared; double tau_squared; int objective_function; int sample_size; } parameters_gsl; static double f_gsl(const gsl_vector *x, void *params) { parameters_gsl *p = params; return evaluate_perturbation_vector_score(p->vc, x->data, p->q_prob_unpaired, p->sigma_squared, p->tau_squared, p->objective_function); } static void df_gsl(const gsl_vector *x, void *params, gsl_vector *df) { parameters_gsl *p = params; gsl_vector_set(df, 0, 0); evaluate_perturbation_vector_gradient(p->vc, x->data, p->q_prob_unpaired, p->sigma_squared, p->tau_squared, p->objective_function, p->sample_size, df->data); } static void fdf_gsl(const gsl_vector *x, void *params, double *f, gsl_vector *g) { *f = f_gsl(x, params); df_gsl(x, params, g); } #endif /* VRNA_WITH_GSL */ PUBLIC void vrna_sc_minimize_pertubation(vrna_fold_compound_t *vc, const double *q_prob_unpaired, int objective_function, double sigma_squared, double tau_squared, int algorithm, int sample_size, double *epsilon, double initialStepSize, double minStepSize, double minImprovement, double minimizerTolerance, progress_callback callback) { int iteration_count = 0; const int max_iterations = 100; int length = vc->length; #ifdef VRNA_WITH_GSL const gsl_multimin_fdfminimizer_type *minimizer_type = 0; struct { int type; const gsl_multimin_fdfminimizer_type *gsl_type; } algorithms[] = { { VRNA_MINIMIZER_CONJUGATE_FR, gsl_multimin_fdfminimizer_conjugate_fr }, { VRNA_MINIMIZER_CONJUGATE_PR, gsl_multimin_fdfminimizer_conjugate_pr }, { VRNA_MINIMIZER_VECTOR_BFGS, gsl_multimin_fdfminimizer_vector_bfgs }, { VRNA_MINIMIZER_VECTOR_BFGS2, gsl_multimin_fdfminimizer_vector_bfgs2 }, { VRNA_MINIMIZER_STEEPEST_DESCENT, gsl_multimin_fdfminimizer_steepest_descent }, { 0, NULL } }; int i; for (i = 0; algorithms[i].type; ++i) if (algorithms[i].type == algorithm) { minimizer_type = algorithms[i].gsl_type; break; } if (minimizer_type) { parameters_gsl parameters; gsl_multimin_function_fdf fdf; gsl_multimin_fdfminimizer *minimizer; gsl_vector *vector; int status; parameters.vc = vc; parameters.q_prob_unpaired = q_prob_unpaired; parameters.sigma_squared = sigma_squared; parameters.tau_squared = tau_squared; parameters.objective_function = objective_function; parameters.sample_size = sample_size; fdf.n = length + 1; fdf.f = &f_gsl; fdf.df = &df_gsl; fdf.fdf = &fdf_gsl; fdf.params = (void *)&parameters; minimizer = gsl_multimin_fdfminimizer_alloc(minimizer_type, length + 1); vector = gsl_vector_calloc(length + 1); /* gsl_multimin_fdfminimizer_set(minimizer, &fdf, vector, 0.01, 1e-4); */ gsl_multimin_fdfminimizer_set(minimizer, &fdf, vector, initialStepSize, minimizerTolerance); if (callback) callback(0, minimizer->f, minimizer->x->data); do { ++iteration_count; status = gsl_multimin_fdfminimizer_iterate(minimizer); if (callback) callback(iteration_count, minimizer->f, minimizer->x->data); if (status) break; status = gsl_multimin_test_gradient(minimizer->gradient, minimizerTolerance); } while (status == GSL_CONTINUE && iteration_count < max_iterations); memcpy(epsilon, minimizer->x->data, sizeof(double) * (length + 1)); gsl_multimin_fdfminimizer_free(minimizer); gsl_vector_free(vector); return; } #endif /* VRNA_WITH_GSL */ double improvement; const double min_improvement = minImprovement; double *new_epsilon = vrna_alloc(sizeof(double) * (length + 1)); double *gradient = vrna_alloc(sizeof(double) * (length + 1)); double score = evaluate_perturbation_vector_score(vc, epsilon, q_prob_unpaired, sigma_squared, tau_squared, objective_function); if (callback) callback(0, score, epsilon); do { double new_score; double step_size; ++iteration_count; evaluate_perturbation_vector_gradient(vc, epsilon, q_prob_unpaired, sigma_squared, tau_squared, objective_function, sample_size, gradient); /* step_size = 0.5 / calculate_norm(gradient, length);*/ step_size = initialStepSize; do { int i; for (i = 1; i <= length; ++i) new_epsilon[i] = epsilon[i] - step_size * gradient[i]; new_score = evaluate_perturbation_vector_score(vc, new_epsilon, q_prob_unpaired, sigma_squared, tau_squared, objective_function); improvement = 1 - new_score / score; step_size /= 2; } while ((improvement < min_improvement) && (step_size >= minStepSize)); if (new_score > score) break; if (callback) callback(iteration_count, new_score, new_epsilon); score = new_score; memcpy(epsilon, new_epsilon, sizeof(double) * (length + 1)); } while (improvement >= min_improvement && iteration_count < max_iterations); free(gradient); free(new_epsilon); }
{ "alphanum_fraction": 0.5231000914, "avg_line_length": 31.8919382504, "ext": "c", "hexsha": "2c612f0415ec2b8c9ac95aa740d19c8d43d043d7", "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": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_forks_repo_licenses": [ "Python-2.0" ], "max_forks_repo_name": "tsjzz/ViennaRNA", "max_forks_repo_path": "src/ViennaRNA/perturbation_fold.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Python-2.0" ], "max_issues_repo_name": "tsjzz/ViennaRNA", "max_issues_repo_path": "src/ViennaRNA/perturbation_fold.c", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_stars_repo_licenses": [ "Python-2.0" ], "max_stars_repo_name": "tsjzz/ViennaRNA", "max_stars_repo_path": "src/ViennaRNA/perturbation_fold.c", "max_stars_repo_stars_event_max_datetime": "2021-12-02T06:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-02T06:38:05.000Z", "num_tokens": 4071, "size": 18593 }
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 #ifdef PADDLE_USE_MKLML #include <mkl_cblas.h> #include <mkl_lapacke.h> #include <mkl_vml_functions.h> #endif #ifdef PADDLE_USE_MKL #include <mkl.h> #include <mkl_lapacke.h> #endif #ifdef PADDLE_USE_ATLAS extern "C" { #include <cblas.h> #include <clapack.h> } #endif #ifdef PADDLE_USE_OPENBLAS #include <cblas.h> #include <lapacke.h> #endif #ifndef LAPACK_FOUND extern "C" { #include <cblas.h> int LAPACKE_sgetrf(int matrix_layout, int m, int n, float* a, int lda, int* ipiv); int LAPACKE_dgetrf(int matrix_layout, int m, int n, double* a, int lda, int* ipiv); int LAPACKE_sgetri(int matrix_layout, int n, float* a, int lda, const int* ipiv); int LAPACKE_dgetri(int matrix_layout, int n, double* a, int lda, const int* ipiv); } #endif #include <cmath> #include "paddle/framework/tensor.h" #include "paddle/platform/device_context.h" #include "paddle/platform/enforce.h" namespace paddle { namespace operators { namespace math { // Support continuous memory now // If transA = N, and transB = N // Then matrixA: M * K, matrixB: K * N matrixC : M * N // For more detailed info, please refer to // http://www.netlib.org/lapack/explore-html/d4/de2/sgemm_8f.html template <typename Place, typename T> void gemm(const platform::DeviceContext& context, const CBLAS_TRANSPOSE transA, const CBLAS_TRANSPOSE transB, const int M, const int N, const int K, const T alpha, const T* A, const T* B, const T beta, T* C); // matrix multiply with continuous memory template <typename Place, typename T> void matmul(const platform::DeviceContext& context, const framework::Tensor& matrix_a, bool trans_a, const framework::Tensor& matrix_b, bool trans_b, T alpha, framework::Tensor* matrix_out, T beta); } // namespace math } // namespace operators } // namespace paddle
{ "alphanum_fraction": 0.7134292566, "avg_line_length": 30.1445783133, "ext": "h", "hexsha": "d8518e77fa7b4abdbcf08b7983013c24806e14ca", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-06-04T04:27:15.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-04T04:27:15.000Z", "max_forks_repo_head_hexsha": "5b5f4f514047975ac09ec42b31e46dabf235e7dd", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "AI-books/Paddle", "max_forks_repo_path": "paddle/operators/math/math_function.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5b5f4f514047975ac09ec42b31e46dabf235e7dd", "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": "AI-books/Paddle", "max_issues_repo_path": "paddle/operators/math/math_function.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "5b5f4f514047975ac09ec42b31e46dabf235e7dd", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "AI-books/Paddle", "max_stars_repo_path": "paddle/operators/math/math_function.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 655, "size": 2502 }
#ifndef __INC_OPTSTRUCT__ #define __INC_OPTSTRUCT__ #include <gsl/gsl_matrix.h> /** * @file optstruct.h * \brief defines the optstruct which holds all the mundane options and dimensions etc */ #define POWEREXPCOVFN 1 #define MATERN32 2 #define MATERN52 3 /** * \struct optstruct * \brief holds the main parameters etc needed by all the emulator fns * * this is the most important structure after the modelstruct, this contains * all the dimensions of xmodel, training_vec etc * */ typedef struct optstruct{ /** * the number of parameters in the covariance fn */ int nthetas; /** * the number of parameters in the model to be emulated, this sets the dimensionality * of the estimation space and the "hardness" of the estimation process */ int nparams; /** * the number of locations in the model space that we have training values at * another contributing factor to how complex the problem becomes, the covariance matrix * scales as (nmodel_points**2) and we need to invert this every step of the estimation * process */ int nmodel_points; /** * how many points to evaluate the emulated model at */ int nemulate_points; /** * what order (if any) should the regression model be * 0 -> a single constant value (a0) * 1 -> a constant plus a slope vector (a0 + a1*x) * 2 -> (a0 + a1*x + a2*x^2) * 3 -> (a0 + a1*x + a2*x^2 + a3*x^3) * >3 (not supported) */ int regression_order; /** * indirectly controls the shape of the regression model, be very careful with this one * this is set correctly by calling setup_regression */ int nregression_fns; /** * fixed nugget? * allow the user to try and supply a nugget which will not be optimized over, but fixed */ int fixed_nugget_mode; double fixed_nugget; /** * set which cov fn to use, can be one of * POWEREXPCOVFN * MATERN32 * MATERN52 * * this is determined by setup_cov_fn */ int cov_fn_index; // set this to not zero if you want to use the length scales set by the data int use_data_scales; /** this holds the ranges for the optimisation routine*/ gsl_matrix* grad_ranges; } optstruct; void free_optstruct(optstruct *opts); void copy_optstruct(optstruct *dst, optstruct* src); void dump_optstruct(FILE *fptr, optstruct* opts); void load_optstruct(FILE *fptr, optstruct* opts); void setup_cov_fn(optstruct *opts); void setup_regression(optstruct *opts); #include "modelstruct.h" void setup_optimization_ranges(optstruct* options, modelstruct* the_model); #endif
{ "alphanum_fraction": 0.7130469058, "avg_line_length": 23.9339622642, "ext": "h", "hexsha": "82ffed2366cf437ffe42326d3383a21935a39cc0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MADAI/MADAIEmulator", "max_forks_repo_path": "src/optstruct.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MADAI/MADAIEmulator", "max_issues_repo_path": "src/optstruct.h", "max_line_length": 90, "max_stars_count": 2, "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_path": "src/optstruct.h", "max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z", "num_tokens": 679, "size": 2537 }
#pragma once #include <queue> #include <vector> #include <gsl/gsl> #define EMPTY_NODE '\0' class minqueue_node { public: minqueue_node(char value, unsigned int score); ~minqueue_node(); unsigned int score; char value; minqueue_node* left; minqueue_node* right; }; struct cmp_minqueue_nodes { bool operator()( const gsl::not_null<minqueue_node*> left, const gsl::not_null<minqueue_node*> right); }; class minqueue { std::priority_queue< minqueue_node*, std::vector<minqueue_node*>, cmp_minqueue_nodes> nodes; public: minqueue(); ~minqueue(); void push(gsl::not_null<minqueue_node*> node); minqueue_node* pop(); bool empty(); int size(); };
{ "alphanum_fraction": 0.6589041096, "avg_line_length": 17.8048780488, "ext": "h", "hexsha": "68c6887c45360fe00ad679bd07f0128b94aefa21", "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/minqueue.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/minqueue.h", "max_line_length": 93, "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/minqueue.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 184, "size": 730 }
#include "cosmocalc.h" #include "weaklens.h" cosmocalcData cosmoData; weaklensData wlData; #include <gsl/gsl_errno.h> void turn_off_gsl_errs(void) { gsl_set_error_handler_off(); }
{ "alphanum_fraction": 0.777173913, "avg_line_length": 16.7272727273, "ext": "c", "hexsha": "7f99f567fa302f3319cb8d0f7f8e8b43e22494b2", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_path": "src/global.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_path": "src/global.c", "max_line_length": 30, "max_stars_count": null, "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_path": "src/global.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 58, "size": 184 }
//This is a simple example meant to test your capabilities with basic library linking functionality. All you have to do is return the output to modelica. #include <stdio.h> #include <gsl/gsl_sf_bessel.h> double sf_bessel(double x) { double y = gsl_sf_bessel_J0 (x); return y; } //The main function has been provided solely for the sake of testing the function. It will be removed when the problem set is formally passed on. /* int main(void) { double x = 5; double a = sf_bessel(x); printf("a = %f \n",a); return 0; } */
{ "alphanum_fraction": 0.7158878505, "avg_line_length": 20.5769230769, "ext": "c", "hexsha": "69788a540169bba9b4255e8f57e7d4839eb268f7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RITUait/OpenModelica", "max_forks_repo_path": "TestSample/Resources/Include/p1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "RITUait/OpenModelica", "max_issues_repo_path": "TestSample/Resources/Include/p1.c", "max_line_length": 153, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RITUait/OpenModelica", "max_stars_repo_path": "Resources/Include/p1.c", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:23:39.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-03T04:23:39.000Z", "num_tokens": 137, "size": 535 }
/* bspline/bspline.c * * Copyright (C) 2006, 2007, 2008, 2009 Patrick Alken * Copyright (C) 2008 Rhys Ulerich * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> /* * This module contains routines related to calculating B-splines. * The algorithms used are described in * * [1] Carl de Boor, "A Practical Guide to Splines", Springer * Verlag, 1978. * * The bspline_pppack_* internal routines contain code adapted from * * [2] "PPPACK - Piecewise Polynomial Package", * http://www.netlib.org/pppack/ * */ #include "bspline.h" /* gsl_bspline_alloc() Allocate space for a bspline workspace. The size of the workspace is O(5k + nbreak) Inputs: k - spline order (cubic = 4) nbreak - number of breakpoints Return: pointer to workspace */ gsl_bspline_workspace * gsl_bspline_alloc (const size_t k, const size_t nbreak) { if (k == 0) { GSL_ERROR_NULL ("k must be at least 1", GSL_EINVAL); } else if (nbreak < 2) { GSL_ERROR_NULL ("nbreak must be at least 2", GSL_EINVAL); } else { gsl_bspline_workspace *w; w = (gsl_bspline_workspace *) malloc (sizeof (gsl_bspline_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->k = k; w->km1 = k - 1; w->nbreak = nbreak; w->l = nbreak - 1; w->n = w->l + k - 1; w->knots = gsl_vector_alloc (w->n + k); if (w->knots == 0) { free (w); GSL_ERROR_NULL ("failed to allocate space for knots vector", GSL_ENOMEM); } w->deltal = gsl_vector_alloc (k); if (w->deltal == 0) { gsl_vector_free (w->knots); free (w); GSL_ERROR_NULL ("failed to allocate space for deltal vector", GSL_ENOMEM); } w->deltar = gsl_vector_alloc (k); if (w->deltar == 0) { gsl_vector_free (w->deltal); gsl_vector_free (w->knots); free (w); GSL_ERROR_NULL ("failed to allocate space for deltar vector", GSL_ENOMEM); } w->B = gsl_vector_alloc (k); if (w->B == 0) { gsl_vector_free (w->deltar);; gsl_vector_free (w->deltal); gsl_vector_free (w->knots); free (w); GSL_ERROR_NULL ("failed to allocate space for temporary spline vector", GSL_ENOMEM); } return w; } } /* gsl_bspline_alloc() */ /* gsl_bspline_deriv_alloc() Allocate space for a bspline derivative workspace. The size of the workspace is O(2k^2) Inputs: k - spline order (cubic = 4) Return: pointer to workspace */ gsl_bspline_deriv_workspace * gsl_bspline_deriv_alloc (const size_t k) { if (k == 0) { GSL_ERROR_NULL ("k must be at least 1", GSL_EINVAL); } else { gsl_bspline_deriv_workspace *dw; dw = (gsl_bspline_deriv_workspace *) malloc (sizeof (gsl_bspline_deriv_workspace)); if (dw == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } dw->A = gsl_matrix_alloc (k, k); if (dw->A == 0) { free (dw); GSL_ERROR_NULL ("failed to allocate space for derivative work matrix", GSL_ENOMEM); } dw->dB = gsl_matrix_alloc (k, k + 1); if (dw->dB == 0) { gsl_matrix_free (dw->A); free (dw); GSL_ERROR_NULL ("failed to allocate space for temporary derivative matrix", GSL_ENOMEM); } dw->k = k; return dw; } } /* gsl_bspline_deriv_alloc() */ /* Return number of coefficients */ size_t gsl_bspline_ncoeffs (gsl_bspline_workspace * w) { return w->n; } /* Return order */ size_t gsl_bspline_order (gsl_bspline_workspace * w) { return w->k; } /* Return number of breakpoints */ size_t gsl_bspline_nbreak (gsl_bspline_workspace * w) { return w->nbreak; } /* Return the location of the i-th breakpoint*/ double gsl_bspline_breakpoint (size_t i, gsl_bspline_workspace * w) { size_t j = i + w->k - 1; return gsl_vector_get (w->knots, j); } /* gsl_bspline_free() Free a gsl_bspline_workspace. Inputs: w - workspace to free Return: none */ void gsl_bspline_free (gsl_bspline_workspace * w) { RETURN_IF_NULL (w); gsl_vector_free (w->knots); gsl_vector_free (w->deltal); gsl_vector_free (w->deltar); gsl_vector_free (w->B); free (w); } /* gsl_bspline_free() */ /* gsl_bspline_deriv_free() Free a gsl_bspline_deriv_workspace. Inputs: dw - workspace to free Return: none */ void gsl_bspline_deriv_free (gsl_bspline_deriv_workspace * dw) { RETURN_IF_NULL (dw); gsl_matrix_free (dw->A); gsl_matrix_free (dw->dB); free (dw); } /* gsl_bspline_deriv_free() */ /* gsl_bspline_knots() Compute the knots from the given breakpoints: knots(1:k) = breakpts(1) knots(k+1:k+l-1) = breakpts(i), i = 2 .. l knots(n+1:n+k) = breakpts(l + 1) where l is the number of polynomial pieces (l = nbreak - 1) and n = k + l - 1 (using matlab syntax for the arrays) The repeated knots at the beginning and end of the interval correspond to the continuity condition there. See pg. 119 of [1]. Inputs: breakpts - breakpoints w - bspline workspace Return: success or error */ int gsl_bspline_knots (const gsl_vector * breakpts, gsl_bspline_workspace * w) { if (breakpts->size != w->nbreak) { GSL_ERROR ("breakpts vector has wrong size", GSL_EBADLEN); } else { size_t i; /* looping */ for (i = 0; i < w->k; i++) gsl_vector_set (w->knots, i, gsl_vector_get (breakpts, 0)); for (i = 1; i < w->l; i++) { gsl_vector_set (w->knots, w->k - 1 + i, gsl_vector_get (breakpts, i)); } for (i = w->n; i < w->n + w->k; i++) gsl_vector_set (w->knots, i, gsl_vector_get (breakpts, w->l)); return GSL_SUCCESS; } } /* gsl_bspline_knots() */ /* gsl_bspline_knots_uniform() Construct uniformly spaced knots on the interval [a,b] using the previously specified number of breakpoints. 'a' is the position of the first breakpoint and 'b' is the position of the last breakpoint. Inputs: a - left side of interval b - right side of interval w - bspline workspace Return: success or error Notes: 1) w->knots is modified to contain the uniformly spaced knots 2) The knots vector is set up as follows (using octave syntax): knots(1:k) = a knots(k+1:k+l-1) = a + i*delta, i = 1 .. l - 1 knots(n+1:n+k) = b */ int gsl_bspline_knots_uniform (const double a, const double b, gsl_bspline_workspace * w) { size_t i; /* looping */ double delta; /* interval spacing */ double x; delta = (b - a) / (double) w->l; for (i = 0; i < w->k; i++) gsl_vector_set (w->knots, i, a); x = a + delta; for (i = 0; i < w->l - 1; i++) { gsl_vector_set (w->knots, w->k + i, x); x += delta; } for (i = w->n; i < w->n + w->k; i++) gsl_vector_set (w->knots, i, b); return GSL_SUCCESS; } /* gsl_bspline_knots_uniform() */ /* gsl_bspline_eval() Evaluate the basis functions B_i(x) for all i. This is a wrapper function for gsl_bspline_eval_nonzero() which formats the output in a nice way. Inputs: x - point for evaluation B - (output) where to store B_i(x) values the length of this vector is n = nbreak + k - 2 = l + k - 1 = w->n w - bspline workspace Return: success or error Notes: The w->knots vector must be initialized prior to calling this function (see gsl_bspline_knots()) */ int gsl_bspline_eval (const double x, gsl_vector * B, gsl_bspline_workspace * w) { if (B->size != w->n) { GSL_ERROR ("vector B not of length n", GSL_EBADLEN); } else { size_t i; /* looping */ size_t istart; /* first non-zero spline for x */ size_t iend; /* last non-zero spline for x, knot for x */ int error; /* error handling */ /* find all non-zero B_i(x) values */ error = gsl_bspline_eval_nonzero (x, w->B, &istart, &iend, w); if (error) { return error; } /* store values in appropriate part of given vector */ for (i = 0; i < istart; i++) gsl_vector_set (B, i, 0.0); for (i = istart; i <= iend; i++) gsl_vector_set (B, i, gsl_vector_get (w->B, i - istart)); for (i = iend + 1; i < w->n; i++) gsl_vector_set (B, i, 0.0); return GSL_SUCCESS; } } /* gsl_bspline_eval() */ /* gsl_bspline_eval_nonzero() Evaluate all non-zero B-spline functions at point x. These are the B_i(x) for i in [istart, iend]. Always B_i(x) = 0 for i < istart and for i > iend. Inputs: x - point at which to evaluate splines Bk - (output) where to store B-spline values (length k) istart - (output) B-spline function index of first non-zero basis for given x iend - (output) B-spline function index of last non-zero basis for given x. This is also the knot index corresponding to x. w - bspline workspace Return: success or error Notes: 1) the w->knots vector must be initialized before calling this function 2) On output, B contains [B_{istart,k}, B_{istart+1,k}, ..., B_{iend-1,k}, B_{iend,k}] evaluated at the given x. */ int gsl_bspline_eval_nonzero (const double x, gsl_vector * Bk, size_t * istart, size_t * iend, gsl_bspline_workspace * w) { if (Bk->size != w->k) { GSL_ERROR ("Bk vector length does not match order k", GSL_EBADLEN); } else { size_t i; /* spline index */ size_t j; /* looping */ int flag = 0; /* interval search flag */ int error = 0; /* error flag */ i = bspline_find_interval (x, &flag, w); error = bspline_process_interval_for_eval (x, &i, flag, w); if (error) { return error; } *istart = i - w->k + 1; *iend = i; bspline_pppack_bsplvb (w->knots, w->k, 1, x, *iend, &j, w->deltal, w->deltar, Bk); return GSL_SUCCESS; } } /* gsl_bspline_eval_nonzero() */ /* gsl_bspline_deriv_eval() Evaluate d^j/dx^j B_i(x) for all i, 0 <= j <= nderiv. This is a wrapper function for gsl_bspline_deriv_eval_nonzero() which formats the output in a nice way. Inputs: x - point for evaluation nderiv - number of derivatives to compute, inclusive. dB - (output) where to store d^j/dx^j B_i(x) values. the size of this matrix is (n = nbreak + k - 2 = l + k - 1 = w->n) by (nderiv + 1) w - bspline derivative workspace Return: success or error Notes: 1) The w->knots vector must be initialized prior to calling this function (see gsl_bspline_knots()) 2) based on PPPACK's bsplvd */ int gsl_bspline_deriv_eval (const double x, const size_t nderiv, gsl_matrix * dB, gsl_bspline_workspace * w, gsl_bspline_deriv_workspace * dw) { if (dB->size1 != w->n) { GSL_ERROR ("dB matrix first dimension not of length n", GSL_EBADLEN); } else if (dB->size2 < nderiv + 1) { GSL_ERROR ("dB matrix second dimension must be at least length nderiv+1", GSL_EBADLEN); } else if (dw->k < w->k) { GSL_ERROR ("derivative workspace is too small", GSL_EBADLEN); } else { size_t i; /* looping */ size_t j; /* looping */ size_t istart; /* first non-zero spline for x */ size_t iend; /* last non-zero spline for x, knot for x */ int error; /* error handling */ /* find all non-zero d^j/dx^j B_i(x) values */ error = gsl_bspline_deriv_eval_nonzero (x, nderiv, dw->dB, &istart, &iend, w, dw); if (error) { return error; } /* store values in appropriate part of given matrix */ for (j = 0; j <= nderiv; j++) { for (i = 0; i < istart; i++) gsl_matrix_set (dB, i, j, 0.0); for (i = istart; i <= iend; i++) gsl_matrix_set (dB, i, j, gsl_matrix_get (dw->dB, i - istart, j)); for (i = iend + 1; i < w->n; i++) gsl_matrix_set (dB, i, j, 0.0); } return GSL_SUCCESS; } } /* gsl_bspline_deriv_eval() */ /* gsl_bspline_deriv_eval_nonzero() At point x evaluate all requested, non-zero B-spline function derivatives and store them in dB. These are the d^j/dx^j B_i(x) with i in [istart, iend] and j in [0, nderiv]. Always d^j/dx^j B_i(x) = 0 for i < istart and for i > iend. Inputs: x - point at which to evaluate splines nderiv - number of derivatives to request, inclusive dB - (output) where to store dB-spline derivatives (size k by nderiv + 1) istart - (output) B-spline function index of first non-zero basis for given x iend - (output) B-spline function index of last non-zero basis for given x. This is also the knot index corresponding to x. w - bspline derivative workspace Return: success or error Notes: 1) the w->knots vector must be initialized before calling this function 2) On output, dB contains [[B_{istart, k}, ..., d^nderiv/dx^nderiv B_{istart ,k}], [B_{istart+1,k}, ..., d^nderiv/dx^nderiv B_{istart+1,k}], ... [B_{iend-1, k}, ..., d^nderiv/dx^nderiv B_{iend-1, k}], [B_{iend, k}, ..., d^nderiv/dx^nderiv B_{iend, k}]] evaluated at x. B_{istart, k} is stored in dB(0,0). Each additional column contains an additional derivative. 3) Note that the zero-th column of the result contains the 0th derivative, which is simply a function evaluation. 4) based on PPPACK's bsplvd */ int gsl_bspline_deriv_eval_nonzero (const double x, const size_t nderiv, gsl_matrix * dB, size_t * istart, size_t * iend, gsl_bspline_workspace * w, gsl_bspline_deriv_workspace * dw) { if (dB->size1 != w->k) { GSL_ERROR ("dB matrix first dimension not of length k", GSL_EBADLEN); } else if (dB->size2 < nderiv + 1) { GSL_ERROR ("dB matrix second dimension must be at least length nderiv+1", GSL_EBADLEN); } else if (dw->k < w->k) { GSL_ERROR ("derivative workspace is too small", GSL_EBADLEN); } else { size_t i; /* spline index */ size_t j; /* looping */ int flag = 0; /* interval search flag */ int error = 0; /* error flag */ size_t min_nderivk; i = bspline_find_interval (x, &flag, w); error = bspline_process_interval_for_eval (x, &i, flag, w); if (error) { return error; } *istart = i - w->k + 1; *iend = i; bspline_pppack_bsplvd (w->knots, w->k, x, *iend, w->deltal, w->deltar, dw->A, dB, nderiv); /* An order k b-spline has at most k-1 nonzero derivatives so we need to zero all requested higher order derivatives */ min_nderivk = GSL_MIN_INT (nderiv, w->k - 1); for (j = min_nderivk + 1; j <= nderiv; j++) { for (i = 0; i < w->k; i++) { gsl_matrix_set (dB, i, j, 0.0); } } return GSL_SUCCESS; } } /* gsl_bspline_deriv_eval_nonzero() */ /**************************************** * INTERNAL ROUTINES * ****************************************/ /* bspline_find_interval() Find knot interval such that t_i <= x < t_{i + 1} where the t_i are knot values. Inputs: x - x value flag - (output) error flag w - bspline workspace Return: i (index in w->knots corresponding to left limit of interval) Notes: The error conditions are reported as follows: Condition Return value Flag --------- ------------ ---- x < t_0 0 -1 t_i <= x < t_{i+1} i 0 t_i < x = t_{i+1} = t_{n+k-1} i 0 t_{n+k-1} < x l+k-1 +1 */ static inline size_t bspline_find_interval (const double x, int *flag, gsl_bspline_workspace * w) { size_t i; if (x < gsl_vector_get (w->knots, 0)) { *flag = -1; return 0; } /* find i such that t_i <= x < t_{i+1} */ for (i = w->k - 1; i < w->k + w->l - 1; i++) { const double ti = gsl_vector_get (w->knots, i); const double tip1 = gsl_vector_get (w->knots, i + 1); if (tip1 < ti) { GSL_ERROR ("knots vector is not increasing", GSL_EINVAL); } if (ti <= x && x < tip1) break; if (ti < x && x == tip1 && tip1 == gsl_vector_get (w->knots, w->k + w->l - 1)) break; } if (i == w->k + w->l - 1) *flag = 1; else *flag = 0; return i; } /* bspline_find_interval() */ /* bspline_process_interval_for_eval() Consumes an x location, left knot from bspline_find_interval, flag from bspline_find_interval, and a workspace. Checks that x lies within the splines' knots, enforces some endpoint continuity requirements, and avoids divide by zero errors in the underlying bspline_pppack_* functions. */ static inline int bspline_process_interval_for_eval (const double x, size_t * i, const int flag, gsl_bspline_workspace * w) { if (flag == -1) { GSL_ERROR ("x outside of knot interval", GSL_EINVAL); } else if (flag == 1) { if (x <= gsl_vector_get (w->knots, *i) + GSL_DBL_EPSILON) { *i -= 1; } else { GSL_ERROR ("x outside of knot interval", GSL_EINVAL); } } if (gsl_vector_get (w->knots, *i) == gsl_vector_get (w->knots, *i + 1)) { GSL_ERROR ("knot(i) = knot(i+1) will result in division by zero", GSL_EINVAL); } return GSL_SUCCESS; } /* bspline_process_interval_for_eval */ /******************************************************************** * PPPACK ROUTINES * * The routines herein deliberately avoid using the bspline workspace, * choosing instead to pass all work areas explicitly. This allows * others to more easily adapt these routines to low memory or * parallel scenarios. ********************************************************************/ /* bspline_pppack_bsplvb() calculates the value of all possibly nonzero b-splines at x of order jout = max( jhigh , (j+1)*(index-1) ) with knot sequence t. Parameters: t - knot sequence, of length left + jout , assumed to be nondecreasing. assumption t(left).lt.t(left + 1). division by zero will result if t(left) = t(left+1) jhigh - index - integers which determine the order jout = max(jhigh, (j+1)*(index-1)) of the b-splines whose values at x are to be returned. index is used to avoid recalculations when several columns of the triangular array of b-spline values are needed (e.g., in bsplpp or in bsplvd ). precisely, if index = 1 , the calculation starts from scratch and the entire triangular array of b-spline values of orders 1,2,...,jhigh is generated order by order , i.e., column by column . if index = 2 , only the b-spline values of order j+1, j+2, ..., jout are generated, the assumption being that biatx, j, deltal, deltar are, on entry, as they were on exit at the previous call. in particular, if jhigh = 0, then jout = j+1, i.e., just the next column of b-spline values is generated. x - the point at which the b-splines are to be evaluated. left - an integer chosen (usually) so that t(left) .le. x .le. t(left+1). j - (output) a working scalar for indexing deltal - (output) a working area which must be of length at least jout deltar - (output) a working area which must be of length at least jout biatx - (output) array of length jout, with biatx(i) containing the value at x of the polynomial of order jout which agrees with the b-spline b(left-jout+i,jout,t) on the interval (t(left), t(left+1)) . Method: the recurrence relation x - t(i) t(i+j+1) - x b(i,j+1)(x) = -----------b(i,j)(x) + ---------------b(i+1,j)(x) t(i+j)-t(i) t(i+j+1)-t(i+1) is used (repeatedly) to generate the (j+1)-vector b(left-j,j+1)(x), ...,b(left,j+1)(x) from the j-vector b(left-j+1,j)(x),..., b(left,j)(x), storing the new values in biatx over the old. the facts that b(i,1) = 1 if t(i) .le. x .lt. t(i+1) and that b(i,j)(x) = 0 unless t(i) .le. x .lt. t(i+j) are used. the particular organization of the calculations follows algorithm (8) in chapter x of [1]. Notes: (1) This is a direct translation of PPPACK's bsplvb routine with j, deltal, deltar rewritten as input parameters and utilizing zero-based indexing. (2) This routine contains no error checking. Please use routines like gsl_bspline_eval(). */ static void bspline_pppack_bsplvb (const gsl_vector * t, const size_t jhigh, const size_t index, const double x, const size_t left, size_t * j, gsl_vector * deltal, gsl_vector * deltar, gsl_vector * biatx) { size_t i; /* looping */ double saved; double term; if (index == 1) { *j = 0; gsl_vector_set (biatx, 0, 1.0); } for ( /* NOP */ ; *j < jhigh - 1; *j += 1) { gsl_vector_set (deltar, *j, gsl_vector_get (t, left + *j + 1) - x); gsl_vector_set (deltal, *j, x - gsl_vector_get (t, left - *j)); saved = 0.0; for (i = 0; i <= *j; i++) { term = gsl_vector_get (biatx, i) / (gsl_vector_get (deltar, i) + gsl_vector_get (deltal, *j - i)); gsl_vector_set (biatx, i, saved + gsl_vector_get (deltar, i) * term); saved = gsl_vector_get (deltal, *j - i) * term; } gsl_vector_set (biatx, *j + 1, saved); } return; } /* gsl_bspline_pppack_bsplvb */ /* bspline_pppack_bsplvd() calculates value and derivs of all b-splines which do not vanish at x Parameters: t - the knot array, of length left+k (at least) k - the order of the b-splines to be evaluated x - the point at which these values are sought left - an integer indicating the left endpoint of the interval of interest. the k b-splines whose support contains the interval (t(left), t(left+1)) are to be considered. it is assumed that t(left) .lt. t(left+1) division by zero will result otherwise (in bsplvb). also, the output is as advertised only if t(left) .le. x .le. t(left+1) . deltal - a working area which must be of length at least k deltar - a working area which must be of length at least k a - an array of order (k,k), to contain b-coeffs of the derivatives of a certain order of the k b-splines of interest. dbiatx - an array of order (k,nderiv). its entry (i,m) contains value of (m)th derivative of (left-k+i)-th b-spline of order k for knot sequence t, i=1,...,k, m=0,...,nderiv. nderiv - an integer indicating that values of b-splines and their derivatives up to AND INCLUDING the nderiv-th are asked for. (nderiv is replaced internally by the integer mhigh in (1,k) closest to it.) Method: values at x of all the relevant b-splines of order k,k-1,..., k+1-nderiv are generated via bsplvb and stored temporarily in dbiatx. then, the b-coeffs of the required derivatives of the b-splines of interest are generated by differencing, each from the preceeding one of lower order, and combined with the values of b-splines of corresponding order in dbiatx to produce the desired values . Notes: (1) This is a direct translation of PPPACK's bsplvd routine with deltal, deltar rewritten as input parameters (to later feed them to bspline_pppack_bsplvb) and utilizing zero-based indexing. (2) This routine contains no error checking. */ static void bspline_pppack_bsplvd (const gsl_vector * t, const size_t k, const double x, const size_t left, gsl_vector * deltal, gsl_vector * deltar, gsl_matrix * a, gsl_matrix * dbiatx, const size_t nderiv) { int i, ideriv, il, j, jlow, jp1mid, kmm, ldummy, m, mhigh; double factor, fkmm, sum; size_t bsplvb_j; gsl_vector_view dbcol = gsl_matrix_column (dbiatx, 0); mhigh = GSL_MIN_INT (nderiv, k - 1); bspline_pppack_bsplvb (t, k - mhigh, 1, x, left, &bsplvb_j, deltal, deltar, &dbcol.vector); if (mhigh > 0) { /* the first column of dbiatx always contains the b-spline values for the current order. these are stored in column k-current order before bsplvb is called to put values for the next higher order on top of it. */ ideriv = mhigh; for (m = 1; m <= mhigh; m++) { for (j = ideriv, jp1mid = 0; j < (int) k; j++, jp1mid++) { gsl_matrix_set (dbiatx, j, ideriv, gsl_matrix_get (dbiatx, jp1mid, 0)); } ideriv--; bspline_pppack_bsplvb (t, k - ideriv, 2, x, left, &bsplvb_j, deltal, deltar, &dbcol.vector); } /* at this point, b(left-k+i, k+1-j)(x) is in dbiatx(i,j) for i=j,...,k-1 and j=0,...,mhigh. in particular, the first column of dbiatx is already in final form. to obtain corresponding derivatives of b-splines in subsequent columns, generate their b-repr. by differencing, then evaluate at x. */ jlow = 0; for (i = 0; i < (int) k; i++) { for (j = jlow; j < (int) k; j++) { gsl_matrix_set (a, j, i, 0.0); } jlow = i; gsl_matrix_set (a, i, i, 1.0); } /* at this point, a(.,j) contains the b-coeffs for the j-th of the k b-splines of interest here. */ for (m = 1; m <= mhigh; m++) { kmm = k - m; fkmm = (float) kmm; il = left; i = k - 1; /* for j=1,...,k, construct b-coeffs of (m)th derivative of b-splines from those for preceding derivative by differencing and store again in a(.,j) . the fact that a(i,j) = 0 for i .lt. j is used. */ for (ldummy = 0; ldummy < kmm; ldummy++) { factor = fkmm / (gsl_vector_get (t, il + kmm) - gsl_vector_get (t, il)); /* the assumption that t(left).lt.t(left+1) makes denominator in factor nonzero. */ for (j = 0; j <= i; j++) { gsl_matrix_set (a, i, j, factor * (gsl_matrix_get (a, i, j) - gsl_matrix_get (a, i - 1, j))); } il--; i--; } /* for i=1,...,k, combine b-coeffs a(.,i) with b-spline values stored in dbiatx(.,m) to get value of (m)th derivative of i-th b-spline (of interest here) at x, and store in dbiatx(i,m). storage of this value over the value of a b-spline of order m there is safe since the remaining b-spline derivatives of the same order do not use this value due to the fact that a(j,i) = 0 for j .lt. i . */ for (i = 0; i < (int) k; i++) { sum = 0; jlow = GSL_MAX_INT (i, m); for (j = jlow; j < (int) k; j++) { sum += gsl_matrix_get (a, j, i) * gsl_matrix_get (dbiatx, j, m); } gsl_matrix_set (dbiatx, i, m, sum); } } } return; } /* bspline_pppack_bsplvd */
{ "alphanum_fraction": 0.5937677054, "avg_line_length": 27.9603960396, "ext": "c", "hexsha": "cf19574129d7fc1ee6ca6673fc99ee1637d98f3c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/bspline/bspline.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/bspline/bspline.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/bspline/bspline.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": 8504, "size": 28240 }
// The various memcached commands that we support. #include "commands.h" #include "connections.h" #include "locking.h" #include "protocol.h" #include "server.h" #include "threads.h" #include "utils.h" #include <assert.h> #include <gsl/gsl_randist.h> #include <stdio.h> #include <stdlib.h> static const char* default_key = "skeleton"; /* // process a memcached get(s) command. (we don't support CAS). This function */ /* // performs the request parsing and setup of backend RPC's. */ /* void process_get_command(conn *c, token_t *tokens, size_t ntokens, */ /* bool return_cas) { */ /* char *key; */ /* size_t nkey; */ /* int i = 0; */ /* item *it; */ /* token_t *key_token = &tokens[KEY_TOKEN]; */ /* char *suffix; */ /* worker_thread_t *t = c->thread; */ /* memcached_t *mc; */ /* */ /* assert(c != NULL); */ /* */ /* key = key_token->value; */ /* nkey = key_token->length; */ /* */ /* if (config.use_dist) { */ /* long size = config.dist_arg1 + gsl_ran_gaussian(config.r, config.dist_arg2); */ /* if (config.verbose > 1) { */ /* fprintf(stderr, "allocated blob: %ld\n", size); */ /* } */ /* c->mem_blob = malloc(sizeof(char) * size); */ /* } */ /* */ /* if(nkey > KEY_MAX_LENGTH) { */ /* error_response(c, "CLIENT_ERROR bad command line format"); */ /* return; */ /* } */ /* */ /* // lookup key-value. */ /* it = item_get(key, nkey); */ /* */ /* // hit. */ /* if (it) { */ /* if (i >= c->isize && !conn_expand_items(c)) { */ /* item_remove(it); */ /* error_response(c, "SERVER_ERROR out of memory writing get response"); */ /* return; */ /* } */ /* // add item to remembered list (i.e., we've taken ownership of them */ /* // through refcounting and later must release them once we've */ /* // written out the iov associated with them). */ /* item_update(it); */ /* *(c->ilist + i) = it; */ /* i++; */ /* } */ /* */ /* // make sure it's a single get */ /* key_token++; */ /* if (key_token->length != 0 || key_token->value != NULL) { */ /* error_response(c, "SERVER_ERROR only support single `get`"); */ /* return; */ /* } */ /* */ /* // update our rememberd reference set. */ /* c->icurr = c->ilist; */ /* c->ileft = i; */ /* */ /* // setup RPC calls. */ /* for (i = 0; i < t->memcache_used; i++) { */ /* mc = t->memcache[i]; */ /* if (!conn_add_msghdr(mc) != 0) { */ /* error_response(mc, "SERVER_ERROR out of memory preparing response"); */ /* return; */ /* } */ /* memcache_get(mc, c, default_key); */ /* } */ /* conn_set_state(c, conn_rpc_wait); */ /* } */ // complete the response to a get request. void finish_get_command(conn *c) { item *it; int i; // setup all items for writing out. for (i = 0; i < c->ileft; i++) { it = *(c->ilist + i); if (it) { // Construct the response. Each hit adds three elements to the // outgoing data list: // "VALUE <key> <flags> <data_length>\r\n" // "<data>\r\n" // The <data> element is stored on the connection item list, not on // the iov list. if (!conn_add_iov(c, "VALUE ", 6) || !conn_add_iov(c, ITEM_key(it), it->nkey) || !conn_add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes)) { item_remove(it); error_response(c, "SERVER_ERROR out of memory writing get response"); return; } if (config.verbose > 1) { fprintf(stderr, ">%d sending key %s\n", c->sfd, ITEM_key(it)); } } else { fprintf(stderr, "ERROR corrupted ilist!\n"); exit(1); } } if (config.verbose > 1) { fprintf(stderr, ">%d END\n", c->sfd); } if (!conn_add_iov(c, "END\r\n", 5) != 0) { error_response(c, "SERVER_ERROR out of memory writing get response"); } else { conn_set_state(c, conn_mwrite); } } // process a memcached get(s) command. (we don't support CAS). void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { char *key; size_t nkey; int i = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; assert(c != NULL); if (config.alloc && c->mem_blob == NULL) { long size = config.alloc_mean + gsl_ran_gaussian(c->thread->r, config.alloc_stddev); size = size <= 0 ? 10 : size; if (config.verbose > 0) { fprintf(stderr, "allocated blob: %ld\n", size); } c->mem_blob = malloc(sizeof(char) * size); c->mem_free_delay = 0; if (config.rtt_delay) { double r = config.rtt_mean + gsl_ran_gaussian(c->thread->r, config.rtt_stddev); if (r >= config.rtt_cutoff) { int wait = r / 100; if (config.verbose > 0) { fprintf(stderr, "delay: %d\n", wait); } c->mem_free_delay = wait; conn_set_state(c, conn_mwrite); } } } // process the whole command line, (only part of it may be tokenized right now) do { // process all tokenized keys at this stage. while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if(nkey > KEY_MAX_LENGTH) { error_response(c, "CLIENT_ERROR bad command line format"); return; } // lookup key-value. it = item_get(key, nkey); // hit. if (it) { if (i >= c->isize && !conn_expand_items(c)) { item_remove(it); break; } // Construct the response. Each hit adds three elements to the // outgoing data list: // "VALUE <key> <flags> <data_length>\r\n" // "<data>\r\n" // The <data> element is stored on the connection item list, not on // the iov list. if (!conn_add_iov(c, "VALUE ", 6) != 0 || !conn_add_iov(c, ITEM_key(it), it->nkey) != 0 || !conn_add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) { item_remove(it); break; } if (config.verbose > 1) { fprintf(stderr, ">%d sending key %s\n", c->sfd, key); } // add item to remembered list (i.e., we've taken ownership of them // through refcounting and later must release them once we've // written out the iov associated with them). item_update(it); *(c->ilist + i) = it; i++; } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); c->icurr = c->ilist; c->ileft = i; if (config.verbose > 1) { fprintf(stderr, ">%d END\n", c->sfd); } // If the loop was terminated because of out-of-memory, it is not reliable // to add END\r\n to the buffer, because it might not end in \r\n. So we // send SERVER_ERROR instead. if (key_token->value != NULL || !conn_add_iov(c, "END\r\n", 5) != 0) { error_response(c, "SERVER_ERROR out of memory writing get response"); } else { conn_set_state(c, conn_mwrite); } } // process a memcached set command. void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) { int vlen; assert(c != NULL); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH || !safe_strtol(tokens[4].value, (int32_t *)&vlen)) { error_response(c, "CLIENT_ERROR bad command line format"); return; } if (vlen < 0) { error_response(c, "CLIENT_ERROR bad command line format"); return; } // setup value to be read c->sbytes = vlen + 2; // for \r\n consumption. conn_set_state(c, conn_read_value); } // process a memcached stat command. void process_stat_command(conn *c, token_t *tokens, const size_t ntokens) { mutex_lock(&c->stats->lock); // just for debugging right now fprintf(stderr, "STAT client_id %d\n", c->stats->client_id); fprintf(stderr, "STAT total_connections %d\n", c->stats->total_connections); fprintf(stderr, "STAT live_connections %d\n", c->stats->live_connections); fprintf(stderr, "STAT requests %d\n", c->stats->requests); mutex_unlock(&c->stats->lock); conn_set_state(c, conn_new_cmd); }
{ "alphanum_fraction": 0.6000251953, "avg_line_length": 28.0494699647, "ext": "c", "hexsha": "dd7a3091797bec9f9a0eadb1e5c7521bc6983f65", "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": "cf998af17337df7b9f50e1aac80855b150841059", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dterei/synthetic-client", "max_forks_repo_path": "src/commands.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "cf998af17337df7b9f50e1aac80855b150841059", "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": "dterei/synthetic-client", "max_issues_repo_path": "src/commands.c", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "cf998af17337df7b9f50e1aac80855b150841059", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dterei/synthetic-client", "max_stars_repo_path": "src/commands.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2385, "size": 7938 }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #pragma once #include <chrono> #include <cstdint> #include <gsl/gsl> #include <iostream> #include <vector> namespace tp { class CanFrame; /** * @brief The TimeProvider struct * TODO if I'm not mistaken, those classes ought to have 100µs resolutiuon instead of 1ms (1000µs). */ struct ChronoTimeProvider { long operator() () const { using namespace std::chrono; system_clock::time_point now = system_clock::now (); auto duration = now.time_since_epoch (); return duration_cast<milliseconds> (duration).count (); } }; struct CoutPrinter { template <typename T> void operator() (T &&a) { std::cout << std::forward<T> (a) << std::endl; } }; /** * Buffer for all input and ouptut operations */ using IsoMessage = std::vector<uint8_t>; } // namespace tp
{ "alphanum_fraction": 0.4265335235, "avg_line_length": 32.6046511628, "ext": "h", "hexsha": "1e79cc1a30e0f1b1f61278f76aebc1708994fd92", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-05-31T07:40:34.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-15T06:14:27.000Z", "max_forks_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "semasquare/cpp-can-isotp", "max_forks_repo_path": "src/StlTypes.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:32:11.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-02T19:05:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "semasquare/cpp-can-isotp", "max_issues_repo_path": "src/StlTypes.h", "max_line_length": 104, "max_stars_count": 14, "max_stars_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "semasquare/cpp-can-isotp", "max_stars_repo_path": "src/StlTypes.h", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:32:58.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-17T15:01:36.000Z", "num_tokens": 248, "size": 1402 }
/* matrix/gsl_matrix_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_MATRIX_DOUBLE_H__ #define __GSL_MATRIX_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/block/gsl_check_range.h> #include <gsl/vector/gsl_vector_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 size1; //nr rows size_t size2; //nr cols size_t tda; //space between two consecutive rows double * data; //a pointer to the data gsl_block * block;//the block pointer. int owner; //this is 1 if the current object owns the memory block, 0 otherwise } gsl_matrix; typedef struct { gsl_matrix matrix; } _gsl_matrix_view; typedef _gsl_matrix_view gsl_matrix_view; typedef struct { gsl_matrix matrix; } _gsl_matrix_const_view; typedef const _gsl_matrix_const_view gsl_matrix_const_view; /* Allocation */ GSL_FUNC gsl_matrix * gsl_matrix_alloc (const size_t n1, const size_t n2); GSL_FUNC gsl_matrix * gsl_matrix_calloc (const size_t n1, const size_t n2); GSL_FUNC gsl_matrix * gsl_matrix_alloc_from_block (gsl_block * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_FUNC gsl_matrix * gsl_matrix_alloc_from_matrix (gsl_matrix * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_FUNC gsl_vector * gsl_vector_alloc_row_from_matrix (gsl_matrix * m, const size_t i); GSL_FUNC gsl_vector * gsl_vector_alloc_col_from_matrix (gsl_matrix * m, const size_t j); GSL_FUNC void gsl_matrix_free (gsl_matrix * m); /* Views */ GSL_FUNC _gsl_matrix_view gsl_matrix_submatrix (gsl_matrix * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUNC _gsl_vector_view gsl_matrix_row (gsl_matrix * m, const size_t i); GSL_FUNC _gsl_vector_view gsl_matrix_column (gsl_matrix * m, const size_t j); GSL_FUNC _gsl_vector_view gsl_matrix_diagonal (gsl_matrix * m); GSL_FUNC _gsl_vector_view gsl_matrix_subdiagonal (gsl_matrix * m, const size_t k); GSL_FUNC _gsl_vector_view gsl_matrix_superdiagonal (gsl_matrix * m, const size_t k); GSL_FUNC _gsl_matrix_view gsl_matrix_view_array (double * base, const size_t n1, const size_t n2); GSL_FUNC _gsl_matrix_view gsl_matrix_view_array_with_tda (double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUNC _gsl_matrix_view gsl_matrix_view_vector (gsl_vector * v, const size_t n1, const size_t n2); GSL_FUNC _gsl_matrix_view gsl_matrix_view_vector_with_tda (gsl_vector * v, const size_t n1, const size_t n2, const size_t tda); GSL_FUNC _gsl_matrix_const_view gsl_matrix_const_submatrix (const gsl_matrix * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUNC _gsl_vector_const_view gsl_matrix_const_row (const gsl_matrix * m, const size_t i); GSL_FUNC _gsl_vector_const_view gsl_matrix_const_column (const gsl_matrix * m, const size_t j); GSL_FUNC _gsl_vector_const_view gsl_matrix_const_diagonal (const gsl_matrix * m); GSL_FUNC _gsl_vector_const_view gsl_matrix_const_subdiagonal (const gsl_matrix * m, const size_t k); GSL_FUNC _gsl_vector_const_view gsl_matrix_const_superdiagonal (const gsl_matrix * m, const size_t k); GSL_FUNC _gsl_matrix_const_view gsl_matrix_const_view_array (const double * base, const size_t n1, const size_t n2); GSL_FUNC _gsl_matrix_const_view gsl_matrix_const_view_array_with_tda (const double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUNC _gsl_matrix_const_view gsl_matrix_const_view_vector (const gsl_vector * v, const size_t n1, const size_t n2); GSL_FUNC _gsl_matrix_const_view gsl_matrix_const_view_vector_with_tda (const gsl_vector * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_FUNC double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j); GSL_FUNC void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x); GSL_FUNC double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j); GSL_FUNC const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j); GSL_FUNC void gsl_matrix_set_zero (gsl_matrix * m); GSL_FUNC void gsl_matrix_set_identity (gsl_matrix * m); GSL_FUNC void gsl_matrix_set_all (gsl_matrix * m, double x); GSL_FUNC int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ; GSL_FUNC int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ; GSL_FUNC int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m); GSL_FUNC int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format); GSL_FUNC int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src); GSL_FUNC int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2); GSL_FUNC int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j); GSL_FUNC int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j); GSL_FUNC int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j); GSL_FUNC int gsl_matrix_transpose (gsl_matrix * m); GSL_FUNC int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src); GSL_FUNC double gsl_matrix_max (const gsl_matrix * m); GSL_FUNC double gsl_matrix_min (const gsl_matrix * m); GSL_FUNC void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out); GSL_FUNC void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax); GSL_FUNC void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin); GSL_FUNC void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_FUNC int gsl_matrix_isnull (const gsl_matrix * m); GSL_FUNC int gsl_matrix_ispos (const gsl_matrix * m); GSL_FUNC int gsl_matrix_isneg (const gsl_matrix * m); GSL_FUNC int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b); GSL_FUNC int gsl_matrix_add_scaled (gsl_matrix * a, const gsl_matrix * b, double scaleA, double scaleB); GSL_FUNC int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b); GSL_FUNC int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b); GSL_FUNC int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b); GSL_FUNC int gsl_matrix_scale (gsl_matrix * a, const double x); GSL_FUNC int gsl_matrix_add_constant (gsl_matrix * a, const double x); GSL_FUNC int gsl_matrix_add_diagonal (gsl_matrix * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_FUNC int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i); GSL_FUNC int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j); GSL_FUNC int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v); GSL_FUNC int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v); /* inline functions if you are using GCC */ #ifdef HAVE_INLINE extern inline double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } #endif return m->data[i * m->tda + j] ; } extern inline void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif m->data[i * m->tda + j] = x ; } extern inline double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (double *) (m->data + (i * m->tda + j)) ; } extern inline const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const double *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_DOUBLE_H__ */
{ "alphanum_fraction": 0.6490677497, "avg_line_length": 33.85625, "ext": "h", "hexsha": "1b42b59ef32046427672c1c66ffe41e203cfdc1f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix_double.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix_double.h", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2711, "size": 10834 }
/* roots/newton.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* newton.c -- newton root finding algorithm This is the classical Newton-Raphson iteration. x[i+1] = x[i] - f(x[i])/f'(x[i]) */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include "roots.h" typedef struct { double f, df; } newton_state_t; static int newton_init (void * vstate, gsl_function_fdf * fdf, double * root); static int newton_iterate (void * vstate, gsl_function_fdf * fdf, double * root); static int newton_init (void * vstate, gsl_function_fdf * fdf, double * root) { newton_state_t * state = (newton_state_t *) vstate; const double x = *root ; state->f = GSL_FN_FDF_EVAL_F (fdf, x); state->df = GSL_FN_FDF_EVAL_DF (fdf, x) ; return GSL_SUCCESS; } static int newton_iterate (void * vstate, gsl_function_fdf * fdf, double * root) { newton_state_t * state = (newton_state_t *) vstate; double root_new, f_new, df_new; if (state->df == 0.0) { GSL_ERROR("derivative is zero", GSL_EZERODIV); } root_new = *root - (state->f / state->df); *root = root_new ; GSL_FN_FDF_EVAL_F_DF(fdf, root_new, &f_new, &df_new); state->f = f_new ; state->df = df_new ; if (!finite(f_new)) { GSL_ERROR ("function not continuous", GSL_EBADFUNC); } if (!finite (df_new)) { GSL_ERROR ("function not differentiable", GSL_EBADFUNC); } return GSL_SUCCESS; } static const gsl_root_fdfsolver_type newton_type = {"newton", /* name */ sizeof (newton_state_t), &newton_init, &newton_iterate}; const gsl_root_fdfsolver_type * gsl_root_fdfsolver_newton = &newton_type;
{ "alphanum_fraction": 0.6887573964, "avg_line_length": 23.691588785, "ext": "c", "hexsha": "e2df7a700f0bf57fc5bea8e871aa8bfbccb2ee53", "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/roots/newton.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/roots/newton.c", "max_line_length": 81, "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/roots/newton.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": 731, "size": 2535 }
/* File Name: grad.c Last Modification Date: 3/9/94 10:03:45 Current Version: grad.c 1.7 %File Creation Date: 26/10/91 Author: Ramesh Gopinath <ramesh@dsp.rice.edu> Copyright: All software, documentation, and related files in this distribution are Copyright (c) 1993 Rice University Permission is granted for use and non-profit distribution providing that this notice be clearly maintained. The right to distribute any portion for profit or as part of any commercial product is specifically reserved for the author. */ /* ################################################################################# grad.mex4: function [g,f,h] = grad(k,M,N,fs); Computes the gradient of stopband energy of the linear-phase prototype filter in a cosine-modulated filter bank with respect to lattice parameters of the J lattices. Input: k : Vector of denormalized lattice parameters for the J lattices of CMFB M : M-channel, M-band etc N : 2Mm, length of the prototype filter fs : Stopband edge (as a fraction of pi) Output: f : Stopband Energy h : Prototype filter (second half) ################################################################################# */ #ifndef PROTOTYPE_DESIGN_H #define PROTOTYPE_DESIGN_H #include <stdio.h> #include <assert.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include "common/refcount.h" #include "common/jexception.h" // ----- definition for class `CosineModulatedPrototypeDesign' ----- // class CosineModulatedPrototypeDesign { public: CosineModulatedPrototypeDesign(int M = 256, int N = 3072, double fs = 1.0); ~CosineModulatedPrototypeDesign(); void fcn(const double* x, double* f); void grad(const double* x, double* g); int M() const { return _M; } int N() const { return _N; } int m() const { return _m; } int J() const { return _J; } // return (one-half) of the prototype filter const gsl_vector* proto(); private: const int _M; // No. of channels const int _N; // filter length 2 * _M * _m const int _M2; // 2 * _M const int _m; const int _Mm; const int _J; const int _Jm; const int _oddM; const int _oddm; double* _sinews; double* _h; double* _hh; double* _Ph; double* _jac; int* _index; gsl_vector* _proto; }; double design_f(const gsl_vector* v, void* params); void design_df(const gsl_vector* v, void* params, gsl_vector* df); void design_fdf(const gsl_vector* v, void* params, double* f, gsl_vector* df); // ----- definition for class `PrototypeDesignBase' ----- // class PrototypeDesignBase { public: PrototypeDesignBase(int M, int m, unsigned r, double wp, int tau); ~PrototypeDesignBase(); protected: virtual void _calculateAb(); void _calculateC(); void _svd(gsl_matrix* U, gsl_matrix* V, gsl_vector* S, gsl_vector* workSpace); gsl_matrix* _nullSpace(const gsl_matrix* A, double tolerance); gsl_vector* _pseudoInverse(const gsl_matrix* A, const gsl_vector* b, double tolerance); void _solveNonSingular(const gsl_matrix* H, const gsl_vector* c0, const gsl_matrix* P, double tolerance); void _solveSingular(gsl_matrix* Ac, gsl_vector* bc, gsl_matrix* K, gsl_vector* dp, double tolerance); double _condition(gsl_matrix* H, gsl_matrix* P); void _printMatrix(const gsl_matrix* A, FILE* fp = stdout) const; void _printVector(const gsl_vector* b, FILE* fp = stdout) const; void save(const String& fileName); const int _M; // the number of subbands const int _m; const double _wp; const int _R; const int _D; const int _L; int _tau; gsl_matrix* _A; gsl_vector* _b; gsl_matrix* _cpA; gsl_vector* _cpb; gsl_matrix* _C; gsl_matrix* _cpC; gsl_vector* _singularVals; gsl_vector* _scratch; gsl_vector* _workSpace; gsl_vector* _prototype; }; // ----- definition for class `AnalysisOversampledDFTDesign' ----- // typedef Countable AnalysisOversampledDFTDesignCountable; class AnalysisOversampledDFTDesign : public AnalysisOversampledDFTDesignCountable, protected PrototypeDesignBase { public: AnalysisOversampledDFTDesign(int M = 512, int m = 2, int r = 1, double wp = 1.0, int tau_h = -1 ); ~AnalysisOversampledDFTDesign(); // design analysis prototype // tolerance for double precision: 2.2204e-16 // tolerance for single precision: 1.1921e-07 const gsl_vector* design(double tolerance = 2.2204e-16); // calculate distortion measures const gsl_vector* calcError(bool doPrint = true); void save(const String& fileName) { PrototypeDesignBase::save(fileName); } protected: virtual void _solve(double tolerance); double _passbandResponseError(); double _inbandAliasingDistortion(); gsl_vector* _error; // [0] the total response error // [1] the residual aliasing distortion // [2] objective fuction }; typedef refcountable_ptr<AnalysisOversampledDFTDesign> AnalysisOversampledDFTDesignPtr; // ----- definition for class `SynthesisOversampledDFTDesign' ----- // typedef Countable SynthesisOversampledDFTDesignCountable; class SynthesisOversampledDFTDesign : public SynthesisOversampledDFTDesignCountable, protected PrototypeDesignBase { public: SynthesisOversampledDFTDesign(const gsl_vector* h, int M = 512, int m = 2, int r = 1, double v = 0.01, double wp = 1.0, int tau_T = -1 ); ~SynthesisOversampledDFTDesign(); // design synthesis prototype // tolerance for double precision: 2.2204e-16 // tolerance for single precision: 1.1921e-07 const gsl_vector* design(double tolerance = 2.2204e-16); // calculate distortion measures virtual const gsl_vector* calcError(bool doPrint = true); void save(const String& fileName) { PrototypeDesignBase::save(fileName); } protected: void _calculateEfP(); virtual void _solve(double tolerance); double _totalResponseError(); double _residualAliasingDistortion(); gsl_vector* _h; const double _v; gsl_matrix* _E; gsl_matrix* _P; gsl_vector* _f; gsl_matrix* _cpE; gsl_matrix* _cpP; gsl_vector* _cpf; gsl_vector* _error; // [0] the total response error // [1] the residual aliasing distortion // [2] objective fuction }; typedef refcountable_ptr<SynthesisOversampledDFTDesign> SynthesisOversampledDFTDesignPtr; // ----- definition for class `AnalysisNyquistMDesign' ----- // class AnalysisNyquistMDesign : public AnalysisOversampledDFTDesign { public: AnalysisNyquistMDesign(int M = 512, int m = 2, int r = 1, double wp = 1.0, int tau_h = -1 ); ~AnalysisNyquistMDesign(); private: virtual void _solve(double tolerance); void _calculateFd(); void _calculateKdp(); gsl_matrix* _F; gsl_vector* _d; gsl_matrix* _K; gsl_vector* _dp; }; typedef Inherit<AnalysisNyquistMDesign, AnalysisOversampledDFTDesignPtr> AnalysisNyquistMDesignPtr; // ----- definition for class `SynthesisNyquistMDesign' ----- // class SynthesisNyquistMDesign : public SynthesisOversampledDFTDesign { public: SynthesisNyquistMDesign(const gsl_vector* h, int M = 512, int m = 2, int r = 1, double wp = 1.0, int tau_g = -1); ~SynthesisNyquistMDesign(); virtual const gsl_vector* calcError(bool doPrint = true); private: virtual void _solve(double tolerance); double _passbandResponseError(); void _calculateHc0(); void _calculateJcp(); gsl_matrix* _H; gsl_vector* _c0; gsl_matrix* _J; gsl_vector* _cp; }; typedef Inherit<SynthesisNyquistMDesign, SynthesisOversampledDFTDesignPtr> SynthesisNyquistMDesignPtr; // ----- definition for class `SynthesisNyquistMDesignCompositeResponse' ----- // class SynthesisNyquistMDesignCompositeResponse : public SynthesisNyquistMDesign { public: SynthesisNyquistMDesignCompositeResponse(const gsl_vector* h, int M = 512, int m = 2, int r = 1, double wp = 1.0, int tau = -1); ~SynthesisNyquistMDesignCompositeResponse(); private: virtual void _calculateAb(); inline double _sinc(int m); double* _sincValues; }; typedef Inherit<SynthesisNyquistMDesignCompositeResponse, SynthesisNyquistMDesignPtr> SynthesisNyquistMDesignCompositeResponsePtr; double SynthesisNyquistMDesignCompositeResponse::_sinc(int m) { int am = abs(m); if (am >= 2 * _L) throw jindex_error("Problem: index %d > 2 * L = %d", am, 2 * _L); double val = _sincValues[am]; if (val != -HUGE_VAL) return val; if (m == 0) val = _sincValues[am] = 1.0; else val = _sincValues[am] = sin(_wp * am) / (_wp * am); return val; } #endif
{ "alphanum_fraction": 0.673821642, "avg_line_length": 30.2274247492, "ext": "h", "hexsha": "e5b1b9ce4d8a88d61f30490bc922d4d5ef2123d7", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/modulated/prototype_design.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/modulated/prototype_design.h", "max_line_length": 130, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/modulated/prototype_design.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 2469, "size": 9038 }
#include <stdio.h> #include <gsl/gsl_fit.h> int main (void) { int i, n = 4; double x[4] = { 1970, 1980, 1990, 2000 }; double y[4] = { 12, 11, 14, 13 }; double w[4] = { 0.1, 0.2, 0.3, 0.4 }; double c0, c1, cov00, cov01, cov11, chisq; gsl_fit_wlinear (x, 1, w, 1, y, 1, n, &c0, &c1, &cov00, &cov01, &cov11, &chisq); printf ("# best fit: Y = %g + %g X\n", c0, c1); printf ("# covariance matrix:\n"); printf ("# [ %g, %g\n# %g, %g]\n", cov00, cov01, cov01, cov11); printf ("# chisq = %g\n", chisq); for (i = 0; i < n; i++) printf ("data: %g %g %g\n", x[i], y[i], 1/sqrt(w[i])); printf ("\n"); for (i = -30; i < 130; i++) { double xf = x[0] + (i/100.0) * (x[n-1] - x[0]); double yf, yf_err; gsl_fit_linear_est (xf, c0, c1, cov00, cov01, cov11, &yf, &yf_err); printf ("fit: %g %g\n", xf, yf); printf ("hi : %g %g\n", xf, yf + yf_err); printf ("lo : %g %g\n", xf, yf - yf_err); } return 0; }
{ "alphanum_fraction": 0.4154929577, "avg_line_length": 24.6956521739, "ext": "c", "hexsha": "5c3696971028b093ea6d806deed68fed1089dfc0", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitting.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitting.c", "max_line_length": 53, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/fitting.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": 469, "size": 1136 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "iterators.h" #include "macros.h" #include "type_traits.h" #include "string.h" #include "path.h" #include <cereal/cereal.hpp> #include <algorithm> #include <assert.h> #include <cmath> #include <gsl/gsl> #include <iterator> #include <map> #include <sstream> #include <string> #include <vector> namespace mira { struct property_bag; struct property_interface { property_interface(const char* type, const char* name) : m_type{ type } , m_name{ name } {} virtual ~property_interface() {} const char* name() const { return m_name; } const char* type() const { return m_type; } private: const char* const m_type; const char* const m_name; }; struct simple_property : public property_interface { virtual void from_string(const std::string& str) = 0; virtual void from_stream(std::istream& str) = 0; virtual void from_other(const property_interface& other) = 0; virtual std::type_index serializable_type() const = 0; virtual std::string to_string() const = 0; simple_property(const char* type, const char* name) : property_interface(type, name) {} }; template<typename SerializableType> struct serializable_property : public simple_property { serializable_property(const char* type, const char* name) : simple_property(type, name) {} virtual ~serializable_property() {} std::type_index serializable_type() const override { return { typeid(SerializableType) }; } // serialization functions template<class Archive> SerializableType save_minimal(Archive const&) const { return get_serializable(); } template<class Archive> void load_minimal(Archive const&, SerializableType const& val) { set_serializable(val); } protected: virtual SerializableType get_serializable() const = 0; virtual void set_serializable(const SerializableType& value) = 0; }; template<typename T> struct property; struct property_bag : public property_interface { bool set(const std::string& name, const std::string& value) { auto itr = m_properties.find(name.c_str()); if (itr == m_properties.end()) return false; itr->second->from_string(value); return true; } void from_other(const property_bag& other) { assert(strcmp(name(), other.name()) == 0); assert(other.m_properties.size() == m_properties.size()); assert(other.m_groups.size() == m_groups.size()); for (auto prop : m_properties) { prop.second->from_other(*other.m_properties.at(prop.first)); } for (size_t i = 0; i < m_groups.size(); ++i) { assert(strcmp(m_groups[i]->name(), other.m_groups[i]->name()) == 0); m_groups[i]->from_other(*other.m_groups[i]); } } std::string get(const std::string& name) const { return m_properties.find(name.c_str())->second->to_string(); } std::vector<simple_property*> properties() { std::vector<simple_property*> props; std::transform(m_properties.begin(), m_properties.end(), std::back_inserter(props), [](const auto& entry) { return entry.second; }); return props; } std::vector<const simple_property*> properties() const { std::vector<const simple_property*> props; std::transform(m_properties.begin(), m_properties.end(), std::back_inserter(props), [](const auto& entry) { return entry.second; }); return props; } gsl::span<property_bag*> groups() { return m_groups; } gsl::span<const property_bag*> groups() const { return { const_cast<property_bag const**>(m_groups.data()), (gsl::span<const property_bag*>::size_type)m_groups.size() }; } // serialization function template<typename ArchiveT> void serialize(ArchiveT& ar) { using arch_func = void(ArchiveT & ar, property_interface * prop); static std::unordered_map<std::type_index, arch_func*> converters{ { typeid(bool), &archive_prop<ArchiveT, serializable_property<bool>> }, { typeid(int), &archive_prop<ArchiveT, serializable_property<int>> }, { typeid(unsigned int), &archive_prop<ArchiveT, serializable_property<unsigned int>> }, { typeid(uint32_t), &archive_prop<ArchiveT, serializable_property<uint32_t>> }, { typeid(uint64_t), &archive_prop<ArchiveT, serializable_property<uint64_t>> }, { typeid(size_t), &archive_prop<ArchiveT, serializable_property<size_t>> }, { typeid(float), &archive_prop<ArchiveT, serializable_property<float>> }, { typeid(std::string), &archive_prop<ArchiveT, serializable_property<std::string>> }, { typeid(double), &archive_prop<ArchiveT, serializable_property<double>> }, }; for (auto prop : m_properties) { auto found = converters.find(prop.second->serializable_type()); if (found == converters.end()) throw std::invalid_argument("unable to convert type, conversion function not found"); found->second(ar, prop.second); } for (auto group : m_groups) { ar(cereal::make_nvp(group->name(), *group)); } } protected: property_bag(const char* name) : property_bag{ name, nullptr } {} property_bag(const char* name, property_bag* owner) : property_interface{ "bag", name } { if (owner != nullptr) { owner->add(this); } } property_bag(const property_bag& other) = delete; property_bag& operator=(const property_bag& other) = delete; private: template<typename ArchiveT, typename T> static void archive_prop(ArchiveT& ar, property_interface* prop) { ar(cereal::make_nvp(prop->name(), *static_cast<T*>(prop))); } template<typename T> friend struct property; void add(simple_property* prop) { m_properties.insert({ prop->name(), prop }); } void add(property_bag* prop) { m_groups.push_back(prop); } std::map<const char*, simple_property*, string_compare> m_properties; std::vector<property_bag*> m_groups; }; template<typename T, bool isEnum = std::is_enum<T>::value> struct property_serialization_traits; template<typename T> struct property_serialization_traits<T, true> { using serialization_type = std::underlying_type_t<T>; static serialization_type to_serializable(const T& value) { return static_cast<serialization_type>(value); } static T from_serializable(const serialization_type& value) { return static_cast<T>(value); } static void from_stream(std::istream& stream, T& value) { serialization_type underlyingValue{}; stream >> underlyingValue; assert(!stream.fail() && "Property bag failed to convert string to value"); value = static_cast<T>(underlyingValue); } static void to_stream(std::ostream& stream, const T& value) { auto underlying = static_cast<serialization_type>(value); std::stringstream ss; stream.precision(std::numeric_limits<serialization_type>::max_digits10); stream << underlying; assert(!stream.fail() && "Property bag failed to convert value to string"); } }; template<typename T> struct property_serialization_traits<T, false> { using serialization_type = T; static serialization_type to_serializable(const T& value) { return value; } static T from_serializable(const serialization_type& value) { return value; } static void from_stream(std::istream& stream, T& value) { if (std::is_same<T, bool>()) { stream >> std::boolalpha >> value; } else { stream >> value; } assert((is_string<T>() || !stream.fail()) && "Property bag failed to convert string to value"); } static void to_stream(std::ostream& stream, const T& value) { if (std::is_same<T, bool>()) { stream << std::boolalpha << value; } else { stream.precision(std::numeric_limits<T>::max_digits10); stream << value; } assert(!stream.fail() && "Property bag failed to convert value to string"); } }; template<> struct property_serialization_traits<path, false> { using serialization_type = std::string; static serialization_type to_serializable(const path& value) { return value.string(); } static path from_serializable(const serialization_type& value) { return { value }; } static void from_stream(std::istream& stream, path& value) { stream >> value; } static void to_stream(std::ostream& stream, const path& value) { stream << value; } }; template<typename T> struct property : public serializable_property<typename property_serialization_traits<T>::serialization_type> { using traits = property_serialization_traits<T>; using type = std::decay_t<T>; property(property_bag* lookup, const char* name, const char* type, const T& defaultValue) : serializable_property<typename traits::serialization_type>{ type, name } , value{ defaultValue } { lookup->add(this); } property& operator=(const property& other) { value = other.value; return *this; } virtual void from_string(const std::string& str) override { std::stringstream ss{ str }; from_stream(ss); } virtual void from_stream(std::istream& stream) override { traits::from_stream(stream, value); } virtual void from_other(const property_interface& other) override { assert(dynamic_cast<const property<T>*>(&other) && "invalid type"); value = static_cast<const property<T>&>(other).value; } virtual std::string to_string() const override { std::stringstream ss; traits::to_stream(ss, value); return ss.str(); } operator T() const { return value; } property& operator=(const T& val) { value = val; return *this; } T value; protected: typename traits::serialization_type get_serializable() const override { return traits::to_serializable(value); } void set_serializable(const typename traits::serialization_type& val) override { value = traits::from_serializable(val); } }; template<typename T> std::ostream& operator<<(std::ostream& os, const property<T>& prop) { return os << prop.value; } } #define PROPERTY(TYPE, NAME, DEFAULT) ::mira::property<TYPE> NAME{ this, #NAME, #TYPE, DEFAULT }; #define WEIRDLY_NAMED_PROPERTY(TYPE, STRNAME, DEFAULT) \ ::mira::property<TYPE> CONCATENATE_MACRO(setting_, __COUNTER__){ this, STRNAME, #TYPE, DEFAULT }; #define BAG_PROPERTY(TYPE) TYPE TYPE{ this }; #define NAMED_BAG_PROPERTY(TYPE, NAME) TYPE NAME{ this, #NAME }; #define PROPERTYBAG(NAME, ...) \ struct NAME : public ::mira::property_bag \ { \ NAME(const NAME& other) \ : NAME{ other.name() } \ { \ from_other(other); \ } \ NAME& operator=(const NAME& other) \ { \ from_other(other); \ return *this; \ } \ NAME() \ : ::mira::property_bag{ #NAME } \ {} \ NAME(::mira::property_bag* owner) \ : ::mira::property_bag{ #NAME, owner } \ {} \ NAME(const char* name) \ : ::mira::property_bag{ name } \ {} \ NAME(::mira::property_bag* owner, const char* name) \ : ::mira::property_bag{ name, owner } \ {} \ __VA_ARGS__ \ }
{ "alphanum_fraction": 0.4726459095, "avg_line_length": 34.1204301075, "ext": "h", "hexsha": "dcd138fe3faa67501296e090fb08203bb6913d66", "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/propertybag.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/propertybag.h", "max_line_length": 133, "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/propertybag.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": 2800, "size": 15866 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C code headers for the geometric coefficients entering the response for LISA-like detectors. * */ #ifndef _LISAGEOMETRY_H #define _LISAGEOMETRY_H #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" #if defined(__cplusplus) #define complex _Complex extern "C" { #elif 0 } /* so that editors will match preceding brace */ #endif /*****************************************************/ /**************** TDI variables **********************/ typedef enum TDItag { delayO, /* Orbital delay */ y12L, /* Constellation-only response y12L */ y12, /* Complete response y12 (includes orbital delay) */ TDIXYZ, TDIalphabetagamma, TDIAETXYZ, TDIAETalphabetagamma, TDIX, TDIalpha, TDIAXYZ, TDIEXYZ, TDITXYZ, TDIAalphabetagamma, TDIEalphabetagamma, TDITalphabetagamma } TDItag; /* Enumerator to choose what level of low-f approximation to do in the response */ typedef enum ResponseApproxtag { full, lowfL, lowf } ResponseApproxtag; /**************************************************/ /************** LISAconstellation *****************/ typedef enum LISANoiseType{ LISA2010noise, LISA2017noise, LISAProposalnoise } LISANoiseType; typedef struct tagLISAconstellation { double OrbitOmega; double OrbitPhi0; double OrbitR; double ConstOmega; double ConstPhi0; double ConstL; LISANoiseType noise; } LISAconstellation; extern LISAconstellation LISAProposal; extern LISAconstellation LISA2017; extern LISAconstellation LISA2010; extern LISAconstellation slowOrbitLISA; extern LISAconstellation tinyOrbitLISA; extern LISAconstellation fastOrbitLISA; extern LISAconstellation bigOrbitLISA; /**************************************************/ /**************** Prototypes **********************/ /* Function to convert string input TDI string to TDItag */ TDItag ParseTDItag(char* string); /* Function to convert string input ResponseApprox to tag */ ResponseApproxtag ParseResponseApproxtag(char* string); /* Function cardinal sine */ double sinc(const double x); /* Compute Solar System Barycenter time tSSB from retarded time at the center of the LISA constellation tL */ /* NOTE: depends on the sky position given in SSB parameters */ double tSSBfromLframe(const LISAconstellation *variant, const double tL, const double lambdaSSB, const double betaSSB); /* Compute retarded time at the center of the LISA constellation tL from Solar System Barycenter time tSSB */ double tLfromSSBframe(const LISAconstellation *variant, const double tSSB, const double lambdaSSB, const double betaSSB); /* Convert L-frame params to SSB-frame params */ /* NOTE: no transformation of the phase -- approximant-dependence with e.g. EOBNRv2HMROM setting phiRef at fRef, and freedom in definition */ int ConvertLframeParamsToSSBframe( double* tSSB, double* lambdaSSB, double* betaSSB, double* polSSB, const double tL, const double lambdaL, const double betaL, const double psiL, const LISAconstellation *variant); /* Convert SSB-frame params to L-frame params */ /* NOTE: no transformation of the phase -- approximant-dependence with e.g. EOBNRv2HMROM setting phiRef at fRef, and freedom in definition */ int ConvertSSBframeParamsToLframe( double* tL, double* lambdaL, double* betaL, double* polL, const double tSSB, const double lambdaSSB, const double betaSSB, const double psiSSB, const LISAconstellation *variant); /* Function to compute, given a value of a sky position and polarization, all the complicated time-independent trigonometric coefficients entering the response */ void SetCoeffsG(const double lambda, const double beta, const double psi); /* Functions evaluating the G_AB functions, combining the two polarization with the spherical harmonics factors */ double complex G21mode(const LISAconstellation *LISAvariant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross); double complex G12mode(const LISAconstellation *LISAvariant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross); double complex G32mode(const LISAconstellation *LISAvariant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross); double complex G23mode(const LISAconstellation *LISAvariant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross); double complex G13mode(const LISAconstellation *LISAvariant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross); double complex G31mode(const LISAconstellation *LISAvariant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross); int EvaluateGABmode( const LISAconstellation *LISAvariant, double complex* G12, /* Output for G12 */ double complex* G21, /* Output for G21 */ double complex* G23, /* Output for G23 */ double complex* G32, /* Output for G32 */ double complex* G31, /* Output for G31 */ double complex* G13, /* Output for G13 */ const double f, /* Frequency */ const double t, /* Time */ const double complex Yfactorplus, /* Spin-weighted spherical harmonic factor for plus */ const double complex Yfactorcross, /* Spin-weighted spherical harmonic factor for cross */ const int tagdelayR, /* Tag: when 1, include the phase term of the R-delay */ const ResponseApproxtag responseapprox); /* Tag to select possible low-f approximation level in FD response */ /* Functions evaluating the Fourier-domain factors (combinations of the GAB's) for TDI observables */ /* NOTE: factors have been scaled out, in parallel of what is done for the noise function */ /* Note: in case only one channel is considered, amplitudes for channels 2 and 3 are simply set to 0 */ /* (allows minimal changes from the old structure that assumed KTV A,E,T - but probably not optimal) */ int EvaluateTDIfactor3Chan( const LISAconstellation *variant, /* Description of LISA variant */ double complex* factor1, /* Output for factor for TDI channel 1 */ double complex* factor2, /* Output for factor for TDI channel 2 */ double complex* factor3, /* Output for factor for TDI channel 3 */ const double complex G12, /* Input for G12 */ const double complex G21, /* Input for G21 */ const double complex G23, /* Input for G23 */ const double complex G32, /* Input for G32 */ const double complex G31, /* Input for G31 */ const double complex G13, /* Input for G13 */ const double f, /* Frequency */ const TDItag tditag, /* Selector for the TDI observables */ const ResponseApproxtag responseapprox); /* Tag to select possible low-f approximation level in FD response */ /* int EvaluateTDIfactor1Chan( */ /* double complex* factor, /\* Output for factor for TDI channel *\/ */ /* const double complex G12, /\* Input for G12 *\/ */ /* const double complex G21, /\* Input for G21 *\/ */ /* const double complex G23, /\* Input for G23 *\/ */ /* const double complex G32, /\* Input for G32 *\/ */ /* const double complex G31, /\* Input for G31 *\/ */ /* const double complex G13, /\* Input for G13 *\/ */ /* const double f, /\* Frequency *\/ */ /* const TDItag tditag); /\* Selector for the TDI observable *\/ */ /* Function evaluating the Fourier-domain factors that have been scaled out of TDI observables */ /* The factors scaled out, parallel what is done for the noise functions */ /* Note: in case only one channel is considered, factors for channels 2 and 3 are simply set to 0 */ int ScaledTDIfactor3Chan( const LISAconstellation *variant, /* Description of LISA variant */ double complex* factor1, /* Output for factor for TDI factor 1 */ double complex* factor2, /* Output for factor for TDI factor 2 */ double complex* factor3, /* Output for factor for TDI factor 3 */ const double f, /* Frequency */ const TDItag tditag); /* Selector for the TDI observables */ /* Function restoring the factor that have been scaled out of the TDI observables */ /* NOTE: the operation is made in-place, and the input is overwritten */ int RestoreInPlaceScaledFactorTDI( const LISAconstellation *variant, /* Description of LISA variant */ ListmodesCAmpPhaseFrequencySeries* listtdi, /* Output/Input: list of mode contributions to TDI observable */ TDItag tditag, /* Tag selecting the TDI observable */ int nchannel); /* TDI channel number */ /* Functions for the response in time domain */ /* Basic yslr observables (including orbital delay) from hplus, hcross */ double y12TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ double y21TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ double y23TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ double y32TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ double y31TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ double y13TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ /* TDI observables (including orbital delay) from hplus, hcross */ int EvaluateTDIXYZTDhphc( const LISAconstellation *variant, /* Description of LISA variant */ double* TDIX, /* Output: value of TDI observable X */ double* TDIY, /* Output: value of TDI observable Y */ double* TDIZ, /* Output: value of TDI observable Z */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ int EvaluateTDIAETXYZTDhphc( const LISAconstellation *variant, /* Description of LISA variant */ double* TDIA, /* Output: value of TDI observable X */ double* TDIE, /* Output: value of TDI observable Y */ double* TDIT, /* Output: value of TDI observable Z */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t); /* Time */ /* Generate hO orbital-delayed for one mode contribution from amp, phase */ int Generateh22TDO( const LISAconstellation *variant, /* Description of LISA variant */ AmpPhaseTimeSeries** h22tdO, /* Output: amp/phase time series for h22TDO */ gsl_spline* splineamp, /* Input spline for TD mode amplitude */ gsl_spline* splinephase, /* Input spline for TD mode phase */ gsl_interp_accel* accelamp, /* Accelerator for amp spline */ gsl_interp_accel* accelphase, /* Accelerator for phase spline */ gsl_vector* times, /* Vector of times to evaluate */ int nbptmargin); /* Margin set to 0 on both side to avoid problems with delays out of the domain */ /* Generate y12L from orbital-delayed h22 in amp/phase form */ int Generatey12LTD( const LISAconstellation *variant, /* Description of LISA variant */ RealTimeSeries** y12Ltd, /* Output: real time series for y12L */ gsl_spline* splineamp, /* Input spline for TD mode amplitude */ gsl_spline* splinephase, /* Input spline for TD mode phase */ gsl_interp_accel* accelamp, /* Accelerator for amp spline */ gsl_interp_accel* accelphase, /* Accelerator for phase spline */ gsl_vector* times, /* Vector of times to evaluate */ double Theta, /* Inclination */ double Phi, /* Phase */ int nbptmargin); /* Margin set to 0 on both side to avoid problems with delays out of the domain */ /* Generate TDI observables (including orbital delay) for one mode contritbution from amp, phase */ /* NOTE: developed for testing purposes, so far supports only dO and y12L */ int GenerateTDITD3Chanhlm( AmpPhaseTimeSeries** hlm, /* Output: real time series for TDI channel 1 */ RealTimeSeries** TDI2, /* Output: real time series for TDI channel 2 */ RealTimeSeries** TDI3, /* Output: real time series for TDI channel 3 */ gsl_spline* splineamp, /* Input spline for TD mode amplitude */ gsl_spline* splinephase, /* Input spline for TD mode phase */ gsl_interp_accel* accelamp, /* Accelerator for amp spline */ gsl_interp_accel* accelphase, /* Accelerator for phase spline */ gsl_vector* times, /* Vector of times to evaluate */ int nbptsmargin, /* Margin set to 0 on both side to avoid problems with delays out of the domain */ double theta, /* Inclination angle - used to convert hlm to hplus, hcross for y12L - ignored for dO */ double phi, /* Observer phase - used to convert hlm to hplus, hcross for y12L - ignored for dO */ TDItag tditag); /* Tag selecting the TDI observables */ /* Generate TDI observables (including orbital delay) for one mode contritbution from hplus, hcross */ int GenerateTDITD3Chanhphc( const LISAconstellation *variant, /* Description of LISA variant */ RealTimeSeries** TDI1, /* Output: real time series for TDI channel 1 */ RealTimeSeries** TDI2, /* Output: real time series for TDI channel 2 */ RealTimeSeries** TDI3, /* Output: real time series for TDI channel 3 */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ gsl_vector* times, /* Vector of times to evaluate */ int nbptsmargin, /* Margin set to 0 on both side to avoid problems with delays out of the domain */ TDItag tditag); /* Tag selecting the TDI observables */ #if 0 { /* so that editors will match succeeding brace */ #elif defined(__cplusplus) } #endif #endif /* _LISAGEOMETRY_H */
{ "alphanum_fraction": 0.6234689414, "avg_line_length": 53.3177842566, "ext": "h", "hexsha": "149e4a69607facaff56731321ca306f6dfa3265a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_path": "LISAsim/LISAgeometry.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "JohnGBaker/flare", "max_issues_repo_path": "LISAsim/LISAgeometry.h", "max_line_length": 162, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_path": "LISAsim/LISAgeometry.h", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 4140, "size": 18288 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" namespace Rendering { class AmbientLightingMaterial; class AmbientLightingDemo final : public Library::DrawableGameComponent { public: AmbientLightingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); bool AnimationEnabled() const; void SetAnimationEnabled(bool enabled); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: inline static const float RotationRate{ DirectX::XM_PI }; std::shared_ptr<AmbientLightingMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; std::uint32_t mIndexCount{ 0 }; float mModelRotationAngle{ 0.0f }; bool mAnimationEnabled{ true }; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7720970537, "avg_line_length": 28.1463414634, "ext": "h", "hexsha": "d95008d06ea422bdf876f71863d4e808885c7d99", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/3.1_Ambient_Lighting/AmbientLightingDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/3.1_Ambient_Lighting/AmbientLightingDemo.h", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/3.1_Ambient_Lighting/AmbientLightingDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 291, "size": 1154 }
/* * Gsl_blas_ddot: test gsl_blas_ddot (vector . vector) * * Copyright (c) 2012 Jérémie Decock * * Required: GSL library (libgsl0-dev) * Usage: gcc gsl_blas_ddot.c -lgsl -lgslcblas -lm * or: gcc gsl_blas_ddot.c $(pkg-config --libs gsl) */ #include <stdio.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> int main (void) { gsl_vector * v1 = gsl_vector_alloc(3); gsl_vector * v2 = gsl_vector_alloc(3); gsl_vector_set_all(v1, 3.0); gsl_vector_set_all(v2, 2.0); double r; gsl_blas_ddot(v1, v2, &r); printf("%f\n", r); gsl_vector_free(v1); gsl_vector_free(v2); return 0; }
{ "alphanum_fraction": 0.6426332288, "avg_line_length": 18.7647058824, "ext": "c", "hexsha": "133bbf2a5e2afa441861d821436d94dae070872b", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_path": "c/gsl/blas/gsl_blas_ddot.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_path": "c/gsl/blas/gsl_blas_ddot.c", "max_line_length": 54, "max_stars_count": 23, "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_path": "c/gsl/blas/gsl_blas_ddot.c", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "num_tokens": 220, "size": 638 }
#ifndef __DUMMY_H__ #define __DUMMY_H__ #include<stdio.h> //#define NDEBUG #include<stdint.h> #include<omp.h> #include<float.h> #include<assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <math.h> #include<string.h> #include<dirent.h> #include<sys/stat.h> #include<sys/param.h> #include<sys/types.h> #include<signal.h> //GSL library #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> #include<gsl/gsl_matrix.h> #include <utility> #include <string> #include <iostream> #include<iterator> #include<map> #include<vector> #include <cctype> #include<algorithm> using namespace std ; const uint32_t loop_max=400; uint32_t loop=0; const double epsilon= 0.05; //error associated with user variable ! const double epsilon_m= 0.000001; //error associated with user variable ! const double epsilon_phi= 0.000001; //error associated with user variable ! const double epsilon_theta= 0.000001; //error associated with user variable ! const double lower_limit_theta= 0.0000000000001; const double lower_limit_m = 0.0000000000001; const double lower_limit_phi = 0.00000000001; clock_t start; clock_t end; gsl_rng *rand_obj ; double maxima_phi_i_possible=0.00000000000000000000000000000000000001; double log_Fx_maxima_phi_i_possible=-DBL_MAX; //double * diversity; uint32_t *freq_single_den; // freqency of theta_w in denominator typedef struct { bool* word_caps; // keeps tag if word at this pos was bool* comma_present_before; bool* period_present_before; vector<string> word_list ; uint32_t *int_word_list ; // Its an array to words uint32_t *topic_usage; int real_word_count ; //Number of words in document int true_label ; int sampled_label; uint8_t *topic_list ; //Topic associated with each word char* document_name ; bool* priority_flag ; bool hasPriorityWord; int mygamma; }document ; document *d_ptr ; //Number of topics defined in begining int updated_doc=0 ; //GIBBS samples count // int gibbs_counter=0; const int gibbs_sample_count =25 ; double *M_gibbs ; double *THETA_gibbs ; double *PHI_gibbs ; const double log_ratio=log(1000); #define topic_count 5 // 1 to 30 ! #define document_count 790 #define total_words_count 10000 double *M ; double *THETA ; double *PHI; //File names const char* M_file="M.bin"; const char* M_IJ_CW_file="m_ij_cw.bin"; const char* THETA_file="THETA.bin"; const char* PHI_file="PHI.bin"; const char* TOPIC_file="topics_list.bin"; //For keeping last maxima , this will speed up search double *last_maxima_theta_iw; double *last_maxima_m_ij; double *last_maxima_phi ; //Thread info const int m_thread_cnt=4; const int theta_thread_cnt=8; //Priors const double m_diag=1; const double m_nondiag=1; const double m_beta=1; const double theta_k=1; const double theta_beta=1; /* double phi_sigma_square=10000; */ double phi_sigma_square=1; double phi_mu=0; //FUNCTIONS //INIT functions void init(); //wrapper for all the inits void init_model_parameters() ; //Inits model params void init_document_params(); //INIT document structure void init_variables(); void init_topic_assignment(document* current_doc); void test_model(); void free_things(); //Topic update for each document inline void update_topic_usage(document* current_doc_ptr, const uint8_t new_topic,const int old_topic ); void topic_update(document* current_doc_ptr); void update_TOPIC(); double get_factor12(const uint32_t word_curr,const int word_next,const uint8_t t_prime,const int t_last,const int t_next,document* doc,const uint32_t mypos); inline double get_factor2_t_i(document* current_doc_ptr, double sum); double get_current_sum(document* doc,const uint32_t N_d, int sz); inline void scale_pdf(double* pdf ,const int size,double sum ); inline void make_cdf_from_pdf(double* pdf ,double* cdf , const int size ); void update_m_i_j_count_word(const uint32_t word_curr,const int word_next,const int t_prime,const int t_last,const int t_next,document* doc,const int mypos); //update m_i_j void update_M(); void update_m_ij(const int row,const int col,double * sum_den,uint32_t* freq_den,uint32_t* freq_num); void get_max_f_m_ij(const uint8_t i, const uint8_t j,double*log_F_max,double* maxima,double*sum_den,uint32_t*freq_den,uint32_t* freq_num,double *maxima_possible,double *value_possible); double evaluate_m_ij_ll(double x0,const uint8_t i,const uint8_t j,double* sum_den,uint32_t* freq_den,uint32_t* freq_num,double *max, double* val_at_maxi); void m_compute_double_term_word_stat(const uint8_t i,double* sum_den ,uint32_t* freq_den,uint32_t* freq_num_i); //UPDATE THETA matrix void update_THETA(); void update_theta_iw(const uint8_t i, const uint32_t w,double* den_single_term_header,double* sum_den,uint32_t * freq_den,const int freq_single_num); void get_max_f_theta_iw(const uint8_t i, const uint32_t w,double* log_Fx,double* maxima,const uint32_t freq_single_den_w); double evaluate_theta_iw_ll(double x0,const uint8_t i,const uint32_t w,const double den_single_term_header,double * sum_den,uint32_t * freq_den,const uint32_t freq_single_num,uint32_t* freq_num,const uint32_t freq_single_den_w,double *maxima_theta_iw_possible,double *log_Fx_maxima_theta_iw_possible); double get_den_theta_jw(const uint8_t j , const uint32_t w); double compute_theta_single_term_denominator(const uint32_t w ); void theta_compute_double_term_word_stat(const uint32_t w,double* theta_double_term_sum_den,uint32_t* theta_double_term_freq_den,uint32_t* freq_single_num_w,uint32_t* freq_double_num); //Common codes double inline get_number_between_two_numbers(double low, double high); inline double rand_0_1(); void ctrl_c_handler(int single_num); void write_model(); double timetaken(clock_t start,clock_t end , const char* mesaage); double gamma_approx_sampler(double r,double log_F_max,double log_f_r,double maxima); void guess_lebel(document* current_doc_ptr); double m_diagonistics(const int i,const int j,double* sum_den,uint32_t* freq_den,uint32_t* freq_num ,double* possible_maxima ,double * value_possible,const char*msg ,double maxima=-1); double theta_diagonistics(const int i, const int w, const double den_single_term_header,double * sum_den,uint32_t* freq_den,const uint32_t freq_single_num,uint32_t * freq_num,const uint32_t freq_single_den_w,double *maxima1,double * val_at_max1,const char*msg,double maxima=-1) ; int linear_scan(double*cdf , const int size,double data); void load_model_params(); void load_topics(); //update PHI double evaluate_phi_i(const double x0,const uint8_t i ); void update_PHI(); void get_max_f_phi_i(const uint8_t i, double* log_Fx,double* maxima ) ; // calculate maximum of function of log ! void print_topic_corpus(); void print_model_params(); void print_system_config(); void reset_topic_usage(); uint32_t get_key_3D_m(int x,int y,int z,int x_size,int y_size); void print_time(); void init_gibbs_params(); void write_model_gibbs(); void do_gibbs_expectation(); const string highlight_tag_start="<:t:>"; const string highlight_tag_end="<:/t:>"; const string comma=","; const string period="."; void make_word_id(string word); std::map<string , int > word_id_map; std::map<int , string > id_word_map; string get_word_from_id(int id); int get_id_from_word(string word); //while we read document we will silently populate this map for furtehr uses ! void create_word_id_id_word_map(string word); //Makes word of document string make_lowercase_string(string word); void make_int_words(document* doc,vector<string>& word_list ); bool doesWordStartsUpper(string data); bool isThisDocumentUnderLined(string name); vector<string> dictionary; const char* dict_file="/data1/rahul/projects/text_mining/branch/punctuation/chris_data/word_list.txt" ; const char* data="/data1/rahul/projects/text_mining/branch/punctuation/chris_data/AD"; //const char* dict_file="/home/rkumar2/final_test/data/word_list.txt" ; //const char* data="/home/rkumar2/final_test/data/AE"; void make_Dictionary(); void inline set_d_2D_m(double *ptr,int row,int col,double value,int row_length); double inline get_d_2D_m(double* ptr,int row,int col,int row_length); void set_i_3D_m(uint32_t *ptr,int x,int y,int z,int value,int y_size,int z_size); void inline set_i_2D_m(uint32_t *ptr,int row,int col,int value,int row_length); uint32_t inline get_i_2D_m(uint32_t* ptr,int row,int col,int row_length); #endif
{ "alphanum_fraction": 0.7880434783, "avg_line_length": 37.1228070175, "ext": "h", "hexsha": "5db466b9fcfdfb379ada71f3ee7469c1b0381b57", "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": "6415097bf3259d9315741787d1ccdc11be2560d3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rahul0/JBI", "max_forks_repo_path": "models/1a/1a.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6415097bf3259d9315741787d1ccdc11be2560d3", "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": "rahul0/JBI", "max_issues_repo_path": "models/1a/1a.h", "max_line_length": 302, "max_stars_count": null, "max_stars_repo_head_hexsha": "6415097bf3259d9315741787d1ccdc11be2560d3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rahul0/JBI", "max_stars_repo_path": "models/1a/1a.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2245, "size": 8464 }
#pragma once #include <functional> #include <gsl/gsl_util> #include <vector> struct Executor; namespace detail { Executor*& get_current_executor_holder(); } struct Executor { using WorkQueue = std::vector<std::function<void()>>; void add_work(std::function<void()> fn) { work_.emplace_back(std::move(fn)); } void execute() { const auto cleanup = gsl::finally([&] { // detail::get_current_executor_holder() = nullptr; }); detail::get_current_executor_holder() = this; while (not work_.empty()) { auto pending_work = WorkQueue{}; swap(pending_work, work_); for (auto&& fn : pending_work) { fn(); } } } WorkQueue work_; }; inline Executor& get_current_executor() { return *detail::get_current_executor_holder(); }
{ "alphanum_fraction": 0.6351351351, "avg_line_length": 20.35, "ext": "h", "hexsha": "6e17f689b9b78d312ec3dd41a7e7bc0fcf9bbeda", "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": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_forks_repo_path": "mixed/src/executor.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "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": "adrianimboden/cppusergroup-adynchronous-programming", "max_issues_repo_path": "mixed/src/executor.h", "max_line_length": 65, "max_stars_count": null, "max_stars_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "adrianimboden/cppusergroup-adynchronous-programming", "max_stars_repo_path": "mixed/src/executor.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 187, "size": 814 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /* * ===================================================================================== * * Filename: Reg_sc.c * * Description: * * Version: 1.0 * Created: 21/04/2014 12:27:24 * Revision: none * Compiler: gcc * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * ===================================================================================== */ /* Re g_sc is made of 4 integrands: 2 with principal values and 2 without. The common factor function is k_func = alpha*k*exp(-k/omega_c)/tanh(b*k/2) The poles are in (omega1-O) and (omega1+O) The sign of the four fractions 1/(k+(omega1+O)) , 1/(k+(omega1-O)) , 1/(k-(omega1-O)) , 1/(k-(omega1+O)) are + , - , + , - */ #include <stdio.h> #include "funcs.h" #include <gsl/gsl_integration.h> /* * === FUNCTION ====================================================================== * Name: k_func * Description: Common integrand factor * ===================================================================================== */ double k_func ( double k, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1, alpha ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; alpha = pars->alpha ; double temp = alpha*k*exp(-k/o_c) ; double val = temp/tanh(b*k/2) ; return val; } /* ----- end of function k_func ----- */ /* * === FUNCTION ====================================================================== * Name: k_func_1 * Description: First integrand: k_func/(k+(omega1+O)) * ===================================================================================== */ double k_func_1 ( double k, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; /* Invoking k_func and returning value */ double v , v1 ; v = k_func( k, pars ) ; v1 = v/(k+(o_1+O)) ; return v1 ; } /* ----- end of function k_func_1 ----- */ /* * === FUNCTION ====================================================================== * Name: first_int * Description: Integrating k_func/(k+(omega1+O)) * ===================================================================================== */ int first_int ( double* val, double* error, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; /* Allocating workspace for integration */ gsl_integration_workspace* first_int_ws = gsl_integration_workspace_alloc(WS_SZ) ; gsl_function F ; F.function = &k_func_1 ; F.params = pars ; /* Integration over (0,+Infinity) */ double res, err ; int status = gsl_integration_qagiu( &F, 0, 1e-9, 1e-3, WS_SZ, first_int_ws, &res, &err ) ; *val = res ; *error = err ; gsl_integration_workspace_free(first_int_ws) ; return status; } /* ----- end of function first_int ----- */ /* * FUNCTION * Name: k_func_2 * Description: Second integrand: k_func/(k+omega1-O) * */ double k_func_2 ( double k , void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; /* Invoking k_func and returning value */ double v, v2 ; v = k_func( k, pars ) ; v2 = v/(k+(o_1-O)) ; return v2; } /* ----- end of function k_func_2 ----- */ /* * FUNCTION * Name: second_int * Description: Integration k_func/(k+(omega1-O)) * */ int second_int ( double* val, double* error, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; /* Allocating workspace for integration */ gsl_integration_workspace* second_int_ws = gsl_integration_workspace_alloc(WS_SZ) ; gsl_function F; F.function = &k_func_2 ; F.params = pars ; double res, err ; int status = gsl_integration_qagiu( &F, 0, 1e-9, 1e-3, WS_SZ, second_int_ws, &res, &err ) ; *val = res ; *error = err ; gsl_integration_workspace_free(second_int_ws) ; return status; } /* ----- end of function second_int ----- */ /* * FUNCTION * Name: k_func_3 * Description: k_func/(k-(omega1-O)) to be integrated on the tail +inf * */ double k_func_3 ( double k, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; double temp , val ; temp = k_func( k, pars ) ; val = temp/(k-(o_1-O)) ; return val; } /* ----- end of function k_func_3 ----- */ /* * FUNCTION * Name: third_int * Description: Integration of the p.v. k_func/(k-(omega1-O)) * */ int third_int ( double* val, double* err, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; /* Integration of the p.v. */ gsl_function F ; F.function = &k_func ; F.params = pars ; gsl_integration_workspace* third_int_ws = gsl_integration_workspace_alloc(WS_SZ) ; double v1 , err1 ; int status1 = gsl_integration_qawc( &F, (o_1-O)/2, 3*(o_1-O)/2, o_1-O, 1e-9, 1e-3, WS_SZ, third_int_ws, &v1, &err1 ) ; gsl_integration_workspace_free(third_int_ws) ; /* Integration to +infinity */ gsl_function G ; G.function = &k_func_3 ; G.params = pars ; gsl_integration_workspace* third_int_ws_2 = gsl_integration_workspace_alloc(WS_SZ) ; double v2, err2 ; int status2 = gsl_integration_qagiu( &G, 3*(o_1-O)/2, 1e-9, 1e-3, WS_SZ, third_int_ws_2, &v2, &err2 ) ; gsl_integration_workspace_free(third_int_ws_2) ; /* Integration on ( 0, (o_1-O)/2 ) */ gsl_integration_workspace* third_int_ws_3 = gsl_integration_workspace_alloc(WS_SZ) ; gsl_function H ; H.function = &k_func_3 ; H.params = pars ; double v3, err3 ; int status3 = gsl_integration_qag( &H, 0, (o_1-O)/2, 1e-9, 1e-3, WS_SZ, 6, third_int_ws_3, &v3, &err3 ) ; gsl_integration_workspace_free(third_int_ws_3) ; *val = v1 + v2 + v3 ; *err = err1 + err2 + err3 ; return status1 + status2 + status3 ; } /* ----- end of function third_int ----- */ /* * FUNCTION * Name: k_func_4 * Description: k_func/(k-(omega1+O)) * */ double k_func_4 ( double k, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; double temp , val ; temp = k_func( k, pars ) ; val = temp/(k-(o_1+O)) ; return val; } /* ----- end of function k_func_4 ----- */ /* * FUNCTION * Name: fourth_integ * Description: Integration of the p.v. kfunc/(k-(omega1+O)) * */ int fourth_int ( double* val, double* err, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; /* Integration of the p.v. */ gsl_function F ; F.function = &k_func ; F.params = pars ; gsl_integration_workspace* fourth_int_ws = gsl_integration_workspace_alloc(WS_SZ) ; double v1 , err1 ; int status1 = gsl_integration_qawc( &F, (o_1+O)/2, 3*(o_1+O)/2, o_1+O, 1e-9, 1e-3, WS_SZ, fourth_int_ws, &v1, &err1 ) ; gsl_integration_workspace_free(fourth_int_ws) ; /* Integration to +infinity */ gsl_function G ; G.function = &k_func_4 ; G.params = pars ; gsl_integration_workspace* fourth_int_ws_2 = gsl_integration_workspace_alloc(WS_SZ) ; double v2, err2 ; int status2 = gsl_integration_qagiu( &G, 3*(o_1+O)/2, 1e-9, 1e-3, WS_SZ, fourth_int_ws_2, &v2, &err2 ) ; gsl_integration_workspace_free(fourth_int_ws_2) ; /* Integration on ( 0 , (O+o_1)/2 ) */ gsl_integration_workspace* fourth_int_ws_3 = gsl_integration_workspace_alloc(WS_SZ) ; gsl_function K ; K.function = &k_func_4 ; K.params = pars ; double v3, err3 ; int status3 = gsl_integration_qag( &K, 0, (O+o_1)/2, 1e-9, 1e-3, WS_SZ, GSL_INTEG_GAUSS61, fourth_int_ws_3, &v3, &err3 ) ; gsl_integration_workspace_free(fourth_int_ws_3) ; *val = v1 + v2 + v3 ; *err = err1 + err2 + err3 ; return status1 + status2 + status3; } /* ----- end of function fourth_integ ----- */ /* * FUNCTION * Name: re_gsc * Description: * */ int re_gsc ( double* result, double* error, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; double v1, v2, v3, v4, err1, err2, err3, err4 ; int status = first_int( &v1, &err1, pars ) + second_int( &v2, &err2, pars ) + third_int( &v3, &err3, pars ) + fourth_int( &v4, &err4, pars ) ; *result = -(v1 - v2 + v3 - v4)/4.0 ; *error = (err1 + err2 + err3 + err4)/4.0 ; return status; } /* ----- end of function re_gsc ----- */ /* * FUNCTION * Name: re_gcs * Description: Re g_cs is the same of Re g_sc but with O and o_1 exchanged. * Therefore the signs are * * + , + , - , - * */ int re_gcs ( double* result, double* error, void* params ) { /* Copying parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p( pars, &o_c, &b, &O, &o_1 ) ; double v1, v2, v3, v4, err1, err2, err3, err4 ; int status = first_int( &v1, &err1, pars ) + second_int( &v2, &err2, pars ) + third_int( &v3, &err3, pars ) + fourth_int( &v4, &err4, pars ) ; *result = -(v1 + v2 - v3 - v4)/4 ; *error = (err1 + err2 + err3 + err4)/4 ; return status; } /* ----- end of function re_gcs ----- */
{ "alphanum_fraction": 0.5981824661, "avg_line_length": 27.5098039216, "ext": "c", "hexsha": "1dfac77b736d30a78678934d3e1cfc5e14aec906", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "Reg_sc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "Reg_sc.c", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "Reg_sc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3450, "size": 11224 }
/* * GSLIntegrator.h * * Created on: 6 cze 2020 * Author: tomhof */ #ifndef SRC_GSLINTEGRATOR_H_ #define SRC_GSLINTEGRATOR_H_ #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_plain.h> #include <gsl/gsl_monte_miser.h> #include <gsl/gsl_monte_vegas.h> class GSLIntegrator { private: size_t calls = 50000; public: GSLIntegrator(); virtual ~GSLIntegrator(); double integrate(double (*f)(double * x_array, size_t dim, void * params), double a1, double b1, double a2, double b2, double* int_err); void display_results(char *title, double result, double error); size_t getCalls() const { return calls; } void setCalls(size_t calls = 50000) { this->calls = calls; } }; #endif /* SRC_GSLINTEGRATOR_H_ */
{ "alphanum_fraction": 0.7098844673, "avg_line_length": 21.0540540541, "ext": "h", "hexsha": "d24de5aad7309fdd6125da094391f6c7d8a70393", "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": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "tomaszhof/interval_arithmetic", "max_forks_repo_path": "NakaoMethod/src/GSLIntegrator.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "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": "tomaszhof/interval_arithmetic", "max_issues_repo_path": "NakaoMethod/src/GSLIntegrator.h", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "0d1e7c842803f8ca211bf2a9d7239f7541452492", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "tomaszhof/interval_arithmetic", "max_stars_repo_path": "NakaoMethod/src/GSLIntegrator.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 236, "size": 779 }
#pragma once #include <gsl/gsl_sf_zeta.h> #include <cmath> double real_trigamma_cmplxarg(double x, double y, int m, int l){ //compute the real part of the trigamma function at z = x + iy using //my accelerated series formula //argument should have positive real part (x > 0) //m gives the number of zeta function terms to use //l gives the number of terms to use in the residual series double result = 0; //if x is small, the result will be large and thus, inaccurate. Use the //polygamma shift formula to give a larger value of x for the computation if(x < 1000){ return ((x*x - y*y)/(x*x + y*y)/(x*x + y*y)) + real_trigamma_cmplxarg(x + 1, y, m, l); } else{ double phase, ypow = 1.0, xpow, denom; //compute finite sum of Hurwitz zeta functions for (int i = 1; i < m; ++i){ phase = 2*(i/2) == i ? -1.0 : 1.0; result += phase*(2*i - 1)*ypow*gsl_sf_hzeta(2*i, x); ypow = ypow*y*y; } //compute the infinite sum of residuals phase = 2*(m/2) == m ? 1.0 : -1.0; for (int n = 0; n < l; ++n){ xpow = pow(x + n, 2*m); denom = ((x + n)*(x + n) + y*y)*((x + n)*(x + n) + y*y); result += phase*ypow*((2*m - 1)*y*y + (2*m + 1)*(x + n)*(x + n)) / xpow / denom; } return result; } }
{ "alphanum_fraction": 0.5357142857, "avg_line_length": 38.1111111111, "ext": "h", "hexsha": "b676ff5973f69a2e2ef80da02a3b644b0127086b", "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": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "butchertx/spin_boson_mc", "max_forks_repo_path": "lib/cmplx_math.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "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": "butchertx/spin_boson_mc", "max_issues_repo_path": "lib/cmplx_math.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "butchertx/spin_boson_mc", "max_stars_repo_path": "lib/cmplx_math.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 446, "size": 1372 }
/* linalg/invtri.c * * Copyright (C) 2016, 2017, 2018, 2019 Patrick Alken * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This source is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This module contains code to invert triangular matrices */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include "recurse.h" static int triangular_inverse_L2(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * T); static int triangular_inverse_L3(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * T); static int triangular_singular(const gsl_matrix * T); int gsl_linalg_tri_invert(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { int status; status = triangular_singular(T); if (status) return status; return triangular_inverse_L3(Uplo, Diag, T); } } /* triangular_inverse_L2() Invert a triangular matrix T Inputs: Uplo - CblasUpper or CblasLower Diag - unit triangular? T - on output the upper (or lower) part of T is replaced by its inverse Return: success/error Notes: 1) Based on LAPACK routine DTRTI2 using Level 2 BLAS */ static int triangular_inverse_L2(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { gsl_matrix_view m; gsl_vector_view v; size_t i; if (Uplo == CblasUpper) { for (i = 0; i < N; ++i) { double aii; if (Diag == CblasNonUnit) { double *Tii = gsl_matrix_ptr(T, i, i); *Tii = 1.0 / *Tii; aii = -(*Tii); } else { aii = -1.0; } if (i > 0) { m = gsl_matrix_submatrix(T, 0, 0, i, i); v = gsl_matrix_subcolumn(T, i, 0, i); gsl_blas_dtrmv(CblasUpper, CblasNoTrans, Diag, &m.matrix, &v.vector); gsl_blas_dscal(aii, &v.vector); } } /* for (i = 0; i < N; ++i) */ } else { for (i = 0; i < N; ++i) { double ajj; size_t j = N - i - 1; if (Diag == CblasNonUnit) { double *Tjj = gsl_matrix_ptr(T, j, j); *Tjj = 1.0 / *Tjj; ajj = -(*Tjj); } else { ajj = -1.0; } if (j < N - 1) { m = gsl_matrix_submatrix(T, j + 1, j + 1, N - j - 1, N - j - 1); v = gsl_matrix_subcolumn(T, j, j + 1, N - j - 1); gsl_blas_dtrmv(CblasLower, CblasNoTrans, Diag, &m.matrix, &v.vector); gsl_blas_dscal(ajj, &v.vector); } } /* for (i = 0; i < N; ++i) */ } return GSL_SUCCESS; } } /* triangular_inverse_L3() Invert a triangular matrix T Inputs: Uplo - CblasUpper or CblasLower Diag - unit triangular? T - on output the upper (or lower) part of T is replaced by its inverse Return: success/error Notes: 1) Based on ReLAPACK routine DTRTRI using Level 3 BLAS */ static int triangular_inverse_L3(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N <= CROSSOVER_INVTRI) { /* use Level 2 BLAS code */ return triangular_inverse_L2(Uplo, Diag, T); } else { /* * partition matrix: * * T11 T12 * T21 T22 * * where T11 is N1-by-N1 */ int status; const size_t N1 = GSL_LINALG_SPLIT(N); const size_t N2 = N - N1; gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1); gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2); gsl_matrix_view T21 = gsl_matrix_submatrix(T, N1, 0, N2, N1); gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2); /* recursion on T11 */ status = triangular_inverse_L3(Uplo, Diag, &T11.matrix); if (status) return status; if (Uplo == CblasLower) { /* T21 = - T21 * T11 */ gsl_blas_dtrmm(CblasRight, Uplo, CblasNoTrans, Diag, -1.0, &T11.matrix, &T21.matrix); /* T21 = T22 * T21^{-1} */ gsl_blas_dtrsm(CblasLeft, Uplo, CblasNoTrans, Diag, 1.0, &T22.matrix, &T21.matrix); } else { /* T12 = - T11 * T12 */ gsl_blas_dtrmm(CblasLeft, Uplo, CblasNoTrans, Diag, -1.0, &T11.matrix, &T12.matrix); /* T12 = T12 * T22^{-1} */ gsl_blas_dtrsm(CblasRight, Uplo, CblasNoTrans, Diag, 1.0, &T22.matrix, &T12.matrix); } /* recursion on T22 */ status = triangular_inverse_L3(Uplo, Diag, &T22.matrix); if (status) return status; return GSL_SUCCESS; } } static int triangular_singular(const gsl_matrix * T) { size_t i; for (i = 0; i < T->size1; ++i) { double Tii = gsl_matrix_get(T, i, i); if (Tii == 0.0) return GSL_ESING; } return GSL_SUCCESS; } #ifndef GSL_DISABLE_DEPRECATED int gsl_linalg_tri_upper_invert(gsl_matrix * T) { int status = triangular_singular(T); if (status) return status; return triangular_inverse_L3(CblasUpper, CblasNonUnit, T); } int gsl_linalg_tri_lower_invert(gsl_matrix * T) { int status = triangular_singular(T); if (status) return status; return triangular_inverse_L3(CblasLower, CblasNonUnit, T); } int gsl_linalg_tri_upper_unit_invert(gsl_matrix * T) { int status = triangular_singular(T); if (status) return status; return triangular_inverse_L3(CblasUpper, CblasUnit, T); } int gsl_linalg_tri_lower_unit_invert(gsl_matrix * T) { int status = triangular_singular(T); if (status) return status; return triangular_inverse_L3(CblasLower, CblasUnit, T); } #endif
{ "alphanum_fraction": 0.5645206635, "avg_line_length": 24.615916955, "ext": "c", "hexsha": "e3e5dd300624a102ecead005140a8ff07f941782", "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/linalg/invtri.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/linalg/invtri.c", "max_line_length": 95, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/linalg/invtri.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": 2051, "size": 7114 }
/* * C functions for the NIG marginal distribution. * * This file is part of Fieldosophy, a toolkit for random fields. * * Copyright (C) 2021 Anders Gunnar Felix Hildeman <fieldosophySPDEC@gmail.com> * * This Source Code is subject to the terms of the BSD 3-Clause License. * If a copy of the license was not distributed with this file, you can obtain one at https://opensource.org/licenses/BSD-3-Clause. * * * Author: Anders Gunnar Felix Hildeman * Date: 2020-04 */ #include <stdio.h> #include <string.h> #include <math.h> #include <omp.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> extern "C" { // Make sure that alpha tilde is not too large void NIG_filterParams( double *pAlphaTilde, double *pBetaTilde) { if (*pAlphaTilde > 100.0d) { *pBetaTilde = *pBetaTilde * ( 100.0d / (*pAlphaTilde) ); *pAlphaTilde = 100.0d; } return; } // Modified Bessel function of the second kind double Kv(const int v, const double x) { double lOut = 0.0d; int status; gsl_sf_result result; switch(v) { case 0: status = gsl_sf_bessel_K0_e(x, &result); break; case 1: status = gsl_sf_bessel_K1_e(x, &result); break; default: status = gsl_sf_bessel_Kn_e(v, x, &result); break; } // If some kind of error if (status != 0) { //printf("Error code: %d in Kv", status); lOut = GSL_NAN; } else { lOut = result.val; } return lOut; } // Logarithm of modified Bessel function of second kind double lKv(const int v, const double x) { double lOut = Kv( v, x ); // Logarithmize lOut = log( lOut ); return lOut; } // logarithm of PDF for NIG distribution unsigned int NIG_lpdf( double * const pX, const unsigned int pN, const double alphaTilde, const double betaTilde, const double mu, const double delta ) { // turn off gsl error handler gsl_set_error_handler_off(); // Loop through each element in vector #pragma omp parallel for for ( unsigned int iter = 0; iter < pN; iter++) { // Get normalized data value const double lCur = (pX[iter] - mu) / delta; // Compute q function const double lQ = sqrt( (1.0d + lCur * lCur) ); // Compute bessel function const double lLogK = lKv(1, alphaTilde * lQ); // compute log pdf double lCurOut = lLogK; lCurOut -= log(lQ); lCurOut += betaTilde * lCur; // Add constants lCurOut += log( alphaTilde / M_PI ) + sqrt( alphaTilde * alphaTilde - betaTilde * betaTilde ); lCurOut -= log(delta); // Store full log pdf pX[iter] = lCurOut; } return pN; } // Compute log-likelihood double NIG_logLikelihood( double * lOut, const double * const pX, const unsigned int pN, const double alphaTilde, const double betaTilde, const double mu, const double delta ) { // Copy content memcpy( lOut, pX, sizeof(double) * pN ); // Compute log-pdf NIG_lpdf( lOut, pN, alphaTilde, betaTilde, mu, delta ); // Sum double lSum = 0.0d; for (unsigned int iter = 0; iter < pN; iter++) { lSum += lOut[iter]; } return lSum; } // EM-algorithm for finding MLE of NIG unsigned int NIG_MLE( double * const pLogLik, double * const pX, const unsigned int pN, double * const pAlphaTilde, double * const pBetaTilde, double * const pMu, double * const pDelta, const double pXBar, const unsigned int pM, const double pTol ) { // turn off gsl error handler gsl_set_error_handler_off(); // Init double lAlphaTilde = *pAlphaTilde; double lBetaTilde = *pBetaTilde; double lMu = *pMu; double lDelta = *pDelta; // Filter tilde parameters NIG_filterParams( &lAlphaTilde, &lBetaTilde); // Preallocate arrays double * lTempArray1 = (double*) malloc(sizeof(double) * pN); double * lTempArray2 = (double*) malloc(sizeof(double) * pN); if (lTempArray1 == NULL || lTempArray2 == NULL) return 1; // Compute log-likelihood *pLogLik = NIG_logLikelihood( lTempArray1, pX, pN, lAlphaTilde, lBetaTilde, lMu, lDelta ); // If likelihood is bad if (isnan(*pLogLik)) return 1; // Iterate EM-algorithm for (unsigned int iter = 0; iter < pM; iter++) { // --- E-step --- double lSBar = 0.0d; double lWBar = 0.0d; #pragma omp parallel for reduction(+:lSBar) reduction(+:lWBar) for (unsigned int iter2 = 0; iter2 < pN; iter2++) { const double lPhiSqrt = sqrt( 1.0d + ( (pX[iter2]-lMu)/lDelta ) * ( (pX[iter2]-lMu)/lDelta ) ); // compute besselk function values const double lK0 = Kv( 0, lAlphaTilde * lPhiSqrt ); const double lK1 = Kv( 1, lAlphaTilde * lPhiSqrt ); const double lK2 = Kv( 2, lAlphaTilde * lPhiSqrt ); // Compute pseudo values lTempArray1[iter2] = ( lDelta * lPhiSqrt * lK0 ) / ( (lAlphaTilde * lK1) / lDelta ); // S lTempArray2[iter2] = ( (lAlphaTilde * lK2) / lDelta ) / ( lDelta * lPhiSqrt * lK1 ); // W lSBar += lTempArray1[iter2]; lWBar += lTempArray2[iter2]; } lSBar /= ((double)pN); lWBar /= ((double)pN); // --- M-step --- // Compute delta lDelta = sqrt( 1.0d / ( lWBar - (1.0d / lSBar) ) ); double lGamma = lDelta / lSBar; // Compute beta double lBeta = 0.0d; for (unsigned int iter2 = 0; iter2 < pN; iter2++) { lBeta += pX[iter2] * lTempArray2[iter2]; } lBeta = lBeta - pXBar * lWBar * ((double)pN); lBeta /= ( (double)pN - lSBar * lWBar * ((double)pN) ); lBetaTilde = lBeta * lDelta; // Compute alpha double lAlpha = sqrt( lGamma * lGamma + lBeta * lBeta ); lAlphaTilde = lAlpha * lDelta; // Filter tilde values NIG_filterParams( &lAlphaTilde, &lBetaTilde); lGamma = sqrt( lAlphaTilde * lAlphaTilde - lBetaTilde * lBetaTilde ) / lDelta; // Compute mu lMu = pXBar - lBetaTilde / lGamma; // Compute loglik const double llLikNew = NIG_logLikelihood( lTempArray1, pX, pN, lAlphaTilde, lBetaTilde, lMu, lDelta ); // If likelihood is bad if (isnan(llLikNew)) return(iter+2); // Mark that likelihood went bad during iterations // Compute likelihood difference const double lLLikDiff = llLikNew - *pLogLik; // If new likelihood is higher if (lLLikDiff > 0) { // Set new log-likelihood as old one *pLogLik = llLikNew; // Update output parameters *pAlphaTilde = lAlphaTilde; *pBetaTilde = lBetaTilde; *pMu = lMu; *pDelta = lDelta; // If should break due to tolerance if ( lLLikDiff < pTol ) break; } } // end of EM-iterations // Free allocated arrays free(lTempArray1); free(lTempArray2); // Return no problem return( 0 ); } }
{ "alphanum_fraction": 0.4943912129, "avg_line_length": 31.9328358209, "ext": "c", "hexsha": "f7f52d63ecf8a94df1cf3be48ab5b41ab6811197", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:49:02.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-27T11:49:02.000Z", "max_forks_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "andyGFHill/fieldosophy", "max_forks_repo_path": "fieldosophy/src/marginal/NIG.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "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": "andyGFHill/fieldosophy", "max_issues_repo_path": "fieldosophy/src/marginal/NIG.c", "max_line_length": 179, "max_stars_count": 3, "max_stars_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "andyGFHill/fieldosophy", "max_stars_repo_path": "fieldosophy/src/marginal/NIG.c", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:24:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-03T10:07:08.000Z", "num_tokens": 2242, "size": 8558 }
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpRNG.h> #include <gbpMCMC.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_interp.h> void init_MCMC_arrays(MCMC_info *MCMC) { int i_DS; MCMC_DS_info *current_DS; MCMC_DS_info *next_DS; if(MCMC->n_M == NULL) { SID_log("Initializing MCMC target arrays for %d dataset(s)...", SID_LOG_OPEN, MCMC->n_DS); // Initialize chain arrays MCMC->n_M = (int *)SID_malloc(sizeof(int) * MCMC->n_DS); MCMC->M_new = (double **)SID_malloc(sizeof(double *) * MCMC->n_DS); MCMC->M_last = (double **)SID_malloc(sizeof(double *) * MCMC->n_DS); MCMC->n_M_total = 0; i_DS = 0; current_DS = MCMC->DS; while(current_DS != NULL) { next_DS = current_DS->next; MCMC->n_M[i_DS] = current_DS->n_M; MCMC->M_new[i_DS] = (double *)SID_malloc(sizeof(double) * MCMC->n_M[i_DS]); MCMC->M_last[i_DS] = (double *)SID_malloc(sizeof(double) * MCMC->n_M[i_DS]); MCMC->n_M_total += MCMC->n_M[i_DS]; current_DS = next_DS; i_DS++; } // Initialize results arrays MCMC->P_min = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_max = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_avg = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->dP_avg = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_best = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_peak = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_lo_68 = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_hi_68 = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_lo_95 = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_hi_95 = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->ln_likelihood_DS = (double *)SID_malloc(sizeof(double) * MCMC->n_DS); MCMC->ln_likelihood_DS_best = (double *)SID_malloc(sizeof(double) * MCMC->n_DS); MCMC->ln_likelihood_DS_peak = (double *)SID_malloc(sizeof(double) * MCMC->n_DS); MCMC->n_DoF_DS = (int *)SID_malloc(sizeof(int) * MCMC->n_DS); MCMC->n_DoF_DS_best = (int *)SID_malloc(sizeof(int) * MCMC->n_DS); MCMC->n_DoF_DS_peak = (int *)SID_malloc(sizeof(int) * MCMC->n_DS); // If MCMC_MODE_MINIMIZE_IO is on, we need to allocate buffers to store the chain if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_MINIMIZE_IO)) { MCMC->flag_success_buffer = (char *)SID_malloc(sizeof(char) * MCMC->n_iterations * MCMC->n_avg); MCMC->ln_likelihood_new_buffer = (double *)SID_malloc(sizeof(double) * MCMC->n_iterations * MCMC->n_avg); MCMC->P_new_buffer = (double *)SID_malloc(sizeof(double) * MCMC->n_iterations * MCMC->n_avg * MCMC->n_P); MCMC->M_new_buffer = (double *)SID_malloc(sizeof(double) * MCMC->n_iterations * MCMC->n_avg * MCMC->n_M_total); } SID_log("Done.", SID_LOG_CLOSE); } }
{ "alphanum_fraction": 0.5978028685, "avg_line_length": 48.9104477612, "ext": "c", "hexsha": "c945b627eecb1d325e7e6bd95be4da6b1371a3fe", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpMCMC/init_MCMC_arrays.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpMCMC/init_MCMC_arrays.c", "max_line_length": 135, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpMCMC/init_MCMC_arrays.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 1022, "size": 3277 }
/** * This file is part of yasimSBML (http://www.labri.fr/perso/ghozlane/metaboflux/about/yasimSBML.php) * Copyright (C) 2010 Amine Ghozlane from LaBRI and University of Bordeaux 1 * * yasimSBML is free software: you can redistribute it and/or modify * it under the terms of the Lesser GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * yasimSBML 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 Lesser GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file simulation.c * \brief Simulate a petri net * \author {Amine Ghozlane} * \version 1.0 * \date 27 octobre 2009 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #include <unistd.h> #include <gsl/gsl_rng.h> #include <sbml/SBMLTypes.h> #include "especes.h" #include "simulation.h" /*TODO Verification des BoundaryConditions,Local parameter values, Global parameter values, Reaction, des equations */ /** * \fn void SBML_initEspeceAmounts(Model_t *mod, pEspeces molecules, int nbEspeces) * \author Amine Ghozlane * \brief Alloc memory and initialize the struct Especes * \param mod Model of the SBML file * \param molecules Struct Especes * \param nbEspeces Number of molecules */ void SBML_initEspeceAmounts(Model_t *mod, pEspeces molecules, int nbEspeces) { int i; Species_t *esp; /* Initialisation des quantites des especes*/ for (i = 0; i < nbEspeces; i++) { esp = Model_getSpecies(mod, i); /*printf("espece: %s, compartiment : %s\n",Species_getId(esp),Species_getCompartment(esp));*/ Especes_save(molecules, i, Species_getInitialAmount(esp), Species_getId(esp), Species_getCompartment(esp)); } } /** * \fn void SBML_setReactions(Model_t *mod, pEspeces molecules, pScore result, double *reactions_ratio, int nbReactions, int nbEspeces) * \author Amine Ghozlane * \brief Alloc memory and initialize the struct Especes * \param mod Model of the SBML file * \param molecules Struct Especes * \param result Struct Score * \param reactions_ratio List of computed reaction ratio * \param nbReactions Number of reaction * \param nbEspeces Number of molecules */ void SBML_setReactions(Model_t *mod, pEspeces molecules, int nbReactions, int nbEspeces) { int ref = 0, i, j; SpeciesReference_t *reactif; Species_t *especeId; Reaction_t *react; const char *kf; const ASTNode_t *km; KineticLaw_t *kl; /*fprintf(stdout, "Debut reaction\n");*/ /* Recherche les reactions ou apparaissent chaque espece */ for (i = 0; i < nbReactions; i++) { react = Model_getReaction(mod, i); for (j = 0; j < (int)Reaction_getNumReactants(react); j++) { reactif = Reaction_getReactant(react, j); especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies( reactif)); ref = Especes_find(molecules, Species_getId(especeId), nbEspeces); /*printf("Reactif :Quantite de ref %d :%f \n", ref,Especes_getQuantite(molecules, ref));*/ kl = Reaction_getKineticLaw(react); if (KineticLaw_isSetFormula(kl)) { kf = KineticLaw_getFormula(kl); /*printf("c du kf %s\n", kf);*/ Especes_allocReactions(molecules, ref, react, SBML_evalExpression(kf)); } else { km = KineticLaw_getMath(kl); printf("C du kM... cas encore ignore\n"); exit(1); } } } /*fprintf(stdout, "Fin reaction\n");*/ } /** * \fn double SBML_evalExpression(const char *formule) * \author Amine Ghozlane * \brief Get the reaction ratio define in the sbml * \param formule Formule SBML * \return Return double value of the constraint */ double SBML_evalExpression(const char *formule) { return atof(formule); } /** * \fn int SBML_checkQuantite(Model_t *mod, Reaction_t *react, int nbEspeces, pEspeces molecules) * \author Amine Ghozlane * \brief Determine the number of reaction for one molecule * \param mod Model of the SBML file * \param react Reaction id * \param nbEspeces Number of molecules * \param molecules Struct Especes * \return Number of reaction for one molecule */ int SBML_checkQuantite(Model_t *mod, Reaction_t *react, int nbEspeces, pEspeces molecules) { double quantite = 0.0, minStep = 0.0, temp = 0.0; int ref = 0, i; SpeciesReference_t *reactif; Species_t *especeId; reactif = Reaction_getReactant(react, 0); especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif)); ref = Especes_find(molecules, Species_getId(especeId), nbEspeces); if ((quantite = Especes_getQuantite(molecules, ref)) <= 0.0) { /*printf("je fais le return\n");*/ return END; } /*printf("quantite : %d\n",quantite);*/ minStep = quantite / SpeciesReference_getStoichiometry(reactif); /*printf("quantite : %d, minStep init : %d\n",quantite,minStep);*/ /* Cas ou le nombre de pas est egal a 0 */ if(minStep==0.0) return END; for (i = 1; i < (int)Reaction_getNumReactants(react); i++) { reactif = Reaction_getReactant(react, i); especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif)); ref = Especes_find(molecules, Species_getId(especeId), nbEspeces); quantite= Especes_getQuantite(molecules, ref); /* La quantite est egale a 0 */ if(quantite<=0.0) return END; temp = floor(Especes_getQuantite(molecules, ref)/SpeciesReference_getStoichiometry(reactif)); /* Cas ou le nombre de pas est egal a 0 */ if(temp==0.0) return END; /* Si le nouveau nombre est inferieur au precedent, on change la valeur de minStep */ if (minStep > temp) minStep = temp; } return (int)minStep; } /** * \fn Reaction_t * SBML_reactChoice(pEspeces molecules, const gsl_rng * r, int ref) * \author Amine Ghozlane * \brief Determine randomly the reaction to achieve for several nodes reactions * \param molecules Struct Especes * \param r Random number generator * \param ref Number reference of one molecule * \return Id of the selected reaction */ Reaction_t * SBML_reactChoice(pEspeces molecules, const gsl_rng * r, int ref) { pReaction temp = NULL; pReaction Q = molecules[ref].system; double value = gsl_rng_uniform(r) * 100.0; double choice = 0.0; /*printf("Choix de la reaction :\n"); printf("value : %f\n", value);*/ /* Choix de la reaction a realiser */ if (value < Q->ratio) temp = Q; else { do { /*printf("reaction %s : ratio %f\n", Reaction_getId(Q->link), Q->ratio);*/ choice += Q->ratio; /*printf("choice : %f\n", choice);*/ Q = Q->suivant; temp = Q; /*printf("ratio suivant : %f\n",Q->ratio );*/ } while (Q->suivant != NULL && value <= (choice + Q->suivant->ratio) && value > choice); } if (temp == NULL) { fprintf(stderr, "on a un probleme de ratio\n"); exit(EXIT_FAILURE); } /*printf("Resultat :\n"); printf("value : %f, choice :%f\n", value, (choice + Q->ratio)); printf("reaction %s : ratio %f\n", Reaction_getId(temp->link), temp->ratio);*/ /*if (Q->suivant == NULL) printf("choice :%f", choice);*/ /*printf("c bon\n");*/ return (temp->link); } /** * \fn void SBML_reaction(Model_t *mod, pEspeces molecules, Reaction_t *react, int nbEspeces) * \author Amine Ghozlane * \brief Simulation of a discrete transision * \param mod Model of the SBML file * \param molecules Struct Especes * \param react Reaction id * \param nbEspeces Number of molecules */ void SBML_reaction(Model_t *mod, pEspeces molecules, Reaction_t *react, int nbEspeces) { SpeciesReference_t *reactif; Species_t *especeId; int i, ref = 0; /*boucle pour retirer des reactifs*/ for (i = 0; i < (int)Reaction_getNumReactants(react); i++) { reactif = Reaction_getReactant(react, i); especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif)); ref = Especes_find(molecules, Species_getId(especeId), nbEspeces); /*printf("Reactif : %s",Species_getId(especeId) ); printf("ref : %d\n",ref); printf("Reactif :Quantite de ref %d :%d \n",ref,Espece_getQuantite(molecules,ref));*/ Especes_setQuantite(molecules, ref,(Especes_getQuantite(molecules, ref)- SpeciesReference_getStoichiometry(reactif))); /*printf("Apres Reactif: Quantite de ref %d :%d \n",ref,Espece_getQuantite(molecules,ref));*/ } /*boucle pour ajouter des produits */ for (i = 0; i < (int)Reaction_getNumProducts(react); i++) { reactif = Reaction_getProduct(react, i); especeId = Model_getSpeciesById(mod, SpeciesReference_getSpecies(reactif)); /*printf("Produit : %s",Species_getId(especeId) );*/ ref = Especes_find(molecules, Species_getId(especeId), /*Species_getCompartment(especeId),*/ nbEspeces); /*printf("Produit : ref : %d\n",ref); printf("Produit : Quantite de ref %d :%d \n",ref,Espece_getQuantite(molecules,ref));*/ Especes_setQuantite(molecules, ref,(Especes_getQuantite(molecules, ref)+ SpeciesReference_getStoichiometry(reactif))); /*printf("Apres Produit : Quantite de ref %d :%d \n",ref,Espece_getQuantite(molecules,ref));*/ } } /** * \fn void SBML_allocTest(pTestReaction T, int nbReactions) * \author Amine Ghozlane * \brief Alloc memory and initialize the struct pTestReaction * \param T Empty struct TestReaction * \param nbReactions Number of reactions */ void SBML_allocTest(pTestReaction T, int nbReactions) { int i; /* Initialisation des tableaux des reactions */ T->tabReactions= (Reaction_t **) malloc(nbReactions * sizeof(Reaction_t *)); T->minStepTab = (int*) malloc(nbReactions * sizeof(int)); if (T->tabReactions == NULL) exit(EXIT_FAILURE); if (T->minStepTab == NULL) exit(EXIT_FAILURE); for (i = 0; i < nbReactions; i++) { T->tabReactions[i] = NULL; T->minStepTab[i] = 0; } } /** * \fn void SBML_freeTest(pTestReaction T) * \author Amine Ghozlane * \brief Free memory of the struct TestReaction * \param T Struct TestReaction gives data on reaction */ void SBML_freeTest(pTestReaction T) { if (T->tabReactions != NULL) free(T->tabReactions); if (T->minStepTab != NULL) free(T->minStepTab); } /** * \fn int SBML_EstimationReaction(Model_t *mod, pTestReaction T, pEspeces molecules, int ref, int nbEspeces) * \author Amine Ghozlane * \brief Alloc memory and initialize the struct Especes * \param mod Model of the SBML file * \param T Struct TestReaction gives data on reaction * \param molecules Struct Especes * \param ref Number reference of one molecule * \param nbEspeces Number of molecules * \return Estimated number of feasible step by reaction */ int SBML_EstimationReaction(Model_t *mod, pTestReaction T, pEspeces molecules, int ref, int nbEspeces) { pReaction Q = molecules[ref].system; int i = 0, min = 0, curr = 0; /* Compte le nombre de reactions rattachees a une espece */ while (Q != NULL) { T->tabReactions[i] = Q->link; T->minStepTab[i] = SBML_checkQuantite(mod, Q->link, nbEspeces, molecules); if (i == 0) min = T->minStepTab[i]; curr = T->minStepTab[i]; if (T->minStepTab[i] <= 0) return END; else if (curr < min) min = curr; Q = Q->suivant; i++; } return min; } /** * \fn int SBML_simulate(Model_t *mod, pEspeces molecules, const gsl_rng * r, pTestReaction T, char **banned, int nbBanned, int nbEspeces, int ref) * \author Amine Ghozlane * \brief Simulate one step of petri net * \param mod Model of the SBML file * \param molecules Struct Especes * \param r Random number generator * \param T Struct TestReaction gives data on reaction * \param banned List of banned compound * \param nbBanned Number of banned compound * \param nbEspeces Number of molecules * \param ref Number reference of one molecule * \return Condition of stop/pursue */ int SBML_simulate(Model_t *mod, pEspeces molecules, const gsl_rng * r, pTestReaction T, int nbEspeces, int ref) { Reaction_t *react = NULL; int minStep = 0, valid = 0/*, i=0*/; /*int nbReactions = Especes_getNbreactions(molecules, ref);*/ int nbReactions = molecules[ref].nbReactions; /*printf("nbreactions : %d, ref : %d\n", nbReactions, ref); printf("molecules : %s\n", molecules[ref].id);*/ /* Probleme ATP, ADP, NADH, NAD+ */ if (!strcmp(molecules[ref].id, "ADP") || !strcmp(molecules[ref].id, "ATP") || !strcmp(molecules[ref].id, "NADH") || !strcmp(molecules[ref].id, "NADplus") || !strcmp(molecules[ref].id, "NADPH") || !strcmp( molecules[ref].id, "NADPplus")|| !strcmp(molecules[ref].id, "NADplus_g")|| !strcmp(molecules[ref].id, "NADH_g")|| !strcmp(molecules[ref].id, "ADP_g")|| !strcmp(molecules[ref].id, "ATP_g")|| !strcmp(molecules[ref].id, "ADP_c")|| !strcmp(molecules[ref].id, "ATP_c")) { /*printf("END : molecules : %s\n", molecules[ref].id);*/ return END; } /* Elimine les calculs sur ADP... */ /*for(j=0;j<BANNI;j++){ if(!strcmp(tab[i],molecules[ref].id)){ printf("test : tab: %s molecules : %s\n",tab[i],molecules[ref].id ); return END; } }*/ /* Variation selon le cas. */ switch (nbReactions) { /* Cas ou aucune reaction n'est possible */ case 0: /*printf("Cas N°1\n");*/ return END; break; /* Cas ou une seule reaction est possible */ case 1: /*printf("Cas N°2\n");*/ react = molecules[ref].system->link; if ((minStep = SBML_checkQuantite(mod, react, nbEspeces, molecules))<= END) return END; /*printf("minstep = %d\n", minStep);*/ while (minStep > 0) { SBML_reaction(mod, molecules, react, nbEspeces); minStep--; } break; /* Cas ou plusieurs reactions sont possibles*/ default: /*printf("Cas N°3\n");*/ /* Allocation de la memoire au tableau des reactions */ SBML_allocTest(T, nbReactions); valid = SBML_EstimationReaction(mod, T, molecules, ref, nbEspeces); if (valid <= END) { /*printf("on ne fait rien\n");*/ return END; } while (Especes_getQuantite(molecules, ref) > 0.0 && valid > END) { react = SBML_reactChoice(molecules, r, ref); /*printf("molecule : %s, reaction %s\n", molecules[ref].id, Reaction_getId(react));*/ /*printf("reaction : %s\n", Reaction_getId(react));*/ /*printf("valid : %d, i : %d\n", valid, i);*/ SBML_reaction(mod, molecules, react, nbEspeces); /*if(i>=valid) valid=SBML_EstimationReaction(mod, T, molecules, ref, nbEspeces);*/ /*i++;*/ valid--; } /*printf("Fin de simulation\n");*/ /* Liberation de la memoire allouee au tableau des reactions */ SBML_freeTest(T); break; } /*printf("On quitte la simulation\n");*/ return PURSUE; } /** * \fn void SBML_compute_simulation(pScore result, Model_t *mod, double *reactions_ratio, gsl_rng * r, char **banned, int nbBanned) * \author Amine Ghozlane * \brief Simulation of metabolic network * \param result Struct Score * \param mod Model of the SBML file * \param reactions_ratio List of computed reaction ratio * \param r Random number generator * \param banned List of banned compound * \param nbBanned Number of banned compound */ void compute_simulation(Model_t *mod) { int i, nbReactions = 0, nbEspeces = 0, temp = 1, tempo = 0; pEspeces molecules; const gsl_rng_type *T; gsl_rng * r; pTestReaction TR = NULL; /* Verifications */ /*TODO numGlobalParameters=Model_getNumParameters(mod); checkBoundaryConditions(mod); if(numGlobalParameters>0){ globalParVec=gsl_vector_alloc(numGlobalParameters); setGlobalParVec(); }*/ /* Allocation memoire et initialisation des generateurs de nombre aleatoire */ gsl_rng_env_setup(); if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(NULL); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_rng_default_seed = gsl_rng_uniform(r); /* Allocation memoire */ TR = (pTestReaction) malloc(1 * sizeof(TestReaction)); if (T == NULL) exit(EXIT_FAILURE); /* File information */ nbReactions = Model_getNumReactions(mod); nbEspeces = Model_getNumSpecies(mod); /*printf("Nom du model : %s\n",Model_getId(mod));*/ molecules = Especes_alloc(nbEspeces); /* Initialisation de la quantite des especes */ SBML_initEspeceAmounts(mod, molecules, nbEspeces); /* Initialisation des reactions et des ratios*/ SBML_setReactions(mod, molecules, nbReactions, nbEspeces); /*TODO checkRatio(mod,molecules);*/ /* Test des donnees enregistrees */ printf("\nEtat des especes :\n\n"); Especes_print(molecules, nbEspeces); printf("\nDebut de simulation ...\n"); /* Simulation des reactions */ while (temp > END) { temp = 0; for (i = 0; i < nbEspeces; i++) { tempo = SBML_simulate(mod, molecules, r, TR, nbEspeces, i); /*if (tempo != END) { Especes_print_2(molecules, nbEspeces); printf("\n"); }*/ temp += tempo; } } printf("Fin de simulation...\n"); printf("\nEtat des especes :\n"); Especes_print_2(molecules, nbEspeces); /* Liberation de la memoire des generateurs aleatoire */ gsl_rng_free(r); /* Liberation de la memoire de la structure Especes */ Especes_free(molecules, nbEspeces); if (TR != NULL) free(TR); } /** * \fn void SBML_score_add(pScore result, pScore result_temp, FILE *debugFile) * \author Amine Ghozlane * \brief Add scores * \param result Struct Score used for all the simulation * \param result_temp Struct Score used at each simulation step * \param debugFile File use for debug */ void SBML_score_add(pScore result, pScore result_temp, int nbEspeces) { /* Addition des scores */ int i; /* Copie des resultats */ for(i=0;i<nbEspeces;i++){ if(result->name[i]==NULL){ result->name[i]=(char*)malloc(((int)strlen(result_temp->name[i])+1)*sizeof(char)); assert(result->name[i]!=NULL); strcpy(result->name[i], result_temp->name[i]); } result->quantite[i]+=result_temp->quantite[i]; } } /** * \fn void SBML_score_mean(pScore result, int n) * \author Amine Ghozlane * \brief Mean quantities for score * \param result Struct Score * \param n Number of simulation step */ void SBML_score_mean(pScore result, int nbEspeces, int n) { /* Moyenne des resultats */ int i; for(i=0;i<nbEspeces;i++){ result->quantite[i]/=n; } } /** * \fn pScore SBML_scoreAlloc(pListParameters a) * \author Amine Ghozlane * \brief Allocation of the struct Score * \param a Global parameters : struct ListParameters * \return Allocated struct Score */ pScore SBML_scoreAlloc(int nbEspeces) { int i; /* Allocation de la structure de score */ pScore result=NULL; result=(pScore)malloc(1*sizeof(Score)); assert(result!=NULL); result->name=NULL; result->quantite=NULL; result->name=(char**)malloc(nbEspeces*sizeof(char*)); assert(result->name!=NULL); result->quantite=(double*)malloc(nbEspeces*sizeof(double)); assert(result->quantite!=NULL); for(i=0;i<nbEspeces;i++){ result->name[i]=NULL; result->quantite[i]=0.0; } return result; } /** * \fn void SBML_scoreFree(pScore out) * \author Amine Ghozlane * \brief Free the struct Score * \param out Struct score */ void SBML_scoreFree(pScore out, int nbEspeces) { int i; /* Libere la memoire alloue a la structure de score */ for(i=0;i<nbEspeces;i++){ if(out->name[i]!=NULL) free(out->name[i]); } if(out->name!=NULL) free(out->name); if(out->quantite!=NULL) free(out->quantite); if(out!=NULL) free(out); } /* Affiche le score moyen */ /** * \fn void SBML_scoreFree(pScore out) * \author Amine Ghozlane * \brief Free the struct Score * \param out Struct score * \param nbEspeces */ void SBML_score_print(pScore result, int nbEspeces) { int i; /* Print head*/ /*for(i=0;i<nbEspeces;i++){ printf("%s;",result->name[i]); } printf("\n");*/ /* Print Value */ for(i=0;i<nbEspeces;i++){ /*printf("Molecule: %s - Biomass: %.0f\n",result->name[i],result->quantite[i]);*/ printf("%.0f;",result->quantite[i]); } printf("\n"); } /** * \fn void SBML_compute_simulation_mean(Model_t *mod, int nb_simulation) * \author Amine Ghozlane * \brief X time simulation of metabolic network * \param mod Model of the SBML file * \param nb_simulation Number of simulation step */ void SBML_compute_simulation_mean(Model_t *mod, int nb_simulation) { /* Simulation du reseau metabolique */ int i, j,nbReactions = 0, nbEspeces = 0, temp = 1, tempo=0, test=0; pEspeces molecules=NULL; pTestReaction TR=NULL; const gsl_rng_type *T; gsl_rng * r; pScore result=NULL,result_temp=NULL; /* Allocation memoire et initialisation des generateurs de nombre aleatoire */ gsl_rng_env_setup(); if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(NULL)+(double)getpid(); T = gsl_rng_default; r = gsl_rng_alloc(T); /*gsl_rng_default_seed = time(NULL)+(double)getpid();*/ /* Allocation memoire */ TR=(pTestReaction)malloc(1*sizeof(TestReaction)); assert(TR!=NULL); /* File information */ nbReactions = (int)Model_getNumReactions(mod); nbEspeces = (int)Model_getNumSpecies(mod); molecules = Especes_alloc(nbEspeces); /* Initialisation de la structure de score temporaire */ result=SBML_scoreAlloc(nbEspeces); result_temp=SBML_scoreAlloc(nbEspeces); /* Initialisation de la quantite des especes */ SBML_initEspeceAmounts(mod, molecules, nbEspeces); /* Initialisation des reactions et des ratios*/ SBML_setReactions(mod, molecules, nbReactions, nbEspeces); /*printf("Start the simulation\n");*/ /* SIMULATION */ for(j=0;j<nb_simulation;j++){ /* Simulation des reactions */ while (temp > END) { temp = 0; for (i = 0; i < nbEspeces; i++) { tempo = SBML_simulate(mod, molecules, r, TR, nbEspeces, i); temp +=tempo; } test+=1; } temp=1; tempo=0; /*printf("Nombre de tour %d\n",test);*/ /*Score */ /* Enregistre le score des especes */ Especes_scoreSpecies(molecules, nbEspeces, result_temp->name, result_temp->quantite); SBML_score_add(result,result_temp,nbEspeces); SBML_initEspeceAmounts(mod, molecules, nbEspeces); } SBML_score_mean(result,nbEspeces,nb_simulation); /*printf("End of the simulation...\n"); printf("Final state of the molecules :\n");*/ SBML_score_print(result, nbEspeces); /* Liberation de la memoire des generateurs aleatoire */ gsl_rng_free(r); /* Liberation de la memoire du score */ SBML_scoreFree(result, nbEspeces); SBML_scoreFree(result_temp, nbEspeces); /* Liberation de la memoire de la structure Especes */ Especes_free(molecules, nbEspeces); if(TR!=NULL) free(TR); }
{ "alphanum_fraction": 0.6659512363, "avg_line_length": 33.3276108727, "ext": "c", "hexsha": "f36531ea27ecc2d93e36923141f6c1124b2e6149", "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": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_forks_repo_licenses": [ "DOC" ], "max_forks_repo_name": "aghozlane/yasimSBML", "max_forks_repo_path": "src/simulation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "DOC" ], "max_issues_repo_name": "aghozlane/yasimSBML", "max_issues_repo_path": "src/simulation.c", "max_line_length": 147, "max_stars_count": null, "max_stars_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0", "max_stars_repo_licenses": [ "DOC" ], "max_stars_repo_name": "aghozlane/yasimSBML", "max_stars_repo_path": "src/simulation.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6829, "size": 23296 }
/** * @file lpc.h * @brief Speech recognition front end. * @author John McDonough, Matthias Woelfel, Kenichi Kumatani */ #include <gsl/gsl_vector.h> #include "feature/feature.h" #ifndef LPC_H #define LPC_H // ----- definition for class `BaseFeature' ----- // class BaseFeature { protected: BaseFeature(unsigned order, unsigned dim); virtual ~BaseFeature(); void fftPower(float* power); //virtual void autoCorrelation(const float* X, float* LP, float* E, float warp ) = 0; unsigned _order; unsigned _dim; private: unsigned _log2Length; unsigned _npoints; unsigned _npoints2; double* _temp; }; // ----- definition for class `WarpFeature' ----- // class WarpFeature : protected BaseFeature { protected: WarpFeature(unsigned order, unsigned dim); virtual ~WarpFeature(); void autoCorrelation(const float* X, float* LP, float* E, float warp ); private: float* _K; float* _R; float* _WX; float* _WXTEMP; gsl_matrix_float* _tmpA; }; // ----- definition for class `BurgFeature' ----- // class BurgFeature : protected BaseFeature { protected: BurgFeature(unsigned order, unsigned dim); virtual ~BurgFeature(); void autoCorrelation(const float* X, float* LP, float* E, float warp ); private: float* _EF; float* _EB; float* _EFP; float* _EBP; float* _A_flip; float* _K; }; // ----- definition for class `MVDRFeature' ----- // template <class AutoCovariance> class MVDRFeature : public VectorFeatureStream, private AutoCovariance { public: MVDRFeature(const VectorFloatFeatureStreamPtr& src, unsigned order = 60, unsigned correlate = 0, float warp = 0.0, const String& nm = "MVDR"); virtual ~MVDRFeature(); virtual const gsl_vector* next(int frame_no = -5); virtual void reset() { _src->reset(); VectorFeatureStream::reset(); } private: VectorFloatFeatureStreamPtr _src; unsigned _temp_order; unsigned _correlate; float _warp; float* _tmpR; float* _tmpA; float* _tmpPC; float* _tmpPA; float* _E; }; // ----- methods for class `MVDRFeature' ----- // template <class AutoCovariance> MVDRFeature<AutoCovariance>:: MVDRFeature(const VectorFloatFeatureStreamPtr& src, unsigned order, unsigned correlate, float warp, const String& nm) : VectorFeatureStream(src->size()/2+1, nm), AutoCovariance(order, src->size()), _src(src), _temp_order(2*order+1), _correlate(correlate), _warp(warp), _tmpR(new float[order+1]), _tmpA(new float[order+1]), _tmpPC(new float[_temp_order]), _tmpPA(new float[AutoCovariance::_dim+1]), _E(new float[order+1]) { if (_correlate < 10) _correlate = AutoCovariance::_dim; if (AutoCovariance::_order >= AutoCovariance::_dim/2+1) throw jparameter_error("Order (%d) and dimension (%d) do not match.", AutoCovariance::_order, AutoCovariance::_dim/2+1); } template <class AutoCovariance> MVDRFeature<AutoCovariance>::~MVDRFeature() { delete[] _tmpR; delete[] _tmpA; delete[] _tmpPC; delete[] _tmpPA; delete[] _E; } template <class AutoCovariance> const gsl_vector* MVDRFeature<AutoCovariance>::MVDRFeature::next(int frame_no) { if (frame_no == frame_no_) return vector_; if (frame_no >= 0 && frame_no - 1 != frame_no_) throw jindex_error("Problem in Feature %s: %d != %d\n", name().c_str(), frame_no - 1, frame_no_); const gsl_vector_float* block = _src->next(frame_no_ + 1); increment_(); const float* X = block->data; float* A = _tmpA; float* PC = _tmpPC; float* PA = _tmpPA; AutoCovariance::autoCorrelation(X, _tmpA, _E, _warp); for (int i = 0; i <= AutoCovariance::_order; i++) { double temp = 0; for (int ii = 0; ii <= (AutoCovariance::_order-i); ii++) temp += (float)(int(AutoCovariance::_order)+1-i-2*ii)*A[ii]*A[ii+i]; if (_E[0] > 0) { PC[AutoCovariance::_order+i] = -temp; // instead of -temp/E[order] in the paper by B. Musicus IEEE 1985 } else { PC[AutoCovariance::_order+i] = 10000000; } } for (int i = 1; i <= AutoCovariance::_order; i++) PC[AutoCovariance::_order-i] = PC[AutoCovariance::_order+i]; PA[0] = 0; for (unsigned i = 1; i <= _temp_order; i++) PA[i] = PC[i-1]; // [..-1] because of fft for (unsigned i = _temp_order+1; i <= AutoCovariance::_dim; i++) PA[i] = 0; /* ------------------------------------------------------------------------ Calculate MVDR Power (also called Capon Max. Likelihood Method) */ AutoCovariance::fftPower(PA); for (unsigned i = 0; i<= AutoCovariance::_dim/2; i++) { double temp = sqrt(PA[i]); if (temp > 0) { temp = _E[0]/temp; } else { temp = 10000000; } gsl_vector_set(vector_, i, temp); } return vector_; } typedef MVDRFeature<WarpFeature> WarpMVDRFeature; typedef Inherit<WarpMVDRFeature, VectorFeatureStreamPtr> WarpMVDRFeaturePtr; typedef MVDRFeature<BurgFeature> BurgMVDRFeature; typedef Inherit<BurgMVDRFeature, VectorFeatureStreamPtr> BurgMVDRFeaturePtr; // ----- definition for class `WarpedTwiceFeature' ----- // class WarpedTwiceFeature : protected BaseFeature { protected: WarpedTwiceFeature(unsigned order, unsigned dim ); virtual ~WarpedTwiceFeature(); void autoCorrelation(const float* X, float* LP, float* E, float warp, float rewarp=0.0 ); private: float* _K; float* _R; float* _WX; float* _WXTEMP; float** _tmpA; }; // ----- definition for class `WarpedTwiceMVDRFeature' ----- // class WarpedTwiceMVDRFeature : public VectorFeatureStream, private WarpedTwiceFeature { public: WarpedTwiceMVDRFeature(const VectorFloatFeatureStreamPtr& src, unsigned order = 60, unsigned correlate = 0, float warp = 0.0, bool warpFactorFixed=false, float sensibility = 0.1, const String& nm = "WTMVDR"); virtual ~WarpedTwiceMVDRFeature(); virtual const gsl_vector* next(int frame_no = -5); virtual void reset() { _src->reset(); VectorFeatureStream::reset(); } private: VectorFloatFeatureStreamPtr _src; unsigned _correlate; unsigned _temp_order; float _warp; float* _tmpR; float* _tmpA; float* _tmpPC; float* _tmpPA; float* _E; float _rewarp; bool _warpFactorFixed; float _sensibility; }; typedef Inherit<WarpedTwiceMVDRFeature,VectorFeatureStreamPtr> WarpedTwiceMVDRFeaturePtr; // ----- definition for class `LPCFeature' ----- // template <class AutoCovariance> class LPCFeature : public VectorFeatureStream, private AutoCovariance { public: LPCFeature(const VectorFloatFeatureStreamPtr& src, unsigned order, unsigned correlate, float warp, const String& nm = "LPC"); virtual ~LPCFeature(); virtual const gsl_vector* next(int frame_no = -5); virtual void reset() { _src->reset(); VectorFeatureStream::reset(); } private: VectorFloatFeatureStreamPtr _src; unsigned _correlate; float _warp; float* _tmpA; float* _tmpPA; float* _E; const String _lpmethod; }; // ----- methods for class `LPCFeature' ----- // template <class AutoCovariance> LPCFeature<AutoCovariance>:: LPCFeature(const VectorFloatFeatureStreamPtr& src, unsigned order, unsigned correlate, float warp, const String& nm) : VectorFeatureStream(src->size()/2+1, nm), AutoCovariance(order, src->size()), _src(src), _correlate(correlate), _warp(warp), _tmpA(new float[order+1]), _tmpPA(new float[AutoCovariance::_dim+1]), _E(new float[order+1]) { if (_correlate < 10) _correlate = AutoCovariance::_dim; if (AutoCovariance::_order >= AutoCovariance::_dim/2+1) throw jparameter_error("Order (%d) and dimension (%d) do not match.", AutoCovariance::_order, AutoCovariance::_dim/2+1); } template <class AutoCovariance> LPCFeature<AutoCovariance>::~LPCFeature() { delete[] _tmpA; delete[] _tmpPA; delete[] _E; } template <class AutoCovariance> const gsl_vector* LPCFeature<AutoCovariance>::next(int frame_no) { if (frame_no == frame_no_) return vector_; if (frame_no >= 0 && frame_no - 1 != frame_no_) throw jindex_error("Problem in Feature %s: %d != %d\n", name().c_str(), frame_no - 1, frame_no_); const gsl_vector_float* block = _src->next(frame_no_ + 1); increment_(); const float* X = block->data; float* A = _tmpA; float* PA = _tmpPA; AutoCovariance::autoCorrelation(X, _tmpA, _E, _warp); PA[0] = 0; for (unsigned i = 1; i <= AutoCovariance::_order+1; i++) PA[i] = A[i-1]; // [..-1] because of fft for (unsigned i = AutoCovariance::_order+2; i <= AutoCovariance::_dim; i++) PA[i] = 0; AutoCovariance::fftPower(PA); for (unsigned i = 0; i <= AutoCovariance::_dim/2; i++) { double temp = PA[i]; if (temp > 0) { temp = (2*_E[0])/(temp*AutoCovariance::_dim); } else { temp = 10000000; } gsl_vector_set(vector_, i, temp); } return vector_; } typedef LPCFeature<WarpFeature> WarpLPCFeature; typedef Inherit<WarpLPCFeature, VectorFeatureStreamPtr> WarpLPCFeaturePtr; typedef LPCFeature<BurgFeature> BurgLPCFeature; typedef Inherit<BurgLPCFeature, VectorFeatureStreamPtr> BurgLPCFeaturePtr; // ----- definition for class `SpectralSmoothing' ----- // class SpectralSmoothing : public VectorFeatureStream { public: SpectralSmoothing(const VectorFeatureStreamPtr& adjustTo, const VectorFeatureStreamPtr& adjustFrom, const String& nm = "Spectral Smoothing"); virtual ~SpectralSmoothing(); virtual const gsl_vector* next(int frame_no = -5); virtual void reset() { _adjustTo->reset(); _adjustFrom->reset(); VectorFeatureStream::reset(); } private: VectorFeatureStreamPtr _adjustTo; VectorFeatureStreamPtr _adjustFrom; float* _R; }; typedef Inherit<SpectralSmoothing, VectorFeatureStreamPtr> SpectralSmoothingPtr; #endif
{ "alphanum_fraction": 0.6632468316, "avg_line_length": 28.4871060172, "ext": "h", "hexsha": "011351d3c0a4647ad8324a1375819b4b7f572e7a", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/feature/lpc.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/feature/lpc.h", "max_line_length": 210, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/feature/lpc.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 2911, "size": 9942 }
#include <gsl/gsl_rng.h> #include "gsl-sprng.h" #include <gsl/gsl_randist.h> #include <mpi.h> int main(int argc,char *argv[]) { int k,i,iters; double x,can,a,alpha; gsl_rng *r; FILE *s; char filename[15]; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&k); if ((argc != 3)) { if (k == 0) fprintf(stderr,"Usage: %s <iters> <alpha>\n",argv[0]); MPI_Finalize(); return(EXIT_FAILURE); } iters=atoi(argv[1]); alpha=atof(argv[2]); r=gsl_rng_alloc(gsl_rng_sprng20); sprintf(filename,"chain-%03d.tab",k); s=fopen(filename,"w"); if (s==NULL) { perror("Failed open"); MPI_Finalize(); return(EXIT_FAILURE); } x = gsl_ran_flat(r,-20,20); fprintf(s,"Iter X\n"); for (i=0;i<iters;i++) { can = x + gsl_ran_flat(r,-alpha,alpha); a = gsl_ran_ugaussian_pdf(can) / gsl_ran_ugaussian_pdf(x); if (gsl_rng_uniform(r) < a) x = can; fprintf(s,"%d %f\n",i,x); } fclose(s); MPI_Finalize(); return(EXIT_SUCCESS); }
{ "alphanum_fraction": 0.6217882837, "avg_line_length": 27.0277777778, "ext": "c", "hexsha": "b566f70135c7fc522b7e3602ea93d656bb043bd5", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-15T12:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-15T12:22:30.000Z", "max_forks_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yuanfangtardis/vscode_project", "max_forks_repo_path": "Externals/PolyChord/parallel_chains_mcmc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "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": "yuanfangtardis/vscode_project", "max_issues_repo_path": "Externals/PolyChord/parallel_chains_mcmc.c", "max_line_length": 62, "max_stars_count": null, "max_stars_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yuanfangtardis/vscode_project", "max_stars_repo_path": "Externals/PolyChord/parallel_chains_mcmc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 328, "size": 973 }
#include <pthread.h> #include <math.h> #include <fftw.h> #include <stdio.h> //C -> Very ugly code //DEFINITION OF COMPLEX NUMBERS typedef struct { double re, im; } mycom; //DEFINITION OF DATA ARRAY NEEDED FOR THE TRANSFORMATION (small space) typedef struct { double* m; double* vi; double* vo; int* nrop; } transdata; //DEFINITION OF DATA ARRAY NEEDED FOR THE TRANSFORMATION (large space) typedef struct { double* m; double* vi; double* vo; long long int* nrop; } ltransdata; //THREAD FUNCTION FOR FORWARD TRANSFORMATION (small space) void transforeT(void* td){ transdata* Td = (transdata *)td; double* Mat = Td->m; double* Vec_in = Td->vi; double* Vec_out = Td->vo; int* Nrop = Td->nrop; int x, y; for(x = 0; x < 2* *Nrop; x++){ Vec_out[x] = 0.; } for(x = 0; x < *Nrop; x++){ for(y = 0; y < *Nrop; y++){ Vec_out[2*x] += Mat[(x* (*Nrop))+y]*Vec_in[2*y]; Vec_out[2*x+1] += Mat[(x* (*Nrop))+y]*Vec_in[2*y+1]; } } } //THREAD FUNCTION FOR FORWARD TRANSFORMATION (large space) void ltransforeT(void* td){ ltransdata* Td = (ltransdata *)td; double* Mat = Td->m; double* Vec_in = Td->vi; double* Vec_out = Td->vo; long long int* Nrop = Td->nrop; long long int x, y; for(x = 0; x < 2* *Nrop; x++){ Vec_out[x] = 0.; } for(x = 0; x < *Nrop; x++){ for(y = 0; y < *Nrop; y++){ Vec_out[2*x] += Mat[(x* (*Nrop))+y]*Vec_in[2*y]; Vec_out[2*x+1] += Mat[(x* (*Nrop))+y]*Vec_in[2*y+1]; } } } //THREAD FUNCTION FOR BACKWARD TRANSFORMATION (small space) void transbackT(void* td){ transdata* Td = (transdata *)td; double* Mat = Td->m; double* Vec_in = Td->vi; double* Vec_out = Td->vo; int* Nrop = Td->nrop; int x, y; for(x = 0; x < 2* *Nrop; x++){ Vec_out[x] = 0.; } for(x = 0; x < *Nrop; x++){ for(y = 0; y < *Nrop; y++){ Vec_out[2*y] += Mat[x* *Nrop+y]*Vec_in[2*x]; Vec_out[2*y+1] += Mat[x* *Nrop+y]*Vec_in[2*x+1]; } } } //THREAD FUNCTION FOR BACKWARD TRANSFORMATION (large space) void ltransbackT(void* td){ ltransdata* Td = (ltransdata *)td; double* Mat = Td->m; double* Vec_in = Td->vi; double* Vec_out = Td->vo; long long int* Nrop = Td->nrop; long long int x, y; for(x = 0; x < 2* *Nrop; x++){ Vec_out[x] = 0.; } for(x = 0; x < *Nrop; x++){ for(y = 0; y < *Nrop; y++){ Vec_out[2*y] += Mat[x* *Nrop+y]*Vec_in[2*x]; Vec_out[2*y+1] += Mat[x* *Nrop+y]*Vec_in[2*x+1]; } } } //MAKE TRANSFORMATION MULTI THREADED (small space) DIR=1 is forward !! void mk_thread_trans(int dir, double* mat1, double* mat2, mycom* vec_in1, mycom* vec_in2, mycom* vec_out1, mycom* vec_out2, int* nrop1, int* nrop2){ pthread_t thread1, thread2; int iret1, iret2; transdata td1, td2; td1.m = mat1; td1.vi = (double* ) vec_in1; td1.vo = (double* ) vec_out1; td1.nrop = nrop1; td2.m = mat2; td2.vi = (double* ) vec_in2; td2.vo = (double* ) vec_out2; td2.nrop = nrop2; if(dir == 1){ iret1 = pthread_create( &thread1, NULL, (void* ) &transforeT , (void*) &td1); iret2 = pthread_create( &thread2, NULL, (void* ) &transforeT , (void*) &td2); }else{ iret1 = pthread_create( &thread1, NULL, (void* ) &transbackT , (void*) &td1); iret2 = pthread_create( &thread2, NULL, (void* ) &transbackT , (void*) &td2); } pthread_join( thread1, NULL); pthread_join( thread2, NULL); } //MAKE TRANSFORMATION MULTI THREADED (large space) DIR=1 is forward !! void lmk_thread_trans(int dir, double* mat1, double* mat2, mycom* vec_in1, mycom* vec_in2, mycom* vec_out1, mycom* vec_out2, long long int* nrop1, long long int* nrop2){ pthread_t thread1, thread2; int iret1, iret2; ltransdata td1, td2; td1.m = mat1; td1.vi = (double* ) vec_in1; td1.vo = (double* ) vec_out1; td1.nrop = nrop1; td2.m = mat2; td2.vi = (double* ) vec_in2; td2.vo = (double* ) vec_out2; td2.nrop = nrop2; if(dir == 1){ iret1 = pthread_create( &thread1, NULL, (void* ) &ltransforeT , (void*) &td1); iret2 = pthread_create( &thread2, NULL, (void* ) &ltransforeT , (void*) &td2); }else{ iret1 = pthread_create( &thread1, NULL, (void* ) &ltransbackT , (void*) &td1); iret2 = pthread_create( &thread2, NULL, (void* ) &ltransbackT , (void*) &td2); } pthread_join( thread1, NULL); pthread_join( thread2, NULL); }
{ "alphanum_fraction": 0.5655594406, "avg_line_length": 25.0054644809, "ext": "c", "hexsha": "29b08ed6a267f0b14e5aa8ae8a06e3fce5a0bf7b", "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": "a717cadb559db823a0d5172545661d5afa2715e7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sklinkusch/scripts", "max_forks_repo_path": "TC-programs/OLD_CIS3D/POPULS/ops_mt.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a717cadb559db823a0d5172545661d5afa2715e7", "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": "sklinkusch/scripts", "max_issues_repo_path": "TC-programs/OLD_CIS3D/POPULS/ops_mt.c", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "a717cadb559db823a0d5172545661d5afa2715e7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sklinkusch/scripts", "max_stars_repo_path": "TC-programs/OLD_CIS3D/POPULS/ops_mt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1732, "size": 4576 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /* * * * Filename: cp_gen.c * * Description: Bloch matrix for the completely positive generator * * Version: 1.0 * Created: 28/04/2014 23:09:21 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include <gsl/gsl_matrix.h> #include <gsl/gsl_math.h> #include <math.h> #include "funcs.h" /* * FUNCTION * Name: cp_mat * Description: Creating the CP generator matrix in Bloch form, taking as * arguments all the integrals, the physical parameters and * the pointer to the matrix * */ int cp_mat ( gsl_matrix* cp_mx , void* params ) { double integrals[12] ; if ( (integration(params,integrals)) != 0 ) return -1; /* Setting the integrals */ double rcc, rss, rsc, isc, rcs, ics, rc0 ; rcc = integrals[0] ; rss = integrals[2] ; rsc = integrals[4] ; isc = integrals[5] ; rcs = integrals[6] ; ics = integrals[7] ; rc0 = integrals[8] ; /* Copying the parameters */ struct f_params* pars = (struct f_params*) params ; double o_c, b, O, o_1 ; assign_p ( pars, &o_c, &b, &O, &o_1 ) ; double D = sqrt(POW_2(o_1)-POW_2(O)) ; /* Ensuring that the matrix is zeroed */ gsl_matrix_set_zero ( cp_mx ) ; /* Building the matrix */ unsigned int i ; for ( i = 0; i < 4; i++ ) gsl_matrix_set ( cp_mx, 0 , i , 0 ) ; gsl_matrix_set ( cp_mx, 1, 0, 0 ) ; gsl_matrix_set ( cp_mx, 1, 1, 2*(O/o_1)*rss+(1+POW_2(O/o_1))*rcc+2*POW_2(D/o_1)*rc0 ) ; gsl_matrix_set ( cp_mx, 1, 2, o_1/4-(1+POW_2(O/o_1))*rcs+2*(O/o_1)*rsc ) ; gsl_matrix_set ( cp_mx, 1, 3, 0 ) ; gsl_matrix_set ( cp_mx, 2, 0, 0 ) ; gsl_matrix_set ( cp_mx, 2, 1, -(o_1/4-(1+POW_2(O/o_1))*rcs+2*(O/o_1)*rsc) ) ; gsl_matrix_set ( cp_mx, 2, 2, 2*(O/o_1)*rss+(1+POW_2(O/o_1))*rcc+2*POW_2(D/o_1)*rc0 ) ; gsl_matrix_set ( cp_mx, 2, 3, 0 ) ; gsl_matrix_set ( cp_mx, 3, 0, (1+POW_2(O/o_1))*ics-2*(O/o_1)*isc ) ; gsl_matrix_set ( cp_mx, 3, 1, 0 ) ; gsl_matrix_set ( cp_mx, 3, 2, 0 ) ; gsl_matrix_set ( cp_mx, 3, 3, (1+POW_2(O/o_1))*rcc+2*(O/o_1)*rss ) ; /* Multiplies times -4 to obtain the Bloch matrix */ gsl_matrix_scale ( cp_mx, -4 ) ; return 0; } /* ----- end of function cp_mat ----- */
{ "alphanum_fraction": 0.6676581936, "avg_line_length": 33.6181818182, "ext": "c", "hexsha": "82c1e3441c65854122053e4b31a0071cdee785ec", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "cp_gen.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "cp_gen.c", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "cp_gen.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1196, "size": 3698 }
/* * knnring_sequential.c * * Created on: Nov 21, 2019 * Author: Lambis */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <cblas.h> #include "knnring.h" knnresult kNN(double * X, double * Y, int n, int m, int d, int k) { knnresult knn; // Allocating memory for the knnresult. knn.nidx = (int *)malloc(m*k*sizeof(int)); knn.ndist = (double *)malloc(m*k*sizeof(double)); // Passing m and k values to knnresult. knn.m = m; knn.k = k; // Allocating memory for the distances array. double *D = (double *)malloc(m*n*sizeof(double)); // Calculation of sum(X.^2,2). double *a = (double *)malloc(n*sizeof(double)); for (int i=0; i<n; i++) { a[i] = cblas_dnrm2(d, &X[i*d], 1); a[i] = a[i]*a[i]; } // Calculation of sum(Y.^2,2). double *b = (double *)malloc(m*sizeof(double)); for (int i=0; i<m; i++) { b[i] = cblas_dnrm2(d, &Y[i*d], 1); b[i] = b[i]*b[i]; } // Calculation of -2*X*Y.' multiplication. double *c = (double *)malloc(n*m*sizeof(double)); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, m, d, -2, X, d, Y, d, 0, c, m); // Adding sum(X.^2,2) sum(Y.^2,2).' to the c array. for (int i=0; i<n; i++) for(int j=0; j<m; j++) c[i*m+j] += a[i] + b[j]; // Cleanup. free(a); free(b); // Applying elementwise square root to the c array. for (int i=0; i<n; i++) for(int j=0; j<m; j++) c[i*m+j] = sqrt(fabs(c[i*m+j])); // Creates a nxn identity array. double *iA = (double *)calloc(n*n, sizeof(double)); for (int i=0; i<n; i++) iA[i*n+i] = 1; // Transposing c array and storing it in D. cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, n, 1, c, m, iA, n, 0, D, n); // More efficient than the multiplication above. This can only be used with openblas. //cblas_domatcopy(CblasRowMajor, CblasTrans, n, m, 1, c, m, D, n); // Cleanup. free(iA); free(c); // Setup of idx number for corpus points. int *idx = (int *)malloc(m*n*sizeof(int)); for (int i=0; i<m; i++) for (int j=0; j<n; j++) idx[i*n+j]= j; // Sorting of all distances. for (int i=0; i<m; i++) quickSort(D, i*n, ((i+1)*n)-1, idx); // Passing the k nearest neighbors' indexes and distances to knnresult. for (int i=0; i<m; i++) { for (int j=0; j<k; j++) { knn.nidx[i*k+j] = idx[i*n+j]; knn.ndist[i*k+j] = D[i*n+j]; } } return knn; } // A utility function to swap two elements. void swap(void* a, void* b, size_t s) { void* tmp = malloc(s); memcpy(tmp, a, s); memcpy(a, b, s); memcpy(b, tmp, s); free(tmp); } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array * and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition(double *arr, int low, int high, int *idx) { double pivot = arr[high]; // Pivot int i = (low - 1); // Index of smaller element for (int j=low; j<=high-1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { i++; // Increment index of smaller element swap(&arr[i], &arr[j], sizeof(double)); swap(&idx[i], &idx[j], sizeof(int)); } } swap(&arr[i + 1], &arr[high], sizeof(double)); swap(&idx[i + 1], &idx[high], sizeof(int)); return (i + 1); } // The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index void quickSort(double *arr, int low, int high, int *idx) { if (low < high) { // pi is partitioning index, arr[pi] is now at right place int pi = partition(arr, low, high, idx); // Separately sort elements before partition and after partition quickSort(arr, low, pi - 1, idx); quickSort(arr, pi + 1, high, idx); } }
{ "alphanum_fraction": 0.5763057325, "avg_line_length": 28.2374100719, "ext": "c", "hexsha": "19dc26f3d62f733355dc4357da647be1f0684a23", "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": "6977dca83c165fc41466e2a28bd7d460cbda29de", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LambisElef/kNN_MPI", "max_forks_repo_path": "knnring_sequential.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6977dca83c165fc41466e2a28bd7d460cbda29de", "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": "LambisElef/kNN_MPI", "max_issues_repo_path": "knnring_sequential.c", "max_line_length": 124, "max_stars_count": null, "max_stars_repo_head_hexsha": "6977dca83c165fc41466e2a28bd7d460cbda29de", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LambisElef/kNN_MPI", "max_stars_repo_path": "knnring_sequential.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1262, "size": 3925 }
/* specfunc/elljac.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_elljac.h> /* GJ: See [Thompson, Atlas for Computing Mathematical Functions] */ /* BJG 2005-07: New algorithm based on Algorithm 5 from Numerische Mathematik 7, 78-90 (1965) "Numerical Calculation of Elliptic Integrals and Elliptic Functions" R. Bulirsch. Minor tweak is to avoid division by zero when sin(x u_l) = 0 by computing reflected values sn(K-u) cn(K-u) dn(K-u) and using transformation from Abramowitz & Stegun table 16.8 column "K-u"*/ int gsl_sf_elljac_e(double u, double m, double * sn, double * cn, double * dn) { if(fabs(m) > 1.0) { *sn = 0.0; *cn = 0.0; *dn = 0.0; GSL_ERROR ("|m| > 1.0", GSL_EDOM); } else if(fabs(m) < 2.0*GSL_DBL_EPSILON) { *sn = sin(u); *cn = cos(u); *dn = 1.0; return GSL_SUCCESS; } else if(fabs(m - 1.0) < 2.0*GSL_DBL_EPSILON) { *sn = tanh(u); *cn = 1.0/cosh(u); *dn = *cn; return GSL_SUCCESS; } else { int status = GSL_SUCCESS; const int N = 16; double mu[16]; double nu[16]; double c[16]; double d[16]; double sin_umu, cos_umu, t, r; int n = 0; mu[0] = 1.0; nu[0] = sqrt(1.0 - m); while( fabs(mu[n] - nu[n]) > 4.0 * GSL_DBL_EPSILON * fabs(mu[n]+nu[n])) { mu[n+1] = 0.5 * (mu[n] + nu[n]); nu[n+1] = sqrt(mu[n] * nu[n]); ++n; if(n >= N - 1) { status = GSL_EMAXITER; break; } } sin_umu = sin(u * mu[n]); cos_umu = cos(u * mu[n]); /* Since sin(u*mu(n)) can be zero we switch to computing sn(K-u), cn(K-u), dn(K-u) when |sin| < |cos| */ if (fabs(sin_umu) < fabs(cos_umu)) { t = sin_umu / cos_umu; c[n] = mu[n] * t; d[n] = 1.0; while(n > 0) { n--; c[n] = d[n+1] * c[n+1]; r = (c[n+1] * c[n+1]) / mu[n+1]; d[n] = (r + nu[n]) / (r + mu[n]); } *dn = sqrt(1.0-m) / d[n]; *cn = (*dn) * GSL_SIGN(cos_umu) / gsl_hypot(1.0, c[n]); *sn = (*cn) * c[n] /sqrt(1.0-m); } else { t = cos_umu / sin_umu; c[n] = mu[n] * t; d[n] = 1.0; while(n > 0) { --n; c[n] = d[n+1] * c[n+1]; r = (c[n+1] * c[n+1]) / mu[n+1]; d[n] = (r + nu[n]) / (r + mu[n]); } *dn = d[n]; *sn = GSL_SIGN(sin_umu) / gsl_hypot(1.0, c[n]); *cn = c[n] * (*sn); } return status; } }
{ "alphanum_fraction": 0.5334302326, "avg_line_length": 26.6666666667, "ext": "c", "hexsha": "340306e485d506799c8772c8fc910e176400e22f", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/elljac.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/specfunc/elljac.c", "max_line_length": 81, "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/specfunc/elljac.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": 1172, "size": 3440 }
#ifndef L_Katyusha_H #define L_Katyusha_H #include <string> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <stdio.h> /* printf */ #include <time.h> #include <fstream> #include <algorithm> #include <iomanip> #include <ctime> #include <sstream> #include <math.h> //This class implements the loopless variance reduced type methods with arbitrary sampling /* The optimization problem to solve is: F(x):=\sum_{i=1}^n 1/n* phi_i(x)+ g(x) */ template<typename L, typename D> class L_Katyusha { protected: // involved variables std::vector<D> proba_vector; std::vector<D> tilde_proba_vector; std::vector<D> group_C; std::vector<D> index_group_C; std::vector<D> maxp_group_C; std::vector<D> isolated_I; std::vector<D> sump_group_C; std::vector<D> theta_S; //theta_S in the paper std::vector<D> Li; // the Lipchitz constant of phi_i std::vector<D> gk; // the vector g^k in the paper std::vector<D> gradient_f_w; // gradient of f at w std::vector<D> gradient_f_x; // gradient of f at x std::vector<D> batch_delta_gradient; // 1/n(G(x^k)-G(w^k))theta_{S_k} I_{S_k} e in the paper L c; L noverc; // auxiliary variables L nb_of_iters_per_loop; L max_nb_loops; D max_p; L nsamples; L nfeatures; D running_time; L nb_loops; L print_every_N; vector<L> batch_i; vector<L> my_batch; L batch_size; L nb_groups; //number of groups in group sampling string uniform; D Lf; D L2; D sumLi; D upper_bound; // upper bound of F(x)-F^* D p; // the probability of changing w to x as in the paper L tau; //number of threads on each node/computer D mu; D scaler; L current_nb_iters; L nb_iters; ofstream samp; D theta1; D theta2; D theta3; D eta; //eta/L in the paper D oneovereta; D primal_value; std::vector<D> x; std::vector<D> w; std::vector<D> y; std::vector<D> z; std::vector<D> next_x; public: gsl_rng * rng; virtual inline D value_of_phi_i(L) {return D(NULL);} virtual inline D value_of_g(){return D(NULL);} virtual inline void prox_of_g(D, vector<D> &, vector<D> &, vector<D> &){} //prox_of_g(L,x, gr, y) computes y=argmin_u{L/2 ||u-(x-gr/L)||^2+g(u)} virtual inline void set_auxiliary_v(){} virtual inline void update_gradient(){} virtual inline void set_Li_Lf(){} virtual inline void compute_batch_delta_gradient(){} virtual inline void compute_full_gradient(vector<D> &, vector<D> &){} L_Katyusha() { } void update_x(){ for(L i=0; i<nfeatures; i++){ x[i]= theta1*z[i]+ theta2*w[i]+ theta3*y[i]; } } void update_y(){ for(L i=0; i<nfeatures; i++){ y[i]=theta1*z[i]+ theta2*w[i]+ theta3*y[i]; } } void update_gk(){ batch_delta_gradient.clear(); batch_delta_gradient.resize(nfeatures,0); compute_batch_delta_gradient(); for(L i=0;i<nfeatures;i++){ gk[i]=batch_delta_gradient[i]+gradient_f_w[i]; } } void update_z(){ prox_of_g(oneovereta,z,gk,z); } void update_w(){ D yi=gsl_rng_uniform(rng); if(yi<=p){ w=x; compute_full_gradient(w, gradient_f_w); } } void compute_upper_bound_of_optimality_gap(){ compute_full_gradient(x, gradient_f_x); prox_of_g(Lf,x,gradient_f_x,next_x); D tmp=0; for(L i=0;i<nfeatures;i++){ tmp+=(next_x[i]-x[i])*(next_x[i]-x[i]); x[i]=next_x[i]; } upper_bound=tmp*Lf*Lf/mu; } void set_rng() { gsl_rng_env_setup(); const gsl_rng_type * T; T = gsl_rng_default; rng = gsl_rng_alloc(T); gsl_rng_set(rng,time(NULL)); //gsl_rng_set(rng, 27432042); } void set_print_every_N(L i){print_every_N=i;} void set_optimal_probability() { tilde_proba_vector.clear(); tilde_proba_vector.resize(nsamples,0); proba_vector.clear(); proba_vector.resize(nsamples,0); D sum=0; for(L i=0; i<nsamples;i++) { tilde_proba_vector[i]=Li[i]; sum+=Li[i]; } max_p=0; for(L i=0; i<nsamples;i++) { tilde_proba_vector[i]=tilde_proba_vector[i]/sum; proba_vector[i]=1-pow(1-tilde_proba_vector[i],tau); if(max_p<tilde_proba_vector[i]) { max_p=tilde_proba_vector[i]; } } cout<<"sum="<<sum<<"; proba"<<tilde_proba_vector[0]<<endl; } void set_group_sampling_probability(){ proba_vector.clear(); proba_vector.resize(nsamples,0); std::vector<D> q(nsamples); D sumq=0; cout<<"start setting group sampling probablity"<<endl; for(L i=0; i<nsamples;i++) { q[i]=Li[i]; sumq+=q[i]; } D maxq=0; L nb=0; D tmp=0; for(L i=0; i<nsamples;i++) { q[i]=q[i]/sumq*tau; if(q[i]>maxq) maxq=q[i]; if(q[i]>1) { nb++; //count the number of elements larger than 1 tmp+=q[i]-1; } } cout<<"maxq="<<maxq<<endl; if(maxq<=1){ for(L i=0; i<nsamples;i++) { proba_vector[i]=q[i]; } }else{ for(L i=0; i<nsamples;i++) { if(q[i]>1) q[i]=1; else { D deltaq=min(1-q[i],tmp); tmp=tmp-deltaq; q[i]+=deltaq; } proba_vector[i]=q[i]; } } } void set_L2(L p_mod, L u){ if(p_mod==0){ //batch sampling mode D tmp=0; D st; for(L i=0;i<nsamples;i++){ st=Li[i]/tilde_proba_vector[i]; if (st>tmp) tmp=st; } L2=tmp/nsamples/tau; cout<<"L2="<<L2<<"; "<<tilde_proba_vector[0]<<endl; } else{ //group sampling mode D tmp=0; D st; for(L i=0;i<nsamples;i++){ st=Li[i]/proba_vector[i]; if(isolated_I[i]==1) st=st-Li[i]; if(st>tmp) tmp=st; } L2=tmp/nsamples; } cout<<"set_L2="<<L2<<endl; } void set_uniform_probability(L p_mod) { if(p_mod==0) { //batch sampling (stochastic process as defined in the paper) proba_vector.clear(); tilde_proba_vector.clear(); tilde_proba_vector.resize(nsamples,1./nsamples); proba_vector.resize(nsamples,1-pow(1-1.0/nsamples,tau)); max_p=1.0/nsamples; cout<<"uniform="<<tilde_proba_vector[0]<<endl; } else{ //group sampling D pi=(tau*c+0.0)/nsamples; proba_vector.clear(); proba_vector.resize(nsamples,pi); } } void sort_p(){ vector<pair<D,L> >a; for (L i = 0 ;i < nsamples ; i++) { a.push_back(make_pair(proba_vector[i],i)); // k = value, i = original index } sort(a.begin(),a.end()); group_C.clear(); group_C.resize(nsamples); isolated_I.clear(); isolated_I.resize(nsamples,0); D tmp=0; D maxpi=0; D previous_i=0; index_group_C.clear(); index_group_C.push_back(0); maxp_group_C.clear(); sump_group_C.clear(); for (L i = 0 ;i < nsamples ; i++){ group_C[i]=a[nsamples-1-i].second; D pi=a[nsamples-1-i].first; if(tmp+pi<=1){ if(pi>maxpi) maxpi=pi; tmp+=pi; } else{ index_group_C.push_back(i); maxp_group_C.push_back(maxpi); sump_group_C.push_back(tmp); tmp=pi; maxpi=pi; if(i-previous_i==1) isolated_I[group_C[previous_i]]=1; previous_i=i; } } index_group_C.push_back(nsamples); maxp_group_C.push_back(maxpi); sump_group_C.push_back(tmp); nb_groups=sump_group_C.size(); if(previous_i==nsamples-1) isolated_I[group_C[previous_i]]=1; cout<<"size of group="<<nb_groups<<endl; } inline L sampling(L n) { L i=(floor)(gsl_rng_uniform(rng)*n); D y=gsl_rng_uniform(rng); while(y*max_p>tilde_proba_vector[i]) { i=(floor)(gsl_rng_uniform(rng)*n); y=gsl_rng_uniform(rng); } return i; } void set_theta(){ theta2=L2/2/max(Lf,L2); if(Lf<=L2/p){ D tmp=mu/L2/p; cout<<"L2="<<L2<<endl; cout<<"tmp="<<tmp<<endl; if(tmp>=1){ theta1=theta2; } else{ theta1=sqrt(tmp)*theta2; } }else theta1=min(sqrt(mu/Lf),p/2); theta3=1-theta1-theta2; eta=1./(theta1*(Lf+2*max(L2,Lf))); oneovereta=theta1*(Lf+2*max(L2,Lf)); cout<<"Lf="<<Lf<<"; L2="<<L2<<"; theta1="<<theta1<<"; theta2="<<theta2<<"; theta3="<<theta3<<endl; cout<<"eta="<<eta<<endl; } void set_p(D scal_p){ p=scal_p*tau/(0.0+nsamples); cout<<"changing probablity: "<<p<<endl; } void initialize(vector<D> & x0, D val_mu, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p) { cout<<"start initializing loopless Katyusha"<<" u="<<u<<endl; c=nb_c; noverc=nsamples/c; if(nb_tau>noverc) perror("tau should be less than n over c"); tau=nb_tau; nb_of_iters_per_loop=floor(nsamples/(c*(tau+0.0))); batch_i.clear(); batch_i.resize(nsamples,0); gk.clear(); gk.resize(nfeatures,0); upper_bound=std::numeric_limits<double>::max(); /**setup parameters**/ max_nb_loops=max_nb; mu=val_mu; cout<<"mu="<<mu<<endl; set_rng(); set_Li_Lf(); running_time=0; /**setup probability**/ if(p_mod==0) // batch sampling (stochastic process as defined in the paper) { if(u==0) // uniform sampling { set_uniform_probability(p_mod); uniform="uniform"; } else{ set_optimal_probability(); uniform="nonuniform"; } } else{ //group sampling if(u==0){ set_uniform_probability(p_mod); uniform="uniform"; }else{ set_group_sampling_probability(); uniform="nonuniform"; } sort_p(); cout<<"sort p"<<endl; } set_L2(p_mod,u); scaler=scal_p; set_p(scal_p); set_thetaS(p_mod); cout<<"set thetaS"<<endl; x.clear(); y.clear(); z.clear(); w.clear(); x.resize(nfeatures); y.resize(nfeatures); z.resize(nfeatures); w.resize(nfeatures); next_x.clear(); next_x.resize(nfeatures); gradient_f_w.clear(); gradient_f_w.resize(nfeatures); gradient_f_x.clear(); gradient_f_x.resize(nfeatures); for(L i=0;i<nfeatures;i++) { x[i]=x0[i]; y[i]= x0[i]; w[i]=x0[i]; z[i]=x0[i]; } set_theta(); cout<<"set stepsizes"<<endl; current_nb_iters=0; compute_primal_value(); cout<<"primal value="<<primal_value<<endl; cout<<"Initialization loopless Katyusha is finished!"<<endl; } void compute_primal_value() { D res=0; for(L i=0;i<nsamples;i++) { res+=value_of_phi_i(i); } D res2=value_of_g(); primal_value= res/nsamples+ res2; } void compute_and_record_result() { if(nb_loops%print_every_N==0){ compute_primal_value(); cout<<setprecision(9)<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<"; "<<running_time<<" primal value="<<primal_value<<endl; samp<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<" "<<running_time<<" "<<primal_value<<endl; } } void compute_and_record_result2() { if(nb_loops%print_every_N==0){ compute_primal_value(); compute_upper_bound_of_optimality_gap(); cout<<setprecision(9)<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<"; "<<running_time<<" primal value="<<primal_value<<" upper bound of F(x)-F^*= "<< upper_bound<< endl; samp<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<" "<<upper_bound<<" "<<running_time<<" "<<primal_value<<endl; } } void batch_sampling() { batch_size=0; L i; for(L it_t=0;it_t<tau;it_t++) { i=sampling(nsamples); batch_i[batch_size]=i; batch_size++; } } void set_thetaS(L p_mod){ theta_S.clear(); theta_S.resize(nsamples,0); if(p_mod==0){ for(L i=0;i<nsamples;i++) theta_S[i]=1.0/(tau*tilde_proba_vector[i]); } else{ for(L i=0;i<nsamples;i++) theta_S[i]=1.0/proba_vector[i]; } } void group_sampling(){ batch_size=0; std::vector<L> sampled_groups; for(L i=0;i<nb_groups;i++){ D y=gsl_rng_uniform(rng); if(y<sump_group_C[i]) { sampled_groups.push_back(i); batch_size++; } } for(L t=0;t<batch_size;t++){ L group_i=sampled_groups[t]; L s1=index_group_C[group_i]; L s2=index_group_C[group_i+1]; L i=s1+(floor)(gsl_rng_uniform(rng)*(s2-s1)); D y=gsl_rng_uniform(rng); D maxpi=maxp_group_C[group_i]; while(y*maxpi>proba_vector[group_C[i]]) { i=s1+(floor)(gsl_rng_uniform(rng)*(s2-s1)); y=gsl_rng_uniform(rng); } batch_i[t]=group_C[i]; } } void loopless(vector<D> & x0, string filename, D val_mu, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p) { initialize(x0, val_mu, max_nb, nb_tau, nb_c, u, p_mod, scal_p); string sampname="results/L_Katyusha"+filename+uniform; if(p_mod==0) sampname=sampname+"_batch"; else sampname=sampname+"_group"; string scal_str; stringstream scal_convert; scal_convert<<scal_p; scal_str=scal_convert.str(); sampname+=scal_str; cout<<"running Loopless Katyusha "<<" ; "<<sampname<<endl; samp.open(sampname.c_str()); nb_loops=0; nb_iters=0; srand48(27432042); //srand(time(NULL)); D start; while(nb_loops<max_nb_loops) { compute_and_record_result(); nb_loops++; start = std::clock(); for(L it=0;it<nb_of_iters_per_loop;it++) { if(p_mod==0) batch_sampling(); else group_sampling(); start = std::clock(); update_x(); update_gk(); update_z(); update_y(); update_w(); update_gradient(); current_nb_iters++; nb_iters++; running_time+= ( std::clock() - start ) / (double) CLOCKS_PER_SEC; } } } void loopless2(vector<D> & x0, string filename, D val_mu, L max_nb, D epsilon, L nb_tau, L nb_c, L u, L p_mod, D scal_p) { cout<<"max_nb="<<max_nb<<endl; initialize(x0, val_mu, max_nb, nb_tau, nb_c, u, p_mod, scal_p); string sampname="results/L_"+filename+uniform; if(p_mod==0) sampname=sampname+"_batch"; else sampname=sampname+"_group"; string scal_str; stringstream scal_convert; scal_convert<<scal_p; scal_str=scal_convert.str(); sampname+=scal_str; cout<<"running Loopless Katyusha 2"<<" ; "<<sampname<<endl; samp.open(sampname.c_str()); nb_loops=0; nb_iters=0; cout<<setprecision(9)<<"initial: "<< "primal: "<<primal_value << endl; samp<<((0.0+nb_iters)*c*tau/(nsamples))<<" "<<running_time<<" "<<primal_value<<endl; //srand48(27432042); srand(time(NULL)); D start; cout<<"nb_loops="<<nb_loops<<"; max_nb_loops="<<max_nb_loops<<"; upper bound="<<upper_bound<<"; epsilon="<<epsilon<<endl; while(nb_loops<max_nb_loops && upper_bound> epsilon) { compute_and_record_result2(); start = std::clock(); nb_loops++; //cout<<"before the loop time elapsed="<<duration<<endl; start = std::clock(); //cout<<"nb_of_iters_per_loop="<<nb_of_iters_per_loop<<endl; for(L it=0;it<nb_of_iters_per_loop;it++) { if(p_mod==0) batch_sampling(); else group_sampling(); start = std::clock(); update_x(); update_gk(); update_z(); update_y(); update_w(); update_gradient(); current_nb_iters++; //cout<< "test 1"<< endl; //cout<< "test 2"<< endl; nb_iters++; running_time+= ( std::clock() - start ) / (double) CLOCKS_PER_SEC; } //cout<< "epoch "<< nb_loops<< " finished"<< endl; //cout<<"after the loop time elapsed="<<duration<<endl; } } }; #endif /* MIN_SMOOTH_CONVEX_H */
{ "alphanum_fraction": 0.576844071, "avg_line_length": 21.5927419355, "ext": "h", "hexsha": "ca5a0ba212632b796cf86577a7cc9e71a989aef7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": [ "BSD-Source-Code" ], "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_path": "IPALM/L_Katyusha.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-Source-Code" ], "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_path": "IPALM/L_Katyusha.h", "max_line_length": 184, "max_stars_count": null, "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": [ "BSD-Source-Code" ], "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_path": "IPALM/L_Katyusha.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4717, "size": 16065 }
/* -*- linux-c -*- */ /* triple.c Copyright (C) 2002-2004 John M. Fregeau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <getopt.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_rng.h> #include "fewbody.h" #include "triple.h" /* print the usage */ void print_usage(FILE *stream) { fprintf(stream, "USAGE:\n"); fprintf(stream, " triple [options...]\n"); fprintf(stream, "\n"); fprintf(stream, "OPTIONS:\n"); fprintf(stream, " -m --m000 <m000/MSUN> : set mass of star 0 of inner binary of triple [%.6g]\n", FB_M000/FB_CONST_MSUN); fprintf(stream, " -n --m001 <m001/MSUN> : set mass of star 1 of inner binary of triple [%.6g]\n", FB_M001/FB_CONST_MSUN); fprintf(stream, " -o --m01 <m01/MSUN> : set mass of outer star of triple [%.6g]\n", FB_M01/FB_CONST_MSUN); fprintf(stream, " -r --r000 <r000/RSUN> : set radius of star 0 of inner binary of triple [%.6g]\n", FB_R000/FB_CONST_RSUN); fprintf(stream, " -g --r001 <r001/RSUN> : set radius of star 1 of inner binary of triple [%.6g]\n", FB_R001/FB_CONST_RSUN); fprintf(stream, " -i --r01 <r01/RSUN> : set radius of outer star of triple [%.6g]\n", FB_R01/FB_CONST_RSUN); fprintf(stream, " -a --a00 <a00/AU> : set inner semimajor axis of triple [%.6g]\n", FB_A00/FB_CONST_AU); fprintf(stream, " -Q --a0 <a0/AU> : set outer semimajor axis of triple [%.6g]\n", FB_A0/FB_CONST_AU); fprintf(stream, " -e --e00 <e00> : set inner eccentricity of triple [%.6g]\n", FB_E00); fprintf(stream, " -F --e0 <e0> : set outer eccentricity of triple [%.6g]\n", FB_E0); fprintf(stream, " -t --tstop <tstop/t_dyn> : set stopping time [%.6g]\n", FB_TSTOP); fprintf(stream, " -D --dt <dt/t_dyn> : set approximate output dt [%.6g]\n", FB_DT); fprintf(stream, " -c --tcpustop <tcpustop/sec> : set cpu stopping time [%.6g]\n", FB_TCPUSTOP); fprintf(stream, " -A --absacc <absacc> : set integrator's absolute accuracy [%.6g]\n", FB_ABSACC); fprintf(stream, " -R --relacc <relacc> : set integrator's relative accuracy [%.6g]\n", FB_RELACC); fprintf(stream, " -N --ncount <ncount> : set number of integration steps between calls\n"); fprintf(stream, " to fb_classify() [%d]\n", FB_NCOUNT); fprintf(stream, " -z --tidaltol <tidaltol> : set tidal tolerance [%.6g]\n", FB_TIDALTOL); fprintf(stream, " -x --fexp <f_exp> : set expansion factor of merger product [%.6g]\n", FB_FEXP); fprintf(stream, " -k --ks : turn K-S regularization on or off [%d]\n", FB_KS); fprintf(stream, " -s --seed : set random seed [%ld]\n", FB_SEED); fprintf(stream, " -d --debug : turn on debugging\n"); fprintf(stream, " -V --version : print version info\n"); fprintf(stream, " -h --help : display this help text\n"); } /* calculate the units used */ int calc_units(fb_obj_t *obj[1], fb_units_t *units) { double m0, m00, m01, m000, m001, a00, a0; m0 = obj[0]->m; m00 = obj[0]->obj[0]->m; m01 = obj[0]->obj[1]->m; m000 = obj[0]->obj[0]->obj[0]->m; m001 = obj[0]->obj[0]->obj[1]->m; a0 = obj[0]->a; a00 = obj[0]->obj[0]->a; /* Unit of velocity is approximate relative orbital speed of inner binary, unit of length is semimajor axis of inner binary; therefore, unit of time is approximately 1 inner orbital period. */ units->v = sqrt(FB_CONST_G*(m000+m001)/a00); units->l = a00; units->t = units->l / units->v; units->m = units->l * fb_sqr(units->v) / FB_CONST_G; units->E = units->m * fb_sqr(units->v); return(0); } /* the main attraction */ int main(int argc, char *argv[]) { int i, j; unsigned long int seed; double m000, m001, m01, r000, r001, r01, a00, a0, e00, e0; double Ei, Lint[3], Li[3], t; fb_hier_t hier; fb_input_t input; fb_ret_t retval; fb_units_t units; char string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH]; gsl_rng *rng; const gsl_rng_type *rng_type=gsl_rng_mt19937; const char *short_opts = "m:n:o:r:g:i:a:Q:e:F:t:D:c:A:R:N:z:x:k:s:dVh"; const struct option long_opts[] = { {"m000", required_argument, NULL, 'm'}, {"m001", required_argument, NULL, 'n'}, {"m01", required_argument, NULL, 'o'}, {"r000", required_argument, NULL, 'r'}, {"r001", required_argument, NULL, 'g'}, {"r01", required_argument, NULL, 'i'}, {"a00", required_argument, NULL, 'a'}, {"a0", required_argument, NULL, 'Q'}, {"e00", required_argument, NULL, 'e'}, {"e0", required_argument, NULL, 'F'}, {"tstop", required_argument, NULL, 't'}, {"dt", required_argument, NULL, 'D'}, {"tcpustop", required_argument, NULL, 'c'}, {"absacc", required_argument, NULL, 'A'}, {"relacc", required_argument, NULL, 'R'}, {"ncount", required_argument, NULL, 'N'}, {"tidaltol", required_argument, NULL, 'z'}, {"fexp", required_argument, NULL, 'x'}, {"ks", required_argument, NULL, 'k'}, {"seed", required_argument, NULL, 's'}, {"debug", no_argument, NULL, 'd'}, {"version", no_argument, NULL, 'V'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; /* set parameters to default values */ m000 = FB_M000; m001 = FB_M001; m01 = FB_M01; r000 = FB_R000; r001 = FB_R001; r01 = FB_R01; a00 = FB_A00; a0 = FB_A0; e00 = FB_E00; e0 = FB_E0; input.ks = FB_KS; input.tstop = FB_TSTOP; input.Dflag = 0; input.dt = FB_DT; input.tcpustop = FB_TCPUSTOP; input.absacc = FB_ABSACC; input.relacc = FB_RELACC; input.ncount = FB_NCOUNT; input.tidaltol = FB_TIDALTOL; input.fexp = FB_FEXP; seed = FB_SEED; fb_debug = FB_DEBUG; while ((i = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) { switch (i) { case 'm': m000 = atof(optarg) * FB_CONST_MSUN; break; case 'n': m001 = atof(optarg) * FB_CONST_MSUN; break; case 'o': m01 = atof(optarg) * FB_CONST_MSUN; break; case 'r': r000 = atof(optarg) * FB_CONST_RSUN; break; case 'g': r001 = atof(optarg) * FB_CONST_RSUN; break; case 'i': r01 = atof(optarg) * FB_CONST_RSUN; break; case 'a': a00 = atof(optarg) * FB_CONST_AU; break; case 'Q': a0 = atof(optarg) * FB_CONST_AU; break; case 'e': e00 = atof(optarg); if (e00 >= 1.0) { fprintf(stderr, "e00 must be less than 1\n"); return(1); } break; case 'F': e0 = atof(optarg); if (e0 >= 1.0) { fprintf(stderr, "e0 must be less than 1\n"); return(1); } break; case 't': input.tstop = atof(optarg); break; case 'D': input.Dflag = 1; input.dt = atof(optarg); break; case 'c': input.tcpustop = atof(optarg); break; case 'A': input.absacc = atof(optarg); break; case 'R': input.relacc = atof(optarg); break; case 'N': input.ncount = atoi(optarg); break; case 'z': input.tidaltol = atof(optarg); break; case 'x': input.fexp = atof(optarg); break; case 'k': input.ks = atoi(optarg); break; case 's': seed = atol(optarg); break; case 'd': fb_debug = 1; break; case 'V': fb_print_version(stdout); return(0); case 'h': fb_print_version(stdout); fprintf(stdout, "\n"); print_usage(stdout); return(0); default: break; } } /* check to make sure there was nothing crazy on the command line */ if (optind < argc) { print_usage(stdout); return(1); } /* initialize a few things for integrator */ t = 0.0; hier.nstarinit = 3; hier.nstar = 3; fb_malloc_hier(&hier); fb_init_hier(&hier); /* put stuff in log entry */ snprintf(input.firstlogentry, FB_MAX_LOGENTRY_LENGTH, " command line:"); for (i=0; i<argc; i++) { snprintf(&(input.firstlogentry[strlen(input.firstlogentry)]), FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), " %s", argv[i]); } snprintf(&(input.firstlogentry[strlen(input.firstlogentry)]), FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), "\n"); /* print out values of paramaters */ fprintf(stderr, "PARAMETERS:\n"); fprintf(stderr, " ks=%d seed=%ld\n", input.ks, seed); fprintf(stderr, " a00=%.6g AU e00=%.6g m000=%.6g MSUN m001=%.6g MSUN r000=%.6g RSUN r001=%.6g RSUN\n", \ a00/FB_CONST_AU, e00, m000/FB_CONST_MSUN, m001/FB_CONST_MSUN, r000/FB_CONST_RSUN, r001/FB_CONST_RSUN); fprintf(stderr, " a0=%.6g AU e0=%.6g m01=%.6g MSUN r01=%.6g RSUN\n", \ a0/FB_CONST_AU, e0, m01/FB_CONST_MSUN, r01/FB_CONST_RSUN); fprintf(stderr, " tstop=%.6g tcpustop=%.6g\n", \ input.tstop, input.tcpustop); fprintf(stderr, " tidaltol=%.6g abs_acc=%.6g rel_acc=%.6g ncount=%d fexp=%.6g\n\n", \ input.tidaltol, input.absacc, input.relacc, input.ncount, input.fexp); /* initialize GSL rng */ gsl_rng_env_setup(); rng = gsl_rng_alloc(rng_type); gsl_rng_set(rng, seed); /* create hierarchies */ hier.narr[2] = 1; hier.narr[3] = 1; /* inner binary of triple */ hier.hier[hier.hi[2]+0].obj[0] = &(hier.hier[hier.hi[1]+0]); hier.hier[hier.hi[2]+0].obj[1] = &(hier.hier[hier.hi[1]+1]); hier.hier[hier.hi[2]+0].t = t; /* outer binary of triple */ hier.hier[hier.hi[3]+0].obj[0] = &(hier.hier[hier.hi[2]+0]); hier.hier[hier.hi[3]+0].obj[1] = &(hier.hier[hier.hi[1]+2]); hier.hier[hier.hi[3]+0].t = t; /* give the objects some properties */ for (j=0; j<hier.nstar; j++) { hier.hier[hier.hi[1]+j].ncoll = 1; hier.hier[hier.hi[1]+j].id[0] = j; snprintf(hier.hier[hier.hi[1]+j].idstring, FB_MAX_STRING_LENGTH, "%d", j); hier.hier[hier.hi[1]+j].n = 1; hier.hier[hier.hi[1]+j].obj[0] = NULL; hier.hier[hier.hi[1]+j].obj[1] = NULL; hier.hier[hier.hi[1]+j].Eint = 0.0; hier.hier[hier.hi[1]+j].Lint[0] = 0.0; hier.hier[hier.hi[1]+j].Lint[1] = 0.0; hier.hier[hier.hi[1]+j].Lint[2] = 0.0; } hier.hier[hier.hi[1]+0].R = r000; hier.hier[hier.hi[1]+1].R = r001; hier.hier[hier.hi[1]+2].R = r01; hier.hier[hier.hi[1]+0].m = m000; hier.hier[hier.hi[1]+1].m = m001; hier.hier[hier.hi[1]+2].m = m01; hier.hier[hier.hi[2]+0].m = m000 + m001; hier.hier[hier.hi[3]+0].m = m000 + m001 + m01; hier.hier[hier.hi[2]+0].a = a00; hier.hier[hier.hi[3]+0].a = a0; hier.hier[hier.hi[2]+0].e = e00; hier.hier[hier.hi[3]+0].e = e0; hier.nobj = 1; hier.obj[0] = &(hier.hier[hier.hi[3]+0]); hier.obj[1] = NULL; hier.obj[2] = NULL; /* get the units and normalize */ calc_units(hier.obj, &units); fb_normalize(&hier, units); /* place triple at origin */ for (j=0; j<3; j++) { hier.obj[0]->x[j] = 0.0; hier.obj[0]->v[j] = 0.0; } /* randomize binary orientations and downsync */ fb_randorient(&(hier.hier[hier.hi[3]+0]), rng); fb_downsync(&(hier.hier[hier.hi[3]+0]), t); fb_randorient(&(hier.hier[hier.hi[2]+0]), rng); fb_downsync(&(hier.hier[hier.hi[2]+0]), t); fprintf(stderr, "UNITS:\n"); fprintf(stderr, " v=%.6g km/s l=%.6g AU t=t_dyn=%.6g yr\n", \ units.v/1.0e5, units.l/FB_CONST_AU, units.t/FB_CONST_YR); fprintf(stderr, " M=%.6g M_sun E=%.6g erg\n\n", units.m/FB_CONST_MSUN, units.E); /* trickle down properties (not sure if this is actually needed here, but it doesn't harm anything) */ fb_trickle(&hier, t); /* store the initial energy and angular momentum*/ Ei = fb_petot(&(hier.hier[hier.hi[1]]), hier.nstar) + fb_ketot(&(hier.hier[hier.hi[1]]), hier.nstar) + fb_einttot(&(hier.hier[hier.hi[1]]), hier.nstar); fb_angmom(&(hier.hier[hier.hi[1]]), hier.nstar, Li); fb_angmomint(&(hier.hier[hier.hi[1]]), hier.nstar, Lint); for (j=0; j<3; j++) { Li[j] += Lint[j]; } /* integrate along */ fb_dprintf("calling fewbody()...\n"); /* call fewbody! */ retval = fewbody(input, &hier, &t); /* print information to screen */ fprintf(stderr, "OUTCOME:\n"); if (retval.retval == 1) { fprintf(stderr, " encounter complete: t=%.6g (%.6g yr) %s (%s)\n\n", t, t * units.t/FB_CONST_YR, fb_sprint_hier(hier, string1), fb_sprint_hier_hr(hier, string2)); } else { fprintf(stderr, " encounter NOT complete: t=%.6g (%.6g yr) %s (%s)\n\n", t, t * units.t/FB_CONST_YR, fb_sprint_hier(hier, string1), fb_sprint_hier_hr(hier, string2)); } fb_dprintf("there were %ld integration steps\n", retval.count); fb_dprintf("fb_classify() was called %ld times\n", retval.iclassify); fprintf(stderr, "FINAL:\n"); fprintf(stderr, " t_final=%.6g (%.6g yr) t_cpu=%.6g s\n", \ t, t*units.t/FB_CONST_YR, retval.tcpu); fprintf(stderr, " L0=%.6g DeltaL/L0=%.6g DeltaL=%.6g\n", fb_mod(Li), retval.DeltaLfrac, retval.DeltaL); fprintf(stderr, " E0=%.6g DeltaE/E0=%.6g DeltaE=%.6g\n", Ei, retval.DeltaEfrac, retval.DeltaE); fprintf(stderr, " Rmin=%.6g (%.6g RSUN) Rmin_i=%d Rmin_j=%d\n", \ retval.Rmin, retval.Rmin*units.l/FB_CONST_RSUN, retval.Rmin_i, retval.Rmin_j); fprintf(stderr, " Nosc=%d (%s)\n", retval.Nosc, (retval.Nosc>=1?"resonance":"non-resonance")); /* free GSL stuff */ gsl_rng_free(rng); /* free our own stuff */ fb_free_hier(hier); /* done! */ return(0); }
{ "alphanum_fraction": 0.624734879, "avg_line_length": 33.5945945946, "ext": "c", "hexsha": "121c82a7c67101757b39ce356a314ad15261a818", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": [ "PSF-2.0" ], "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/triple.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_licenses": [ "PSF-2.0" ], "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_path": "ext/fewbod/fewbody-0.26/triple.c", "max_line_length": 132, "max_stars_count": null, "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": [ "PSF-2.0" ], "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/triple.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4787, "size": 13673 }
/* Copyright (c) 2015, Patrick Weltevrede All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_sort_float.h> #include <gsl/gsl_statistics_float.h> #include <gsl/gsl_integration.h> #include "psrsalsa.h" int filterPApoints(datafile_definition *datafile, verbose_definition verbose) { int dPa_polnr; long i, j, nrpoints; float *olddata; if(datafile->poltype != POLTYPE_ILVPAdPA && datafile->poltype != POLTYPE_PAdPA && datafile->poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR filterPApoints: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl."); return -1; } if(datafile->poltype == POLTYPE_ILVPAdPA && datafile->NrPols != 5) { printerror(verbose.debug, "ERROR filterPApoints: 5 polarization channels were expected, but there are only %ld.", datafile->NrPols); return -1; }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl && datafile->NrPols != 8) { printerror(verbose.debug, "ERROR filterPApoints: 8 polarization channels were expected, but there are only %ld.", datafile->NrPols); return -1; }else if(datafile->poltype == POLTYPE_PAdPA && datafile->NrPols != 2) { printerror(verbose.debug, "ERROR filterPApoints: 2 polarization channels were expected, but there are only %ld.", datafile->NrPols); return -1; } if(datafile->NrSubints > 1 || datafile->NrFreqChan > 1) { printerror(verbose.debug, "ERROR filterPApoints: Can only do this opperation if there is one subint and one frequency channel."); return -1; } if(datafile->tsampMode != TSAMPMODE_LONGITUDELIST) { printerror(verbose.debug, "ERROR filterPApoints: Expected pulse longitudes to be defined."); return -1; } if(datafile->poltype == POLTYPE_ILVPAdPA || datafile->poltype == POLTYPE_ILVPAdPATEldEl) { dPa_polnr = 4; }else if(datafile->poltype == POLTYPE_PAdPA) { dPa_polnr = 1; } nrpoints = 0; for(i = 0; i < datafile->NrBins; i++) { if(datafile->data[i+dPa_polnr*datafile->NrBins] > 0 && isfinite(datafile->data[i+dPa_polnr*datafile->NrBins])) { nrpoints++; } } if(verbose.verbose) printf("Keeping %ld significant PA points\n", nrpoints); olddata = datafile->data; datafile->data = (float *)malloc(nrpoints*datafile->NrPols*sizeof(float)); if(datafile->data == NULL) { printerror(verbose.debug, "ERROR filterPApoints: Memory allocation error."); return -1; } j = 0; for(i = 0; i < datafile->NrBins; i++) { if(olddata[i+dPa_polnr*datafile->NrBins] > 0 && isfinite(olddata[i+dPa_polnr*datafile->NrBins])) { if(datafile->poltype == POLTYPE_ILVPAdPA) { datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins]; datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins]; datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins]; datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins]; datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins]; }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl) { datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins]; datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins]; datafile->data[j+2*nrpoints] = olddata[i+2*datafile->NrBins]; datafile->data[j+3*nrpoints] = olddata[i+3*datafile->NrBins]; datafile->data[j+4*nrpoints] = olddata[i+4*datafile->NrBins]; datafile->data[j+5*nrpoints] = olddata[i+5*datafile->NrBins]; datafile->data[j+6*nrpoints] = olddata[i+6*datafile->NrBins]; datafile->data[j+7*nrpoints] = olddata[i+7*datafile->NrBins]; }else { datafile->data[j+0*nrpoints] = olddata[i+0*datafile->NrBins]; datafile->data[j+1*nrpoints] = olddata[i+1*datafile->NrBins]; } datafile->tsamp_list[j] = datafile->tsamp_list[i]; j++; } } free(olddata); datafile->NrBins = nrpoints; return datafile->NrBins; } int make_paswing_fromIQUV_remove_lowS2N_points_sp_isLsignificant(float sigma_limit, int sigmaI, float dataL, float rmsI, float rmsL, verbose_definition verbose) { if(sigmaI == 0) { if(dataL < sigma_limit*rmsL) { return 0; } return 1; }else { if(dataL < sigma_limit*rmsI) { return 0; } return 1; } } int make_paswing_fromIQUV_remove_lowS2N_points_sp_isPsignificant(float sigma_limit, int sigmaI, float dataP, float rmsI, float rmsP, verbose_definition verbose) { if(sigmaI == 0) { if(dataP < sigma_limit*rmsP) { return 0; } return 1; }else { if(dataP < sigma_limit*rmsI) { return 0; } return 1; } } int make_paswing_fromIQUV_remove_lowS2N_points_sp_isVsignificant(float sigma_limit, int sigmaI, float dataV, float rmsI, float rmsV, verbose_definition verbose) { if(sigmaI == 0) { if(fabs(dataV) < sigma_limit*rmsV) { return 0; } return 1; }else { if(fabs(dataV) < sigma_limit*rmsI) { return 0; } return 1; } } void make_paswing_fromIQUV_remove_lowS2N_points_sp(float sigma_limit, int sigmaI, int nrBins, float *dataL, float *dataP, float *dataPA, float *dataPaErr, float *dataEll, float *dataEllErr, float rmsI, float rmsL, float rmsP, pulselongitude_regions_definition *onpulse, verbose_definition verbose) { long j; if(sigma_limit < 0) { return; } for(j = 0; j < nrBins; j++) { int issignificant; issignificant = 1; if(onpulse != NULL) { if(checkRegions(j, onpulse, 0, verbose) == 0) { issignificant = 0; } } if(dataL != NULL && (dataPA != NULL || dataPaErr != NULL)) { if(issignificant == 0 || make_paswing_fromIQUV_remove_lowS2N_points_sp_isLsignificant(sigma_limit, sigmaI, dataL[j], rmsI, rmsL, verbose) == 0) { if(dataPA != NULL) { dataPA[j] = 0; } if(dataPaErr != NULL) { dataPaErr[j] = -1; } } } if(dataP != NULL && (dataEll != NULL || dataEllErr != NULL)) { if(issignificant == 0 || make_paswing_fromIQUV_remove_lowS2N_points_sp_isPsignificant(sigma_limit, sigmaI, dataP[j], rmsI, rmsP, verbose) == 0) { if(dataEll != NULL) { dataEll[j] = 0; } if(dataEllErr != NULL) { dataEllErr[j] = -1; } } } } } int make_paswing_fromIQUV_sp(float *dataI, float *dataQ, float *dataU, float *dataV, int nrBins, float *dataL, float *dataP, float *dataPA, float *dataPaErr, float *dataEll, float *dataEllErr, float *baseline_intensity, float *rmsI, float *rmsQ, float *rmsU, float *rmsV, float *rmsL, float *rmsP, float *medianL, float *medianP, pulselongitude_regions_definition onpulse, int normalize, int correctLbias, int correctPbias, float correctQV, float correctV, float paoffset, int rms_file_nrBins, float *rms_file_I, float *rms_file_Q, float *rms_file_U, float *rms_file_V, float rebin_factor, verbose_definition verbose) { int rms_file_specified; float *Loffpulse, *Poffpulse, median_L, median_P; double ymax, avrgI, RMSI, RMSQ, RMSU, RMSV, RMSL, RMSP; long i, nrOffpulseBins; rms_file_specified = 1; if(rms_file_I == NULL) { rms_file_I = dataI; rms_file_Q = dataQ; rms_file_U = dataU; rms_file_V = dataV; rms_file_nrBins = nrBins; rms_file_specified = 0; } Loffpulse = (float *)malloc(rms_file_nrBins*sizeof(float)); Poffpulse = (float *)malloc(rms_file_nrBins*sizeof(float)); if(Loffpulse == NULL || Poffpulse == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV_sp: Memory allocation error."); return 0; } if(normalize == 0) { ymax = 1; }else { ymax = dataI[0]; for(i = 1; i < nrBins; i++) { if(dataI[i] > ymax) { ymax = dataI[i]; } } if(ymax == 0) { ymax = 1; } } if(ymax != 1.0 || correctQV != 1.0 || correctV != 1.0) { for(i = 0; i < nrBins; i++) { dataI[i] /= ymax; dataQ[i] /= correctQV*ymax; dataU[i] /= ymax; dataV[i] /= correctV*correctQV*ymax; } if(rms_file_specified) { for(i = 0; i < rms_file_nrBins; i++) { rms_file_I[i] /= ymax; rms_file_Q[i] /= correctQV*ymax; rms_file_U[i] /= ymax; rms_file_V[i] /= correctV*correctQV*ymax; } } } nrOffpulseBins = 0; avrgI = 0; RMSI = 0; RMSQ = 0; RMSU = 0; RMSV = 0; RMSL = 0; RMSP = 0; for(i = 0; i < rms_file_nrBins; i++) { if(checkRegions(i, &onpulse, 0, verbose) == 0) { double sampleI2, sampleQ2, sampleU2, sampleV2; avrgI += rms_file_I[i]; sampleI2 = rms_file_I[i]*rms_file_I[i]; sampleQ2 = rms_file_Q[i]*rms_file_Q[i]; sampleU2 = rms_file_U[i]*rms_file_U[i]; sampleV2 = rms_file_V[i]*rms_file_V[i]; RMSI += sampleI2; RMSQ += sampleQ2; RMSU += sampleU2; RMSV += sampleV2; RMSL += sampleQ2+sampleU2; RMSP += sampleQ2+sampleU2+sampleV2; Loffpulse[nrOffpulseBins] = sqrt(sampleQ2+sampleU2); Poffpulse[nrOffpulseBins] = sqrt(sampleQ2+sampleU2+sampleV2); nrOffpulseBins++; } } avrgI /= (double)nrOffpulseBins; RMSI = sqrt(RMSI/(double)nrOffpulseBins); RMSQ = sqrt(RMSQ/(double)nrOffpulseBins); RMSU = sqrt(RMSU/(double)nrOffpulseBins); RMSV = sqrt(RMSV/(double)nrOffpulseBins); RMSL = sqrt(RMSL/(double)nrOffpulseBins); RMSP = sqrt(RMSP/(double)nrOffpulseBins); if(rms_file_specified) { double scale = 1.0/sqrt(rebin_factor); RMSI *= scale; RMSQ *= scale; RMSU *= scale; RMSV *= scale; RMSL *= scale; RMSP *= scale; } gsl_sort_float(Loffpulse, 1, nrOffpulseBins); median_L = gsl_stats_float_median_from_sorted_data(Loffpulse, 1, nrOffpulseBins); gsl_sort_float(Poffpulse, 1, nrOffpulseBins); median_P = gsl_stats_float_median_from_sorted_data(Poffpulse, 1, nrOffpulseBins); if(baseline_intensity != NULL) *baseline_intensity = avrgI; if(rmsI != NULL) *rmsI = RMSI; if(rmsQ != NULL) *rmsQ = RMSQ; if(rmsU != NULL) *rmsU = RMSU; if(rmsV != NULL) *rmsV = RMSV; if(rmsL != NULL) *rmsL = RMSL; if(rmsP != NULL) *rmsP = RMSP; if(medianL != NULL) *medianL = median_L; if(medianP != NULL) *medianP = median_P; for(i = 0; i < nrBins; i++) { double sampleQ2, sampleU2, sampleV2, sampleL, sampleP; sampleQ2 = dataQ[i]*dataQ[i]; sampleU2 = dataU[i]*dataU[i]; sampleV2 = dataV[i]*dataV[i]; sampleL = sqrt(sampleQ2+sampleU2); if(correctLbias == 0) { sampleL -= median_L; }else if(correctLbias == 1) { double junk = (sqrt(0.5*(RMSQ*RMSQ+RMSU*RMSU))/sampleL); if(junk < 1.0) { sampleL *= sqrt(1.0-junk*junk); }else { sampleL = 0.0; } } if(dataL != NULL) { dataL[i] = sampleL; } sampleP = sqrt(sampleQ2+sampleU2+sampleV2); if(correctPbias == 0) { sampleP -= median_P; } if(dataP != NULL) { dataP[i] = sampleP; } if(dataPA != NULL) { dataPA[i] = 90.0*atan2(dataU[i], dataQ[i])/M_PI; if(paoffset != 0.0) { dataPA[i] += paoffset; dataPA[i] = derotate_180_small_double(dataPA[i]); } } if(dataPaErr != NULL) { if(sampleQ2 == 0 && sampleU2 == 0) { dataPaErr[i] = 0; }else { dataPaErr[i] = sqrt(sampleQ2*RMSU*RMSU + sampleU2*RMSQ*RMSQ); dataPaErr[i] /= 2.0*(sampleQ2 + sampleU2); dataPaErr[i] *= 180.0/M_PI; } } if(dataEll != NULL) { if(sampleQ2 == 0 && sampleU2 == 0 && sampleV2 == 0) { dataEll[i] = 0; } double value; value = dataV[i]/sqrt(sampleQ2+sampleU2+sampleV2); if(value < -1.0) { value = -1.0; }else if(value > 1.0) { value = 1.0; } dataEll[i] = 90.0*asin(value)/M_PI; } if(dataEllErr != NULL) { if(dataQ[i] == 0 && dataU[i] == 0 && dataV[i] == 0) { dataEllErr[i] = -1; } dataEllErr[i] = sampleV2*(sampleQ2*RMSQ*RMSQ+sampleU2*RMSU*RMSU); dataEllErr[i] += (sampleQ2+sampleU2)*(sampleQ2+sampleU2)*RMSV*RMSV; dataEllErr[i] /= 4.0*(sampleQ2+sampleU2); dataEllErr[i] = sqrt(dataEllErr[i]); dataEllErr[i] /= (sampleQ2+sampleU2+sampleV2); dataEllErr[i] *= 180.0/M_PI; } } free(Loffpulse); free(Poffpulse); return 1; } void make_paswing_fromIQUV_reportRMS(long pulsenr, long freqnr, int extended, int spstat, float rmsI, float rmsQ, float rmsU, float rmsV, float rmsL, float rmsP, float medianL, float medianP, float baseline_intensity, verbose_definition verbose) { int indent; if(spstat == 0) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " PA conversion output for subint %ld frequency channel %ld:\n", pulsenr, freqnr); } for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " Avrg baseline Stokes I: %f (only reported, not subtracted)\n", baseline_intensity); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS I: %f\n", rmsI); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS Q: %f\n", rmsQ); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS U: %f\n", rmsU); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS V: %f\n", rmsV); for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS L (before de-bias): %f\n", rmsL); if(extended) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " RMS sqrt(Q^2+U^2+V^2): %f\n", rmsP); } for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " Median L: %f\n", medianL); if(extended) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " Median sqrt(Q^2+U^2+V^2): %f\n", medianP); } } int make_paswing_fromIQUV(datafile_definition *datafile, int extended, int spstat, float sigma_limit, int sigmaI, pulselongitude_regions_definition onpulse, int normalize, int correctLbias, int correctPbias, float correctQV, float correctV, int nolongitudes, float loffset, float paoffset, datafile_definition *rms_file, float rebin_factor, int onpulseonly, verbose_definition verbose) { int indent, output_nr_pols; long i, pulsenr, freqnr; float *newdata, *newdata_current_pulse; if(verbose.verbose) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); printf("Constructing PA and degree of linear polarization"); if(extended) printf(", total polarization and ellipticity"); if(rms_file != NULL) printf(" (using a seperate file to determine the off-pulse rms)"); printf("\n"); for(indent = 0; indent < verbose.indent; indent++) printf(" "); printf(" Reference frequency for PA is "); if(datafile->isDeFarad) { if((datafile->freq_ref > -1.1 && datafile->freq_ref < -0.9) || (datafile->freq_ref > 0.99e10 && datafile->freq_ref < 1.01e10)) printf("infinity\n"); else if(datafile->freq_ref < 0) printf("unknown\n"); else printf("%f MHz\n", datafile->freq_ref); }else { if(datafile->NrFreqChan == 1) printf("%lf MHz\n", get_centre_frequency(*datafile, verbose)); else printf("observing frequencies of individual frequency channels\n"); } for(indent = 0; indent < verbose.indent; indent++) printf(" "); printf(" "); switch(correctLbias) { case -1: printf("No L de-bias applied"); break; case 0: printf("De-bias L using median noise subtraction"); break; case 1: printf("De-bias L using Wardle & Kronberg correction"); break; default: printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Undefined L de-bias method specified."); return 0; } if(extended) { switch(correctPbias) { case -1: printf(", no P de-bias applied"); break; case 0: printf(", de-bias P using median noise subtraction"); break; case 1: printf(", de-bias P using Wardle & Kronberg like correction"); break; default: printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Undefined P de-bias method specified."); return 0; } } if(correctQV != 1 || correctV != 1) printf(", Q correction factor %f, V correction factor %f", 1.0/correctQV, 1.0/(correctQV*correctV)); if(normalize) printf(", output is normalised"); if(loffset != 0) printf(", pulse longitude shifted by %f deg\n", loffset); if(paoffset != 0) printf(", PA shifted by %f deg\n", paoffset); printf("\n"); } if(datafile->NrPols != 4) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Expected 4 input polarizations."); return 0; } if(rms_file != NULL) { if(rms_file->NrPols != 4) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Expected 4 input polarizations."); return 0; } } if(datafile->poltype != POLTYPE_STOKES) { if(datafile->poltype == POLTYPE_UNKNOWN) { printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Polarization state unknown, it is assumed the data are Stokes parameters."); }else { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Please convert data into Stokes parameters first."); return 0; } } if(rms_file != NULL) { if(rms_file->poltype != POLTYPE_STOKES) { if(rms_file->poltype == POLTYPE_UNKNOWN) { printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Polarization state of the data to be used to determine the off-pulse rms is unknown. It is assumed the data are Stokes parameters."); }else { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Please convert data to be used to determine the off-pulse rms into Stokes parameters first."); return 0; } } } if(datafile->tsampMode != TSAMPMODE_FIXEDTSAMP) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: It is expected that the input has a uniform time sampling."); return 0; } if(correctQV == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: correctQV is set to zero, you probably want this to be 1."); return 0; } if(correctV == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: correctV is set to zero, you probably want this to be 1."); return 0; } if(datafile->isDebase == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase."); return 0; }else if(datafile->isDebase != 1) { fflush(stdout); printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Unknown baseline removal state. It will be assumed the baseline has already removed from the data."); } if(rms_file != NULL) { if(rms_file->isDebase == 0) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Please remove baseline first, i.e. use pmod -debase."); return 0; }else if(rms_file->isDebase != 1) { fflush(stdout); printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Unknown baseline removal state. It is assumed the baseline has already removed from the data."); } if(datafile->NrSubints != rms_file->NrSubints) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Number of subintegrations is different in the data to be used to determine the off-pulse rms compared to the data used to compute the polarization information."); return 0; } if(datafile->NrFreqChan != rms_file->NrFreqChan) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Number of frequency channels is different in the data to be used to determine the off-pulse rms compared to the data used to compute the polarization information (%ld != %ld).", rms_file->NrFreqChan, datafile->NrFreqChan); return 0; } if(correctLbias == 0) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Subtracting the median of L is not supported when a separate file is used for the off-pulse statistics."); return 0; } if(extended && correctPbias == 0) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Subtracting the median of P is not supported when a separate file is used for the off-pulse statistics."); return 0; } } if(normalize && (datafile->NrSubints > 1 || datafile->NrFreqChan > 1)) { if(spstat == 0) { fflush(stdout); printwarning(verbose.debug, "WARNING make_paswing_fromIQUV: Normalization of the polarization information will cause all subintegrations/frequency channels to be normalised individually. This may not be desired."); } } if(extended) { output_nr_pols = 8; }else { output_nr_pols = 5; } if(spstat == 0) { newdata = (float *)malloc(datafile->NrBins*datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float)); }else { newdata = (float *)malloc(datafile->NrBins*output_nr_pols*sizeof(float)); newdata_current_pulse = (float *)malloc(datafile->NrBins*output_nr_pols*sizeof(float)); } if(datafile->offpulse_rms != NULL) { free(datafile->offpulse_rms); } if(spstat == 0) { datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*output_nr_pols*sizeof(float)); }else { datafile->offpulse_rms = (float *)malloc(output_nr_pols*sizeof(float)); } if(newdata == NULL || datafile->offpulse_rms == NULL ) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Memory allocation error."); return 0; } if(nolongitudes == 0) { datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double)); if(datafile->tsamp_list == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Memory allocation error."); return 0; } for(i = 0; i < datafile->NrBins; i++) { datafile->tsamp_list[i] = get_pulse_longitude(*datafile, 0, i, verbose); datafile->tsamp_list[i] += loffset; } } float *dataI, *dataQ, *dataU, *dataV, *newdataL, *newdataP, *newdataPa, *newdataPaErr, *newdataEll, *newdataEllErr; float baseline_intensity, rmsI, rmsQ, rmsU, rmsV, rmsL, rmsP, medianL, medianP; for(pulsenr = 0; pulsenr < datafile->NrSubints; pulsenr++) { for(freqnr = 0; freqnr < datafile->NrFreqChan; freqnr++) { int normalize_sp; dataI = &(datafile->data[datafile->NrBins*(0+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]); dataQ = &(datafile->data[datafile->NrBins*(1+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]); dataU = &(datafile->data[datafile->NrBins*(2+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]); dataV = &(datafile->data[datafile->NrBins*(3+datafile->NrPols*(freqnr+pulsenr*datafile->NrFreqChan))]); if(spstat == 0) { newdataL = &(newdata[datafile->NrBins*(1+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]); newdataPa = &(newdata[datafile->NrBins*(3+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]); newdataPaErr = &(newdata[datafile->NrBins*(4+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]); normalize_sp = normalize; }else { newdataL = &(newdata_current_pulse[datafile->NrBins*1]); newdataPa = NULL; newdataPaErr = NULL; normalize_sp = 0; } if(extended == 0) { newdataP = NULL; newdataEll = NULL; newdataEllErr = NULL; }else { if(spstat == 0) { newdataP = &(newdata[datafile->NrBins*(5+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]); newdataEll = &(newdata[datafile->NrBins*(6+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]); newdataEllErr = &(newdata[datafile->NrBins*(7+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))]); }else { newdataP = &(newdata_current_pulse[datafile->NrBins*5]); newdataEll = NULL; newdataEllErr = NULL; } } long rms_file_nrBins; float *rms_file_I, *rms_file_Q, *rms_file_U, *rms_file_V; if(rms_file != NULL) { rms_file_nrBins = rms_file->NrBins; rms_file_I = &(rms_file->data[rms_file->NrBins*(0+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]); rms_file_Q = &(rms_file->data[rms_file->NrBins*(1+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]); rms_file_U = &(rms_file->data[rms_file->NrBins*(2+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]); rms_file_V = &(rms_file->data[rms_file->NrBins*(3+rms_file->NrPols*(freqnr+pulsenr*rms_file->NrFreqChan))]); }else { rms_file_nrBins = 0; rms_file_I = NULL; rms_file_Q = NULL; rms_file_U = NULL; rms_file_V = NULL; } if(make_paswing_fromIQUV_sp(dataI, dataQ, dataU, dataV, datafile->NrBins, newdataL, newdataP, newdataPa, newdataPaErr, newdataEll, newdataEllErr, &baseline_intensity, &rmsI, &rmsQ, &rmsU, &rmsV, &rmsL, &rmsP, &medianL, &medianP, onpulse, normalize_sp, correctLbias, correctPbias, correctQV, correctV, paoffset, rms_file_nrBins, rms_file_I, rms_file_Q, rms_file_U, rms_file_V, rebin_factor, verbose) == 0) { printerror(verbose.debug, "ERROR make_paswing_fromIQUV: Calculating polarization products failed."); return 0; } pulselongitude_regions_definition *onpulse_ptr; onpulse_ptr = NULL; if(onpulseonly) { onpulse_ptr = &onpulse; } make_paswing_fromIQUV_remove_lowS2N_points_sp(sigma_limit, sigmaI, datafile->NrBins, newdataL, newdataP, newdataPa, newdataPaErr, newdataEll, newdataEllErr, rmsI, rmsL, rmsP, onpulse_ptr, verbose); if(spstat == 0) { for(i = 0; i < datafile->NrBins; i++) { newdata[datafile->NrBins*(0+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))+i] = dataI[i]; newdata[datafile->NrBins*(2+output_nr_pols*(freqnr+datafile->NrFreqChan*pulsenr))+i] = dataV[i]; } datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsI; datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsL; datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsV; datafile->offpulse_rms[3+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; datafile->offpulse_rms[4+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; if(extended) { datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = rmsP; datafile->offpulse_rms[6+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; datafile->offpulse_rms[7+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)] = -1; } } if(verbose.verbose) { if(spstat == 0 && ((freqnr == 0 && pulsenr == 0) || verbose.debug)) { if(datafile->NrFreqChan > 1 || datafile->NrSubints > 1) { for(indent = 0; indent < verbose.indent; indent++) printf(" "); fprintf(stdout, " Statistics based on first processed pulse\n"); } if(extended) { make_paswing_fromIQUV_reportRMS(pulsenr, freqnr, extended, spstat, datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], rmsQ, rmsU, datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], datafile->offpulse_rms[5+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], medianL, medianP, baseline_intensity, verbose); }else { make_paswing_fromIQUV_reportRMS(pulsenr, freqnr, extended, spstat, datafile->offpulse_rms[0+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], rmsQ, rmsU, datafile->offpulse_rms[2+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], datafile->offpulse_rms[1+output_nr_pols*(freqnr + datafile->NrFreqChan*pulsenr)], 0.0, medianL, 0.0, baseline_intensity, verbose); } } } } } free(datafile->data); datafile->data = newdata; if(nolongitudes == 0) { datafile->tsampMode = TSAMPMODE_LONGITUDELIST; } datafile->NrPols = output_nr_pols; if(extended) { datafile->poltype = POLTYPE_ILVPAdPATEldEl; }else { datafile->poltype = POLTYPE_ILVPAdPA; } return 1; } void paswing_remove_observed_PA_swing_sp(float *dataPA, float *dataPAerr, float *dataPAref, float *dataPArefErr, int nrBins, int add, verbose_definition verbose) { int ok; long j; for(j = 0; j < nrBins; j++) { ok = 1; if(dataPAerr != NULL) { if(dataPAerr[j] < 0) { ok = 0; } } if(dataPArefErr != NULL) { if(dataPArefErr[j] < 0) { ok = 0; dataPA[j] = 0; if(dataPAerr != NULL) { dataPAerr[j] = -1; } } } if(ok) { if(add) { dataPA[j] += dataPAref[j]; }else { dataPA[j] -= dataPAref[j]; } dataPA[j] = derotate_180(dataPA[j]) - 90; if(dataPAerr != NULL && dataPArefErr != NULL) { dataPAerr[j] = sqrt(dataPAerr[j]*dataPAerr[j]+dataPArefErr[j]*dataPArefErr[j]); } }else { dataPA[j] = 0; if(dataPAerr != NULL) { dataPAerr[j] = -1; } } } } int paswing_remove_observed_PA_swing(datafile_definition *datafile, datafile_definition datafile_reference, int add, verbose_definition verbose) { int pachannel_ref, pachannelerr_ref, pachannel, pachannelerr; if(datafile->poltype != POLTYPE_ILVPAdPA && datafile->poltype != POLTYPE_PAdPA && datafile->poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl."); return 0; } if(datafile_reference.poltype != POLTYPE_ILVPAdPA && datafile_reference.poltype != POLTYPE_PAdPA && datafile_reference.poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: Data in the reference doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl."); return 0; } if(datafile->poltype == POLTYPE_ILVPAdPA && datafile->NrPols != 5) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: 5 polarization channels were expected, but there are only %ld.", datafile->NrPols); return 0; }else if(datafile->poltype == POLTYPE_ILVPAdPATEldEl && datafile->NrPols != 8) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: 8 polarization channels were expected, but there are only %ld.", datafile->NrPols); return 0; }else if(datafile->poltype == POLTYPE_PAdPA && datafile->NrPols != 2) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: 2 polarization channels were expected, but there are only %ld.", datafile->NrPols); return 0; } if(datafile_reference.poltype == POLTYPE_ILVPAdPA && datafile_reference.NrPols != 5) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: 5 polarization channels were expected in the reference, but there are only %ld.", datafile_reference.NrPols); return 0; }else if(datafile_reference.poltype == POLTYPE_ILVPAdPATEldEl && datafile_reference.NrPols != 8) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: 8 polarization channels were expected in the reference, but there are only %ld.", datafile_reference.NrPols); return 0; }else if(datafile_reference.poltype == POLTYPE_PAdPA && datafile_reference.NrPols != 2) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: 2 polarization channels were expected in the reference, but there are only %ld.", datafile_reference.NrPols); return 0; } if(datafile_reference.NrBins != datafile->NrBins) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: Mismatch in the number of bins in the data and the reference (%ld != %ld).", datafile->NrBins, datafile_reference.NrBins); return 0; } if(datafile_reference.NrFreqChan != 1) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: The number of frequency channels in the reference should be 1 (it is %ld).", datafile_reference.NrFreqChan); return 0; } if(datafile_reference.NrSubints != 1) { printerror(verbose.debug, "ERROR paswing_remove_observed_PA_swing: The number of subints in the reference should be 1 (it is %ld).", datafile_reference.NrSubints); return 0; } if(datafile->poltype == POLTYPE_ILVPAdPA || datafile->poltype == POLTYPE_ILVPAdPATEldEl) { pachannel = 3; pachannelerr = 4; }else if(datafile->poltype == POLTYPE_PAdPA) { pachannel = 0; pachannelerr = 1; } if(datafile_reference.poltype == POLTYPE_ILVPAdPA || datafile_reference.poltype == POLTYPE_ILVPAdPATEldEl) { pachannel_ref = 3; pachannelerr_ref = 4; }else if(datafile_reference.poltype == POLTYPE_PAdPA) { pachannel_ref = 0; pachannelerr_ref = 1; } long i, f; for(i = 0; i < datafile->NrSubints; i++) { for(f = 0; f < datafile->NrFreqChan; f++) { paswing_remove_observed_PA_swing_sp(&(datafile->data[datafile->NrBins*(pachannel + datafile->NrPols*(f+datafile->NrFreqChan*i))]), &(datafile->data[datafile->NrBins*(pachannelerr + datafile->NrPols*(f+datafile->NrFreqChan*i))]), &(datafile_reference.data[datafile->NrBins*pachannel_ref]), &(datafile_reference.data[datafile->NrBins*pachannelerr_ref]), datafile->NrBins, add, verbose); } } return 1; } int writePPOLHeader(datafile_definition datafile, int argc, char **argv, verbose_definition verbose) { char *txt; txt = malloc(10000); if(txt == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR writePPOLHeader: Memory allocation error."); return 0; } constructCommandLineString(txt, 10000, argc, argv, verbose); fprintf(datafile.fptr_hdr, "#ppol file: %s\n", txt); free(txt); return 1; } int readPPOLHeader(datafile_definition *datafile, int extended, verbose_definition verbose) { float dummy_float; int ret, maxlinelength, nrwords; char *txt, *ret_ptr, *word_ptr; maxlinelength = 2000; txt = malloc(maxlinelength); if(txt == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error."); return 0; } datafile->isFolded = 1; datafile->foldMode = FOLDMODE_FIXEDPERIOD; datafile->fixedPeriod = 0; datafile->tsampMode = TSAMPMODE_LONGITUDELIST; datafile->fixedtsamp = 0; datafile->tsubMode = TSUBMODE_FIXEDTSUB; if(datafile->tsub_list != NULL) free(datafile->tsub_list); datafile->tsub_list = (double *)malloc(sizeof(double)); if(datafile->tsub_list == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error"); return 0; } datafile->tsub_list[0] = 0; datafile->NrSubints = 1; datafile->NrFreqChan = 1; datafile->datastart = 0; rewind(datafile->fptr); ret = fread(txt, 1, 3, datafile->fptr); txt[3] = 0; if(ret != 3) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: cannot read from file."); free(txt); return 0; } if(strcmp(txt, "#pp") != 0 ) { fflush(stdout); printwarning(verbose.debug, "WARNING readPPOLHeader: File does not appear to be in PPOL or PPOLSHORT format. I will try to load file, but this will probably fail. Did you run ppol first?"); } skipallhashedlines(datafile); datafile->NrBins = 0; dummy_float = 0; do { ret_ptr = fgets(txt, maxlinelength, datafile->fptr); if(ret_ptr != NULL) { if(txt[0] != '#') { if(extended) { word_ptr = pickWordFromString(txt, 2, &nrwords, 1, ' ', verbose); if(nrwords != 10 && nrwords != 14) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Line should have 10 or 14 words, got %d", nrwords); if(nrwords == 3) printerror(verbose.debug, " Maybe file is in format %s?", returnFileFormat_str(PPOL_SHORT_format)); printerror(verbose.debug, " Line: '%s'.", txt); free(txt); return 0; } if(nrwords == 10) { datafile->poltype = POLTYPE_ILVPAdPA; datafile->NrPols = 5; }else { datafile->poltype = POLTYPE_ILVPAdPATEldEl; datafile->NrPols = 8; } }else { word_ptr = pickWordFromString(txt, 1, &nrwords, 1, ' ', verbose); if(nrwords != 3) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Line should have 3 words, got %d", nrwords); if(nrwords == 10) printerror(verbose.debug, " Maybe file is in format %s?", returnFileFormat_str(PPOL_format)); printerror(verbose.debug, " Line: '%s'.", txt); free(txt); return 0; } } ret = sscanf(word_ptr, "%f", &dummy_float); if(ret != 1) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Cannot interpret as a float: '%s'.", txt); free(txt); return 0; } if(dummy_float >= 360) { fflush(stdout); printwarning(verbose.debug, "WARNING: IGNORING POINTS AT PULSE LONGITUDES > 360 deg."); }else { (datafile->NrBins)++; } } } }while(ret_ptr != NULL && dummy_float < 360); if(extended == 0) { datafile->poltype = POLTYPE_PAdPA; datafile->NrPols = 2; } fflush(stdout); if(verbose.verbose) fprintf(stdout, "Going to load %ld points from %s\n", datafile->NrBins, datafile->filename); if(datafile->NrBins == 0) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: No data in %s", datafile->filename); free(txt); return 0; } fseek(datafile->fptr, datafile->datastart, SEEK_SET); free(txt); if(datafile->offpulse_rms != NULL) { free(datafile->offpulse_rms); datafile->offpulse_rms = NULL; } if(extended) { datafile->offpulse_rms = (float *)malloc(datafile->NrSubints*datafile->NrFreqChan*datafile->NrPols*sizeof(float)); if(datafile->offpulse_rms == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error"); return 0; } } datafile->tsamp_list = (double *)malloc(datafile->NrBins*sizeof(double)); if(datafile->tsamp_list == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLHeader: Memory allocation error"); return 0; } return 1; } int readPPOLfile(datafile_definition *datafile, float *data, int extended, float add_longitude_shift, verbose_definition verbose) { int maxlinelength; long i, k, dummy_long; char *txt, *ret_ptr; if(datafile->NrBins == 0) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLfile: No data in %s", datafile->filename); return 0; } maxlinelength = 2000; txt = malloc(maxlinelength); if(txt == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLfile: Memory allocation error."); return 0; } fseek(datafile->fptr, datafile->datastart, SEEK_SET); k = 0; if(extended) { datafile->offpulse_rms[3] = -1; datafile->offpulse_rms[4] = -1; if(datafile->NrPols == 8) { datafile->offpulse_rms[6] = -1; datafile->offpulse_rms[7] = -1; } } for(i = 0; i < datafile->NrBins; i++) { ret_ptr = fgets(txt, maxlinelength, datafile->fptr); if(ret_ptr == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR readPPOLfile: Cannot read next line, should not happen after successfully reading in header"); free(txt); return 0; } if(txt[0] != '#') { if(extended == 0) { sscanf(txt, "%lf %f %f", &(datafile->tsamp_list[k]), &(data[k]), &(data[k+datafile->NrBins])); }else { if(datafile->NrPols == 8) { sscanf(txt, "%ld %lf %f %f %f %f %f %f %f %f %f %f %f %f", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins]), &(data[k+5*datafile->NrBins]), &(datafile->offpulse_rms[5]), &(data[k+6*datafile->NrBins]), &(data[k+7*datafile->NrBins])); }else { sscanf(txt, "%ld %lf %f %f %f %f %f %f %f %f", &dummy_long, &(datafile->tsamp_list[k]), &(data[k]), &(datafile->offpulse_rms[0]), &(data[k+datafile->NrBins]), &(datafile->offpulse_rms[1]), &(data[k+2*datafile->NrBins]), &(datafile->offpulse_rms[2]), &(data[k+3*datafile->NrBins]), &(data[k+4*datafile->NrBins])); } } datafile->tsamp_list[k] += add_longitude_shift; if(datafile->tsamp_list[k] >= 0 && datafile->tsamp_list[k] < 360) { k++; }else { fflush(stdout); printwarning(verbose.debug, "WARNING readPPOLfile: IGNORING POINTS AT PULSE LONGITUDES outside range 0 ... 360 deg."); } } } if(k != datafile->NrBins) { fflush(stdout); printerror(verbose.debug, "WARNING readPPOLfile: The nr of bins read in is different as determined from header. Something is wrong."); return 0; } fflush(stdout); if(verbose.verbose) fprintf(stdout, "readPPOLfile: Accepted %ld points\n", datafile->NrBins); free(txt); return 1; } int writePPOLfile(datafile_definition datafile, float *data, int extended, int onlysignificantPA, int twoprofiles, float PAoffset, verbose_definition verbose) { long j; if(datafile.poltype != POLTYPE_ILVPAdPA && datafile.poltype != POLTYPE_PAdPA && datafile.poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR writePPOLfile: Data doesn't appear to have poltype ILVPAdPA, PAdPA or ILVPAdPATEldEl (it is %d).", datafile.poltype); return 0; } if(datafile.poltype == POLTYPE_ILVPAdPA && datafile.NrPols != 5) { printerror(verbose.debug, "ERROR writePPOLfile: 5 polarization channels were expected, but there are %ld.", datafile.NrPols); return 0; }else if(datafile.poltype == POLTYPE_PAdPA && datafile.NrPols != 2) { printerror(verbose.debug, "ERROR writePPOLfile: 2 polarization channels were expected, but there are %ld.", datafile.NrPols); return 0; }else if(datafile.poltype == POLTYPE_ILVPAdPATEldEl && datafile.NrPols != 8) { printerror(verbose.debug, "ERROR writePPOLfile: 8 polarization channels were expected, but there are %ld.", datafile.NrPols); return 0; } if(datafile.NrSubints > 1 || datafile.NrFreqChan > 1) { printerror(verbose.debug, "ERROR writePPOLfile: Can only do this opperation if there is one subint and one frequency channel."); return 0; } if(datafile.tsampMode != TSAMPMODE_LONGITUDELIST) { printerror(verbose.debug, "ERROR writePPOLfile: Expected pulse longitudes to be defined."); return 0; } int pa_offset, dpa_offset; if(datafile.poltype == POLTYPE_ILVPAdPA || datafile.poltype == POLTYPE_ILVPAdPATEldEl) { pa_offset = 3; dpa_offset = 4; }else if(datafile.poltype == POLTYPE_PAdPA) { pa_offset = 0; dpa_offset = 1; } for(j = 0; j < datafile.NrBins; j++) { if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) { if(extended) { fprintf(datafile.fptr, "%ld %e %e %e %e %e %e %e %e %e", j, datafile.tsamp_list[j], data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]); if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) fprintf(datafile.fptr, " %e %e %e %e", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]); fprintf(datafile.fptr, "\n"); }else { fprintf(datafile.fptr, "%e %e %e\n", datafile.tsamp_list[j], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]); } } } if(twoprofiles) { for(j = 0; j < datafile.NrBins; j++) { if(data[j+dpa_offset*datafile.NrBins] > 0 || onlysignificantPA == 0) { if(extended) { fprintf(datafile.fptr, "%ld %e %e %e %e %e %e %e %e %e", j, datafile.tsamp_list[j]+360, data[j], datafile.offpulse_rms[0], data[j+datafile.NrBins], datafile.offpulse_rms[1], data[j+2*datafile.NrBins], datafile.offpulse_rms[2], data[j+pa_offset*datafile.NrBins]+PAoffset, data[j+dpa_offset*datafile.NrBins]); if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) fprintf(datafile.fptr, " %e %e %e %e", data[j+5*datafile.NrBins], datafile.offpulse_rms[5], data[j+6*datafile.NrBins], data[j+7*datafile.NrBins]); fprintf(datafile.fptr, "\n"); }else { fprintf(datafile.fptr, "%e %e %e\n", datafile.tsamp_list[j]+360, data[j]+PAoffset, data[j+dpa_offset*datafile.NrBins]); } } } } return 1; } int make_pa_distribution(datafile_definition datain, datafile_definition *dataout, int nrbins, int normalise, int weighttype, datafile_definition *pamask, float pamask_value, int ellipticity, verbose_definition verbose) { long i, j, f, nrpointsadded, nrpointsadded_max, binnr; float dpa; if(datain.NrSubints <= 1 && datain.NrFreqChan <= 1) { fflush(stdout); printerror(verbose.debug, "ERROR make_pa_distribution: Need more than a single subints and frequency channel to make a PA distribution"); return 0; } if(datain.poltype != POLTYPE_ILVPAdPA && datain.poltype != POLTYPE_PAdPA && datain.poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR make_pa_distribution: Data doesn't appear to have poltype ILVPAdPA, ILVPAdPATEldEl or PAdPA."); return 0; } if(ellipticity && datain.poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR make_pa_distribution: The data isn't of polarization type ILVPAdPATEldEl, while the ellipticity distribution was requested."); return 0; } if(datain.poltype == POLTYPE_ILVPAdPA && datain.NrPols != 5) { printerror(verbose.debug, "ERROR make_pa_distribution: 5 polarization channels were expected, but there are %ld.", datain.NrPols); return 0; }else if(datain.poltype == POLTYPE_ILVPAdPATEldEl && datain.NrPols != 8) { printerror(verbose.debug, "ERROR make_pa_distribution: 8 polarization channels were expected, but there are %ld.", datain.NrPols); return 0; }else if(datain.poltype == POLTYPE_PAdPA && datain.NrPols != 2) { printerror(verbose.debug, "ERROR make_pa_distribution: 2 polarization channels were expected, but there are %ld.", datain.NrPols); return 0; } if(pamask != NULL) { if(datain.NrBins != pamask->NrBins) { printerror(verbose.debug, "ERROR make_pa_distribution: Applying a PA mask only works when the input data has the same number of pulse longitude bins compared to that of the provided mask. (the input data has %ld pulse longitude bins, while the mask has %ld).", datain.NrBins, pamask->NrBins); return 0; } if(nrbins != pamask->NrSubints) { printerror(verbose.debug, "ERROR make_pa_distribution: Applying a PA mask only works when generating a PA-distribution with an equal number of PA bins compared to that of the provided mask. (now %ld pa bins are requested, while the mask has %ld pa-bins defined).", nrbins, pamask->NrSubints); return 0; } if(pamask->NrFreqChan > 1) { printerror(verbose.debug, "ERROR make_pa_distribution: Applying a PA mask only works when the mask has one frequency channel defined. There are currently %ld channels defined).", pamask->NrFreqChan); return 0; } } cleanPSRData(dataout, verbose); copy_params_PSRData(datain, dataout, verbose); dataout->format = MEMORY_format; dataout->NrSubints = nrbins; dataout->NrPols = 1; dataout->NrFreqChan = 1; if(ellipticity == 0) dataout->gentype = GENTYPE_PADIST; else dataout->gentype = GENTYPE_ELLDIST; dataout->tsubMode = TSUBMODE_FIXEDTSUB; if(dataout->tsub_list != NULL) free(dataout->tsub_list); dataout->tsub_list = (double *)malloc(sizeof(double)); if(dataout->tsub_list == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR make_pa_distribution: Memory allocation error"); return 0; } dataout->tsub_list[0] = get_tobs(datain, verbose); dataout->yrangeset = 1; if(ellipticity == 0) { dataout->yrange[0] = -90.0+0.5*180.0/(float)(nrbins); dataout->yrange[1] = 90.0-0.5*180.0/(float)(nrbins); }else { dataout->yrange[0] = -45.0+0.5*90.0/(float)(nrbins); dataout->yrange[1] = 45.0-0.5*90.0/(float)(nrbins); } dataout->data = (float *)calloc(dataout->NrSubints*dataout->NrBins*dataout->NrPols*dataout->NrFreqChan, sizeof(float)); if(dataout->data == NULL) { fflush(stdout); printerror(verbose.debug, "ERROR make_pa_distribution: Cannot allocate memory for data."); return 0; } if(ellipticity == 0) { dpa = 180.0/(float)nrbins; }else { dpa = 90.0/(float)nrbins; } int pa_chan, dpa_chan, weight_chan; if(datain.poltype == POLTYPE_ILVPAdPA || datain.poltype == POLTYPE_ILVPAdPATEldEl) { if(ellipticity == 0) { pa_chan = 3; dpa_chan = 4; }else { pa_chan = 6; dpa_chan = 7; } if(weighttype == 0) { weight_chan = -1; }else if(weighttype == 1) { weight_chan = 1; }else if(weighttype == 2) { weight_chan = 2; }else if(weighttype == 3) { weight_chan = 0; }else if(weighttype == 4) { weight_chan = 5; if(datain.poltype != POLTYPE_ILVPAdPATEldEl) { printerror(verbose.debug, "ERROR make_pa_distribution: Weighting by the total polarization is requested, but that is not appears to be defined in the input data."); return 0; } }else { printerror(verbose.debug, "ERROR make_pa_distribution: Unsupported weighttype is specified."); return 0; } }else { pa_chan = 0; dpa_chan = 1; if(weighttype != 0) { printerror(verbose.debug, "ERROR make_pa_distribution: Data only has PA values defined, so weighting is not supported."); return 0; } } nrpointsadded_max = 0; for(j = 0; j < datain.NrBins; j++) { nrpointsadded = 0; for(i = 0; i < datain.NrSubints; i++) { for(f = 0; f < datain.NrFreqChan; f++) { float paerr; paerr = datain.data[j+datain.NrBins*(dpa_chan+datain.NrPols*(f+datain.NrFreqChan*i))]; if(paerr > 0) { float pa = derotate_180_small_double(datain.data[j+datain.NrBins*(pa_chan+datain.NrPols*(f+datain.NrFreqChan*i))]); float weight = 1.0; if(weighttype != 0) { weight = datain.data[j+datain.NrBins*(weight_chan+datain.NrPols*(f+datain.NrFreqChan*i))]; if(weighttype == 2) { weight = fabs(weight); } } if(ellipticity == 0) { if(pa == 90.0) binnr = 0; else binnr = (pa + 90.0)/dpa; }else { if(pa == 45.0) binnr = 0; else binnr = (pa + 45.0)/dpa; } if(binnr < 0 || binnr >= nrbins) { fflush(stdout); printerror(verbose.debug, "ERROR make_pa_distribution: %ld %f %f BUG!!!!!!!!!!!!!!!", binnr, datain.data[j+datain.NrBins*(pa_chan+datain.NrPols*(f+datain.NrFreqChan*i))], dpa); return 0; } dataout->data[j+dataout->NrBins*binnr] += weight; nrpointsadded++; } if(pamask != NULL) { float value; if(paerr <= 0) { value = 0; }else { value = pamask->data[j+pamask->NrBins*(0+pamask->NrPols*(0+pamask->NrFreqChan*binnr))]; } if(isnan(pamask_value)) { int curpol; for(curpol = 0; curpol < datain.NrPols; curpol++) { datain.data[j+datain.NrBins*(curpol+datain.NrPols*(f+datain.NrFreqChan*i))] = value; } }else { if(value < pamask_value-0.01 || value > pamask_value+0.01 || paerr <= 0) { int curpol; for(curpol = 0; curpol < datain.NrPols; curpol++) { datain.data[j+datain.NrBins*(curpol+datain.NrPols*(f+datain.NrFreqChan*i))] = 0; } } } } } } if(nrpointsadded > nrpointsadded_max) nrpointsadded_max = nrpointsadded; } if(normalise) { if(nrpointsadded_max > 0) { for(i = 0; i < nrbins; i++) { for(j = 0; j < datain.NrBins; j++) { dataout->data[j+datain.NrBins*i] /= (float)nrpointsadded_max; } } } } return 1; } int make_polarization_projection_map(datafile_definition datafile, float *map, int nrx, int nry, float background, int binnr, pulselongitude_regions_definition onpulse, int weighting, float threshold, int projection, float rot_long, float rot_lat, float conalselection, datafile_definition *subtract_pa_data, verbose_definition verbose) { int ok; long i, xi, yi, pulsenr; float longitude, stokesI, L, P, latitude, x, y, weight; if(projection < 1 || projection > 3) { fflush(stdout); printerror(verbose.debug, "ERROR make_projection_map_formIQUV: Projection type is not implemented."); return 0; } if(datafile.NrFreqChan != 1) { fflush(stdout); printerror(verbose.debug, "ERROR make_projection_map_formIQUV: Expected 1 frequency channel."); return 0; } if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) { if(datafile.NrPols != 8) { fflush(stdout); printerror(verbose.debug, "ERROR make_projection_map_formIQUV: Expected 8 input polarizations when reading in data containing PA's and ellipticities."); return 0; } }else { if(datafile.NrPols != 4) { fflush(stdout); printerror(verbose.debug, "ERROR make_projection_map_formIQUV: Expected 4 input polarizations."); return 0; } } if(subtract_pa_data != NULL) { if(subtract_pa_data->NrBins != datafile.NrBins) { printerror(verbose.debug, "ERROR make_projection_map_formIQUV: The reference PA-swing has a different number of pulse phase bins compared to the input data."); return 0; } if(subtract_pa_data->NrFreqChan != 1) { fflush(stdout); printerror(verbose.debug, "ERROR make_projection_map_formIQUV: The reference PA-swing should have a single frequency channel."); return 0; } if(subtract_pa_data->NrSubints != 1) { fflush(stdout); printerror(verbose.debug, "ERROR make_projection_map_formIQUV: The reference PA-swing should have a single subint."); return 0; } } rot_long *= M_PI/180.0; rot_lat *= M_PI/180.0; float *normmap; if(weighting == 2) { normmap = malloc(nrx*nry*sizeof(float)); if(normmap == NULL) { printerror(verbose.debug, "ERROR make_projection_map_formIQUV: Memory allocation error."); return 0; } } for(xi = 0; xi < nrx; xi++) { for(yi = 0; yi < nry; yi++) { map[xi+nrx*yi] = 0; if(weighting == 2) { normmap[xi+nrx*yi] = 0; } } } for(pulsenr = 0; pulsenr < datafile.NrSubints; pulsenr++) { for(i = 0; i < (datafile.NrBins); i++) { ok = 1; if(binnr >= 0) { if(i != binnr) ok = 0; }else if(binnr == -1) { if(checkRegions(i, &onpulse, 0, verbose) == 0) { ok = 0; } } if(ok) { if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) { longitude = 2.0*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]*M_PI/180.0; L = datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+1*(datafile.NrBins)]; latitude = 2.0*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+6*(datafile.NrBins)]*M_PI/180.0; if(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+4*(datafile.NrBins)] < 0 || datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+7*(datafile.NrBins)] < 0) { longitude = latitude = sqrt(-1.0); } }else { longitude = atan2(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+2*(datafile.NrBins)],datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+(datafile.NrBins)]); L = sqrt(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+2*(datafile.NrBins)]*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+2*(datafile.NrBins)] + datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+(datafile.NrBins)]*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+(datafile.NrBins)]); latitude = atan(datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]/L); } if(subtract_pa_data != NULL) { int pachannel_subtract_fin; if(subtract_pa_data->poltype == POLTYPE_ILVPAdPATEldEl) { pachannel_subtract_fin = 3; }else { pachannel_subtract_fin = subtract_pa_data->NrPols-2; } longitude -= 2.0*subtract_pa_data->data[i+subtract_pa_data->NrBins*(pachannel_subtract_fin)]*M_PI/180.0; } if(!isnan(latitude)) { if(conalselection > 0) { double sphericaldistance; sphericaldistance = acos(cos(latitude-rot_lat)*cos(longitude+rot_long))*180.0/M_PI; if(sphericaldistance > conalselection) { latitude = sqrt(-1.0); } } } if(!isnan(latitude)) { if(weighting) { if(weighting != 3) { if(datafile.poltype == POLTYPE_ILVPAdPATEldEl) { P = datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+5*(datafile.NrBins)]; }else { P = sqrt(L*L+datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]*datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr+3*(datafile.NrBins)]); } } if(weighting == 2 || weighting == 3) { stokesI = datafile.data[i+datafile.NrBins*datafile.NrPols*pulsenr]; } } if(projection == 1) { projectionHammerAitoff_xy(longitude, latitude, rot_long, rot_lat, &x, &y); weight = 1; }else if(projection == 2) { projection_sphere_xy(longitude, latitude, rot_long, rot_lat, &x, &y, &weight); }else if(projection == 3) { projection_longlat_xy(longitude, latitude, rot_long, rot_lat, &x, &y); weight = 1; x /= 80.0; y /= 80.0; } xi = 0.5*nrx + x*nrx/4.5; yi = 0.5*nry + y*nry/2.25; if(weighting == 0) { map[xi+nrx*yi] += 1.0*weight; }else { if(weighting == 3) { map[xi+nrx*yi] += stokesI*weight; }else { map[xi+nrx*yi] += P*weight; } if(weighting == 2) { normmap[xi+nrx*yi] += stokesI*weight; } } } } } } if((weighting == 1 || weighting == 2) && threshold > 0) { float maxvalue = map[0]; for(xi = 0; xi < nrx; xi++) { for(yi = 0; yi < nry; yi++) { if(map[xi+nrx*yi] > maxvalue) { maxvalue = map[xi+nrx*yi]; } } } for(xi = 0; xi < nrx; xi++) { for(yi = 0; yi < nry; yi++) { if(map[xi+nrx*yi] < threshold*maxvalue) { map[xi+nrx*yi] = 0; } } } } if(weighting == 2) { for(xi = 0; xi < nrx; xi++) { for(yi = 0; yi < nry; yi++) { if(normmap[xi+nrx*yi] != 0.0) { map[xi+nrx*yi] /= normmap[xi+nrx*yi]; if(map[xi+nrx*yi] < 0) { map[xi+nrx*yi] = 0; } if(map[xi+nrx*yi] > 1) { map[xi+nrx*yi] = 1; } }else { map[xi+nrx*yi] = 0; } } } free(normmap); } return 1; }
{ "alphanum_fraction": 0.6713558007, "avg_line_length": 41.8390966831, "ext": "c", "hexsha": "a1cb26e03ae91facc7a33aad8b259c1335cd1f83", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "weltevrede/psrsalsa", "max_forks_repo_path": "src/lib/psrio_paswing.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "weltevrede/psrsalsa", "max_issues_repo_path": "src/lib/psrio_paswing.c", "max_line_length": 755, "max_stars_count": 5, "max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "weltevrede/psrsalsa", "max_stars_repo_path": "src/lib/psrio_paswing.c", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "num_tokens": 18613, "size": 59286 }
#include <stdio.h> #include <gsl/gsl_matrix.h> int main (void) { int i, j, k = 0; gsl_matrix * m = gsl_matrix_alloc (100, 100); gsl_matrix * a = gsl_matrix_alloc (100, 100); for (i = 0; i < 100; i++) for (j = 0; j < 100; j++) gsl_matrix_set (m, i, j, 0.23 + i + j); { FILE * f = fopen ("test.dat", "wb"); gsl_matrix_fwrite (f, m); fclose (f); } { FILE * f = fopen ("test.dat", "rb"); gsl_matrix_fread (f, a); fclose (f); } for (i = 0; i < 100; i++) for (j = 0; j < 100; j++) { double mij = gsl_matrix_get (m, i, j); double aij = gsl_matrix_get (a, i, j); if (mij != aij) k++; } gsl_matrix_free (m); gsl_matrix_free (a); printf ("differences = %d (should be zero)\n", k); return (k > 0); }
{ "alphanum_fraction": 0.4969097651, "avg_line_length": 19.7317073171, "ext": "c", "hexsha": "b05ffbd03f899d3987655987815d8dbea9eeee45", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/matrixw.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/matrixw.c", "max_line_length": 52, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/matrixw.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": 294, "size": 809 }
static char help[] = "Load a collection of PETSc vectors and stack them into a tall-skinny matrix\n\n"; #include <petsc.h> #include <petscvec.h> #include <petscmat.h> /* Mesh size (129, 33, 257) <xdmf reverse order>, so ni = 257, nk = 129 */ PetscErrorCode SnapshotView(Vec u,const char suffix[]) { const PetscInt M = 257; const PetscInt N = 33; const PetscInt P = 129; DM dm; Vec cu; PetscViewer viewer; char ofile[PETSC_MAX_PATH_LEN]; PetscErrorCode ierr; PetscFunctionBegin; ierr = DMDACreate3d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE, DMDA_STENCIL_BOX,M,N,P,PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE, 1,1,NULL,NULL,NULL,&dm);CHKERRQ(ierr); ierr = DMSetUp(dm);CHKERRQ(ierr); ierr = DMDASetUniformCoordinates(dm,0.0,12.0,-1.5,0.0,0.0,6.0);CHKERRQ(ierr); ierr = DMCreateGlobalVector(dm,&cu);CHKERRQ(ierr); ierr = VecCopy(u,cu);CHKERRQ(ierr); PetscSNPrintf(ofile,PETSC_MAX_PATH_LEN-1,"%s.vts",suffix); ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,ofile,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = VecView(cu,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); ierr = DMDestroy(&dm);CHKERRQ(ierr); ierr = VecDestroy(&cu);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SnapshotViewFromFile(const char coor_fname[],const char u_fname[],const char suffix[]) { const PetscInt M = 257; const PetscInt N = 33; const PetscInt P = 129; DM dm; Vec u,coor,_u,_coor; PetscViewer viewer; char ofile[PETSC_MAX_PATH_LEN]; PetscErrorCode ierr; PetscFunctionBegin; PetscPrintf(PETSC_COMM_WORLD,"Loading solution: %s\n",u_fname); ierr = VecCreate(PETSC_COMM_WORLD,&u);CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,u_fname,FILE_MODE_READ,&viewer);CHKERRQ(ierr); ierr = VecLoad(u,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"Loading coordinates: %s\n",coor_fname); ierr = VecCreate(PETSC_COMM_WORLD,&coor);CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,coor_fname,FILE_MODE_READ,&viewer);CHKERRQ(ierr); ierr = VecLoad(coor,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); ierr = DMDACreate3d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE, DMDA_STENCIL_BOX,M,N,P,PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE, 1,1,NULL,NULL,NULL,&dm);CHKERRQ(ierr); ierr = DMSetUp(dm);CHKERRQ(ierr); ierr = DMDASetUniformCoordinates(dm,0.0,1.0,0.0,1.0,0.0,1.0);CHKERRQ(ierr); ierr = DMCreateGlobalVector(dm,&_u);CHKERRQ(ierr); ierr = VecCopy(u,_u);CHKERRQ(ierr); ierr = DMGetCoordinates(dm,&_coor);CHKERRQ(ierr); ierr = VecCopy(coor,_coor);CHKERRQ(ierr); PetscSNPrintf(ofile,PETSC_MAX_PATH_LEN-1,"%s.vts",suffix); PetscPrintf(PETSC_COMM_WORLD,"Writing output: %s\n",ofile); ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,ofile,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = VecView(_u,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); ierr = DMDestroy(&dm);CHKERRQ(ierr); ierr = VecDestroy(&_u);CHKERRQ(ierr); ierr = VecDestroy(&u);CHKERRQ(ierr); ierr = VecDestroy(&coor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SnapshotMatCreate(Mat *snapshots) { PetscErrorCode ierr; Vec u; PetscViewer viewer; const PetscInt steps[] = { 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400 }; char fname[PETSC_MAX_PATH_LEN]; PetscInt i,len,m,n,k; Mat S; PetscInt *idx; PetscFunctionBegin; len = sizeof(steps) / sizeof(PetscInt); n = len; ierr = PetscOptionsGetInt(NULL,NULL,"-truncate",&n,NULL);CHKERRQ(ierr); if (n > len) SETERRQ1(PETSC_COMM_WORLD,PETSC_ERR_USER,"Truncate value cannot be larger than %D",len); for (i=0; i<n; i++) { PetscSNPrintf(fname,PETSC_MAX_PATH_LEN-1,"data/step%1.6d_energy.pbvec",steps[i]); PetscPrintf(PETSC_COMM_WORLD,"[%d] Loading: %s\n",i,fname); ierr = VecCreate(PETSC_COMM_WORLD,&u);CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,fname,FILE_MODE_READ,&viewer);CHKERRQ(ierr); ierr = VecLoad(u,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); if (i == 0) { ierr = VecGetSize(u,&m);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"S: m %d, n %d\n",m,n); ierr = MatCreate(PETSC_COMM_WORLD,&S);CHKERRQ(ierr); ierr = MatSetSizes(S,PETSC_DECIDE,PETSC_DECIDE,m,n);CHKERRQ(ierr); ierr = MatSetType(S,MATDENSE);CHKERRQ(ierr); ierr = MatSetUp(S);CHKERRQ(ierr); ierr = PetscCalloc1(m,&idx);CHKERRQ(ierr); for (k=0; k<m; k++) { idx[k] = k; } } { const PetscScalar *_u; ierr = VecGetArrayRead(u,&_u);CHKERRQ(ierr); ierr = MatSetValues(S,m,idx,1,&i,_u,INSERT_VALUES);CHKERRQ(ierr); ierr = VecRestoreArrayRead(u,&_u);CHKERRQ(ierr); } ierr = MatAssemblyBegin(S,MAT_FLUSH_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(S,MAT_FLUSH_ASSEMBLY);CHKERRQ(ierr); if (i == 0) { ierr = SnapshotView(u,"snapshot0");CHKERRQ(ierr); } ierr = VecDestroy(&u);CHKERRQ(ierr); } ierr = MatAssemblyBegin(S,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(S,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); *snapshots = S; ierr = PetscFree(idx);CHKERRQ(ierr); PetscFunctionReturn(0); } int main(int argc,char **args) { PetscErrorCode ierr; Mat S; PetscInt step = -1; PetscBool found = PETSC_FALSE; ierr = PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr; ierr = SnapshotMatCreate(&S);CHKERRQ(ierr); /* Dump S(i,j) as ascii to stdout */ /*ierr = MatView(S,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);*/ /* Dump S(i,j) as bindary to file */ { PetscViewer viewer; ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,"snapshot.pbmat",FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = MatView(S,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } ierr = PetscOptionsGetInt(NULL,NULL,"-solution_view",&step,&found);CHKERRQ(ierr); if (found) { char s_fname[PETSC_MAX_PATH_LEN]; char c_fname[PETSC_MAX_PATH_LEN]; char ofname[PETSC_MAX_PATH_LEN]; PetscSNPrintf(s_fname,PETSC_MAX_PATH_LEN-1,"data/step%1.6d_energy.pbvec",step); PetscSNPrintf(c_fname,PETSC_MAX_PATH_LEN-1,"data/step%1.6d_coor.pbvec",step); PetscSNPrintf(ofname,PETSC_MAX_PATH_LEN-1,"step%d_temperature",step); PetscPrintf(PETSC_COMM_WORLD,"Snapshot to visualize: %d\n",step); ierr = SnapshotViewFromFile(c_fname,s_fname,ofname);CHKERRQ(ierr); } ierr = PetscFinalize(); return ierr; }
{ "alphanum_fraction": 0.6828417841, "avg_line_length": 36.0366492147, "ext": "c", "hexsha": "b25c60e8f8c818916ce58b005275fad3cc03ab57", "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": "58581831cf30919a473cf639456351cc5821cf0d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MayHPCGSLab/ptatin-timeseries-svd-data", "max_forks_repo_path": "v2m.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "58581831cf30919a473cf639456351cc5821cf0d", "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": "MayHPCGSLab/ptatin-timeseries-svd-data", "max_issues_repo_path": "v2m.c", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "58581831cf30919a473cf639456351cc5821cf0d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MayHPCGSLab/ptatin-timeseries-svd-data", "max_stars_repo_path": "v2m.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2026, "size": 6883 }
#ifndef SAMPLER_H #define SAMPLER_H #include <gsl/gsl_rng.h> #include <stdlib.h> typedef struct sampler { gsl_rng *internal_rng_state; unsigned long int seed; double (*generate)(void *samplerp); } Sampler; Sampler *new_sampler(unsigned long int seed); void free_sampler(Sampler *p); double generate_method(void *samplerp); #endif
{ "alphanum_fraction": 0.7565982405, "avg_line_length": 17.9473684211, "ext": "h", "hexsha": "b326c2635d84303da7d3b56ba5930d8c79b46753", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-08T18:18:12.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-08T18:18:12.000Z", "max_forks_repo_head_hexsha": "959370b3137ec826b3eb8e750721fd8ea09fdff1", "max_forks_repo_licenses": [ "BSD-3-Clause-LBNL" ], "max_forks_repo_name": "BlauGroup/RNMC_archived", "max_forks_repo_path": "src/sampler.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "959370b3137ec826b3eb8e750721fd8ea09fdff1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-LBNL" ], "max_issues_repo_name": "BlauGroup/RNMC_archived", "max_issues_repo_path": "src/sampler.h", "max_line_length": 45, "max_stars_count": null, "max_stars_repo_head_hexsha": "959370b3137ec826b3eb8e750721fd8ea09fdff1", "max_stars_repo_licenses": [ "BSD-3-Clause-LBNL" ], "max_stars_repo_name": "BlauGroup/RNMC_archived", "max_stars_repo_path": "src/sampler.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 86, "size": 341 }
/* specfunc/gsl_sf_gamma.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_GAMMA_H__ #define __GSL_SF_GAMMA_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 /* Log[Gamma(x)], x not a negative integer * Uses real Lanczos method. * Returns the real part of Log[Gamma[x]] when x < 0, * i.e. Log[|Gamma[x]|]. * * exceptions: GSL_EDOM, GSL_EROUND */ int gsl_sf_lngamma_e(double x, gsl_sf_result * result); double gsl_sf_lngamma(const double x); /* Log[Gamma(x)], x not a negative integer * Uses real Lanczos method. Determines * the sign of Gamma[x] as well as Log[|Gamma[x]|] for x < 0. * So Gamma[x] = sgn * Exp[result_lg]. * * exceptions: GSL_EDOM, GSL_EROUND */ int gsl_sf_lngamma_sgn_e(double x, gsl_sf_result * result_lg, double *sgn); /* Gamma(x), x not a negative integer * Uses real Lanczos method. * * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EROUND */ int gsl_sf_gamma_e(const double x, gsl_sf_result * result); double gsl_sf_gamma(const double x); /* Regulated Gamma Function, x > 0 * Gamma^*(x) = Gamma(x)/(Sqrt[2Pi] x^(x-1/2) exp(-x)) * = (1 + 1/(12x) + ...), x->Inf * A useful suggestion of Temme. * * exceptions: GSL_EDOM */ int gsl_sf_gammastar_e(const double x, gsl_sf_result * result); double gsl_sf_gammastar(const double x); /* 1/Gamma(x) * Uses real Lanczos method. * * exceptions: GSL_EUNDRFLW, GSL_EROUND */ int gsl_sf_gammainv_e(const double x, gsl_sf_result * result); double gsl_sf_gammainv(const double x); /* Log[Gamma(z)] for z complex, z not a negative integer * Uses complex Lanczos method. Note that the phase part (arg) * is not well-determined when |z| is very large, due * to inevitable roundoff in restricting to (-Pi,Pi]. * This will raise the GSL_ELOSS exception when it occurs. * The absolute value part (lnr), however, never suffers. * * Calculates: * lnr = log|Gamma(z)| * arg = arg(Gamma(z)) in (-Pi, Pi] * * exceptions: GSL_EDOM, GSL_ELOSS */ int gsl_sf_lngamma_complex_e(double zr, double zi, gsl_sf_result * lnr, gsl_sf_result * arg); /* x^n / n! * * x >= 0.0, n >= 0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_taylorcoeff_e(const int n, const double x, gsl_sf_result * result); double gsl_sf_taylorcoeff(const int n, const double x); /* n! * * exceptions: GSL_EDOM, GSL_OVRFLW */ int gsl_sf_fact_e(const unsigned int n, gsl_sf_result * result); double gsl_sf_fact(const unsigned int n); /* n!! = n(n-2)(n-4) ... * * exceptions: GSL_EDOM, GSL_OVRFLW */ int gsl_sf_doublefact_e(const unsigned int n, gsl_sf_result * result); double gsl_sf_doublefact(const unsigned int n); /* log(n!) * Faster than ln(Gamma(n+1)) for n < 170; defers for larger n. * * exceptions: none */ int gsl_sf_lnfact_e(const unsigned int n, gsl_sf_result * result); double gsl_sf_lnfact(const unsigned int n); /* log(n!!) * * exceptions: none */ int gsl_sf_lndoublefact_e(const unsigned int n, gsl_sf_result * result); double gsl_sf_lndoublefact(const unsigned int n); /* log(n choose m) * * exceptions: GSL_EDOM */ int gsl_sf_lnchoose_e(unsigned int n, unsigned int m, gsl_sf_result * result); double gsl_sf_lnchoose(unsigned int n, unsigned int m); /* n choose m * * exceptions: GSL_EDOM, GSL_EOVRFLW */ int gsl_sf_choose_e(unsigned int n, unsigned int m, gsl_sf_result * result); double gsl_sf_choose(unsigned int n, unsigned int m); /* Logarithm of Pochhammer (Apell) symbol * log( (a)_x ) * where (a)_x := Gamma[a + x]/Gamma[a] * * a > 0, a+x > 0 * * exceptions: GSL_EDOM */ int gsl_sf_lnpoch_e(const double a, const double x, gsl_sf_result * result); double gsl_sf_lnpoch(const double a, const double x); /* Logarithm of Pochhammer (Apell) symbol, with sign information. * result = log( |(a)_x| ) * sgn = sgn( (a)_x ) * where (a)_x := Gamma[a + x]/Gamma[a] * * a != neg integer, a+x != neg integer * * exceptions: GSL_EDOM */ int gsl_sf_lnpoch_sgn_e(const double a, const double x, gsl_sf_result * result, double * sgn); /* Pochhammer (Apell) symbol * (a)_x := Gamma[a + x]/Gamma[x] * * a != neg integer, a+x != neg integer * * exceptions: GSL_EDOM, GSL_EOVRFLW */ int gsl_sf_poch_e(const double a, const double x, gsl_sf_result * result); double gsl_sf_poch(const double a, const double x); /* Relative Pochhammer (Apell) symbol * ((a,x) - 1)/x * where (a,x) = (a)_x := Gamma[a + x]/Gamma[a] * * exceptions: GSL_EDOM */ int gsl_sf_pochrel_e(const double a, const double x, gsl_sf_result * result); double gsl_sf_pochrel(const double a, const double x); /* Normalized Incomplete Gamma Function * * Q(a,x) = 1/Gamma(a) Integral[ t^(a-1) e^(-t), {t,x,Infinity} ] * * a >= 0, x >= 0 * Q(a,0) := 1 * Q(0,x) := 0, x != 0 * * exceptions: GSL_EDOM */ int gsl_sf_gamma_inc_Q_e(const double a, const double x, gsl_sf_result * result); double gsl_sf_gamma_inc_Q(const double a, const double x); /* Complementary Normalized Incomplete Gamma Function * * P(a,x) = 1/Gamma(a) Integral[ t^(a-1) e^(-t), {t,0,x} ] * * a > 0, x >= 0 * * exceptions: GSL_EDOM */ int gsl_sf_gamma_inc_P_e(const double a, const double x, gsl_sf_result * result); double gsl_sf_gamma_inc_P(const double a, const double x); /* Non-normalized Incomplete Gamma Function * * Gamma(a,x) := Integral[ t^(a-1) e^(-t), {t,x,Infinity} ] * * x >= 0.0 * Gamma(a, 0) := Gamma(a) * * exceptions: GSL_EDOM */ int gsl_sf_gamma_inc_e(const double a, const double x, gsl_sf_result * result); double gsl_sf_gamma_inc(const double a, const double x); /* Logarithm of Beta Function * Log[B(a,b)] * * a > 0, b > 0 * exceptions: GSL_EDOM */ int gsl_sf_lnbeta_e(const double a, const double b, gsl_sf_result * result); double gsl_sf_lnbeta(const double a, const double b); int gsl_sf_lnbeta_sgn_e(const double x, const double y, gsl_sf_result * result, double * sgn); /* Beta Function * B(a,b) * * a > 0, b > 0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_beta_e(const double a, const double b, gsl_sf_result * result); double gsl_sf_beta(const double a, const double b); /* Normalized Incomplete Beta Function * B_x(a,b)/B(a,b) * * a > 0, b > 0, 0 <= x <= 1 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_beta_inc_e(const double a, const double b, const double x, gsl_sf_result * result); double gsl_sf_beta_inc(const double a, const double b, const double x); /* The maximum x such that gamma(x) is not * considered an overflow. */ #define GSL_SF_GAMMA_XMAX 171.0 /* The maximum n such that gsl_sf_fact(n) does not give an overflow. */ #define GSL_SF_FACT_NMAX 170 /* The maximum n such that gsl_sf_doublefact(n) does not give an overflow. */ #define GSL_SF_DOUBLEFACT_NMAX 297 __END_DECLS #endif /* __GSL_SF_GAMMA_H__ */
{ "alphanum_fraction": 0.693598348, "avg_line_length": 26.3537414966, "ext": "h", "hexsha": "a06b74edd456d2220d8614fd20fdacb58890a997", "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_sf_gamma.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": "2017-05-09T10:24:03.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-29T22:11:01.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/specfunc/gsl_sf_gamma.h", "max_line_length": 94, "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_sf_gamma.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": 2321, "size": 7748 }
/** * * @file core_blas.h * * PLASMA auxiliary routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Jakub Kurzak * @author Hatem Ltaief * @date 2010-11-15 * **/ #ifndef _PLASMA_CORE_BLAS_H_ #define _PLASMA_CORE_BLAS_H_ #include <cblas.h> #include "plasmatypes.h" #include "descriptor.h" #include "core_zblas.h" #include "core_dblas.h" #include "core_cblas.h" #include "core_sblas.h" #include "core_zcblas.h" #include "core_dsblas.h" #ifdef __cplusplus extern "C" { #endif /* * Coreblas Error */ #define coreblas_error(k, str) fprintf(stderr, "%s: Parameter %d / %s\n", __func__, k, str); /** **************************************************************************** * LAPACK Constants **/ extern char *plasma_lapack_constants[]; #define lapack_const(plasma_const) plasma_lapack_constants[plasma_const][0] /* * CBlas enum */ #define CBLAS_TRANSPOSE enum CBLAS_TRANSPOSE #define CBLAS_UPLO enum CBLAS_UPLO #define CBLAS_DIAG enum CBLAS_DIAG #define CBLAS_SIDE enum CBLAS_SIDE /* CBLAS requires for scalar arguments to be passed by address rather than by value */ #ifndef CBLAS_SADDR #define CBLAS_SADDR( _val_ ) &(_val_) #endif /** **************************************************************************** * External interface of the GKK algorithm for InPlace Layout Translation **/ int GKK_minloc(int n, int *T); void GKK_BalanceLoad(int thrdnbr, int *Tp, int *leaders, int nleaders, int L); int GKK_getLeaderNbr(int me, int ne, int *nleaders, int **leaders); /** **************************************************************************** * Extra quark wrapper functions that do not rely on precision * (Defined only if quark.h is included prior to this file) **/ #if defined(QUARK_H) /* * Functions which don't depend on precision */ void CORE_free_quark(Quark *quark); void CORE_foo_quark(Quark *quark); void CORE_foo2_quark(Quark *quark); void QUARK_CORE_free(Quark *quark, Quark_Task_Flags *task_flags, void *A, int szeA); void CORE_pivot_update(int m, int n, int *ipiv, int *indices, int offset, int init); void CORE_pivot_update_quark(Quark *quark); void QUARK_CORE_pivot_update(Quark *quark, Quark_Task_Flags *task_flags, int m, int n, int *ipiv, int *indices, int offset, int init); #endif /* defined(QUARK_H) */ #ifdef __cplusplus } #endif #endif /* _PLASMA_CORE_BLAS_H_ */
{ "alphanum_fraction": 0.6300734441, "avg_line_length": 28.1195652174, "ext": "h", "hexsha": "6f77a2f95250ba83cb99cbf02ecfb08df090898e", "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": "include/core_blas.h", "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": "include/core_blas.h", "max_line_length": 92, "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": "include/core_blas.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 692, "size": 2587 }
// 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. // // Copyright 2005-2016 Brian Roark and Google, Inc. // Classes to generate random sentences from an LM or more generally // paths through any FST where epsilons are treated as failure transitions. #ifndef NGRAM_NGRAM_RANDGEN_H_ #define NGRAM_NGRAM_RANDGEN_H_ #include <sys/types.h> #include <unistd.h> #include <vector> // Faster multinomial sampling possible if Gnu Scientific Library available. #ifdef HAVE_GSL #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #endif // HAVE_GSL #include <fst/fst.h> #include <fst/randgen.h> #include <ngram/util.h> namespace ngram { using fst::Fst; using fst::ArcIterator; using fst::LogWeight; using fst::Log64Weight; // Same as FastLogProbArcSelector but treats *all* epsilons as // failure transitions that have a backoff weight. The LM must // be fully normalized. template <class A> class NGramArcSelector { public: typedef typename A::StateId StateId; typedef typename A::Weight Weight; explicit NGramArcSelector(int seed = time(0) + getpid()) : seed_(seed) { srand(seed); } // Samples one transition. size_t operator()(const Fst<A> &fst, StateId s, double total_prob, fst::CacheLogAccumulator<A> *accumulator) const { double r = rand() / (RAND_MAX + 1.0); // In effect, subtract out excess mass from the cumulative distribution. // Requires the backoff epsilon be the initial transition. double z = r + total_prob - 1.0; if (z <= 0.0) return 0; ArcIterator<Fst<A> > aiter(fst, s); return accumulator->LowerBound(-log(z), &aiter); } int Seed() const { return seed_; } private: int seed_; fst::WeightConvert<Weight, LogWeight> to_log_weight_; }; } // namespace ngram namespace fst { // Specialization for NGramArcSelector. template <class A> class ArcSampler<A, ngram::NGramArcSelector<A> > { public: typedef ngram::NGramArcSelector<A> S; typedef typename A::StateId StateId; typedef typename A::Weight Weight; typedef typename A::Label Label; typedef CacheLogAccumulator<A> C; ArcSampler(const Fst<A> &fst, const S &arc_selector, int max_length = INT_MAX) : fst_(fst), arc_selector_(arc_selector), max_length_(max_length), matcher_(fst_, MATCH_INPUT) { // Ensure the input FST has any epsilons as the initial transitions. if (!fst_.Properties(kILabelSorted, true)) NGRAMERROR() << "ArcSampler: is not input-label sorted"; accumulator_.reset(new C()); accumulator_->Init(fst); #ifdef HAVE_GSL rng_ = gsl_rng_alloc(gsl_rng_taus); gsl_rng_set(rng_, arc_selector.Seed()); #endif // HAVE_GSL } ArcSampler(const ArcSampler<A, S> &sampler, const Fst<A> *fst = 0) : fst_(fst ? *fst : sampler.fst_), arc_selector_(sampler.arc_selector_), max_length_(sampler.max_length_), matcher_(fst_, MATCH_INPUT) { if (fst) { accumulator_.reset(new C()); accumulator_->Init(*fst); } else { // shallow copy accumulator_.reset(new C(*sampler.accumulator_)); } } ~ArcSampler() { #ifdef HAVE_GSL gsl_rng_free(rng_); #endif // HAVE_GSL } bool Sample(const RandState<A> &rstate) { sample_map_.clear(); forbidden_labels_.clear(); if ((fst_.NumArcs(rstate.state_id) == 0 && fst_.Final(rstate.state_id) == Weight::Zero()) || rstate.length == max_length_) { Reset(); return false; } double total_prob = TotalProb(rstate.state_id); #ifdef HAVE_GSL if (fst_.NumArcs(rstate.state_id) + 1 < rstate.nsamples) { Weight numer_weight, denom_weight; BackoffWeight(rstate.state_id, total_prob, &numer_weight, &denom_weight); MultinomialSample(rstate, numer_weight); Reset(); return true; } #endif // HAVE_GSL ArcIterator<Fst<A> > aiter(fst_, rstate.state_id); for (size_t i = 0; i < rstate.nsamples; ++i) { size_t pos = 0; Label label = kNoLabel; do { pos = arc_selector_(fst_, rstate.state_id, total_prob, accumulator_.get()); if (pos < fst_.NumArcs(rstate.state_id)) { aiter.Seek(pos); label = aiter.Value().ilabel; } else { label = kNoLabel; } } while (ForbiddenLabel(label, rstate)); ++sample_map_[pos]; } Reset(); return true; } bool Done() const { return sample_iter_ == sample_map_.end(); } void Next() { ++sample_iter_; } std::pair<size_t, size_t> Value() const { return *sample_iter_; } void Reset() { sample_iter_ = sample_map_.begin(); } bool Error() const { return false; } private: double TotalProb(StateId s) { // Get cumulative weight at the state. ArcIterator<Fst<A> > aiter(fst_, s); accumulator_->SetState(s); Weight total_weight = accumulator_->Sum(fst_.Final(s), &aiter, 0, fst_.NumArcs(s)); return exp(-to_log_weight_(total_weight).Value()); } void BackoffWeight(StateId s, double total_prob, Weight *numer_weight, Weight *denom_weight); #ifdef HAVE_GSL void MultinomialSample(const RandState<A> &rstate, Weight fail_weight); #endif // HAVE_GSL bool ForbiddenLabel(Label l, const RandState<A> &rstate); const Fst<A> &fst_; const S &arc_selector_; int max_length_; // Stores (N, K) as described for Value(). std::map<size_t, size_t> sample_map_; std::map<size_t, size_t>::const_iterator sample_iter_; std::unique_ptr<C> accumulator_; #ifdef HAVE_GSL gsl_rng *rng_; // GNU Sci Lib random number generator vector<double> pr_; // multinomial parameters vector<unsigned int> pos_; // sample positions vector<unsigned int> n_; // sample counts #endif // HAVE_GSL WeightConvert<Log64Weight, Weight> to_weight_; WeightConvert<Weight, Log64Weight> to_log_weight_; std::set<Label> forbidden_labels_; // labels forbidden for failure transitions Matcher<Fst<A> > matcher_; }; // Finds and decomposes the backoff probability into its numerator and // denominator. template <class A> void ArcSampler<A, ngram::NGramArcSelector<A> >::BackoffWeight( StateId s, double total, Weight *numer_weight, Weight *denom_weight) { // Get backoff prob. double backoff = 0.0; matcher_.SetState(s); matcher_.Find(0); for (; !matcher_.Done(); matcher_.Next()) { const A &arc = matcher_.Value(); if (arc.ilabel != kNoLabel) { // not an implicit epsilon loop backoff = exp(-to_log_weight_(arc.weight).Value()); break; } } if (backoff == 0.0) { // no backoff transition *numer_weight = Weight::Zero(); *denom_weight = Weight::Zero(); return; } // total = 1 - numer + backoff double numer = 1.0 + backoff - total; *numer_weight = to_weight_(-log(numer)); // backoff = numer/denom double denom = numer / backoff; *denom_weight = to_weight_(-log(denom)); } #ifdef HAVE_GSL template <class A> void ArcSampler<A, ngram::NGramArcSelector<A> >::MultinomialSample( const RandState<A> &rstate, Weight fail_weight) { pr_.clear(); pos_.clear(); n_.clear(); size_t pos = 0; for (ArcIterator<Fst<A> > aiter(fst_, rstate.state_id); !aiter.Done(); aiter.Next(), ++pos) { const A &arc = aiter.Value(); if (!ForbiddenLabel(arc.ilabel, rstate)) { pos_.push_back(pos); Weight weight = arc.ilabel == 0 ? fail_weight : arc.weight; pr_.push_back(exp(-to_log_weight_(weight).Value())); } } if (fst_.Final(rstate.state_id) != Weight::Zero() && !ForbiddenLabel(kNoLabel, rstate)) { pos_.push_back(pos); pr_.push_back(exp(-to_log_weight_(fst_.Final(rstate.state_id)).Value())); } if (rstate.nsamples < UINT_MAX) { n_.resize(pr_.size()); gsl_ran_multinomial(rng_, pr_.size(), rstate.nsamples, &(pr_[0]), &(n_[0])); for (size_t i = 0; i < n_.size(); ++i) if (n_[i] != 0) sample_map_[pos_[i]] = n_[i]; } else { for (size_t i = 0; i < pr_.size(); ++i) sample_map_[pos_[i]] = ceil(pr_[i] * rstate.nsamples); } } #endif // HAVE_GSL template <class A> bool ArcSampler<A, ngram::NGramArcSelector<A> >::ForbiddenLabel( Label l, const RandState<A> &rstate) { if (l == 0) return false; if (fst_.NumArcs(rstate.state_id) > rstate.nsamples) { for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) { StateId parent_id = rs->parent->state_id; ArcIterator<Fst<A> > aiter(fst_, parent_id); aiter.Seek(rs->select); if (aiter.Value().ilabel != 0) // not backoff transition return false; if (l == kNoLabel) { // super-final label return fst_.Final(parent_id) != Weight::Zero(); } else { matcher_.SetState(parent_id); if (matcher_.Find(l)) return true; } } return false; } else { if (forbidden_labels_.empty()) { for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) { StateId parent_id = rs->parent->state_id; ArcIterator<Fst<A> > aiter(fst_, parent_id); aiter.Seek(rs->select); if (aiter.Value().ilabel != 0) // not backoff transition break; for (aiter.Reset(); !aiter.Done(); aiter.Next()) { Label l = aiter.Value().ilabel; if (l != 0) forbidden_labels_.insert(l); } if (fst_.Final(parent_id) != Weight::Zero()) forbidden_labels_.insert(kNoLabel); } } return forbidden_labels_.count(l) > 0; } } } // namespace fst #endif // NGRAM_NGRAM_RANDGEN_H_
{ "alphanum_fraction": 0.6512483836, "avg_line_length": 30.556231003, "ext": "h", "hexsha": "eacb75b2f49154d3127f826748c81713c3824ac3", "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": "ce9b55b406c681902a20c4b547bdd254a8a399e7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "unixnme/opengrm_ngram", "max_forks_repo_path": "src/include/ngram/ngram-randgen.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ce9b55b406c681902a20c4b547bdd254a8a399e7", "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": "unixnme/opengrm_ngram", "max_issues_repo_path": "src/include/ngram/ngram-randgen.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ce9b55b406c681902a20c4b547bdd254a8a399e7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "unixnme/opengrm_ngram", "max_stars_repo_path": "src/include/ngram/ngram-randgen.h", "max_stars_repo_stars_event_max_datetime": "2020-05-11T00:44:55.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-11T00:44:55.000Z", "num_tokens": 2762, "size": 10053 }
#include <assert.h> #include <gsl/gsl_nan.h> #include "csm_all.h" int minmax(int from, int to, int x) { return GSL_MAX(GSL_MIN(x,to),from); } void possible_interval( const double *p_i_w, LDP ld, double max_angular_correction_deg, double max_linear_correction, int*from, int*to, int*start_cell) { double angle_res = (ld->max_theta-ld->min_theta)/ld->nrays; /* Delta for the angle */ double delta = fabs(deg2rad(max_angular_correction_deg)) + fabs(atan(max_linear_correction/norm_d(p_i_w))); /* Dimension of the cell range */ int range = (int) ceil(delta/angle_res); /* To be turned into an interval of cells */ double start_theta = atan2(p_i_w[1], p_i_w[0]); /* Make sure that start_theta is in the interval [min_theta,max_theta]. For example, -1 is not in [0, 2pi] */ if(start_theta<ld->min_theta) start_theta += 2*M_PI; if(start_theta>ld->max_theta) start_theta -= 2*M_PI; *start_cell = (int) ((start_theta - ld->min_theta) / (ld->max_theta-ld->min_theta) * ld->nrays); *from = minmax(0,ld->nrays-1, *start_cell-range); *to = minmax(0,ld->nrays-1, *start_cell+range); if(0) printf("from: %d to: %d delta: %f start_theta: %f min/max theta: [%f,%f] range: %d start_cell: %d\n", *from, *to, delta,start_theta,ld->min_theta,ld->max_theta, range, *start_cell); } int distance_counter = 0; double distance_squared_d(const double a[2], const double b[2]) { distance_counter++; double x = a[0]-b[0]; double y = a[1]-b[1]; return x*x + y*y; } double distance_d(const double a[2], const double b[2]) { return sqrt(distance_squared_d(a,b)); } int is_nan(double v) { return v == v ? 0 : 1; } int any_nan(const double *d, int n) { int i; for(i=0;i<n;i++) if(is_nan(d[i])) return 1; return 0; } double norm_d(const double p[2]) { return sqrt(p[0]*p[0]+p[1]*p[1]); } double deg2rad(double deg) { return deg * (M_PI / 180); } double rad2deg(double rad) { return rad * (180 / M_PI); } void copy_d(const double*from, int n, double*to) { int i; for(i=0;i<n;i++) to[i] = from[i]; } void ominus_d(const double x[3], double res[3]) { double c = cos(x[2]); double s = sin(x[2]); res[0] = -c*x[0]-s*x[1]; res[1] = s*x[0]-c*x[1]; res[2] = -x[2]; } /** safe if res == x1 */ void oplus_d(const double x1[3], const double x2[3], double res[3]) { double c = cos(x1[2]); double s = sin(x1[2]); double x = x1[0]+c*x2[0]-s*x2[1]; double y = x1[1]+s*x2[0]+c*x2[1]; double theta = x1[2]+x2[2]; res[0]=x; res[1]=y; res[2]=theta; } void transform_d(const double point2d[2], const double pose[3], double result2d[2]) { double theta = pose[2]; double c = cos(theta); double s = sin(theta); result2d[0] = pose[0] + c * point2d[0] - s * point2d[1]; result2d[1] = pose[1] + s * point2d[0] + c * point2d[1]; } void pose_diff_d(const double pose2[3], const double pose1[3], double res[3]) { double temp[3]; ominus_d(pose1, temp); oplus_d(temp, pose2, res); while(res[2] > +M_PI) res[2] -= 2*M_PI; while(res[2] < -M_PI) res[2] += 2*M_PI; } double square(double x) { return x*x; } double angleDiff(double a, double b) { double t = a - b; while(t<-M_PI) t+= 2*M_PI; while(t>M_PI) t-= 2*M_PI; return t; } void projection_on_line_d(const double a[2], const double b[2], const double p[2], double res[2], double *distance) { double t0 = a[0]-b[0]; double t1 = a[1]-b[1]; double one_on_r = 1 / sqrt(t0*t0+t1*t1); /* normal */ double nx = t1 * one_on_r ; double ny = -t0 * one_on_r ; double c= nx, s = ny; double rho = c*a[0]+s*a[1]; res[0] = c*rho + s*s*p[0] - c*s*p[1] ; res[1] = s*rho - c*s*p[0] + c*c*p[1] ; if(distance) *distance = fabs(rho-(c*p[0]+s*p[1])); } void projection_on_segment_d( const double a[2], const double b[2], const double x[2], double proj[2]) { projection_on_line_d(a,b,x,proj,0); if ((proj[0]-a[0])*(proj[0]-b[0]) + (proj[1]-a[1])*(proj[1]-b[1]) < 0 ) { /* the projection is inside the segment */ } else if(distance_squared_d(a,x) < distance_squared_d(b,x)) copy_d(a,2,proj); else copy_d(b,2,proj); } double dist_to_segment_squared_d(const double a[2], const double b[2], const double x[2]) { double projection[2]; projection_on_segment_d(a, b, x, projection); double distance_sq_d = distance_squared_d(projection, x); return distance_sq_d; } double dist_to_segment_d(const double a[2], const double b[2], const double x[2]) { double proj[2]; double distance; projection_on_line_d(a,b,x,proj, &distance); if ((proj[0]-a[0])*(proj[0]-b[0]) + (proj[1]-a[1])*(proj[1]-b[1]) < 0 ) { /* the projection is inside the segment */ return distance; } else return sqrt(GSL_MIN( distance_squared_d(a,x), distance_squared_d(b,x))); } int count_equal(const int*v, int n, int value) { int num = 0, i; for(i=0;i<n;i++) if(value == v[i]) num++; return num; } double normalize_0_2PI(double t) { if(is_nan(t)) { sm_error("Passed NAN to normalize_0_2PI().\n"); return GSL_NAN; } while(t<0) t+=2*M_PI; while(t>=2*M_PI) t-=2*M_PI; return t; } double dot_d(const double p[2], const double q[2]); double dot_d(const double p[2], const double q[2]) { return p[0]*q[0] + p[1]*q[1]; } /* Executes ray tracing for a segment. p0 and p1 are the segments extrema, eye is the position of the eye, and direction is the direction of the ray coming out of the eye. Returns true if the ray intersects the segment, and in that case *range contains the length of the ray. */ int segment_ray_tracing(const double p0[2], const double p1[2], const double eye[2], double direction, double*range) { *range = NAN; // p0 - p1 double arrow[2] = {p1[0]-p0[0],p1[1]-p0[1]}; // Normal to segment line double S[2] = { -arrow[1], arrow[0]}; // Viewing direction double N[2] = { cos(direction), sin(direction)}; // If S*N = 0 then they cannot cross double S_dot_N = dot_d(S,N); if( S_dot_N == 0) return 0; // Rho of the line in polar coordinates (multiplied by |S|) double line_rho = dot_d(p0,S); // Rho of the eye (multiplied by |S|) double eye_rho = dot_d(eye,S); // Black magic double dist = (line_rho - eye_rho) / S_dot_N; if(dist<=0) return 0; // Now we check whether the crossing point // with the line lies within the segment // Crossing point double crossing[2] = {eye[0] + N[0]*dist, eye[1]+N[1]*dist}; // Half of the segment double midpoint[2] = { 0.5*(p1[0]+p0[0]),0.5*(p1[1]+p0[1])}; double seg_size = distance_d(p0, p1); double dist_to_midpoint = distance_d(crossing, midpoint); if(dist_to_midpoint > seg_size/2 ) return 0; *range = dist; return 1; } double segment_alpha(const double p0[2], const double p1[2]) { double arrow[2] = {p1[0]-p0[0],p1[1]-p0[1]}; // Normal to segment line double S[2] = { -arrow[1], arrow[0]}; return atan2(S[1], S[0]); } static char tmp_buf[1024]; const char* friendly_pose(const double*pose) { sprintf(tmp_buf, "(%4.2f mm, %4.2f mm, %4.4f deg)", 1000*pose[0],1000*pose[1],rad2deg(pose[2])); return tmp_buf; } double max_in_array(const double*v, int n) { assert(n>0); double m = v[0]; int i; for(i=0;i<n;i++) if(v[i]>m) m = v[i]; return m; }
{ "alphanum_fraction": 0.6403718834, "avg_line_length": 25.2633451957, "ext": "c", "hexsha": "275aabf2e00d4e4951cd4d13855f07b72f0ae3b9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_path": "src/csm/sm/csm/math_utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_path": "src/csm/sm/csm/math_utils.c", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_path": "src/csm/sm/csm/math_utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2462, "size": 7099 }
#pragma once #include "cell.h" #include <boost/mp11/algorithm.hpp> #include <array> #include <gsl/span> #include <type_traits> #include <tuple> using ColumnId = CellId; template <typename T> constexpr ColumnId GetColumnId() { return CellMetaT<T>().id; } template <typename T> constexpr auto storage_required_v = std::is_empty_v<T> ? 0 : sizeof(T); // Sorts by alignment, storage size, and then name. template <typename L, typename R> struct ColumnId_less { static constexpr bool value = CellMetaT<L>() > CellMetaT<R>(); }; // List is assumed to be unique and sorted by criteria listed above class ColumnList : public gsl::span<const ColumnId> { public: using span::span; bool ContainsAll(const ColumnList& rhs) const { auto curL = begin(), endL = end(); auto curR = rhs.begin(), endR = rhs.end(); for (; curR != endR; ++curR) { for (;; ++curL) { if (curL == endL) return false; if (*curL == *curR) break; } } return true; } }; template <typename U> struct extraction; template <typename... Us> struct extraction<std::tuple<Us...>> { static constexpr std::array<ColumnId, sizeof...(Us)> ids = { GetColumnId<Us>()... }; static constexpr std::array<CellMeta, sizeof...(Us)> metas = { CellMetaT<Us>()... }; }; template <typename... Ts> struct ColumnListT : ColumnList { using unique = boost::mp11::mp_unique<std::tuple<Ts...>>; using sorted = boost::mp11::mp_sort<unique, ColumnId_less>; using types = sorted; static constexpr auto ids = extraction<types>::ids; static constexpr auto metas = extraction<types>::metas; constexpr ColumnListT() : ColumnList(ids) { } };
{ "alphanum_fraction": 0.6242905789, "avg_line_length": 27.1076923077, "ext": "h", "hexsha": "8dc8c1f5a66570e004f2c49803a6d5069d2c77f7", "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": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zestier/lime", "max_forks_repo_path": "inc/lime/column.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "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": "zestier/lime", "max_issues_repo_path": "inc/lime/column.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "c2e500421c443ebe40f04637d0c8340fa52fc495", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zestier/lime", "max_stars_repo_path": "inc/lime/column.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 438, "size": 1762 }