Search is not available for this dataset
text
string
meta
dict
#pragma once #include "GradUtil.h" #include "DistanceGrad.h" #ifndef _NOGSL #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #else #include "CustomSolver.h" #endif #include <limits> #include <math.h> #include <vector> #include "BasicError.h" using namespace std; class IntervalGrad { double low; double high; gsl_vector* lgrad; gsl_vector* hgrad; //static constexpr double DELTA = 0.7; public: bool singleton; IntervalGrad(double _low, double _high, gsl_vector* _lgrad, gsl_vector* _hgrad): low(_low), high(_high), lgrad(_lgrad), hgrad(_hgrad) { singleton = false; } ~IntervalGrad(void) { gsl_vector_free(lgrad); gsl_vector_free(hgrad); } double getLow() const { return low; } double getHigh() const { return high; } gsl_vector* getLGrad() const { return lgrad; } gsl_vector* getHGrad() const { return hgrad; } void update(double _low, double _high) { low = _low; high = _high; } static void ig_plus(IntervalGrad* m, IntervalGrad* f, IntervalGrad* o); // o = m + f static void ig_times(IntervalGrad* m, IntervalGrad* f, IntervalGrad* o); // o = m * f static void ig_div(IntervalGrad* m, IntervalGrad* f, IntervalGrad* o); // o = m / f static void ig_neg(IntervalGrad* m, IntervalGrad* o); // o = -m static void ig_union(const vector<IntervalGrad*>& m, IntervalGrad* o); // o = m_1 V m_2 V ... static void ig_equal(IntervalGrad* m, IntervalGrad* f, DistanceGrad* o); // o = m == f static void ig_lt(IntervalGrad* m, IntervalGrad* f, DistanceGrad* o); // o = m < f static void ig_square(IntervalGrad* m, IntervalGrad* o); // o = m * m static void ig_arctan(IntervalGrad* m, IntervalGrad* o); // o = arctan(m) static void ig_sin(IntervalGrad* m, IntervalGrad* o); // o = sin(m) static void ig_cos(IntervalGrad* m, IntervalGrad* o); // o = cos(m) static void ig_tan(IntervalGrad* m, IntervalGrad* o); // o = tan(m) static void ig_sqrt(IntervalGrad* m, IntervalGrad* o); // o = sqrt(m) static void ig_exp(IntervalGrad* m, IntervalGrad* o); static void ig_copy(IntervalGrad* i1, IntervalGrad* i2); // copy i1 into i2 static void ig_cast_int_float(IntervalGrad* m, IntervalGrad* o); static void ig_conditionalUnion(IntervalGrad* m, IntervalGrad* f, DistanceGrad* d, IntervalGrad* o); static void ig_intersect(const vector<IntervalGrad*>& m, IntervalGrad* o); string print() { stringstream str; str << "Range: " << low << " " << high; return str.str(); } string printFull() { stringstream str; str << "Range: " << low << " " << high << endl; str << "LGrads: "; for (int i = 0; i < lgrad->size; i++) { str << gsl_vector_get(lgrad, i) << ", "; } str << endl; str << "HGrads: " ; for (int i = 0; i < hgrad->size; i++) { str << gsl_vector_get(hgrad, i) << ", "; } return str.str(); } private: void bound() { double oldLow = low; low = GradUtil::bound(low); if (oldLow != low) { GradUtil::default_grad(lgrad); } double oldHigh = high; high = GradUtil::bound(high); if (oldHigh != high) { GradUtil::default_grad(hgrad); } for (int i = 0; i < lgrad->size; i++) { gsl_vector_set(lgrad, i, GradUtil::bound(gsl_vector_get(lgrad, i))); gsl_vector_set(hgrad, i, GradUtil::bound(gsl_vector_get(hgrad, i))); } } };
{ "alphanum_fraction": 0.6656346749, "avg_line_length": 31.0576923077, "ext": "h", "hexsha": "1e5fca6b6681367fa7b202750eba5971f5fa1ebf", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/IntervalGrad.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/IntervalGrad.h", "max_line_length": 136, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/IntervalGrad.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 1011, "size": 3230 }
#ifndef UTIL_H #define UTIL_H #include <iostream> #include <stdio.h> #include <vector> #include <Eigen/Core> #include <Eigen/SparseCore> #include <Eigen/Householder> #include <Eigen/LU> #include <assert.h> #include <time.h> #include <sys/time.h> #include <random> #ifdef USE_MKL #include <mkl_cblas.h> #include <mkl_lapacke.h> #else #include <cblas.h> #include <lapacke.h> #endif #include "spaND.h" namespace spaND { bool are_connected(Eigen::VectorXi &a, Eigen::VectorXi &b, SpMat &A); bool should_be_disconnected(int lvl1, int lvl2, int sep1, int sep2); double elapsed(timeval& start, timeval& end); void swap2perm(Eigen::VectorXi* swap, Eigen::VectorXi* perm); bool isperm(const Eigen::VectorXi* perm); Eigen::VectorXi invperm(const Eigen::VectorXi& perm); SpMat symmetric_graph(SpMat& A); typedef timeval timer; timer wctime(); /** * C <- alpha A * B + beta C * C <- alpha A^T * B + beta C * C <- alpha A * B^T + beta C * C <- alpha A^T * B^T + beta C * Gemm */ void gemm(Eigen::MatrixXd* A, Eigen::MatrixXd* B, Eigen::MatrixXd* C, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha, double beta); /** Return a new * C <- alpha A^(/T) * B^(/T) **/ Eigen::MatrixXd* gemm_new(Eigen::MatrixXd* A, Eigen::MatrixXd* B, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha); /** * C <- alpha A * A^T + beta C (or A^T * A) */ void syrk(Eigen::MatrixXd* A, Eigen::MatrixXd* C, CBLAS_TRANSPOSE tA, double alpha, double beta); /** * A <- L, L L^T = A * Return != 0 if potf failed (not spd) */ int potf(Eigen::MatrixXd* A); int ldlt(Eigen::MatrixXd* A, Eigen::MatrixXd* L, Eigen::VectorXd* d, Eigen::VectorXi* p, double* rcond); /** * A <- [L\U] (lower and upper) * p <- swap (NOT a permutation) * A[p] = L*U * L is unit diagonal * U is not * Return != 0 if getf failed (singular) */ int getf(Eigen::MatrixXd* A, Eigen::VectorXi* swap); /** * A = P L U Q * A <- [L\U] (lower and upper) * L is unit diagonal * U is not */ void fpgetf(Eigen::MatrixXd* A, Eigen::VectorXi* p, Eigen::VectorXi* q); /** * A = L U * breaks down into L & U, and split the diagonal between the two * A = L * (D + U') = L * D (I + D^-1 U') = { L * |D|^1/2 } { |D|^1/2 sign(D) (I + D^-1 U') } */ void split_LU(Eigen::MatrixXd* A, Eigen::MatrixXd* L, Eigen::MatrixXd* U); /** * Compute an estimated 1-norm condition number of A using its LU or Cholesky factorization */ double rcond_1_getf(Eigen::MatrixXd* A_LU, double A_1_norm); double rcond_1_potf(Eigen::MatrixXd* A_LLT, double A_1_norm); double rcond_1_trcon(Eigen::MatrixXd* LU, char uplo, char diag); /** * B <- B * L^(-1) * B <- B * L^(-T) * B <- B * U^(-1) * B <- B * U^(-T) */ void trsm_right(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag); /** * B <- L^(-1) * B * B <- L^(-T) * B * B <- U^(-1) * B * B <- U^(-T) * B */ void trsm_left(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag); /** * x <- L^(-1) * x * x <- L^(-T) * x * x <- U^(-1) * x * x <- U^(-T) * x */ void trsv(Eigen::MatrixXd* L, Segment* x, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag); /** * x <- L^T * x */ void trmv_trans(Eigen::MatrixXd* L, Segment* x); /** * A <- L^T * A */ void trmm_trans(Eigen::MatrixXd* L, Eigen::MatrixXd* A); /** * x2 <- x2 - A21 * x1 */ void gemv_notrans(Eigen::MatrixXd* A21, Segment* x1, Segment* x2); /** * x2 <- x2 - A12^T * x1 */ void gemv_trans(Eigen::MatrixXd* A12, Segment* x1, Segment* x2); /** * AP = QR */ void geqp3(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau); /** * A = U S VT * Compute the full SVD, where if A is mxn, U is mxm, V is nxn, and S is min(M,N) * VT is V^T, *not* V. */ void gesvd(Eigen::MatrixXd* A, Eigen::MatrixXd* U, Eigen::VectorXd* S, Eigen::MatrixXd* VT); /** * A = U S U^T * A <- U * Full Symmetric EVD */ void syev(Eigen::MatrixXd* A, Eigen::VectorXd* S); /** * x <- Q * x */ void ormqr_notrans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x); /** * x <- Q^T * x * A <- Q^T * A */ void ormqr_trans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x); /** * A <- A * Q * A <- A * Q^T * A <- Q * A * A <- Q^T * A */ void ormqr(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A, char side, char trans); /** * Create the thin Q */ void orgqr(Eigen::MatrixXd* v, Eigen::VectorXd* h); /** * Create a square Q */ // void orgqr_fat(Eigen::MatrixXd* v, Eigen::VectorXd* h); /** * A = QR */ void geqrf(Eigen::MatrixXd* A, Eigen::VectorXd* tau); int choose_rank(Eigen::VectorXd& s, double tol); std::size_t hashv(std::vector<size_t> vals); // Hash function for Eigen matrix and vector. // The code is from `hash_combine` function of the Boost library. See // http://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine . template<typename T> struct matrix_hash : std::unary_function<T, size_t> { std::size_t operator()(T const& matrix) const { // Note that it is oblivious to the storage order of Eigen matrix (column- or // row-major). It will give you the same hash value for two different matrices if they // are the transpose of each other in different storage order. size_t seed = 0; for (size_t i = 0; i < matrix.size(); ++i) { auto elem = *(matrix.data() + i); seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } }; void block2dense(Eigen::VectorXi &rowval, Eigen::VectorXi &colptr, Eigen::VectorXd &nnzval, int i, int j, int li, int lj, Eigen::MatrixXd *dst, bool transpose); Eigen::MatrixXd linspace_nd(int n, int dim); // Returns A[p,p] SpMat symm_perm(SpMat &A, Eigen::VectorXi &p); // Random vector with seed Eigen::VectorXd random(int size, int seed); Eigen::MatrixXd random(int rows, int cols, int seed); // Set Eigen::MatrixXd to zero using memset void setZero(Eigen::MatrixXd* A); // Print vector template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { for(auto v_ : v) { os << v_ << " " ; } os << std::endl; return os; } // Range template<typename T> struct ItRange { public: ItRange(const T& begin, const T& end) : begin_(begin), end_(end) {} const T& begin() const { return this->begin_; } const T& end() { return this->end_; } private: T begin_; T end_; }; /** * Statistics and Logging **/ struct Profile { public: double elim; double scale; double spars; double merge; double elim_pivot; double elim_panel; double elim_schur; double scale_pivot; double scale_panel; double spars_assmb; double spars_spars; double spars_scatt; double merge_alloc; double merge_copy; double potf; double ldlt; double trsm; double gemm; double geqp3; double geqrf; double syev; double gesvd; double getf; double buildq; double scattq; double perma; double scatta; double assmb; double phi; Profile() : elim(0), scale(0), spars(0), merge(0), elim_pivot(0), elim_panel(0), elim_schur(0), scale_pivot(0), scale_panel(0), spars_assmb(0), spars_spars(0), spars_scatt(0), merge_alloc(0), merge_copy(0), potf(0), ldlt(0), trsm(0), gemm(0), geqp3(0), geqrf(0), syev(0), gesvd(0), getf(0), buildq(0), scattq(0), perma(0), scatta(0), assmb(0), phi(0) {} }; struct PivotFlops { long rows; double time; }; struct PanelFlops { long rows; long cols; double time; }; struct GemmFlops { long rows; long cols; long inner; double time; }; struct RRQRFlops { long rows; long cols; double time; }; struct ProfileFlops { public: std::vector<PivotFlops> pivot; std::vector<PanelFlops> panel; std::vector<GemmFlops> gemm; std::vector<RRQRFlops> rrqr; ProfileFlops() {}; }; template<typename T> struct Stats { private: T min; T max; T sum; int count; public: Stats(): min(std::numeric_limits<T>::max()), max(std::numeric_limits<T>::lowest()), sum(0), count(0) {}; void addData(T value) { this->min = (this->min < value ? this->min : value); this->max = (this->max > value ? this->max : value); this->sum += value; this->count += 1; } T getMin() const { return this->count == 0 ? 0 : this->min; } T getMax() const { return this->count == 0 ? 0 : this->max; } double getMean() const { return ((double)this->sum)/((double)this->count); } int getCount() const { return this->count; } T getSum() const { return this->sum; } }; struct Log { public: int dofs_nd; int dofs_left_nd; int dofs_left_elim; int dofs_left_spars; long long int fact_nnz; Stats<int> rank_before; Stats<int> rank_after; int ignored; Stats<int> nbrs; Stats<double> cond_diag_elim; Stats<double> norm_diag_elim; Stats<double> cond_U_elim; Stats<double> cond_L_elim; Stats<double> cond_diag_scal; Stats<double> norm_diag_scal; Stats<double> cond_U_scal; Stats<double> cond_L_scal; double Asym_before_scaling; double Asym_after_scaling; Stats<double> Anorm_before_lower; Stats<double> Anorm_before_upper; Stats<double> Anorm_after_lower; Stats<double> Anorm_after_upper; Log() : dofs_nd(0), dofs_left_nd(0), dofs_left_elim(0), dofs_left_spars(0), fact_nnz(0), ignored(0), Asym_before_scaling(0), Asym_after_scaling(0) {} }; } #endif
{ "alphanum_fraction": 0.5938058368, "avg_line_length": 24.8128078818, "ext": "h", "hexsha": "95b53703ddfb0466422ea81226558e9b07d77080", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-06-23T12:04:28.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-23T12:04:28.000Z", "max_forks_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "leopoldcambier/spaND_public", "max_forks_repo_path": "include/util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "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": "leopoldcambier/spaND_public", "max_issues_repo_path": "include/util.h", "max_line_length": 160, "max_stars_count": 6, "max_stars_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "leopoldcambier/spaND_public", "max_stars_repo_path": "include/util.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T14:56:30.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-06T21:17:07.000Z", "num_tokens": 3051, "size": 10074 }
/* * SpecialFunctions.h * PSCAcoustic * * Special functions and more. * * * Copyright 2014 Pierre-David Letourneau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef SPECIALFUNCTIONS_H #define SPECIALFUNCTIONS_H #include "General.h" // GSL library //#include "../gsl-1.16/include/gsl/gsl_sf_bessel.h" //spherical bessel functions #include <gsl/gsl_sf_bessel.h> //spherical bessel functions #include "./gsl-1.16/include/gsl/gsl_sf_legendre.h" //associated Legendre polynomials (for spherical harmonics) #include "./gsl-1.16/include/gsl/gsl_complex_math.h" #include "./gsl-1.16/include/gsl/gsl_sf_gamma.h" #include "./gsl-1.16/include/gsl/gsl_sf_hyperg.h" #include "./gsl-1.16/include/gsl/gsl_sf_coupling.h" #include "./gsl-1.16/include/gsl/gsl_integration.h" #include "./gsl-1.16/include/gsl/gsl_complex.h" #include "./gsl-1.16/include/gsl/gsl_sf_coupling.h" #include "./gsl-1.16/include/gsl/gsl_math.h" #include "./gsl-1.16/include/gsl/gsl_ieee_utils.h" #include "./gsl-1.16/include/gsl/gsl_errno.h" #include "./gsl-1.16/include/gsl/gsl_integration.h" // Complex Bessel functions //#include "../AmosBessel/libAmosBessel.h" //GSL wrappers (Cannot handle complex arguments) //Hankel function of the 1st kind (gsl) inline complex gsl_sf_hankel_1( int l, double x){ return gsl_sf_bessel_jl(l,x) + gsl_sf_bessel_yl(l,x) * CI; } inline double gsl_sf_legendre( int l, int m, double x){ double C = 1; if( m < 0 ) C *= pow(-1, std::abs(m)); return (C * gsl_sf_legendre_sphPlm ( l, std::abs(m), x) ); } // Y_lm (spherical harmonics) //\sqrt{(2l+1)/(4\pi)} \sqrt{(l-m)!/(l+m)!} P_l^m(x) exp(I*m*phi) ) inline complex gsl_sf_harmonic( int l, int m, double theta, double phi){ if( l >= std::abs(m) ){ return gsl_sf_legendre(l, m, cos(theta)) * exp(m*phi*CI); } else { return 0.; } } inline complex gsl_sf_clebsch(int l1, int l2, int l3, int m1, int m2, int m3){ return pow(-1., (double) l1-l2+m3) * sqrt(2.*l3+1.) * gsl_sf_coupling_3j(2*l1, 2*l2, 2*l3, 2*m1, 2*m2, -2*m3); } inline double gsl_sf_gaunt(int n, int m, int nu, int mu, int q){ return pow(-1., (double) (m+mu) ) * sqrt((2*n+1)*(2*nu+1)*(2*q+1)/(4*PI)) * gsl_sf_coupling_3j(2.*n,2.*nu,2.*q,0,0,0) * gsl_sf_coupling_3j(2.*n,2.*nu,2.*q,2.*m,2.*mu,-2.*(m+mu)); } // TODO: FIX AMOS //Amos wrappers for Bessel functions (these can handle complex arguments) inline complex Amos_sf_bessel_jl(int l, complex z){ complex value; //AmosBessel('j', z, (double) l, 1, 0, &value); value = gsl_sf_bessel_jl(l,std::real(z)); return value; } inline complex Amos_sf_bessel_yl(int l, complex z){ complex value; //AmosBessel('y', z, (double) l, 1, 0, &value); value = gsl_sf_bessel_yl(l,std::real(z)); return value; } inline complex Amos_sf_hankel_1(int l, complex z){ //complex valueR; //AmosBessel('j', z, (double) l, 1, 0, &valueR); //complex valueI; //AmosBessel('y', z, (double) l, 1, 0, &valueI); //return (valueR + valueI*CI); complex value = gsl_sf_hankel_1(l, std::real(z)); return value; } // Derivatives inline double gsl_sf_bessel_jl_prime(int l, double z){ return l/z * gsl_sf_bessel_jl(l,z) - gsl_sf_bessel_jl(l+1,z); } inline complex gsl_sf_hankel_l_prime(int l, double z){ return l/z * gsl_sf_hankel_1( l, z) - gsl_sf_hankel_1(l+1, z); } inline complex Amos_sf_bessel_jl_prime(double l, complex z){ return l/z * Amos_sf_bessel_jl(l,z) - Amos_sf_bessel_jl(l+1,z); } inline complex Amos_sf_hankel_l_prime(double l, complex z){ return l/z * Amos_sf_hankel_1( l, z) - Amos_sf_hankel_1(l+1, z); } // Chebyshev polynomial evaluation inline double Cheb(int n, double x){ return cos(n*acos(x)); } // Gauss-Legendre quadrature inline void getGaussLegendreQuad(int N, std::vector<double>& x, std::vector<double>& w) { x.resize(N); w.resize(N); gsl_integration_glfixed_table* GLTable = gsl_integration_glfixed_table_alloc(N); for( int n = 0; n < (N+1)/2; ++n ) { x[n + N/2] = GLTable->x[n]; w[n + N/2] = GLTable->w[n]; } for( int n = 0; n < N/2; ++n ) { x[n] = -x[N-1-n]; w[n] = w[N-1-n]; } gsl_integration_glfixed_table_free( GLTable ); } // Gauss-Chebyshev quadrature inline void getGaussChebyshevQuad(int N, std::vector<double>& x, std::vector<double>& w) { x.resize(N); w.resize(N); for( int n = 0; n < N; n++ ) { x[n] = cos( (2.*n+1.)/(2.*N)*PI ); w[n] = 2./N; } } //---------General Functions--------// #define ISODD(x) ((x) & 1) #define ISNAN(x) ((x) != (x)) //TODO : still needed? inline int choose( int n, int r ){ if( (n < r) || (r < 0) || (n < 0) ){ return 0; } else { return gsl_sf_gamma(n+1) / (gsl_sf_gamma(r+1) * gsl_sf_gamma(n-r+1)); } } // Implementation os Sparse Matrix class // TODO: this takes a lot of memory? class SpMatrix { map<std::pair<int,int>, complex > M; public: // Empty constructor SpMatrix(){} ~SpMatrix(){} void add(int i, int j, complex val){ assert( i >= 0 ); assert( j >= 0 ); std::pair<int,int> coord = std::make_pair(i,j); if( M.count(coord) ){ M.insert(std::make_pair(coord, val)); } else { M[coord] = val; } } complex operator () (int i, int j){ std::pair<int,int> coord = std::make_pair(i,j); complex val = 0.; ( M.count(coord) ) ? val = M.find(coord)->second : val = 0.; return val; } inline int size() { return M.size(); } }; #endif
{ "alphanum_fraction": 0.6563706564, "avg_line_length": 25.1945525292, "ext": "h", "hexsha": "4e671062372e718e25b9efaefecc5d44f10225ce", "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": "eaf127f0bd6aa9bdf4a051b4390966e86fdf6751", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "pl2526/PSCAcoustic", "max_forks_repo_path": "SpecialFunctions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "eaf127f0bd6aa9bdf4a051b4390966e86fdf6751", "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": "pl2526/PSCAcoustic", "max_issues_repo_path": "SpecialFunctions.h", "max_line_length": 112, "max_stars_count": null, "max_stars_repo_head_hexsha": "eaf127f0bd6aa9bdf4a051b4390966e86fdf6751", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "pl2526/PSCAcoustic", "max_stars_repo_path": "SpecialFunctions.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2130, "size": 6475 }
/* multifit/multilinear.c * * Copyright (C) 2000, 2007, 2010 Brian Gough * Copyright (C) 2013, 2015 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //#include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include "linear_common.c" static int multifit_linear_svd (const gsl_matrix * X, const int balance, gsl_multifit_linear_workspace * work); int gsl_multifit_linear (const gsl_matrix * X, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { size_t rank; int status = gsl_multifit_linear_tsvd(X, y, GSL_DBL_EPSILON, c, cov, chisq, &rank, work); return status; } /* gsl_multifit_linear_tsvd() Solve linear least squares system with truncated SVD Inputs: X - least squares matrix, n-by-p y - right hand side vector, n-by-1 tol - tolerance for singular value truncation; if s_j <= tol * s_0 then it is discarded from series expansion c - (output) solution vector, p-by-1 cov - (output) covariance matrix, p-by-p chisq - (output) cost function chi^2 rank - (output) effective rank (number of singular values used in solution) work - workspace */ int gsl_multifit_linear_tsvd (const gsl_matrix * X, const gsl_vector * y, const double tol, gsl_vector * c, gsl_matrix * cov, double * chisq, size_t * rank, gsl_multifit_linear_workspace * work) { const size_t n = X->size1; const size_t p = X->size2; if (y->size != n) { GSL_ERROR("number of observations in y does not match matrix", GSL_EBADLEN); } else if (p != c->size) { GSL_ERROR ("number of parameters c does not match matrix", GSL_EBADLEN); } else if (tol <= 0) { GSL_ERROR ("tolerance must be positive", GSL_EINVAL); } else { int status; double rnorm = 0.0, snorm; /* compute balanced SVD */ status = gsl_multifit_linear_bsvd (X, work); if (status) return status; status = multifit_linear_solve (X, y, tol, -1.0, rank, c, &rnorm, &snorm, work); *chisq = rnorm * rnorm; /* variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */ { double r2 = rnorm * rnorm; double s2 = r2 / (double)(n - *rank); size_t i, j; gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p); gsl_vector_view D = gsl_vector_subvector(work->D, 0, p); for (i = 0; i < p; i++) { gsl_vector_view row_i = gsl_matrix_row (&QSI.matrix, i); double d_i = gsl_vector_get (&D.vector, i); for (j = i; j < p; j++) { gsl_vector_view row_j = gsl_matrix_row (&QSI.matrix, j); double d_j = gsl_vector_get (&D.vector, j); double s; gsl_blas_ddot (&row_i.vector, &row_j.vector, &s); gsl_matrix_set (cov, i, j, s * s2 / (d_i * d_j)); gsl_matrix_set (cov, j, i, s * s2 / (d_i * d_j)); } } } return status; } } /* gsl_multifit_linear_svd() Perform SVD decomposition of the matrix X and store in work without balancing */ int gsl_multifit_linear_svd (const gsl_matrix * X, gsl_multifit_linear_workspace * work) { /* do not balance by default */ int status = multifit_linear_svd(X, 0, work); return status; } /* gsl_multifit_linear_bsvd() Perform SVD decomposition of the matrix X and store in work with balancing */ int gsl_multifit_linear_bsvd (const gsl_matrix * X, gsl_multifit_linear_workspace * work) { int status = multifit_linear_svd(X, 1, work); return status; } size_t gsl_multifit_linear_rank(const double tol, const gsl_multifit_linear_workspace * work) { double s0 = gsl_vector_get (work->S, 0); size_t rank = 0; size_t j; for (j = 0; j < work->p; j++) { double sj = gsl_vector_get (work->S, j); if (sj > tol * s0) ++rank; } return rank; } /* Estimation of values for given x */ int gsl_multifit_linear_est (const gsl_vector * x, const gsl_vector * c, const gsl_matrix * cov, double *y, double *y_err) { if (x->size != c->size) { GSL_ERROR ("number of parameters c does not match number of observations x", GSL_EBADLEN); } else if (cov->size1 != cov->size2) { GSL_ERROR ("covariance matrix is not square", GSL_ENOTSQR); } else if (c->size != cov->size1) { GSL_ERROR ("number of parameters c does not match size of covariance matrix cov", GSL_EBADLEN); } else { size_t i, j; double var = 0; gsl_blas_ddot(x, c, y); /* y = x.c */ /* var = x' cov x */ for (i = 0; i < x->size; i++) { const double xi = gsl_vector_get (x, i); var += xi * xi * gsl_matrix_get (cov, i, i); for (j = 0; j < i; j++) { const double xj = gsl_vector_get (x, j); var += 2 * xi * xj * gsl_matrix_get (cov, i, j); } } *y_err = sqrt (var); return GSL_SUCCESS; } } /* gsl_multifit_linear_rcond() Return reciprocal condition number of LS matrix; gsl_multifit_linear_svd() must first be called to compute the SVD of X and its reciprocal condition number */ double gsl_multifit_linear_rcond (const gsl_multifit_linear_workspace * w) { return w->rcond; } /* gsl_multifit_linear_residuals() Compute vector of residuals from fit Inputs: X - design matrix y - rhs vector c - fit coefficients r - (output) where to store residuals */ int gsl_multifit_linear_residuals (const gsl_matrix *X, const gsl_vector *y, const gsl_vector *c, gsl_vector *r) { if (X->size1 != y->size) { GSL_ERROR ("number of observations in y does not match rows of matrix X", GSL_EBADLEN); } else if (X->size2 != c->size) { GSL_ERROR ("number of parameters c does not match columns of matrix X", GSL_EBADLEN); } else if (y->size != r->size) { GSL_ERROR ("number of observations in y does not match number of residuals", GSL_EBADLEN); } else { /* r = y - X c */ gsl_vector_memcpy(r, y); gsl_blas_dgemv(CblasNoTrans, -1.0, X, c, 1.0, r); return GSL_SUCCESS; } } /* gsl_multifit_linear_residuals() */ /* Perform a SVD decomposition on the least squares matrix X = U S Q^T * * Inputs: X - least squares matrix * balance - 1 to perform column balancing * work - workspace * * Notes: * 1) On output, * work->A contains the matrix U * work->Q contains the matrix Q * work->S contains the vector of singular values * 2) The matrix X may have smaller dimensions than the workspace * in the case of stdform2() - but the dimensions cannot be larger * 3) On output, work->n and work->p are set to the dimensions of X * 4) On output, work->rcond is set to the reciprocal condition number of X */ static int multifit_linear_svd (const gsl_matrix * X, const int balance, gsl_multifit_linear_workspace * work) { const size_t n = X->size1; const size_t p = X->size2; if (n > work->nmax || p > work->pmax) { GSL_ERROR("observation matrix larger than workspace", GSL_EBADLEN); } else { gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p); gsl_matrix_view Q = gsl_matrix_submatrix(work->Q, 0, 0, p, p); gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p); gsl_vector_view S = gsl_vector_subvector(work->S, 0, p); gsl_vector_view xt = gsl_vector_subvector(work->xt, 0, p); gsl_vector_view D = gsl_vector_subvector(work->D, 0, p); /* Copy X to workspace, A <= X */ gsl_matrix_memcpy (&A.matrix, X); /* Balance the columns of the matrix A if requested */ if (balance) { gsl_linalg_balance_columns (&A.matrix, &D.vector); } else { gsl_vector_set_all (&D.vector, 1.0); } /* decompose A into U S Q^T */ gsl_linalg_SV_decomp_mod (&A.matrix, &QSI.matrix, &Q.matrix, &S.vector, &xt.vector); /* compute reciprocal condition number rcond = smin / smax */ { double smin, smax; gsl_vector_minmax(&S.vector, &smin, &smax); work->rcond = smin / smax; } work->n = n; work->p = p; return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.581010101, "avg_line_length": 27.731092437, "ext": "c", "hexsha": "6a6931f6338e2531a722ac2f49e7c4e617e7c832", "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": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "agroimpacts/imager", "max_forks_repo_path": "C/AFMapTSComposite/multilinear.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "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": "agroimpacts/imager", "max_issues_repo_path": "C/AFMapTSComposite/multilinear.c", "max_line_length": 91, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "agroimpacts/imager", "max_stars_repo_path": "C/AFMapTSComposite/multilinear.c", "max_stars_repo_stars_event_max_datetime": "2021-09-01T18:48:12.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-01T18:48:12.000Z", "num_tokens": 2660, "size": 9900 }
/* multimin/fminimizer.c * * Copyright (C) 2002 Tuomo Keskitalo, Ivo Alxneit * * 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 <gsl/gsl_errno.h> #include <gsl/gsl_multimin.h> gsl_multimin_fminimizer * gsl_multimin_fminimizer_alloc (const gsl_multimin_fminimizer_type * T, size_t n) { int status; gsl_multimin_fminimizer *s = (gsl_multimin_fminimizer *) malloc (sizeof (gsl_multimin_fminimizer)); if (s == 0) { GSL_ERROR_VAL ("failed to allocate space for minimizer struct", GSL_ENOMEM, 0); } s->type = T; s->x = gsl_vector_calloc (n); if (s->x == 0) { free (s); GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0); } s->state = malloc (T->size); if (s->state == 0) { gsl_vector_free (s->x); free (s); GSL_ERROR_VAL ("failed to allocate space for minimizer state", GSL_ENOMEM, 0); } status = (T->alloc) (s->state, n); if (status != GSL_SUCCESS) { free (s->state); gsl_vector_free (s->x); free (s); GSL_ERROR_VAL ("failed to initialize minimizer state", GSL_ENOMEM, 0); } return s; } int gsl_multimin_fminimizer_set (gsl_multimin_fminimizer * s, gsl_multimin_function * f, const gsl_vector * x, const gsl_vector * step_size) { if (s->x->size != f->n) { GSL_ERROR ("function incompatible with solver size", GSL_EBADLEN); } if (x->size != f->n || step_size->size != f->n) { GSL_ERROR ("vector length not compatible with function", GSL_EBADLEN); } s->f = f; gsl_vector_memcpy (s->x,x); return (s->type->set) (s->state, s->f, s->x, &(s->size), step_size); } void gsl_multimin_fminimizer_free (gsl_multimin_fminimizer * s) { (s->type->free) (s->state); free (s->state); gsl_vector_free (s->x); free (s); } int gsl_multimin_fminimizer_iterate (gsl_multimin_fminimizer * s) { return (s->type->iterate) (s->state, s->f, s->x, &(s->size), &(s->fval)); } const char * gsl_multimin_fminimizer_name (const gsl_multimin_fminimizer * s) { return s->type->name; } gsl_vector * gsl_multimin_fminimizer_x (const gsl_multimin_fminimizer * s) { return s->x; } double gsl_multimin_fminimizer_minimum (const gsl_multimin_fminimizer * s) { return s->fval; } double gsl_multimin_fminimizer_size (const gsl_multimin_fminimizer * s) { return s->size; }
{ "alphanum_fraction": 0.6400621118, "avg_line_length": 23.8518518519, "ext": "c", "hexsha": "507dfd4efca87f52f577b64b44c8a186985def7c", "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/multimin/fminimizer.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/multimin/fminimizer.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/multimin/fminimizer.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": 924, "size": 3220 }
/* ** TFCE heuristic ** ** M. Kuhlmann, MPI-KYB, Sept 2015 */ #include <viaio/VImage.h> #include <viaio/Vlib.h> #include <viaio/mu.h> #include <via/via.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_math.h> #define ABS(x) ((x) > 0 ? (x) : -(x)) VImage tfce(VImage t_image,VImage map,int nstrata) { int b,r,c,i,j,k; size_t nslices = VImageNBands(t_image); size_t nrows = VImageNRows(t_image); size_t ncols = VImageNColumns(t_image); double tiny = 1e-16; /* if pixel map is not given, compute it */ if(!map) { VImage mask = VCreateImage(nslices,nrows,ncols,VBitRepn); VFillImage(mask,VAllBands,0); size_t nvox = 0; float u; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { u = VPixel(t_image,b,r,c,VFloat); if (ABS(u) >= tiny) { VPixel(mask,b,r,c,VBit) = 1; nvox++; } } } } if(nvox == 0) VError("TFCE: Number of voxels!=0 is zero."); /* voxel addresses */ map = VCreateImage(1,3,nvox,VShortRepn); if (map == NULL) VError(" error allocating addr map"); VFillImage(map,VAllBands,0); i = 0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { if (VGetPixel(mask,b,r,c) < 0.5) continue; VPixel(map,0,0,i,VShort) = b; VPixel(map,0,1,i,VShort) = r; VPixel(map,0,2,i,VShort) = c; i++; } } } VDestroyImage(mask); } /* stratification */ /* set z strata */ size_t nvox = VImageNColumns(map); double z; /* get an idea of z-value distribution */ double zmax=0; for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VShort); r = VPixel(map,0,1,i,VShort); c = VPixel(map,0,2,i,VShort); z = VPixel(t_image,b,r,c,VFloat); if (z > zmax) zmax = z; } /* ini strata */ double step = zmax / (double)nstrata; double *stratum = (double *) VCalloc(nstrata+1,sizeof(double)); for (j=0; j<=nstrata; j++) stratum[j] = step*j; float *clustersize = (float *) VCalloc(nvox,sizeof(float)); if (!clustersize) VError(" err allocating clustersize"); float *cluster_cont = (float *) VCalloc(nvox,sizeof(float)); if (!cluster_cont) VError(" err allocating cluster_cont"); for (i=0; i<nvox; i++) { clustersize[i] = 0; cluster_cont[i] = 0; } /* output, create TFCE image */ VImage tfce = VCreateImage(nslices,nrows,ncols,VFloatRepn); if (!tfce) VError(" err allocating tfce image"); VFillImage(tfce,VAllBands,0); /* ini images */ VImage bin_image = VCreateImage(nslices,nrows,ncols,VBitRepn); if (!bin_image) VError(" err allocating bin_image image"); VImage label_image = VCreateImage(nslices,nrows,ncols,VShortRepn); if (!label_image) VError(" err allocating label_image image"); /* for each stratum */ double *strat_sq = (double *)VCalloc(nstrata,sizeof(double)); for (j=0; j<nstrata; j++) strat_sq[j] = stratum[j] * stratum[j]; for (j=0; j<nstrata; j++) { VFillImage(bin_image,VAllBands,0); for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VShort); r = VPixel(map,0,1,i,VShort); c = VPixel(map,0,2,i,VShort); z = VPixel(t_image,b,r,c,VFloat); if (z > stratum[j]) { VPixel(bin_image,b,r,c,VBit) = 1; } } /* get connected components (clusters) */ long nl=0; VLabelImage3d(bin_image,label_image,26,VShortRepn,&nl); if (nl < 1) continue; /* no voxels in this stratum found */ /* compute cluster sizes */ int max_k = 0; for (i=0; i<nvox; i++) clustersize[i] = 0; for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VShort); r = VPixel(map,0,1,i,VShort); c = VPixel(map,0,2,i,VShort); k = VPixel(label_image,b,r,c,VShort); if (k > 0) clustersize[k]++; if (k > max_k) max_k = k; } /* compute contribution of the cluster to the voxels in it */ for (i=0; i<=max_k; i++) cluster_cont[i] = sqrt(clustersize[i]) * strat_sq[j]; /* add cluster contribution to each voxel */ for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VShort); r = VPixel(map,0,1,i,VShort); c = VPixel(map,0,2,i,VShort); k = VPixel(label_image,b,r,c,VShort); VPixel(tfce,b,r,c,VFloat) += cluster_cont[k]; } } /* thickness correction */ for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VShort); r = VPixel(map,0,1,i,VShort); c = VPixel(map,0,2,i,VShort); k = VPixel(label_image,b,r,c,VShort); VPixel(tfce,b,r,c,VFloat) *= step; } VDestroyImage(bin_image); VDestroyImage(label_image); VFree(clustersize); VFree(cluster_cont); VFree(stratum); VFree(strat_sq); return tfce; }
{ "alphanum_fraction": 0.5943555181, "avg_line_length": 26.9772727273, "ext": "c", "hexsha": "eb8b144fd2ac5cf1b46ec8091a4f594f5c9815c2", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/utils/tfce.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/utils/tfce.c", "max_line_length": 68, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/utils/tfce.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 1629, "size": 4748 }
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira 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, 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. $Id$ */ #include <config.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_sf_expint.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_combination.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_chebyshev.h> #include <gsl/gsl_deriv.h> #include "string_f.h" #include <fortran_types.h> /* Numerical threshold for oct_bessel_k0 and oct_bessel_k1 */ #define BESSEL_K_THRES 1.0e2 /* ---------------------- Interface to GSL functions ------------------------ */ /* Mathematical Functions */ double FC_FUNC_(oct_asinh, OCT_ASINH) (const double *x) { return gsl_asinh(*x); } /* Special Functions */ double FC_FUNC_(oct_gamma, OCT_GAMMA) (const double *x) { return gsl_sf_gamma(*x); } double FC_FUNC_(oct_hypergeometric, OCT_HYPERGEOMETRIC) (const double *a, const double*b, const double *x) { return gsl_sf_hyperg_U(*a, *b, *x); } double FC_FUNC_(oct_incomplete_gamma, OCT_INCOMPLETE_GAMMA) (const double *a, const double *x) { return gsl_sf_gamma_inc_Q(*a, *x); } double FC_FUNC_(oct_sph_bessel, OCT_SPH_BESSEL) (const fint *l, const double*x) { return gsl_sf_bessel_jl(*l, *x); } double FC_FUNC_(oct_bessel, OCT_BESSEL) (const fint *n, const double *x) { return gsl_sf_bessel_Jn(*n, *x); } double FC_FUNC_(oct_bessel_in, OCT_BESSEL_IN) (const fint *n, const double *x) { return gsl_sf_bessel_In(*n, *x); } double FC_FUNC_(oct_bessel_j0, OCT_BESSEL_J0) (const double *x) { return gsl_sf_bessel_J0(*x); } double FC_FUNC_(oct_bessel_j1, OCT_BESSEL_J1) (const double *x) { return gsl_sf_bessel_J1(*x); } double FC_FUNC_(oct_bessel_k0, OCT_BESSEL_K0) (const double *x) { if( *x > BESSEL_K_THRES ) { return 0.0e0; } else { return gsl_sf_bessel_K0(*x); } } double FC_FUNC_(oct_bessel_k1, OCT_BESSEL_K1) (const double *x) { if( *x > BESSEL_K_THRES ) { return 0.0e0; } else { return gsl_sf_bessel_K1(*x); } } /* the GSL headers specify double x, not const double x */ double FC_FUNC_(oct_erfc, OCT_ERFC) (const double *x) { /* avoid floating invalids in the asymptotic limit */ if(*x > 20.0) return 0.0; if(*x < -20.0) return 2.0; /* otherwise call gsl */ return gsl_sf_erfc(*x); } /* the GSL headers specify double x, not const double x */ double FC_FUNC_(oct_erf, OCT_ERF) (const double *x) { /* avoid floating invalids in the asymptotic limit */ if(*x > 20.0) return 1.0; if(*x < -20.0) return -1.0; /* otherwise call gsl */ return gsl_sf_erf(*x); } double FC_FUNC_(oct_legendre_sphplm, OCT_LEGENDRE_SPHPLM) (const fint *l, const int *m, const double *x) { return gsl_sf_legendre_sphPlm(*l, *m, *x); } double FC_FUNC_(oct_sine_integral, OCT_SINE_INTEGRAL) (const double *x) { return gsl_sf_Si(*x); } /* generalized Laguerre polynomials */ double FC_FUNC_(oct_sf_laguerre_n, OCT_SF_LAGUERRE_N) (const int *n, const double *a, const double *x) { return gsl_sf_laguerre_n(*n, *a, *x); } /* Vectors and Matrices */ /* Permutations */ /* Combinations */ void FC_FUNC_(oct_combination_init, OCT_COMBINATION_INIT) (gsl_combination **c, const fint *n, const fint *k) { *c = gsl_combination_calloc (*n, *k); } void FC_FUNC_(oct_combination_next, OCT_COMBINATION_NEXT) (gsl_combination **c, fint *next) { *next = gsl_combination_next (((gsl_combination *)(*c))); } void FC_FUNC_(oct_get_combination, OCT_GET_COMBINATION) (gsl_combination **c, fint *comb) { int i; for (i=0;i< ((gsl_combination *)(*c))->k; i++) { comb[i]=(fint)((gsl_combination *)(*c))->data[i]; } } void FC_FUNC_(oct_combination_end, OCT_COMBINATION_END) (gsl_combination **c) { gsl_combination_free (((gsl_combination *)(*c))); } /* Linear Algebra */ /* Random Number Generation */ void FC_FUNC_(oct_ran_init, OCT_RAN_INIT) (gsl_rng **r) { gsl_rng_env_setup(); *r = gsl_rng_alloc(gsl_rng_default); } void FC_FUNC_(oct_ran_end, OCT_RAN_END) (gsl_rng **r) { gsl_rng_free(*r); } /* Random Number Distributions */ double FC_FUNC_(oct_ran_gaussian, OCT_RAN_GAUSSIAN) (const gsl_rng **r, const double *sigma) { return gsl_ran_gaussian(*r, *sigma); } double FC_FUNC_(oct_ran_flat, OCT_RAN_FLAT) (const gsl_rng **r, const double *a, const double *b) { return gsl_ran_flat(*r, *a, *b); } /* Interpolation */ void FC_FUNC_(oct_spline_end, OCT_SPLINE_END) (void **spl, void **acc) { gsl_spline_free((gsl_spline *)(*spl)); gsl_interp_accel_free((gsl_interp_accel *)(*acc)); } void FC_FUNC_(oct_spline_fit, OCT_SPLINE_FIT) (const fint *nrc, const double *x, const double *y, void **spl, void **acc) { /* the GSL headers actually specify size_t instead of const int for nrc */ *acc = (void *)gsl_interp_accel_alloc(); *spl = (void *)gsl_spline_alloc(gsl_interp_cspline, *nrc); gsl_spline_init((gsl_spline *)(*spl), x, y, *nrc); fflush(stdout); } double FC_FUNC_(oct_spline_eval, OCT_SPLINE_EVAL) (const double *x, const void **spl, void **acc) { /* the GSL headers specify double x instead of const double x */ return gsl_spline_eval((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } void FC_FUNC_(oct_spline_eval_array, OCT_SPLINE_EVAL_ARRAY) (const fint * nn, double *xf, const void **spl, void **acc) { int ii; for(ii = 0; ii < *nn; ii++){ xf[ii] = gsl_spline_eval((gsl_spline *)(*spl), xf[ii], (gsl_interp_accel *)(*acc)); } } void FC_FUNC_(oct_spline_eval_array4, OCT_SPLINE_EVAL_ARRAY4) (const fint * nn, float *xf, const void **spl, void **acc) { int ii; for(ii = 0; ii < *nn; ii++){ xf[ii] = (float) gsl_spline_eval((gsl_spline *)(*spl), (double) xf[ii], (gsl_interp_accel *)(*acc)); } } /* use a stride of 2 to store into just the real part of a Fortran complex array */ void FC_FUNC_(oct_spline_eval_arrayz, OCT_SPLINE_EVAL_ARRAYZ) (const fint * nn, double *xf, const void **spl, void **acc) { int ii; for(ii = 0; ii < *nn; ii++){ xf[ii*2] = gsl_spline_eval((gsl_spline *)(*spl), xf[ii*2], (gsl_interp_accel *)(*acc)); } } /* use a stride of 2 to store into just the real part of a Fortran complex array */ void FC_FUNC_(oct_spline_eval_arrayc, OCT_SPLINE_EVAL_ARRAYC) (const fint * nn, float *xf, const void **spl, void **acc) { int ii; for(ii = 0; ii < *nn; ii++){ xf[ii*2] = (float) gsl_spline_eval((gsl_spline *)(*spl), (double) xf[ii*2], (gsl_interp_accel *)(*acc)); } } /* This function returns the number of points with which a spline was constructed (the size component of the gsl_spline struct). */ fint FC_FUNC_(oct_spline_npoints, OCT_SPLINE_NPOINTS) (const void **spl) { return (fint)((gsl_spline *)(*spl))->size; } /* This function places in the x array the x values of a given spline spl*/ void FC_FUNC_(oct_spline_x, OCT_SPLINE_X) (const void **spl, double *x) { int size, i; size = (int)((gsl_spline *)(*spl))->size; for(i=0; i<size; i++) x[i] = ((gsl_spline *)(*spl))->x[i]; } /* This function places in the y array the y values of a given spline spl*/ void FC_FUNC_(oct_spline_y, OCT_SPLINE_Y) (const void **spl, double *y) { int size, i; size = (int)((gsl_spline *)(*spl))->size; for(i=0; i<size; i++) y[i] = ((gsl_spline *)(*spl))->y[i]; } /* Returns the integral of the spline stored in spl, between a and b */ double FC_FUNC_(oct_spline_eval_integ, OCT_SPLINE_EVAL_INTEG) (const void **spl, const double *a, const double *b, void **acc) { /* the GSL headers specify double a, double b */ return gsl_spline_eval_integ((gsl_spline *)(*spl), *a, *b, (gsl_interp_accel *)(* acc)); } /* Performs the derivative of a spline */ double FC_FUNC_(oct_spline_eval_der, OCT_SPLINE_EVAL_DER) (const double *x, const void **spl, void **acc) { /* the GSL headers specify double x */ return gsl_spline_eval_deriv((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } /* Performs the second derivative of a spline */ double FC_FUNC_(oct_spline_eval_der2, OCT_SPLINE_EVAL_DER2) (const double *x, const void **spl, void **acc) { /* the GSL headers specify double x */ return gsl_spline_eval_deriv2((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } void FC_FUNC_(oct_strerror, OCT_STRERROR) (const fint *err, STR_F_TYPE res STR_ARG1) { const char *c; c = gsl_strerror(*err); TO_F_STR1(c, res); } /* Chebyshev Approximations */ /* void FC_FUNC_(oct_chebyshev_coeffs, OCT_CHEBYSHEV_COEFFS) (gsl_complex *coeffs, int *order) { int i; double f (double x, void *p){return cos(x);} double g (double x, void *p){return -sin(x);} gsl_cheb_series *cs = gsl_cheb_alloc (*order); gsl_function F; F.function = f; F.params = 0; gsl_cheb_init (cs, &F, -1.0, 1.0); for(i=0; i<=12; i++){GSL_SET_REAL(&coeffs[i], (*cs).c[i]);} F.function = g; F.params = 0; gsl_cheb_init (cs, &F, -1.0, 1.0); for(i=0; i<=12; i++){GSL_SET_IMAG(&coeffs[i], (*cs).c[i]);} } */ /* Numerical Derivatives. The following is an interface to the GSL support for numerical derivatives, in particular the gsl_deriv_central function. It computes a four points approximation to the derivative of a function, supplying an error estimation. */ /* This is a type used to communicate with Fortran; func_nd is the type of the interface to a Fortran subroutine that calculates the value of the function. The first argument is the function argument, whereas the second is the function value. For convenience reasons, it is wrapped around the "param_nd_t" struct. */ typedef void (*func_nd)(double*, double*); typedef struct{ func_nd func; } param_nd_t; /* This is the function that is called by the GSL function gsl_deriv_central. It receives as first argument the function argument, and as second argument a pointer to a params data type (a GSL data type), which in this case should be a pointer to a param_nd_t data type, where the address of the Fortran subroutine is. */ double function_oct_numerical_derivative (double x, void * params) { double res; param_nd_t * p; p = (param_nd_t *) params; p->func(&x, &res); return res; } /* This is the function that should be called by Fortran. The interface is defined in loct_math.F90 file. */ void FC_FUNC_(oct_numerical_derivative, OCT_NUMERICAL_DERIVATIVE) (const double *x, const double *h, double *result, double *abserr, const func_nd f) { gsl_function F; param_nd_t p; p.func = f; F.function = &function_oct_numerical_derivative; F.params = (void *) &p; /* the GSL headers specify double x, double h */ gsl_deriv_central (&F, *x, *h, result, abserr); return; }
{ "alphanum_fraction": 0.6827278193, "avg_line_length": 26.8891454965, "ext": "c", "hexsha": "659604be1baf030bb6972a60d989794c8fda3ef4", "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": "25cb84cf590276af9ce4617039ba3849e328594c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "neelravi/octopus", "max_forks_repo_path": "src/math/oct_gsl_f.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "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": "neelravi/octopus", "max_issues_repo_path": "src/math/oct_gsl_f.c", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "neelravi/octopus", "max_stars_repo_path": "src/math/oct_gsl_f.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3568, "size": 11643 }
$NetBSD: patch-Src___dotblas.c,v 1.1 2015/01/27 05:05:30 dbj Exp $ --- Src/_dotblas.c.orig 2006-07-24 20:11:35.000000000 +0000 +++ Src/_dotblas.c @@ -12,7 +12,11 @@ static char module_doc[] = #include "Python.h" #include "libnumarray.h" #include "arrayobject.h" +#ifdef __APPLE__ +#include <Accelerate/Accelerate.h> +#else #include <cblas.h> +#endif #include <stdio.h>
{ "alphanum_fraction": 0.6833773087, "avg_line_length": 22.2941176471, "ext": "c", "hexsha": "5a8a7af10869cb8267673a3f01c994c90bd0bc44", "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": "51004b1e2b032664cce6b553d2052757c286087d", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "Scottx86-64/dotfiles-1", "max_forks_repo_path": "source/pkgsrc/math/py-numarray/patches/patch-Src___dotblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "51004b1e2b032664cce6b553d2052757c286087d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "Scottx86-64/dotfiles-1", "max_issues_repo_path": "source/pkgsrc/math/py-numarray/patches/patch-Src___dotblas.c", "max_line_length": 66, "max_stars_count": 1, "max_stars_repo_head_hexsha": "51004b1e2b032664cce6b553d2052757c286087d", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "Scottx86-64/dotfiles-1", "max_stars_repo_path": "source/pkgsrc/math/py-numarray/patches/patch-Src___dotblas.c", "max_stars_repo_stars_event_max_datetime": "2021-11-20T22:46:39.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-20T22:46:39.000Z", "num_tokens": 141, "size": 379 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_srot (const int N, float *X, const int incX, float *Y, const int incY, const float c, const float s) { #define BASE float #include "source_rot.h" #undef BASE }
{ "alphanum_fraction": 0.68359375, "avg_line_length": 19.6923076923, "ext": "c", "hexsha": "ee602d0f64c9b582c0bf482ef3cd7e8a01101c8e", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/cblas/srot.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/cblas/srot.c", "max_line_length": 76, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/cblas/srot.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 78, "size": 256 }
#ifndef LIC_METADATA_DEFINITION #define LIC_METADATA_DEFINITION #include <gsl/gsl> #include "format/ClrMetadataFormat.h" namespace lic { class Assembly; class Metadata { public: Metadata(Assembly& assembly, MetadataTable table, size_t rid, gsl::byte* row); ~Metadata(); protected: Assembly& assembly; MetadataTable table; size_t rid; gsl::byte* row; }; } #endif // !LIC_METADATA_DEFINITION
{ "alphanum_fraction": 0.7227488152, "avg_line_length": 14.5517241379, "ext": "h", "hexsha": "18839c216e253c73ba1f7ee3281fec6bade3fa17", "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": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_path": "src/loader/Metadata.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "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": "roberthusak/lic", "max_issues_repo_path": "src/loader/Metadata.h", "max_line_length": 82, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_path": "src/loader/Metadata.h", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "num_tokens": 98, "size": 422 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef dir_710838b0_50ee_47d4_bb24_95e5ded5be0b_h #define dir_710838b0_50ee_47d4_bb24_95e5ded5be0b_h #include <direct.h> #include <io.h> #include <gslib/type.h> #ifdef _UNICODE #define _gs_getcwd _wgetcwd #define _gs_chdir _wchdir #define _gs_mkdir _wmkdir #define _gs_rmdir _wrmdir #define _gs_finddata_t _wfinddata_t #define _gs_findfirst _wfindfirst #define _gs_findnext _wfindnext #define _gs_findclose _findclose #else #define _gs_getcwd _getcwd #define _gs_chdir _chdir #define _gs_mkdir _mkdir #define _gs_rmdir _rmdir #define _gs_finddata_t _finddata_t #define _gs_findfirst _findfirst #define _gs_findnext _findnext #define _gs_findclose _findclose #endif #endif
{ "alphanum_fraction": 0.7641700405, "avg_line_length": 32.9333333333, "ext": "h", "hexsha": "cb0bd7c34cbd1c96de5da2a3ef86c88e78ab132a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/gslib/dir.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/gslib/dir.h", "max_line_length": 82, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/gslib/dir.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 503, "size": 1976 }
#include "globals.h" #include "peano.h" #include <gsl/gsl_heapsort.h> peanoKey Peano_Key ( const double x, const double y, const double z ); static void reorder_particles(); void Print_Int_Bits128 ( const peanoKey val ) { for ( int i = 127; i >= 0; i-- ) { printf ( "%llu", ( long long ) ( ( val & ( ( peanoKey ) 1 << i ) ) >> i ) ); if ( i % 3 == 0 && i != 0 ) { printf ( "." ); } } printf ( "\n" ); fflush ( stdout ); return ; } void Print_Int_Bits128r ( const peanoKey val ) { for ( int i = 127; i >= 0; i-- ) { printf ( "%llu", ( long long ) ( ( val & ( ( peanoKey ) 1 << i ) ) >> i ) ); if ( i % 3 - 2 == 0 && i != 0 ) { printf ( "." ); } } printf ( "\n" ); fflush ( stdout ); return ; } int compare_peanoKeys ( const void *a, const void *b ) { const peanoKey *x = ( const peanoKey * ) a; const peanoKey *y = ( const peanoKey * ) b; return ( int ) ( *x > *y ) - ( *x < *y ); } static peanoKey *Keys = NULL; static size_t *Idx = NULL; void Sort_Particles_By_Peano_Key() { if ( Keys == NULL ) { Keys = malloc ( Param.Npart * sizeof ( *Keys ) ); } else { memset ( Keys, 0, Param.Npart * sizeof ( *Keys ) ); } if ( Idx == NULL ) { Idx = malloc ( Param.Npart * sizeof ( *Idx ) ); } else { memset ( Idx, 0, Param.Npart * sizeof ( *Idx ) ); } #pragma omp parallel for for ( int ipart = 0; ipart < Param.Npart; ipart++ ) { double px = P[ipart].Pos[0] / Problem.Boxsize[0]; double py = P[ipart].Pos[1] / Problem.Boxsize[1]; double pz = P[ipart].Pos[2] / Problem.Boxsize[2]; P[ipart].Key = Keys[ipart] = Peano_Key ( px, py, pz ); } gsl_heapsort_index ( Idx, Keys, Param.Npart, sizeof ( *Keys ), &compare_peanoKeys ); reorder_particles(); return ; } static void reorder_particles() { for ( int i = 0; i < Param.Npart; i++ ) { if ( Idx[i] == i ) { continue; } int dest = i; struct ParticleData Ptmp = P[i]; struct GasParticleData Sphtmp = SphP[i]; int src = Idx[i]; for ( ;; ) { P[dest] = P[src]; SphP[dest] = SphP[src]; Idx[dest] = dest; dest = src; src = Idx[dest]; if ( src == i ) { break; } } P[dest] = Ptmp; SphP[dest] = Sphtmp; Idx[dest] = dest; } // for i return ; } peanoKey Peano_Key ( const double x, const double y, const double z ) { Assert ( x >= 0 && x <= 1, "X coordinate of out range [0,1] have %g", x ); Assert ( y >= 0 && y <= 1, "Y coordinate of out range [0,1] have %g", y ); Assert ( z >= 0 && z <= 1, "Z coordinate of out range [0,1] have %g", z ); const uint64_t m = 1UL << 63; // = 2^63; uint64_t X[3] = { y * m, z * m, x * m }; /* Inverse undo */ for ( uint64_t q = m; q > 1; q >>= 1 ) { uint64_t P = q - 1; if ( X[0] & q ) { X[0] ^= P; // invert } for ( int i = 1; i < 3; i++ ) { if ( X[i] & q ) { X[0] ^= P; // invert } else { uint64_t t = ( X[0] ^ X[i] ) & P; X[0] ^= t; X[i] ^= t; } // exchange } } /* Gray encode (inverse of decode) */ for ( int i = 1; i < 3; i++ ) { X[i] ^= X[i - 1]; } uint64_t t = X[2]; for ( int i = 1; i < 64; i <<= 1 ) { X[2] ^= X[2] >> i; } t ^= X[2]; for ( int i = 1; i >= 0; i-- ) { X[i] ^= t; } /* branch free bit interleave of transpose array X into key */ peanoKey key = 0; X[1] >>= 1; X[2] >>= 2; // lowest bits not important for ( int i = 0; i < N_PEANO_TRIPLETS + 1; i++ ) { uint64_t col = ( ( X[0] & 0x8000000000000000 ) | ( X[1] & 0x4000000000000000 ) | ( X[2] & 0x2000000000000000 ) ) >> 61; key <<= 3; X[0] <<= 1; X[1] <<= 1; X[2] <<= 1; key |= col; } key <<= 2; return key; } /* This constructs the peano key with reversed triplet order. The order in the * triplets however is the same ! Also level zero is carried explicitely * to ease tree construction. */ peanoKey Reversed_Peano_Key ( const double x, const double y, const double z ) { Assert ( x >= 0 && x <= 1, "X coordinate of out range [0,1] have %g", x ); Assert ( y >= 0 && y <= 1, "Y coordinate of out range [0,1] have %g", y ); Assert ( z >= 0 && z <= 1, "Z coordinate of out range [0,1] have %g", z ); const uint64_t m = 1UL << 63; // = 2^63; uint64_t X[3] = { y * m, z * m, x * m }; /* Inverse undo */ for ( uint64_t q = m; q > 1; q >>= 1 ) { uint64_t P = q - 1; if ( X[0] & q ) { X[0] ^= P; // invert } for ( int i = 1; i < 3; i++ ) { if ( X[i] & q ) { X[0] ^= P; // invert } else { uint64_t t = ( X[0] ^ X[i] ) & P; X[0] ^= t; X[i] ^= t; } // exchange } } /* Gray encode (inverse of decode) */ for ( int i = 1; i < 3; i++ ) { X[i] ^= X[i - 1]; } uint64_t t = X[2]; for ( int i = 1; i < 64; i <<= 1 ) { X[2] ^= X[2] >> i; } t ^= X[2]; for ( int i = 1; i >= 0; i-- ) { X[i] ^= t; } /* branch free reversed (!) bit interleave of transpose array X into key */ peanoKey key = 0; X[0] >>= 18; X[1] >>= 19; X[2] >>= 20; // lowest bits not important for ( int i = 0; i < N_PEANO_TRIPLETS + 1; i++ ) { uint64_t col = ( ( X[0] & 0x4 ) | ( X[1] & 0x2 ) | ( X[2] & 0x1 ) ); key <<= 3; key |= col; X[0] >>= 1; X[1] >>= 1; X[2] >>= 1; } key <<= 3; // include level 0 return key; } void test_peanokey() { const double box[3] = { 1.0, 1, 1}; double a[3] = { 0 }; int order = 1; float delta = 1 / pow ( 2.0, order ); int n = roundf ( 1 / delta ); for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) { for ( int k = 0; k < n; k++ ) { a[0] = ( i + 0.5 ) * delta / box[0]; a[1] = ( j + 0.5 ) * delta / box[1]; a[2] = ( k + 0.5 ) * delta / box[2]; peanoKey stdkey = Peano_Key ( a[0], a[1], a[2] ); printf ( "%g %g %g %llu \n", a[0], a[1], a[2], ( long long ) stdkey ); Print_Int_Bits128 ( stdkey ); printf ( "\n" ); } } } return ; }
{ "alphanum_fraction": 0.4178623719, "avg_line_length": 21.2111801242, "ext": "c", "hexsha": "2463081d7f6bac1f7545614ef9f9981564a67106", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:31:56.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-29T09:38:57.000Z", "max_forks_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elehcim/WVTICs", "max_forks_repo_path": "src/peano.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_issues_repo_issues_event_max_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "elehcim/WVTICs", "max_issues_repo_path": "src/peano.c", "max_line_length": 88, "max_stars_count": 5, "max_stars_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elehcim/WVTICs", "max_stars_repo_path": "src/peano.c", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-29T04:44:13.000Z", "num_tokens": 2319, "size": 6830 }
/* diff/diff.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 David Morrison * * 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_diff.h> int gsl_diff_backward (const gsl_function * f, double x, double *result, double *abserr) { /* Construct a divided difference table with a fairly large step size to get a very rough estimate of f''. Use this to estimate the step size which will minimize the error in calculating f'. */ int i, k; double h = GSL_SQRT_DBL_EPSILON; double a[3], d[3], a2; /* Algorithm based on description on pg. 204 of Conte and de Boor (CdB) - coefficients of Newton form of polynomial of degree 2. */ for (i = 0; i < 3; i++) { a[i] = x + (i - 2.0) * h; d[i] = GSL_FN_EVAL (f, a[i]); } for (k = 1; k < 4; k++) { for (i = 0; i < 3 - k; i++) { d[i] = (d[i + 1] - d[i]) / (a[i + k] - a[i]); } } /* Adapt procedure described on pg. 282 of CdB to find best value of step size. */ a2 = fabs (d[0] + d[1] + d[2]); if (a2 < 100.0 * GSL_SQRT_DBL_EPSILON) { a2 = 100.0 * GSL_SQRT_DBL_EPSILON; } h = sqrt (GSL_SQRT_DBL_EPSILON / (2.0 * a2)); if (h > 100.0 * GSL_SQRT_DBL_EPSILON) { h = 100.0 * GSL_SQRT_DBL_EPSILON; } *result = (GSL_FN_EVAL (f, x) - GSL_FN_EVAL (f, x - h)) / h; *abserr = fabs (10.0 * a2 * h); return GSL_SUCCESS; } int gsl_diff_forward (const gsl_function * f, double x, double *result, double *abserr) { /* Construct a divided difference table with a fairly large step size to get a very rough estimate of f''. Use this to estimate the step size which will minimize the error in calculating f'. */ int i, k; double h = GSL_SQRT_DBL_EPSILON; double a[3], d[3], a2; /* Algorithm based on description on pg. 204 of Conte and de Boor (CdB) - coefficients of Newton form of polynomial of degree 2. */ for (i = 0; i < 3; i++) { a[i] = x + i * h; d[i] = GSL_FN_EVAL (f, a[i]); } for (k = 1; k < 4; k++) { for (i = 0; i < 3 - k; i++) { d[i] = (d[i + 1] - d[i]) / (a[i + k] - a[i]); } } /* Adapt procedure described on pg. 282 of CdB to find best value of step size. */ a2 = fabs (d[0] + d[1] + d[2]); if (a2 < 100.0 * GSL_SQRT_DBL_EPSILON) { a2 = 100.0 * GSL_SQRT_DBL_EPSILON; } h = sqrt (GSL_SQRT_DBL_EPSILON / (2.0 * a2)); if (h > 100.0 * GSL_SQRT_DBL_EPSILON) { h = 100.0 * GSL_SQRT_DBL_EPSILON; } *result = (GSL_FN_EVAL (f, x + h) - GSL_FN_EVAL (f, x)) / h; *abserr = fabs (10.0 * a2 * h); return GSL_SUCCESS; } int gsl_diff_central (const gsl_function * f, double x, double *result, double *abserr) { /* Construct a divided difference table with a fairly large step size to get a very rough estimate of f'''. Use this to estimate the step size which will minimize the error in calculating f'. */ int i, k; double h = GSL_SQRT_DBL_EPSILON; double a[4], d[4], a3; /* Algorithm based on description on pg. 204 of Conte and de Boor (CdB) - coefficients of Newton form of polynomial of degree 3. */ for (i = 0; i < 4; i++) { a[i] = x + (i - 2.0) * h; d[i] = GSL_FN_EVAL (f, a[i]); } for (k = 1; k < 5; k++) { for (i = 0; i < 4 - k; i++) { d[i] = (d[i + 1] - d[i]) / (a[i + k] - a[i]); } } /* Adapt procedure described on pg. 282 of CdB to find best value of step size. */ a3 = fabs (d[0] + d[1] + d[2] + d[3]); if (a3 < 100.0 * GSL_SQRT_DBL_EPSILON) { a3 = 100.0 * GSL_SQRT_DBL_EPSILON; } h = pow (GSL_SQRT_DBL_EPSILON / (2.0 * a3), 1.0 / 3.0); if (h > 100.0 * GSL_SQRT_DBL_EPSILON) { h = 100.0 * GSL_SQRT_DBL_EPSILON; } *result = (GSL_FN_EVAL (f, x + h) - GSL_FN_EVAL (f, x - h)) / (2.0 * h); *abserr = fabs (100.0 * a3 * h * h); return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5805031447, "avg_line_length": 26.3535911602, "ext": "c", "hexsha": "83aae18b7fb8b822fa824fc1713e2f4f8d58472d", "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/diff/diff.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/diff/diff.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/diff/diff.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": 1626, "size": 4770 }
#if !defined(lowMachFlow_h) #define lowMachFlow_h #include <petsc.h> // Define the test field number typedef enum { VTEST, QTEST, WTEST } LowMachFlowTestFields; typedef enum { STROUHAL, REYNOLDS, FROUDE, PECLET, HEATRELEASE, GAMMA, PTH, MU, K, CP, BETA, GRAVITY_DIRECTION, TOTAL_LOW_MACH_FLOW_PARAMETERS } LowMachFlowParametersTypes; PETSC_EXTERN const char* lowMachFlowParametersTypeNames[TOTAL_LOW_MACH_FLOW_PARAMETERS + 1]; typedef enum {VEL, PRES, TEMP, TOTAL_LOW_MACH_FLOW_FIELDS} LowMachFlowFields; typedef enum {MOM, MASS, ENERGY, TOTAL_LOW_MACH_SOURCE_FIELDS} LowMachSourceFields; // Low Mach Kernels PETSC_EXTERN void LowMachFlow_vIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]); PETSC_EXTERN void LowMachFlow_vIntegrandTestGradientFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[]); PETSC_EXTERN void LowMachFlow_wIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]); PETSC_EXTERN void LowMachFlow_wIntegrandTestGradientFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[]); PETSC_EXTERN void LowMachFlow_qIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]); PETSC_EXTERN void LowMachFlow_g0_qu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g1_qu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g0_qT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g0_qT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g1_qT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g0_vT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g0_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g1_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g3_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g2_vp(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g0_wu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g0_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g1_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); PETSC_EXTERN void LowMachFlow_g3_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]); #endif
{ "alphanum_fraction": 0.6750708215, "avg_line_length": 108.0612244898, "ext": "h", "hexsha": "82776e26ec4650a68f5139d04032569d8d42eb7c", "lang": "C", "max_forks_count": 17, "max_forks_repo_forks_event_max_datetime": "2022-03-21T18:46:06.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-10T22:34:57.000Z", "max_forks_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mtmcgurn-buffalo/ablate", "max_forks_repo_path": "ablateCore/flow/lowMachFlow.h", "max_issues_count": 124, "max_issues_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:44:31.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-14T15:30:48.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "mtmcgurn-buffalo/ablate", "max_issues_repo_path": "ablateCore/flow/lowMachFlow.h", "max_line_length": 216, "max_stars_count": 3, "max_stars_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mtmcgurn-buffalo/ablate", "max_stars_repo_path": "ablateCore/flow/lowMachFlow.h", "max_stars_repo_stars_event_max_datetime": "2021-08-20T19:54:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-19T21:29:10.000Z", "num_tokens": 2480, "size": 10590 }
/* * Test the effective difference of a single bit changing on the input. * Evaluate each bit position on the first hash against all the bit * positions on the other hash for any less than random distribution. * * This tests for the "Bit Independence Criterion" of this hash. */ #include "hash_bbt.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <stdint.h> #include <stdio.h> #include <string.h> #define HASH_PARAMS bbt_table_1 extern struct bbt_hash_patterns HASH_PARAMS; #define HASH_INPUT_SZ 32 //#define SAMPLE_SZ 1048576 //#define SAMPLE_SZ 100 #define SAMPLE_SZ 65536 #define HASH_BITS_COUNT (8*sizeof(bbt_hash_t)) #define COUNT_MATRIX_SZ (HASH_BITS_COUNT * HASH_BITS_COUNT) #define BIT_ROTATE(HASH,SHIFT) ((bbt_hash_t)((HASH)<<(SHIFT)) | (bbt_hash_t)((HASH)>>(BBT_HASH_WIDTH - (SHIFT)))) int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %d\n", argc); printf("Usage: %s <bit position> <numeric random seed>\n", argv[0]); return 1; } unsigned argPos = 1; unsigned long int bitPos = strtoul(argv[argPos++], NULL, 10); if (bitPos > ((8*HASH_INPUT_SZ)-1)) { fprintf(stderr, "ERROR: bitPos too large. Beyond end of buffer length.\n"); return 1; } unsigned long int seed = strtoul(argv[argPos++], NULL, 10); unsigned char hashInput[HASH_INPUT_SZ]; gsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937); /* Mersenne Twister */ gsl_rng_set(rng, seed); bbt_hash_ctxt hc; bbt_hash_init(&hc, &(HASH_PARAMS)); unsigned bitIndex = bitPos/8; unsigned bitShift = 7 - (bitPos%8); bbt_hash_t bitMask = ((bbt_hash_t)1) << bitShift; bbt_hash_t bitMatrix[HASH_BITS_COUNT]; unsigned countMatrix[COUNT_MATRIX_SZ]; memset(countMatrix, 0, COUNT_MATRIX_SZ * sizeof(unsigned)); for (unsigned sampleCount = 0; sampleCount < SAMPLE_SZ; sampleCount++) { unsigned char *p = hashInput; for (unsigned i = 0; i < HASH_INPUT_SZ; i++) { *p = gsl_rng_get(rng) & 0xFF; p++; } bbt_hash_calc(&hc, hashInput, HASH_INPUT_SZ); bbt_hash_t hashA = bbt_hash_getHash(&hc); bbt_hash_reset(&hc); hashInput[bitIndex] = hashInput[bitIndex] ^ bitMask; bbt_hash_calc(&hc, hashInput, HASH_INPUT_SZ); bbt_hash_t hashB = bbt_hash_getHash(&hc); bbt_hash_reset(&hc); for (unsigned i = 0; i < HASH_BITS_COUNT; i++) { bitMatrix[i] = hashB ^ BIT_ROTATE(hashA, i); } for (unsigned i = 0; i < HASH_BITS_COUNT; i++) { bbt_hash_t hashC = bitMatrix[i]; for (unsigned j = 0; j < HASH_BITS_COUNT; j++) { if ((hashC & 1) != 0) { countMatrix[j * HASH_BITS_COUNT + i] ++; } hashC = hashC >> 1; } } } printf("cat(\"Bit change at index %u and shift %u.\\n\")\n", bitIndex, bitShift); printf("sampleSize <- %u\n", SAMPLE_SZ); printf("cat(\"Sample size is %u.\\n\")\n", SAMPLE_SZ); printf("cat(\"Half of sample size is %u.\\n\")\n", SAMPLE_SZ/2); printf("data <- c(\n"); for (unsigned i = 0; i < HASH_BITS_COUNT; i++) { for (unsigned j = 0; j < HASH_BITS_COUNT; j++) { printf("%u, ", countMatrix[j * HASH_BITS_COUNT + i]); } printf("\n"); } printf("0)\n"); printf("dataMatrix <- matrix(data[1:%lu], ncol=%lu, byrow=T)\n", COUNT_MATRIX_SZ, HASH_BITS_COUNT); printf("cat(\"Summary of the distribution of counts:\\n\")\n"); printf("print(summary(as.vector(dataMatrix)))\n"); printf("p <- dataMatrix / sampleSize\n"); printf("q <- 1-p\n"); printf("h <- -p*log(p, base=2) -q*log(q, base=2)\n"); printf("cat(\"Summary of the distribution of H (entropy):\\n\")\n"); printf("print(summary(as.vector(h)))\n"); gsl_rng_free(rng); return 0; }
{ "alphanum_fraction": 0.6710005653, "avg_line_length": 29.9830508475, "ext": "c", "hexsha": "0b26fe9af910ac1f9ebf6301129297e7969c95f2", "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": "dc103a67d0826f09b07196217f00a454441d5011", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonkanderson/BitBalancedTableHash", "max_forks_repo_path": "tests/entropy_tests/test8_bitCascade.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "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": "jonkanderson/BitBalancedTableHash", "max_issues_repo_path": "tests/entropy_tests/test8_bitCascade.c", "max_line_length": 113, "max_stars_count": null, "max_stars_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonkanderson/BitBalancedTableHash", "max_stars_repo_path": "tests/entropy_tests/test8_bitCascade.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1078, "size": 3538 }
/* Copyright [2017-2020] [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 __BUFFER_MGR_H__ #define __BUFFER_MGR_H__ #ifdef __cplusplus #include <common/chksum.h> #include <common/delete_copy.h> #include <common/logging.h> #include <common/moveable_ptr.h> #include <common/utils.h> /* MiB, UNLIKELY */ #include <api/components.h> #include <api/fabric_itf.h> #include <api/kvstore_itf.h> #include <api/registrar_memory_direct.h> /* Opaque_memory_region */ #include <sys/mman.h> #include "mcas_config.h" #include "memory_registered.h" #include <gsl/pointers> /* not_null */ #include <cassert> #include <cstring> /* memset */ #include <memory> /* unique_ptr */ namespace { inline auto alloc_base(std::size_t len) -> gsl::not_null<void *> { auto b = ::aligned_alloc(MiB(2), len); if (b == nullptr) { throw std::bad_alloc(); } ::memset(b, 0, len); return gsl::not_null<void *>(b); } } namespace mcas { template <class Memory> class Buffer_manager : private common::log_source { static constexpr const char *_cname = "Buffer_manager"; public: static constexpr size_t DEFAULT_BUFFER_COUNT = NUM_SHARD_BUFFERS; static constexpr size_t BUFFER_LEN = MiB(2); /* corresponds to huge page see below */ using memory_registered_t = memory_registered<Memory>; using memory_region_t = typename Memory::memory_region_t; struct iov_mem_lock { private: common::moveable_ptr<::iovec> _iov; public: iov_mem_lock(::iovec *iov_) : _iov(iov_) { ::madvise(_iov->iov_base, _iov->iov_len, MADV_HUGEPAGE); ::mlock(_iov->iov_base, _iov->iov_len); } iov_mem_lock(iov_mem_lock &&) noexcept = default; ~iov_mem_lock() { if ( _iov ) { ::munlock(_iov->iov_base, _iov->iov_len); } } }; /* Although client tried to hide it with a reinterpret_cast, buffer_base is used as a component::memory_region_t */ struct buffer_base : public component::Registrar_memory_direct::Opaque_memory_region, private common::log_source { private: static constexpr const char *_cname = "buffer_base"; void *_base; std::size_t _original_length; memory_registered_t _region; const unsigned magic; public: buffer_base(unsigned debug_level_, Memory * transport_, void * base_, size_t length_ ) : common::log_source(debug_level_) , _base(base_) , _original_length(length_) , _region(memory_registered_t(debug_level_, transport_, base_, length_, 0, 0)) , magic(0xC0FFEE) { if ( length_ <= 1 ) { throw std::domain_error("buffer length too small"); } CPLOG(3, "%s::%s %p transport %p region %p", _cname, __func__, common::p_fmt(this), common::p_fmt(transport()), common::p_fmt(region())); } void *get_desc() const { return _region.desc(); } DELETE_COPY(buffer_base); protected: ~buffer_base() { CPLOG(3, "%s::%s %p transport %p region %p", _cname, __func__, common::p_fmt(this), common::p_fmt(transport()), common::p_fmt(region())); } public: size_t original_length() const { return _original_length; } inline gsl::not_null<void *> base() const { return _base; } auto region() const { return _region.mr(); } Memory * transport() const { return _region.transport(); } #if 0 /* unused */ inline bool check_magic() const { return magic == 0xC0FFEE; } unsigned int crc32() const { return common::chksum32(_base, _length); } #endif }; struct free_deleter { void operator()(void *v_) { ::free(v_); } }; struct buffer_internal : private std::unique_ptr<void, free_deleter> , public buffer_base { ::iovec iov[2]; void *desc[2]; iov_mem_lock _ml; using completion_t = void (*)(void *, buffer_internal *); completion_t completion_cb; void * value_adjunct; inline void set_completion(completion_t completion_) { completion_cb = completion_; } void set_completion(completion_t completion_, void *value_adjunct_) { completion_cb = completion_; value_adjunct = value_adjunct_; } buffer_internal(unsigned debug_level_, Memory * transport_, size_t length_ ) : std::unique_ptr<void, free_deleter>(alloc_base(length_)) , buffer_base(debug_level_, transport_, std::unique_ptr<void, free_deleter>::get(), length_) , iov{{this->base(), this->original_length()}, {nullptr, 0}} , desc{this->get_desc(), nullptr} , _ml(&this->iov[0]) , completion_cb(nullptr) , value_adjunct(nullptr) { } DELETE_COPY(buffer_internal); void set_length(size_t s) { iov->iov_len = s; } inline void reset_length() { assert(this->original_length() > 1); this->iov[0].iov_len = this->original_length(); value_adjunct = nullptr; completion_cb = nullptr; } size_t length() const { return iov[0].iov_len; } unsigned int crc32() const { return common::chksum32(iov->iov_base, iov->iov_len); } }; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" // missing initializers Buffer_manager(unsigned debug_level_, Memory *transport, size_t buffer_count = DEFAULT_BUFFER_COUNT) : common::log_source(debug_level_), _buffer_count(buffer_count), _transport(transport) { for (unsigned i = 0; i < _buffer_count; i++) { const auto len = BUFFER_LEN; _buffers.emplace_back(std::make_unique<buffer_internal>(debug_level_, _transport, len)); _free.push_back(_buffers.back().get()); } PLOG("%s %p allocated %lu buffers", __func__, common::p_fmt(this), buffer_count); } #pragma GCC diagnostic pop Buffer_manager(Buffer_manager &&) noexcept = default; ~Buffer_manager() { } using completion_t = void (*)(void *, buffer_internal *); gsl::not_null<buffer_internal *> allocate(completion_t completion_) { if (UNLIKELY(_free.empty())) throw Program_exception("Buffer_manager: no shard buffers remaining"); gsl::not_null<buffer_internal *> iob = _free.back(); _free.pop_back(); CPLOG(3, "%s::%s %p (%lu free)", _cname, __func__, common::p_fmt(iob), _free.size()); iob->reset_length(); iob->set_completion(completion_); return iob; } void free(gsl::not_null<buffer_internal *> iob) { CPLOG(3, "%s::%s %p (%lu free)", _cname, __func__, common::p_fmt(iob), _free.size()); iob->reset_length(); iob->set_completion(nullptr); _free.push_back(iob); } private: // static constexpr size_t buffer_len() { return BUFFER_LEN; } using pool_t = component::IKVStore::pool_t; using key_t = std::uint64_t; const size_t _buffer_count; gsl::not_null<Memory *> _transport; std::vector<std::unique_ptr<buffer_internal>> _buffers; std::vector<buffer_internal *> _free; }; } // namespace mcas #endif #endif
{ "alphanum_fraction": 0.6546819439, "avg_line_length": 30.130952381, "ext": "h", "hexsha": "cf94880931fc77d04a460d834a36c9f10b2c1e48", "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": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "fQuinzan/mcas", "max_forks_repo_path": "src/server/mcas/src/buffer_manager.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "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": "fQuinzan/mcas", "max_issues_repo_path": "src/server/mcas/src/buffer_manager.h", "max_line_length": 114, "max_stars_count": 60, "max_stars_repo_head_hexsha": "efaf438eb20cffa18b13f176c74a2b3153f89c07", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "fQuinzan/mcas", "max_stars_repo_path": "src/server/mcas/src/buffer_manager.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": 1916, "size": 7593 }
/*****************************************************************\ __ / / / / __ __ / /______ _______ / / / / ________ __ __ / ______ \ /_____ \ / / / / / _____ | / / / / / / | / _______| / / / / / / /____/ / / / / / / / / / / _____ / / / / / / _______/ / / / / / / / / / /____/ / / / / / / |______ / |______/ / /_/ /_/ |________/ / / / / \_______/ \_______ / /_/ /_/ / / / / 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 <random> #include <halley/utils/utils.h> #include <gsl/span> namespace Halley { typedef std::mt19937 RandomGenType; class Random { public: static Random& getGlobal(); Random(); Random(long seed); Random(char* bytes, size_t nBytes); template <typename T> T get(T max) { return get(T(0), max); } template <typename T> T get(T min, T max); template <typename T> T getInt(T min, T max) { if (min > max) { std::swap(min, max); } std::uniform_int_distribution<T> dist(min, max); return dist(generator); } template <typename T> T getFloat(T min, T max) { if (min > max) std::swap(min, max); std::uniform_real_distribution<T> dist(min, max); return dist(generator); } void getBytes(gsl::span<gsl::byte> dst); void setSeed(long seed); void setSeed(char* bytes, size_t nBytes); private: RandomGenType generator; }; template <typename T> struct _getHack { static T get(Random* rng, T min, T max) { return rng->getInt(min, max); } }; template <> struct _getHack<float> { static float get(Random *rng, float min, float max) { return rng->getFloat(min, max); } }; template <> struct _getHack<double> { static double get(Random *rng, double min, double max) { return rng->getFloat(min, max); } }; template <typename T> T Random::get(T min, T max) { return _getHack<T>::get(this, min, max); } }
{ "alphanum_fraction": 0.4954088325, "avg_line_length": 25.1318681319, "ext": "h", "hexsha": "25d49ea8dcb5c758dc997d9a306da14555e5057c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Healthire/halley", "max_forks_repo_path": "src/engine/utils/include/halley/maths/random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Healthire/halley", "max_issues_repo_path": "src/engine/utils/include/halley/maths/random.h", "max_line_length": 92, "max_stars_count": null, "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Healthire/halley", "max_stars_repo_path": "src/engine/utils/include/halley/maths/random.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 615, "size": 2287 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <gsl_p/span.h> namespace phosphor { /** * Pure virtual base class for receiving stats from phosphor internals * * Methods on this class will be called with the key and value of each stat. * Callback implementations MUST NOT re-enter the TraceLog or TraceBuffer * upon which it used as locks may be held when the callback is invoked. * * Example usage: * * class MyStatsCallback : public phosphor::StatsCallback { * // Implement callback methods * } callback; * * phosphor::TraceLog::getInstance().getStats(callback); * * // Stash data as required for application * auto data = callback.getData(); * * Implementations should note that phosphor makes no guarantees about * atomicity of the stats with respect to each other. */ class StatsCallback { public: /** * Utility template method for passing a string literal as the first * argument instead of a string span * @param s String to convert to a span * @param value Value to forward */ template <size_t N, typename T> void operator()(const char (&s)[N], T&& value) { this->operator()(gsl_p::make_span(s), std::forward<T>(value)); } virtual void operator()(gsl_p::cstring_span key, gsl_p::cstring_span value) = 0; virtual void operator()(gsl_p::cstring_span key, bool value) = 0; virtual void operator()(gsl_p::cstring_span key, size_t value) = 0; virtual void operator()(gsl_p::cstring_span key, ssize_t value) = 0; virtual void operator()(gsl_p::cstring_span key, double value) = 0; }; }
{ "alphanum_fraction": 0.6789109767, "avg_line_length": 34.5373134328, "ext": "h", "hexsha": "69da67a324677985d7d9725d9a69bdd3daa53947", "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": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Chippiewill/Phosphor", "max_forks_repo_path": "include/phosphor/stats_callback.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "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": "Chippiewill/Phosphor", "max_issues_repo_path": "include/phosphor/stats_callback.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Chippiewill/Phosphor", "max_stars_repo_path": "include/phosphor/stats_callback.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 549, "size": 2314 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <mpi.h> #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include "StgFEM/Discretisation/src/types.h" #include "ElementType.h" #include "ElementType_Register.h" #include "Element.h" #include "FeMesh.h" #include "FeEquationNumber.h" #include "FeVariable.h" #include "LinkedDofInfo.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <mpi.h> #include <petsc.h> #include <petscvec.h> // Private prototype int GenerateEquationNumbering( int NX, int NY, int NZ, int nlocal, int g_node_id[], int dof, int nglobal, PetscTruth periodic_x, PetscTruth periodic_y, PetscTruth periodic_z, int npx, int npy, int npz, int periodic_x_gnode_id[], int periodic_y_gnode_id[], int periodic_z_gnode_id[], int eqnums[], int *neqnums ); int stgCmpInt( const void *l, const void *r ) { return *(int*)l - *(int*)r; } /*###### Typedefs and Structs ######*/ /** Textual name of this class */ const Type FeEquationNumber_Type = "FeEquationNumber"; /** struct to store sub-totals: what is the equation number up to at a given node? These can then be exchanged between processors */ typedef struct CritPointInfo { Node_GlobalIndex index; Dof_EquationNumber eqNum; } CritPointInfo; /** An element of linked list of critical point info. Several of the functions use this to keep track of key points */ typedef struct AddListEntry { CritPointInfo* critPointInfo; struct AddListEntry* next; } AddListEntry; /** Enum to say whetehr values at crit. nodes should be printed */ typedef enum PrintValuesFlag { DONT_PRINT_VALUES, PRINT_VALUES } PrintValuesFlag; /** MPI datatype handle for efficiently exchanging CritPointInfo structures. see FeEquationNumber_Create_CritPointInfo_MPI_Datatype() for where this handle is defined. */ MPI_Datatype MPI_critPointInfoType; /*###### Private Function Declarations ######*/ /*###### Function Definitions ######*/ /** Public constructor */ FeEquationNumber* FeEquationNumber_New( Name name, DomainContext* context, void* mesh, DofLayout* dofLayout, VariableCondition* bcs, LinkedDofInfo* linkedDofInfo ) { FeEquationNumber* self = FeEquationNumber_DefaultNew( name ); self->isConstructed = True; _FeEquationNumber_Init( self, context, mesh, dofLayout, bcs, linkedDofInfo ); return self; } void* FeEquationNumber_DefaultNew( Name name ) { /* Variables set in this function */ SizeT _sizeOfSelf = sizeof(FeEquationNumber); Type type = FeEquationNumber_Type; Stg_Class_DeleteFunction* _delete = _FeEquationNumber_Delete; Stg_Class_PrintFunction* _print = _FeEquationNumber_Print; Stg_Class_CopyFunction* _copy = _FeEquationNumber_Copy; Stg_Component_DefaultConstructorFunction* _defaultConstructor = (Stg_Component_DefaultConstructorFunction*)FeEquationNumber_DefaultNew; Stg_Component_ConstructFunction* _construct = _FeEquationNumber_AssignFromXML; Stg_Component_BuildFunction* _build = _FeEquationNumber_Build; Stg_Component_InitialiseFunction* _initialise = _FeEquationNumber_Initialise; Stg_Component_ExecuteFunction* _execute = _FeEquationNumber_Execute; Stg_Component_DestroyFunction* _destroy = _FeEquationNumber_Destroy; AllocationType nameAllocationType = NON_GLOBAL; return _FeEquationNumber_New( FEEQUATIONNUMBER_PASSARGS ); } /** Constructor implementation. */ FeEquationNumber* _FeEquationNumber_New( FEEQUATIONNUMBER_DEFARGS ){ FeEquationNumber* self; /* Allocate memory */ assert( _sizeOfSelf >= sizeof(FeEquationNumber) ); self = (FeEquationNumber*)_Stg_Component_New( STG_COMPONENT_PASSARGS ); /* General info */ /* Virtual info */ self->_build = _build; self->_initialise = _initialise; /* Mesh info */ return self; } /** Constructor variables initialisation. Doesn't allocate any memory, just saves arguments and sets counters to 0. */ void _FeEquationNumber_Init( FeEquationNumber* self, DomainContext* context, void* feMesh, DofLayout* dofLayout, VariableCondition* bcs, LinkedDofInfo* linkedDofInfo ) { /* General and Virtual info should already be set */ /* FinteElementMesh info */ self->context = context; self->feMesh = (FeMesh*)feMesh; self->globalSumUnconstrainedDofs = 0; self->isBuilt = False; self->locationMatrixBuilt = False; self->_lowestLocalEqNum = -1; self->_lowestGlobalEqNums = NULL; self->_highestLocalEqNum = -1; self->dofLayout = dofLayout; self->bcs = bcs; self->linkedDofInfo = linkedDofInfo; self->remappingActivated = False; /* register streams */ self->debug = Stream_RegisterChild( StgFEM_Discretisation_Debug, FeEquationNumber_Type ); self->debugLM = Stream_RegisterChild( self->debug, "LM" ); self->warning = Stream_RegisterChild( StgFEM_Warning, FeEquationNumber_Type ); self->removeBCs = True; self->bcEqNums = STree_New(); STree_SetIntCallbacks( self->bcEqNums ); STree_SetItemSize( self->bcEqNums, sizeof(int) ); self->ownedMap = STreeMap_New(); STreeMap_SetItemSize( self->ownedMap, sizeof(int), sizeof(int) ); STree_SetIntCallbacks( self->ownedMap ); Stream_SetPrintingRank( self->debug, 0 ); } void _FeEquationNumber_AssignFromXML( void* feEquationNumber, Stg_ComponentFactory *cf, void* data ) { } void _FeEquationNumber_Execute( void* feEquationNumber, void *data ){ } void _FeEquationNumber_Destroy( void* feEquationNumber, void *data ){ FeEquationNumber* self = (FeEquationNumber*) feEquationNumber; Index ii; /* free destination array memory */ Journal_DPrintfL( self->debug, 2, "Freeing I.D. Array\n" ); FreeArray( self->mapNodeDof2Eq ); if (self->locationMatrix) { Journal_DPrintfL( self->debug, 2, "Freeing Full L.M. Array\n" ); for( ii = 0; ii < self->nDomainEls; ii++ ) FreeArray( self->locationMatrix[ii] ); FreeArray( self->locationMatrix ); } if( self->bcEqNums ) Stg_Class_Delete( self->bcEqNums ); if( self->ownedMap ) Stg_Class_Delete( self->ownedMap ); } /* Copy */ /** Stg_Class_Delete implementation. */ void _FeEquationNumber_Delete( void* feEquationNumber ) { FeEquationNumber* self = (FeEquationNumber*) feEquationNumber; // This calls the Destroy() function _Stg_Component_Delete( self ); } /** Print implementation */ void _FeEquationNumber_Print( void* mesh, Stream* stream ) { FeEquationNumber* self = (FeEquationNumber*)mesh; /* General info */ Journal_Printf( stream, "FeEquationNumber (ptr): %p\n", self ); /* Print parent */ _Stg_Class_Print( self, stream ); /* Virtual info */ Journal_Printf( stream, "\t_build (func ptr): %p\n", self->_build ); Journal_Printf( stream, "\t_intialise (func ptr): %p\n", self->_initialise ); /* FeEquationNumber info */ /* Don't print dofs or bcs as these will be printed by FeVariable */ if ( self->mapNodeDof2Eq ) { FeEquationNumber_PrintmapNodeDof2Eq( self, stream ); FeEquationNumber_PrintLocationMatrix( self, stream ); } else { Journal_Printf( stream, "\tmapNodeDof2Eq: (null)... not built yet\n" ); Journal_Printf( stream, "\tlocationMatrix: (null)... not built yet\n" ); } } void* _FeEquationNumber_Copy( void* feEquationNumber, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap ) { abort(); } void _FeEquationNumber_Build( void* feEquationNumber, void* data ) { FeEquationNumber* self = (FeEquationNumber*) feEquationNumber; assert(self); Journal_DPrintf( self->debug, "In %s:\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); Stg_Component_Build( self->feMesh , data, False ); Stg_Component_Build( self->dofLayout, data, False ); if ( self->linkedDofInfo ) Stg_Component_Build( self->dofLayout, data, False ); if ( self->bcs ) Stg_Component_Build( self->bcs , data, False ); /* If we have new mesh topology information, do this differently. */ /* if( self->feMesh->topo->domains && self->feMesh->topo->domains[MT_VERTEX] ) { */ if( Mesh_HasExtension( self->feMesh, "vertexGrid" ) ) FeEquationNumber_BuildWithDave( self ); else FeEquationNumber_BuildWithTopology( self ); /* If not removing BCs, construct a table of which equation numbers are actually BCs. */ if( !self->removeBCs ) { FeMesh* mesh = self->feMesh; DofLayout* dofLayout = self->dofLayout; VariableCondition* bcs = self->bcs; int nDofs, varInd; int ii, jj; for( ii = 0; ii < FeMesh_GetNodeLocalSize( mesh ); ii++ ) { nDofs = dofLayout->dofCounts[ii]; for( jj = 0; jj < nDofs; jj++ ) { varInd = dofLayout->varIndices[ii][jj]; if( bcs && VariableCondition_IsCondition( bcs, ii, varInd ) ) { if( !STree_Has( self->bcEqNums, self->mapNodeDof2Eq[ii] + jj ) ) STree_Insert( self->bcEqNums, self->mapNodeDof2Eq[ii] + jj ); } } } } if ( Stream_IsPrintableLevel( self->debug, 3 ) ) { FeEquationNumber_PrintmapNodeDof2Eq( self, self->debug ); } Stream_UnIndentBranch( StgFEM_Debug ); } /** Initialise implementation. Currently does nothing. */ void _FeEquationNumber_Initialise( void* feEquationNumber, void* data ) { FeEquationNumber* self = (FeEquationNumber*) feEquationNumber; Stg_Component_Initialise( self->feMesh , data, False ); Stg_Component_Initialise( self->dofLayout, data, False ); if ( self->linkedDofInfo ) Stg_Component_Initialise( self->dofLayout, data, False ); if ( self->bcs ) Stg_Component_Initialise( self->bcs , data, False ); } Index FeEquationNumber_CalculateActiveEqCountAtNode( void* feEquationNumber, Node_DomainIndex dNode_I, Dof_EquationNumber* lowestActiveEqNumAtNodePtr ) { FeEquationNumber* self = (FeEquationNumber*) feEquationNumber; Dof_Index nodalDof_I = 0; Index activeEqsAtCurrRowNode = 0; Dof_EquationNumber currEqNum; Bool foundLowest = False; for ( nodalDof_I = 0; nodalDof_I < self->dofLayout->dofCounts[dNode_I]; nodalDof_I++ ) { currEqNum = self->mapNodeDof2Eq[dNode_I][nodalDof_I]; if ( currEqNum != -1 ) { activeEqsAtCurrRowNode++; if ( False == foundLowest ) { (*lowestActiveEqNumAtNodePtr) = currEqNum; foundLowest = True; } } } return activeEqsAtCurrRowNode; } void FeEquationNumber_BuildLocationMatrix( void* feEquationNumber ) { FeEquationNumber* self = (FeEquationNumber*)feEquationNumber; FeMesh* feMesh; unsigned nDomainEls; unsigned* nNodalDofs; unsigned nElNodes; int* elNodes; int** dstArray; int*** locMat; IArray* inc; unsigned e_i, n_i, dof_i; assert( self ); /* Don't build if already done. */ if( self->locationMatrixBuilt ) { Journal_DPrintf( self->debugLM, "In %s: LM already built, so just returning.\n", __func__ ); Stream_UnIndentBranch( StgFEM_Debug ); return; } inc = IArray_New(); /* Shortcuts. */ feMesh = self->feMesh; nDomainEls = FeMesh_GetElementDomainSize( feMesh ); nNodalDofs = self->dofLayout->dofCounts; dstArray = self->mapNodeDof2Eq; /* Allocate for the location matrix. */ locMat = AllocArray( int**, nDomainEls ); for( e_i = 0; e_i < nDomainEls; e_i++ ) { FeMesh_GetElementNodes( feMesh, e_i, inc ); nElNodes = IArray_GetSize( inc ); elNodes = IArray_GetPtr( inc ); locMat[e_i] = AllocArray( int*, nElNodes ); for( n_i = 0; n_i < nElNodes; n_i++ ) locMat[e_i][n_i] = AllocArray( int, nNodalDofs[elNodes[n_i]] ); } /* Build location matrix. */ for( e_i = 0; e_i < nDomainEls; e_i++ ) { FeMesh_GetElementNodes( feMesh, e_i, inc ); nElNodes = IArray_GetSize( inc ); elNodes = IArray_GetPtr( inc ); for( n_i = 0; n_i < nElNodes; n_i++ ) { for( dof_i = 0; dof_i < nNodalDofs[elNodes[n_i]]; dof_i++ ) locMat[e_i][n_i][dof_i] = dstArray[elNodes[n_i]][dof_i]; } } Stg_Class_Delete( inc ); /* Store result. */ self->locationMatrix = locMat; } FeEquationNumber* _FeEquationNumber_Create( void* _self, Bool removeBCs ) { /* Build a n equation number for a given feVariable */ FeVariable* feVar = Stg_CheckType( (FeVariable*)_self, FeVariable) ; FeEquationNumber* eqNum=NULL; Stg_Component_Build( feVar, NULL, False ); Stg_Component_Initialise( feVar, NULL, False ); eqNum = FeEquationNumber_New( "", feVar->context, feVar->feMesh, feVar->dofLayout, feVar->bcs, NULL ); eqNum->removeBCs = removeBCs; memcpy( eqNum->periodic, feVar->periodic, 3*sizeof(Bool) ); Stg_Component_Build( eqNum, NULL, False ); Stg_Component_Initialise( eqNum, NULL, False ); // feVar->eqNum = self->eqNum; // We do it for now return eqNum; } void FeEquationNumber_PrintmapNodeDof2Eq( void* feFeEquationNumber, Stream* stream ) { FeEquationNumber* self = (FeEquationNumber*) feFeEquationNumber; FeMesh* feMesh = self->feMesh; MPI_Comm comm = Comm_GetMPIComm( Mesh_GetCommTopology( feMesh, MT_VERTEX ) ); unsigned rank; Node_GlobalIndex gNode_I; Node_GlobalIndex nodeGlobalCount = FeMesh_GetNodeGlobalSize( feMesh ); MPI_Comm_rank( comm, (int*)&rank ); Journal_Printf( stream, "%d: *** Printing destination array ***\n", rank ); for (gNode_I =0; gNode_I < nodeGlobalCount; gNode_I++) { Node_DomainIndex dNode_I; if ( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &dNode_I ) ) { Journal_Printf( stream, "\tmapNodeDof2Eq[(gnode)%2d]: on another proc\n", gNode_I); } else { Dof_Index currNodeNumDofs = self->dofLayout->dofCounts[ dNode_I ]; Dof_Index nodeLocalDof_I; Journal_Printf( stream, "\tmapNodeDof2Eq[(gnode)%2d][(dof)0-%d]:",gNode_I, currNodeNumDofs ); for( nodeLocalDof_I = 0; nodeLocalDof_I < currNodeNumDofs; nodeLocalDof_I++ ) { Journal_Printf( stream, "%3d, ", self->mapNodeDof2Eq[dNode_I][nodeLocalDof_I] ); } Journal_Printf( stream, "\n" ); } } } void FeEquationNumber_PrintmapNodeDof2EqBox( void* feFeEquationNumber, Stream* stream ) { FeEquationNumber* self = (FeEquationNumber*) feFeEquationNumber; FeMesh* feMesh = self->feMesh; MPI_Comm comm = Comm_GetMPIComm( Mesh_GetCommTopology( feMesh, MT_VERTEX ) ); unsigned rank; Grid* vGrid; int ijk[3]; Element_LocalIndex lNode_I; Node_GlobalIndex gNode_I; Node_Index sizeI, sizeJ, sizeK; Dof_Index nDofs; Dof_Index dof_I; MPI_Comm_rank( comm, (int*)&rank ); Journal_Printf( stream, "%d: *** Printing destination array ***\n", rank ); vGrid = *Mesh_GetExtension( feMesh, Grid**, feMesh->vertGridId ); nDofs = self->dofLayout->dofCounts[0]; sizeI = vGrid->sizes[ I_AXIS ]; sizeJ = vGrid->sizes[ J_AXIS ]; sizeK = vGrid->sizes[ K_AXIS ] ? vGrid->sizes[ K_AXIS ] : 1; for ( ijk[2] = 0 ; ijk[2] < sizeK ; ijk[2]++ ) { if ( sizeK != 1 ) Journal_Printf( stream, "\nk = %d\n", ijk[2] ); for ( ijk[1] = sizeJ - 1 ; ijk[1] >= 0 ; ijk[1]-- ) { Journal_Printf( stream, "%2d - ", ijk[1] ); for ( ijk[0] = 0 ; ijk[0] < sizeI ; ijk[0]++ ) { gNode_I = Grid_Project( vGrid, ijk ); Journal_Printf( stream, "{ " ); if ( Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ) { for ( dof_I = 0 ; dof_I < nDofs ; dof_I++ ) Journal_Printf( stream, "%3d ", self->mapNodeDof2Eq[lNode_I][dof_I] ); } else { for ( dof_I = 0 ; dof_I < nDofs ; dof_I++ ) Journal_Printf( stream, " XX " ); } Journal_Printf( stream, "}" ); } Journal_Printf( stream, "\n" ); } /* Bottom row */ Journal_Printf( stream, " " ); for ( ijk[0] = 0 ; ijk[0] < sizeI ; ijk[0]++ ) { Journal_Printf( stream, " %3d ", ijk[0] ); if ( nDofs == 3 ) Journal_Printf( stream, " " ); } Journal_Printf( stream, "\n" ); } } void FeEquationNumber_PrintLocationMatrix( void* feFeEquationNumber, Stream* stream ) { FeEquationNumber* self = (FeEquationNumber*) feFeEquationNumber; FeMesh* feMesh = self->feMesh; MPI_Comm comm = Comm_GetMPIComm( Mesh_GetCommTopology( feMesh, MT_VERTEX ) ); unsigned rank; Element_GlobalIndex gEl_I; unsigned nDims = Mesh_GetDimSize( feMesh ); Element_GlobalIndex elementGlobalCount = FeMesh_GetElementGlobalSize( feMesh ); unsigned nLocalEls = FeMesh_GetElementLocalSize( feMesh ); Journal_Printf( stream, "%d: *** Printing location matrix ***\n", rank ); MPI_Comm_rank( comm, (int*)&rank ); for (gEl_I =0; gEl_I < elementGlobalCount; gEl_I++ ) { Element_LocalIndex lEl_I; if ( !Mesh_GlobalToDomain( feMesh, nDims, gEl_I, &lEl_I ) || lEl_I >= nLocalEls ) { Journal_Printf( stream, "\tLM[(g/l el)%2d/XXX]: on another proc\n", gEl_I); } else { Node_LocalIndex numNodesAtElement; Node_LocalIndex elLocalNode_I; unsigned* incNodes; IArray* inc; inc = IArray_New(); FeMesh_GetElementNodes( self->feMesh, lEl_I, inc ); numNodesAtElement = IArray_GetSize( inc ); incNodes = IArray_GetPtr( inc ); Journal_Printf( stream, "\tLM[(g/l el)%2d/%2d][(enodes)0-%d]", gEl_I, lEl_I, numNodesAtElement); /* print the nodes and dofs */ for ( elLocalNode_I = 0; elLocalNode_I < numNodesAtElement; elLocalNode_I++ ) { /* look up processor local node number. */ Element_LocalIndex currNode = incNodes[elLocalNode_I == 2 ? 3 : elLocalNode_I == 3 ? 2 : elLocalNode_I == 6 ? 7 : elLocalNode_I == 7 ? 6 : elLocalNode_I]; /* get the number of dofs at current node */ Dof_Index currNodeNumDofs = self->dofLayout->dofCounts[ currNode ]; Dof_Index nodeLocalDof_I; Journal_Printf( stream, "({%2d}", currNode ); for( nodeLocalDof_I = 0; nodeLocalDof_I < currNodeNumDofs; nodeLocalDof_I++ ) { Journal_Printf( stream, "%3d,", self->mapNodeDof2Eq[currNode][nodeLocalDof_I] ); } Journal_Printf( stream, "), " ); } Journal_Printf( stream, "\n" ); Stg_Class_Delete( inc ); } } } Partition_Index FeEquationNumber_CalculateOwningProcessorOfEqNum( void* feEquationNumber, Dof_EquationNumber eqNum ) { FeEquationNumber* self = (FeEquationNumber*)feEquationNumber; /* Partition_Index ownerProc = (unsigned int)-1; */ Comm* comm = Mesh_GetCommTopology( self->feMesh, MT_VERTEX ); MPI_Comm mpiComm = Comm_GetMPIComm( comm ); unsigned nProcs; unsigned p_i; MPI_Comm_size( mpiComm, (int*)&nProcs ); for( p_i = 1; p_i < nProcs; p_i++ ) { if( eqNum < self->_lowestGlobalEqNums[p_i] ) break; } return p_i - 1; } void FeEquationNumber_BuildWithTopology( FeEquationNumber* self ) { Stream* stream; double startTime, endTime, time, tmin, tmax; FeMesh* feMesh; Sync* sync; Comm* comm; MPI_Comm mpiComm; unsigned rank, nProcs; unsigned nDims; unsigned nDomainNodes; unsigned nLocalNodes; unsigned* nNodalDofs; unsigned nElNodes, *elNodes; int** dstArray; int *nLocMatDofs, ***locMat; unsigned varInd; unsigned curEqNum; unsigned base; unsigned subTotal; MPI_Status status; unsigned maxDofs; unsigned* tuples; LinkedDofInfo* links; unsigned highest; IArray* inc; unsigned e_i, n_i, dof_i, s_i; int ii; assert( self ); inc = IArray_New(); // stream = Journal_Register( Info_Type, (Name)self->type ); // Stream_SetPrintingRank( stream, 0 ); // // Journal_RPrintf( stream, "FeEquationNumber: '%s'\n", self->name ); // Stream_Indent( stream ); // Journal_RPrintf( stream, "Generating equation numbers...\n" ); // Stream_Indent( stream ); // if( self->removeBCs ) // Journal_RPrintf( stream, "BCs set to be removed.\n" ); // else // Journal_RPrintf( stream, "BCs will not be removed.\n" ); startTime = MPI_Wtime(); /* Shortcuts. */ feMesh = self->feMesh; comm = Mesh_GetCommTopology( feMesh, MT_VERTEX ); mpiComm = Comm_GetMPIComm( comm ); MPI_Comm_size( mpiComm, (int*)&nProcs ); MPI_Comm_rank( mpiComm, (int*)&rank ); nDims = Mesh_GetDimSize( feMesh ); nDomainNodes = FeMesh_GetNodeDomainSize( feMesh ); self->nDomainEls = FeMesh_GetElementDomainSize( feMesh ); nLocalNodes = FeMesh_GetNodeLocalSize( feMesh ); nNodalDofs = self->dofLayout->dofCounts; links = self->linkedDofInfo; /* Allocate for destination array. */ dstArray = Memory_Alloc_2DComplex( int, nDomainNodes, nNodalDofs, "FeEquationNumber::mapNodeDof2Eq" ); /* If needed, allocate for linked equation numbers. */ if( links ) { unsigned s_i; links->eqNumsOfLinkedDofs = ReallocArray( links->eqNumsOfLinkedDofs, int, links->linkedDofSetsCount ); for( s_i = 0; s_i < links->linkedDofSetsCount; s_i++ ) links->eqNumsOfLinkedDofs[s_i] = -1; } /* Allocate for the location matrix. */ nLocMatDofs = NULL; locMat = AllocArray( int**, self->nDomainEls ); for( e_i = 0; e_i < self->nDomainEls; e_i++ ) { FeMesh_GetElementNodes( feMesh, e_i, inc ); nElNodes = IArray_GetSize( inc ); elNodes = IArray_GetPtr( inc ); nLocMatDofs = ReallocArray( nLocMatDofs, int, nElNodes ); for( n_i = 0; n_i < nElNodes; n_i++ ) nLocMatDofs[n_i] = nNodalDofs[elNodes[n_i]]; locMat[e_i] = AllocComplex2D( int, nElNodes, nLocMatDofs ); } FreeArray( nLocMatDofs ); /* Build initial destination array and store max dofs. */ curEqNum = 0; maxDofs = 0; for( n_i = 0; n_i < nLocalNodes; n_i++ ) { if( nNodalDofs[n_i] > maxDofs ) maxDofs = nNodalDofs[n_i]; for( dof_i = 0; dof_i < nNodalDofs[n_i]; dof_i++ ) { varInd = self->dofLayout->varIndices[n_i][dof_i]; if( !self->bcs || !VariableCondition_IsCondition( self->bcs, n_i, varInd ) || !self->removeBCs ) { if( links && links->linkedDofTbl[n_i][dof_i] != -1 ) { if( rank > 0 ) { dstArray[n_i][dof_i] = -2; continue; } if( links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]] == -1 ) links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]] = curEqNum++; dstArray[n_i][dof_i] = links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]]; } else dstArray[n_i][dof_i] = curEqNum++; } else dstArray[n_i][dof_i] = -1; } } /* Order the equation numbers based on processor rank; cascade counts forward. */ base = 0; if( rank > 0 ) (void)MPI_Recv( &base, 1, MPI_UNSIGNED, rank - 1, 6669, mpiComm, &status ); subTotal = base + curEqNum; if( rank < nProcs - 1 ) (void)MPI_Send( &subTotal, 1, MPI_UNSIGNED, rank + 1, 6669, mpiComm ); if( links ) { /* Reduce to find lowest linked DOFs. */ for( s_i = 0; s_i < links->linkedDofSetsCount; s_i++ ) { if( links->eqNumsOfLinkedDofs[s_i] != -1 ) links->eqNumsOfLinkedDofs[s_i] += base; /* MPI_Allreduce( links->eqNumsOfLinkedDofs + s_i, &lowest, 1, MPI_UNSIGNED, MPI_MAX, mpiComm ); */ MPI_Allreduce( links->eqNumsOfLinkedDofs + s_i, &highest, 1, MPI_INT, MPI_MAX, mpiComm ); /* assert( (lowest == (unsigned)-1) ? lowest == highest : 1 ); */ links->eqNumsOfLinkedDofs[s_i] = highest; } } /* Modify existing destination array and dump to a tuple array. */ tuples = AllocArray( unsigned, nDomainNodes * maxDofs ); for( n_i = 0; n_i < nLocalNodes; n_i++ ) { for( dof_i = 0; dof_i < nNodalDofs[n_i]; dof_i++ ) { varInd = self->dofLayout->varIndices[n_i][dof_i]; if( !self->bcs || !VariableCondition_IsCondition( self->bcs, n_i, varInd ) || !self->removeBCs ) { if( links && links->linkedDofTbl[n_i][dof_i] != -1 ) { highest = links->eqNumsOfLinkedDofs[links->linkedDofTbl[n_i][dof_i]]; dstArray[n_i][dof_i] = highest; } else dstArray[n_i][dof_i] += base; } tuples[n_i * maxDofs + dof_i] = dstArray[n_i][dof_i]; } } /* Update all other procs. */ sync = Mesh_GetSync( feMesh, MT_VERTEX ); Sync_SyncArray( sync, tuples, maxDofs * sizeof(unsigned), tuples + nLocalNodes * maxDofs, maxDofs * sizeof(unsigned), maxDofs * sizeof(unsigned) ); /* Update destination array's domain indices. */ for( n_i = nLocalNodes; n_i < nDomainNodes; n_i++ ) { for( dof_i = 0; dof_i < nNodalDofs[n_i]; dof_i++ ) { varInd = self->dofLayout->varIndices[n_i][dof_i]; if( !self->bcs || !VariableCondition_IsCondition( self->bcs, n_i, varInd ) || !self->removeBCs ) { dstArray[n_i][dof_i] = tuples[n_i * maxDofs + dof_i]; } else dstArray[n_i][dof_i] = -1; } } /* Destroy tuple array. */ FreeArray( tuples ); /* Build location matrix. */ for( e_i = 0; e_i < self->nDomainEls; e_i++ ) { FeMesh_GetElementNodes( feMesh, e_i, inc ); nElNodes = IArray_GetSize( inc ); elNodes = IArray_GetPtr( inc ); for( n_i = 0; n_i < nElNodes; n_i++ ) { for( dof_i = 0; dof_i < nNodalDofs[elNodes[n_i]]; dof_i++ ) locMat[e_i][n_i][dof_i] = dstArray[elNodes[n_i]][dof_i]; } } /* Store stuff on class. */ self->mapNodeDof2Eq = dstArray; self->locationMatrix = locMat; self->locationMatrixBuilt = True; self->remappingActivated = False; self->localEqNumsOwnedCount = curEqNum; self->firstOwnedEqNum = base; self->lastOwnedEqNum = subTotal - 1; self->_lowestLocalEqNum = self->firstOwnedEqNum; /* Setup owned mapping. */ STree_Clear( self->ownedMap ); for( ii = self->firstOwnedEqNum; ii <= self->lastOwnedEqNum; ii++ ) { int val = ii - self->firstOwnedEqNum; STreeMap_Insert( self->ownedMap, &ii, &val ); } /* Bcast global sum from highest rank. */ if( rank == nProcs - 1 ) self->globalSumUnconstrainedDofs = self->lastOwnedEqNum + 1; (void)MPI_Bcast( &self->globalSumUnconstrainedDofs, 1, MPI_UNSIGNED, nProcs - 1, mpiComm ); /* Construct lowest global equation number list. */ self->_lowestGlobalEqNums = AllocArray( int, nProcs ); (void)MPI_Allgather( &self->firstOwnedEqNum, 1, MPI_UNSIGNED, self->_lowestGlobalEqNums, 1, MPI_UNSIGNED, mpiComm ); // endTime = MPI_Wtime(); // Journal_RPrintf( stream, "Assigned %d global equation numbers.\n", self->globalSumUnconstrainedDofs ); // Journal_Printf( stream, "[%u] Assigned %d local equation numbers, within range %d to %d.\n", // rank, self->lastOwnedEqNum - self->firstOwnedEqNum + 1, self->firstOwnedEqNum, self->lastOwnedEqNum + 1 ); // Stream_UnIndent( stream ); // time = endTime - startTime; // (void)MPI_Reduce( &time, &tmin, 1, MPI_DOUBLE, MPI_MIN, 0, mpiComm ); // (void)MPI_Reduce( &time, &tmax, 1, MPI_DOUBLE, MPI_MAX, 0, mpiComm ); // Journal_RPrintf( stream, "... Completed in %g [min] / %g [max] seconds.\n", tmin, tmax ); // Stream_UnIndent( stream ); Stg_Class_Delete( inc ); } void FeEquationNumber_BuildWithDave( FeEquationNumber* self ) { int nLocals, *locals; Grid *vGrid; int varInd; int nEqNums, **dstArray; IArray *inc; int nDofs; int *periodic; int ***locMat; int nDims; int *elNodes; Comm *comm; MPI_Comm mpiComm; int nRanks, rank; Sync *sync; Bool isCond; int nPeriodicInds[3]; int *periodicInds[3]; int inds[3]; Bool usePeriodic; int *tmpArray, nLocalEqNums; int lastOwnedEqNum, ind; STree *doneSet; int ii, jj, kk; comm = Mesh_GetCommTopology( self->feMesh, 0 ); mpiComm = Comm_GetMPIComm( comm ); MPI_Comm_size( mpiComm, &nRanks ); MPI_Comm_rank( mpiComm, &rank ); /* Setup an array containing global indices of all locally owned nodes. */ nLocals = Mesh_GetLocalSize( self->feMesh, 0 ); locals = AllocArray( int, nLocals ); for( ii = 0; ii < nLocals; ii++ ) locals[ii] = Mesh_DomainToGlobal( self->feMesh, 0, ii ); /* Allocate for destination array. */ nDofs = self->dofLayout->dofCounts[0]; dstArray = AllocArray2D( int, Mesh_GetDomainSize( self->feMesh, 0 ), nDofs ); /* Get the vertex grid extension and any periodicity. */ nDims = Mesh_GetDimSize( self->feMesh ); vGrid = *Mesh_GetExtension( self->feMesh, Grid**, self->feMesh->vertGridId ); periodic = Mesh_GetExtension( self->feMesh, int*, self->feMesh->periodicId ); /* Fill destination array with initial values, setting dirichlet BCs as we go. */ for( ii = 0; ii < nLocals; ii++ ) { /* Grid_Lift( vGrid, locals[ii], inds ); usePeriodic = False; for( jj = 0; jj < nDims; jj++ ) { if( (periodic[jj] || self->periodic[jj]) && (inds[jj] == 0 || inds[jj] == vGrid->sizes[jj] - 1) ) { usePeriodic = True; break; } } */ for( jj = 0; jj < nDofs; jj++ ) { varInd = self->dofLayout->varIndices[ii][jj]; if( self->bcs ) isCond = VariableCondition_IsCondition( self->bcs, ii, varInd ); else isCond = False; if( isCond && self->removeBCs ) dstArray[ii][jj] = -1; else dstArray[ii][jj] = 0; } } /* Generate opposing indices for periodicity. */ for( ii = 0; ii < nDims; ii++ ) { nPeriodicInds[ii] = 0; periodicInds[ii] = NULL; if( periodic[ii] || self->periodic[ii] ) { periodicInds[ii] = AllocArray( int, nLocals ); for( jj = 0; jj < nLocals; jj++ ) { Grid_Lift( vGrid, locals[jj], inds ); if( inds[ii] != vGrid->sizes[ii] - 1 ) continue; /* for( kk = 0; kk < nDofs; kk++ ) if( dstArray[jj][kk] == -1 ) break; if( kk < nDofs ) continue; */ periodicInds[ii][nPeriodicInds[ii]++] = locals[jj]; } } } /* Call Dave's equation number generation routine. */ if( nDims == 2 ) { GenerateEquationNumbering( vGrid->sizes[0], vGrid->sizes[1], 1, nLocals, locals, nDofs, Mesh_GetGlobalSize( self->feMesh, 0 ), periodic[0] || self->periodic[0], periodic[1] || self->periodic[1], False, nPeriodicInds[0], nPeriodicInds[1], 0, periodicInds[0], periodicInds[1], NULL, dstArray[0], &nEqNums ); } else if( nDims == 3 ) { GenerateEquationNumbering( vGrid->sizes[0], vGrid->sizes[1], vGrid->sizes[2], nLocals, locals, nDofs, Mesh_GetGlobalSize( self->feMesh, 0 ), periodic[0] || self->periodic[0], periodic[1] || self->periodic[1], periodic[2] || self->periodic[2], nPeriodicInds[0], nPeriodicInds[1], nPeriodicInds[2], periodicInds[0], periodicInds[1], periodicInds[2], dstArray[0], &nEqNums ); } else if( nDims == 1 ) { GenerateEquationNumbering( vGrid->sizes[0], 1, 1, nLocals, locals, nDofs, Mesh_GetGlobalSize( self->feMesh, 0 ), periodic[0], False, False, nPeriodicInds[0], 0, 0, periodicInds[0], NULL, NULL, dstArray[0], &nEqNums ); } else abort(); /* Free periodic arrays. */ for( ii = 0; ii < nDims; ii++ ) { if( periodicInds[ii] ) FreeArray( periodicInds[ii] ); } /* Setup owned mapping part 1. */ STree_Clear( self->ownedMap ); for( ii = 0; ii < nLocals; ii++ ) { Grid_Lift( vGrid, locals[ii], inds ); for( jj = 0; jj < nDims; jj++ ) { if( (periodic[jj] || self->periodic[jj]) && inds[jj] == vGrid->sizes[jj] - 1 ) { inds[jj] = 0; ind = Grid_Project( vGrid, inds ); if( !FeMesh_NodeGlobalToDomain( self->feMesh, ind, &ind ) ) break; } } if( jj < nDims ) continue; for( jj = 0; jj < nDofs; jj++ ) { if( dstArray[ii][jj] == -1 || STreeMap_HasKey( self->ownedMap, dstArray[ii] + jj ) ) continue; STreeMap_Insert( self->ownedMap, dstArray[ii] + jj, &ii ); } } /* Setup owned mapping. */ tmpArray = AllocArray( int, nLocals * nDofs ); memcpy( tmpArray, dstArray[0], nLocals * nDofs * sizeof(int) ); qsort( tmpArray, nLocals * nDofs, sizeof(int), stgCmpInt ); doneSet = STree_New(); STree_SetItemSize( doneSet, sizeof(int) ); STree_SetIntCallbacks( doneSet ); for( nLocalEqNums = 0, ii = 0; ii < nLocals * nDofs; ii++ ) { if( tmpArray[ii] != -1 && STreeMap_HasKey( self->ownedMap, tmpArray + ii ) && !STree_Has( doneSet, tmpArray + ii ) ) { if( !nLocalEqNums ) self->_lowestLocalEqNum = tmpArray[ii]; *(int*)STreeMap_Map( self->ownedMap, tmpArray + ii ) = nLocalEqNums; STree_Insert( doneSet, tmpArray + ii ); nLocalEqNums++; } } lastOwnedEqNum = -1; /* Don't need this anymore. */ FreeArray( tmpArray ); Stg_Class_Delete( doneSet ); /* Transfer remote equation numbers. */ sync = Mesh_GetSync( self->feMesh, 0 ); Sync_SyncArray( sync, dstArray[0], nDofs * sizeof(int), dstArray[0] + nLocals * nDofs, nDofs * sizeof(int), nDofs * sizeof(int) ); /* Allocate for location matrix. */ /* first store nDomainEls for usage during destroy */ self->nDomainEls = Mesh_GetDomainSize( self->feMesh, nDims ); locMat = AllocArray( int**, self->nDomainEls ); for( ii = 0; ii < self->nDomainEls; ii++ ) locMat[ii] = AllocArray2D( int, FeMesh_GetElementNodeSize( self->feMesh, 0 ), nDofs ); /* Fill in location matrix. */ inc = IArray_New(); for( ii = 0; ii < Mesh_GetDomainSize( self->feMesh, nDims ); ii++ ) { FeMesh_GetElementNodes( self->feMesh, ii, inc ); elNodes = IArray_GetPtr( inc ); for( jj = 0; jj < FeMesh_GetElementNodeSize( self->feMesh, 0 ); jj++ ) { for( kk = 0; kk < nDofs; kk++ ) locMat[ii][jj][kk] = dstArray[elNodes[jj]][kk]; } } Stg_Class_Delete( inc ); /* Fill in our other weird values. */ self->mapNodeDof2Eq = dstArray; self->locationMatrix = locMat; self->locationMatrixBuilt = True; self->remappingActivated = False; self->localEqNumsOwnedCount = nLocalEqNums; /* Bcast global sum from highest rank. */ self->globalSumUnconstrainedDofs = nEqNums; /* Construct lowest global equation number list. */ self->_lowestGlobalEqNums = AllocArray( int, nRanks ); (void)MPI_Allgather( &self->_lowestLocalEqNum, 1, MPI_UNSIGNED, self->_lowestGlobalEqNums, 1, MPI_UNSIGNED, mpiComm ); FreeArray( locals ); /* printf( "%d: localEqNumsOwned = %d\n", rank, self->localEqNumsOwnedCount ); printf( "%d: globalSumUnconstrainedDofs = %d\n", rank, self->globalSumUnconstrainedDofs ); */ } /* Input: nlocal - number of locally ownded nodes g_node_id - global indices of nodes owned locally. Size nlocal dof - degrees of freedom per node nglobal - number of global nodes npx - number of consider to be periodic in x (local to this proc) npy - number of consider to be periodic in y (local to this proc) periodic_x_gnode_id - global indices of nodes (on this proc) which are on right hand side boundary periodic_y_gnode_id - global indices of nodes (on this proc) whipch are on top boundary eqnums - contains any dirichlet boundary conditions. Size nlocal*dof Output; eqnums - contains full list of eqnums Assumptions: - Ordering eqnums[] = { (node_0,[dof_0,dof_1,..,dof_x]), (node_1,[dof_0,dof_1,..,dof_x]), ... } - Any dirichlet set along a boundary deemed to be periodic will be clobbered. - Processors may have duplicate nodes in the g_node_id[] list. - A number in the corner is considered part of both boundaries (horiz and vert) - If npx is not 0, then periodicity is assumed in x - If npy is not 0, then periodicity is assumed in y - Dofs constrained to be dirichlet must be marked with a negative number. - Dofs are NOT split across processors. - We can define a logical i,j,k ordering to uniquely identify nodes. */ PetscErrorCode _VecScatterBeginEnd( VecScatter vscat, Vec FROM, Vec TO, InsertMode addv,ScatterMode mode ) { #if( (PETSC_VERSION_MAJOR==2) && (PETSC_VERSION_MINOR==3) && (PETSC_VERSION_SUBMINOR==2) ) // 2.3.2 ordering of args VecScatterBegin( FROM, TO, addv, mode, vscat ); VecScatterEnd( FROM, TO, addv, mode, vscat ); #else // 2.3.3 or 3.0.0 VecScatterBegin( vscat, FROM, TO, addv, mode ); VecScatterEnd( vscat, FROM, TO, addv, mode ); #endif PetscFunctionReturn(0); } int GenerateEquationNumbering( int NX, int NY, int NZ, int nlocal, int g_node_id[], int dof, int nglobal, PetscTruth periodic_x, PetscTruth periodic_y, PetscTruth periodic_z, int npx, int npy, int npz, int periodic_x_gnode_id[], int periodic_y_gnode_id[], int periodic_z_gnode_id[], int eqnums[], int *neqnums ) { PetscErrorCode ierr; PetscInt periodic_mask; Vec global_eqnum, g_ownership; PetscInt i; PetscMPIInt rank; /* processor rank */ PetscMPIInt size; /* size of communicator */ Vec local_ownership, local_eqnum; PetscInt *_g_node_id; IS is_gnode, is_eqnum; VecScatter vscat_ownership, vscat_eqnum; PetscScalar *_local_ownership, *_local_eqnum; PetscInt local_eqnum_count,global_eqnum_count; PetscScalar val[10]; PetscInt d,idx[10]; PetscInt *to_fetch,cnt,number_to_fetch; PetscInt eq_cnt; Vec offset_list; VecScatter vscat_offset; Vec seq_offset_list; PetscInt offset, inc; PetscInt spanx,spany,spanz,total; PetscInt loc; PetscReal max; PetscInt n_inserts; ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr); ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr); if( dof>=10 ) { Stg_SETERRQ(PETSC_ERR_SUP, "Max allowable degrees of freedom per node = 10. Change static size" ); } /* Claim locally owned nodes. Duplicate nodes on the interior will be resolved by the processor which inserts last. */ VecCreate( PETSC_COMM_WORLD, &g_ownership ); VecSetSizes( g_ownership, PETSC_DECIDE, nglobal ); VecSetFromOptions( g_ownership ); for( i=0; i<nlocal; i++ ) { VecSetValue( g_ownership, g_node_id[i], rank, INSERT_VALUES ); } VecAssemblyBegin(g_ownership); VecAssemblyEnd(g_ownership); /* Mask out the periodic boundaries. */ periodic_mask = -6699.0; if (periodic_x_gnode_id!=NULL) { for( i=0; i<npx; i++ ) { VecSetValue( g_ownership, periodic_x_gnode_id[i], periodic_mask, INSERT_VALUES ); } } if (periodic_y_gnode_id!=NULL) { for( i=0; i<npy; i++ ) { VecSetValue( g_ownership, periodic_y_gnode_id[i], periodic_mask, INSERT_VALUES ); } } if (periodic_z_gnode_id!=NULL) { for( i=0; i<npz; i++ ) { VecSetValue( g_ownership, periodic_z_gnode_id[i], periodic_mask, INSERT_VALUES ); } } VecAssemblyBegin(g_ownership); VecAssemblyEnd(g_ownership); /* PetscPrintf(PETSC_COMM_WORLD, "g_ownership \n"); VecView( g_ownership, PETSC_VIEWER_STDOUT_WORLD ); */ /* Get all locally owned nodes */ VecCreate( PETSC_COMM_SELF, &local_ownership ); VecSetSizes( local_ownership, PETSC_DECIDE, nlocal ); VecSetFromOptions( local_ownership ); PetscMalloc( sizeof(PetscInt)*nlocal, &_g_node_id); for( i=0; i<nlocal; i++ ) { _g_node_id[i] = g_node_id[i]; } ISCreateGeneralWithArray( PETSC_COMM_WORLD, nlocal, _g_node_id, &is_gnode ); VecScatterCreate( g_ownership, is_gnode, local_ownership, PETSC_NULL, &vscat_ownership ); /* assign unique equation numbers */ VecSet( local_ownership, -6699 ); _VecScatterBeginEnd( vscat_ownership, g_ownership, local_ownership, INSERT_VALUES, SCATTER_FORWARD ); /* Count instances of rank in the local_ownership vector */ VecGetArray( local_ownership, &_local_ownership ); local_eqnum_count = 0; for( i=0; i<nlocal; i++ ) { if( ((PetscInt)_local_ownership[i]) == rank ) { local_eqnum_count++; } } (void)MPI_Allreduce( &local_eqnum_count, &global_eqnum_count, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD ); /* PetscPrintf( PETSC_COMM_SELF, "[%d] number of local,global equations (without dofs) %d,%d \n", rank, local_eqnum_count, global_eqnum_count ); */ /* check */ spanx = NX; spany = NY; spanz = NZ; if( periodic_x==PETSC_TRUE ) { spanx--; } if( periodic_y==PETSC_TRUE ) { spany--; } if( periodic_z==PETSC_TRUE ) { spanz--; } total = spanx*spany*spanz; if( total!=global_eqnum_count ) { Stg_SETERRQ(PETSC_ERR_SUP, "Something stinks. Computed global size for nodes does not match expected" ); } VecCreate( PETSC_COMM_WORLD, &global_eqnum ); VecSetSizes( global_eqnum, PETSC_DECIDE, nglobal*dof ); VecSetFromOptions( global_eqnum ); VecSet( global_eqnum, 0.0 ); /* Load existing eqnums in */ for( i=0; i<nlocal; i++ ) { n_inserts = 0; for( d=0; d<dof; d++ ) { /* idx[d] = -(g_node_id[i]*dof + d); val[d] = 0.0; */ if( eqnums[ i*dof + d ] < 0.0 ) { idx[n_inserts] = g_node_id[i]*dof + d; val[n_inserts] = eqnums[ i*dof + d ]; n_inserts++; } } /* only insert dirichlet bc's */ VecSetValues( global_eqnum, n_inserts, idx, val, INSERT_VALUES ); } VecAssemblyBegin(global_eqnum); VecAssemblyEnd(global_eqnum); /* Generate list of eqnums to get */ PetscMalloc( sizeof(PetscInt)*nlocal*dof, &to_fetch ); cnt = 0; for( i=0; i<nlocal; i++ ) { if( _local_ownership[i]==rank ) { for( d=0; d<dof; d++ ) { to_fetch[cnt] = g_node_id[i]*dof + d; cnt++; } } } number_to_fetch = cnt; VecCreate( PETSC_COMM_SELF, &local_eqnum ); VecSetSizes( local_eqnum, PETSC_DECIDE, number_to_fetch); VecSetFromOptions( local_eqnum ); ISCreateGeneralWithArray( PETSC_COMM_SELF, number_to_fetch, to_fetch, &is_eqnum ); VecScatterCreate( global_eqnum, is_eqnum, local_eqnum, PETSC_NULL, &vscat_eqnum ); VecSet( local_eqnum, -6699 ); _VecScatterBeginEnd( vscat_eqnum, global_eqnum, local_eqnum, INSERT_VALUES, SCATTER_FORWARD ); /* compute offset */ /* count how many entries there are */ VecGetArray( local_eqnum, &_local_eqnum ); eq_cnt = 0; for( i=0; i<number_to_fetch; i++ ) { if( (PetscInt)_local_eqnum[i]==0 ) { eq_cnt++; } } VecRestoreArray( local_eqnum, &_local_eqnum ); VecCreate( PETSC_COMM_WORLD, &offset_list ); VecSetSizes( offset_list, PETSC_DECIDE, size ); VecSetFromOptions( offset_list ); VecSetValue( offset_list, rank, eq_cnt, INSERT_VALUES ); VecAssemblyBegin(offset_list); VecAssemblyEnd(offset_list); /* PetscPrintf(PETSC_COMM_WORLD, "offset_list \n"); VecView( offset_list, PETSC_VIEWER_STDOUT_WORLD ); */ VecScatterCreateToAll(offset_list,&vscat_offset,&seq_offset_list); _VecScatterBeginEnd( vscat_offset, offset_list, seq_offset_list, INSERT_VALUES, SCATTER_FORWARD ); { PetscScalar *_seq_offset_list; VecGetArray( seq_offset_list, &_seq_offset_list ); offset = 0; for (i=0; i<rank; i++) { offset+=_seq_offset_list[ i ]; } VecRestoreArray( seq_offset_list, &_seq_offset_list ); } Stg_VecScatterDestroy(&vscat_offset); Stg_VecDestroy(&offset_list); Stg_VecDestroy(&seq_offset_list); // PetscPrintf( PETSC_COMM_SELF, "[%d]: offset = %d \n", rank, offset ); VecGetArray( local_eqnum, &_local_eqnum ); inc = 0; for( i=0; i<number_to_fetch; i++ ) { if( (PetscInt)_local_eqnum[i]==0 ) { _local_eqnum[i] = offset+inc; inc++; } } VecRestoreArray( local_eqnum, &_local_eqnum ); _VecScatterBeginEnd( vscat_eqnum, local_eqnum, global_eqnum, INSERT_VALUES, SCATTER_REVERSE ); /* PetscPrintf(PETSC_COMM_WORLD, "global_eqnum \n"); VecView( global_eqnum, PETSC_VIEWER_STDOUT_WORLD ); */ /* For each periodic boundary, get the mapped nodes */ if( periodic_x==PETSC_TRUE ) { VecScatter vscat_p; IS is_from; PetscInt *from, *to; Vec mapped; PetscScalar *_mapped; PetscInt c; PetscMalloc( sizeof(PetscInt)*npx*dof, &from ); PetscMalloc( sizeof(PetscInt)*npx*dof, &to ); c = 0; for( i=0; i<npx; i++ ) { PetscInt I,J,K,gid,from_gid; gid = periodic_x_gnode_id[i]; K = gid/(NX*NY); J = (gid - K*(NX*NY))/NX; I = gid - K*(NX*NY) - J*NX; from_gid = (I-(NX-1)) + J*NX + K*(NX*NY); for( d=0; d<dof; d++ ) { to[c] = gid * dof + d; from[c] = from_gid * dof + d; c++; } } VecCreate( PETSC_COMM_SELF, &mapped ); VecSetSizes( mapped, PETSC_DECIDE, npx*dof ); VecSetFromOptions( mapped ); ISCreateGeneralWithArray( PETSC_COMM_SELF, npx*dof, from, &is_from ); VecScatterCreate( global_eqnum, is_from, mapped, PETSC_NULL, &vscat_p ); _VecScatterBeginEnd( vscat_p, global_eqnum, mapped, INSERT_VALUES, SCATTER_FORWARD ); if( npx>0 ) { VecGetArray( mapped, &_mapped ); VecSetValues( global_eqnum, npx*dof, to, _mapped, INSERT_VALUES ); VecRestoreArray( mapped, &_mapped ); } VecAssemblyBegin(global_eqnum); VecAssemblyEnd(global_eqnum); Stg_VecScatterDestroy(&vscat_p ); Stg_ISDestroy(&is_from ); Stg_VecDestroy(&mapped ); PetscFree( from ); PetscFree( to ); } if( periodic_y==PETSC_TRUE ) { VecScatter vscat_p; IS is_from; PetscInt *from, *to; Vec mapped; PetscScalar *_mapped; PetscInt c; PetscMalloc( sizeof(PetscInt)*npy*dof, &from ); PetscMalloc( sizeof(PetscInt)*npy*dof, &to ); c = 0; for( i=0; i<npy; i++ ) { PetscInt I,J,K,gid,from_gid; gid = periodic_y_gnode_id[i]; K = gid/(NX*NY); J = (gid - K*(NX*NY))/NX; I = gid - K*(NX*NY) - J*NX; from_gid = I + (J - (NY - 1))*NX + K*(NX*NY); for( d=0; d<dof; d++ ) { to[c] = gid * dof + d; from[c] = from_gid * dof + d; c++; } } VecCreate( PETSC_COMM_SELF, &mapped ); VecSetSizes( mapped, PETSC_DECIDE, npy*dof ); VecSetFromOptions( mapped ); ISCreateGeneralWithArray( PETSC_COMM_SELF, npy*dof, from, &is_from ); VecScatterCreate( global_eqnum, is_from, mapped, PETSC_NULL, &vscat_p ); _VecScatterBeginEnd( vscat_p, global_eqnum, mapped, INSERT_VALUES, SCATTER_FORWARD ); if( npy>0 ) { VecGetArray( mapped, &_mapped ); VecSetValues( global_eqnum, npy*dof, to, _mapped, INSERT_VALUES ); VecRestoreArray( mapped, &_mapped ); } VecAssemblyBegin(global_eqnum); VecAssemblyEnd(global_eqnum); Stg_VecScatterDestroy(&vscat_p ); Stg_ISDestroy(&is_from ); Stg_VecDestroy(&mapped ); PetscFree( from ); PetscFree( to ); } if( periodic_z==PETSC_TRUE ) { VecScatter vscat_p; IS is_from; PetscInt *from, *to; Vec mapped; PetscScalar *_mapped; PetscInt c; PetscMalloc( sizeof(PetscInt)*npz*dof, &from ); PetscMalloc( sizeof(PetscInt)*npz*dof, &to ); c = 0; for( i=0; i<npz; i++ ) { PetscInt I,J,K,gid,from_gid; gid = periodic_z_gnode_id[i]; K = gid/(NX*NY); J = (gid - K*(NX*NY))/NX; I = gid - K*(NX*NY) - J*NX; from_gid = I + J*NX + (K - (NZ-1))*(NX*NY); for( d=0; d<dof; d++ ) { to[c] = gid * dof + d; from[c] = from_gid * dof + d; c++; } } VecCreate( PETSC_COMM_SELF, &mapped ); VecSetSizes( mapped, PETSC_DECIDE, npz*dof ); VecSetFromOptions( mapped ); ISCreateGeneralWithArray( PETSC_COMM_SELF, npz*dof, from, &is_from ); VecScatterCreate( global_eqnum, is_from, mapped, PETSC_NULL, &vscat_p ); _VecScatterBeginEnd( vscat_p, global_eqnum, mapped, INSERT_VALUES, SCATTER_FORWARD ); if( npz>0 ) { VecGetArray( mapped, &_mapped ); VecSetValues( global_eqnum, npz*dof, to, _mapped, INSERT_VALUES ); VecRestoreArray( mapped, &_mapped ); } VecAssemblyBegin(global_eqnum); VecAssemblyEnd(global_eqnum); Stg_VecScatterDestroy(&vscat_p ); Stg_ISDestroy(&is_from ); Stg_VecDestroy(&mapped ); PetscFree( from ); PetscFree( to ); } /* PetscPrintf(PETSC_COMM_WORLD, "global_eqnum following periodic \n"); VecView( global_eqnum, PETSC_VIEWER_STDOUT_WORLD ); */ /* Finally, scatter stuff from global_eqnums into MY array */ { IS is_all_my_eqnums; PetscInt *all_my_eqnum_index; PetscInt _I,_D,CNT; Vec all_my_eqnums; PetscScalar *_all_my_eqnums; VecScatter vscat_p; PetscMalloc( sizeof(PetscInt)*dof*nlocal, &all_my_eqnum_index ); CNT = 0; for( _I=0; _I<nlocal; _I++ ) { for( _D=0; _D<dof; _D++ ) { all_my_eqnum_index[CNT] = g_node_id[_I]*dof + _D; CNT++; } } ISCreateGeneralWithArray( PETSC_COMM_SELF, nlocal*dof, all_my_eqnum_index, &is_all_my_eqnums ); VecCreate( PETSC_COMM_SELF, &all_my_eqnums ); VecSetSizes( all_my_eqnums, PETSC_DECIDE, nlocal*dof ); VecSetFromOptions( all_my_eqnums ); VecScatterCreate( global_eqnum, is_all_my_eqnums, all_my_eqnums, PETSC_NULL, &vscat_p ); _VecScatterBeginEnd( vscat_p, global_eqnum, all_my_eqnums, INSERT_VALUES, SCATTER_FORWARD ); VecGetArray( all_my_eqnums, &_all_my_eqnums ); for( i=0; i<nlocal*dof; i++ ) { eqnums[i] = (int)_all_my_eqnums[i]; } VecRestoreArray( all_my_eqnums, &_all_my_eqnums ); Stg_VecScatterDestroy(&vscat_p ); Stg_VecDestroy(&all_my_eqnums ); Stg_ISDestroy(&is_all_my_eqnums ); PetscFree( all_my_eqnum_index ); } VecMax( global_eqnum, &loc, &max ); *neqnums = (int)max; (*neqnums)++; /* tidy up */ VecRestoreArray( local_ownership, &_local_ownership ); Stg_VecDestroy(&g_ownership ); Stg_VecDestroy(&local_ownership ); PetscFree( _g_node_id ); Stg_ISDestroy(&is_gnode ); Stg_VecScatterDestroy(&vscat_ownership ); Stg_VecDestroy(&global_eqnum ); Stg_VecDestroy(&local_eqnum ); PetscFree( to_fetch ); Stg_ISDestroy(&is_eqnum ); Stg_VecScatterDestroy(&vscat_eqnum ); return 0; }
{ "alphanum_fraction": 0.6381409506, "avg_line_length": 32.7698209719, "ext": "c", "hexsha": "8f8b5cf72a34e3e0d5f3aee2225b85b7e30f577b", "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": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/FeEquationNumber.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/FeEquationNumber.c", "max_line_length": 137, "max_stars_count": null, "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_path": "underworld/libUnderworld/StgFEM/Discretisation/src/FeEquationNumber.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 15825, "size": 51252 }
/** * A metropolis hasting sampler for bremsstrahlung and pair production cross sections * * copyright (C) 2007 * the icecube collaboration * * $Id: I3MetropolisHastings.h 143040 2016-03-11 17:35:25Z nega $ * * @version $Revision: 143040 $ * @date $LastChangedDate: 2016-03-11 10:35:25 -0700 (Fri, 11 Mar 2016) $ * @author Bernhard Voigt <bernhard.voigt@desy.de> $LastChangedBy$ */ #ifndef I3METROPOLISHASTINGS_h_ #define I3METROPOLISHASTINGS_h_ // icetray includes #include "icetray/I3Logging.h" #include "cmc/I3CascadeMCCommon.h" // gsl includes #include <gsl/gsl_rng.h> // c++ includes #include <string> /** * @brief This class implements a Metropolis Hastings sampler * * It uses a pdf and a proposal distribution to efficiently * produce random samples from the pdf * * The proposal distribution used is a beta distribution, which * matches almost the shape of the bremsstrahlung and pair production * cross sections, using the right parameters. See I3CascadeSimulation * for the usage. * * For details on the algorithm, take a look at : * http://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm */ class I3MetropolisHastings : public I3CascadeMCCommon::Sampler { // set logging name for icetray SET_LOGGER("I3MetropolisHastings"); public: /** * Default Constructor */ I3MetropolisHastings() {} /** * Constructor * * @param rng a gsl_random instance * @param pdf a function with two parameters, ie. the energy and * fractional energy of the cross section * @param proposal a gsl random instance sampling from the proposal * distribution which is a beta distribution * @param proposalDistribution a beta function in x * @param name name of this instance for logging purposes * * The proposal gsl random instance as well as the proposalDistribution are implemented * in a struct beta_dist in the header file I3CascadeSimulation.h */ I3MetropolisHastings(I3RandomServicePtr rng, double (*pdf)(const double&, const double&), double (*proposal)(const gsl_rng*), double (*proposalDistribution)(const double&), std::string name); /** * Get the total sample loop count */ unsigned long GetCounter() { return counter_; } /** * Reset the total sample loop count */ void ResetCounter() { counter_ = 0; } /** * Get the number of returned samples */ unsigned long GetYield() { return yield_; } /** * Reset the number of returned samples */ void ResetYield() { yield_ = 0; } /** * Samples n times starting at start position * * Used to forget the initial state * * @param energy parameter of underlying pdf * @param start starting position * @param n number of samples */ void BurnIn(double energy, double start, unsigned int n=100); /** * Samples the underlying pdf in the given range * * @param energy parameter to the underlying pdf * @param lower edge of sample range * @param higher edge of sample range * @return random number */ double Sample(double energy, double lower=0, double higher=1); private: /** * @brief pdf, ie a cross section with energy and fractional energy parameters */ double (*pdf_)(const double&, const double&); /** * @brief a gls random instance drawing samples from the proposal distribution */ double (*proposal_)(const gsl_rng*); /** * @brief a proposal distribution, in this case a beta distribution in x */ double (*proposalDistribution_)(const double&); /** * @brief loop counter */ unsigned long counter_; /** * @brief counts how many successful attemps have been made to draw a new random number */ unsigned long yield_; /** * @brief name of this instance, for logging purpose */ std::string name_; /** * @brief last drawn sample */ double x_; /** * @brief last value of pdf(x) */ double y_; /** * @brief last value of proposalDist(x) */ double propDistY_; }; #endif
{ "alphanum_fraction": 0.6613019457, "avg_line_length": 23.6534090909, "ext": "h", "hexsha": "018c2d87b37ce34c03e13ebeb3bbca5d6648acf8", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_path": "cmc/private/cmc/I3MetropolisHastings.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "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": "hschwane/offline_production", "max_issues_repo_path": "cmc/private/cmc/I3MetropolisHastings.h", "max_line_length": 90, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_path": "cmc/private/cmc/I3MetropolisHastings.h", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "num_tokens": 1045, "size": 4163 }
// Copyright (c) 2021 Stig Rune Sellevag // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #ifndef SCILIB_LINALG_BLAS1_VECTOR_NORM2_H #define SCILIB_LINALG_BLAS1_VECTOR_NORM2_H #ifdef USE_MKL #include <mkl.h> #else #include <cblas.h> #endif #include <experimental/mdspan> namespace Sci { namespace Linalg { namespace stdex = std::experimental; template <stdex::extents<>::size_type ext_x, class Layout_x, class Accessor_x> inline double norm2(stdex::mdspan<double, stdex::extents<ext_x>, Layout_x, Accessor_x> x) { const BLAS_INT n = static_cast<BLAS_INT>(x.size()); const BLAS_INT incx = static_cast<BLAS_INT>(x.stride(0)); return cblas_dnrm2(n, x.data(), incx); } template <stdex::extents<>::size_type ext_x, class Layout_x, class Accessor_x> inline double norm2( stdex::mdspan<const double, stdex::extents<ext_x>, Layout_x, Accessor_x> x) { const BLAS_INT n = static_cast<BLAS_INT>(x.size()); const BLAS_INT incx = static_cast<BLAS_INT>(x.stride(0)); return cblas_dnrm2(n, x.data(), incx); } template <class Layout, class Allocator> inline double norm2(const Sci::Vector<double, Layout, Allocator>& x) { return norm2(x.view()); } } // namespace Linalg } // namespace Sci #endif // SCILIB_LINALG_BLAS1_VECTOR_NORM2_H
{ "alphanum_fraction": 0.7375988497, "avg_line_length": 26.2452830189, "ext": "h", "hexsha": "fd1345543888529a19e1dec7ad84bd939100095f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "stigrs/scilib", "max_forks_repo_path": "include/scilib/linalg_impl/blas1_vector_norm2.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "stigrs/scilib", "max_issues_repo_path": "include/scilib/linalg_impl/blas1_vector_norm2.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "stigrs/scilib", "max_stars_repo_path": "include/scilib/linalg_impl/blas1_vector_norm2.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 402, "size": 1391 }
#ifndef COMMAND_LINE_INCLUDE #define COMMAND_LINE_INCLUDE #include <string> #include <vector> #include <gsl/string_span> #include "config/fleetingOptionsInterface.h" #include "config/variablesMap.h" #include "core/task.h" namespace execHelper { namespace plugins { using CommandLineArg = std::string; using CommandLineArgs = std::vector<CommandLineArg>; static const gsl::czstring<> COMMAND_LINE_KEY = "command-line"; /** * \brief Extends the functionality to include the _command-line_ config parameter and processes this parameter */ struct CommandLine { /*! @copydoc AddEnvironment::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&) */ static void getVariables(config::VariablesMap& variables, const config::FleetingOptionsInterface& options) noexcept; /*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&) */ inline static void apply(core::Task& task, const config::VariablesMap& variables) noexcept { task.append(*(variables.get<CommandLineArgs>(COMMAND_LINE_KEY))); } }; } // namespace plugins } // namespace execHelper #endif /* COMMAND_LINE_INCLUDE */
{ "alphanum_fraction": 0.7198669992, "avg_line_length": 28.6428571429, "ext": "h", "hexsha": "4f5aee25c3bf723e5f9f6fe658b127664a7d0109", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "exec-helper/source", "max_forks_repo_path": "src/plugins/include/plugins/commandLine.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "exec-helper/source", "max_issues_repo_path": "src/plugins/include/plugins/commandLine.h", "max_line_length": 111, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "exec-helper/source", "max_stars_repo_path": "src/plugins/include/plugins/commandLine.h", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "num_tokens": 247, "size": 1203 }
#pragma once #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <cblas.h> #include <omp.h> #include "matrix.h" double l1_distance(double *vec_1, double *vec_2, int N); void naive_ranking(double *matrix, double *result, int N); void pagerank(double *matrix, double *result, int N, double tolerance, double damping_factor, int max_iter);
{ "alphanum_fraction": 0.7124352332, "avg_line_length": 27.5714285714, "ext": "h", "hexsha": "fcb2cf7278eda6af979ccf879f658e128336c8ec", "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": "bc9a3966c4f2b165b1b2d568b811f947aafe98bf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Illumaria/made-high-performance-computing", "max_forks_repo_path": "hw4/src/ranking.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bc9a3966c4f2b165b1b2d568b811f947aafe98bf", "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": "Illumaria/made-high-performance-computing", "max_issues_repo_path": "hw4/src/ranking.h", "max_line_length": 69, "max_stars_count": 1, "max_stars_repo_head_hexsha": "bc9a3966c4f2b165b1b2d568b811f947aafe98bf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Illumaria/made-high-performance-computing", "max_stars_repo_path": "hw4/src/ranking.h", "max_stars_repo_stars_event_max_datetime": "2021-12-25T02:36:32.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-25T02:36:32.000Z", "num_tokens": 99, "size": 386 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <omp.h> #include "util.h" int main(int argc, char *argv[]) { char* input_fileName1 = argv[1]; char* input_fileName2 = argv[2]; int N_doc_bg = atoi(argv[3]); int N_kw = atoi(argv[4]); int N_obs = atoi(argv[5]); int N_iter = atoi(argv[6]); char* output_fileName = argv[7]; int N_doc = 480000 / 2; int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs); int* matrix_bg = (int*) malloc(sizeof(int) * N_kw * N_kw); int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs); int* true_index = (int*) malloc(sizeof(int) * N_kw); int* permutation = (int*) malloc(sizeof(int) * N_obs); gsl_matrix* matrix_obs; for (int round = 0; round < 10; round++) { char input_fileName1_extend[40]; char input_fileName2_extend[40]; sprintf(input_fileName1_extend, "%s%d", input_fileName1, round); sprintf(input_fileName2_extend, "%s%d", input_fileName2, round); // Setup struct timeval tv1,tv2; gettimeofday(&tv1, NULL); read_matrix(&true_index, &matrix_bg, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend); read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend); gettimeofday(&tv2, NULL); printf("Reading done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); // compute the maximum frequency of a keyword int freq_max = 0; for (int ii = 0; ii < N_kw; ii++) if (matrix_bg[ii*N_kw+ii] > freq_max) freq_max = matrix_bg[ii*N_kw+ii]; for (int ii = 0; ii < N_obs; ii++) if (matrix[ii*N_obs+ii] > freq_max) freq_max = matrix[ii*N_obs+ii]; printf("Max frequency: %d\n", freq_max); for (int iter = 0; iter < 10; iter++) { printf("Run %d\n", iter); matrix_obs = gsl_matrix_alloc(N_obs, N_obs); gettimeofday(&tv1, NULL); pad_matrix(&matrix_padded, &matrix, N_obs, N_doc, freq_max); gettimeofday(&tv2, NULL); printf("Padding done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); gettimeofday(&tv1, NULL); observe_matrix(matrix_obs, &matrix_padded, N_obs); gettimeofday(&tv2, NULL); printf("Observed matrix generated: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); // Permute observed matrix randomly and attack gettimeofday(&tv1, NULL); attack(matrix_obs, &matrix_bg, &permutation, N_kw, N_obs, N_doc, freq_max, N_iter); gettimeofday(&tv2, NULL); printf("Main attack done: %d.\n", (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); char output_fileName_full[40]; sprintf(output_fileName_full, "%s%d-%d", output_fileName, round, iter); print_result(output_fileName_full, &permutation, &true_index, N_obs); //sprintf(output_fileName_full, "%s%d-%d-full", output_fileName, round, iter); //print_full_result(output_fileName_full, &permutation, &true_index, N_obs); } } free(matrix); free(matrix_padded); gsl_matrix_free(matrix_obs); return(0); } double log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_doc, int freq_max) { if (idx1 == idx2) return(0.0); int idx1_m = (*permutation)[idx1]; int idx2_m = (*permutation)[idx2]; int n1 = 2*freq_max - (*matrix)[idx1_m*N_kw + idx1_m]; int n2 = 2*freq_max - (*matrix)[idx2_m*N_kw + idx2_m]; /* int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc); int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper; N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper; int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2); double score = 0; double prob = (*matrix)[idx1_m*N_kw + idx2_m] / (double) N_doc; for (int kk = N_lower; kk < N_upper+1; kk+=20) score += gsl_ran_binomial_pdf(kk, prob, N_doc) * gsl_ran_hypergeometric_pdf(count_total - kk, n1, 2*N_doc - n1, n2); */ double mean = 1.0 * freq_max / N_doc * (n1 + n2); double var = 1.0 * (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]); var += 1.0 * n1 / N_doc * freq_max * (2 * N_doc - 2*freq_max) / N_doc; var += 1.0 * n2 / N_doc * freq_max * (2 * N_doc - 2*freq_max) / N_doc; int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2); int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc); int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper; N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper; mean += (*matrix)[idx1_m*N_kw + idx2_m]; var += (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]); double score = gsl_ran_gaussian_pdf(count_total - mean, sqrt(var)); if (score == 0) return(-500.0); return(log(score)); } void attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_obs, int N_doc, int freq_max, int N_iter) { // Initialise data structures double* score_matrix = (double*) malloc(sizeof(double) * N_obs * N_obs); double* score_row1 = (double*) malloc(sizeof(double) * N_obs); double* score_row2 = (double*) malloc(sizeof(double) * N_obs); int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs); int* permutation_inv = (int*) malloc(sizeof(int) * N_kw); // Initialise permutations for (int ii = 0; ii < N_obs; ii++) (*permutation)[ii] = ii; for (int ii = 0; ii < N_obs; ii++) permutation_tmp[ii] = ii; for (int ii = 0; ii < N_kw; ii++) permutation_inv[ii] = -1; for (int ii = 0; ii < N_obs; ii++) permutation_inv[permutation_tmp[ii]] = ii; // Initialising RNG const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); struct timeval tv1,tv2; gettimeofday(&tv1, NULL); // Compute initial score #pragma omp parallel for shared(score_matrix, matrix_obs, matrix) for (int ii = 0; ii < N_obs * N_obs; ii++) score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, N_kw, N_doc, freq_max); gettimeofday(&tv2, NULL); printf("Initial score computed: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); // Iterations of simulated annealing double temp = (double) N_kw; int N_stuck = 0; for (int iter = 0; iter < N_iter; iter++) { /* Status code */ if (iter % (N_iter / 10) == 0) { gettimeofday(&tv1, NULL); printf("Iteration: %d, %d, %d.\n", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec)); fflush(stdout); gettimeofday(&tv2, NULL); } // used to be 20k if (N_stuck >= 80000) iter = N_iter; /* Main code */ int idx1, idx2; permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, N_kw, N_obs); int ii = 0; #pragma omp parallel for shared(score_row1) for (ii = 0; ii < N_obs; ii++) score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, freq_max); if (idx2 >= 0) #pragma omp parallel for shared(score_row2) for (ii = 0; ii < N_obs; ii++) score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, freq_max); double score_diff = 0; for (int ii = 0; ii < N_obs; ii++) score_diff += score_row1[ii]; for (int ii = 0; ii < N_obs; ii++) score_diff -= score_matrix[idx1*N_obs + ii]; if (idx2 >= 0) { for (int ii = 0; ii < N_obs; ii++) score_diff += score_row2[ii]; for (int ii = 0; ii < N_obs; ii++) score_diff -= score_matrix[idx2*N_obs + ii]; } // compute difference in score, with exponentiation score_diff = score_diff / temp; if (score_diff < -40) score_diff = 0; else if (score_diff > 0) score_diff = 1.01; else score_diff = exp(score_diff); if (gsl_ran_flat(r, 0, 1) < score_diff) { // Update the scores for (int ii = 0; ii < N_obs; ii++) score_matrix[idx1*N_obs + ii] = score_row1[ii]; for (int ii = 0; ii < N_obs; ii++) score_matrix[ii*N_obs + idx1] = score_row1[ii]; if (idx2 >= 0) { for (int ii = 0; ii < N_obs; ii++) score_matrix[idx2*N_obs + ii] = score_row2[ii]; for (int ii = 0; ii < N_obs; ii++) score_matrix[ii*N_obs + idx2] = score_row2[ii]; } // Update the permutation permutation_inv[(*permutation)[idx1]] = -1; (*permutation)[idx1] = permutation_tmp[idx1]; permutation_inv[permutation_tmp[idx1]] = idx1; if (idx2 >= 0) { (*permutation)[idx2] = permutation_tmp[idx2]; permutation_inv[permutation_tmp[idx2]] = idx2; } N_stuck = 0; } else { // Update the permutation permutation_tmp[idx1] = (*permutation)[idx1]; if (idx2 >= 0) permutation_tmp[idx2] = (*permutation)[idx2]; N_stuck += 1; } temp *= 0.995; } free(score_matrix); free(score_row1); free(score_row2); gsl_rng_free(r); } void print_result(char* output_fileName, int** permutation, int** true_index, int N_obs) { FILE* fp = fopen(output_fileName, "w"); int count = 0; for (int ii = 0; ii < N_obs; ii++) if ((*permutation)[ii] == (*true_index)[ii]) count++; fprintf(fp, "%d\n", count); fclose(fp); printf("Success: %d/%d.\n", count, N_obs); } void print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs) { FILE* fp = fopen(output_fileName, "w"); int count = 0; for (int ii = 0; ii < N_obs; ii++) if ((*permutation)[ii] == (*true_index)[ii]) count++; printf("Success: %d/%d.\n", count, N_obs); fprintf(fp, "%d\n", count); for (int ii = 0; ii < N_obs; ii++) fprintf(fp, "%d,%d\n", (*permutation)[ii], (*true_index)[ii]); fclose(fp); }
{ "alphanum_fraction": 0.5677494616, "avg_line_length": 34.7165109034, "ext": "c", "hexsha": "b6f0feacba7587329611e9b25cb6e88463d11b29", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_path": "FP-EMM/attack_mp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_path": "FP-EMM/attack_mp.c", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_path": "FP-EMM/attack_mp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3255, "size": 11144 }
/*========================================================== * Multinomial_gsl.c * * Return multinomially distributed integers based on input probability vector * *========================================================*/ /* */ #include "mex.h" #include "matrix.h" #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> /* For EXIT_FAILURE, EXIT_SUCCESS */ #include "mat.h" // #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_randist.h> #include <time.h> #define pi acos(-1.0) int rlxd_seed(){ int seed; FILE *file_seeds; file_seeds=fopen("/dev/urandom","rb"); // /dev/urandom is designed so that each time it is opened it produces a different random seed fread(&seed, sizeof(int), 1, file_seeds); fclose(file_seeds); return abs(seed); } void Multinomial(unsigned int *n, double N, double *x, mwSize K) { // Multinomial(n,N,x,K); // /* calculate eigenvalues and eigenvectors */ //mexCallMATLAB(2, lhs, 1, &x, "eig"); // printf("N =%f\n",N); // printf("K =%d\n",K); //Initialisation for using gls multinomial function const gsl_rng_type *Type; //initialise a constant Type which holds type of random number generator gsl_rng *r; //Initialise pointer to r which is an "instance" of random number generator //Set seed for random numbers from current time // srand(time(0)); // srand(rlxd_seed()); unsigned long int seed = rlxd_seed(); //initialise integer seed and set to value shown // unsigned long int seed = random_seed(); //initialise integer seed and set to value shown gsl_rng_env_setup(); //read in environmental variables set at command line Type = gsl_rng_default; //set random number generator to default, which is mt19937 r = gsl_rng_alloc (Type); //Allocate memory for type T generator and get pointer gsl_rng_set (r, seed); //initialise random number generator unsigned int NN = N; //Sample size size_t KK =K; // double mx[KK]; //Initialise pointer to mx real positive array of probabilities // unsigned int n[KK]; //Initialise output integer array // printf ("generator type: %s\n", gsl_rng_name (r)); // printf ("seed = %d\n", seed); // printf("NN=%d\n",NN); // printf("KK=%d\n",KK); gsl_ran_multinomial(r, KK, NN, x, n); gsl_rng_free(r); // free(n); // free(mx); } /* The gateway function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* check for proper number of arguments */ if(nrhs!=3) { mexErrMsgIdAndTxt("MyToolbox:Multinomial_gsl:nrhs","Three inputs required."); } if(nlhs!=1) { mexErrMsgIdAndTxt("MyToolbox:Multinomial_gsl:nlhs","One output required."); } /* get input variables */ double N=mxGetScalar(prhs[0]); double *x = mxGetPr(prhs[1]); double K=mxGetScalar(prhs[2]); int *n; mwSize Ka=K; // plhs[0] = mxCreateDoubleMatrix(1, Ka,mxREAL); //mxCreateNumericMatrix is used here as we want to create a vector of integers plhs[0] = mxCreateNumericMatrix(1, Ka, mxUINT32_CLASS, mxREAL); /* get a pointer to the real data in the output matrix */ //As arrays is not DOUBLE then we can't use mxGetPr n = (int*) mxGetData(plhs[0]); Multinomial(n,N,x,Ka); }
{ "alphanum_fraction": 0.5709219858, "avg_line_length": 26.9558823529, "ext": "c", "hexsha": "f7615e8a3bd58107ddc612b732c98ea42814fafb", "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": "1076f8aa4edb942533b4afd56aa5cb54be146176", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BhavKhatri/MutliplexDriveResistanceSims", "max_forks_repo_path": "Multinomial_gsl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1076f8aa4edb942533b4afd56aa5cb54be146176", "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": "BhavKhatri/MutliplexDriveResistanceSims", "max_issues_repo_path": "Multinomial_gsl.c", "max_line_length": 138, "max_stars_count": null, "max_stars_repo_head_hexsha": "1076f8aa4edb942533b4afd56aa5cb54be146176", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "BhavKhatri/MutliplexDriveResistanceSims", "max_stars_repo_path": "Multinomial_gsl.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 934, "size": 3666 }
/* NAME: proj_EM_step PURPOSE: one proj_EM step CALLING SEQUENCE: proj_EM_step(struct datapoint * data, int N, struct gaussian * gaussians, int K,bool * fixamp, bool * fixmean, bool * fixcovar, double * avgloglikedata, bool likeonly, double w, bool noproj, bool diagerrs, bool noweight) INPUT: data - the data N - number of data points gaussians - model gaussians K - number of model gaussians fixamp - fix the amplitude? fixmean - fix the mean? fixcovar - fix the covar? likeonly - only compute likelihood? w - regularization parameter noproj - don't perform any projections diagerrs - the data->SS errors-squared are diagonal noweight - don't use data-weights OUTPUT: avgloglikedata - average loglikelihood of the data REVISION HISTORY: 2008-09-21 - Written Bovy 2010-03-01 Added noproj option - Bovy 2010-04-01 Added noweight option - Bovy */ #ifdef _OPENMP #include <omp.h> #endif #include <math.h> //#include <time.h> //#include <sys/time.h> #include <float.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <proj_gauss_mixtures.h> #define CHUNKSIZE 1 void proj_EM_step(struct datapoint * data, int N, struct gaussian * gaussians, int K,bool * fixamp, bool * fixmean, bool * fixcovar, double * avgloglikedata, bool likeonly, double w, bool noproj, bool diagerrs, bool noweight){ *avgloglikedata = 0.0; //struct timeval start,time1, time2, time3, time4, time5,end; struct datapoint * thisdata; struct gaussian * thisgaussian; struct gaussian * thisnewgaussian; int signum,di; double exponent; double currqij; struct modelbs * thisbs; int d = (gaussians->VV)->size1;//dim of mm //gettimeofday(&start,NULL); //Initialize new parameters int kk; for (kk=0; kk != K*nthreads; ++kk){ newgaussians->alpha = 0.0; gsl_vector_set_zero(newgaussians->mm); gsl_matrix_set_zero(newgaussians->VV); ++newgaussians; } newgaussians= startnewgaussians; //gettimeofday(&time1,NULL); //check whether for some Gaussians none of the parameters get updated double sumfixedamps= 0; bool * allfixed = (bool *) calloc(K, sizeof (bool) ); double ampnorm; for (kk=0; kk != K; ++kk){ if (*fixamp == true){ sumfixedamps += gaussians->alpha; } ++gaussians; if (*fixamp == true && *fixmean == true && *fixcovar == true) *allfixed= true; ++allfixed; ++fixamp; ++fixmean; ++fixcovar; } gaussians -= K; allfixed -= K; fixamp -= K; fixmean -= K; fixcovar -= K; //gettimeofday(&time2,NULL); //now loop over data and gaussians to update the model parameters int ii, jj, ll; double sumSV; int chunk; chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) \ private(tid,di,signum,exponent,ii,jj,ll,kk,Tij,Tij_inv,wminusRm,p,VRTTinv,sumSV,VRT,TinvwminusRm,Rtrans,thisgaussian,thisdata,thisbs,thisnewgaussian,currqij) \ shared(newgaussians,gaussians,bs,allfixed,K,d,data,avgloglikedata) for (ii = 0 ; ii < N; ++ii){ thisdata= data+ii; #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif di = (thisdata->SS)->size1; //printf("Datapoint has dimension %i\n",di); p = gsl_permutation_alloc (di); wminusRm = gsl_vector_alloc (di); TinvwminusRm = gsl_vector_alloc (di); Tij = gsl_matrix_alloc(di,di); Tij_inv = gsl_matrix_alloc(di,di); if ( ! noproj ) VRT = gsl_matrix_alloc(d,di); VRTTinv = gsl_matrix_alloc(d,di); if ( ! noproj ) Rtrans = gsl_matrix_alloc(d,di); for (jj = 0; jj != K; ++jj){ //printf("%i,%i\n",(thisdata->ww)->size,wminusRm->size); gsl_vector_memcpy(wminusRm,thisdata->ww); //fprintf(stdout,"Where is the seg fault?\n"); thisgaussian= gaussians+jj; //prepare... if ( ! noproj ) { if ( diagerrs ) { gsl_matrix_set_zero(Tij); for (ll = 0; ll != di; ++ll) gsl_matrix_set(Tij,ll,ll,gsl_matrix_get(thisdata->SS,ll,0));} else gsl_matrix_memcpy(Tij,thisdata->SS); } //Calculate Tij if ( ! noproj ) { gsl_matrix_transpose_memcpy(Rtrans,thisdata->RR); gsl_blas_dsymm(CblasLeft,CblasUpper,1.0,thisgaussian->VV,Rtrans,0.0,VRT);//Only the upper right part of VV is calculated --> use only that part gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,thisdata->RR,VRT,1.0,Tij);}//This is Tij else { if ( diagerrs ) { for (kk = 0; kk != d; ++kk){ gsl_matrix_set(Tij,kk,kk,gsl_matrix_get(thisdata->SS,kk,0)+gsl_matrix_get(thisgaussian->VV,kk,kk)); for (ll = kk+1; ll != d; ++ll){ sumSV= gsl_matrix_get(thisgaussian->VV,kk,ll); gsl_matrix_set(Tij,kk,ll,sumSV); gsl_matrix_set(Tij,ll,kk,sumSV);}}} else { for (kk = 0; kk != d; ++kk){ gsl_matrix_set(Tij,kk,kk,gsl_matrix_get(thisdata->SS,kk,kk)+gsl_matrix_get(thisgaussian->VV,kk,kk)); for (ll = kk+1; ll != d; ++ll){ sumSV= gsl_matrix_get(thisdata->SS,kk,ll)+gsl_matrix_get(thisgaussian->VV,kk,ll); gsl_matrix_set(Tij,kk,ll,sumSV); gsl_matrix_set(Tij,ll,kk,sumSV);}}}} //gsl_matrix_add(Tij,thisgaussian->VV);} //Calculate LU decomp of Tij and Tij inverse gsl_linalg_LU_decomp(Tij,p,&signum); gsl_linalg_LU_invert(Tij,p,Tij_inv); //Calculate Tijinv*(w-Rm) if ( ! noproj ) gsl_blas_dgemv(CblasNoTrans,-1.0,thisdata->RR,thisgaussian->mm,1.0,wminusRm); else gsl_vector_sub(wminusRm,thisgaussian->mm); //printf("wminusRm = %f\t%f\n",gsl_vector_get(wminusRm,0),gsl_vector_get(wminusRm,1)); gsl_blas_dsymv(CblasUpper,1.0,Tij_inv,wminusRm,0.0,TinvwminusRm); //printf("TinvwminusRm = %f\t%f\n",gsl_vector_get(TinvwminusRm,0),gsl_vector_get(TinvwminusRm,1)); gsl_blas_ddot(wminusRm,TinvwminusRm,&exponent); //printf("Exponent = %f\nDet = %f\n",exponent,gsl_linalg_LU_det(Tij,signum)); gsl_matrix_set(qij,ii,jj,log(thisgaussian->alpha) - di * halflogtwopi - 0.5 * gsl_linalg_LU_lndet(Tij) -0.5 * exponent);//This is actually the log of qij //printf("Here we have = %f\n",gsl_matrix_get(qij,ii,jj)); //Now calculate bij and Bij thisbs= bs+tid*K+jj; gsl_vector_memcpy(thisbs->bbij,thisgaussian->mm); //printf("%i,%i,%i\n",tid,ii,jj); if ( ! noproj ) gsl_blas_dgemv(CblasNoTrans,1.0,VRT,TinvwminusRm,1.0,thisbs->bbij); else gsl_blas_dsymv(CblasUpper,1.0,thisgaussian->VV,TinvwminusRm,1.0,thisbs->bbij); //printf("bij = %f\t%f\n",gsl_vector_get(bs->bbij,0),gsl_vector_get(bs->bbij,1)); gsl_matrix_memcpy(thisbs->BBij,thisgaussian->VV); if ( ! noproj ) { gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,VRT,Tij_inv,0.0,VRTTinv); gsl_blas_dgemm(CblasNoTrans,CblasTrans,-1.0,VRTTinv,VRT,1.0,thisbs->BBij);} else { gsl_blas_dsymm(CblasLeft,CblasUpper,1.0,thisgaussian->VV,Tij_inv,0.0,VRTTinv); gsl_blas_dsymm(CblasRight,CblasUpper,-1.0,thisgaussian->VV,VRTTinv,1.0,thisbs->BBij);} gsl_blas_dsyr(CblasUpper,1.0,thisbs->bbij,thisbs->BBij);//This is bijbijT + Bij, which is the relevant quantity } gsl_permutation_free (p); gsl_vector_free(wminusRm); gsl_vector_free(TinvwminusRm); gsl_matrix_free(Tij); gsl_matrix_free(Tij_inv); if ( ! noproj ) gsl_matrix_free(VRT); gsl_matrix_free(VRTTinv); if ( ! noproj ) gsl_matrix_free(Rtrans); //Again loop over the gaussians to update the model(can this be more efficient? in any case this is not so bad since generally K << N) #pragma omp critical { //Normalize qij properly *avgloglikedata += normalize_row(qij,ii,true,noweight,thisdata->logweight); } //printf("qij = %f\t%f\n",gsl_matrix_get(qij,ii,0),gsl_matrix_get(qij,ii,1)); //printf("avgloglgge = %f\n",*avgloglikedata); for (jj = 0; jj != K; ++jj){ currqij = exp(gsl_matrix_get(qij,ii,jj)); //printf("Current qij = %f\n",currqij); thisbs= bs+tid*K+jj; thisnewgaussian= newgaussians+tid*K+jj; gsl_vector_scale(thisbs->bbij,currqij); gsl_vector_add(thisnewgaussian->mm,thisbs->bbij); gsl_matrix_scale(thisbs->BBij,currqij); gsl_matrix_add(thisnewgaussian->VV,thisbs->BBij); //printf("bij = %f\t%f\n",gsl_vector_get(bs->bbij,0),gsl_vector_get(bs->bbij,1)); //printf("Bij = %f\t%f\t%f\n",gsl_matrix_get(bs->BBij,0,0),gsl_matrix_get(bs->BBij,1,1),gsl_matrix_get(bs->BBij,0,1)); } } *avgloglikedata /= N; if (likeonly) return; //gettimeofday(&time3,NULL); //gather newgaussians if ( nthreads != 1 ) #pragma omp parallel for schedule(static,chunk) \ private(ll,jj) for (jj = 0; jj < K; ++jj) for (ll = 1; ll != nthreads; ++ll) { gsl_vector_add((newgaussians+jj)->mm,(newgaussians+ll*K+jj)->mm); gsl_matrix_add((newgaussians+jj)->VV,(newgaussians+ll*K+jj)->VV); } //gettimeofday(&time4,NULL); //Now update the parameters //Thus, loop over gaussians again! double qj; #pragma omp parallel for schedule(dynamic,chunk) \ private(jj,qj) for (jj = 0; jj < K; ++jj){ if (*(allfixed+jj)){ continue; } else { qj = exp(logsum(qij,jj,false)); (qj < DBL_MIN) ? qj = 0: 0; //printf("qj = %f\n",qj); if (*(fixamp+jj) != true) { (gaussians+jj)->alpha = qj; if (qj == 0) {//rethink this *(fixamp+jj)=1; *(fixmean+jj)=1; *(fixcovar+jj)=1; continue; } } gsl_vector_scale((newgaussians+jj)->mm,1.0/qj); if (*(fixmean+jj) != true){ gsl_vector_memcpy((gaussians+jj)->mm,(newgaussians+jj)->mm); } if (*(fixcovar+jj) != true){ // if (*(fixmean+jj) != true) // gsl_blas_dsyr(CblasUpper,-qj,(gaussians+jj)->mm,(newgaussians+jj)->VV); //else { gsl_blas_dsyr(CblasUpper,qj,(gaussians+jj)->mm,(newgaussians+jj)->VV); gsl_blas_dsyr2(CblasUpper,-qj,(gaussians+jj)->mm,(newgaussians+jj)->mm,(newgaussians+jj)->VV); //} if (w > 0.){ gsl_matrix_add((newgaussians+jj)->VV,I); gsl_matrix_scale((newgaussians+jj)->VV,1.0/(qj+1.0)); } else gsl_matrix_scale((newgaussians+jj)->VV,1.0/qj); gsl_matrix_memcpy((gaussians+jj)->VV,(newgaussians+jj)->VV); } } } //gettimeofday(&time5,NULL); //normalize the amplitudes if ( sumfixedamps == 0. && noweight ){ for (kk=0; kk != K; ++kk){ if ( noweight ) (gaussians++)->alpha /= (double) N; } } else { ampnorm= 0; for (kk=0; kk != K; ++kk){ if (*(fixamp++) == false) ampnorm += gaussians->alpha; ++gaussians; } fixamp -= K; gaussians -= K; for (kk=0; kk != K; ++kk){ if (*(fixamp++) == false){ gaussians->alpha /= ampnorm; gaussians->alpha *= (1. - sumfixedamps); } ++gaussians; } fixamp -= K; gaussians -= K; } //gettimeofday(&end,NULL); //double diff, diff1, diff2, diff3, diff4, diff5,diff6; //diff= difftime (end.tv_sec,start.tv_sec)+difftime (end.tv_usec,start.tv_usec)/1000000; //diff1= (difftime(time1.tv_sec,start.tv_sec)+difftime(time1.tv_usec,start.tv_usec)/1000000)/diff; //diff2= (difftime(time2.tv_sec,time1.tv_sec)+difftime(time2.tv_usec,time1.tv_usec)/1000000)/diff; //diff3= (difftime(time3.tv_sec,time2.tv_sec)+difftime(time3.tv_usec,time2.tv_usec)/1000000)/diff; //diff4= (difftime(time4.tv_sec,time3.tv_sec)+difftime(time4.tv_usec,time3.tv_usec)/1000000)/diff; //diff5= (difftime(time5.tv_sec,time4.tv_sec)+difftime(time5.tv_usec,time4.tv_usec)/1000000)/diff; //diff6= (difftime(end.tv_sec,time5.tv_sec)+difftime(end.tv_usec,time5.tv_usec)/1000000)/diff; //printf("%f,%f,%f,%f,%f,%f,%f\n",diff,diff1,diff2,diff3,diff4,diff5,diff6); free(allfixed); return; }
{ "alphanum_fraction": 0.6524160384, "avg_line_length": 36.5893416928, "ext": "c", "hexsha": "a5963f8d75ceaa3f6ee94152c6d9772c59f4b210", "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": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_forks_repo_path": "src/proj_EM_step.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "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": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_issues_repo_path": "src/proj_EM_step.c", "max_line_length": 161, "max_stars_count": 1, "max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_stars_repo_path": "src/proj_EM_step.c", "max_stars_repo_stars_event_max_datetime": "2016-07-11T14:02:03.000Z", "max_stars_repo_stars_event_min_datetime": "2016-07-11T14:02:03.000Z", "num_tokens": 3945, "size": 11672 }
/** * * @file qwrapper_slange.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Julien Langou * @author Henricus Bouwmeester * @author Mathieu Faverge * @date 2010-11-15 * @generated s Tue Jan 7 11:44:56 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_slange(Quark *quark, Quark_Task_Flags *task_flags, int norm, int M, int N, const float *A, int LDA, int szeA, int szeW, float *result) { szeW = max(1, szeW); DAG_CORE_LANGE; QUARK_Insert_Task(quark, CORE_slange_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, 0); } /***************************************************************************//** * **/ void QUARK_CORE_slange_f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, int M, int N, const float *A, int LDA, int szeA, int szeW, float *result, float *fake, int szeF) { szeW = max(1, szeW); DAG_CORE_LANGE; if ( result == fake ) { QUARK_Insert_Task(quark, CORE_slange_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT | GATHERV, 0); } else { QUARK_Insert_Task(quark, CORE_slange_f1_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, sizeof(float)*szeF, fake, OUTPUT | GATHERV, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slange_quark = PCORE_slange_quark #define CORE_slange_quark PCORE_slange_quark #endif void CORE_slange_quark(Quark *quark) { float *normA; int norm; int M; int N; float *A; int LDA; float *work; quark_unpack_args_7(quark, norm, M, N, A, LDA, work, normA); *normA = LAPACKE_slange_work( LAPACK_COL_MAJOR, lapack_const(norm), M, N, A, LDA, work); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slange_f1_quark = PCORE_slange_f1_quark #define CORE_slange_f1_quark PCORE_slange_f1_quark #endif void CORE_slange_f1_quark(Quark *quark) { float *normA; int norm; int M; int N; float *A; int LDA; float *work; float *fake; quark_unpack_args_8(quark, norm, M, N, A, LDA, work, normA, fake); *normA = LAPACKE_slange_work( LAPACK_COL_MAJOR, lapack_const(norm), M, N, A, LDA, work); }
{ "alphanum_fraction": 0.4607381719, "avg_line_length": 32.0396825397, "ext": "c", "hexsha": "37e814ce52802635f1522686d423a2e8277c10de", "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_slange.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_slange.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_slange.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1009, "size": 4037 }
// SPDX-License-Identifier: Unlicense /* * libinput calibration calculation */ #include <stdio.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> /* * Compute the (Moore-Penrose) pseudo-inverse of a matrix. * * PUBLIC DOMAIN by Charl Linssen <charl@itfromb.it> * * If the singular value decomposition (SVD) of A = UΣVᵀ then the * pseudoinverse A⁻¹ = VΣ⁻¹Uᵀ, where ᵀ indicates transpose and * Σ⁻¹ is obtained by taking the reciprocal of each nonzero element on * the diagonal, leaving zeros in place. Elements on the diagonal smaller * than ``rcond`` times the largest singular value are considered zero. * * @parameter A Input matrix. **WARNING**: the input matrix ``A`` is * destroyed. However, it is still the responsibility of * the caller to free it. * * @parameter rcond A real number specifying the singular value threshold * for inclusion. NumPy default for ``rcond`` is 1E-15. * * @returns A_pinv Matrix containing the result. ``A_pinv`` is allocated * in this function and it is the responsibility of the * caller to free it. * * */ gsl_matrix* moore_penrose_pinv(gsl_matrix *A, const double rcond) { gsl_matrix *V, *Sigma_pinv, *U, *A_pinv; gsl_matrix *_tmp_mat = NULL; gsl_vector *_tmp_vec; gsl_vector *u; double x, cutoff; size_t i, j; unsigned int n = A->size1; unsigned int m = A->size2; unsigned int was_swapped = 0; if (m > n) { /* libgsl SVD can only handle the case m <= n - transpose matrix */ was_swapped = 1; _tmp_mat = gsl_matrix_alloc(m, n); gsl_matrix_transpose_memcpy(_tmp_mat, A); A = _tmp_mat; i = m; m = n; n = i; } /* do SVD */ V = gsl_matrix_alloc(m, m); u = gsl_vector_alloc(m); _tmp_vec = gsl_vector_alloc(m); gsl_linalg_SV_decomp(A, V, u, _tmp_vec); gsl_vector_free(_tmp_vec); /* compute Σ⁻¹ */ Sigma_pinv = gsl_matrix_alloc(m, n); gsl_matrix_set_zero(Sigma_pinv); cutoff = rcond * gsl_vector_max(u); for (i = 0; i < m; ++i) { if (gsl_vector_get(u, i) > cutoff) { x = 1. / gsl_vector_get(u, i); } else { x = 0.; } gsl_matrix_set(Sigma_pinv, i, i, x); } /* libgsl SVD yields "thin" SVD - pad to full matrix by adding zeros */ U = gsl_matrix_alloc(n, n); gsl_matrix_set_zero(U); for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { gsl_matrix_set(U, i, j, gsl_matrix_get(A, i, j)); } } if (_tmp_mat != NULL) { gsl_matrix_free(_tmp_mat); } /* two dot products to obtain pseudoinverse */ _tmp_mat = gsl_matrix_alloc(m, n); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1., V, Sigma_pinv, 0., _tmp_mat); if (was_swapped) { A_pinv = gsl_matrix_alloc(n, m); gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1., U, _tmp_mat, 0., A_pinv); } else { A_pinv = gsl_matrix_alloc(m, n); gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1., _tmp_mat, U, 0., A_pinv); } gsl_matrix_free(_tmp_mat); gsl_matrix_free(U); gsl_matrix_free(Sigma_pinv); gsl_vector_free(u); gsl_matrix_free(V); return A_pinv; } int main(int argc, char **argv) { const unsigned int col = 4; const unsigned int row = 3; const double rcond = 1E-15; const double oneEigth = 1.0/8.0; const double sevenEight = 7.0/8.0; if (argc < 11) { printf("usage: %s x-res y-res x0 y0 x1 y1 x2 y2 x3 y3 [swap-x-y]\n", argv[0]); return EXIT_FAILURE; } int xres = atoi(argv[1]); int yres = atoi(argv[2]); int x0in = atoi(argv[3]); int y0in = atoi(argv[4]); int x1in = atoi(argv[5]); int y1in = atoi(argv[6]); int x2in = atoi(argv[7]); int y2in = atoi(argv[8]); int x3in = atoi(argv[9]); int y3in = atoi(argv[10]); int swapxy = 0; if (argc > 11) swapxy = 1; double x0 = (double)x0in / (double)xres; double y0 = (double)y0in / (double)yres; double x1 = (double)x1in / (double)xres; double y1 = (double)y1in / (double)yres; double x2 = (double)x2in / (double)xres; double y2 = (double)y2in / (double)yres; double x3 = (double)x3in / (double)xres; double y3 = (double)y3in / (double)yres; gsl_matrix *A = gsl_matrix_alloc(row, col); gsl_matrix *C = gsl_matrix_alloc(row, col); gsl_matrix *R = gsl_matrix_alloc(3, 3); gsl_matrix *S; gsl_matrix *T; gsl_matrix *A_pinv; gsl_matrix_set(A, 0, 0, x0); gsl_matrix_set(A, 0, 1, x1); gsl_matrix_set(A, 0, 2, x2); gsl_matrix_set(A, 0, 3, x3); gsl_matrix_set(A, 1, 0, y0); gsl_matrix_set(A, 1, 1, y1); gsl_matrix_set(A, 1, 2, y2); gsl_matrix_set(A, 1, 3, y3); gsl_matrix_set(A, 2, 0, 1.0); gsl_matrix_set(A, 2, 1, 1.0); gsl_matrix_set(A, 2, 2, 1.0); gsl_matrix_set(A, 2, 3, 1.0); gsl_matrix_set(C, 0, 0, oneEigth); gsl_matrix_set(C, 0, 1, sevenEight); gsl_matrix_set(C, 0, 2, oneEigth); gsl_matrix_set(C, 0, 3, sevenEight); gsl_matrix_set(C, 1, 0, oneEigth); gsl_matrix_set(C, 1, 1, oneEigth); gsl_matrix_set(C, 1, 2, sevenEight); gsl_matrix_set(C, 1, 3, sevenEight); gsl_matrix_set(C, 2, 0, 1.0); gsl_matrix_set(C, 2, 1, 1.0); gsl_matrix_set(C, 2, 2, 1.0); gsl_matrix_set(C, 2, 3, 1.0); A_pinv = moore_penrose_pinv(A, rcond); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, C, A_pinv, 0.0, R); if (swapxy) { S = gsl_matrix_alloc(3, 3); /* extra swapping x-y axes as requested */ gsl_matrix_set(S, 0, 0, 0.0); gsl_matrix_set(S, 0, 1, -1.0); gsl_matrix_set(S, 0, 2, 1.0); gsl_matrix_set(S, 1, 0, -1.0); gsl_matrix_set(S, 1, 1, 0.0); gsl_matrix_set(S, 1, 2, 1.0); gsl_matrix_set(S, 2, 0, 0.0); gsl_matrix_set(S, 2, 1, 0.0); gsl_matrix_set(S, 2, 2, 1.0); T = R; R = gsl_matrix_alloc(3, 3); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, T, S, 0.0, R); } printf("%f, %f, %f, %f, %f, %f, %f, %f, %f\n", gsl_matrix_get((const gsl_matrix *)R, 0, 0), gsl_matrix_get((const gsl_matrix *)R, 0, 1), gsl_matrix_get((const gsl_matrix *)R, 0, 2), gsl_matrix_get((const gsl_matrix *)R, 1, 0), gsl_matrix_get((const gsl_matrix *)R, 1, 1), gsl_matrix_get((const gsl_matrix *)R, 1, 2), gsl_matrix_get((const gsl_matrix *)R, 2, 0), gsl_matrix_get((const gsl_matrix *)R, 2, 1), gsl_matrix_get((const gsl_matrix *)R, 2, 2)); gsl_matrix_free(A); gsl_matrix_free(C); gsl_matrix_free(R); gsl_matrix_free(A_pinv); if (swapxy) { gsl_matrix_free(S); gsl_matrix_free(T); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.6482131461, "avg_line_length": 27.7345132743, "ext": "c", "hexsha": "610104bbdd43d15e9d7334ff960326c2d2f78d71", "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": "8b10c8a7530b20a9b25835e47c614e1dd7ec4dd9", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "g0hl1n/xinput_calibrator_libinput", "max_forks_repo_path": "calc_libinput_matrix.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8b10c8a7530b20a9b25835e47c614e1dd7ec4dd9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "g0hl1n/xinput_calibrator_libinput", "max_issues_repo_path": "calc_libinput_matrix.c", "max_line_length": 151, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8b10c8a7530b20a9b25835e47c614e1dd7ec4dd9", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "g0hl1n/xinput_calibrator_libinput", "max_stars_repo_path": "calc_libinput_matrix.c", "max_stars_repo_stars_event_max_datetime": "2021-11-23T14:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-23T14:18:22.000Z", "num_tokens": 2314, "size": 6268 }
#ifndef H_LASER_DATA_JSON #define H_LASER_DATA_JSON #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <json-c/json.h> #include <json-c/json_more_utils.h> #include "laser_data.h" #include "algos.h" /* Laserdata to/from json */ JO ld_to_json(LDP); LDP json_to_ld(JO); JO corr_to_json(struct correspondence*, int n); int json_to_corr(JO jo, struct correspondence*, int n); LDP ld_from_json_stream(FILE*); LDP ld_from_json_string(const char*s); void ld_write_as_json(LDP ld, FILE * stream); /* Other stuff to/from json */ JO matrix_to_json(gsl_matrix*m); JO vector_to_json(gsl_vector*v); JO result_to_json(struct sm_params*p, struct sm_result *r); #endif
{ "alphanum_fraction": 0.7592319055, "avg_line_length": 20.5151515152, "ext": "h", "hexsha": "8e1dfe53bbf7c42614a726f4f93317751eadc797", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ozaslan/basics", "max_forks_repo_path": "csm/sm/csm/laser_data_json.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ozaslan/basics", "max_issues_repo_path": "csm/sm/csm/laser_data_json.h", "max_line_length": 59, "max_stars_count": null, "max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ozaslan/basics", "max_stars_repo_path": "csm/sm/csm/laser_data_json.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 182, "size": 677 }
#include <stdlib.h> #include <math.h> #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_vegas.h> #include "timer.c" #include "timer.h" double g (double *t, size_t dim, void *params); void timer_start(void); double timer_stop(void); int main (void) { double tvegas, tmonte; double res, err; double distmin = 1.001; double distmax = 4.; double dist = distmin; int np = 20; double nt = (distmax - distmin) / ((double) np - 1.); size_t dim = 6; double x1[] = { 0., 0., 0., 0., 0., 0. }; double xu[] = { 1., 1., 1., 1., 1., 1. }; double vegas[20], dipole[20], distance[20], monte[20]; int f = 0; gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2); unsigned long seed = 1UL; gsl_rng_set (r, seed); size_t calls = 1500000; //Vegas Integration gsl_monte_function G = { &g, dim, &dist }; gsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim); gsl_monte_vegas_init (sv); timer_start(); do { gsl_monte_vegas_integrate (&G, x1, xu, dim, calls / 5, r, sv, &res, &err); do { gsl_monte_vegas_integrate (&G, x1, xu, dim, calls, r, sv, &res, &err); fflush (stdout); } while (fabs (gsl_monte_vegas_chisq (sv) - 1.) > .2); vegas[f] = res; f++; dist = dist + nt; } while (dist <= distmax); tvegas = timer_stop(); gsl_monte_vegas_free (sv); // Montecarlo Integration double sum = 0.; double x[6]; long i, j, l; l = 1E6; dist = distmin; timer_start(); for (j = 0; j < np; j++) { sum = 0.; for (i = 0; i < l; i++) { for (int k = 0; k < (int) dim; k++) { x[k] = gsl_rng_uniform (r); } sum += g (x, dim, &dist); } res = sum / (double) l; monte[j] = res; dist += nt; } tmonte = timer_stop(); gsl_rng_free (r); dist = distmin; for (int y = 0; y < np; y++) { dipole[y] = 2. / pow (dist, 3); distance[y] = dist; dist = dist + nt; } printf ("# Dist Vegas Monte Dipolapprox\n"); for (int q = 0; q < np; q++) { double dd = distance[q]; double vv = fabs (vegas[q]); double hh = fabs (monte[q]); double di = fabs (dipole[q]); printf (" %.6f %.6f %.6f %.6f\n", dd, vv, hh, di); } printf("\n\n"); printf("Time for Vegas = %f\n", tvegas); printf("Time for Monte = %f\n", tmonte); printf("Speed up Factor = %f\n", tvegas/tmonte); return 0; }
{ "alphanum_fraction": 0.5307906238, "avg_line_length": 19.8188976378, "ext": "c", "hexsha": "18dd83016abc4c3a69dfef342af94ddf9582a52e", "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": "9a0590d201beff3bb161f8096c0b67961b13d31c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Paulther/fin2", "max_forks_repo_path": "vegas-integral.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9a0590d201beff3bb161f8096c0b67961b13d31c", "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": "Paulther/fin2", "max_issues_repo_path": "vegas-integral.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "9a0590d201beff3bb161f8096c0b67961b13d31c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Paulther/fin2", "max_stars_repo_path": "vegas-integral.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 886, "size": 2517 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018-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 <gsl/gsl-lite.hpp> #include <nlohmann/json_fwd.hpp> #include <cstdint> #include <string> /** * The Event class represents the information needed for a single * audit event entry. */ class Event { public: Event() = delete; /** * Construct and initialize a new Event structure based off the * provided JSON. See ../README.md for information about the * layout of the JSON element. * * @param entry * @throws std::runtime_error for errors accessing the expected * elements */ explicit Event(const nlohmann::json& json); /// The identifier for this entry uint32_t id; /// The name of the entry std::string name; /// The full description of the entry std::string description; /// Set to true if this entry should be handled synchronously bool sync; /// Set to true if this entry is enabled (or should be dropped) bool enabled; /// Set to true if the user may enable filtering for the enry bool filtering_permitted; /// The textual representation of the JSON describing mandatory /// fields in the event (NOTE: this is currently not enforced /// by the audit daemon) std::string mandatory_fields; /// The textual representation of the JSON describing the optional /// fields in the event (NOTE: this is currently not enforced /// by the audit daemon) std::string optional_fields; };
{ "alphanum_fraction": 0.6711133915, "avg_line_length": 33.0338983051, "ext": "h", "hexsha": "930c81359783f88129d98a173d2008d0ba36a8be", "lang": "C", "max_forks_count": 71, "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_path": "auditd/generator/generator_event.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_path": "auditd/generator/generator_event.h", "max_line_length": 79, "max_stars_count": 104, "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": "auditd/generator/generator_event.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "num_tokens": 449, "size": 1949 }
#include <jni.h> #include <assert.h> #include <lapacke.h> /*extern void dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb);*/ JNIEXPORT jint Java_JAMAJni_QRDecomposition_dgeqrf (JNIEnv *env, jclass klass, jint matrix_layout, jint m, jint n, jdoubleArray a, jint lda, jdoubleArray tau){ double *aElems, *tauElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL); assert(aElems && tauElems); info = LAPACKE_dgeqrf ((int) matrix_layout, (lapack_int) m, (lapack_int) n, aElems, (lapack_int) lda, tauElems); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0); return info; } JNIEXPORT jint Java_JAMAJni_QRDecomposition_dorgqr (JNIEnv *env, jclass klass, jint matrix_layout, jint m, jint n, jint k, jdoubleArray a, jint lda, jdoubleArray tau){ double *aElems, *tauElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL); assert(aElems && tauElems); info = LAPACKE_dorgqr((int) matrix_layout, (lapack_int) m, (lapack_int) n, (lapack_int) k, aElems, (lapack_int) lda, tauElems); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0); return info; } JNIEXPORT jint Java_JAMAJni_QRDecomposition_dgeqp3 (JNIEnv *env, jclass klass, jint matrix_layout, jint m, jint n, jdoubleArray a, jint lda, jintArray jpvt, jdoubleArray tau){ double *aElems, *tauElems; lapack_int *jpvtElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL); jpvtElems = (*env)-> GetIntArrayElements (env, jpvt, NULL); assert(aElems && tauElems && jpvtElems); info = LAPACKE_dgeqp3 ((int) matrix_layout, (lapack_int) m, (lapack_int) n, aElems, (lapack_int) lda, jpvtElems, tauElems); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0); (*env)-> ReleaseIntArrayElements (env, jpvt, jpvtElems, 0); return info; } JNIEXPORT jint Java_JAMAJni_QRDecomposition_dormqr (JNIEnv *env, jclass klass, jint matrix_layout, jchar side, jchar trans, jint m, jint n, jint k, jdoubleArray a, jint lda, jdoubleArray tau, jdoubleArray c, jint ldc){ double *aElems, *tauElems, *cElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL); cElems = (*env)-> GetDoubleArrayElements (env, c, NULL); assert(aElems && tauElems && cElems); info = LAPACKE_dormqr ((int) matrix_layout, (char) side, (char) trans, (lapack_int) m, (lapack_int) n, (lapack_int) k, aElems, (lapack_int) lda, tauElems, cElems, (lapack_int) ldc); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0); (*env)-> ReleaseDoubleArrayElements (env, c, cElems, JNI_ABORT); return info; }
{ "alphanum_fraction": 0.5874569992, "avg_line_length": 36.6893203883, "ext": "c", "hexsha": "9e9881fa61ee3c008a74dd103caacd3f952b21db", "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": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_forks_repo_licenses": [ "AAL" ], "max_forks_repo_name": "dw6ja/JAMAJni", "max_forks_repo_path": "src/jni_lapacke/c/QRDecomposition.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "AAL" ], "max_issues_repo_name": "dw6ja/JAMAJni", "max_issues_repo_path": "src/jni_lapacke/c/QRDecomposition.c", "max_line_length": 131, "max_stars_count": null, "max_stars_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_stars_repo_licenses": [ "AAL" ], "max_stars_repo_name": "dw6ja/JAMAJni", "max_stars_repo_path": "src/jni_lapacke/c/QRDecomposition.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1081, "size": 3779 }
#pragma once #include <cassert> #include <stdint.h> #include <gsl/gsl-lite.hpp> // gsl::span #include "HypCommands.h" // RECORD_LENGTH // Utility constexpr function converting a enum class to its underlying type N/U #include <type_traits> template <typename E, typename = std::enable_if_t<std::is_enum<E>::value>> constexpr auto ut(E e) noexcept { return static_cast<std::underlying_type_t<E>>(e); } class SamplePoint { public: explicit SamplePoint(const gsl::span<uint8_t>& data); enum ValueIndex { eSeconds = 0, eVolts , eAmps , emAh_Out , // recalculated emAh_In , // -"- (is rarely present) eRPM , // [] eAltitude, // RDU eTemp1 , // [] eTemp2 , // [] eTemp3 , // [] eThrottle, // [RDU] eTempAmb , // RDU ePowerIn, ePowerOut, // [PRM] eEfficiency,//[PRM] eThrust, // [RPM] eNUM_VALUES }; inline double& operator [](size_t idx) { if (idx < eNUM_VALUES) { return m_values[idx]; } else { assert(!"Invalid index"); static double ERROR = 0.0; return ERROR; } } inline const double& operator [](size_t idx) const { if (idx < eNUM_VALUES) { return m_values[idx]; } else { assert(!"Invalid index"); static const double ERROR = 0.0; return ERROR; } } //static: static const char* SeriesName(size_t idx) { if (idx < eNUM_VALUES) { return sSeriesNames[idx]; } else { return "ERROR"; } } static const std::array<size_t, eNUM_VALUES> sSeriesPrecision; private: std::array<double, eNUM_VALUES> m_values; //static static const std::array<const char*, eNUM_VALUES> sSeriesNames; };
{ "alphanum_fraction": 0.5291411043, "avg_line_length": 25.4025974026, "ext": "h", "hexsha": "580e41f52b52112b82313ecbc145741763b2d8fc", "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": "105124530364cdf9f625a03046b5edba140c9114", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bsergeev/HyperionEmeter2", "max_forks_repo_path": "src/SamplePoint.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "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": "bsergeev/HyperionEmeter2", "max_issues_repo_path": "src/SamplePoint.h", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bsergeev/HyperionEmeter2", "max_stars_repo_path": "src/SamplePoint.h", "max_stars_repo_stars_event_max_datetime": "2021-04-01T08:01:08.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-01T08:01:08.000Z", "num_tokens": 487, "size": 1956 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "viaio/Vlib.h" #include "viaio/VImage.h" #include "viaio/mu.h" #include "viaio/option.h" #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_sort_vector.h> /* two-pass formula, correct for round-off error */ void VNormalize(gsl_vector *vec) { double ave,var,sd,nx,s,u,tiny=1.0e-6; size_t j,nt = vec->size; nx = (double)nt; ave = 0; for (j=0; j<nt; j++) ave += vec->data[j]; ave /= nx; var = u = 0; for (j=0; j<nt; j++) { s = vec->data[j]-ave; u += s; var += s*s; } var=(var-u*u/nx)/(nx-1); sd = sqrt(var); if (sd < tiny) { for (j=0; j<nt; j++) vec->data[j] = 0; } else { for (j=0; j<nt; j++) { u = vec->data[j]; vec->data[j] = (u-ave)/sd; } } } /* convert to ranks for spearman correlation */ void GetRank(gsl_vector *vec,gsl_permutation *perm,gsl_permutation *rank) { size_t i; size_t n = vec->size; gsl_sort_vector_index (perm, vec); gsl_permutation_inverse (rank, perm); for (i=0; i<n; i++) vec->data[i] = (float)rank->data[i]; } size_t NumVoxels(VImage src) { int b,r,c; size_t n=0; for (b=0; b<VImageNBands(src); b++) { for (r=0; r<VImageNRows(src); r++) { for (c=0; c<VImageNColumns(src); c++) { if (VGetPixel(src,b,r,c) > 0.01) n++; } } } return n; } gsl_matrix_float *DataMatrix(VImage *src,int nslices,VImage roi,int metric) { int b,r,c; float u=0; size_t nt = VImageNBands(src[0]); size_t nvox = NumVoxels(roi); gsl_matrix_float *X = gsl_matrix_float_calloc(nvox,nt); if (X==NULL) VError(" error allocating data matrix, size: %lu x %lu\n",nvox,nt); gsl_vector *vec = gsl_vector_calloc(nt); gsl_permutation *perm = NULL; gsl_permutation *rank = NULL; if (metric == 1) { /* only needed for spearman correlation */ perm = gsl_permutation_alloc(nt); rank = gsl_permutation_alloc(nt); } size_t i=0,j=0; for (b=0; b<VImageNBands(roi); b++) { for (r=0; r<VImageNRows(roi); r++) { for (c=0; c<VImageNColumns(roi); c++) { if (VGetPixel(roi,b,r,c) < 0.01) continue; for (j=0; j<nt; j++) { u = (float) VGetPixel(src[b],j,r,c); vec->data[j] = u; } if (metric == 0) { /* linear correlation */ VNormalize(vec); } else if (metric == 1) { /* convert to ranks for Spearman corr */ GetRank(vec,perm,rank); } else { VError(" unknown metric %d",metric); } for (j=0; j<nt; j++) { gsl_matrix_float_set(X,i,j,(float)vec->data[j]); } i++; } } } gsl_vector_free(vec); if (metric==1) { gsl_permutation_free (perm); gsl_permutation_free (rank); } return X; } /* new voxel map */ VImage VoxelMap(VImage roi) { size_t nvox = NumVoxels(roi); VImage map = VCreateImage(1,4,nvox,VShortRepn); if (map == NULL) VError(" error allocating addr map"); VFillImage(map,VAllBands,0); int nslices = VImageNBands(roi); int nrows = VImageNRows(roi); int ncols = VImageNColumns(roi); VSetAttr(VImageAttrList(map),"nvoxels",NULL,VLongRepn,(VLong)nvox); VSetAttr(VImageAttrList(map),"nslices",NULL,VLongRepn,(VLong)nslices); VSetAttr(VImageAttrList(map),"nrows",NULL,VLongRepn,(VLong)nrows); VSetAttr(VImageAttrList(map),"ncols",NULL,VLongRepn,(VLong)ncols); VPixel(map,0,3,0,VShort) = nslices; VPixel(map,0,3,1,VShort) = nrows; VPixel(map,0,3,2,VShort) = ncols; int b,r,c; size_t i = 0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { float u = VGetPixel(roi,b,r,c); if (u < 0.1) continue; VPixel(map,0,0,i,VShort) = b; VPixel(map,0,1,i,VShort) = r; VPixel(map,0,2,i,VShort) = c; i++; } } } return map; }
{ "alphanum_fraction": 0.6110526316, "avg_line_length": 22.4852071006, "ext": "c", "hexsha": "debd81a1782cd78cae22b523abf39e39f4c6018e", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/nets/vbcm/VoxelMap.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/nets/vbcm/VoxelMap.c", "max_line_length": 82, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/nets/vbcm/VoxelMap.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 1369, "size": 3800 }
#ifndef DART_META_H #define DART_META_H /*----- System Includes -----*/ #include <memory> #include <gsl/gsl> #include <type_traits> /*----- Local Includes -----*/ #include "shim.h" /*----- Type Declarations -----*/ namespace dart { namespace meta { template <class...> using void_t = void; template <class T> struct identity { using type = T; }; // Removes one level of "pointer to const", "pointer to volatile" // "reference to const", "reference to volatile", etc, // to make working with strings easier. // Like std::decay except it doesn't decay C arrays, // but it otherwise much stronger. template <class T> struct canonical_type { using type = T; }; template <class T> struct canonical_type<T const> { using type = T; }; template <class T> struct canonical_type<T volatile> { using type = T; }; template <class T> struct canonical_type<T const volatile> { using type = T; }; template <class T> struct canonical_type<T&> { using type = T&; }; template <class T> struct canonical_type<T const&> { using type = T&; }; template <class T> struct canonical_type<T volatile&> { using type = T&; }; template <class T> struct canonical_type<T const volatile&> { using type = T&; }; template <class T> struct canonical_type<T*> { using type = T*; }; template <class T> struct canonical_type<T const*> { using type = T*; }; template <class T> struct canonical_type<T volatile*> { using type = T*; }; template <class T> struct canonical_type<T const volatile*> { using type = T*; }; template <class T, size_t len> struct canonical_type<T (&)[len]> { using type = T (&)[len]; }; template <class T, size_t len> struct canonical_type<T const (&)[len]> { using type = T (&)[len]; }; template <class T, size_t len> struct canonical_type<T volatile (&)[len]> { using type = T (&)[len]; }; template <class T, size_t len> struct canonical_type<T const volatile (&)[len]> { using type = T (&)[len]; }; template <class T, size_t len> struct canonical_type<T (*)[len]> { using type = T (*)[len]; }; template <class T, size_t len> struct canonical_type<T const (*)[len]> { using type = T (*)[len]; }; template <class T, size_t len> struct canonical_type<T volatile (*)[len]> { using type = T (*)[len]; }; template <class T, size_t len> struct canonical_type<T const volatile (*)[len]> { using type = T (*)[len]; }; template <class T> using canonical_type_t = typename canonical_type<T>::type; template <class T> struct is_ptr_to_const : std::false_type {}; template <class T> struct is_ptr_to_const<T const*> : std::true_type {}; // Create type traits to check for each type of comparison. template <class Lhs, class Rhs, class = void> struct are_comparable : std::false_type {}; template <class Lhs, class Rhs> struct are_comparable< Lhs, Rhs, void_t<decltype(std::declval<Lhs>() == std::declval<Rhs>())> > : std::true_type {}; template <class T, class = void> struct is_dereferenceable : std::false_type {}; template <class T> struct is_dereferenceable< T, void_t<decltype(*std::declval<T>())> > : std::true_type {}; template <class...> struct conjunction : std::true_type {}; template <class B1> struct conjunction<B1> : B1 {}; template <class B1, class... Bn> struct conjunction<B1, Bn...> : std::conditional_t< bool(B1::value), conjunction<Bn...>, B1 > {}; template <class...> struct disjunction : std::false_type {}; template <class B1> struct disjunction<B1> : B1 {}; template <class B1, class... Bn> struct disjunction<B1, Bn...> : std::conditional_t< bool(B1::value), B1, disjunction<Bn...> > {}; template <class B> struct negation : std::integral_constant<bool, !bool(B::value)> {}; template <class T, class... Ts> struct contained : disjunction<std::is_same<T, Ts>...> {}; template <class T, class... Ts> struct not_contained : conjunction<negation<std::is_same<T, Ts>>...> {}; template <class... Types> struct types { template <class T, class = std::enable_if_t< contained<T, Types...>::value > > types(T) {} }; template <class... Types> struct not_types { template <class T, class = std::enable_if_t< not_contained<T, Types...>::value > > not_types(T) {} }; template <class...> struct first_type { using type = void; }; template <class T, class... Ts> struct first_type<T, Ts...> { using type = T; }; template <class... Ts> using first_type_t = typename first_type<Ts...>::type; namespace detail { template <class Default, class AlwaysVoid, template <class...> class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template <class Default, template <class...> class Op, class... Args> struct detector<Default, void_t<Op<Args...>>, Op, Args...> { // Note that std::void_t is a C++17 feature using value_t = std::true_type; using type = Op<Args...>; }; } struct nonesuch { nonesuch(nonesuch const&) = delete; nonesuch(nonesuch&&) = delete; ~nonesuch() = delete; }; template <template <class...> class Op, class... Args> using is_detected = typename detail::detector<nonesuch, void, Op, Args...>::value_t; template <template <class...> class Op, class... Args> using detected_t = typename detail::detector<nonesuch, void, Op, Args...>::type; template <class Default, template <class...> class Op, class... Args> using detected_or = detail::detector<Default, void, Op, Args...>; template <class T> using strv_t = decltype(std::declval<T>().strv()); template <class T> using integer_t = decltype(std::declval<T>().integer()); template <class T> using decimal_t = decltype(std::declval<T>().decimal()); template <class T> using boolean_t = decltype(std::declval<T>().boolean()); template <class T> using get_type_t = decltype(std::declval<T>().get_type()); template <class T> struct is_dartlike : meta::conjunction< is_detected<strv_t, T>, is_detected<integer_t, T>, is_detected<decimal_t, T>, is_detected<boolean_t, T>, is_detected<get_type_t, T> > {}; template <class T, template <class> class Template> struct is_specialization_of : std::false_type {}; template <class... Args, template <class> class Template> struct is_specialization_of<Template<Args...>, Template> : std::true_type {}; template <class T, template <template <class> class> class Compound> struct is_higher_specialization_of : std::false_type {}; template <template <class> class Inner, template <template <class> class> class Outer> struct is_higher_specialization_of<Outer<Inner>, Outer> : std::true_type {}; template <class T> struct is_span : std::false_type {}; #ifdef DART_USING_GSL_LITE template <class T> struct is_span<gsl::span<T>> : std::true_type {}; #else template <class T, std::size_t extent> struct is_span<gsl::span<T, extent>> : std::true_type {}; #endif template <class T> struct is_std_smart_ptr : std::false_type {}; template <class T, class Del> struct is_std_smart_ptr<std::unique_ptr<T, Del>> : std::true_type {}; template <class T> struct is_std_smart_ptr<std::shared_ptr<T>> : std::true_type {}; template <class T> struct is_std_smart_ptr<std::weak_ptr<T>> : std::true_type {}; template <size_t pos> struct priority_tag : priority_tag<pos - 1> {}; template <> struct priority_tag<0> {}; namespace detail { template <class T> struct is_builtin_string_impl : std::false_type {}; template <> struct is_builtin_string_impl<char*> : std::true_type {}; template <> struct is_builtin_string_impl<wchar_t*> : std::true_type {}; template <> struct is_builtin_string_impl<char16_t*> : std::true_type {}; template <> struct is_builtin_string_impl<char32_t*> : std::true_type {}; template <size_t len> struct is_builtin_string_impl<char (&)[len]> : std::true_type {}; template <size_t len> struct is_builtin_string_impl<wchar_t (&)[len]> : std::true_type {}; template <size_t len> struct is_builtin_string_impl<char16_t (&)[len]> : std::true_type {}; template <size_t len> struct is_builtin_string_impl<char32_t (&)[len]> : std::true_type {}; } template <class T> struct is_builtin_string : detail::is_builtin_string_impl<canonical_type_t<T>> {}; template <class T> struct is_std_string : std::false_type {}; template <class CharT, class Traits, class Allocator> struct is_std_string<std::basic_string<CharT, Traits, Allocator>> : std::true_type {}; template <class T> struct is_std_string_view : std::false_type {}; template <class CharT, class Traits> struct is_std_string_view<shim::basic_string_view<CharT, Traits>> : std::true_type {}; template <class T> struct is_string : meta::disjunction< is_builtin_string<T>, is_std_string<T>, is_std_string_view<T> > {}; template <class T> struct spannable_value_type { template <class U> static typename U::value_type detect(priority_tag<1>); template <class U> static typename U::element_type detect(priority_tag<0>); template <class U> static nonesuch detect(...); using type = std::remove_cv_t<decltype(detect<T>(priority_tag<1> {}))>; }; template <class T> using spannable_value_type_t = typename spannable_value_type<T>::type; } } #undef DART_COMPARE_HELPER #endif
{ "alphanum_fraction": 0.611003299, "avg_line_length": 29.3618233618, "ext": "h", "hexsha": "35fc5342d323fc1bccc91ba42652e233b1a8a35f", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z", "max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Cfretz244/libdart", "max_forks_repo_path": "include/dart/meta.h", "max_issues_count": 10, "max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Cfretz244/libdart", "max_issues_repo_path": "include/dart/meta.h", "max_line_length": 93, "max_stars_count": 85, "max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Cfretz244/libdart", "max_stars_repo_path": "include/dart/meta.h", "max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z", "num_tokens": 2592, "size": 10306 }
#ifndef _LINEAR_ALGEBRA_HELPERS_H_ #define _LINEAR_ALGEBRA_HELPERS_H_ #include <stddef.h> #ifdef HAVE_LAPACK #include <lapacke.h> #include <cblas.h> #endif /* Define constants */ #define LAH_PI 3.14159265358979323846 /*--- Data types ------------------------------------------------------------*/ #ifdef HAVE_LAPACK typedef size_t lah_index; #else typedef size_t lah_index; #endif /* Choose type of data */ #ifdef USE_SINGLE /* Single or double precission */ typedef float lah_value; #else typedef double lah_value; #endif /* Automatically choose BLAS/Lapack routines based on data type */ /* If not OpenBLAS (cblas, lapacke) is used, * here is the place to account for another calling convention */ #ifdef HAVE_LAPACK #ifdef USE_SINGLE #define GEMM cblas_sgemm #define POTRF LAPACKE_spotrf #define POTRS LAPACKE_spotrs #define GETRF LAPACKE_sgetrf #define GETRS LAPACKE_sgetrs #define GEQRF LAPACKE_sgeqrf #define SYEVR LAPACKE_ssyevr #define GESDD LAPACKE_sgesdd #define LAMCH LAPACKE_slamch #else #define GEMM cblas_dgemm #define POTRF LAPACKE_dpotrf /* Chol Decomposition */ #define POTRS LAPACKE_dpotrs /* Solving Triangular System */ #define GETRF LAPACKE_dgetrf /* LU Decomposition */ #define GETRS LAPACKE_dgetrs /* Solving Triangular System */ #define GEQRF LAPACKE_dgeqrf /* QR factorization */ #define SYEVR LAPACKE_dsyevr /* SVD for matSqrt (symmetric matrix) */ #define GESDD LAPACKE_dgesdd /* General SVD with divide and conquer */ #define LAMCH LAPACKE_dlamch /* Helper to obtain machine precision */ #endif /* end Data_Types*/ #endif /* end HAVE_LAPACK*/ /* Check if called from C++ */ #ifdef __cplusplus extern "C" { #endif /*--- Definitions for Linear Algebra subroutines*/ /* Specifies whether Row- or ColMajor */ typedef enum { lahRowMajor=101, lahColMajor=102 } lah_layout; #define LAH_LAYOUT lahRowMajor /*#define LAH_LAYOUT(A) (((A)->matType & lahTypeColMajor) ? lahColMajor : lahRowMajor) */ #ifdef HAVE_LAPACK #if LAH_LAYOUT == lahColMajor #define LAH_CBLAS_LAYOUT CblasColMajor #define LAH_LAPACK_LAYOUT LAPACK_COL_MAJOR #define LAH_LEADING_DIM(A) ((A)->nR) #else #define LAH_CBLAS_LAYOUT CblasRowMajor #define LAH_LAPACK_LAYOUT LAPACK_ROW_MAJOR #define LAH_LEADING_DIM(A) ((A)->nC) #endif #endif /* Option for LA operations: Transpose Input before Computation or not? */ typedef enum { lahTrans = 'T', lahNorm = 'N' } lah_MatOp; /* Error Types definition*/ typedef enum { lahReturnOk = 0, /* Success */ lahReturnParameterError, /* Wrong Parameters */ lahReturnMathError, /* General Math Error, either error while * computing or prerequisit not met */ lahReturnFPError, /* Error when evaluating function pointer */ lahReturnExternError /* Error when evaluating function pointer */ } lah_Return; typedef enum { /* Properties, which are known in matAlloc */ lahTypeColMajor = 0x01, /* 0000 0001 */ lahTypeNoData = 0x02, /* 0000 0010 */ lahTypeVector = 0x04, /* 0000 0100 */ lahTypeSquare = 0x08, /* 0000 1000 */ /* Properties, which are not known in matAlloc */ lahTypeDiagonal = 0x10, /* 0001 0000 */ lahTypeSymmetric = 0x20, /* 0010 0000 */ lahTypePositive = 0x40, /* 0100 0000 */ lahTypeOrthogonal = 0x80 /* 1000 0000 */ } lah_MatType; /* lah_mat: Matrix format */ typedef struct { lah_index nC; /* Number of Columns */ lah_index nR; /* Number of Rows */ lah_index incRow; /* increment of rows */ lah_index incCol; /* increment of columns */ lah_value *data; /* pointer to data */ lah_MatType matType; /* flags for several properties of Matrix */ } lah_mat; /*---------------------------------------------------------------------------*/ /*--- Common Linear Algebra helpers ----------------------------------------*/ /* If provided, these functions are using a CBLAS/LAPACKE library */ /* else they use a simple handwritten defintion */ /*--------------------------------------------------------------------------*/ /* Computes the general Matrix mulitplikation of form: * C = alpha*C + beta*op(A)*op(B) * similar to the BLAS routine ?gemm. * op(A) = A for transA=koopNorm or op(A) = At for transA = koopTrans */ lah_Return lah_matMul(lah_MatOp transA, lah_MatOp transB, lah_value alpha, lah_value beta, lah_mat *C, lah_mat const *A, lah_mat const *B); /* Adds two matrices C = alpha*A + beta*B */ lah_Return lah_matAdd(lah_mat *C, lah_value alpha, lah_mat const *A, lah_value beta, lah_mat const *B); /* This will return a lah_mat struct At with inverted order * (RowMajor <-> ColMajor). If At is not needed anymore, call free(At) * NOT lah_matFree(At), as this will also delete A->data */ lah_mat *lah_matTrans(lah_mat const *A); /* Computes the Cholesky factorization of the form P = L * Lt * where P is a symmetric positive-definite matrix, L is a lower triangular * matrix and Lt denotes its transpose. */ lah_Return lah_chol(lah_mat *P, lah_index setZero); /* Computes a rank-1 Update to a Cholesky factorization. * Let L is the Cholesky factor of a spd matrix P = L * Lt, then * the update is the Cholesky factor of the matrix P_new = P + x * x' */ lah_Return lah_cholUpdate(lah_mat *L, lah_mat *x, lah_value alpha); /* Computes the Forward Substitution of the linear equation system L * X = B * where L is a lower triangular matrix, * x and b are matrices with the same number of columns. */ lah_Return lah_forwardSub(lah_mat *B, lah_mat const *L); /* Computes an Update to a matrix C of form D = A*C*A'+B */ /* workspace needed for special case C = A*C*A'+B */ lah_Return lah_matUpdate(lah_mat *D, lah_mat const *C, lah_mat const *A, lah_mat const *B, lah_mat *W); /*--------------------------------------------------------------------------*/ /*--- Function only defined for HAVE_LAPACK --------------------------------*/ #ifdef HAVE_LAPACK /* Computes the LU factorization of the form A = L * U, * as an alternative to Cholesky for general matrices*/ lah_Return lah_LU(lah_mat *A, lah_index setZero, lapack_int *ipiv); /* Solves the linear equation system L * X = B * arising from the LU factorization */ /*lah_Return lah_solveLU(lah_mat *X, const lah_mat *L, const lah_mat *B, lah_index *ipiv); */ lah_Return lah_solveLU(lah_mat *B, const lah_mat *L, lapack_int *ipiv); /* Computes the QR factorization of the form A = L * U, * as an alternative to Cholesky for general matrices*/ lah_Return lah_QR(lah_mat *A, lah_value *tau); /* Computes the eigen values and vectors of a symmetric matrix P*/ lah_Return lah_eigenValue(lah_mat *P, lah_value *S, lah_mat *Z); /* Computes the Sqrt of a positive Matrix by computing the eigen values */ lah_Return lah_matSqrt(lah_mat *P, lah_mat *Psqrt, lah_mat *Work); /*General Singular Value Decomposition */ lah_Return lah_SVD(lah_mat *A, lah_mat *U, lah_value *S, lah_mat *Vt); #endif /*--------------------------------------------------------------------------*/ /*--- Helper functions -----------------------------------------------------*/ /*--- Utility functions ---*/ /* allocation for the Matrix struct lah_mat */ lah_mat* lah_matAlloc(lah_index nC, lah_index nR, lah_index AllocData); /* Free all data used bei the Matrix struct lah_mat */ lah_mat* lah_matFree(lah_mat *mat); /* load a matrix from a file */ lah_mat* lah_matLoad(const char *fname); /* Print a lah_mat Matrix struct (used for debugging) */ lah_Return lah_matPrint(lah_mat const *A, lah_index brief); /*--- Noise Generators ---*/ /* Returns a random number from a Gaussian distribution */ lah_value lah_gaussNoise(); /* Returns a random number from a Lorentz (Cauchy) distribution */ lah_value lah_lorentzNoise(); /*--- Property checks ---*/ /* Checks if matrix is symmetric. * It compares with $(precision) significant digits */ lah_index lah_isSymmetric(lah_mat *A, lah_index precision); /* Checks if matrix is positive definite. It tries to compute a Cholesky * factorization, which only works for positive definite matrices*/ lah_index lah_isPositive(lah_mat *A); /*--- Construct different Matrix types ---*/ /* Construct a diagonal matrix from n parameters */ lah_mat *lah_matConstructDiag(lah_index nC, const lah_value *parameter_vec); /* Construct a symmetric Matrix from n(n+1)/2 parameters */ lah_mat *lah_matConstructSy(lah_index nC, const lah_value *parameter_vec); /* Construct a orthogonal Matrix from n(n+1)/2 parameters */ lah_mat *lah_matConstructOrtho(lah_index nC, lah_value *parameter_vec); /* Construct a positive Matrix from n(n+3)/2 parameters */ lah_mat *lah_matConstructPo(lah_index nC, lah_value *parameter_vec); /* Construct a positive Matrix the simple way from a nxn Maxtrix */ lah_mat *lah_matConstructPo_simple(lah_mat *A); /*--- Macro definitions ----------------------------------------------------*/ /* Macro to access element of Matrix A[i,j] */ #define LAH_ENTRY(A, i, j) ((A)->data[(i) * (A)->incRow + (j) * (A)->incCol]) #define LAH_MAX(A, B) (((A) > (B)) ? (A) : (B)) #define LAH_MIN(A, B) (((A) < (B)) ? (A) : (B)) #define LAH_SIGN(A) ((A) < 0) ? (-1) : (1)) /*--- Property MACROS---*/ #define LAH_ISTYPE(A, Type) ((A)->matType & (Type)) /* AND */ #define LAH_SETTYPE(A, Type) ((A)->matType |= (Type)) /* OR */ #define LAH_UNSETTYPE(A, Type) ((A)->matType &= (~Type)) /* NAND */ #define LAH_TOGGLETYPE(A, Type) ((A)->matType ^= (Type)) /* XOR */ /*--- LAPACK_ONLY HEADERS ---*/ #ifdef HAVE_LAPACK #endif /*--------------------------------------------------------------------------*/ #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.6270886574, "avg_line_length": 36.0780141844, "ext": "h", "hexsha": "7a3cc43053e0a21e721dc8f214a0c0c17950a73b", "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": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_path": "Include/lah.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "maj0e/linear-algebra-helpers", "max_issues_repo_path": "Include/lah.h", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_path": "Include/lah.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2614, "size": 10174 }
#include <gsl/gsl_spmatrix.h> #include <munit.h> #include <osqp/cs.h> #include <osqp/osqp.h> #include <unistd.h> #include <qdm.h> #include "test.h" static MunitResult test_qdm_vector_seq( const MunitParameter params[], MUNIT_UNUSED void* fixture ) { double min = atof(munit_parameters_get(params, "qdm_vector_seq_min")); double max = atof(munit_parameters_get(params, "qdm_vector_seq_max")); double delta = atof(munit_parameters_get(params, "qdm_vector_seq_delta")); if (min >= max) { return MUNIT_SKIP; } gsl_vector *seq = qdm_vector_seq(min, max, delta); munit_assert_size(((max - min) / delta) + 1, ==, seq->size); for (size_t i = 0; i < seq->size; i++) { double expecting = min + delta * i; double found = gsl_vector_get(seq, i); munit_logf(MUNIT_LOG_DEBUG, "%.17g", found); munit_assert_double_equal(expecting, found, 3); } return MUNIT_OK; } static MunitResult test_qdm_vector_set_seq( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { gsl_vector *seq = gsl_vector_alloc(10); qdm_vector_set_seq(seq, 0, 9); for (size_t i = 0; i < seq->size; i++) { double expecting = (double)i; double found = gsl_vector_get(seq, i); munit_logf(MUNIT_LOG_DEBUG, "e %.17g f %.17g", expecting, found); munit_assert_double_equal(expecting, found, 3); } qdm_vector_set_seq(seq, 9, 0); for (size_t i = 0; i < seq->size; i--) { double expecting = (double)(9 - i); double found = gsl_vector_get(seq, i); munit_logf(MUNIT_LOG_DEBUG, "e %.17g f %.17g", expecting, found); munit_assert_double_equal(expecting, found, 3); } qdm_vector_set_seq(seq, 0, 1); double data[10] = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, }; for (size_t i = 0; i < seq->size; i--) { double expecting = data[i]; double found = gsl_vector_get(seq, i); munit_logf(MUNIT_LOG_DEBUG, "e %.17g f %.17g", expecting, found); munit_assert_double_equal(expecting, found, 3); } return MUNIT_OK; } static MunitResult test_qdm_matrix_det_tmm( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { int status = 0; /* Zero */ double data_zero[4][3] = { {1,1,1}, {2,2,2}, {3,3,3}, {4,4,4}, }; gsl_matrix_view m = gsl_matrix_view_array((double *)data_zero, 4, 3); double det_zero = 0; status = qdm_matrix_det_tmm(&m.matrix, &det_zero); munit_assert_int(status, ==, 0); munit_assert_double_equal(0, det_zero, 3); /* Non-zero */ double data_nonzero[4][3] = { {1,2,3}, {4,5,2}, {1,1,3}, {1,1,4}, }; m = gsl_matrix_view_array((double *)data_nonzero, 4, 3); double det_nonzero = 0; status = qdm_matrix_det_tmm(&m.matrix, &det_nonzero); munit_assert_int(status, ==, 0); munit_assert_double_equal(271, det_nonzero, 3); return MUNIT_OK; } static MunitResult test_qdm_vector_quantile( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { /* Basic */ double data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; gsl_vector_view v = gsl_vector_view_array((double *)data, 10); gsl_vector *probs = qdm_vector_seq(0, 1, 0.25); gsl_vector *quantiles = qdm_vector_quantile(&v.vector, probs); munit_log(MUNIT_LOG_DEBUG, "basic"); munit_log_vector(MUNIT_LOG_DEBUG, &v.vector); munit_log_vector(MUNIT_LOG_DEBUG, probs); munit_log_vector(MUNIT_LOG_DEBUG, quantiles); munit_assert_int(quantiles->size, ==, 5); double expected[5] = { 1, 3.25, 5.5, 7.75, 10, }; for (size_t i = 0; i < 5; i++) { munit_assert_double_equal(expected[i], gsl_vector_get(quantiles, i), 3); } /* Random */ double rnorm_data[10] = { -1.7792761, -0.9436401, -0.8845596, -0.4213213, -0.1831428, -0.1497455, 0.1402677, 0.4509039, 0.7415657, 0.8864738, }; v = gsl_vector_view_array((double *)rnorm_data, 10); quantiles = qdm_vector_quantile(&v.vector, probs); munit_log(MUNIT_LOG_DEBUG, "random"); munit_log_vector(MUNIT_LOG_DEBUG, &v.vector); munit_log_vector(MUNIT_LOG_DEBUG, probs); munit_log_vector(MUNIT_LOG_DEBUG, quantiles); munit_assert_int(quantiles->size, ==, 5); double rnorm_expected[5] = { -1.7792761, -0.7687500, -0.1664441, 0.3732449, 0.8864738, }; for (size_t i = 0; i < 5; i++) { munit_assert_double_equal(rnorm_expected[i], gsl_vector_get(quantiles, i), 3); } return MUNIT_OK; } static MunitResult test_qdm_vector_sum( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { gsl_vector_view v; double sum = 0.0; /* Basic */ double basic_data[3] = { 1, 2, 3, }; v = gsl_vector_view_array((double *)basic_data, 3); sum = qdm_vector_sum(&v.vector); munit_assert_double(6, ==, sum); /* Interleaved alternating big sign */ double iabs_data[4] = { 1, 1e100, 1, -1e100, }; v = gsl_vector_view_array((double *)iabs_data, 4); sum = qdm_vector_sum(&v.vector); munit_assert_double(2, ==, sum); /* Long sequence */ gsl_vector *ls0_data = qdm_vector_seq(100, 1000, 1); sum = qdm_vector_sum(ls0_data); munit_assert_double(495550, ==, sum); gsl_vector_free(ls0_data); gsl_vector *ls1_data = qdm_vector_seq(10, 100, 0.1); sum = qdm_vector_sum(ls1_data); munit_assert_double_equal(49555, sum, 10); gsl_vector_free(ls1_data); gsl_vector *ls2_data = qdm_vector_seq(1, 10, 0.01); sum = qdm_vector_sum(ls2_data); munit_assert_double_equal(4955.5, sum, 10); gsl_vector_free(ls2_data); gsl_vector *ls3_data = qdm_vector_seq(0.000000001, 0.00000001, 0.00000000001); sum = qdm_vector_sum(ls3_data); munit_assert_double_equal(4.9555e-06, sum, 10); gsl_vector_free(ls3_data); return MUNIT_OK; } static MunitResult test_qdm_matrix_select_upper_triangle( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { double grid_data[] = { 1,2,3, 4,5,6, 7,8,9, }; gsl_matrix_view grid = gsl_matrix_view_array(grid_data, 3, 3); double expected_data[] = { 1,2,3, 0,5,6, 0,0,9, }; gsl_matrix_view expected = gsl_matrix_view_array(expected_data, 3, 3); qdm_matrix_select_upper_triangle(&grid.matrix); for (size_t i = 0; i < 3; i++) { for (size_t j = 0; j < 3; j++) { double e = gsl_matrix_get(&expected.matrix, i, j); double r = gsl_matrix_get(&grid.matrix, i, j); munit_logf(MUNIT_LOG_DEBUG, "(%zu, %zu)", i, j); munit_assert_double(e, ==, r); } } return MUNIT_OK; } static MunitResult test_qdm_matrix_to_csc_matrix( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { int status = 0; int n = 2; int P_nnz = 3; double P_x[3] = {4.0, 1.0, 2.0}; int P_i[3] = {0, 0, 1}; int P_p[3] = {0, 1, 3}; double input_data[] = { 4, 1, 1, 2, }; gsl_matrix_view input = gsl_matrix_view_array(input_data, 2, 2); qdm_matrix_select_upper_triangle(&input.matrix); munit_log(MUNIT_LOG_DEBUG, "input"); qdm_matrix_csv_fwrite(stderr, &input.matrix); csc *result = NULL; status = qdm_matrix_to_csc_matrix(&result, &input.matrix); munit_assert_int(status, ==, 0); munit_assert_int(P_nnz, ==, result->nzmax); munit_assert_int(n, ==, result->n); for (size_t i = 0; i < (size_t)(result->n + 1); i++) { munit_logf(MUNIT_LOG_DEBUG, "result.p[%zu] = %i", i, result->p[i]); munit_assert_int(result->p[i], ==, P_p[i]); } for (size_t i = 0; i < (size_t)result->nzmax; i++) { munit_logf(MUNIT_LOG_DEBUG, "result.i[%zu] = %i", i, result->i[i]); munit_assert_int(result->i[i], ==, P_i[i]); } for (size_t i = 0; i < (size_t)result->nzmax; i++) { munit_logf(MUNIT_LOG_DEBUG, "result.x[%zu] = %.17g", i, result->x[i]); munit_assert_double(result->x[i], ==, P_x[i]); } return MUNIT_OK; } static MunitResult test_qdm_vector_hd5_write( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { int status = 0; double v_data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; gsl_vector_view v = gsl_vector_view_array(v_data, 9); int tf_fd = 0; char tf_name[] = "/tmp/qdm-test-hd5-vector-XXXXXX"; tf_fd = mkstemp(tf_name); close(tf_fd); hid_t tf_file = qdm_data_create_file(tf_name); munit_assert_int(tf_file, >=, 0); unlink(tf_name); hid_t tf_group = qdm_data_create_group(tf_file, "data"); munit_assert_int(tf_group, >=, 0); status = qdm_vector_hd5_write(tf_group, "v", &v.vector); munit_assert_int(status, ==, 0); status = H5Gclose(tf_group); munit_assert_int(status, ==, 0); status = H5Fclose(tf_file); munit_assert_int(status, ==, 0); return MUNIT_OK; } static MunitResult test_qdm_matrix_hd5_write( MUNIT_UNUSED const MunitParameter params[], MUNIT_UNUSED void* fixture ) { int status = 0; double m_data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; gsl_matrix_view m = gsl_matrix_view_array(m_data, 3, 3); int tf_fd = 0; char tf_name[] = "/tmp/qdm-test-hd5-matrix-XXXXXX"; tf_fd = mkstemp(tf_name); close(tf_fd); hid_t tf_file = qdm_data_create_file(tf_name); munit_assert_int(tf_file, >=, 0); unlink(tf_name); hid_t tf_group = qdm_data_create_group(tf_file, "data"); munit_assert_int(tf_group, >=, 0); status = qdm_matrix_hd5_write(tf_group, "m", &m.matrix); munit_assert_int(status, ==, 0); status = H5Gclose(tf_group); munit_assert_int(status, ==, 0); status = H5Fclose(tf_file); munit_assert_int(status, ==, 0); return MUNIT_OK; } static char *test_param_qdm_vector_seq_min[] = { "1", "10", "0.1", NULL, }; static char *test_param_qdm_vector_seq_max[] = { "10", "20", "1.1", NULL, }; static char *test_param_qdm_vector_seq_delta[] = { "1", "0.1", "2", NULL, }; static MunitParameterEnum test_params_qdm_vector_seq[] = { { "qdm_vector_seq_min" , test_param_qdm_vector_seq_min } , { "qdm_vector_seq_max" , test_param_qdm_vector_seq_max } , { "qdm_vector_seq_delta" , test_param_qdm_vector_seq_delta } , { NULL , NULL } , }; MunitTest tests_gsl[] = { { "/qdm_vector_seq" , // name test_qdm_vector_seq , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options test_params_qdm_vector_seq , // parameters }, { "/qdm_vector_set_seq", // name test_qdm_vector_set_seq, // test NULL, // setup NULL, // tear_down MUNIT_TEST_OPTION_NONE, // options NULL, // parameters }, { "/qdm_matrix_det_tmm" , // name test_qdm_matrix_det_tmm , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options NULL , // parameters }, { "/qdm_vector_quantile" , // name test_qdm_vector_quantile , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options NULL , // parameters }, { "/qdm_vector_sum" , // name test_qdm_vector_sum , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options NULL , // parameters }, { "/qdm_matrix_select_upper_triangle" , // name test_qdm_matrix_select_upper_triangle , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options NULL , // parameters }, { "/qdm_matrix_to_csc_matrix" , // name test_qdm_matrix_to_csc_matrix , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options NULL , // parameters }, { "/qdm_vector_hd5_write" , // name test_qdm_vector_hd5_write , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options NULL , // parameters }, { "/qdm_matrix_hd5_write" , // name test_qdm_matrix_hd5_write , // test NULL , // setup NULL , // tear_down MUNIT_TEST_OPTION_NONE , // options NULL , // parameters }, { NULL, NULL, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL }, }; static const MunitSuite test_suite_gsl = { "/gsl" , // name tests_gsl , // tests NULL , // suites 1 , // iterations MUNIT_SUITE_OPTION_NONE , // options };
{ "alphanum_fraction": 0.6046099291, "avg_line_length": 23.3309352518, "ext": "c", "hexsha": "04f51722ec2877d5cab9fd4b8e4a220141e7079d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "test/test_gsl.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "test/test_gsl.c", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "test/test_gsl.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4126, "size": 12972 }
static char help[] = "Newton's method for a two-variable system. Implements analytical Jacobian.\n" "Adds struct to hold parameter.\n"; #include <petsc.h> typedef struct { double b; } AppCtx; extern PetscErrorCode FormFunction(SNES, Vec, Vec, void*); extern PetscErrorCode FormJacobian(SNES, Vec, Mat, Mat, void*); //STARTMAIN int main(int argc,char **argv) { SNES snes; // nonlinear solver context Vec x,r; // solution, residual vectors Mat J; AppCtx user; PetscErrorCode ierr; PetscInitialize(&argc,&argv,NULL,help); user.b = 2.0; ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr); ierr = VecSetSizes(x,PETSC_DECIDE,2); CHKERRQ(ierr); ierr = VecSetFromOptions(x); CHKERRQ(ierr); ierr = VecDuplicate(x,&r); CHKERRQ(ierr); ierr = MatCreate(PETSC_COMM_WORLD,&J); CHKERRQ(ierr); ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,2,2); CHKERRQ(ierr); ierr = MatSetFromOptions(J); CHKERRQ(ierr); ierr = MatSetUp(J); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetFunction(snes,r,FormFunction,&user);CHKERRQ(ierr); ierr = SNESSetJacobian(snes,J,J,FormJacobian,&user);CHKERRQ(ierr); ierr = SNESSetFromOptions(snes);CHKERRQ(ierr); ierr = VecSet(x,1.0);CHKERRQ(ierr); ierr = SNESSolve(snes,NULL,x);CHKERRQ(ierr); ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr); VecDestroy(&x); VecDestroy(&r); SNESDestroy(&snes); MatDestroy(&J); return PetscFinalize(); } //ENDMAIN //STARTFORM PetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) { PetscErrorCode ierr; AppCtx *user = (AppCtx*)ctx; const double b = user->b, *ax; double *aF; ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr); ierr = VecGetArray(F,&aF);CHKERRQ(ierr); aF[0] = (1.0 / b) * PetscExpReal(b * ax[0]) - ax[1]; aF[1] = ax[0] * ax[0] + ax[1] * ax[1] - 1.0; ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr); ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr); return 0; } PetscErrorCode FormJacobian(SNES snes, Vec x, Mat J, Mat P, void *ctx) { PetscErrorCode ierr; AppCtx *user = (AppCtx*)ctx; const double b = user->b, *ax; double v[4]; int row[2] = {0,1}, col[2] = {0,1}; ierr = VecGetArrayRead(x,&ax); CHKERRQ(ierr); v[0] = PetscExpReal(b * ax[0]); v[1] = -1.0; v[2] = 2.0 * ax[0]; v[3] = 2.0 * ax[1]; ierr = VecRestoreArrayRead(x,&ax); CHKERRQ(ierr); ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr); ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (J != P) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } return 0; } //ENDFORM
{ "alphanum_fraction": 0.6475095785, "avg_line_length": 33, "ext": "c", "hexsha": "42854af8d91952e54e5e2c2a9e8836915d7062bb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_path": "c/ch4/ecjac.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_path": "c/ch4/ecjac.c", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_path": "c/ch4/ecjac.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 914, "size": 2871 }
// // Created by L.Jonathan Feldstein // #ifndef CIMPLE_SYSTEM_H #define CIMPLE_SYSTEM_H #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> #include "cimple_polytope_library.h" // EXAMPLE ALLOCATION FOR STRUCT // Try to allocate structure. // struct struct_name *return_**** = malloc(sizeof(struct)); // Try to allocate data, free structure if fail. // return_****->**** = malloc(***); // Free structure if fail, return NULL // if (return_****->**** == NULL){ // return NULL; //} /** * Functions that help perform several mathematical operations * on the way to calculating the input. */ typedef struct auxiliary_matrices{ gsl_matrix * A_K; gsl_matrix * A_N; gsl_matrix * Ct; /* B_diag = B E_diag = E for i in range(N-1): B_diag = _block_diag2(B_diag, B) E_diag = _block_diag2(E_diag, E) */ gsl_matrix * B_diag; gsl_matrix * E_diag; gsl_matrix * L_default; gsl_matrix * E_default; //LU = ([Uset->size1*N, n+N*m]) gsl_matrix * LU; //MU = tile(Uset->G, N) gsl_vector * MU; //GU = ([Uset->size1*N, p*N]) gsl_matrix * GU; //K_hat = tile(K, N) gsl_vector * K_hat; }auxiliary_matrices; /** * Cost function to be minimized: * * |Rx|_{ord} + |Qu|_{ord} + r'x + mid_weight * |xc - x(N)|_{ord} * * R: state cost matrix for: * x = [x(1)' x(2)' .. x(N)']' * If empty, zero matrix is used. * dim[N*n x N*n] (n = x.size) * * r: cost vector for state trajectory: * x = [x(1)' x(2)' .. x(N)']' * r: size (N*xdim x 1) * * Q: input cost matrix for control input:: * u = [u(0)' u(1)' .. u(N-1)']' * If empty, identity matrix is used. * dim[N*m x N*m] m = u.size * * distance_error_weight: cost weight for |x(N)-xc|_{ord} * * ord: norm used for cost function: ord in {1, 2, INFINITY} */ typedef struct cost_function{ gsl_matrix *R; gsl_matrix *Q; gsl_vector *r; double distance_error_weight; }cost_function; /** * Abstraction of the system * contains all the polytopes * * number_of_region = total number of possible states that can be reached * regions: array of region, each containing one or multiple polytopes * * closed_loop: if 'true' only first input of next N calculated inputs is applied. * All others are discarded. * conservative: if 'true' x(0)...x(N-1) are in starting polytope, x(N) is in final polytope * if false x(1)...x(N-1) can be anywhere * * ord: norm that is used for minimizing cost function in {1, 2, INFINITY} * * time_horizon: number of next steps that are taken into account in calculation of the path */ typedef struct discrete_dynamics{ int abstract_states_count; int number_of_original_regions; abstract_state **abstract_states_set; abstract_state **original_regions; int closed_loop; int conservative; int ord; size_t time_horizon; }discrete_dynamics; /** * Dynamics of the system * * x(t+1) = Ax(t) + Bu(t) + E * * A system dynamics * B input dynamics * E disturbance * U_set, W_set constraints on states and inputs * aux_matrices: auxiliary matrices to fasten calculation of next input */ typedef struct system_dynamics{ gsl_matrix *A; gsl_matrix *B; gsl_matrix *E; gsl_vector *K; polytope *W_set; polytope *U_set; auxiliary_matrices *aux_matrices; }system_dynamics; /** * State plant is in at the beginning of the calculation * * current_abs_state starting region */ typedef struct current_state{ int current_abs_state; gsl_vector *x; } current_state; /** * @brief "Constructor" Dynamically allocates the memory all auxiliary matrices need * @param n s_dyn.A.size2 * @param p s_dyn.E.size2 * @param m s_dyn.B.size2 * @param u_set_size Uset.size1 * @param N time horizon * @return */ struct auxiliary_matrices *aux_matrices_alloc(size_t n, size_t p, size_t m, size_t u_set_size, size_t N); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the auxiliary matrices * @param aux_matrices */ void aux_matrices_free(auxiliary_matrices *aux_matrices); /** * @brief "Constructor" Dynamically allocates the memory the complete system dynamics need * @param n * @param m * @param p * @param w_set_size * @param u_set_size * @param N * @return */ struct system_dynamics *system_dynamics_alloc (size_t n, size_t m, size_t p, size_t w_set_size, size_t u_set_size, size_t N); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the system dynamics * @param system_dynamics */ void system_dynamics_free(system_dynamics * system_dynamics); /** * @brief "Constructor" Dynamically allocates the memory for the state of the plant * @param n * @param abstract_state * @return */ struct current_state *state_alloc(size_t n, int abstract_state); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the state of the plant * @param state */ void state_free(current_state *state); /** * @brief "Constructor" Dynamically allocates the memory for cost function matrices * @param n * @param m * @param N * @param distance_error_weight * @return */ struct cost_function *cost_function_alloc(size_t n,size_t m, size_t N, double distance_error_weight); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the cost function matrices * @param cost_function */ void cost_function_free(cost_function *cost_function); /** * @brief "Constructor" Dynamically allocates the memory for the discrete abstraction of the system * @param polytopes_in_region * @param polytope_sizes * @param hull_sizes * @param orig_polytopes_in_region * @param orig_polytope_sizes * @param orig_hull_sizes * @param n * @param abstract_states_count * @param number_of_original_regions * @param closed_loop * @param conservative * @param ord * @param time_horizon * @return */ struct discrete_dynamics *discrete_dynamics_alloc(int *polytopes_in_region, size_t *polytope_sizes, size_t *hull_sizes, int *orig_polytopes_in_region, size_t *orig_polytope_sizes, size_t *orig_hull_sizes, int *transitions_in_sizes, int *transitions_out_sizes, size_t n, int abstract_states_count, int number_of_original_regions, int closed_loop, int conservative, int ord, size_t time_horizon); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the discrete dynamics * @param d_dyn */ void discrete_dynamics_free(discrete_dynamics *d_dyn); /** * */ typedef struct control_computation_arguments{ gsl_matrix *u; current_state * now; discrete_dynamics *d_dyn; system_dynamics *s_dyn; int target_abs_state; cost_function * f_cost; size_t current_time_horizon; polytope **polytope_list_backup; }control_computation_arguments; typedef struct total_safemode_computation_arguments{ current_state *now; gsl_matrix *u; polytope *current; polytope *safe; system_dynamics *s_dyn; size_t time_horizon; cost_function *f_cost; polytope **polytope_list_backup; }total_safemode_computation_arguments; typedef struct next_safemode_computation_arguments{ current_state *now; gsl_matrix *u; system_dynamics *s_dyn; size_t time_horizon; cost_function *f_cost; polytope **polytope_list_backup; }next_safemode_computation_arguments; /** * "Constructor" Dynamically allocates the space for the get_input thread */ struct control_computation_arguments *cc_arguments_alloc(current_state *now, gsl_matrix* u, system_dynamics *s_dyn, discrete_dynamics *d_dyn, cost_function *f_cost, size_t current_time_horizon, int target_abs_state, polytope **polytope_list); /** * "Constructor" Dynamically allocates the space for the arguments of the safemode computation thread */ struct total_safemode_computation_arguments *sm_arguments_alloc(current_state *now, gsl_matrix * u, polytope *current, polytope *safe, system_dynamics * s_dyn, size_t time_horizon, cost_function *f_cost, polytope **polytope_list_safemode); /** * "Constructor" Dynamically allocates the space for the arguments of the next step towards safemode computation thread */ struct next_safemode_computation_arguments *next_sm_arguments_alloc(current_state *now, gsl_matrix * u, system_dynamics * s_dyn, size_t time_horizon, cost_function *f_cost, polytope **polytope_list_safemode); #endif //CIMPLE_SYSTEM_H
{ "alphanum_fraction": 0.5614100532, "avg_line_length": 30.6371428571, "ext": "h", "hexsha": "002af29f31936abc55ba87a18d44f04e65665297", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_path": "Interface/Cimple/cimple_system.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_path": "Interface/Cimple/cimple_system.h", "max_line_length": 119, "max_stars_count": 1, "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_path": "Interface/Cimple/cimple_system.h", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "num_tokens": 2239, "size": 10723 }
#include <stdio.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_rng.h> #define NUM 5 int main() { int i; double data[NUM]; double mean, variance, largest, smallest; gsl_rng* r = gsl_rng_alloc(gsl_rng_default); for (i = 0; i < NUM; ++i) data[i] = gsl_rng_uniform(r); mean = gsl_stats_mean(data, 1, NUM); variance = gsl_stats_variance(data, 1, NUM); largest = gsl_stats_max(data, 1, NUM); smallest = gsl_stats_min(data, 1, NUM); printf("The data set is"); for (i = 0; i < NUM; ++i) printf(" %6.3f", data[i]); printf("\n"); printf("Mean: %6.3f\n", mean); printf("Variance: %6.3f\n", variance); printf("Max value:%6.3f\n", largest); printf("Min value:%6.3f\n", smallest); return 0; }
{ "alphanum_fraction": 0.6273972603, "avg_line_length": 23.5483870968, "ext": "c", "hexsha": "6883e512eb2578235df87ad8e0a5a6c588287383", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_forks_repo_licenses": [ "FSFAP" ], "max_forks_repo_name": "julnamoo/practice-linux", "max_forks_repo_path": "src_book0/ex10/list1032/list1032C.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "FSFAP" ], "max_issues_repo_name": "julnamoo/practice-linux", "max_issues_repo_path": "src_book0/ex10/list1032/list1032C.c", "max_line_length": 57, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_stars_repo_licenses": [ "FSFAP" ], "max_stars_repo_name": "julnamoo/practice-linux", "max_stars_repo_path": "src_book0/ex10/list1032/list1032C.c", "max_stars_repo_stars_event_max_datetime": "2018-09-14T05:43:58.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-14T05:43:58.000Z", "num_tokens": 244, "size": 730 }
/* We are using the OpenCV implementation and adding gridding to the feature detection. Modified : computeKeyPoints Added methods : keepBestKeyPoints and subimageToImageCoordinates */ /********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage 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 OWNER 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. *********************************************************************/ /** Authors: Ethan Rublee, Vincent Rabaud, Gary Bradski */ #pragma once #include "Utils\thread_memory.h" #include "ImageData.h" #include <iterator> #include <opencv2\core\types.hpp> #include <gsl\gsl> namespace UnitTests { class OpenCVModifiedUnitTest; class OrbFeatureDetectorUnitTest; } class OrbDetector { using ImageData = mage::ImageData<mage::ImageAllocator>; public: OrbDetector( unsigned int gaussianKernelSize, unsigned int nfeatures, float scaleFactor, unsigned int nlevels, unsigned int patchSize, unsigned int fastThreshold, bool useOrientation, float featureFactorANMS, float featureStrengthANMS, int strongResponseANMS, float minRobustFactor, float maxRobustFactor, int numCellsX, int numCellsY); // Compute the ORB_Impl features and descriptors on an image void DetectAndCompute( mage::thread_memory memory, ImageData& imageData, const cv::Mat& image); private: void ComputeKeyPoints(const cv::Mat& imagePyramid, gsl::span<const cv::Rect> layerInfo, gsl::span<const float> layerScale, mage::thread_memory memory, ImageData& result); static void ResizeAndComputeOrbDescriptorsPrerotated( const cv::Mat& image, gsl::span<const cv::KeyPoint> keypoints, gsl::span<mage::ORBDescriptor> descriptors, const std::vector<std::vector<signed char>>& scaledPatterns, size_t dsize, float upScale); // amount to upscale the source image static void ComputeOrbDescriptorsPrerotated( const cv::Mat& imagePyramid, gsl::span<const cv::Rect> layerInfo, gsl::span<const float> layerScale, gsl::span<const cv::KeyPoint> keypoints, gsl::span<mage::ORBDescriptor> descriptors, const signed char* _patternRotated, size_t dsize); static void ComputeOrbDescriptors( const cv::Mat& imagePyramid, gsl::span<const cv::Rect> layerInfo, gsl::span<const float> layerScale, gsl::span<const cv::KeyPoint> keypoints, gsl::span<mage::ORBDescriptor> descriptors, gsl::span<const cv::Point> _pattern, size_t dsize); static void ICAngles( const cv::Mat& img, gsl::span<const cv::Rect> layerinfo, gsl::span<const int> u_max, int half_k, gsl::span<cv::KeyPoint> pts); static void HarrisResponses( const cv::Mat& img, gsl::span<const cv::Rect> layerinfo, gsl::span<cv::KeyPoint> pts, int blockSize, float harris_k); static void MakeRandomPattern(int patchSize, cv::Point* pattern, int npoints); enum class FeatureType { TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2 }; void AdaptiveNonMaximalSuppresion(mage::temp::vector<cv::KeyPoint>& keypoints, unsigned int numToKeep, int threshold, mage::thread_memory memory); void FAST( const cv::Mat& img, mage::temp::vector<cv::KeyPoint>& keypoints, int threshold, bool nonmax_suppression, uchar* threshold_tab, mage::thread_memory& memory, FeatureType type = FeatureType::TYPE_9_16); const unsigned int m_gaussianKernelSize; const unsigned int m_nfeatures; const float m_scaleFactor; const unsigned int m_nlevels; const unsigned int m_patchSize; const unsigned int m_fastThreshold; const bool m_useOrientation; const float m_featureFactorANMS; const float m_featureStrengthANMS; const int m_strongResponseANMS; const float m_minRobustFactorANMS; const float m_maxRobustFactorANMS; const int m_numCellsX; const int m_numCellsY; friend class ::UnitTests::OpenCVModifiedUnitTest; friend class ::UnitTests::OrbFeatureDetectorUnitTest; };
{ "alphanum_fraction": 0.6816473001, "avg_line_length": 33.44, "ext": "h", "hexsha": "58b3e7331fd2edde9e06407a0d7f04e2f5cbeffa", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Image/OpenCVModified.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Image/OpenCVModified.h", "max_line_length": 82, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Image/OpenCVModified.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": 1324, "size": 5852 }
/* * The MIT License is a permissive free software license, which permits reuse * within both open source and proprietary software. The software is licensed * as is, and no warranty is given as to fitness for purpose or absence of * infringement of third parties' rights, such as patents. Generally use for * research activities is allowed regardless of any third party patents, but * commercial use may be subject to a separate license. * * * The MIT License (MIT) * * Copyright (c) 2015 Tuomo Raitio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * * * * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * GlottHMM Speech Parameter Extractor * <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> * * This program reads a speech file and extracts speech * parameters using glottal inverse filtering. * * This program has been written in Aalto University, * Department of Signal Processign and Acoustics, Espoo, Finland * * Author: Tuomo Raitio * Acknowledgements: Antti Suni, Paavo Alku, Martti Vainio * * File Analysis.c * Version: 1.1 * */ /***********************************************/ /* INCLUDE */ /***********************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <sndfile.h> /* Read and write wav */ #include <gsl/gsl_vector.h> /* GSL, Vector */ #include <gsl/gsl_matrix.h> /* GSL, Matrix */ #include <gsl/gsl_fft_real.h> /* GSL, FFT */ #include <libconfig.h> /* Configuration file */ #include "AnalysisFunctions.h" /*******************************************************************/ /* MAIN */ /*******************************************************************/ int main(int argc, char *argv[]) { /* Check command line format */ if(Check_command_line(argc) == EXIT_FAILURE) return EXIT_FAILURE; /* Read default configuration file and assign parameters */ struct config_t *conf_def = Read_config(argv[2]); if(conf_def == NULL) return EXIT_FAILURE; PARAM params; if(Assign_config_parameters(conf_def,&params,DEF_CONF) == EXIT_FAILURE) { config_destroy(conf_def); free(conf_def); return EXIT_FAILURE; } /* Read user configuration file and assign parameters */ if(argc == 4) { struct config_t *conf_usr = Read_config(argv[3]); if(conf_usr == NULL) return EXIT_FAILURE; if(Assign_config_parameters(conf_usr,&params,USR_CONF) == EXIT_FAILURE) { config_destroy(conf_usr); free(conf_usr); return EXIT_FAILURE; } } /* Check the validity of the parameters */ if(Check_parameter_validity(&params) == EXIT_FAILURE) return EXIT_FAILURE; /* Read soundfile, define sampling frequency, invert signal if requested */ gsl_vector *signal = Read_soundfile(argv[1], &params); if(signal == NULL) return EXIT_FAILURE; /* Read external F0 file if requested */ gsl_vector *fundf; if(Read_external_f0(&fundf,&params) == EXIT_FAILURE) { gsl_vector_free(signal); return EXIT_FAILURE; } /* High-pass filtering */ if(HighPassFilter(signal,&params) == EXIT_FAILURE) { gsl_vector_free(signal); return EXIT_FAILURE; } /*******************************************************************/ /* ALLOCATE MEMORY */ /*******************************************************************/ /* Allocate memory for variables */ int i,j,index; double f0 = 0; gsl_vector *frame,*frame0,*glottal,*gain,*uvgain,*f0_frame,*glottal_f0,*f0_frame0,*glottsig,*glottsig_f0; gsl_vector *source_signal,*h1h2,*naq,*ph1h2,*pnaq; gsl_matrix *fundf_candidates, *LSF, *LSF2, *bp_gain, *spectral_tilt, *HNR, *waveform, *harmonics, *fftmatrix_vt, *fftmatrix_src, *fftmatrix_uv; Allocate_variables(&frame,&frame0,&glottal,&gain,&uvgain,&f0_frame,&glottal_f0,&f0_frame0,&glottsig, &glottsig_f0,&source_signal,&fundf_candidates,&LSF,&LSF2,&bp_gain,&spectral_tilt,&HNR, &waveform,&harmonics,&h1h2,&naq,&fftmatrix_vt,&fftmatrix_src,&fftmatrix_uv,&params); /*******************************************************************/ /* ALLOCATE PULSE LIBRARY */ /*******************************************************************/ /* Allocate memory for pulse library variables */ gsl_vector *pulse_inds,*pulse_lengths,*pulse_pos,*pgain; gsl_matrix *gpulses,*gpulses_rs,*plsf,*ptilt,*pharm,*phnr,*pwaveform; Allocate_pulselib_variables(&gpulses,&gpulses_rs,&pulse_inds,&pulse_pos,&pulse_lengths, &plsf,&ptilt,&pharm,&phnr,&pwaveform,&pgain,&ph1h2,&pnaq,&params); /********************************************************************/ /* EXTRACT PARAMETERS */ /********************************************************************/ /* Analysis: Start reading signal vector */ for(index=0; index<params.n_frames; index++) { /* Print progress */ Print_progress(index,params.n_frames,argv[1],params.FS); /* Get samples to frames */ Get_samples_to_frames(signal,frame,frame0,f0_frame,f0_frame0,params.shift,index); /* Gain extraction */ Gain(frame, gain, index, USE_WINDOWING); UnvoicedGain(frame, uvgain, index, USE_WINDOWING, params.unvoiced_frame_length); BandPassGain(frame, bp_gain, &params, index); /* Preliminary inverse filtering for GCI detection (e.g. in GCI-weighted SWLP) */ if(params.lp_method == LP_METHOD_ID_WLP && params.lp_weighting == LP_WEIGHTING_ID_GCI) { InverseFiltering_long(f0_frame, f0_frame0, glottsig_f0, fundf, glottsig, index, &params); FundF(glottsig_f0, frame, fundf_candidates, fundf, bp_gain, index, &params); InverseFiltering_long(frame, frame0, glottsig, fundf, glottsig, index, &params); } /* Inverse filtering */ InverseFiltering(frame, frame0, glottal, LSF, LSF2, spectral_tilt, fundf, glottsig, fftmatrix_vt, fftmatrix_src, fftmatrix_uv, index, &params); InverseFiltering_long(f0_frame, f0_frame0, glottal_f0, fundf, glottsig_f0, index, &params); /* Fundamental frequency estimation. Define a f0 value for the frame (even if unvoiced) */ FundF(glottal_f0, frame, fundf_candidates, fundf, bp_gain, index, &params); f0 = Define_current_f0(fundf,f0,index); /* Estimate Harmonic-to-Noise Ratio (HNR) and magnitudes of the first N harmonics */ Harmonic_analysis(glottal_f0, harmonics, HNR, h1h2, f0, params.FS, index); /* Extract pulses, pitch-synchronous spectrum estimation */ Extract_pulses(f0_frame,glottal_f0,fundf,naq,gpulses,gpulses_rs,pulse_pos,pulse_inds,pulse_lengths, plsf,ptilt,pharm,phnr,pgain,ph1h2,pnaq,LSF,spectral_tilt,harmonics,h1h2,HNR,gain,pwaveform,waveform,index,&params); /* Construct source signal */ Construct_source(source_signal, glottal, glottal_f0, index, &params); } /********************************************************************/ /* POSTPROCESSING OF PARAMETERS */ /********************************************************************/ /* Add missing frames to the beginning and the end of parameter vectors/matrices. * This is due to the analysis scheme, where the analysis starts * and ends with whole frames instead of zero-padding */ Add_missing_frames(&fundf,&fundf_candidates,&gain,&uvgain,&HNR,&spectral_tilt,&LSF,&LSF2,&harmonics,&waveform,&naq,&h1h2, &fftmatrix_vt,&fftmatrix_src,&fftmatrix_uv,&params); /* Postprocess F0 */ F0_postprocess(fundf,fundf_candidates,&params); /* Median filtering */ MedFilt5_matrix(HNR); MedFilt5_matrix(harmonics); MedFilt5(h1h2); MedFilt5(naq); /* Replace unvoiced fetures */ for(i=0; i<fundf->size; i++) { if(gsl_vector_get(fundf, i) == 0) { if(params.sep_vuv_spectrum == 0) { for(j=0; j<params.lpc_order_vt; j++) gsl_matrix_set(LSF, i, j, gsl_matrix_get(LSF2, i, j)); } for(j=0; j<fftmatrix_vt->size2; j++) gsl_matrix_set(fftmatrix_vt, i, j, gsl_matrix_get(fftmatrix_uv, i, j)); gsl_vector_set(gain,i,gsl_vector_get(uvgain,i)); } } /* Noise reduction */ Noise_reduction(gain,&params); /* Fill possible gaps in waveform and NAQ */ Fill_waveform_gaps(fundf,waveform); Fill_naq_gaps(fundf,naq); /* Select new values to pulse parameters according to refined parameters */ Select_new_refined_values(fundf,gain,LSF,spectral_tilt,HNR,harmonics,pgain,plsf,ptilt, phnr,pharm,pulse_pos,pulse_lengths,waveform,h1h2,ph1h2,naq,pnaq,&params); /* Select only unique pulses */ Select_unique_pulses(&gpulses,&gpulses_rs,&pulse_lengths,&pulse_pos,&pulse_inds,&plsf, &ptilt,&phnr,&pharm,&pwaveform,&pgain,&ph1h2,&pnaq,&params); /* Select only one pulse per frame */ Select_one_pulse_per_frame(&gpulses,&gpulses_rs,&pulse_lengths,&pulse_pos,&pulse_inds,&plsf, &ptilt,&phnr,&pharm,&pwaveform,&pgain,&ph1h2,&pnaq,&params); /********************************************************************/ /* FORMANT ENHANCEMENT */ /********************************************************************/ /* Formant enhancement by LSFs*/ if(params.formant_enh_method == FORMANT_ENH_ID_LSF) LSF_Postfilter(LSF, &params); /* Formant Enhancement by re-estimating LPC and modifying the autocorrelation */ if(params.formant_enh_method == FORMANT_ENH_ID_LPC) LPC_Postfilter(LSF, &params); /* Differentiate LSFs if requested */ if(params.differential_lsf == 1) { Differentiate_LSFs(&LSF); Differentiate_LSFs(&LSF2); Differentiate_LSFs(&spectral_tilt); } /* Convert F0 to logarithmic scale */ Convert_F0_to_log(fundf,&params); /********************************************************************/ /* WRITE PARAMETERS TO FILE */ /********************************************************************/ /* Open files for writing parameters, free memory */ Write_parameters_to_file(argv[1],LSF,LSF2,spectral_tilt,HNR,harmonics,waveform,fundf,gain,h1h2,naq,source_signal, fftmatrix_vt,fftmatrix_src,&params); Free_variables(frame,frame0,signal,glottal,glottsig,glottsig_f0,uvgain,f0_frame,f0_frame0,glottal_f0,bp_gain, fundf_candidates,fftmatrix_uv); /**************************************************************/ /* WRITE PULSE LIBRARY TO FILE */ /**************************************************************/ /* Select unique pulses and write pulse library data to file, free memory */ Write_pulselibrary_to_file(argv[1],gpulses,gpulses_rs,pulse_lengths,pulse_pos,pulse_inds,plsf, ptilt,phnr,pharm,pwaveform,pgain,ph1h2,pnaq,&params); /* Finish */ printf("\nFinished analysis.\n\n"); return EXIT_SUCCESS; } /***********/ /* EOF */ /***********/
{ "alphanum_fraction": 0.6276876009, "avg_line_length": 38.328990228, "ext": "c", "hexsha": "55c7460de87ca4d2ca24be8d50a6a3aa64187801", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:17:33.000Z", "max_forks_repo_forks_event_min_datetime": "2016-08-03T12:08:32.000Z", "max_forks_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mjansche/GlottHMM", "max_forks_repo_path": "src/Analysis.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "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": "mjansche/GlottHMM", "max_issues_repo_path": "src/Analysis.c", "max_line_length": 122, "max_stars_count": 10, "max_stars_repo_head_hexsha": "4dfe5eb0b6dacc227299acc29c6df8b030de82b8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mjansche/GlottHMM", "max_stars_repo_path": "src/Analysis.c", "max_stars_repo_stars_event_max_datetime": "2020-09-03T12:46:50.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-29T22:08:09.000Z", "num_tokens": 3062, "size": 11767 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <sys/time.h> #include <inttypes.h> #include <omp.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_heapsort.h> #include "sph_data_types.h" #include "sph_linked_list.h" #include "sph_compute.h" int compute_density_3d_naive(int N,double h, double* restrict x, double* restrict y, double* restrict z,double* restrict nu, double* restrict Fx){ #pragma omp parallel for for(int64_t ii=0;ii<N;ii+=1){ Fx[ii] = 0; for(int64_t jj=0;jj<N;jj+=1){ double dist = 0.; dist += (x[ii]-x[jj])*(x[ii]-x[jj]); dist += (y[ii]-y[jj])*(y[ii]-y[jj]); dist += (z[ii]-z[jj])*(z[ii]-z[jj]); dist = sqrt(dist); Fx[ii] += nu[jj]*w_bspline_3d(dist,h); } } return 0; } int compute_density_3d_ref(int N,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict Fx){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); #pragma omp parallel for for(int64_t ii=0;ii<N;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) aligned(x,y,z,nu) for(int64_t jj=0;jj<N;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; //q = sqrt(q);//*inv_h; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); } Fx[ii] = kernel_constant*rhoii; } return 0; } int compute_density_3d_tiled(int N,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict Fx){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); const int64_t STRIP = 1000; const int64_t N_tiles = N/STRIP; const int64_t N_prime = N - N%STRIP; #pragma omp parallel for num_threads(24) for(int64_t ii=0;ii<N;ii+=1) Fx[ii] = 0.; #pragma omp parallel for for(int64_t i=0;i<N_prime;i+=STRIP){ for(int64_t j=0;j<N_prime;j+=STRIP){ for(int64_t ii=i;ii<i+STRIP;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) aligned(x,y,z,nu) for(int64_t jj=j;jj<j+STRIP;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); } Fx[ii] += kernel_constant*rhoii; } } } #pragma omp parallel for for(int64_t j=0;j<N_prime;j+=STRIP){ for(int64_t ii=N_prime;ii<N;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) aligned(x,y,z,nu) for(int64_t jj=j;jj<j+STRIP;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); } Fx[ii] += kernel_constant*rhoii; } } return 0; } void swap_int64_t2(int64_t* a, int64_t* b) { int64_t t0 = *a; int64_t t1 = *(a+1); *a = *b; *(a+1) = *(b+1); *b = t0; *(b+1) = t1; } int64_t partition_int64_t2(int64_t arr[], int64_t low, int64_t high) { int64_t pivot = arr[2*high]; // pivot int64_t i = (low - 1); // Index of smaller element and indicates the right position of pivot found so far for (int64_t j = low; j <= high - 1; j++){ // If current element is smaller than the pivot if (arr[2*j] < pivot){ i++; // increment index of smaller element swap_int64_t2(&arr[2*i], &arr[2*j]); } } swap_int64_t2(&arr[2*(i + 1)], &arr[2*high]); return (i + 1); } /* void insertionSort_int64_t2(int64_t *arr, int64_t n){ // https://www.geeksforgeeks.org/insertion-sort/ int64_t i=0, key0=0, key1=0, j=0; for (i = 1; i < n; i++){ key0 = arr[2*i+0]; key1 = arr[2*i+1]; j = i - 1; // Move elements of arr[0..i-1], that are // greater than key, to one position ahead // of their current position while (j >= 0 && arr[2*j] > key0){ arr[2*(j+1)+0] = arr[2*j+0]; arr[2*(j+1)+1] = arr[2*j+1]; j = j-1; } arr[2*(j+1)+0] = key0; arr[2*(j+1)+1] = key1; } }*/ void insertionSort_int64_t2(int64_t *arr, int64_t low, int64_t high) { int64_t i, key0, key1, j; for (i = low+1; i < high; i++){ key0 = arr[2*i+0]; key1 = arr[2*i+1]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[2*j] > key0){ arr[2*(j+1)+0] = arr[2*j+0]; arr[2*(j+1)+1] = arr[2*j+1]; j = j-1; } arr[2*(j+1)+0] = key0; arr[2*(j+1)+1] = key1; } } #define MIN_DEPTH 120 void quickSort_int64_t2(int64_t *arr, int64_t low, int64_t high){ // https://www.geeksforgeeks.org/quick-sort/ if (low < high){ // pi is partitioning index, arr[p] is now // at right place int64_t pi = partition_int64_t2(arr, low, high); // Separately sort elements before // partition and after partition //quickSort_int64_t2(arr, low, pi-1); //quickSort_int64_t2(arr, pi + 1, high); if(pi-low-1 >= MIN_DEPTH){ #pragma omp task shared(arr) quickSort_int64_t2(arr, low, pi-1); } else{ //quickSort_int64_t2(arr, low, pi-1); //#pragma omp task shared(arr) insertionSort_int64_t2(arr,low,pi-1); } if(high - (pi+1) >= MIN_DEPTH){ #pragma omp task shared(arr) quickSort_int64_t2(arr, pi+1, high); } else{ //quickSort_int64_t2(arr, low, pi-1); //#pragma omp task shared(arr) insertionSort_int64_t2(arr,pi+1,high); } } } int main(){ int err,dbg=0; int64_t N = 1000000; double h=0.05; linkedListBox *box; SPHparticle *lsph; err = SPHparticle_SoA_malloc(N,&lsph); if(err) printf("error in SPHparticle_SoA_malloc\n"); err = gen_unif_rdn_pos( N,123123123,lsph); if(err) printf("error in gen_unif_rdn_pos\n"); box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); if(box==NULL) printf("error alocating the linkedListBox\n"); box->Xmin = -1.0; box->Ymin = -1.0; box->Zmin = -1.0; box->Xmax = 2.0; box->Ymax = 2.0; box->Zmax = 2.0; box->Nx = (int)( (box->Xmax-box->Xmin)/(2*h) ); box->Ny = (int)( (box->Ymax-box->Ymin)/(2*h) ); box->Nz = (int)( (box->Zmax-box->Zmin)/(2*h) ); box->N = (box->Nx)*(box->Ny)*(box->Nz); double min_val = fmin((box->Xmax-box->Xmin)/box->Nx,fmin((box->Ymax-box->Ymin)/box->Ny,(box->Zmax-box->Zmin)/box->Nz)); box->width = (int)( 0.5 + 2*h/min_val ); box->hbegin = kh_init(0); box->hend = kh_init(1); double t0,t1,t2,t3,t4,t5,t6,t7; t0 = omp_get_wtime(); if(dbg) printf("hello - 3\n"); err = compute_hash_MC3D(N,lsph,box); t1 = omp_get_wtime(); if(dbg) printf("hello - 4\n"); //qsort(lsph->hash,N,2*sizeof(int64_t),compare_int64_t); //quickSort_int64_t2(lsph->hash,0,N-1); #pragma omp parallel num_threads(1) { #pragma omp single quickSort_int64_t2(lsph->hash,0,N-1); } /* #pragma omp parallel num_threads(1) { #pragma omp single quicksort_omp(lsph->hash,0,N); }*/ t2 = omp_get_wtime(); if(dbg) printf("hello - 5\n"); void *swap_arr = malloc(N*sizeof(double)); err = reorder_lsph_SoA(N,lsph,swap_arr); if(err) printf("error in reorder_lsph_SoA\n"); t3 = omp_get_wtime(); if(dbg) printf("hello - 6\n"); err = setup_interval_hashtables(N,lsph,box); if(err) printf("error in setup_interval_hashtables\n"); t4 = omp_get_wtime(); if(dbg) printf("hello - 7\n"); //err = compute_density_3d(N,h,lsph,box); //err = compute_density_3d_load_ballanced(N,h,lsph,box); err = compute_density_3d_symmetrical_load_ballance(N,h,lsph,box); //err = compute_density_3d_symmetrical_lb_branching(N,h,lsph,box); //err = compute_density_3d_symmetrical_lb(N,h,lsph,box); if(err) printf("error in setup_interval_hashtables\n"); t5 = omp_get_wtime(); if(dbg) printf("hello - 7\n"); //err = compute_density_3d(N,h,lsph,box); //err = compute_density_3d_innerOmp(N,h,lsph,box); //err = compute_density_3d_loopswapped(N,h,lsph,box); // if(err) printf("error in setup_interval_hashtables\n"); t6 = omp_get_wtime(); if(dbg) printf("hello - 8\n"); //err = compute_density_3d_tiled(N,h,lsph->x,lsph->y,lsph->z,lsph->nu,lsph->Fx); //err = compute_density_3d_ref(N,h,lsph->x,lsph->y,lsph->z,lsph->nu,lsph->Fx); //err = compute_density_3d_naive(N,h,lsph->x,lsph->y,lsph->z,lsph->nu,lsph->Fx); err = compute_density_3d_load_ballanced(N,h,lsph,box); if(err) printf("error in compute_density_3d_ref\n"); t7 = omp_get_wtime(); printf("compute_hash_MC3D calculation time : %lf : %lf\n",t1-t0,100*(t1-t0)/(t5-t0)); printf("qsort calculation time : %lf : %lf\n",t2-t1,100*(t2-t1)/(t5-t0)); printf("reorder_lsph_SoA calculation time : %lf : %lf\n",t3-t2,100*(t3-t2)/(t5-t0)); printf("setup_interval_hashtables calculation time : %lf : %lf\n",t4-t3,100*(t4-t3)/(t5-t0)); printf("compute_density_3d base calculation time : %lf : %lf\n",t5-t4,100*(t5-t4)/(t5-t0)); printf("compute_density_3d load balanced calculation time : %lf : %lf\n",t6-t5,0.); printf("Total Linked-List compute_density_3d calculation time : %lf : %lf\n",t5-t0,100*(t5-t0)/(t5-t0)); printf("Reference tiled compute_density_3d calculation time : %lf\n",t7-t6); if(dbg) printf("hello - 9\n"); FILE *fp = fopen("data/sph_density_compute_ref.csv","w"); if(fp!=NULL){ for(int64_t i=0;i<N;i+=1) fprintf(fp,"%ld %.12lf %.12lf %.6lg\n",i, lsph->rho[i], lsph->Fx[i], fabs(lsph->rho[i]-lsph->Fx[i])); fclose(fp); } if(dbg) printf("hello - 10\n"); SPHparticleSOA_safe_free(N,&lsph); safe_free_box(box); free(swap_arr); return 0; }
{ "alphanum_fraction": 0.5659149248, "avg_line_length": 26.411622276, "ext": "c", "hexsha": "cad53d50c459e0be19a83e10a9a07c8fee4b8e76", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "jhelsas/sphalerite", "max_forks_repo_path": "test/compute_density_3d_test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "jhelsas/sphalerite", "max_issues_repo_path": "test/compute_density_3d_test.c", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "jhelsas/sphalerite", "max_stars_repo_path": "test/compute_density_3d_test.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3712, "size": 10908 }
/* cdf/binomial.c * * Copyright (C) 2004 Jason H. Stover. * Copyright (C) 2004 Giulio Bottazzi * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_sf_gamma.h> #include "error.h" /* Computes the cumulative distribution function for a binomial random variable. For a binomial random variable X with n trials and success probability p, Pr( X <= k ) = Pr( Y >= p ) where Y is a beta random variable with parameters k+1 and n-k. The binomial distribution has the form, prob(k) = n!/(k!(n-k)!) * p^k (1-p)^(n-k) for k = 0, 1, ..., n The cumulated distributions can be expressed in terms of normalized incomplete beta functions (see Abramowitz & Stegun eq. 26.5.26 and eq. 6.6.3). Reference: W. Feller, "An Introduction to Probability and Its Applications," volume 1. Wiley, 1968. Exercise 45, page 173, chapter 6. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_cdf.h> double gsl_cdf_binomial_P (const unsigned int k, const double p, const unsigned int n) { double P; double a; double b; if (p > 1.0 || p < 0.0) { CDF_ERROR ("p < 0 or p > 1", GSL_EDOM); } if (k >= n) { P = 1.0; } else { a = (double) k + 1.0; b = (double) n - k; P = gsl_cdf_beta_Q (p, a, b); } return P; } double gsl_cdf_binomial_Q (const unsigned int k, const double p, const unsigned int n) { double Q; double a; double b; if (p > 1.0 || p < 0.0) { CDF_ERROR ("p < 0 or p > 1", GSL_EDOM); } if (k >= n) { Q = 0.0; } else { a = (double) k + 1.0; b = (double) n - k; Q = gsl_cdf_beta_P (p, a, b); } return Q; }
{ "alphanum_fraction": 0.6291732909, "avg_line_length": 23.0825688073, "ext": "c", "hexsha": "190945df9cf7986b538b352ed47e7adc14aa1134", "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/cdf/binomial.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cdf/binomial.c", "max_line_length": 79, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/cdf/binomial.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": 775, "size": 2516 }
/* ** BCM - bipartite connectivity mapping ** ** G.Lohmann, MPI-KYB, Aug 2017 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "viaio/Vlib.h" #include "viaio/VImage.h" #include "viaio/mu.h" #include "viaio/option.h" #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_math.h> extern void gsl_sort_vector_index(gsl_permutation *,gsl_vector *); #define SQR(x) ((x) * (x)) #define ABS(x) ((x) > 0 ? (x) : -(x)) #ifdef _OPENMP #include <omp.h> #endif /*_OPENMP*/ extern gsl_matrix_float *DataMatrix(VImage *src,int nslices,VImage roi,int); extern size_t NumVoxels(VImage src); extern VImage VoxelMap(VImage roi); typedef struct SpointStruct{ VShort x; VShort y; VShort z; } SPoint; VDictEntry MetricDict[] = { { "pearson", 0 }, { "spearman", 1 }, { "MI", 2 }, { NULL } }; VImage VCallocImage(int nslices,int nrows,int ncols,VRepnKind repn,VImage ref) { VImage image = VCreateImage(nslices,nrows,ncols,repn); if (image == NULL) VError(" error allocating image"); VFillImage(image,VAllBands,0); if (ref != NULL) VCopyImageAttrs (ref,image); return image; } void ShowImage(gsl_matrix_float *A,char *filename) { int i,j; int n=A->size1; int m=A->size2; VImage tstimage = VCallocImage(1,n,m,VFloatRepn,NULL); for (i=0; i <n; i++) { for (j=0; j<m; j++) { VPixel(tstimage,0,i,j,VFloat) = gsl_matrix_float_get(A,i,j); } } VAttrList out_list = VCreateAttrList(); VAppendAttr(out_list,"image",NULL,VImageRepn,tstimage); FILE *out_file = fopen(filename,"w"); VWriteFile (out_file, out_list); } VImage GetRoi(SPoint addr,int nslices,int nrows,int ncols,int radius) { int i,b,r,c; int rad2 = radius*radius+1; int b0 = addr.z; int r0 = addr.y; int c0 = addr.x; i=0; for (b=b0-radius; b<=b0+radius; b++) { for (r=r0-radius; r<=r0+radius; r++) { for (c=c0-radius; c<=c0+radius; c++) { if (SQR(b-b0) + SQR(r-r0) + SQR(c-c0) > rad2) continue; i++; } } } VImage roi = VCreateImage(nslices,nrows,ncols,VBitRepn); VFillImage(roi,VAllBands,0); for (b=b0-radius; b<=b0+radius; b++) { if (b < 0 || b >= nslices) VError(" b %d",b); for (r=r0-radius; r<=r0+radius; r++) { if (r < 0 || r >= nrows) VError(" r %d",r); for (c=c0-radius; c<=c0+radius; c++) { if (c < 0 || c >= ncols) VError(" c %d",c); if (SQR(b-b0) + SQR(r-r0) + SQR(c-c0) > rad2) continue; VPixel(roi,b,r,c,VBit) = 1; } } } return roi; } double Pearson(const float *data1,const float *data2,int n) { int i; double corr=0; for (i=0; i<n; i++) { const double u = (double)data1[i]; const double v = (double)data2[i]; corr += u*v; } corr /= (double)n; return corr; } double Spearman(const float *data1,const float *data2,int n) { int i; double nx = (double)n; double kx = nx*(nx*nx-1.0); double sxy=0.0; for (i=0; i<n; i++) { const double u = (double)data1[i]; const double v = (double)data2[i]; const double d = (u-v); sxy += d*d; } double rho = 1.0 - 6.0*sxy/kx; return rho; } /* if X,Y are normalized Gaussians, then I=-0.5*log(1-r^2), with r covariance */ double MutualInformation(const float *data1,const float *data2,int nt) { int i; double covar,mi,u; double tiny=1.0e-10; covar = 0; for (i=0; i<nt; i++) { const double u = data1[i]; const double v = data2[i]; covar += u*v; } const double nx= nt; covar /= nx; mi = 0; u = 1.0 - covar*covar; if (u > tiny) mi = -0.5 * log(u); if (mi < 0) { VWarning("MI: %f",mi); mi = 0; } return mi; } double Correlation(const float *data1,const float *data2,int n,int metric) { double corr=0.0; if (metric == 0) corr = Pearson(data1,data2,n); if (metric == 1) corr = Spearman(data1,data2,n); if (metric == 2) corr = MutualInformation(data1,data2,n); if (gsl_isnan(corr) || gsl_isinf(corr)) corr = 0; return corr; } void VectorNormalize(gsl_vector_float *x) { int i; double nx = (float)x->size; double sum1=0,sum2=0; for (i=0; i<x->size; i++) { sum1 += x->data[i]; sum2 += x->data[i]*x->data[i]; } double mean = sum1/nx; double sigma = sqrt((double)((sum2 - nx * mean * mean) / (nx - 1.0))); for (i=0; i<x->size; i++) { x->data[i] = (x->data[i] - mean)/sigma; } } /* bipartite eigenvector centrality mapping */ void VBiadjacencyECM(gsl_matrix_float *C,gsl_vector_float *xa,gsl_vector_float *xb) { int na = C->size1; int nb = C->size2; int i,iter,maxiter=100; double d=0,sum=0,sum_old=0; /* ini */ gsl_vector_float *ya = gsl_vector_float_calloc(na); gsl_vector_float *yb = gsl_vector_float_calloc(nb); double nx = (double)(na+nb); for (i=0; i<na; i++) xa->data[i] = 1.0/nx; for (i=0; i<nb; i++) xb->data[i] = 1.0/nx; /* iterations */ for (iter=0; iter<maxiter; iter++) { gsl_blas_sgemv (CblasNoTrans,1.0,C,xb,0.0,ya); gsl_blas_sgemv (CblasTrans,1.0,C,xa,0.0,yb); sum = 0; for (i=0; i<na; i++) sum += ya->data[i]*ya->data[i]; for (i=0; i<nb; i++) sum += yb->data[i]*yb->data[i]; sum = sqrt(sum); for (i=0; i<na; i++) xa->data[i] = ya->data[i]/sum; for (i=0; i<nb; i++) xb->data[i] = yb->data[i]/sum; d = fabs(sum-sum_old); if (iter > 0) fprintf(stderr," %5d %f\n",(int)iter,d); if (d < 1.0e-8 && iter > 3) break; if (iter > 5 && sum > sum_old) break; sum_old = sum; } gsl_vector_float_free(ya); gsl_vector_float_free(yb); } /* bipartite degree centrality mapping */ void VBiadjacencyDegreeMap(gsl_matrix_float *C,gsl_vector_float *xa,gsl_vector_float *xb) { size_t na = C->size1; size_t nb = C->size2; size_t i; gsl_vector_float *ya = gsl_vector_float_calloc(na); gsl_vector_float *yb = gsl_vector_float_calloc(nb); for (i=0; i<na; i++) xa->data[i] = 1.0/(double)na; for (i=0; i<nb; i++) xb->data[i] = 1.0/(double)nb; gsl_blas_sgemv (CblasNoTrans,1.0,C,xb,0.0,ya); gsl_blas_sgemv (CblasTrans,1.0,C,xa,0.0,yb); gsl_vector_float_memcpy(xa,ya); gsl_vector_float_memcpy(xb,yb); gsl_vector_float_free(ya); gsl_vector_float_free(yb); } /* project onto ROI */ void VNetworkProjection(gsl_matrix_float *C,gsl_vector_float *x) { size_t na = C->size1; size_t nb = C->size2; size_t i,n1=0,n2=0; if (x->size == na) { n1 = na; n2 = nb; } else { n1 = nb; n2 = na; } float nx = (float)n2; fprintf(stderr," network projection\n"); /* project bipartite graph onto ROI */ gsl_matrix_float *A = gsl_matrix_float_calloc(n1,n1); if (!A) VError(" err allocating projection network"); int progress=0; #pragma omp parallel for schedule(guided) firstprivate(C,A) for (i=0; i<n1; i++) { size_t j=0,k=0; if (i%10 == 0) fprintf(stderr," %d0 of %lu\r",(int)(++progress),n1); for (j=0; j<n1; j++) { float w=0; for (k=0; k<n2; k++) { float u = gsl_matrix_float_get(C,i,k); float v = gsl_matrix_float_get(C,j,k); w += u*v; } #pragma omp critical { gsl_matrix_float_set(A,i,j,w/nx); } } } fprintf(stderr,"\n"); /* Hubs of projected network */ float w=0; size_t j=0; for (i=0; i<n1; i++) { w=0; for (j=0; j<n1; j++) { w += gsl_matrix_float_get(A,i,j); } x->data[i] = w/nx; } gsl_matrix_float_free(A); } /* make matrix positive */ void VThresholdMatrix(gsl_matrix_float *C,float threshold) { int i,j; size_t nneg=0,npos=0; float u=0,tiny=1.0e-6; double sum1=0,sum2=0; double nx = (double)(C->size1 * C->size2); for (i=0; i<C->size1; i++) { for (j=0; j<C->size2; j++) { u = gsl_matrix_float_get(C,i,j); sum1 += u; sum2 += u*u; if (u < threshold+tiny) nneg++; else npos++; if (u < threshold+tiny) gsl_matrix_float_set(C,i,j,0.0); } } if (npos < 1) VWarning(" Subthreshold correlations only"); double mean = sum1/nx; double sigma = sqrt((double)((sum2 - nx * mean * mean) / (nx - 1.0))); fprintf(stderr," matrix mean,std: %f %f, npos: %lu, nneg: %lu\n",mean,sigma,npos,nneg); } int main (int argc,char *argv[]) { static SPoint addr1; static SPoint addr2; static VString roi1_filename = ""; static VString roi2_filename = ""; static VShort type=1; static VFloat threshold = 0.0; static VShort radius=5; static VShort metric = 0; static VBoolean plotboth=FALSE; static VBoolean normalize=TRUE; static VOptionDescRec options[] = { {"roi1",VStringRepn,1,(VPointer) &roi1_filename,VOptionalOpt,NULL,"ROI 1"}, {"roi2",VStringRepn,1,(VPointer) &roi2_filename,VOptionalOpt,NULL,"ROI 2"}, {"seed1",VShortRepn,3,(VPointer) &addr1,VOptionalOpt,NULL,"Voxel address of seed point (x,y,z)"}, {"seed2",VShortRepn,3,(VPointer) &addr2,VOptionalOpt,NULL,"Voxel address of seed point (x,y,z)"}, {"type", VShortRepn,1,(VPointer) &type,VOptionalOpt,NULL,"Type, 0:ECM, 1: DCM, 2: project onto ROI1, 3: project onto ROI2"}, {"threshold", VFloatRepn,1,(VPointer) &threshold,VOptionalOpt,NULL,"Matrix threshold"}, {"metric",VShortRepn,1,(VPointer) &metric,VOptionalOpt,MetricDict,"Correlation metric"}, {"radius", VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,"Radius around seed voxel"}, {"both", VBooleanRepn,1,(VPointer) &plotboth,VOptionalOpt,NULL,"Whether to plot results of both ROIs"}, {"normalize", VBooleanRepn,1,(VPointer) &normalize,VOptionalOpt,NULL,"Whether to normalize results"}, }; FILE *out_file=NULL; VString in_file=NULL; VImage roi1=NULL,roi2=NULL; int i; char *prg = GetLipsiaName("vbcm"); /* Parse command line arguments and identify files: */ VParseFilterCmdX (VNumber (options), options, argc, argv,&in_file,&out_file); fprintf(stderr," type= %d\n",type); /* read functional data */ VAttrList list = VReadAttrList(in_file,0L,TRUE,FALSE); if (list == NULL) VError(" error reading input file %s",in_file); /* get pointers to image data */ int nrows=0,ncols=0,nt=0; int nslices = VAttrListNumImages(list); VImage *src = VAttrListGetImages(list,nslices); VImageDimensions(src,nslices,&nt,&nrows,&ncols); fprintf(stderr," image dims: %d %d %d, nt: %d\n",nslices,nrows,ncols,nt); /* omp-stuff */ #ifdef _OPENMP int num_procs=omp_get_num_procs(); printf("using %d cores\n",(int)num_procs); omp_set_num_threads(num_procs); #endif /* _OPENMP */ /* ROI 1 */ if (strlen(roi1_filename) > 0) { VAttrList list1 = VReadAttrList(roi1_filename,0L,TRUE,FALSE); if (list1 == NULL) VError(" error reading roi file %s",roi1_filename); roi1 = VReadImage(list1); if (roi1 == NULL) VError(" err reading %s",roi1_filename); } /* ROI 2 */ if (strlen(roi2_filename) > 0) { VAttrList list2 = VReadAttrList(roi2_filename,0L,TRUE,FALSE); if (list2 == NULL) VError(" error reading roi file %s",roi2_filename); roi2 = VReadImage(list2); if (roi2 == NULL) VError(" err reading %s",roi2_filename); } /* ROIs from seed voxels */ if (roi1 == NULL) roi1 = GetRoi(addr1,nslices,nrows,ncols,radius); if (roi2 == NULL) roi2 = GetRoi(addr2,nslices,nrows,ncols,radius); /* voxel maps */ VImage map1 = VoxelMap(roi1); VImage map2 = VoxelMap(roi2); size_t nvox1 = NumVoxels(roi1); size_t nvox2 = NumVoxels(roi2); fprintf(stderr," nvox1: %lu, nvox2: %lu\n",nvox1,nvox2); /* read data matrices */ gsl_matrix_float *X1 = DataMatrix(src,nslices,roi1,(int)metric); gsl_matrix_float *X2 = DataMatrix(src,nslices,roi2,(int)metric); /* correlation matrix */ fprintf(stderr," CorrMatrix...\n"); int rad2 = 3*3; /* exclusion radius */ gsl_matrix_float *A = gsl_matrix_float_calloc(nvox1,nvox2); if (A == NULL) VError(" err allocating corr matrix, %d x %d",nvox1,nvox2); int progress=0; #pragma omp parallel for schedule(guided) firstprivate(A) for (i=0; i<nvox1; i++) { if (i%100 == 0) fprintf(stderr," %d00\r",(int)(++progress)); int bi = VPixel(map1,0,0,i,VShort); int ri = VPixel(map1,0,1,i,VShort); int ci = VPixel(map1,0,2,i,VShort); int j=0; float u=0; float *tmp = (float *) VCalloc(nvox2,sizeof(float)); for (j=0; j<nvox2; j++) tmp[j] = -1.0; const float *data1 = gsl_matrix_float_const_ptr(X1,i,0); for (j=0; j<nvox2; j++) { int bj = VPixel(map2,0,0,j,VShort); int rj = VPixel(map2,0,1,j,VShort); int cj = VPixel(map2,0,2,j,VShort); int di = SQR(bi-bj) + SQR(ri-rj) + SQR(ci-cj); if (di < rad2) continue; const float *data2 = gsl_matrix_float_const_ptr(X2,j,0); tmp[j] = Correlation(data1,data2,nt,(int)metric); } #pragma omp critical { for (j=0; j<nvox2; j++) { u = tmp[j]; gsl_matrix_float_set(A,i,j,u); } } VFree(tmp); } fprintf(stderr,"\n"); /* ShowImage(A,"test.v"); exit(0); */ /* Biadjacency ECM */ fprintf(stderr," Biadjacency Connectivity...\n"); gsl_vector_float *xa = gsl_vector_float_calloc(nvox1); gsl_vector_float *xb = gsl_vector_float_calloc(nvox2); fprintf(stderr," type= %d\n",type); VThresholdMatrix(A,threshold); switch(type) { case 0: VBiadjacencyECM(A,xa,xb); break; case 1: VBiadjacencyDegreeMap(A,xa,xb); break; case 2: VNetworkProjection(A,xa); break; case 3: VNetworkProjection(A,xb); break; default: VError(" unknown type"); } /* normalize */ if (normalize) { VectorNormalize(xa); VectorNormalize(xb); } /* output */ VImage dest = VCallocImage(nslices,nrows,ncols,VFloatRepn,src[0]); int b,r,c; for (i=0; i<nvox1; i++) { b = VPixel(map1,0,0,i,VShort); r = VPixel(map1,0,1,i,VShort); c = VPixel(map1,0,2,i,VShort); VPixel(dest,b,r,c,VFloat) = 100.0*xa->data[i]; } if (plotboth) { for (i=0; i<nvox2; i++) { b = VPixel(map2,0,0,i,VShort); r = VPixel(map2,0,1,i,VShort); c = VPixel(map2,0,2,i,VShort); VPixel(dest,b,r,c,VFloat) = 100.0*xb->data[i]; } } /* write output to disk */ VAttrList out_list = VCreateAttrList(); VAttrList geolist = VGetGeoInfo(list); if (geolist != NULL) { double *D = VGetGeoDim(geolist,NULL); D[0] = 3; /* 3D */ D[4] = 1; VSetGeoDim(geolist,D); VSetGeoInfo(geolist,out_list); } VHistory(VNumber(options),options,prg,&list,&out_list); VAppendAttr(out_list,"image",NULL,VImageRepn,dest); VWriteFile (out_file, out_list); fclose(out_file); fprintf (stderr, "%s: done. \n", argv[0]); exit(0); }
{ "alphanum_fraction": 0.6221934075, "avg_line_length": 26.2128801431, "ext": "c", "hexsha": "88fa4177661dacd21e4f9294e8ba94aafd08c697", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/nets/vbcm/vbcm.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/nets/vbcm/vbcm.c", "max_line_length": 132, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/nets/vbcm/vbcm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 5124, "size": 14653 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <gsl/gsl_multifit.h> //DEFINES #define SUCCESS 1 #define FAILURE -1 #define PROGRESS "====================" #define PRG_WIDTH 20 //FUNCTIONS DECLARATION int rows_number(char *); double mean(double *, int); void cumsum(double *, double *, int); void slice_vec(double *, double *, int, int); void polynomialFit(int, int, double *, double *, double *); //MAIN int main(int argc, char **argv) { //inputs int input_args = 6; if(argc < input_args){ printf("Not enough input arguments!\n"); return FAILURE; }else if(argc > input_args){ printf("Too many input arguments!\n"); return FAILURE; } char file_name[255]; memset(file_name, 0x00, sizeof(file_name)); sprintf(file_name, "%s", argv[1]); int min_win = atoi(argv[2]); int ord = atoi(argv[3]); int rev_seg = atoi(argv[4]); char path_tot[255]; memset(path_tot, 0x00, sizeof(path_tot)); sprintf(path_tot, "%s/dfa_mw=%d_pol=%d_bck=%d.txt", argv[5], min_win, ord, rev_seg); //file length int N = rows_number(file_name); if(N == FAILURE){ printf("Cannot open input file.\n"); return FAILURE; } //time series double *pn; pn = calloc(N, sizeof(double)); if(!pn){ printf("MALLOC ERROR (pn)\n"); return FAILURE; } FILE *f; f = fopen(file_name, "r"); if(!f){ printf("Cannot open input file.\n"); return FAILURE; } for(int i = 0; i < N; i++) fscanf(f, "%lf", pn+i); fclose(f); printf("Data length: <%d>\n", N); //time vector double *t; t = calloc(N, sizeof(double)); if(!t){ printf("MALLOC ERROR (t)\n"); return FAILURE; } for(int i = 0; i < N; i++) t[i] = (double)(i+1); //time series minus its mean double a_ave = mean(pn, N); double *pn_nomean; pn_nomean = calloc(N, sizeof(double)); if(!pn_nomean){ printf("MALLOC ERROR (pn_nomean)\n"); return FAILURE; } for(int i = 0; i < N; i++) pn_nomean[i] = pn[i] - a_ave; //cumulative sum double *y; y = calloc(N, sizeof(double)); if(!y){ printf("MALLOC ERROR (y)\n"); return FAILURE; } printf("Data integration..."); cumsum(pn_nomean, y, N); printf("done!\n"); //defining parameters int max_win = 5; int end_dfa = N / max_win; int *s; int range_dfa = end_dfa - min_win + 1; s = calloc(range_dfa, sizeof(int)); if(!s){ printf("MALLOC ERROR (s)\n"); return FAILURE; } for(int i = 0; i < range_dfa; i++) s[i] = i + min_win; //fluctuations vector and other arrays double *F, *F_nu1, *F_nu2, *t_fit, *y_fit, *diff_vec; int F_len = N / min_win; F = calloc(range_dfa, sizeof(double)); if(!F){ printf("MALLOC ERROR (F)\n"); return FAILURE; } F_nu1 = calloc(F_len, sizeof(double)); if(!F_nu1){ printf("MALLOC ERROR (F_nu1)\n"); return FAILURE; } F_nu2 = calloc(F_len, sizeof(double)); if(!F_nu2){ printf("MALLOC ERROR (F_nu2)\n"); return FAILURE; } t_fit = calloc(end_dfa, sizeof(double)); if(!t_fit){ printf("MALLOC ERROR (t_fit)\n"); return FAILURE; } y_fit = calloc(end_dfa, sizeof(double)); if(!y_fit){ printf("MALLOC ERROR (y_fit)\n"); return FAILURE; } diff_vec = calloc(end_dfa, sizeof(double)); if(!diff_vec){ printf("MALLOC ERROR (diff_vec)\n"); return FAILURE; } //computation int start_lim, end_lim; double *fit_coeffs; fit_coeffs = calloc(ord+1, sizeof(double)); if(!fit_coeffs){ printf("MALLOC ERROR (fit_coeffs)\n"); return FAILURE; } for(int i = 0; i < range_dfa; i++){ int N_s = N / s[i]; double perc = i * 100 / (double)range_dfa; int prg = (i * PRG_WIDTH) / range_dfa; printf("Computing fluctuations => [%.*s%*s] %.2lf%%\r", prg, PROGRESS, PRG_WIDTH-prg, "", perc); fflush(stdout); for(int v = 0; v < N_s; v++){ start_lim = v * s[i]; end_lim = (v + 1) * s[i] - 1; slice_vec(t, t_fit, start_lim, end_lim); slice_vec(y, y_fit, start_lim, end_lim); polynomialFit(s[i], ord+1, t_fit, y_fit, fit_coeffs); for(int j = 0; j < s[i]; j++){ for(int k = 0; k < ord+1; k++) y_fit[j] -= fit_coeffs[k] * pow(t_fit[j], k); diff_vec[j] = pow(y_fit[j], 2.0); } F_nu1[v] = mean(diff_vec, s[i]); } if(rev_seg == 1){ for(int v = 0; v < N_s; v++){ start_lim = v * s[i] + (N - N_s * s[i]); end_lim = (v + 1) * s[i] + (N - N_s * s[i]); slice_vec(t, t_fit, start_lim, end_lim); slice_vec(y, y_fit, start_lim, end_lim); polynomialFit(s[i], ord+1, t_fit, y_fit, fit_coeffs); for(int j = 0; j < s[i]; j++){ for(int k = 0; k < ord+1; k++) y_fit[j] -= fit_coeffs[k] * pow(t_fit[j], k); diff_vec[j] = pow(y_fit[j], 2.0); } F_nu2[v] = mean(diff_vec, s[i]); } F[i] = sqrt((mean(F_nu1, N_s) + mean(F_nu2, N_s)) / (double)2); }else{ F[i] = sqrt(mean(F_nu1, N_s)); } } printf("Computing fluctuations => [%s] 100.00%%\r", PROGRESS); fflush(stdout); printf("\n"); free(F_nu1); free(F_nu2); free(t_fit); free(y_fit); free(diff_vec); free(fit_coeffs); //HURST EXPONENT printf("Computing hurst exponent..."); double *log_s, *log_F, *H_fit; log_s = calloc(range_dfa, sizeof(double)); if(!log_s){ printf("MALLOC ERROR (log_s)\n"); return FAILURE; } log_F = calloc(range_dfa, sizeof(double)); if(!log_F){ printf("MALLOC ERROR (log_F)\n"); return FAILURE; } H_fit = calloc(2, sizeof(double)); if(!H_fit){ printf("MALLOC ERROR (H_fit)\n"); return FAILURE; } for(int i = 0; i < range_dfa; i++){ log_s[i] = log(s[i]); log_F[i] = log(F[i]); } polynomialFit(range_dfa, 2, log_s, log_F, H_fit); printf("done\n"); printf("Output file..."); f = fopen(path_tot, "w"); if(!f){ printf("Cannot open output file.\n"); return FAILURE; } for(int i = 0; i < range_dfa; i++) fprintf(f, "%d %lf %lf %lf\n", s[i], F[i], H_fit[0]+log_s[i]*H_fit[1], H_fit[1]); fclose(f); printf("done\n"); free(F); free(log_s); free(log_F); free(H_fit); return 0; } //FUNCTIONS int rows_number(char *file_name) { FILE *f; int stop; int lines = 0; f = fopen(file_name,"r"); if(!f){ printf("Cannot open file %s\n", file_name); return FAILURE; } while(!feof(f)){ stop = fgetc(f); if(stop == '\n') lines++; } fclose(f); return lines; } double mean(double *vec, int L) { double avg = 0.0; for(int i = 0; i < L; i++) avg += vec[i]; avg /= (double)L; return avg; } void cumsum(double *vec, double *sum_vec, int L) { sum_vec[0] = vec[0]; for(int i = 1; i < L; i++) sum_vec[i] = sum_vec[i-1] + vec[i]; } void slice_vec(double *all_vec, double *sliced_vec, int start, int end) { for(int i = 0; i <= (end-start); i++) sliced_vec[i] = all_vec[start+i]; } void polynomialFit(int obs, int degree, double *dx, double *dy, double *store) { gsl_multifit_linear_workspace *ws; gsl_matrix *cov, *X; gsl_vector *y, *c; double chisq; int i, j; //alloc X = gsl_matrix_alloc(obs, degree); y = gsl_vector_alloc(obs); c = gsl_vector_alloc(degree); cov = gsl_matrix_alloc(degree, degree); //computation for(i = 0; i < obs; i++){ for(j = 0; j < degree; j++) gsl_matrix_set(X, i, j, pow(dx[i], j)); gsl_vector_set(y, i, dy[i]); } ws = gsl_multifit_linear_alloc(obs, degree); gsl_multifit_linear(X, y, c, cov, &chisq, ws); for(i = 0; i < degree; i++) store[i] = gsl_vector_get(c, i); //free memory gsl_multifit_linear_free(ws); gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(y); gsl_vector_free(c); }
{ "alphanum_fraction": 0.528821167, "avg_line_length": 28.3143812709, "ext": "c", "hexsha": "a7c3b148b4db61fe0cb3942c8681fbb5449a9e15", "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": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "stfbnc/C_fa", "max_forks_repo_path": "dfa.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "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": "stfbnc/C_fa", "max_issues_repo_path": "dfa.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "stfbnc/C_fa", "max_stars_repo_path": "dfa.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2538, "size": 8466 }
#pragma once #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include <cstdint> #include <array> #include <limits> #include <gsl\gsl> namespace Library { class Game; class RenderStateHelper final { public: RenderStateHelper(Game& game); RenderStateHelper(const RenderStateHelper&) = delete; RenderStateHelper(RenderStateHelper&&) = default; RenderStateHelper& operator=(const RenderStateHelper&) = delete; RenderStateHelper& operator=(RenderStateHelper&&) = default; ~RenderStateHelper() = default; static void ResetAll(gsl::not_null<ID3D11DeviceContext*> deviceContext); static void ResetRasterizerState(gsl::not_null<ID3D11DeviceContext*> deviceContext); static void ResetBlendState(gsl::not_null<ID3D11DeviceContext*> deviceContext); static void ResetDepthStencilState(gsl::not_null<ID3D11DeviceContext*> deviceContext); ID3D11RasterizerState* RasterizerState(); ID3D11BlendState* BlendState(); ID3D11DepthStencilState* DepthStencilState(); void SaveRasterizerState(); void RestoreRasterizerState() const; void SaveBlendState(); void RestoreBlendState() const; void SaveDepthStencilState(); void RestoreDepthStencilState() const; void SaveAll(); void RestoreAll() const; void ClearAll(); private: Game& mGame; winrt::com_ptr<ID3D11RasterizerState> mRasterizerState; winrt::com_ptr<ID3D11BlendState> mBlendState; std::array<float, 4> mBlendFactor; std::uint32_t mSampleMask{ std::numeric_limits<std::uint32_t>::max() }; winrt::com_ptr<ID3D11DepthStencilState> mDepthStencilState; std::uint32_t mStencilRef{ std::numeric_limits<std::uint32_t>::max() }; }; }
{ "alphanum_fraction": 0.7700729927, "avg_line_length": 29.3571428571, "ext": "h", "hexsha": "b9abd483393d67f5709351e9376537aa47506105", "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/Library.Shared/RenderStateHelper.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/Library.Shared/RenderStateHelper.h", "max_line_length": 88, "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/Library.Shared/RenderStateHelper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 441, "size": 1644 }
#ifndef UTILSH #define UTILSH #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_permutation.h> #include <math.h> #include <time.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> #include <stdlib.h> #include <stdarg.h> time_t TIME; char line1[80]; void outlog(char* fmt, ...); typedef struct int_vector { int size; int* val; } int_vector; int_vector* new_int_vector(int size); void delete_int_vector(int_vector* iv); void ivappend(int_vector* v, int val); static inline int ivget(int_vector* v, int n) { return(v->val[n]); }; static inline void ivset(int_vector* v, int n, int val) { v->val[n] = val; }; static inline void vset(gsl_vector* v, int i, double x) { gsl_vector_set(v, i, x); }; static inline double vget(const gsl_vector* v, int i) { return(gsl_vector_get(v, i)); }; static inline void vinc(gsl_vector* v, int i, double x) { vset(v, i, vget(v, i) + x); }; static inline double log_sum(double log_a, double log_b) { if (log_a < log_b) return(log_b+log(1 + exp(log_a-log_b))); else return(log_a+log(1 + exp(log_b-log_a))); }; static inline double lgam(double x) { return(gsl_sf_lngamma(x)); } double runif(); double rgauss(double mean, double stdev); int sample_from_log(gsl_vector* log_prob); void init_random_number_generator(); void vct_fscanf(const char* filename, gsl_vector* v); void iv_permute(int_vector* iv); void iv_permute_from_perm(int_vector* iv, gsl_permutation* p); int_vector* iv_copy(int_vector* iv); double sum(gsl_vector* v); void print_vector(gsl_vector* v); gsl_permutation* rpermutation(int size); void write_vect(gsl_vector* vect, char* name, FILE* file); gsl_vector* read_vect(char* name, int size, FILE* file); int read_int(char* name, FILE* file); void write_int(int x, char* name, FILE* file); void write_double(double x, char* name, FILE* file); double read_double(char* name, FILE* file); int directory_exist(const char *dname); void make_directory(char* name); int rbernoulli(double p); double rbeta(double a, double b); double rgamma(double shape, double scale); double log_dgamma(double x, double shape, double scale); void resize(gsl_vector * vec, size_t newsize); #endif
{ "alphanum_fraction": 0.7011197244, "avg_line_length": 20.9189189189, "ext": "h", "hexsha": "b095ecbe4748ca8943f2cbb8b84fe9721eed2d8e", "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": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thatindiandude/PGM-Project", "max_forks_repo_path": "Algorithms/OurAlgo/hlda-c/utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "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": "thatindiandude/PGM-Project", "max_issues_repo_path": "Algorithms/OurAlgo/hlda-c/utils.h", "max_line_length": 62, "max_stars_count": null, "max_stars_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thatindiandude/PGM-Project", "max_stars_repo_path": "Algorithms/OurAlgo/hlda-c/utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 636, "size": 2322 }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #include <assert.h> #include <alloca.h> #include <gsl/gsl_cdf.h> #include "limits.h" #include "stattest.h" #include "cat.h" #include "fisher.h" #include "min2.h" #include "bvr.h" typedef unsigned int count_t; typedef const count_t COUNT_T; typedef double prob_t; /** * This class is stateful in the interest of efficiency * because some methods share preliminary computations: * 1) statistics require expectation, and * 2) expectation requires marginals * (which may also be used incidentally for other purposes), so this * variable captures the progress towards complete calculations * to enable implicit just-in-time calculation. */ enum State { Nothing = 0, Marginals, Expectation }; struct CatCovars { /** * Buffers are sized to accomodate these dimensions at construction * and are not changeable thereafter. */ unsigned int ROW_CAPACITY, COL_CAPACITY; /** * "decl(ared)_" because the bounds says nothing about the row/col * content--empty rows/columns may exist! I'm just driving this point * home in these members' names because it has already burned me once! */ unsigned int decl_rows, decl_cols, decl_cells; /** * Count of samples pushed since last cat_clear. */ count_t sample_count; // Calculation state /////////////////////////////////////////////////// prob_t minimumExpected; /** * This is used strictly by badCellExists */ count_t REQUIRED_CELL_MINIMUM; enum State calculated; // Buffers ///////////////////////////////////////////////////////////// size_t SIZEOF_PROB_BUF; prob_t *expect; size_t SIZEOF_COUNT_BUF; /** * The counts matrix is stored packed against the head of this * (heap-allocated) buffer. In other words, though this buffer * is -expected- to be larger than required (since the class * is designed to be iteratively re-used), only the first * (decl_rows*decl_cols) of the buffer are used for any given * matrix. */ count_t *counts; /** * Following are derivative data...computed from counts. */ count_t *rmarg; count_t *cmarg; }; static void _coordsOfOffset( struct CatCovars *co, unsigned int off, unsigned int *r, unsigned int *c ) { *r = off / co->decl_cols; *c = off % co->decl_cols; } static count_t _count( struct CatCovars *co, coord_t r, coord_t c ) { const int C = co->decl_cols; assert( r < co->decl_rows && c < C ); return co->counts[ r*C + c ]; } static prob_t _expected( struct CatCovars *co, coord_t r, coord_t c ) { const int C = co->decl_cols; assert( r < co->decl_rows && c < C ); return co->expect[ r*C + c ]; } static void _recalcSampleCount( struct CatCovars *co ) { int n = co->decl_cells; co->sample_count = 0; while( n-- > 0 ) co->sample_count += co->counts[n]; } /** * This starts searching at the given coordinates and continues linearly * through the matrix until it finds a violating cell at which point it * turns the linear index into 2D coordinates. */ static bool _badCellExists( struct CatCovars *co, unsigned int *offset ) { unsigned int i = *offset; while( i < co->decl_cells ) { if( co->counts[i] < co->REQUIRED_CELL_MINIMUM ) { *offset = i; return true; } i++; } return false; } /** * If after accumulation there are fewer than 2 rows or fewer than 2 * columns, the table is degenerate. Rows or columns with zero marginal * sum are OK! For a contingency table that's bad but not -degenerate-. */ static bool _immediatelyDegenerate( struct CatCovars *co ) { return ! ( co->decl_rows >= 2 && co->decl_cols >= 2 ); } #if 0 static bool _eventuallyDegenerate( struct CatCovars *co ) { unsigned nonemprows = 0; unsigned nonempcols = 0; unsigned i; for(i = 0; i < co->decl_rows; i++ ) if( co->rmarg[i] > 0 ) nonemprows++; for(i = 0; i < co->decl_cols; i++ ) if( co->cmarg[i] > 0 ) nonempcols++; return ! ( nonemprows >= 2 && nonempcols >= 2 ); } #endif static void _cullRow( struct CatCovars *co, unsigned int r ) { // An over-writing copy suffices since matrix is // stored row-major. mergeCols is more intricate. if( r+1 < co->decl_rows ) { // ...so 0 < rows-U-1 memmove( co->counts + (r )*co->decl_cols, co->counts + (r+1)*co->decl_cols, (co->decl_rows - r - 1)*co->decl_cols*sizeof(count_t) ); } else { // ...it's the last row, and there's nothing to move. } co->decl_rows -= 1; co->decl_cells -= co->decl_cols; co->sample_count = 0; co->calculated = Nothing; // ...to trigger recomputation. } static void _cullCol( struct CatCovars *co, unsigned int c ) { const unsigned int N = co->decl_cells; // Shrink. Because matrices are stored row-major and calculations // throughout this class assume the matrix is packed at the head of // the buffer, there is actually a fairly complex shifting of all // but the first c entries that has to occurr... // Basically, traverse the matrix linearly (storage order) shifting // "left" all entries that are NOT in the c'th column... for(unsigned int src = 0, dst = 0 ; src < N; src++ ) { if( src % co->decl_cols != c ) { co->counts[dst++] = co->counts[src]; } } co->decl_cols -= 1; co->decl_cells -= co->decl_rows; co->sample_count = 0; co->calculated = Nothing; // ...to trigger recomputation. } /** * Following two MUST be called in order before any of * the statistics are computed. In other words, * !!!! THESE ARE NOT CALLED IMPLICITLY! !!!! * (Statistical methods which -ought- to be const can't be unless * 'expect', '[rc]marg' and friends are made mutable->) */ static void _calc_marginals( struct CatCovars *co ) { const int R = co->decl_rows; const int C = co->decl_cols; co->sample_count = 0; memset( co->rmarg, 0, R*sizeof(count_t) ); memset( co->cmarg, 0, C*sizeof(count_t) ); // Calculate the marginals... for(unsigned int i = 0; i < R; i++ ) { for(unsigned int j = 0; j < C; j++ ) { const count_t C = _count( co, i,j); co->rmarg[i] += C; co->cmarg[j] += C; co->sample_count += C; } } co->calculated = Marginals; } /** * Calculates the expected probabilities of a contingency table assuming * independence of the two variables. * "Since the Chi-square and G^2 statistics rest on the normal approximation * to the hypergeometric distribution, these approximations get strained * when there are zero frequency cells or when the expected counts are * 'very small'." ...from Yaramakala's Masters Thesis, p.43 * * "...for an independence test to be reliable, all cells have non-zero * expected values and at least 80% of the cells should have expected * values greater than 5." [Everitt 1977, Upton 1978] */ static void _calc_expectation( struct CatCovars *co ) { const int R = co->decl_rows; const int C = co->decl_cols; if( co->calculated < Marginals ) _calc_marginals( co ); if( co->sample_count > 0 ) { co->minimumExpected = (prob_t)(co->rmarg[0] * co->cmarg[0]) / (prob_t)co->sample_count; for(unsigned int i = 0; i < R; i++ ) { for(unsigned int j = 0; j < C; j++ ) { const prob_t E = (prob_t)(co->rmarg[i] * co->cmarg[j]) / (prob_t)co->sample_count; co->expect[i*co->decl_cols + j] = E; if( co->minimumExpected > E ) co->minimumExpected = E; } } } co->calculated = Expectation; } /** * This function cannot fail. Valid results always exist. * Returns the indices of the minimal row and columns marginals. */ #if 0 static void _minimalMarginals( struct CatCovars *co, unsigned int *rm, unsigned int *cm ) { unsigned int MIN_DIM = co->decl_rows < co->decl_cols ? co->decl_rows : co->decl_cols; unsigned int i, ri = 0, ci = 0; count_t mr, mc; if( co->calculated < Marginals ) _calc_marginals( co ); mr = co->rmarg[ri]; mc = co->cmarg[ci]; // Iterate over marginals at indices [0,min(rows,cols) ) for(i = 0; i < MIN_DIM; i++ ) { if( mr > co->rmarg[i] ) { mr = co->rmarg[i]; ri = i; } if( mc > co->cmarg[i] ) { mc = co->cmarg[i]; ci = i; } } // ...continue iteration over [ min(rows,cols), max(rows,cols) ). if( co->decl_cols > co->decl_rows ) for(; i < co->decl_cols; i++ ) { if( mc > co->cmarg[i] ) { mc = co->cmarg[i]; ci = i; } } else if( co->decl_rows > co->decl_cols ) for(; i < co->decl_rows; i++ ) { if( mr > co->rmarg[i] ) { mr = co->rmarg[i]; ri = i; } } *rm = ri; *cm = ci; } #endif /** * A pretty printer...primarily for debugging. */ #ifdef _DEBUG static void dbg_dump( struct CatCovars *co, FILE *fp, const char *prefix ) { if( prefix==NULL ) prefix=""; fprintf( fp, "%s %d(r) x %d(c) (capacity = %dx%d)\n", prefix, co->decl_rows, co->decl_cols, co->ROW_CAPACITY, co->COL_CAPACITY ); fprintf( fp, "%s cell counts...\n", prefix ); for(unsigned int r = 0; r < co->decl_rows; r++ ) { fputs( prefix, fp ); for(unsigned int c = 0; c < co->decl_cols; c++ ) { fprintf( fp, "\t%d", _count(co,r,c) ); } fputc( '\n', fp ); } if( co->calculated >= Expectation ) { fprintf( fp, "%s %d total samples, expectation...\n", prefix, co->sample_count ); for(unsigned int r = 0; r < co->decl_rows; r++ ) { fputs( prefix, fp ); for(unsigned int c = 0; c < co->decl_cols; c++ ) { fprintf( fp, "\t%.3e", _expected( co, r, c) ); } fputc( '\n', fp ); } } } #endif /*************************************************************************** * Publics */ void cat_destroy( void *pv ) { if( pv ) { struct CatCovars *co = (struct CatCovars *)pv; if( co->expect ) free( co->expect ); free( pv ); } } /** * Pre-allocate a set of working buffers large enough for all anticipated * calculations (max feature length) and a struct to wrap them. */ void *cat_create( unsigned int rcap, unsigned int ccap ) { struct CatCovars *co = calloc( 1, sizeof(struct CatCovars) ); if( co ) { co->ROW_CAPACITY = rcap; co->COL_CAPACITY = ccap; co->SIZEOF_COUNT_BUF = (rcap*ccap+rcap+ccap)*sizeof(count_t); co->SIZEOF_PROB_BUF = rcap*ccap*sizeof(prob_t); // Allocate one large buffer and partition it up. co->expect = calloc( co->SIZEOF_PROB_BUF + co->SIZEOF_COUNT_BUF, sizeof(char) ); co->counts = (count_t*)( co->expect + rcap*ccap ); co->rmarg = co->counts + rcap*ccap; co->cmarg = co->rmarg + rcap; co->REQUIRED_CELL_MINIMUM = 5; // If -anything- failed clean up any successes. if( (NULL == co->counts) || (NULL == co->expect) ) { cat_destroy( co ); return NULL; } return co; } return NULL; } void cat_clear( void *pv, coord_t nr, coord_t nc ) { struct CatCovars *co = (struct CatCovars *)pv; assert( nr <= co->ROW_CAPACITY && nc <= co->COL_CAPACITY ); // Set dimensions and cell count. co->decl_rows = nr; co->decl_cols = nc; co->decl_cells = nr*nc; co->sample_count = 0; co->minimumExpected = 0.0; co->calculated = Marginals; // OPTIMIZATION: Only clearing the part of capacity intended for use! memset( co->counts, 0, co->decl_cells*sizeof(count_t) ); memset( co->rmarg, 0, co->decl_rows*sizeof(count_t) ); memset( co->cmarg, 0, co->decl_cols*sizeof(count_t) ); memset( co->expect, 0, co->decl_cells*sizeof(prob_t) ); } void cat_setMinCellCount( void *pv, unsigned n ) { struct CatCovars *co = (struct CatCovars *)pv; co->REQUIRED_CELL_MINIMUM = n; } /** * Only this one is public in order that we may count the samples * as they're added... */ void cat_push( void *pv, coord_t r, coord_t c ) { struct CatCovars *co = (struct CatCovars *)pv; assert( r < co->decl_rows ); assert( c < co->decl_cols ); co->counts[ r*co->decl_cols + c ] += 1; // size and marginals are kept up to date... co->sample_count++; co->rmarg[r] += 1; co->cmarg[c] += 1; } size_t cat_size( void *pv ) { struct CatCovars *co = (struct CatCovars *)pv; return co->sample_count; } bool cat_complete( void *pv ) { struct CatCovars *co = (struct CatCovars *)pv; return ! _immediatelyDegenerate( co ); } bool cat_is2x2( void *pv ) { struct CatCovars *co = (struct CatCovars *)pv; return (2 == co->decl_rows) && (2 == co->decl_cols); } /** * <bits> will ALWAYS be non-zero on entry, but it may only contain * a single set bit. */ static int _offsetOfLeastLoss( unsigned bits, COUNT_T *loss, count_t *leastLoss ) { int v = __builtin_ctz( bits ); int l = loss[v]; bits ^= (1<<v); while( bits ) { const int i = __builtin_ctz( bits ); bits ^= (1<<i); if( l > loss[i] ) { l = loss[i]; v = i; } } *leastLoss = l; return v; } /** * This removes all rows and any columns containing cells with * counts LESS THAN OR EQUAL TO REQUIRED_CELL_MINIMUM. * * This method assumes we start with a table larger in at least * one dimention than 2x2 and halts when/if we reach a 2x2. */ unsigned int cat_cullBadCells( void *pv, char *log, int buflen ) { unsigned int culled = 0; struct CatCovars *co = (struct CatCovars *)pv; const char * const EOL = log + buflen - 2; // leave room for "+\0". // BEGIN log maintenance... const int MIN_LOG_RECORD_LEN = 3; // "R99" // ...since tables will never exceed 99 rows or columns. char *pc = log; // ...END log maintenance. unsigned int victim; unsigned int raw_mem_offset = 0; // linear offsets of "bad" cell. #ifdef _DEBUG const bool SHOW_CULLING = getenv("SHOW_CULLING") != NULL; if( SHOW_CULLING ) { fprintf( stderr, "CULL log: original matrix\n" ); dbg_dump( co, stderr, "CULL" ); } #endif assert( ! _immediatelyDegenerate( co ) ); // so BOTH dims >= 2 while( (co->decl_rows > 2 || co->decl_cols > 2) && _badCellExists( co, &raw_mem_offset ) ) { unsigned int r, c; char cullty = '?'; /** * It is always necessary to cull a row or column. * If |columns| > 3, calculate "best" column to cull. * If |rows| > 3, calculate "best" row to cull. * "Best" victim is row OR column among the candidates for * culling with minimal marginal. */ unsigned row_bitfield = 0; unsigned col_bitfield = 0; count_t minRowCost, minColCost; assert( sizeof(row_bitfield)*8 >= MAX_CATEGORY_COUNT ); // Find ALL rows and columns that are candidates for culling by // virtue of containing a bad cell. do { _coordsOfOffset( co, raw_mem_offset, &r, &c ); row_bitfield |= (1<<r); col_bitfield |= (1<<c); ++ raw_mem_offset; // Add the row and column to the list of candidate victims. } while( _badCellExists( co, &raw_mem_offset ) ); if( co->calculated < Marginals ) _calc_marginals( co ); if( co->decl_rows > 2 ) { r = _offsetOfLeastLoss( row_bitfield, co->rmarg, &minRowCost ); if( co->decl_cols > 2 ) { // EITHER a col OR row may be culled c = _offsetOfLeastLoss( col_bitfield, co->cmarg, &minColCost ); cullty = minRowCost < minColCost ? 'R' : 'C'; } else // ONLY a row may be culled cullty = 'R'; } else { // ONLY a column may be culled c = _offsetOfLeastLoss( col_bitfield, co->cmarg, &minColCost ); cullty = 'C'; } if( cullty == 'R' ) _cullRow( co, (victim = r) ); else { assert( cullty == 'C' ); _cullCol( co, (victim = c) ); } // Log it, if possible... if( pc ) { pc += sprintf( pc, "%c%d", cullty, victim ); // Following is a bit of overkill to make sure we can // give some indication that we ran out of log space. if( EOL - pc < MIN_LOG_RECORD_LEN ) { if( EOL - pc > 0 ) strcpy( pc, "+"); pc = NULL; // no more logging. // Really this should never be executed if log buffer // is always sufficient. } } // Unlike merging, decimating CAN leave a 0 cell at a lower // linear index, so reset is required... culled++; raw_mem_offset = 0; #ifdef _DEBUG if( SHOW_CULLING ) { fprintf( stderr, "CULL After %d selected %c%d (from R:%08X,C:%08X) costing %d samples\n", culled, cullty, victim, row_bitfield, col_bitfield, cullty=='R' ? minRowCost : minColCost ); dbg_dump( co, stderr, "CULL" ); } #endif } if( culled > 0 ) _recalcSampleCount( co ); return culled; } #ifdef HAVE_G_TEST int cat_g( void *pv, struct Statistic *result ) { struct CatCovars *co = (struct CatCovars *)pv; const int R = co->decl_rows; const int C = co->decl_cols; double g = 0.0; abort(); // unfinished. if( co->calculated < Expectation ) _calc_expectation( co ); for(unsigned int i = 0; i < R; i++ ) { for(unsigned int j = 0; j < C; j++ ) { const double O = _count( co, i, j ); const double E = _expected( co, i, j ); if( E > 0 && O > 0 ) g += ( O * log( O / E ) ); } } g *= 2.0; // TODO: verify! result->name = "G"; result->sample_count = co->sample_count; result->probability = gsl_cdf_chisq_Q( g, (R-1)*(C-1) ); return 0; } #endif int cat_chi_square( void *pv, struct Statistic *result ) { struct CatCovars *co = (struct CatCovars *)pv; const int R = co->decl_rows; const int C = co->decl_cols; unsigned int n_empty = 0; double chi = 0.0; if( co->calculated < Expectation ) _calc_expectation( co ); for(unsigned int i = 0; i < R; i++ ) { for(unsigned int j = 0; j < C; j++ ) { const double O = _count( co, i, j ); const double E = _expected( co, i, j ); if( E > 0 && O > 0 ) chi += ((O-E)*(O-E))/E; else if( O == 0 ) n_empty++; } } result->name = "Chi-square"; result->sample_count = co->sample_count; result->probability = gsl_cdf_chisq_Q( chi, (R-1)*(C-1) ); result->extra_value[0] = R; result->extra_value[1] = C; result->extra_value[2] = co->minimumExpected; result->extra_value[3] = n_empty; return 0; } int cat_fisher_exact( void *pv, struct Statistic *result ) { struct CatCovars *co = (struct CatCovars *)pv; // OPTIMIZE: does not make sense to call fisher exact without // NULL stest_t argument. Keeping this signature for consistency // with all other stats, but it might make sense to change the // signature of just this function to return P-value (unless I // ever added log-likelihood ratio calculation which is what // ought to be returned as the function value). /** * Given the table: * a | b * --+-- * c | d * * ...we need to pass fexact_prob( x, m, n, k ) * m == a+c * n == b+d * k == a+b * x == a */ result->name = "Fisher_Exact"; result->sample_count = co->sample_count; result->probability = fexact_prob( _count(co,0,0), _count(co,0,0) + _count(co,1,0), // a+c _count(co,0,1) + _count(co,1,1), // b+d _count(co,0,0) + _count(co,0,1) ); // a+b // TODO: Don't need these now. result->extra_value[0] = co->decl_rows; result->extra_value[1] = co->decl_cols; return 0; } /** */ double cat_spearman_rho( void *pv ) { struct CatCovars *co = (struct CatCovars *)pv; double rho = nan("nan"); const unsigned r0 = _count(co,0,0) + _count(co,0,1); const unsigned r1 = _count(co,1,0) + _count(co,1,1); const unsigned c0 = _count(co,0,0) + _count(co,1,0); const unsigned c1 = _count(co,0,1) + _count(co,1,1); // Continuing is pointless if any of these are 0. if( r0 > 0 && r1 > 0 && c0 > 0 && c1 > 0 ) { const float MU = (co->sample_count+1.0)/2.0; const float r0_mu = (r0+1.0)/2.0; const float r1_mu = MEAN_RANK_OF_TIES( r0, co->sample_count ); const float c0_mu = (c0+1.0)/2.0; const float c1_mu = MEAN_RANK_OF_TIES( c0, co->sample_count ); /** * Following is a heavily compacted form of the Pearson rho, * compacted because thanks to all the ties there are only two * "versions" of (x_i-x_mu) and (y_i-x_mu), and the general * sums in the Pearson quotient just become multiples of these. */ const double DENOM = sqrt( (r0*(r0_mu-MU)*(r0_mu-MU) + r1*(r1_mu-MU)*(r1_mu-MU)) * (c0*(c0_mu-MU)*(c0_mu-MU) + c1*(c1_mu-MU)*(c1_mu-MU)) ); if( isnormal(DENOM) ) { rho = ( _count(co,0,0)*(r0_mu-MU)*(c0_mu-MU) + _count(co,0,1)*(r0_mu-MU)*(c1_mu-MU) + _count(co,1,0)*(r1_mu-MU)*(c0_mu-MU) + _count(co,1,1)*(r1_mu-MU)*(c1_mu-MU) ) / DENOM; } } return rho; } #ifdef _UNITTEST_CAT_ #include <err.h> int main( int argc, char *argv[] ) { if( argc >= 3 ) { const int MERGE_LOG_LEN = 128; char merge_log[ MERGE_LOG_LEN ]; struct Statistic result; const unsigned int MAXROW = atoi(argv[1]); const unsigned int MAXCOL = atoi(argv[2]); FILE *fp = argc > 3 ? fopen( argv[3], "r" ) : stdin; int err = 0; char *line = NULL; size_t n = 0; void *accum = cat_create( MAXROW, MAXCOL); cat_setMinCellCount( accum, 5 ); cat_clear( accum, MAXROW, MAXCOL ); // ...as per command line. while( getline( &line, &n, fp ) > 0 ) { int cat[2]; if( line[0] == '#' ) { fputs( line, stdout ); continue; } if( 2 == sscanf( line, "%d\t%d\n", cat+0, cat+1 ) ) { if( 0 <= cat[0] && 0 <= cat[1] ) { cat_push( accum, cat[0], cat[1] ); } } else { fprintf( stderr, "Failure parsing line: %s", line ); } } free( line ); fclose( fp ); puts( "Original..." ); dbg_dump( accum, stdout, "" ); if( cat_cullBadCells( accum, merge_log, MERGE_LOG_LEN ) > 0 ) { fprintf( stdout, "Culled %s, leaving...\n", merge_log ); dbg_dump( accum, stdout, "" ); } memset( &result, 0, sizeof(struct Statistic) ); err = cat_is2x2( accum ) ? cat_fisher_exact( accum, &result ) : cat_chi_square( accum, &result ); if( ! err ) { printf( "p-value=%f", result.probability ); if( cat_is2x2( accum ) ) printf( ", spearman=%f\n", cat_spearman_rho( accum ) ); else fputc( '\n', stdout ); } else printf( "error\n" ); cat_destroy( accum ); } else err( -1, "%s <max row> <max col> [ <2-column file> ]", argv[0] ); return 0; } #endif
{ "alphanum_fraction": 0.621198199, "avg_line_length": 24.4561797753, "ext": "c", "hexsha": "dab9ec88c75e6c785809d4f5005ddae4405f874a", "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": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "IlyaLab/kramtools", "max_forks_repo_path": "pairwise/src/cat.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "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": "IlyaLab/kramtools", "max_issues_repo_path": "pairwise/src/cat.c", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "IlyaLab/kramtools", "max_stars_repo_path": "pairwise/src/cat.c", "max_stars_repo_stars_event_max_datetime": "2020-03-30T03:07:45.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-30T03:07:45.000Z", "num_tokens": 7006, "size": 21766 }
/* GENETIC - A simple genetic algorithm. Copyright 2014, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file selection.c * \brief Source file to define parents selection functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved. */ #define _GNU_SOURCE #include <math.h> #include <gsl/gsl_rng.h> //#include "config.h" #include "entity.h" #include "population.h" #include "selection.h" void (*selection_mutation) (Population *, Entity **, gsl_rng *); ///< Pointer to the function to apply mutation selection operations. void (*selection_reproduction) (Population *, Entity **, Entity **, gsl_rng *); ///< Pointer to the function to apply reproduction selection operations. void (*selection_adaptation) (Population *, Entity **, gsl_rng *); ///< Pointer to the function to apply adaptation selection operations. /** * Function to select a single random entity. */ static void selection_mutation_random (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. gsl_rng * rng) ///< GSL random numbers generator. { *mother = population->entity + gsl_rng_uniform_int (rng, population->nsurvival); } /** * Function to select the best of two random entities. */ static void selection_mutation_bestof2 (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i, j; i = gsl_rng_uniform_int (rng, population->nsurvival); j = gsl_rng_uniform_int (rng, population->nsurvival); if (j < i) i = j; *mother = population->entity + i; } /** * Function to select the best of three random entities. */ static void selection_mutation_bestof3 (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i, j; i = gsl_rng_uniform_int (rng, population->nsurvival); j = gsl_rng_uniform_int (rng, population->nsurvival); if (j < i) i = j; j = gsl_rng_uniform_int (rng, population->nsurvival); if (j < i) i = j; *mother = population->entity + i; } /** * Function to select the best entity only. */ static void selection_mutation_best (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. gsl_rng * rng __attribute__ ((unused))) ///< GSL random numbers generator. { *mother = population->entity; } /** * Function to select an entity based on linear probability distribution with * respect to rank. */ static void selection_mutation_linearrank (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i; i = (1.0 - sqrt (gsl_rng_uniform (rng))) * population->nsurvival; *mother = population->entity + i; } /** * Function to select a pair of random entities. */ static void selection_reproduction_random (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. Entity ** father, ///< Pointer to the father entity. gsl_rng * rng) ///< GSL random numbers generator. { *mother = population->entity + gsl_rng_uniform_int (rng, population->nsurvival); do *father = population->entity + gsl_rng_uniform_int (rng, population->nsurvival); while (father == mother); } /** * Function to select a pair of entities. For each parent select the best of two * random entities. */ static void selection_reproduction_bestof2 (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. Entity ** father, ///< Pointer to the father entity. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i, j, k; i = gsl_rng_uniform_int (rng, population->nsurvival); j = gsl_rng_uniform_int (rng, population->nsurvival); if (i < j) i = j; do j = gsl_rng_uniform_int (rng, population->nsurvival); while (i == j); k = gsl_rng_uniform_int (rng, population->nsurvival); if (i != k && k < j) j = k; *mother = population->entity + i; *father = population->entity + j; } /** * Function to select a pair of entities. For each parent select the best of * three random entities. */ static void selection_reproduction_bestof3 (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. Entity ** father, ///< Pointer to the father entity. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i, j, k; i = gsl_rng_uniform_int (rng, population->nsurvival); j = gsl_rng_uniform_int (rng, population->nsurvival); if (i < j) i = j; j = gsl_rng_uniform_int (rng, population->nsurvival); if (i < j) i = j; do j = gsl_rng_uniform_int (rng, population->nsurvival); while (i == j); k = gsl_rng_uniform_int (rng, population->nsurvival); if (i != k && k < j) j = k; k = gsl_rng_uniform_int (rng, population->nsurvival); if (i != k && k < j) j = k; *mother = population->entity + i; *father = population->entity + j; } /** * Function to select a pair of entities using the best and a random entity. */ static void selection_reproduction_best (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. Entity ** father, ///< Pointer to the father entity. gsl_rng * rng) ///< GSL random numbers generator. { *mother = population->entity + gsl_rng_uniform_int (rng, population->nsurvival); *father = population->entity; } /** * Function to select a pair of entities based on linear probability * distribution with respect to rank. */ static void selection_reproduction_linearrank (Population * population, ///< Population. Entity ** mother, ///< Pointer to the mother entity. Entity ** father, ///< Pointer to the father entity. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i, j; i = (unsigned int) ((1.0 - sqrt (gsl_rng_uniform (rng))) * population->nsurvival); *mother = population->entity + i; do j = (unsigned int) ((1.0 - sqrt (gsl_rng_uniform (rng))) * population->nsurvival); while (i == j); *father = population->entity + j; } /** * Function to select the selection operations. */ void selection_init (unsigned int mutation_type, ///< Type of mutation selection operations. unsigned int reproduction_type, ///< Type of reproduction selection operations. unsigned int adaptation_type) ///< Type of adaptation selection operations. { switch (mutation_type) { case SELECTION_MUTATION_TYPE_RANDOM: selection_mutation = &selection_mutation_random; break; case SELECTION_MUTATION_TYPE_BESTOF2: selection_mutation = &selection_mutation_bestof2; break; case SELECTION_MUTATION_TYPE_BESTOF3: selection_mutation = &selection_mutation_bestof3; break; case SELECTION_MUTATION_TYPE_BEST: selection_mutation = &selection_mutation_best; break; default: selection_mutation = &selection_mutation_linearrank; } switch (reproduction_type) { case SELECTION_REPRODUCTION_TYPE_RANDOM: selection_reproduction = &selection_reproduction_random; break; case SELECTION_REPRODUCTION_TYPE_BESTOF2: selection_reproduction = &selection_reproduction_bestof2; break; case SELECTION_REPRODUCTION_TYPE_BESTOF3: selection_reproduction = &selection_reproduction_bestof3; break; case SELECTION_REPRODUCTION_TYPE_BEST: selection_reproduction = &selection_reproduction_best; break; default: selection_reproduction = &selection_reproduction_linearrank; } switch (adaptation_type) { case SELECTION_ADAPTATION_TYPE_RANDOM: selection_adaptation = &selection_mutation_random; break; case SELECTION_ADAPTATION_TYPE_BESTOF2: selection_adaptation = &selection_mutation_bestof2; break; case SELECTION_ADAPTATION_TYPE_BESTOF3: selection_adaptation = &selection_mutation_bestof3; break; case SELECTION_ADAPTATION_TYPE_BEST: selection_adaptation = &selection_mutation_best; break; default: selection_adaptation = &selection_mutation_linearrank; } }
{ "alphanum_fraction": 0.6105158909, "avg_line_length": 35.0378548896, "ext": "c", "hexsha": "580205ca6acd9f014ffb539d4e9a2570191bc858", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_path": "3.0.0/selection.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_path": "3.0.0/selection.c", "max_line_length": 80, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_path": "3.0.0/selection.c", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "num_tokens": 2310, "size": 11107 }
/* matrix/gsl_matrix_complex_long_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ #define __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_complex_long_double.h> #include <gsl/gsl_blas_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; long double * data; gsl_block_complex_long_double * block; int owner; } gsl_matrix_complex_long_double ; typedef struct { gsl_matrix_complex_long_double matrix; } _gsl_matrix_complex_long_double_view; typedef _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view; typedef struct { gsl_matrix_complex_long_double matrix; } _gsl_matrix_complex_long_double_const_view; typedef const _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view; /* Allocation */ GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_calloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc_from_matrix (gsl_matrix_complex_long_double * b, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_FUN gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_row_from_matrix (gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_col_from_matrix (gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN void gsl_matrix_complex_long_double_free (gsl_matrix_complex_long_double * m); /* Views */ GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_submatrix (gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_row (gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_column (gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_diagonal (gsl_matrix_complex_long_double * m); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subdiagonal (gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_superdiagonal (gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subrow (gsl_matrix_complex_long_double * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subcolumn (gsl_matrix_complex_long_double * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_array (long double * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_array_with_tda (long double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_vector (gsl_vector_complex_long_double * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_vector_with_tda (gsl_vector_complex_long_double * v, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_submatrix (const gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_row (const gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_column (const gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_diagonal (const gsl_matrix_complex_long_double * m); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subdiagonal (const gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_superdiagonal (const gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subrow (const gsl_matrix_complex_long_double * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subcolumn (const gsl_matrix_complex_long_double * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_array (const long double * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_array_with_tda (const long double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_vector (const gsl_vector_complex_long_double * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_vector_with_tda (const gsl_vector_complex_long_double * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_FUN void gsl_matrix_complex_long_double_set_zero (gsl_matrix_complex_long_double * m); GSL_FUN void gsl_matrix_complex_long_double_set_identity (gsl_matrix_complex_long_double * m); GSL_FUN void gsl_matrix_complex_long_double_set_all (gsl_matrix_complex_long_double * m, gsl_complex_long_double x); GSL_FUN int gsl_matrix_complex_long_double_fread (FILE * stream, gsl_matrix_complex_long_double * m) ; GSL_FUN int gsl_matrix_complex_long_double_fwrite (FILE * stream, const gsl_matrix_complex_long_double * m) ; GSL_FUN int gsl_matrix_complex_long_double_fscanf (FILE * stream, gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_fprintf (FILE * stream, const gsl_matrix_complex_long_double * m, const char * format); GSL_FUN int gsl_matrix_complex_long_double_memcpy(gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); GSL_FUN int gsl_matrix_complex_long_double_swap(gsl_matrix_complex_long_double * m1, gsl_matrix_complex_long_double * m2); GSL_FUN int gsl_matrix_complex_long_double_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); GSL_FUN int gsl_matrix_complex_long_double_swap_rows(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_swap_columns(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_swap_rowcol(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_transpose (gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_transpose_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); GSL_FUN int gsl_matrix_complex_long_double_transpose_tricpy(CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); GSL_FUN int gsl_matrix_complex_long_double_conjtrans_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); GSL_FUN int gsl_matrix_complex_long_double_equal (const gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_isnull (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_ispos (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_isneg (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_isnonneg (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_add (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_sub (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_mul_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_div_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_scale (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); GSL_FUN int gsl_matrix_complex_long_double_scale_rows (gsl_matrix_complex_long_double * a, const gsl_vector_complex_long_double * x); GSL_FUN int gsl_matrix_complex_long_double_scale_columns (gsl_matrix_complex_long_double * a, const gsl_vector_complex_long_double * x); GSL_FUN int gsl_matrix_complex_long_double_add_constant (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); GSL_FUN int gsl_matrix_complex_long_double_add_diagonal (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_FUN int gsl_matrix_complex_long_double_get_row(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN int gsl_matrix_complex_long_double_get_col(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_set_row(gsl_matrix_complex_long_double * m, const size_t i, const gsl_vector_complex_long_double * v); GSL_FUN int gsl_matrix_complex_long_double_set_col(gsl_matrix_complex_long_double * m, const size_t j, const gsl_vector_complex_long_double * v); /***********************************************************************/ /* inline functions if you are using GCC */ GSL_FUN INLINE_DECL gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x); GSL_FUN INLINE_DECL gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j); #ifdef HAVE_INLINE INLINE_FUN gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { gsl_complex_long_double zero = {{0,0}}; if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, zero) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, zero) ; } } #endif return *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } INLINE_FUN void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } } #endif *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) = x ; } INLINE_FUN gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } INLINE_FUN const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (const gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ */
{ "alphanum_fraction": 0.7220347155, "avg_line_length": 44.9647696477, "ext": "h", "hexsha": "79212ab8e6a0e2203c5289c88ff6fc6d99f322d5", "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": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_complex_long_double.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_complex_long_double.h", "max_line_length": 185, "max_stars_count": null, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_matrix_complex_long_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3702, "size": 16592 }
// This random generator is a C++ wrapper for the GNU Scientific Library // Copyright (C) 2001 Torbjorn Vik // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #ifndef __histogram_h #define __histogram_h #include <gsl/gsl_histogram.h> #include <stdexcept> #include <exception> namespace gsl{ #ifndef __HP_aCC using std::string; using std::runtime_error; #endif //! Encapsulates the histogram object of gsl. Only uniformly spaced bins yet. class histogram { public: histogram(int nBins, double xmin, double xmax) { h=gsl_histogram_calloc(nBins); if (!h) { throw runtime_error("Couldn't allocate memory for histogram"); } gsl_histogram_set_ranges_uniform(h, xmin, xmax); } ~histogram(){gsl_histogram_free(h);} //@{ Updating and Accessing Methods int increment(double x){return gsl_histogram_increment(h, x);} int accumulate(double x, double weight){return gsl_histogram_accumulate(h, x, weight);} double get(int i) const {return gsl_histogram_get(h, i);} double& operator[](const uint & i) { const uint n = h->n; if (i >= n) { throw runtime_error("index lies outside valid range of 0 .. n - 1"); // GSL_ERROR_VAL ("index lies outside valid range of 0 .. n - 1", GSL_EDOM, 0); } return h->bin[i]; } const double& operator[](const uint & i) const //{return (*this)[i];/*gsl_histogram_get(h, i);*/} { const uint n = h->n; if (i >= n) { throw runtime_error("index lies outside valid range of 0 .. n - 1"); // GSL_ERROR_VAL ("index lies outside valid range of 0 .. n - 1", GSL_EDOM, 0); } return h->bin[i]; } void get_range(int i, double& xmin, double& xmax) const {gsl_histogram_get_range(h, i, &xmin, &xmax);} //@} //@{These functions return the maximum upper and minimum lower range limits // and the number of bins of the histogram h. They provide a way of determining these values without // accessing the gsl_histogram struct directly. double max() const {return gsl_histogram_max(h);} double min() const {return gsl_histogram_min(h);} int bins()const {return gsl_histogram_bins(h);} int size()const {return gsl_histogram_bins(h);} //@} //@{ Histogram statistics double mean()const {return gsl_histogram_mean(h);} // not in gsl library ? double max_val() const {return gsl_histogram_max_val(h);} int max_bin() const {return gsl_histogram_max_bin(h);} double min_val() const {return gsl_histogram_min_val(h);} int min_bin() const {return gsl_histogram_min_bin(h);} double sum() const {return gsl_histogram_sum(h);} //@} //@{ Accessor for gsl compatibility gsl_histogram* gslobj() { return h;} const gsl_histogram* gslobj() const { return h;} //@} protected: gsl_histogram * h; }; } #endif // __histogram_h
{ "alphanum_fraction": 0.7103857567, "avg_line_length": 31.2037037037, "ext": "h", "hexsha": "61408fac42a672fed949f8a37def05821ff6f8bd", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_path": "src/gslwrap/histogram.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_path": "src/gslwrap/histogram.h", "max_line_length": 103, "max_stars_count": 4, "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_path": "src/gslwrap/histogram.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": 862, "size": 3370 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "engine_error.h" #include "types.h" #include <gsl/gsl> struct ServerDocumentIface { virtual ~ServerDocumentIface() = default; /** * This callback is called from the underlying engine right before * it is linked into the list of available documents (it is currently * not visible to anyone). The engine should have validated all * properties set in the document by the client and the core, and * assigned a new CAS number for the document (and sequence number if * the underlying engine use those). * * The callback may at this time do post processing of the document * content (it is allowed to modify the content data, but not * reallocate or change the size of the data in any way). * * Given that the engine MAY HOLD LOCKS when calling this function * the core is *NOT* allowed to acquire *ANY* locks (except for doing * some sort of memory allocation for a temporary buffer). * * @param cookie The cookie provided to the engine for the storage * command which may (which may hold more context) * @param info the items underlying data * @return ENGINE_SUCCESS means that the underlying engine should * proceed to link the item. All other * error codes means that the engine should * *NOT* link the item */ virtual ENGINE_ERROR_CODE pre_link(gsl::not_null<const void*> cookie, item_info& info) = 0; /** * This callback is called from the underlying engine right before * a particular document expires. The callback is responsible for * modifying the contents of the itm_info passed in. The updated * total size is available in itm_info.nbytes. * * @param itm_info info pertaining to the item that is to be expired. * @return true indicating that the info has been modified in itm_info. * false indicating that there is no data available in itm_info. * @throws std::bad_alloc in case of memory allocation failure * @throws std::logic_error if the data has grown */ virtual bool pre_expiry(item_info& itm_info) = 0; };
{ "alphanum_fraction": 0.6664420485, "avg_line_length": 43.0144927536, "ext": "h", "hexsha": "7e4ef62f72016d896f7af47675991f906b2d5d96", "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": "233945fe4ddb033c2292e51f5845ab630c33276f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "gsauere/kv_engine", "max_forks_repo_path": "include/memcached/server_document_iface.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "233945fe4ddb033c2292e51f5845ab630c33276f", "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": "gsauere/kv_engine", "max_issues_repo_path": "include/memcached/server_document_iface.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "233945fe4ddb033c2292e51f5845ab630c33276f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "gsauere/kv_engine", "max_stars_repo_path": "include/memcached/server_document_iface.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 654, "size": 2968 }
#include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> // author: Andrew Liew <liew@arch.ethz.ch> // copyright: Copyright 2018, BLOCK Research Group - ETH Zurich // license: MIT License // email: liew@arch.ethz.ch int i; int j; // ========================================================================================================== // One vector // ========================================================================================================== double length_vector(gsl_vector *u) { double L = gsl_blas_dnrm2(u); return L; } double length_vector_squared(gsl_vector *u) { double a = 0.; for (i = 0; i < 3; i++) { a += gsl_pow_2(gsl_vector_get(u, i)); } return a; } void normalize_vector(gsl_vector *u) { gsl_vector_scale(u, 1./length_vector(u)); } void scale_vector(gsl_vector *u, double a) { gsl_vector_scale(u, a); } void vector_from_pointer(double *ptr, gsl_vector *w) { gsl_vector_set(w, 0, *(ptr + 0)); gsl_vector_set(w, 1, *(ptr + 1)); gsl_vector_set(w, 2, *(ptr + 2)); } // ========================================================================================================== // Two vectors // ========================================================================================================== void add_vectors(const gsl_vector *u, const gsl_vector *v, gsl_vector *w) { gsl_vector_memcpy(w, u); gsl_vector_add(w, v); } void cross_vectors(const gsl_vector *u, const gsl_vector *v, gsl_vector *w) { double w1 = gsl_vector_get(u, 1) * gsl_vector_get(v, 2) - gsl_vector_get(u, 2) * gsl_vector_get(v, 1); double w2 = gsl_vector_get(u, 2) * gsl_vector_get(v, 0) - gsl_vector_get(u, 0) * gsl_vector_get(v, 2); double w3 = gsl_vector_get(u, 0) * gsl_vector_get(v, 1) - gsl_vector_get(u, 1) * gsl_vector_get(v, 0); gsl_vector_set(w, 0, w1); gsl_vector_set(w, 1, w2); gsl_vector_set(w, 2, w3); } double dot_vectors(const gsl_vector *u, const gsl_vector *v) { double a = 0.; for (i = 0; i < 3; i++) { a += gsl_vector_get(u, i) * gsl_vector_get(v, i); } return a; } void subtract_vectors(const gsl_vector *u, const gsl_vector *v, gsl_vector *w) { gsl_vector_memcpy(w, u); gsl_vector_sub(w, v); }
{ "alphanum_fraction": 0.515807709, "avg_line_length": 22.2019230769, "ext": "h", "hexsha": "cd7fd34e0f9d86458b3bca6f8432afb9c4aaf032", "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": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "philianeles/compas", "max_forks_repo_path": "src/compas_hpc/geometry/basic_c.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "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": "philianeles/compas", "max_issues_repo_path": "src/compas_hpc/geometry/basic_c.h", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "philianeles/compas", "max_stars_repo_path": "src/compas_hpc/geometry/basic_c.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 622, "size": 2309 }
#pragma once #include "halleystring.h" #include "halley/data_structures/vector.h" #include <optional> #include <gsl/span> namespace Halley { class FuzzyTextMatcher { public: class Score { public: int curJumps = 0; int jumpLength = 0; int sections = 0; int sectionLens = 0; int sectionPos = 0xFFFF; Vector<std::pair<uint16_t, uint16_t>> matchPositions; bool operator<(const Score& other) const; Score advance(int jumpLen, int sectionPos, int newSectionLen) const; void makeMatchPositions(const Vector<int>& breadcrumbs); }; class Result { public: Result() = default; Result(String str, String id, Score score); bool operator<(const Result& other) const; const String& getString() const; const String& getId() const; gsl::span<const std::pair<uint16_t, uint16_t>> getMatchPositions() const; private: String str; String id; Vector<std::pair<uint16_t, uint16_t>> matchPositions; Score score; }; FuzzyTextMatcher(bool caseSensitive, std::optional<size_t> resultsLimit); void addStrings(Vector<String> strings); void addString(String string, String id = ""); void clear(); Vector<Result> match(const String& query) const; private: struct Entry { String string; String id; }; Vector<Entry> strings; bool caseSensitive; std::optional<size_t> resultsLimit; std::optional<Result> match(const String& str, const String& id, const StringUTF32& query) const; }; }
{ "alphanum_fraction": 0.6272838002, "avg_line_length": 25.2615384615, "ext": "h", "hexsha": "cafc2602c2995c6640f80bab2517cbd132a6493f", "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/engine/utils/include/halley/text/fuzzy_text_matcher.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/engine/utils/include/halley/text/fuzzy_text_matcher.h", "max_line_length": 102, "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/engine/utils/include/halley/text/fuzzy_text_matcher.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 384, "size": 1642 }
/* histogram/ntuple.h * * Copyright (C) 2000 Simone Piccardi * * 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. * */ /* Jan/2001 Modified by Brian Gough. Minor changes for GSL */ #ifndef __GSL_NTUPLE_H__ #define __GSL_NTUPLE_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.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 { FILE * file; void * ntuple_data; size_t size; } gsl_ntuple; typedef struct { int (* function) (void * ntuple_data, void * params); void * params; } gsl_ntuple_select_fn; typedef struct { double (* function) (void * ntuple_data, void * params); void * params; } gsl_ntuple_value_fn; GSL_FUN gsl_ntuple * gsl_ntuple_open (char * filename, void * ntuple_data, size_t size); GSL_FUN gsl_ntuple * gsl_ntuple_create (char * filename, void * ntuple_data, size_t size); GSL_FUN int gsl_ntuple_write (gsl_ntuple * ntuple); GSL_FUN int gsl_ntuple_read (gsl_ntuple * ntuple); GSL_FUN int gsl_ntuple_bookdata (gsl_ntuple * ntuple); /* synonym for write */ GSL_FUN int gsl_ntuple_project (gsl_histogram * h, gsl_ntuple * ntuple, gsl_ntuple_value_fn *value_func, gsl_ntuple_select_fn *select_func); GSL_FUN int gsl_ntuple_close (gsl_ntuple * ntuple); __END_DECLS #endif /* __GSL_NTUPLE_H__ */
{ "alphanum_fraction": 0.6972332016, "avg_line_length": 27.2043010753, "ext": "h", "hexsha": "8392ca9d0fbc80831f2b7b74e4e6bdb9f7b6e1b0", "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": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_ntuple.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_ntuple.h", "max_line_length": 82, "max_stars_count": 2, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_ntuple.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 646, "size": 2530 }
#ifndef __NODE_H__ #define __NODE_H__ //#include <pybind11/functional.h> #include <pybind11/numpy.h> //#include <pybind11/stl.h> //#include <pybind11/pybind11.h> #include <torch/script.h> #include <pybind11/embed.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <iomanip> #include <sstream> #include <cmath> #include <math.h> #include <string> #include <memory> #include <mutex> #include "state.h" namespace py = pybind11; struct Node{ public: int select(State *state, double cpuct); struct Node* next_node(int action); struct Node* make_move(int action); void backpropagate(int action, float value); void set_prior(torch::Tensor p, gsl_rng *r, const double *alpha, double dir_eps); void set_prior(State *state, gsl_rng *r, const double *alpha, const double dir_eps); std::array<long int, SIZE>* counts(); std::string repr(); std::string print_u(State *state, double cpuct); bool is_null(int a); long long int nodeN; std::mutex node_mutex; std::array<double, SIZE> childP; // std::string name; //Node(std::string &name, int a); Node(); ~Node(); private: std::array<std::unique_ptr<Node>, SIZE> child; int child_cnt; std::array<long int, SIZE> childN; std::array<double, SIZE> childW; }; #endif
{ "alphanum_fraction": 0.7150928168, "avg_line_length": 24.2941176471, "ext": "h", "hexsha": "734a8e92bf590bb608a323f0d98eb41060114b4c", "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": "f2e333dfb11559a2bc9fdea1b3179fe4de05f93d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SlavkaMichal/alphazero", "max_forks_repo_path": "mcts/src/node.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f2e333dfb11559a2bc9fdea1b3179fe4de05f93d", "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": "SlavkaMichal/alphazero", "max_issues_repo_path": "mcts/src/node.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "f2e333dfb11559a2bc9fdea1b3179fe4de05f93d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SlavkaMichal/alphazero", "max_stars_repo_path": "mcts/src/node.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 333, "size": 1239 }
/************************************************************************//** * @file time_evolution.c * * This file contains code to advance the solutions one step forward in time * * *****************************************************************************/ #include <stdio.h> #include <math.h> #include <gsl/gsl_vector.h> #include "ChannelsAndJunctions.h" #include "MeshAttributes.h" #include "mathfunctions.h" #include "oneTimeStep.h" /* @cond GLOBAL_VARIABLES */ extern const double g; /* @endcond */ /***************************************************************************//** * * Function to advance a channel structure one step forward in time using 2-stage * RKDG scheme * @param[in] Chan channel structure that we are currently working on * @param[in] time current time of the simulation * @param[in] dt size of the time step * @param[in] channelNumber identity (number) of the channel structure that we * are currently working on * * *********************************************************************************/ void oneTimeStep (struct channel *Chan, double time, double dt, int channelNumber) { int TotalNumNodes = 2*Chan->NumNodes; double RHSA[TotalNumNodes]; double RHSQ[TotalNumNodes]; // Calculate wet/dry status of elements #ifdef WDON wetDryStatus1D(Chan); #endif // store A and Q gsl_vector *A = gsl_vector_alloc(TotalNumNodes); gsl_vector *Q = gsl_vector_alloc(TotalNumNodes); for (int i=0; i < TotalNumNodes; ++i) { gsl_vector_set(A,i,(*Chan).A[i]); gsl_vector_set(Q,i,(*Chan).Q[i]); } /******** For debugging print out RHSA and RHSQ)************/ #ifdef DEBUG printf("Intial A and Q:\n"); gsl_vector_fprintf(stdout, A, "%1.16f"); printf("\n"); gsl_vector_fprintf(stdout, Q, "%1.16f"); printf("\n"); #endif /***********************************************************/ // Intermediate RK step computeL(Chan, time, channelNumber, RHSA, RHSQ); gsl_vector *gRHSA = gsl_vector_alloc(TotalNumNodes); gsl_vector *gRHSQ = gsl_vector_alloc(TotalNumNodes); for (int i=0; i<TotalNumNodes; ++i) { gsl_vector_set(gRHSA,i,RHSA[i]); gsl_vector_set(gRHSQ,i,RHSQ[i]); } /******** For debugging print out RHSA and RHSQ)************/ #ifdef DEBUG printf("RHSA and RHSQ after first computeL:\n"); gsl_vector_fprintf(stdout, RHSA, "%1.16f"); printf("\n"); gsl_vector_fprintf(stdout, RHSQ, "%1.16f"); printf("\n"); #endif /***********************************************************/ // w_1 = w + dt*L gsl_vector *A_1 = gsl_vector_alloc(TotalNumNodes); gsl_vector *Q_1 = gsl_vector_alloc(TotalNumNodes); for (int i=0; i<TotalNumNodes; ++i) { gsl_vector_set(A_1,i,gsl_vector_get(A,i)); gsl_vector_set(Q_1,i,gsl_vector_get(Q,i)); } gsl_vector_scale(gRHSA,dt); gsl_vector_scale(gRHSQ,dt); gsl_vector_add(A_1,gRHSA); gsl_vector_add(Q_1,gRHSQ); /******** For debugging print out A_1 and Q_1************/ #ifdef DEBUG printf("A_1 and Q_1\n"); gsl_vector_fprintf(stdout, A_1, "%1.16f"); printf("\n"); gsl_vector_fprintf(stdout, Q_1, "%1.16f"); printf("\n"); #endif /***********************************************************/ for (int i=0; i <TotalNumNodes; ++i) { Chan->A[i] = gsl_vector_get(A_1,i); Chan->Q[i] = gsl_vector_get(Q_1,i); } // Apply minmod slope limiter on w_1 minmod(Chan); #ifdef WDON // apply the positive-depth operaton on w_1 PDop1D(Chan); // Caculate wet/dry status again wetDryStatus1D(Chan); #endif // internal_BC(); boundary_conditions(); for (int i = 0; i<TotalNumNodes; ++i) { gsl_vector_set(A_1,i,Chan->A[i]); gsl_vector_set(Q_1,i,Chan->Q[i]); } /******** For debugging print out A and Q************/ /* #ifdef DEBUG printf("A and Q after first minmod\n"); gsl_vector_fprintf(stdout, A_1, "%e"); printf("\n"); gsl_vector_fprintf(stdout, Q_1, "%e"); printf("\n"); #endif */ /***********************************************************/ // Compute w computeL(Chan, time, channelNumber, RHSA, RHSQ); for (int i=0; i<TotalNumNodes; ++i) { gsl_vector_set(gRHSA, i, RHSA[i]); gsl_vector_set(gRHSQ, i, RHSQ[i]); } /******** For debugging print out RHSA and RHSQ)************/ #ifdef DEBUG printf("RHSA and RHSQ after second computeL:\n"); gsl_vector_fprintf(stdout, RHSA, "%1.16f"); printf("\n"); gsl_vector_fprintf(stdout, RHSQ, "%1.16f"); printf("\n"); #endif /***********************************************************/ // w_1 = w + w_1 gsl_vector_add(A_1,A); gsl_vector_add(Q_1,Q); // w = (w1 + dt*L)/2 gsl_vector_scale(A_1,0.5); gsl_vector_scale(Q_1,0.5); gsl_vector_scale(gRHSA,dt/2); gsl_vector_scale(gRHSQ,dt/2); gsl_vector_add(A_1,gRHSA); gsl_vector_add(Q_1,gRHSQ); for (int i=0; i < TotalNumNodes; ++i) { Chan->A[i] = gsl_vector_get(A_1,i); Chan->Q[i] = gsl_vector_get(Q_1,i); } /******** For debugging print out A and Q)************/ #ifdef DEBUG printf("A and Q after second computeL:\n"); gsl_vector_fprintf(stdout, A_1, "%1.16f"); printf("\n"); gsl_vector_fprintf(stdout, Q_1, "%1.16f"); printf("\n"); #endif /***********************************************************/ // Apply minmod slope limiter to w minmod(Chan); #ifdef WDON PDop1D(Chan); #endif gsl_vector_free(A); gsl_vector_free(Q); gsl_vector_free(A_1); gsl_vector_free(Q_1); gsl_vector_free(gRHSA); gsl_vector_free(gRHSQ); boundary_conditions(); } /***************************************************************************//** * * Function to advance a junction structure one step forward in time using 2-stage * RKDG scheme * @param[in] junc the junction tructure that we are currently working on * @param[in] time current time of the simulation * @param[in] dt size of the time step * * *********************************************************************************/ void oneTimeStep2D (struct junction *junc, double time, double dt) { int NumEl = junc->NumEl; int NumEdges = 3*NumEl; double RHSZeta[NumEdges], RHSQx[NumEdges], RHSQy[NumEdges]; #ifdef WDON wetDryStatus2D(junc); #endif // store H, Qx, Qy gsl_vector *zeta = gsl_vector_alloc(NumEdges); gsl_vector *Qx = gsl_vector_alloc(NumEdges); gsl_vector *Qy = gsl_vector_alloc(NumEdges); int j = 0; for (int i=0; i < NumEl; ++i) { for (int k=0; k < 3; ++k){ gsl_vector_set(zeta,j,junc->zeta[index(i,k,3)]); gsl_vector_set(Qx,j, junc->Qx[index(i,k,3)]); gsl_vector_set(Qy,j, junc->Qy[index(i,k,3)]); ++j; } } /************ print out zeta, Qx and Qy for debugging ********************/ #ifdef DEBUG printf("Initial values:\n zeta \n"); gsl_vector_fprintf(stdout,zeta,"%e"); printf("\n Qx \n"); gsl_vector_fprintf(stdout,Qx,"%e"); printf("\n Qy \n"); gsl_vector_fprintf(stdout,Qy,"%e"); printf("\n"); #endif /***************************************************************************/ // Intermediate RK step compute2DL(junc, time, RHSZeta, RHSQx, RHSQy); gsl_vector *gRHSZeta = gsl_vector_alloc(NumEdges); gsl_vector *gRHSQx = gsl_vector_alloc(NumEdges); gsl_vector *gRHSQy = gsl_vector_alloc(NumEdges); j = 0; for (int i=0; i < NumEl; ++i) { for (int k=0; k < 3; ++k){ gsl_vector_set(gRHSZeta,j,RHSZeta[index(i,k,3)]); gsl_vector_set(gRHSQx,j,RHSQx[index(i,k,3)]); gsl_vector_set(gRHSQy,j,RHSQy[index(i,k,3)]); ++j; } } /************ print out RHSZeta, RHSQx and RHSQy for debugging ********************/ #ifdef DEBUG printf("After first computeL:\n RHSZeta \n"); gsl_vector_fprintf(stdout,RHSZeta,"%e"); printf("\n RHSQx \n"); gsl_vector_fprintf(stdout,RHSQx,"%e"); printf("\n RHSQy \n"); gsl_vector_fprintf(stdout,RHSQy,"%e"); printf("\n"); #endif /***************************************************************************/ // w_1 = w + dt*L; gsl_vector *zeta_1 = gsl_vector_alloc(NumEdges); gsl_vector *Qx_1 = gsl_vector_alloc(NumEdges); gsl_vector *Qy_1 = gsl_vector_alloc(NumEdges); for (int i=0; i<NumEdges; ++i) { gsl_vector_set(zeta_1,i,gsl_vector_get(zeta,i)); gsl_vector_set(Qx_1,i,gsl_vector_get(Qx,i)); gsl_vector_set(Qy_1,i,gsl_vector_get(Qy,i)); } gsl_vector_scale(gRHSZeta,dt); gsl_vector_scale(gRHSQx,dt); gsl_vector_scale(gRHSQy,dt); gsl_vector_add(zeta_1,gRHSZeta); gsl_vector_add(Qx_1, gRHSQx); gsl_vector_add(Qy_1, gRHSQy); /************ print out zeta, Qx and Qy for debugging ********************/ #ifdef DEBUG printf("After first computeL:\n Zeta \n"); gsl_vector_fprintf(stdout,zeta_1,"%e"); printf("\n Qx \n"); gsl_vector_fprintf(stdout,Qx_1,"%e"); printf("\n Qy \n"); gsl_vector_fprintf(stdout,Qy_1,"%e"); printf("\n"); #endif /***************************************************************************/ j = 0; for (int i=0; i<NumEl; ++i){ for (int k =0; k < 3; ++k){ junc->zeta[index(i,k,3)] = gsl_vector_get(zeta_1,j); junc->Qx[index(i,k,3)] = gsl_vector_get(Qx_1,j); junc->Qy[index(i,k,3)] = gsl_vector_get(Qy_1,j); ++j; } } // Apply minmod slope limiter on w_1 SlopeLimiter(junc); // internal_BC(); #ifdef WDON PDop2D(junc); wetDryStatus2D(junc); #endif j = 0; for (int i=0; i<NumEl; ++i) { for(int k=0; k <3; ++k) { gsl_vector_set(zeta_1,j,junc->zeta[index(i,k,3)]); gsl_vector_set(Qx_1,j,junc->Qx[index(i,k,3)]); gsl_vector_set(Qy_1,j,junc->Qy[index(i,k,3)]); ++j; } } /************ print out zeta, Qx and Qy for debugging ********************/ #ifdef DEBUG printf("After first slope limiting:\n zeta \n"); gsl_vector_fprintf(stdout,zeta_1,"%e"); printf("\n Qx \n"); gsl_vector_fprintf(stdout,Qx_1,"%e"); printf("\n Qy \n"); gsl_vector_fprintf(stdout,Qy_1,"%e"); printf("\n"); #endif /***************************************************************************/ // w_1 = w_1 + w; gsl_vector_add(zeta_1,zeta); gsl_vector_add(Qx_1, Qx); gsl_vector_add(Qy_1,Qy); // Compute w compute2DL(junc, time, RHSZeta, RHSQx, RHSQy); j = 0; for (int i=0; i < NumEl; ++i) { for (int k=0; k < 3; ++k){ gsl_vector_set(gRHSZeta,j,RHSZeta[index(i,k,3)]); gsl_vector_set(gRHSQx,j,RHSQx[index(i,k,3)]); gsl_vector_set(gRHSQy,j,RHSQy[index(i,k,3)]); ++j; } } /************ print out zeta, Qx and Qy for debugging ********************/ #ifdef DEBUG printf("After second computeL:\n RHSZeta \n"); gsl_vector_fprintf(stdout,RHSZeta,"%e"); printf("\n RHSQx \n"); gsl_vector_fprintf(stdout,RHSQx,"%e"); printf("\n RHSQy \n"); gsl_vector_fprintf(stdout,RHSQy,"%e"); printf("\n"); #endif /***************************************************************************/ gsl_vector_scale(zeta_1,0.5); gsl_vector_scale(Qx_1,0.5); gsl_vector_scale(Qy_1,0.5); gsl_vector_scale(gRHSZeta,dt/2); gsl_vector_scale(gRHSQx,dt/2); gsl_vector_scale(gRHSQy,dt/2); gsl_vector_add(zeta_1,gRHSZeta); gsl_vector_add(Qx_1,gRHSQx); gsl_vector_add(Qy_1,gRHSQy); j = 0; for (int i=0; i<NumEl; ++i){ for (int k =0; k < 3; ++k){ junc->zeta[index(i,k,3)] = gsl_vector_get(zeta_1,j); junc->Qx[index(i,k,3)] = gsl_vector_get(Qx_1,j); junc->Qy[index(i,k,3)] = gsl_vector_get(Qy_1,j); ++j; } } // Apply minmod slope limiter to w SlopeLimiter(junc); #ifdef WDON PDop2D(junc); #endif gsl_vector_free(zeta); gsl_vector_free(Qx); gsl_vector_free(Qy); gsl_vector_free(zeta_1); gsl_vector_free(Qx_1); gsl_vector_free(Qy_1); gsl_vector_free(gRHSZeta); gsl_vector_free(gRHSQx); gsl_vector_free(gRHSQy); } /*******************************************************************//** * * Function to evolve the channels as well as the junctions through time * until the final simulation time. It also outputs the data at a certain * time * * *********************************************************************/ void time_evolution(double FinalTime) { //Output initial conditions FILE* file1; FILE* file2; for (int i=0; i<NumChannels; ++i) { char filename1[100]; char filename2[100]; sprintf(filename1, "000_Zeta%d.dat", i); sprintf(filename2, "000_Q%d.dat", i); file1 = fopen(filename1, "w"); file2 = fopen(filename2, "w"); fprintf(file1, "Height at time 0 for Channel %d\n", i); fprintf(file2, "Q at time 0 for Channel %d\n", i); int NumNodes = ChannelList[i]->NumNodes; for (int j = 0; j<NumNodes; ++j) { double B; double z; B = ChannelList[i]->b[j]; z = ChannelList[i]->z[j]; double x_val = ChannelList[i]->x[j]; double y_val = ChannelList[i]->y[j]; for (int k=0; k<2; ++k) { double A = ChannelList[i]->A[index(j,k,2)]; double Q = ChannelList[i]->Q[index(j,k,2)]; double H = A/B; double zeta = H - z; fprintf(file1, "%e\t%e\t%e\t%e\n", x_val, y_val, -z, H); fprintf(file2, "%e\t%e\t%e\t%e\n", x_val, y_val, -z, Q); } } fclose(file1); fclose(file2); } // output the file with x y and z information for the elements /* FILE *juncMesh; for (int i=0; i <NumJunctions; ++i) { char filename1[100]; sprintf(filename1, "Junction%dMesh.dat",i); juncMesh = fopen(filename1, "w"); int NumEl = JunctionList[i]->NumEl; int NumNodes = JunctionList[i]->NumNodes; int NumEdges = JunctionList[i]->TotalNumEdges; fprintf(juncMesh, "NodeNum \t x \t\t y \t\t z\n"); for (int j = 0; j < NumNodes; ++j) { double xcor = JunctionList[i]->x[j]; double ycor = JunctionList[i]->y[j]; double zcor = JunctionList[i]->z[j]; fprintf(juncMesh, "%d\t%e\t%e\t%e\n",j+1, xcor, ycor, zcor); } fprintf(juncMesh, "\n EltoVert \n"); for (int j = 0; j < NumEl; ++j) { int n1 = JunctionList[i]->EltoVert[j*3]+1; int n2 = JunctionList[i]->EltoVert[j*3+1]+1; int n3 = JunctionList[i]->EltoVert[j*3+2]+1; fprintf(juncMesh, "%d\t3\t%d\t%d\t%d\n", j+1, n1, n2,n3); } fprintf(juncMesh, "\n EdgtoVert \n"); for (int j =0; j < NumEdges; ++j) { int n1 = JunctionList[i]->EdgtoVert[j*2]+1; int n2 = JunctionList[i]->EdgtoVert[j*2+1]+1; fprintf(juncMesh, "%d\t%d\n",n1,n2); } fprintf(juncMesh, "\n EdgtoEls \n"); for (int j =0; j < NumEdges; ++j) { int n1 = JunctionList[i]->EdgtoEls[j*2]; int n2 = JunctionList[i]->EdgtoEls[j*2+1]; fprintf(juncMesh, "%d\t%d\n",n1,n2); } fclose(juncMesh); } */ boundary_conditions(); double time = 0; double dt = 1e-5; int Nstep = 0; int fileNumber = 1; double minLength = 99999999; for (int i = 0; i < NumChannels; ++i) { minLength = fmin(minLength, ChannelList[i]->mindh); } for (int i = 0; i < NumJunctions; ++i) { minLength = fmin(minLength, JunctionList[i]->minEdgLength); } while (time < FinalTime) { time = time + dt; printf("dt = %e\n", dt); printf("time = %e\n", time); double maxLambda = 0; // step forward in time for(int i=0; i<NumChannels; ++i) { oneTimeStep(ChannelList[i],time,dt,i); maxLambda = fmax(maxLambda, ChannelList[i]->max_lambda); } internal_BC(); for(int i=0; i<NumJunctions; ++i) { oneTimeStep2D(JunctionList[i],time,dt); maxLambda = fmax(maxLambda, JunctionList[i]->max_lambda); } internal_BC(); boundary_conditions(); /********* Output data every twentienth step *************/ Nstep = Nstep + 1; int NstepinOneSec = floor(1./dt); if (Nstep%5000== 0 || time == FinalTime) //if (Nstep% NstepinOneSec == 0) { //Files for the channels FILE* file1; FILE* file2; for (int i=0; i<NumChannels; ++i) { char filename1[100]; char filename2[100]; sprintf(filename1, "%3.3d_Zeta%d.dat", fileNumber,i); sprintf(filename2, "%3.3d_Q%d.dat", fileNumber,i); file1 = fopen(filename1, "w"); file2 = fopen(filename2, "w"); fprintf(file1, "Height at time %e for Channel %d\n", time, i); fprintf(file2, "Q at time %e for Channel %d\n", time,i); int NumNodes = ChannelList[i]->NumNodes; for (int j = 0; j<NumNodes; ++j) { double B; double z; B = ChannelList[i]->b[j]; z = ChannelList[i]->z[j]; double x_val = ChannelList[i]->x[j]; double y_val = ChannelList[i]->y[j]; int k; for (k=0; k<2; ++k) { double A = ChannelList[i]->A[index(j,k,2)]; double Q = ChannelList[i]->Q[index(j,k,2)]; double H = A/B; double zeta = H - z; fprintf(file1, "%e\t%e\t%e\t%e\n", x_val, y_val, -z, H); fprintf(file2, "%e\t%e\t%e\t%e\n", x_val, y_val, -z, Q); } } fclose(file1); fclose(file2); } FILE* file3; FILE* file4; FILE* file5; for (int i=0; i<NumJunctions;++i) { char filename1[100]; char filename2[100]; char filename3[100]; sprintf(filename1, "%3.3d_Height_junc%d.dat", fileNumber,i); sprintf(filename2, "%3.3d_Qx_junc%d.dat", fileNumber,i); sprintf(filename3, "%3.3d_Qy_junc%d.dat", fileNumber,i); file3 = fopen(filename1, "w"); file4 = fopen(filename2, "w"); file5 = fopen(filename3, "w"); fprintf(file3, "Zeta at time %e for Junction %d\n", time, i); fprintf(file4, "Qx at time %e for Junction %d\n", time, i); fprintf(file5, "Qy at time %e for Junction %d\n", time,i); int j; int k; for (j=0; j<JunctionList[i]->NumEl; ++j) { for(k=0; k<3; ++k) { double zeta = JunctionList[i]->zeta[index(j,k,3)]; double Qx = JunctionList[i]->Qx[index(j,k,3)]; double Qy = JunctionList[i]->Qy[index(j,k,3)]; double z1 = JunctionList[i]->z[JunctionList[i]->EltoVert[j*3+k]]; double z2 = JunctionList[i]->z[JunctionList[i]->EltoVert[j*3+(k+1)%3]]; double z = 0.5*(z1+z2); double height = zeta + z; fprintf(file3, "%1.15f\t\t",height); fprintf(file4, "%1.15f\t\t",Qx); fprintf(file5, "%1.15f\t\t",Qy); } fprintf(file3, "\n"); fprintf(file4, "\n"); fprintf(file5, "\n"); } fclose(file3); fclose(file4); fclose(file5); } ++fileNumber; } /**************** Set next time step ****************/ // set next time step //printf("max_lambda = %e\n", maxlambda); //printf("mindx = %e\n", mindx); dt = 0.4*minLength/maxLambda; if ((time + dt) > FinalTime) dt = FinalTime - time; } }
{ "alphanum_fraction": 0.5779307282, "avg_line_length": 25.9223021583, "ext": "c", "hexsha": "44c7209daca174f848aa9d2bfeaeaa20cda3c352", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_path": "ChanNet/time_evolution.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "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": "evalseth/DG-RAIN", "max_issues_repo_path": "ChanNet/time_evolution.c", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_path": "ChanNet/time_evolution.c", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "num_tokens": 5903, "size": 18016 }
#ifndef CONVERTERS_H_HVFGCFVK #define CONVERTERS_H_HVFGCFVK #include <fmt/core.h> #include <gsl/gsl> #include <opencv2/imgcodecs.hpp> #include <sens_loc/conversion/depth_to_bearing.h> #include <sens_loc/conversion/depth_to_curvature.h> #include <sens_loc/conversion/depth_to_flexion.h> #include <sens_loc/conversion/depth_to_laserscan.h> #include <sens_loc/conversion/depth_to_max_curve.h> #include <util/batch_converter.h> namespace sens_loc::apps { /// \addtogroup conversion-driver /// @{ /// Batch conversion to bearing-angle images. /// \sa conversion::depth_to_bearing template <typename Intrinsic> class bearing_converter : public batch_sensor_converter<Intrinsic> { public: bearing_converter(const file_patterns& files, depth_type t, Intrinsic intrinsic) : batch_sensor_converter<Intrinsic>(files, t, std::move(intrinsic)) { if (files.horizontal.empty() && files.vertical.empty() && files.diagonal.empty() && files.antidiagonal.empty()) { throw std::invalid_argument{ "Missing output pattern for at least one bearing direction"}; } } bearing_converter(const bearing_converter&) = default; bearing_converter(bearing_converter&&) = default; bearing_converter& operator=(const bearing_converter&) = default; bearing_converter& operator=(bearing_converter&&) = default; ~bearing_converter() override = default; private: [[nodiscard]] bool process_file(const math::image<float>& depth_image, int idx) const noexcept override; }; #include "converter_bearing.h.inl" /// Convert orthographic depth-images to range (laserscan-like) images. /// \sa conversion::depth_to_laserscan template <typename Intrinsic> class range_converter : public batch_sensor_converter<Intrinsic> { public: range_converter(const file_patterns& files, depth_type t, Intrinsic intrinsic) : batch_sensor_converter<Intrinsic>(files, t, std::move(intrinsic)) {} range_converter(const range_converter&) = default; range_converter(range_converter&&) = default; range_converter& operator=(const range_converter&) = default; range_converter& operator=(range_converter&&) = default; ~range_converter() override = default; private: [[nodiscard]] bool process_file(const math::image<float>& depth_image, int idx) const noexcept override; }; #include "converter_laserscan.h.inl" /// Convert range-images to gaussian curvature images. /// \sa conversion::depth_to_gaussian_curvature template <typename Intrinsic> class gauss_curv_converter : public batch_sensor_converter<Intrinsic> { public: /// \param files,t,intrinsic normal parameters for batch conversion /// \param lower_bound,upper_bound clamping parameters. Values below/above /// will map to these values. gauss_curv_converter(const file_patterns& files, depth_type t, Intrinsic intrinsic, double lower_bound, double upper_bound) : batch_sensor_converter<Intrinsic>(files, t, std::move(intrinsic)) , lower_bound{lower_bound} , upper_bound{upper_bound} {} gauss_curv_converter(const gauss_curv_converter&) = default; gauss_curv_converter(gauss_curv_converter&&) = default; gauss_curv_converter& operator=(const gauss_curv_converter&) = default; gauss_curv_converter& operator=(gauss_curv_converter&&) = default; ~gauss_curv_converter() override = default; private: [[nodiscard]] bool process_file(const math::image<float>& depth_image, int idx) const noexcept override; double lower_bound; double upper_bound; }; /// Convert range-images to mean curvature images. /// \sa conversion::depth_to_mean_curvature template <typename Intrinsic> class mean_curv_converter : public batch_sensor_converter<Intrinsic> { public: /// \param files,t,intrinsic normal parameters for batch conversion /// \param lower_bound,upper_bound clamping parameters. Values /// below/above will map to these values. mean_curv_converter(const file_patterns& files, depth_type t, Intrinsic intrinsic, double lower_bound, double upper_bound) : batch_sensor_converter<Intrinsic>(files, t, std::move(intrinsic)) , lower_bound{lower_bound} , upper_bound{upper_bound} {} mean_curv_converter(const mean_curv_converter&) = default; mean_curv_converter(mean_curv_converter&&) = default; mean_curv_converter& operator=(const mean_curv_converter&) = default; mean_curv_converter& operator=(mean_curv_converter&&) = default; ~mean_curv_converter() override = default; private: [[nodiscard]] bool process_file(const math::image<float>& depth_image, int idx) const noexcept override; double lower_bound; double upper_bound; }; #include "converter_curvature.h.inl" /// Convert range-images to max-curve images. /// \sa conversion::depth_to_max_curve template <typename Intrinsic> class max_curve_converter : public batch_sensor_converter<Intrinsic> { public: max_curve_converter(const file_patterns& files, depth_type t, Intrinsic intrinsic) : batch_sensor_converter<Intrinsic>(files, t, std::move(intrinsic)) {} max_curve_converter(const max_curve_converter&) = default; max_curve_converter(max_curve_converter&&) = default; max_curve_converter& operator=(const max_curve_converter&) = default; max_curve_converter& operator=(max_curve_converter&&) = default; ~max_curve_converter() override = default; private: [[nodiscard]] bool process_file(const math::image<float>& depth_image, int idx) const noexcept override; }; #include "converter_max_curve.h.inl" /// Convert range-images to flexion images. /// \sa conversion::depth_to_flexion template <typename Intrinsic> class flexion_converter : public batch_sensor_converter<Intrinsic> { public: flexion_converter(const file_patterns& files, depth_type t, Intrinsic intrinsic) : batch_sensor_converter<Intrinsic>(files, t, std::move(intrinsic)) {} flexion_converter(const flexion_converter&) = default; flexion_converter(flexion_converter&&) = default; flexion_converter& operator=(const flexion_converter&) = default; flexion_converter& operator=(flexion_converter&&) = default; ~flexion_converter() override = default; private: [[nodiscard]] bool process_file(const math::image<float>& depth_image, int idx) const noexcept override; }; #include "converter_flexion.h.inl" /// @} } // namespace sens_loc::apps #endif
{ "alphanum_fraction": 0.6572514938, "avg_line_length": 42.08, "ext": "h", "hexsha": "e6bf94b82f856cdbc34c81ee548c124d1f069020", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_path": "src/apps/depth2x/converters.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_path": "src/apps/depth2x/converters.h", "max_line_length": 78, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_path": "src/apps/depth2x/converters.h", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "num_tokens": 1489, "size": 7364 }
/* roots/brent.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* brent.c -- brent root finding algorithm */ #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 a, b, c, d, e; double fa, fb, fc; } brent_state_t; static int brent_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper); static int brent_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper); static int brent_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper) { brent_state_t * state = (brent_state_t *) vstate; double f_lower, f_upper ; *root = 0.5 * (x_lower + x_upper) ; SAFE_FUNC_CALL (f, x_lower, &f_lower); SAFE_FUNC_CALL (f, x_upper, &f_upper); state->a = x_lower; state->fa = f_lower; state->b = x_upper; state->fb = f_upper; state->c = x_upper; state->fc = f_upper; state->d = x_upper - x_lower ; state->e = x_upper - x_lower ; if ((f_lower < 0.0 && f_upper < 0.0) || (f_lower > 0.0 && f_upper > 0.0)) { GSL_ERROR ("endpoints do not straddle y=0", GSL_EINVAL); } return GSL_SUCCESS; } static int brent_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper) { brent_state_t * state = (brent_state_t *) vstate; double tol, m; int ac_equal = 0; double a = state->a, b = state->b, c = state->c; double fa = state->fa, fb = state->fb, fc = state->fc; double d = state->d, e = state->e; if ((fb < 0 && fc < 0) || (fb > 0 && fc > 0)) { ac_equal = 1; c = a; fc = fa; d = b - a; e = b - a; } if (fabs (fc) < fabs (fb)) { ac_equal = 1; a = b; b = c; c = a; fa = fb; fb = fc; fc = fa; } tol = 0.5 * GSL_DBL_EPSILON * fabs (b); m = 0.5 * (c - b); if (fb == 0) { *root = b; *x_lower = b; *x_upper = b; return GSL_SUCCESS; } if (fabs (m) <= tol) { *root = b; if (b < c) { *x_lower = b; *x_upper = c; } else { *x_lower = c; *x_upper = b; } return GSL_SUCCESS; } if (fabs (e) < tol || fabs (fa) <= fabs (fb)) { d = m; /* use bisection */ e = m; } else { double p, q, r; /* use inverse cubic interpolation */ double s = fb / fa; if (ac_equal) { p = 2 * m * s; q = 1 - s; } else { q = fa / fc; r = fb / fc; p = s * (2 * m * q * (q - r) - (b - a) * (r - 1)); q = (q - 1) * (r - 1) * (s - 1); } if (p > 0) { q = -q; } else { p = -p; } if (2 * p < GSL_MIN (3 * m * q - fabs (tol * q), fabs (e * q))) { e = d; d = p / q; } else { /* interpolation failed, fall back to bisection */ d = m; e = m; } } a = b; fa = fb; if (fabs (d) > tol) { b += d; } else { b += (m > 0 ? +tol : -tol); } SAFE_FUNC_CALL (f, b, &fb); state->a = a ; state->b = b ; state->c = c ; state->d = d ; state->e = e ; state->fa = fa ; state->fb = fb ; state->fc = fc ; /* Update the best estimate of the root and bounds on each iteration */ *root = b; if ((fb < 0 && fc < 0) || (fb > 0 && fc > 0)) { c = a; } if (b < c) { *x_lower = b; *x_upper = c; } else { *x_lower = c; *x_upper = b; } return GSL_SUCCESS ; } static const gsl_root_fsolver_type brent_type = {"brent", /* name */ sizeof (brent_state_t), &brent_init, &brent_iterate}; const gsl_root_fsolver_type * gsl_root_fsolver_brent = &brent_type;
{ "alphanum_fraction": 0.5084504174, "avg_line_length": 20.0448979592, "ext": "c", "hexsha": "5cd527541a58221718c50bfdecf4174410b27b21", "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/roots/brent.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/roots/brent.c", "max_line_length": 110, "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/roots/brent.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": 1562, "size": 4911 }
#ifndef INIT #define INIT #include <assert.h> #include <stdio.h> #include <time.h> #include <math.h> /* #include <gsl/gsl_linalg.h> */ #include "macros.h" #include "algebra.h" #include "util.h" /** * Initialization of params and vectors. * These functions are not (necessarily) optimized for performance. */ void init_random(curandGenerator_t *gen) { static unsigned int seed = 1234; // TODO manage externally from this function seed++; // TODO do this on CPU to avoid data copying curandCreateGenerator(gen, CURAND_RNG_PSEUDO_XORWOW); /* curandCreateGenerator(gen, CURAND_RNG_PSEUDO_MT19937); */ curandSetPseudoRandomGeneratorSeed(*gen, seed); } void randomize(float *x, float *d_x, size_t len, curandGenerator_t gen) { // TODO do this on cpu or at runtime (per batch) curandGenerateUniform(gen, d_x, len); cuR( curandGenerateUniform(gen, d_x, len * sizeof(float) / 32) ); cudaMemcpy(x, d_x, len * sizeof(float), cudaMemcpyDeviceToHost); cudaDeviceSynchronize(); } /////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// namespace init { /////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void derive_secondary_geometry(struct Geometry& p) { p.gridSize = {p.blockDim.x * p.gridDim.x, p.blockDim.y * p.gridDim.y, 1}; p.batch_size = {MIN(p.n.x, p.thread_size.x * p.gridSize.x), MIN(p.n.y, p.thread_size.y * p.gridSize.y)}; #ifdef SQUARE_TARGET_BATCHES if (p.n.y > p.batch_size.y) { // round down to the nearest square const size_t sq = sqrt(p.batch_size.y); p.batch_size.y = sq * sq; } #endif p.n_batches = {CEIL(p.n.x, p.batch_size.x), CEIL(p.n.y, p.batch_size.y)}; check_hyper_params(p); } Geometry simple_geometry(const size_t x, const size_t y) { Geometry p; p.blockDim = {1,1,1}; p.gridDim = {1,1,1}; p.n = {x, y}; p.thread_size = {1,1}; p.n_streams = 1; derive_secondary_geometry(p); return p; } Geometry geometry(struct Params& params, const size_t x, const size_t y) { Geometry p; p.algorithm = params.algorithm; p.blockDim = params.blockDim; p.gridDim = params.gridDim; p.n = {x, y}; p.thread_size = params.thread_size; p.n_streams = params.n_streams; derive_secondary_geometry(p); return p; } /** * Distribute sampling points over a 2D plane in 3D space. */ void plane(std::vector<SPACE> &v, const Plane p) { // TODO return ptr to device memory, copy pos data to CPU during batches const size_t n = v.size() / DIMS; printf("offset: %f\n", p.offset.z); for (unsigned int i = 0; i < n; ++i) v[i*DIMS + 2] = p.offset.z; /* * Assume HD dimensions, keep remaining pixels for kernel geometry compatibility * solve for x: `n * (ratio) = x * y * (x/y) = x^2 -> x = sqrt(n * ratio)` */ auto x = (size_t) sqrt(n * p.aspect_ratio), y = n / x; if (p.aspect_ratio != 1.0) { printf("Screen dimensions: %i x %i\t", x, y); printf("Remaining points: %i/%i\n", n - x*y, n); } assert(x * y <= n); // distribute points over a lattice (each point in the center of a cell in a grid) const double height = p.width / p.aspect_ratio, dx = p.width / (double) x, // excl. boundary; don't divide by (x-1) dy = height / (double) y, x_half = (p.width - dx) / 2., // subtract dx/2 to position points in center y_half = (height - dy) / 2.; printf("init::plane, width: %e, n_x: %lu, dx: %e, x_half: %e\n", p.width, x, dx, x_half); // properties to generate random offsets const double rel_margin = p.randomize ? 0.05 : 0.0, x_margin = rel_margin * dx, // TODO min space between projector pixels y_margin = rel_margin * dy, x_random_range = dx - 0.5 * x_margin, y_random_range = dy - 0.5 * y_margin; const size_t n_random = x + y; curandGenerator_t generator; float *d_random, random[n_random]; if (p.randomize) { init_random(&generator); cu( cudaMalloc( (void **) &d_random, n_random * sizeof(float) ) ); } for (unsigned int i = 0; i < x; ++i) { if (p.randomize) randomize(random, d_random, n_random, generator); for (unsigned int j = 0; j < y; ++j) { v[Ix2D(i,j,0,y)] = i * dx - x_half + p.offset.x; v[Ix2D(i,j,1,y)] = j * dy - y_half + p.offset.y; v[Ix2D(i,j,2,y)] = p.offset.z; if (p.randomize) { v[Ix2D(i,j,0,y)] += x_random_range * (random[j*2] - 0.5); v[Ix2D(i,j,1,y)] += y_random_range * (random[j*2+1] - 0.5); } } } if (p.randomize) { curandDestroyGenerator(generator); cu( cudaFree( d_random ) ); } // fill rest of array with semi-realistic values to minimize incompatibility issues for (unsigned int i = x * y; i < n; ++i) for (unsigned int j = 0; j < DIMS; ++j) v[Ix(i, j)] = v[Ix(0,j)]; } std::vector<SPACE> sparse_plane(std::vector<SPACE> &u, Shape shape, double width, const Cartesian<double> &offset, double modulate = 0.) { const size_t n = u.size() / DIMS; for (unsigned int i = 0; i < n; ++i) u[Ix(i, 2)] = offset.z; assert(n != 0); if (n == 1) { u[Ix(0,0)] = offset.x; u[Ix(0,1)] = offset.y; return u; } // set the x,y dimensions switch (shape) { case Shape::Line: { // Distribute datapoints over a line auto du = width / (double) (n-1), // TODO use SCALE? half_width = width / 2.0; for (unsigned int i = 0; i < n; ++i) u[Ix(i,0)] = i * du - half_width; break; } case Shape::LogLine: { const auto x = geomspace(n, 1, 1 + width); for (auto& i : range(n)) u[Ix(i,0)] = x[i] - 1 + width / 2.; break; } case Shape::Circle: { // Distribute datapoints over a circle // (using polar coordinates, s.t. $phi_i \equiv i \Delta \phi$) auto radius = width / 2.0, /* circumference = TWO_PI * pow(radius, 2), */ d_phase = TWO_PI / (double) n, arbitrary_offset = 0.1125 + modulate * TWO_PI; for (unsigned int i = 0; i < n; ++i) { u[Ix(i,0)] = sin(i * d_phase + arbitrary_offset) * radius; u[Ix(i,1)] = cos(i * d_phase + arbitrary_offset) * radius; } break; } case Shape::DottedCircle: { // (using polar coordinates) auto radius = width / 2.0, /* circumference = TWO_PI * pow(radius, 2), */ /* don't include end; divide by n */ d_phase = TWO_PI / (double) (n-1), // subtract center point arbitrary_offset = 0.1125 + modulate * TWO_PI; // TODO randomize slightly? for (unsigned int i = 1; i < n; ++i) { u[Ix(i,0)] = sin(i * d_phase + arbitrary_offset) * radius; u[Ix(i,1)] = cos(i * d_phase + arbitrary_offset) * radius; } break; } } if (offset.x != 0 || offset.y != 0) { for (unsigned int i = 0; i < n; ++i) { u[Ix(i,0)] += offset.x; u[Ix(i,1)] += offset.y; } } return u; } template<typename T> std::vector<T*> malloc_vectors(T **d_ptr, size_t dim1, size_t dim2) { // TODO rename => malloc_arrays // Return a host vector of device pointers assert(dim1 >= 1); assert(dim2 >= 1); cu( cudaMalloc( d_ptr, dim1 * dim2 * sizeof(T) ) ); auto vec = std::vector<T*>(dim1); for (size_t i = 0; i < dim1; ++i) vec[i] = *d_ptr + i * dim2; return vec; } template<typename T> std::vector<CUDAVector<T>> malloc_matrix(T **d_ptr, size_t dim1, size_t dim2) { // Return a host vector of CUDAVector elements assert(dim1 >= 1); assert(dim2 >= 1); cu( cudaMalloc( d_ptr, dim1 * dim2 * sizeof(T) ) ); auto matrix = std::vector<CUDAVector<T>>(dim1); // std::vector<T>(*d_ptr + a, *d_ptr + b); has weird side effects // note that *ptr+i == &ptr[i], but that ptr[i] cannot be read by host if it's located on device for (size_t i = 0; i < dim1; ++i) matrix[i] = CUDAVector<T>{data: *d_ptr + i * dim2, size: dim2}; return matrix; } template<typename T> std::vector<T*> pinned_malloc_vectors(T **d_ptr, size_t dim1, size_t dim2) { // Return a host vector of pointers assert(dim1 >= 1); assert(dim2 >= 1); // TODO consider cudaHostAllocMapped(..., cudaHostAllocMapped) cu( cudaMallocHost( d_ptr, dim1 * dim2 * sizeof(T) ) ); auto vec = std::vector<T*>(dim1); for (size_t i = 0; i < dim1; ++i) vec[i] = *d_ptr + i * dim2; return vec; } template<typename T> std::vector<CUDAVector<T>> pinned_malloc_matrix(T **d_ptr, size_t dim1, size_t dim2) { // Return a host vector of DeviceVector elements assert(dim1 >= 1); assert(dim2 >= 1); cu( cudaMallocHost( d_ptr, dim1 * dim2 * sizeof(T) ) ); auto matrix = std::vector<CUDAVector<T>>(dim1); // std::vector<T>(*d_ptr + a, *d_ptr + b); has weird side effects // note that *ptr+i == &ptr[i], but that ptr[i] cannot be read by host if it's located on device for (size_t i = 0; i < dim1; ++i) matrix[i] = CUDAVector<T>{data: *d_ptr + i * dim2, size: dim2}; return matrix; } /////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// } // end namespace /////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// #endif
{ "alphanum_fraction": 0.5601773649, "avg_line_length": 32.2176870748, "ext": "h", "hexsha": "4c2e1b4323e32ae251b8a55fda5f3b403748bf2a", "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": "e127cf86093f15ed68c36592591e2eee196b5705", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "voschezang/Holographic-Projector-Simulations", "max_forks_repo_path": "cuda/init.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e127cf86093f15ed68c36592591e2eee196b5705", "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": "voschezang/Holographic-Projector-Simulations", "max_issues_repo_path": "cuda/init.h", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "e127cf86093f15ed68c36592591e2eee196b5705", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "voschezang/Holographic-Projector-Simulations", "max_stars_repo_path": "cuda/init.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2809, "size": 9472 }
/* * ----------------------------------------------------------------- * Ellipsoid Library --- ell_lib.h * Version: 1.6180 * Date: Feb 19, 2010 * ----------------------------------------------------------------- * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2010 by Americo Barbosa da Cunha Junior * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * A copy of the GNU General Public License is available in * LICENSE.txt or http://www.gnu.org/licenses/. * ----------------------------------------------------------------- * This is the header file for a library that operates an * n-dimensional ellipsoid. * ----------------------------------------------------------------- */ #ifndef __ELL_LIB_H__ #define __ELL_LIB_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #undef TOL #define TOL 1.0e-7 #undef TRUE #define TRUE 1 #undef FALSE #define FALSE 0 /* *------------------------------------------------------------ * function prototypes *------------------------------------------------------------ */ void ell_psd2eig(gsl_matrix *B, gsl_matrix *V, gsl_vector *lam); void ell_psd2chol(gsl_matrix *B, gsl_matrix *L); void ell_eig2chol(gsl_matrix *V, gsl_vector *sig, gsl_matrix *L); double ell_pt_in(gsl_vector *x, gsl_vector *c, gsl_matrix *L); void ell_map2uhs(gsl_vector *x, gsl_vector *c, gsl_matrix *L, gsl_vector *y); void ell_pt_modify(gsl_vector *p, gsl_vector *c, gsl_matrix *L); #endif /* __ELL_LIB_H__ */
{ "alphanum_fraction": 0.5115350488, "avg_line_length": 26.2093023256, "ext": "h", "hexsha": "e433221ef52d732c106b8ecb9b4ddf9fdcedc914", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_path": "CRFlowLib-1.0/include/ell_lib.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_path": "CRFlowLib-1.0/include/ell_lib.h", "max_line_length": 68, "max_stars_count": 1, "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_path": "CRFlowLib-1.0/include/ell_lib.h", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "num_tokens": 489, "size": 2254 }
/** * @file kjg_gsl.h * @brief Augment GSL functions */ #ifndef KJG_GSL_H_ #define KJG_GSL_H_ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> /** * Prints the matrix tab-delimited * @param *stream output file pointer * @param *m gsl_matrix to print * @param *template character template for fprintf */ void kjg_gsl_matrix_fprintf (FILE * stream, gsl_matrix * m, const char *template); /** * Prints the eigenvalues and then eigenvectors below * @param *stream output file pointer * @param *eval eigenvalues * @param *evec eigenvectors * @param *template character template for fprintf */ void kjg_gsl_evec_fprintf (FILE * stream, gsl_vector * eval, gsl_matrix * evec, const char *template); /** * Reads a matrix * @param *stream input file pointer * @param *m matrix to store */ void kjg_gsl_matrix_fscanf (FILE * stream, gsl_matrix * m); /** * Reads an evec * @param *stream input file pointer * @param *eval eigenvalues vector * @param *evec eigenvectors matrix */ int kjg_gsl_evec_fscanf (FILE * stream, gsl_vector * eval, gsl_matrix * evec); /** * Initializes random number generation. */ gsl_rng *kjg_gsl_rng_init (); /** * Initializes the matrix with random unit gaussians * @param *m matrix to be set * @param *r random number generator */ void kjg_gsl_ran_ugaussian_pair (const gsl_rng * r, double x[2]); /** Fills a matrix with unit Gaussian random variates * @param *r random number generator * @param *m matrix to be filled */ void kjg_gsl_ran_ugaussian_matrix (const gsl_rng * r, gsl_matrix * m); /** * Normalizes the matrix so the Frobenius norm is M*N * @param *m matrix to normalize * @return if error */ int kjg_gsl_matrix_frobenius_normalize (gsl_matrix * m); /** * Calculates the norm of a matrix * @param norm type of norm to return, see lapack dlange * @param *m matrix to find norm of * @return norm */ double kjg_gsl_dlange (const char norm, const gsl_matrix * m); /** * Performs the QR decomposition on the matrix and return Q in the matrix * @param *m matrix to orthogonalize */ void kjg_gsl_matrix_QR (gsl_matrix * m); /** * Calls LAPACK dgeqrf and return R and compacted Q matrix * @param *m input matrix * @param *tau see LAPACK documentation * @return LAPACK return */ int kjg_gsl_dgeqrf (gsl_matrix * m, gsl_vector * tau); /** * Calls LAPACK dorgqr to extract Q matrix * @param *m matrix with compacted Q and will store unpacked Q * @param *tau see LAPACK documentation * @return LAPACK return */ int kjg_gsl_dorgqr (gsl_matrix * m, gsl_vector * tau); /** * Calls LAPACK dgesvd, keeping u (in m) and s, discarding v^T * @param *m input matrix / where u is stored * @param *s entries of the diagonal matrix * @return LAPACK return */ int kjg_gsl_SVD (gsl_matrix * M, gsl_matrix * V, gsl_vector * S); #endif /* KJG_GSL_H_ */
{ "alphanum_fraction": 0.706472828, "avg_line_length": 23.6803278689, "ext": "h", "hexsha": "97e23432fd4d870c6d1e12860ff8cfad6f89b1eb", "lang": "C", "max_forks_count": 63, "max_forks_repo_forks_event_max_datetime": "2022-01-31T18:57:58.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-20T08:57:41.000Z", "max_forks_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "nevrome/EIG", "max_forks_repo_path": "include/kjg_gsl.h", "max_issues_count": 73, "max_issues_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:30:51.000Z", "max_issues_repo_issues_event_min_datetime": "2016-03-27T14:57:04.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "nevrome/EIG", "max_issues_repo_path": "include/kjg_gsl.h", "max_line_length": 78, "max_stars_count": 142, "max_stars_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "nevrome/EIG", "max_stars_repo_path": "include/kjg_gsl.h", "max_stars_repo_stars_event_max_datetime": "2022-03-29T14:29:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-12T07:58:32.000Z", "num_tokens": 815, "size": 2889 }
#ifndef libceed_petsc_examples_bps_problem_data_h #define libceed_petsc_examples_bps_problem_data_h #include <ceed.h> #include <petsc.h> #include "../include/bcfunctions.h" #include "../include/structs.h" #include "../qfunctions/bps/bp1.h" #include "../qfunctions/bps/bp2.h" #include "../qfunctions/bps/bp3.h" #include "../qfunctions/bps/bp4.h" #include "../qfunctions/bps/common.h" // ----------------------------------------------------------------------------- // BP Option Data // ----------------------------------------------------------------------------- // BP options typedef enum { CEED_BP1 = 0, CEED_BP2 = 1, CEED_BP3 = 2, CEED_BP4 = 3, CEED_BP5 = 4, CEED_BP6 = 5 } BPType; BPData bp_options[6] = { [CEED_BP1] = { .num_comp_u = 1, .num_comp_x = 3, .topo_dim = 3, .q_data_size = 1, .q_extra = 1, .setup_geo = SetupMassGeo, .setup_rhs = SetupMassRhs, .apply = Mass, .error = Error, .setup_geo_loc = SetupMassGeo_loc, .setup_rhs_loc = SetupMassRhs_loc, .apply_loc = Mass_loc, .error_loc = Error_loc, .in_mode = CEED_EVAL_INTERP, .out_mode = CEED_EVAL_INTERP, .q_mode = CEED_GAUSS, .enforce_bc = PETSC_FALSE, .bc_func = BCsMass }, [CEED_BP2] = { .num_comp_u = 3, .num_comp_x = 3, .topo_dim = 3, .q_data_size = 1, .q_extra = 1, .setup_geo = SetupMassGeo, .setup_rhs = SetupMassRhs3, .apply = Mass3, .error = Error3, .setup_geo_loc = SetupMassGeo_loc, .setup_rhs_loc = SetupMassRhs3_loc, .apply_loc = Mass3_loc, .error_loc = Error3_loc, .in_mode = CEED_EVAL_INTERP, .out_mode = CEED_EVAL_INTERP, .q_mode = CEED_GAUSS, .enforce_bc = PETSC_FALSE, .bc_func = BCsMass }, [CEED_BP3] = { .num_comp_u = 1, .num_comp_x = 3, .topo_dim = 3, .q_data_size = 7, .q_extra = 1, .setup_geo = SetupDiffGeo, .setup_rhs = SetupDiffRhs, .apply = Diff, .error = Error, .setup_geo_loc = SetupDiffGeo_loc, .setup_rhs_loc = SetupDiffRhs_loc, .apply_loc = Diff_loc, .error_loc = Error_loc, .in_mode = CEED_EVAL_GRAD, .out_mode = CEED_EVAL_GRAD, .q_mode = CEED_GAUSS, .enforce_bc = PETSC_TRUE, .bc_func = BCsDiff }, [CEED_BP4] = { .num_comp_u = 3, .num_comp_x = 3, .topo_dim = 3, .q_data_size = 7, .q_extra = 1, .setup_geo = SetupDiffGeo, .setup_rhs = SetupDiffRhs3, .apply = Diff3, .error = Error3, .setup_geo_loc = SetupDiffGeo_loc, .setup_rhs_loc = SetupDiffRhs3_loc, .apply_loc = Diff3_loc, .error_loc = Error3_loc, .in_mode = CEED_EVAL_GRAD, .out_mode = CEED_EVAL_GRAD, .q_mode = CEED_GAUSS, .enforce_bc = PETSC_TRUE, .bc_func = BCsDiff }, [CEED_BP5] = { .num_comp_u = 1, .num_comp_x = 3, .topo_dim = 3, .q_data_size = 7, .q_extra = 0, .setup_geo = SetupDiffGeo, .setup_rhs = SetupDiffRhs, .apply = Diff, .error = Error, .setup_geo_loc = SetupDiffGeo_loc, .setup_rhs_loc = SetupDiffRhs_loc, .apply_loc = Diff_loc, .error_loc = Error_loc, .in_mode = CEED_EVAL_GRAD, .out_mode = CEED_EVAL_GRAD, .q_mode = CEED_GAUSS_LOBATTO, .enforce_bc = PETSC_TRUE, .bc_func = BCsDiff }, [CEED_BP6] = { .num_comp_u = 3, .num_comp_x = 3, .topo_dim = 3, .q_data_size = 7, .q_extra = 0, .setup_geo = SetupDiffGeo, .setup_rhs = SetupDiffRhs3, .apply = Diff3, .error = Error3, .setup_geo_loc = SetupDiffGeo_loc, .setup_rhs_loc = SetupDiffRhs3_loc, .apply_loc = Diff3_loc, .error_loc = Error3_loc, .in_mode = CEED_EVAL_GRAD, .out_mode = CEED_EVAL_GRAD, .q_mode = CEED_GAUSS_LOBATTO, .enforce_bc = PETSC_TRUE, .bc_func = BCsDiff } }; #endif // libceed_petsc_examples_bps_problem_data_h
{ "alphanum_fraction": 0.6100760955, "avg_line_length": 25.75, "ext": "h", "hexsha": "d63e595c52d81a593f788f24c00a986ff73d8072", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_path": "examples/petsc/include/bpsproblemdata.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_path": "examples/petsc/include/bpsproblemdata.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_path": "examples/petsc/include/bpsproblemdata.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1281, "size": 3811 }
#ifndef _params_h_ #define _params_h_ #include <stdio.h> #include <time.h> #include <unistd.h> //For getpid() function #include <string.h> #include <stdlib.h> #include <math.h> #include <fftw3.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_matrix.h> //****Simulation Parameters: #define N_ps (int) 64 //Number of points in PS file #define N_gen (int) 4 //To generate the 21cm field #define LEN (double) 8.0 //Length of simulation box (in Mpc h^{-1}) #define freq_width (double) 2.0 //Width of frequency channel (in MHz) //****Foreground Removal Parameters: double *expo; int expo_array; int count(int); //****Function declarations: double interp_ps_lin(double); double read_21cm_cube(char *); double sim_21cm_cube(); double generate_full_signal(); double count_freq_channels(); double noise_removal(); //****Multifrequency fitting declarations: double *y, *x, *N, *Ni, *xtNi, *xtNix, *xtNix_i, *big_matrix, *a, *xa; //****GSL rng declarations: const gsl_rng_type *T; gsl_rng *rand1, *rand2; long seed; double a_q, b_q; //****Others: int SimON, XY_pix, Z_pix, Npol; //XY_pix and Z_pix are the box dimensions in pixels double frequency, original_21cm_mean, total_21cm_mean; double *original_21cm_field, *total_21cm_field, *detector_noise_field, *total_noise_field , *recovered_21cm_field, *parameter_a_cube; double k[N_ps], Pk[N_ps]; double *freq_array; double sigma, nu, tau, offset; double XY_LEN, Z_LEN; //Length of the box FILE *file; char cmnd[1000], header[100], polystr[100]; //****polystr is to store the exponents of variables of the fitting polynomial #endif
{ "alphanum_fraction": 0.7111486486, "avg_line_length": 28.6451612903, "ext": "h", "hexsha": "30ac429936de28ef47eeceae7e56ab6b8577fa51", "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": "fb473c1ef245d2768e6044f5903f5109e7393b69", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "anand-avinash/21cm-signal-with-multifrequency-fitting", "max_forks_repo_path": "params.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fb473c1ef245d2768e6044f5903f5109e7393b69", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "anand-avinash/21cm-signal-with-multifrequency-fitting", "max_issues_repo_path": "params.h", "max_line_length": 134, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fb473c1ef245d2768e6044f5903f5109e7393b69", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "anand-avinash/21cm-signal-with-multifrequency-fitting", "max_stars_repo_path": "params.h", "max_stars_repo_stars_event_max_datetime": "2020-05-27T07:59:48.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-27T07:59:48.000Z", "num_tokens": 499, "size": 1776 }
/* linalg/balance.c * * Copyright (C) 2006 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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. */ /* Balance a general matrix by scaling the rows and columns, so the * new row and column norms are the same order of magnitude. * * B = D^-1 A D * * where D is a diagonal matrix * * This is necessary for the unsymmetric eigenvalue problem since the * calculation can become numerically unstable for unbalanced * matrices. * * See Golub & Van Loan, "Matrix Computations" (3rd ed), Section 7.5.7 * and Wilkinson & Reinsch, "Handbook for Automatic Computation", II/11 p320. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #define FLOAT_RADIX 2.0 #define FLOAT_RADIX_SQ (FLOAT_RADIX * FLOAT_RADIX) int gsl_linalg_balance_matrix(gsl_matrix * A, gsl_vector * D) { const size_t N = A->size1; if (N != D->size) { GSL_ERROR ("vector must match matrix size", GSL_EBADLEN); } else { double row_norm, col_norm; int not_converged; gsl_vector_view v; /* initialize D to the identity matrix */ gsl_vector_set_all(D, 1.0); not_converged = 1; while (not_converged) { size_t i, j; double g, f, s; not_converged = 0; for (i = 0; i < N; ++i) { row_norm = 0.0; col_norm = 0.0; for (j = 0; j < N; ++j) { if (j != i) { col_norm += fabs(gsl_matrix_get(A, j, i)); row_norm += fabs(gsl_matrix_get(A, i, j)); } } if ((col_norm == 0.0) || (row_norm == 0.0)) { continue; } g = row_norm / FLOAT_RADIX; f = 1.0; s = col_norm + row_norm; /* * find the integer power of the machine radix which * comes closest to balancing the matrix */ while (col_norm < g) { f *= FLOAT_RADIX; col_norm *= FLOAT_RADIX_SQ; } g = row_norm * FLOAT_RADIX; while (col_norm > g) { f /= FLOAT_RADIX; col_norm /= FLOAT_RADIX_SQ; } if ((row_norm + col_norm) < 0.95 * s * f) { not_converged = 1; g = 1.0 / f; /* * apply similarity transformation D, where * D_{ij} = f_i * delta_{ij} */ /* multiply by D^{-1} on the left */ v = gsl_matrix_row(A, i); gsl_blas_dscal(g, &v.vector); /* multiply by D on the right */ v = gsl_matrix_column(A, i); gsl_blas_dscal(f, &v.vector); /* keep track of transformation */ gsl_vector_set(D, i, gsl_vector_get(D, i) * f); } } } return GSL_SUCCESS; } } /* gsl_linalg_balance_matrix() */ /* gsl_linalg_balance_accum() Accumulate a balancing transformation into a matrix. This is used during the computation of Schur vectors since the Schur vectors computed are the vectors for the balanced matrix. We must at some point accumulate the balancing transformation into the Schur vector matrix to get the vectors for the original matrix. A -> D A where D is the diagonal matrix Inputs: A - matrix to transform D - vector containing diagonal elements of D */ int gsl_linalg_balance_accum(gsl_matrix *A, gsl_vector *D) { const size_t N = A->size1; if (N != D->size) { GSL_ERROR ("vector must match matrix size", GSL_EBADLEN); } else { size_t i; double s; gsl_vector_view r; for (i = 0; i < N; ++i) { s = gsl_vector_get(D, i); r = gsl_matrix_row(A, i); gsl_blas_dscal(s, &r.vector); } return GSL_SUCCESS; } } /* gsl_linalg_balance_accum() */
{ "alphanum_fraction": 0.5453269154, "avg_line_length": 26.6631016043, "ext": "c", "hexsha": "f07b1df375d6ef678ca4910be6e43d653e915a32", "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/linalg/balancemat.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/linalg/balancemat.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/linalg/balancemat.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": 1217, "size": 4986 }
/* ** Copyright (c) 2008, 2009 Gerald I. Evenden */ static const char RCS_ID[] = "$Id: proj_gdinverse.c,v 5.6 2009/05/17 19:41:47 gie Exp gie $"; /* ** Permission is hereby granted, free of charge, to any person obtaining ** a copy of this software and associated documentation files (the ** "Software"), to deal in the Software without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Software, and to ** permit persons to whom the Software is furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** @file proj_gdinverse.c * @brief general inverse projection support * @author Gerald I. Evenden */ #include "config.h" #include <stdlib.h> #if HAVE_LIBGSL #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> #include <project.h> #define LOOP_LIMIT 10 struct p_gsl { PROJ *P; double x, y; }; typedef struct p_gsl GP; static int func_f(const gsl_vector *x, void *p, gsl_vector *f) { //func_f(const gsl_vector *x, GP *p, gsl_vector *f) { PROJ_LP lp; lp.lam = gsl_vector_get(x,0); lp.phi = gsl_vector_get(x,1); PROJ_XY xy = (*((GP *)p)->P->fwd)(lp, ((GP *)p)->P); gsl_vector_set(f, 0, xy.x - ((GP *)p)->x); gsl_vector_set(f, 1, xy.y - ((GP *)p)->y); return GSL_SUCCESS; } static int func_df(const gsl_vector * x, void *p, gsl_matrix *J) { struct PROJ_DERIVS der; PROJ_LP lp; lp.lam = gsl_vector_get(x,0); lp.phi = gsl_vector_get(x,1); (*((GP *)p)->P->derivs)(((GP *)p)->P, lp, &der); gsl_matrix_set(J, 0, 0, der.x_l); gsl_matrix_set(J, 0, 1, der.x_p); gsl_matrix_set(J, 1, 0, der.y_l); gsl_matrix_set(J, 1, 1, der.y_p); return GSL_SUCCESS; } static int func_fdf(const gsl_vector * x, void *p, gsl_vector *f, gsl_matrix *J) { func_f(x, p, f); func_df(x, p, J); return GSL_SUCCESS; } /* @brief determine projection inverse * @param[in] P projection control structure * @param est estimated geographic answer * @param[in] xy Cartesian location * @param[in] tol tolerance * @return ==0 if successful */ int proj_gdinverse(PROJ *P, PROJ_LP *est, PROJ_XY xy, double tol) { const gsl_multiroot_fdfsolver_type *T2; const gsl_multiroot_fsolver_type *T1; gsl_multiroot_fdfsolver *s2; gsl_multiroot_fsolver *s1; int status; size_t i, iter = 0; const size_t n = 2; GP p; int ders = P->derivs != NULL; gsl_multiroot_function_fdf f2 = {&func_f, &func_df, &func_fdf, n, &p}; gsl_multiroot_function f1 = {&func_f, n, &p}; p.P = P; p.x = xy.x; p.y = xy.y; gsl_vector *x = gsl_vector_alloc(n); gsl_vector_set(x, 0, est->lam); gsl_vector_set(x, 1, est->phi); if (ders) { T2 = gsl_multiroot_fdfsolver_gnewton; s2 = gsl_multiroot_fdfsolver_alloc(T2, n); gsl_multiroot_fdfsolver_set(s2, &f2, x); } else { T1 = gsl_multiroot_fsolver_hybrids; s1 = gsl_multiroot_fsolver_alloc(T1, n); gsl_multiroot_fsolver_set(s1, &f1, x); } do { ++iter; status = ders ? gsl_multiroot_fdfsolver_iterate(s2): gsl_multiroot_fsolver_iterate(s1); if (status) break; status = gsl_multiroot_test_residual( ders?s2->f : s1->f, tol); } while (status == GSL_CONTINUE && iter < LOOP_LIMIT); if (ders) { est->lam = gsl_vector_get(s2->x,0); est->phi = gsl_vector_get(s2->x,1); gsl_multiroot_fdfsolver_free(s2); } else { est->lam = gsl_vector_get(s1->x,0); est->phi = gsl_vector_get(s1->x,1); gsl_multiroot_fsolver_free(s1); } gsl_vector_free(x); return 0; } #else // end LIBGSL true /* the following is present to resolve any funky linking and to * ensure the system fails if gdinverse is called when the GSL flag * is not set. */ #include <stdio.h> #include <project.h> int proj_gdinverse(PROJ *P, PROJ_LP *est, PROJ_XY xy, double tol) { fprintf(stderr,"libproj4: entered gdinverse---no GSL avail. See admin\n"); exit(-1); return -1; } #endif // end LIBGSL condition /* * $Log: */
{ "alphanum_fraction": 0.7005132783, "avg_line_length": 30.4829931973, "ext": "c", "hexsha": "8bcdcda6b6143c3099ecd0baf7db826338bf8cb1", "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": "d7c3bde003b7d4c2c408f905f2fcdfe3d53c2313", "max_forks_repo_licenses": [ "X11", "MIT" ], "max_forks_repo_name": "rouault/libproj4", "max_forks_repo_path": "libproject-1.01/src/proj_gdinverse.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d7c3bde003b7d4c2c408f905f2fcdfe3d53c2313", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "X11", "MIT" ], "max_issues_repo_name": "rouault/libproj4", "max_issues_repo_path": "libproject-1.01/src/proj_gdinverse.c", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "d7c3bde003b7d4c2c408f905f2fcdfe3d53c2313", "max_stars_repo_licenses": [ "X11", "MIT" ], "max_stars_repo_name": "rouault/libproj4", "max_stars_repo_path": "libproject-1.01/src/proj_gdinverse.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1386, "size": 4481 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ /* Given a block system A x = b, or ( K G )(u) = (f) ( D C )(p) (h) We define a symmetrically scaled system, L A R R^-1 x = L b, A'x' = b' where L = diag(L1, L2), R = diag(R1,R2) are block diagonal and L_i and R_i are both diagonal matrirces. The scaling produces ( L1 )( K G )( R1 )( R1 )^-1(u) = ( L1 )(f) ( L2 )( D C )( R2 )( R2 ) (p) ( L2 )(h) and we solve ( L1 )( K G )( R1 )(v) = ( L1 )(f) ( L2 )( D C )( R2 )(q) ( L2 )(h) or ( L1KR1 L1GR2 )(v) = (L1f) ( L2DR1 L2CR2 )(q) (L2h) The solution u,p is recovered via (u) = ( R1 )(v) (p) ( R2 )(q) */ #include <petsc.h> #include <petscmat.h> #include <petscvec.h> #include <StGermain/StGermain.h> #include <StgDomain/StgDomain.h> #include "common-driver-utils.h" #include "stokes_block_scaling.h" /* private prototypes */ PetscErrorCode BSSCR_MatStokesBlock_ApplyScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ); /* A x = b -> A'x' = b' */ /* Note this routine actually modifies the matrix and rhs b. */ // updated PetscErrorCode BSSCR_MatStokesBlock_ApplyScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ) { Mat K,G,D,C; Vec L1,L2, R1,R2; Vec f,h, u,p; /* Get the scalings out the block mat data */ VecNestGetSubVec( BA->Lz, 0, &L1 ); VecNestGetSubVec( BA->Lz, 1, &L2 ); VecNestGetSubVec( BA->Rz, 0, &R1 ); VecNestGetSubVec( BA->Rz, 1, &R2 ); /* get the subblock solution and rhs */ if( x != PETSC_NULL ) { VecNestGetSubVec( x, 0, &u ); VecNestGetSubVec( x, 1, &p ); VecPointwiseDivide( u, u,R1); /* x <- x * 1/R1 */ VecPointwiseDivide( p, p,R2); } if( b != PETSC_NULL ) { VecNestGetSubVec( b, 0, &f ); VecNestGetSubVec( b, 1, &h ); VecPointwiseMult( f, f,L1); /* f <- f * L1 */ VecPointwiseMult( h, h,L2); } /* Scale matrices */ MatNestGetSubMat( A, 0,0, &K ); MatNestGetSubMat( A, 0,1, &G ); MatNestGetSubMat( A, 1,0, &D ); MatNestGetSubMat( A, 1,1, &C ); if( K != PETSC_NULL ) { MatDiagonalScale( K, L1,R1 ); } if( G != PETSC_NULL ) { MatDiagonalScale( G, L1,R2 ); } if( D != PETSC_NULL && !sym ) { MatDiagonalScale( D, L2,R1 ); } if( C != PETSC_NULL ) { MatDiagonalScale( C, L2,R2 ); } if( S != PETSC_NULL ) { MatDiagonalScale( S, L2,R2 ); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_MatStokesBlock_ApplyScaling2( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, Mat M, PetscTruth sym ) { Mat K,G,D,C; Vec L1,L2, R1,R2; Vec f,h, u,p; /* Get the scalings out the block mat data */ VecNestGetSubVec( BA->Lz, 0, &L1 ); VecNestGetSubVec( BA->Lz, 1, &L2 ); VecNestGetSubVec( BA->Rz, 0, &R1 ); VecNestGetSubVec( BA->Rz, 1, &R2 ); /* get the subblock solution and rhs */ if( x != PETSC_NULL ) { VecNestGetSubVec( x, 0, &u ); VecNestGetSubVec( x, 1, &p ); VecPointwiseDivide( u, u,R1); /* x <- x * 1/R1 */ VecPointwiseDivide( p, p,R2); } if( b != PETSC_NULL ) { VecNestGetSubVec( b, 0, &f ); VecNestGetSubVec( b, 1, &h ); VecPointwiseMult( f, f,L1); /* f <- f * L1 */ VecPointwiseMult( h, h,L2); } /* Scale matrices */ MatNestGetSubMat( A, 0,0, &K ); MatNestGetSubMat( A, 0,1, &G ); MatNestGetSubMat( A, 1,0, &D ); MatNestGetSubMat( A, 1,1, &C ); if( K != PETSC_NULL ) { MatDiagonalScale( K, L1,R1 ); } if( G != PETSC_NULL ) { MatDiagonalScale( G, L1,R2 ); } if( D != PETSC_NULL && !sym ) { MatDiagonalScale( D, L2,R1 ); } if( C != PETSC_NULL ) { MatDiagonalScale( C, L2,R2 ); } if( S != PETSC_NULL ) { MatDiagonalScale( S, L2,R2 ); } if( M != PETSC_NULL ) { MatDiagonalScale( M, L2,R2 ); } PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesBlockScalingCreate( MatStokesBlockScaling *_BA ) { MatStokesBlockScaling BA; PetscMalloc( sizeof(struct _p_MatStokesBlockScaling), &BA ); BA->Lz = PETSC_NULL; BA->Rz = PETSC_NULL; BA->scaling_exists = PETSC_FALSE; BA->scalings_have_been_inverted = PETSC_FALSE; BA->system_has_been_scaled = PETSC_FALSE; *_BA = BA; PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesBlockScalingDestroy( MatStokesBlockScaling BA ) { if( BA->scaling_exists == PETSC_FALSE ) PetscFunctionReturn(0); if( BA->Lz != PETSC_NULL ) { Stg_VecDestroy(&BA->Lz ); BA->Lz = PETSC_NULL; } if( BA->Rz != PETSC_NULL ) { Stg_VecDestroy(&BA->Rz ); BA->Rz = PETSC_NULL; } PetscFree( BA ); PetscFunctionReturn(0); } /* A is 2x2 block matrix b and x are 2x1 block vectors */ // updated PetscErrorCode BSSCR_MatBlock_ConstructScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x ) { if( BA->scaling_exists == PETSC_FALSE ) { VecDuplicate( x, &BA->Lz ); VecDuplicate( x, &BA->Rz ); BA->scaling_exists = PETSC_TRUE; BSSCR_MatStokesBlockDefaultBuildScaling( BA,A ); BA->scalings_have_been_inverted = PETSC_FALSE; } PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_mat_block_invert_scalings( MatStokesBlockScaling BA ) { Vec L1,L2, R1,R2; VecNestGetSubVec( BA->Lz, 0, &L1 ); VecNestGetSubVec( BA->Lz, 1, &L2 ); VecNestGetSubVec( BA->Rz, 0, &R1 ); VecNestGetSubVec( BA->Rz, 1, &R2 ); VecReciprocal(L1); VecReciprocal(L2); VecReciprocal(R1); VecReciprocal(R2); /* toggle inversion flag */ if( BA->scalings_have_been_inverted == PETSC_TRUE ) { BA->scalings_have_been_inverted = PETSC_FALSE; } if( BA->scalings_have_been_inverted == PETSC_FALSE ) { BA->scalings_have_been_inverted = PETSC_TRUE; } PetscFunctionReturn(0); } /* updated */ PetscErrorCode BSSCR_MatStokesBlockScaleSystem( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ) { if( BA->scaling_exists == PETSC_FALSE ) { BSSCR_MatBlock_ConstructScaling( BA,A,b,x ); } if( BA->scalings_have_been_inverted == PETSC_TRUE ) { BSSCR_mat_block_invert_scalings(BA); /* to undo inversion */ } BSSCR_MatStokesBlock_ApplyScaling(BA,A,b,x,S,sym); BA->system_has_been_scaled = PETSC_TRUE; /* PetscPrintf( PETSC_COMM_WORLD, "Post Scaling \n"); MatBlock_ReportOperatorScales(A); */ PetscFunctionReturn(0); } PetscErrorCode BSSCR_MatStokesBlockScaleSystem2( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, Mat M, PetscTruth sym ) { if( BA->scaling_exists == PETSC_FALSE ) { BSSCR_MatBlock_ConstructScaling( BA,A,b,x ); } if( BA->scalings_have_been_inverted == PETSC_TRUE ) { BSSCR_mat_block_invert_scalings(BA); /* to undo inversion */ } BSSCR_MatStokesBlock_ApplyScaling2(BA,A,b,x,S,M,sym); BA->system_has_been_scaled = PETSC_TRUE; /* PetscPrintf( PETSC_COMM_WORLD, "Post Scaling \n"); MatBlock_ReportOperatorScales(A); */ PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesBlockUnScaleSystem( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym ) { if( BA->system_has_been_scaled == PETSC_FALSE ) { printf("Warning: MatBlock has not been scaled !! \n"); PetscFunctionReturn(0); } if( BA->scalings_have_been_inverted == PETSC_FALSE ) { BSSCR_mat_block_invert_scalings(BA); } BSSCR_MatStokesBlock_ApplyScaling(BA,A,b,x,S,sym); BA->system_has_been_scaled = PETSC_FALSE; PetscFunctionReturn(0); } PetscErrorCode BSSCR_MatStokesBlockReportOperatorScales( Mat A, PetscTruth sym ) { Vec rA, rG; PetscInt loc; PetscReal min, max; Mat K,G,D,C; MatNestGetSubMat( A, 0,0, &K ); MatNestGetSubMat( A, 0,1, &G ); MatNestGetSubMat( A, 1,0, &D ); MatNestGetSubMat( A, 1,1, &C ); MatGetVecs( K, PETSC_NULL, &rA ); VecDuplicate( rA, &rG ); /* Report the row max and mins */ if (K!=PETSC_NULL) { PetscReal KNorm; MatGetRowMax( K, rA, PETSC_NULL ); VecMax( rA, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(K) = %g \n", max ); MatGetRowMinAbs( K, rA, PETSC_NULL ); VecMin( rA, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(K) = %g \n", min ); MatNorm(K,NORM_1,&KNorm); PetscPrintf( PETSC_COMM_WORLD, "norm_1(K) = %g \n\n",KNorm); } if( G != PETSC_NULL ) { MatGetRowMax( G, rG, PETSC_NULL ); VecMax( rG, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(G) = %g \n", max ); MatGetRowMinAbs( G, rG, PETSC_NULL ); VecMin( rG, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(G) = %g \n", min ); } if( D != PETSC_NULL && !sym ) { Vec rD; MatGetVecs( D, PETSC_NULL, &rD ); MatGetRowMax( D, rD, PETSC_NULL ); VecMax( rD, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(D) = %g \n", max ); MatGetRowMinAbs( D, rD, PETSC_NULL ); VecMin( rD, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(D) = %g \n", min ); Stg_VecDestroy(&rD ); } if( C != PETSC_NULL ) { Vec cG; MatGetVecs( G, &cG, PETSC_NULL ); MatGetRowMax( C, cG, PETSC_NULL ); VecMax( cG, &loc, &max ); PetscPrintf( PETSC_COMM_WORLD, "Sup_max(C) = %g \n", max ); MatGetRowMin( C, cG, PETSC_NULL ); VecMin( cG, &loc, &min ); PetscPrintf( PETSC_COMM_WORLD, "Sup_min(C) = %g \n\n", min ); Stg_VecDestroy(&cG); } Stg_VecDestroy(&rA ); Stg_VecDestroy(&rG ); PetscFunctionReturn(0); } // updated PetscErrorCode BSSCR_MatStokesBlockDefaultBuildScaling( MatStokesBlockScaling BA, Mat A ) { Mat K,G,D,C; Vec rG; PetscScalar rg2, rg, ra; PetscInt N; Vec rA, rC; Vec L1,L2, R1,R2; VecNestGetSubVec( BA->Lz, 0, &L1 ); VecNestGetSubVec( BA->Lz, 1, &L2 ); VecNestGetSubVec( BA->Rz, 0, &R1 ); VecNestGetSubVec( BA->Rz, 1, &R2 ); rA = L1; rC = L2; MatNestGetSubMat( A, 0,0, &K ); MatNestGetSubMat( A, 0,1, &G ); MatNestGetSubMat( A, 1,0, &D ); MatNestGetSubMat( A, 1,1, &C ); VecDuplicate( rA, &rG ); /* Get magnitude of K */ //px_MatGetAbsRowSum( K, rA ); MatGetRowMax( K, rA, PETSC_NULL ); VecSqrt( rA ); VecReciprocal( rA ); VecDot( rA,rA, &ra ); VecGetSize( rA, &N ); ra = PetscSqrtScalar( ra/N ); /* Get magnitude of G */ //px_MatGetAbsRowSum( G, rG ); MatGetRowMax( G, rG, PETSC_NULL ); VecDot( rG, rG, &rg2 ); VecGetSize( rG, &N ); rg = PetscSqrtScalar(rg2/N); // printf("rg = %f \n", rg ); VecSet( rC, 1.0/(rg*ra) ); Stg_VecDestroy(&rG ); VecCopy( L1, R1 ); VecCopy( L2, R2 ); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6143263322, "avg_line_length": 24.8926940639, "ext": "c", "hexsha": "537c73cf02c2ef2492459279d03a5241e88c4218", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_block_scaling.c", "max_issues_count": 561, "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_block_scaling.c", "max_line_length": 128, "max_stars_count": 116, "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_block_scaling.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "num_tokens": 4135, "size": 10903 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "../mersenne.h" #include <lapacke.h> #include <time.h> #include <sys/time.h> #ifndef M_PI #define M_PI 3.14159265358979323846264338327 #endif /* Lattice size and dimensions */ #define NT 4 #define NX 4 #define ND 2 #define NDIRS (2*ND) #define TUP 0 #define XUP 1 #define TDN 2 #define XDN 3 #define VOLUME (NT*NX) //#define ANTISYMMETRIC //Antisymmetric boundaries #define OPENX //Antisymmetric in time, open in space /* Enumerate possible values for a field */ #define MONOMER 1 #define LINK_TUP (2+TUP) // Links enumerated as 2+direction #define LINK_XUP (2+XUP) #define LINK_TDN (2+TDN) #define LINK_XDN (2+XDN) #define SOURCE_MONOMER (2+NDIRS) #define EMPTY -100 //A meta value for sites that don't exist #define CG_ACCURACY 1e-20 #define CG_MAX_ITER 10000 /* Propability of exiting in the monomer moving worm update */ #define flip_exit_propability 0.2 #define FLUCTUATION_MATRIX #define WITH_MASS_MONOMERS #define PROPAGATOR_MATRIX /* Functions in vec_ops.c */ void vec_zero( double **a ); void vec_one(double **a); void vec_add(double **a, double **b); void vec_d_mul(double **a, double d); void vec_zero_occupied(double **a); void free_vector(double ** a); double ** alloc_vector(); void cg_propagator( double **propagator, double **source ); void fM( double **chi, double **psi ); void fM_transpose(double **chi, double **psi ); int cg_MdM_occupied( double *chi, double *psi ); void fM_occupied( double *chi, double *psi ); double action(double *psi); void vec_gaussian(double *a); double * alloc_field();
{ "alphanum_fraction": 0.7279503106, "avg_line_length": 23, "ext": "h", "hexsha": "ad486c2af254997a1b625571ebabef1200686a0d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-07-18T10:21:16.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-18T10:21:16.000Z", "max_forks_repo_head_hexsha": "38251013d554584df39aec18b841b4ec431abfc7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rantahar/Thirring2D", "max_forks_repo_path": "tests/thirring_brute.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "38251013d554584df39aec18b841b4ec431abfc7", "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": "rantahar/Thirring2D", "max_issues_repo_path": "tests/thirring_brute.h", "max_line_length": 62, "max_stars_count": null, "max_stars_repo_head_hexsha": "38251013d554584df39aec18b841b4ec431abfc7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rantahar/Thirring2D", "max_stars_repo_path": "tests/thirring_brute.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 465, "size": 1610 }
#ifndef CONSTITUTIVE_DF_H #define CONSTITUTIVE_DF_H #include <algorithm> #include <numeric> #include "SIMD_BDB_Integrator.h" #ifdef HAS_MKL #include <mkl.h> #else #include <cblas.h> #endif inline void GetTotalTraction_(Real *TotalTraction, const Real *CauchyStressTensor, int ndim) { if (ndim==3) { TotalTraction[0] = CauchyStressTensor[0]; TotalTraction[1] = CauchyStressTensor[4]; TotalTraction[2] = CauchyStressTensor[8]; TotalTraction[3] = CauchyStressTensor[1]; TotalTraction[4] = CauchyStressTensor[2]; TotalTraction[5] = CauchyStressTensor[5]; } else if (ndim == 2) { TotalTraction[0] = CauchyStressTensor[0]; TotalTraction[1] = CauchyStressTensor[3]; TotalTraction[2] = CauchyStressTensor[1]; } } inline void FillConstitutiveB_(Real *B, const Real* SpatialGradient, int ndim, int nvar, int rows, int cols) { int i = 0; if (ndim == 3) { for (; i<rows; ++i) { // Store in registers const Real a0 = SpatialGradient[i*ndim]; const Real a1 = SpatialGradient[i*ndim+1]; const Real a2 = SpatialGradient[i*ndim+2]; // MECHANICAL TERMS B[i*cols*nvar] = a0; B[i*cols*nvar+cols+1] = a1; B[i*cols*nvar+2*(cols+1)] = a2; B[i*cols*nvar+cols+5] = a2; B[i*cols*nvar+2*cols+5] = a1; B[i*cols*nvar+4] = a2; B[i*cols*nvar+2*cols+4] = a0; B[i*cols*nvar+3] = a1; B[i*cols*nvar+cols+3] = a0; } } else if (ndim == 2) { for (; i<rows; ++i) { // Store in registers const Real a0 = SpatialGradient[i*ndim]; const Real a1 = SpatialGradient[i*ndim+1]; // MECHANICAL TERMS B[i*cols*nvar] = a0; B[i*cols*nvar+cols+1] = a1; B[i*cols*nvar+2] = a1; B[i*cols*nvar+cols+2] = a0; } } } inline void _ConstitutiveStiffnessIntegrandDF_Filler_( Real *stiffness, Real *traction, const Real* SpatialGradient, const Real* CauchyStressTensor, const Real* H_Voigt, const Real* detJ, int ngauss, int noderpelem, int ndim, int nvar, int H_VoigtSize, int requires_geometry_update) { int local_size = nvar*noderpelem; Real *t; if (ndim==3) { t = allocate<Real>(6);} else if (ndim==2) { t = allocate<Real>(3);} Real *B = allocate<Real>(H_VoigtSize*local_size); Real *HBT = allocate<Real>(H_VoigtSize*local_size); Real *BDB_1 = allocate<Real>(local_size*local_size); std::fill(B,B+H_VoigtSize*local_size,0.); for (int igauss = 0; igauss < ngauss; ++igauss) { FillConstitutiveB_(B,&SpatialGradient[igauss*ndim*noderpelem],ndim,nvar,noderpelem,H_VoigtSize); // if (ndim == 3) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, H_VoigtSize, local_size, H_VoigtSize, 1.0, &H_Voigt[igauss*H_VoigtSize*H_VoigtSize], H_VoigtSize, B, H_VoigtSize, 0.0, HBT, local_size); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, local_size, local_size, H_VoigtSize, 1.0, B, H_VoigtSize, HBT, local_size, 0.0, BDB_1, local_size); // } // else // { // _SIMD_BDB_Integrator_DF_2D_( // HBT, // BDB_1, // &SpatialGradient[igauss*ndim*noderpelem], // &H_Voigt[igauss*H_VoigtSize*H_VoigtSize], // noderpelem // ); // } // Multiply stiffness with detJ const Real detJ_igauss = detJ[igauss]; for (int i=0; i<local_size*local_size; ++i) { stiffness[i] += BDB_1[i]*detJ_igauss; } if (requires_geometry_update==1) { // Compute tractions GetTotalTraction_(t, &CauchyStressTensor[igauss*ndim*ndim], ndim); // Multiply B with traction - for loop is okay for (int i=0; i<local_size; ++i) { Real tmp = 0; for (int j=0; j<H_VoigtSize; ++j) { tmp += B[i*H_VoigtSize+j]*t[j]; } // local_traction[i] = tmp; traction[i] += tmp*detJ_igauss; } } } deallocate(t); deallocate(B); deallocate(HBT); deallocate(BDB_1); } #endif
{ "alphanum_fraction": 0.5443539511, "avg_line_length": 28.753164557, "ext": "h", "hexsha": "b52d830ff2fbe337ad42165d66ec1dfe9d75b736", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-05-18T08:06:51.000Z", "max_forks_repo_forks_event_min_datetime": "2018-05-30T09:44:10.000Z", "max_forks_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jdlaubrie/florence", "max_forks_repo_path": "Florence/VariationalPrinciple/_ConstitutiveStiffness_/_ConstitutiveStiffnessDF_.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_issues_repo_issues_event_max_datetime": "2022-01-18T02:30:22.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-03T02:29:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jdlaubrie/florence", "max_issues_repo_path": "Florence/VariationalPrinciple/_ConstitutiveStiffness_/_ConstitutiveStiffnessDF_.h", "max_line_length": 152, "max_stars_count": 65, "max_stars_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jdlaubrie/florence", "max_stars_repo_path": "Florence/VariationalPrinciple/_ConstitutiveStiffness_/_ConstitutiveStiffnessDF_.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:45:09.000Z", "max_stars_repo_stars_event_min_datetime": "2017-08-04T10:21:13.000Z", "num_tokens": 1439, "size": 4543 }
/* * BRAINS * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling * Yan-Rong Li, liyanrong@ihep.ac.cn * Thu, Aug 4, 2016 */ /*! * \file reconstruct_con.c * \brief reconstruct continuum. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_randist.h> #include "brains.h" void *best_model_con; /*!< best model */ void *best_model_std_con; /*!< standard deviation of the best model */ /*! * this function does postprocess for continuum. */ void postprocess_con() { char posterior_sample_file[BRAINS_MAX_STR_LENGTH]; double *pm, *pmstd; int num_ps, i, j; void *posterior_sample, *post_model; int size_of_modeltype = num_params * sizeof(double); best_model_con = malloc(size_of_modeltype); best_model_std_con = malloc(size_of_modeltype); if(thistask == roottask) { char fname[200]; FILE *fp, *fcon; /* get file name of posterior sample file */ //get_posterior_sample_file(dnest_options_file, posterior_sample_file); dnest_get_posterior_sample_file(posterior_sample_file); /* open file for posterior sample */ fp = fopen(posterior_sample_file, "r"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", posterior_sample_file); exit(0); } /* open file for continuum reconstruction */ sprintf(fname, "%s/%s", parset.file_dir, "data/con_rec.txt"); fcon = fopen(fname, "w"); if(fcon == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } /* read number of points in posterior sample */ if(fscanf(fp, "# %d", &num_ps) < 1) { fprintf(stderr, "# Error: Cannot read file %s.\n", posterior_sample_file); exit(0); } printf("# Number of points in posterior sample: %d\n", num_ps); post_model = malloc(size_of_modeltype); posterior_sample = malloc(num_ps * size_of_modeltype); which_parameter_update = -1; which_particle_update = 0; for(i=0; i<num_ps; i++) { for(j=0; j<num_params; j++) { if(fscanf(fp, "%lf", (double *)post_model + j) < 1) { fprintf(stderr, "# Error: Cannot read file %s.\n", posterior_sample_file); exit(0); } } fscanf(fp, "\n"); memcpy(posterior_sample+i*size_of_modeltype, post_model, size_of_modeltype); /* not output reconstruction when flag_dim = -1 */ if(parset.flag_dim != -1) { calculate_con_from_model_semiseparable(post_model); if(gsl_rng_uniform(gsl_r) < 1.0) { for(j=0; j<parset.n_con_recon; j++) { fprintf(fcon, "%e %e %f\n", Tcon[j]*(1.0+parset.redshift), Fcon[j]/con_scale, Fcerrs[j]/con_scale); } fprintf(fcon, "\n"); } } } fclose(fp); fclose(fcon); /* calcaulte mean and standard deviation of posterior samples. */ pm = (double *)best_model_con; pmstd = (double *)best_model_std_con; for(j=0; j<num_params; j++) { pm[j] = pmstd[j] = 0.0; } for(i=0; i<num_ps; i++) { for(j =0; j<num_params; j++) pm[j] += *((double *)posterior_sample + i*num_params + j ); } for(j=0; j<num_params; j++) pm[j] /= num_ps; for(i=0; i<num_ps; i++) { for(j=0; j<num_params; j++) pmstd[j] += pow( *((double *)posterior_sample + i*num_params + j ) - pm[j], 2.0 ); } for(j=0; j<num_params; j++) { if(num_ps > 1) pmstd[j] = sqrt(pmstd[j]/(num_ps-1.0)); else pmstd[j] = 0.0; } for(j = 0; j<num_params_var; j++) printf("Best params %d %f +- %f\n", j, *((double *)best_model_con + j), *((double *)best_model_std_con+j) ); free(post_model); free(posterior_sample); } return; } /*! * This function runs dnest sampling and postprocessing, reconstructs the continuum * using the best estimates of model parameters. */ void reconstruct_con() { int i, argc=0; char **argv; // configure restart of dnest argv = malloc(9*sizeof(char *)); for(i=0; i<9; i++) { argv[i] = malloc(BRAINS_MAX_STR_LENGTH*sizeof(char)); } //setup argc and argv strcpy(argv[argc++], "dnest"); strcpy(argv[argc++], "-s"); strcpy(argv[argc], parset.file_dir); strcat(argv[argc++], "/data/restart_dnest.txt"); if(parset.flag_restart == 1 && parset.flag_dim == 0) { strcpy(argv[argc++], "-r"); strcpy(argv[argc], parset.file_dir); strcat(argv[argc], "/"); strcat(argv[argc++], "data/restart_dnest.txt"); } if(parset.flag_postprc == 1 || (parset.flag_dim !=0 && parset.flag_restart == 1)) { strcpy(argv[argc++], "-p"); } if(parset.flag_temp == 1) { sprintf(argv[argc++], "-t%f", parset.temperature); } if(parset.flag_sample_info == 1) { strcpy(argv[argc++], "-c"); } //level-dependent sampling { strcpy(argv[argc++], "-l"); } reconstruct_con_init(); logz_con = dnest_con(argc, argv); if(parset.flag_para_name != 1) { if(parset.flag_exam_prior != 1) { postprocess_con(); if(thistask == roottask) { which_parameter_update = -1; which_particle_update = 0; calculate_con_from_model_semiseparable(best_model_con); FILE *fp; char fname[200]; int i; sprintf(fname, "%s/%s", parset.file_dir, parset.pcon_out_file); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } for(i=0; i<parset.n_con_recon; i++) { fprintf(fp, "%e %e %e\n", Tcon[i]*(1.0+parset.redshift), Fcon[i] / con_scale, Fcerrs[i]/con_scale); } fclose(fp); memcpy(var_param, best_model_con, num_params_var*sizeof(double)); memcpy(var_param_std, best_model_std_con, num_params_var*sizeof(double)); } } else { for(i=0; i<num_params_var; i++) { var_param[i] = 0.5*(par_range_model[i][0] + par_range_model[i][1]); var_param_std[i] =0.5*(par_range_model[i][1] - par_range_model[i][0])/2.35; } } //use the posterior mean and standard variance as the prior for the 1d and 2d RM. //only for variability parameters. MPI_Bcast(var_param, num_params_var, MPI_DOUBLE, roottask, MPI_COMM_WORLD); MPI_Bcast(var_param_std, num_params_var, MPI_DOUBLE, roottask, MPI_COMM_WORLD); } reconstruct_con_end(); //clear up argv for(i=0; i<9; i++) { free(argv[i]); } free(argv); return; } /*! * this function calculates continuum light curves from model parameters * and stores it into Fcon. */ void calculate_con_from_model(const void *model) { double *ybuf, *y, *yu, *Cq, *yq, *yuq; double syserr; double *pm = (double *)model; double sigma, tau, alpha; int i, info; syserr = (exp(pm[0]) - 1.0) * con_error_mean; // systematic error tau = exp(pm[2]); sigma = exp(pm[1]) * sqrt(tau); alpha = 1.0; ybuf = workspace; y = ybuf + n_con_data*nq; Cq = y + n_con_data; yq = Cq + nq*nq; yu = yq + nq; yuq = yu + parset.n_con_recon; set_covar_Pmat_data(sigma, tau, alpha, syserr); set_covar_Umat(sigma, tau, alpha); inverse_pomat(PCmat_data, n_con_data, &info); // Cq^-1 = L^TxC^-1xL multiply_mat_MN(PCmat_data, Larr_data, ybuf, n_con_data, nq, n_con_data); multiply_mat_MN_transposeA(Larr_data, ybuf, Cq, nq, nq, n_con_data); // L^TxC^-1xy multiply_matvec(PCmat_data, Fcon_data, n_con_data, ybuf); multiply_mat_MN_transposeA(Larr_data, ybuf, yq, nq, 1, n_con_data); // (hat q) = Cqx(L^TxC^-1xy) inverse_pomat(Cq, nq, &info); multiply_mat_MN(Cq, yq, ybuf, nq, 1, nq); // q = uq + (hat q) Chol_decomp_L(Cq, nq, &info); multiply_matvec(Cq, &pm[3], nq, yq); for(i=0; i<nq; i++) yq[i] += ybuf[i]; // y = yc - Lxq multiply_matvec_MN(Larr_data, n_con_data, nq, yq, ybuf); for(i=0; i<n_con_data; i++) { y[i] = Fcon_data[i] - ybuf[i]; } // (hat s) = SxC^-1xy multiply_matvec(PCmat_data, y, n_con_data, ybuf); multiply_matvec_MN(USmat, parset.n_con_recon, n_con_data, ybuf, Fcon); // SxC^-1xS^T multiply_mat_MN(USmat, PCmat_data, PEmat1, parset.n_con_recon, n_con_data, n_con_data); multiply_mat_MN_transposeB(PEmat1, USmat, PEmat2, parset.n_con_recon, parset.n_con_recon, n_con_data); // set DRW covariance at reconstructed points set_covar_Pmat(sigma, tau, alpha); // S - SxC^-1xS^T; covariance of reconstructed points for(i=0; i<parset.n_con_recon*parset.n_con_recon; i++) PQmat[i] = PSmat[i] - PEmat2[i]; // assign errors for(i=0; i<parset.n_con_recon; i++) { Fcerrs[i] = sqrt(PQmat[i*parset.n_con_recon + i]); } Chol_decomp_L(PQmat, parset.n_con_recon, &info); multiply_matvec(PQmat, &pm[num_params_var], parset.n_con_recon, yu); // add back long-term trend of continuum multiply_matvec_MN(Larr_rec, parset.n_con_recon, nq, yq, yuq); for(i=0; i<parset.n_con_recon; i++) { Fcon[i] += yu[i] + yuq[i]; } return; } /*! * this function calculates continuum light curves from model parameters * and stores it into Fcon. * * using fast algorithm for semiseparable matrices */ void calculate_con_from_model_semiseparable(const void *model) { double *Lbuf, *ybuf, *y, *Cq, *yq, *W, *D, *phi, *u, *v; double syserr; double *pm = (double *)model; double sigma, sigma2, tau, alpha; int i, info; syserr = (exp(pm[0]) - 1.0) * con_error_mean; // systematic error tau = exp(pm[2]); sigma = exp(pm[1]) * sqrt(tau); sigma2 = sigma*sigma; alpha = 1.0; Lbuf = workspace; ybuf = Lbuf + n_con_data*nq; y = ybuf + n_con_max; Cq = y + n_con_max; yq = Cq + nq*nq; W = yq + nq; D = W + n_con_max; phi = D + n_con_max; u = phi + n_con_max; v = u + parset.n_con_recon; set_covar_Umat(sigma, tau, alpha); compute_semiseparable_drw(Tcon_data, n_con_data, sigma2, 1.0/tau, Fcerrs_data, syserr, W, D, phi); // Cq^-1 = L^TxC^-1xL multiply_mat_semiseparable_drw(Larr_data, W, D, phi, n_con_data, nq, sigma2, Lbuf); multiply_mat_MN_transposeA(Larr_data, Lbuf, Cq, nq, nq, n_con_data); // L^TxC^-1xy multiply_matvec_semiseparable_drw(Fcon_data, W, D, phi, n_con_data, sigma2, ybuf); multiply_mat_MN_transposeA(Larr_data, ybuf, yq, nq, 1, n_con_data); // (hat q) = Cqx(L^TxC^-1xy) inverse_pomat(Cq, nq, &info); multiply_mat_MN(Cq, yq, ybuf, nq, 1, nq); // q = uq + (hat q) Chol_decomp_L(Cq, nq, &info); multiply_matvec(Cq, &pm[3], nq, yq); for(i=0; i<nq; i++) yq[i] += ybuf[i]; // y = yc - Lxq multiply_matvec_MN(Larr_data, n_con_data, nq, yq, ybuf); for(i=0; i<n_con_data; i++) { y[i] = Fcon_data[i] - ybuf[i]; } // (hat s) = SxC^-1xy multiply_matvec_semiseparable_drw(y, W, D, phi, n_con_data, sigma2, ybuf); multiply_matvec_MN(USmat, parset.n_con_recon, n_con_data, ybuf, Fcon); // SxC^-1xS^T multiply_mat_transposeB_semiseparable_drw(USmat, W, D, phi, n_con_data, parset.n_con_recon, sigma2, PEmat1); multiply_mat_MN(USmat, PEmat1, PEmat2, parset.n_con_recon, parset.n_con_recon, n_con_data); // set DRW covariance at reconstructed points set_covar_Pmat(sigma, tau, alpha); // S - SxC^-1xS^T; covariance of reconstructed points for(i=0; i<parset.n_con_recon*parset.n_con_recon; i++) PQmat[i] = PSmat[i] - PEmat2[i]; // assign errors for(i=0; i<parset.n_con_recon; i++) { Fcerrs[i] = sqrt(PQmat[i*parset.n_con_recon + i]); } Chol_decomp_L(PQmat, parset.n_con_recon, &info); multiply_matvec(PQmat, &pm[num_params_var], parset.n_con_recon, y); // add back long-term trend of continuum multiply_matvec_MN(Larr_rec, parset.n_con_recon, nq, yq, ybuf); for(i=0; i<parset.n_con_recon; i++) { Fcon[i] += y[i] + ybuf[i]; } return; } /*! * This function calculate continuum light curves from variability parameters. */ void reconstruct_con_from_varmodel(double sigma_hat, double tau, double alpha, double syserr) { double *Lbuf, *ybuf, *y, *yq, *yuq, *Cq, sigma; int i, info; double *PEmat3, *PEmat4; sigma = sigma_hat * sqrt(tau); Lbuf = workspace; ybuf = Lbuf + n_con_data * nq; y = ybuf + n_con_data; Cq = y + n_con_data; yq = Cq + nq*nq; yuq = yq + nq; PEmat3 = malloc(parset.n_con_recon * nq * sizeof(double)); PEmat4 = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double)); set_covar_Pmat_data(sigma, tau, alpha, syserr); set_covar_Umat(sigma, tau, alpha); inverse_pomat(PCmat_data, n_con_data, &info); multiply_mat_MN(PCmat_data, Larr_data, Lbuf, n_con_data, nq, n_con_data); multiply_mat_MN_transposeA(Larr_data, Lbuf, Cq, nq, nq, n_con_data); multiply_matvec(PCmat_data, Fcon_data, n_con_data, ybuf); multiply_mat_MN_transposeA(Larr_data, ybuf, yq, nq, 1, n_con_data); inverse_pomat(Cq, nq, &info); multiply_mat_MN(Cq, yq, ybuf, nq, 1, nq); memcpy(yq, ybuf, nq*sizeof(double)); multiply_matvec_MN(Larr_data, n_con_data, nq, yq, ybuf); for(i=0; i<n_con_data; i++) { y[i] = Fcon_data[i] - ybuf[i]; } multiply_matvec(PCmat_data, y, n_con_data, ybuf); multiply_matvec_MN(USmat, parset.n_con_recon, n_con_data, ybuf, Fcon); multiply_matvec_MN(Larr_rec, parset.n_con_recon, nq, yq, yuq); for(i=0; i<parset.n_con_recon; i++) Fcon[i] += yuq[i]; // SxC^-1xS^T multiply_mat_MN(USmat, PCmat_data, PEmat1, parset.n_con_recon, n_con_data, n_con_data); multiply_mat_MN_transposeB(PEmat1, USmat, PEmat2, parset.n_con_recon, parset.n_con_recon, n_con_data); multiply_mat_MN(PEmat1, Larr_data, PEmat3, parset.n_con_recon, nq, n_con_data); for(i=0; i<parset.n_con_recon*nq; i++)PEmat3[i] -= Larr_rec[i]; multiply_mat_MN(PEmat3, Cq, PEmat1, parset.n_con_recon, nq, nq); multiply_mat_MN_transposeB(PEmat1, PEmat3, PEmat4, parset.n_con_recon, parset.n_con_recon, nq); for(i=0; i<parset.n_con_recon; i++) { Fcerrs[i] = sqrt(sigma*sigma - PEmat2[i*parset.n_con_recon+i] + PEmat4[i*parset.n_con_recon + i]); } free(PEmat3); free(PEmat4); return; } /*! * this function calculates likelihood */ double prob_con_variability(const void *model) { double prob = 0.0; int i, info; double *pm = (double *)model; double tau, sigma, alpha, lndet, syserr; double *Lbuf, *ybuf, *y, *yq, *Cq; which_particle_update = dnest_get_which_particle_update(); if( which_parameter_update < num_params_var) { syserr = (exp(pm[0])-1.0)*con_error_mean; tau = exp(pm[2]); sigma = exp(pm[1]) * sqrt(tau); alpha = 1.0; Lbuf = workspace; ybuf = Lbuf + n_con_data*nq; y = ybuf + n_con_data; yq = y + n_con_data; Cq = yq + nq; set_covar_Pmat_data(sigma, tau, alpha, syserr); memcpy(IPCmat_data, PCmat_data, n_con_data*n_con_data*sizeof(double)); lndet = lndet_mat(PCmat_data, n_con_data, &info); inverse_pomat(IPCmat_data, n_con_data, &info); /* calculate C^-1 */ /* calculate L^T*C^-1*L */ multiply_mat_MN(IPCmat_data, Larr_data, Lbuf, n_con_data, nq, n_con_data); multiply_mat_MN_transposeA(Larr_data, Lbuf, Cq, nq, nq, n_con_data); /* calculate L^T*C^-1*y */ multiply_matvec(IPCmat_data, Fcon_data, n_con_data, ybuf); multiply_mat_MN_transposeA(Larr_data, ybuf, yq, nq, 1, n_con_data); /* calculate (L^T*C^-1*L)^-1 * L^T*C^-1*y */ inverse_pomat(Cq, nq, &info); multiply_mat_MN(Cq, yq, ybuf, nq, 1, nq); Chol_decomp_L(Cq, nq, &info); multiply_matvec(Cq, &pm[3], nq, yq); for(i=0; i<nq; i++) yq[i] += ybuf[i]; multiply_matvec_MN(Larr_data, n_con_data, nq, yq, ybuf); for(i=0; i<n_con_data; i++) { y[i] = Fcon_data[i] - ybuf[i]; } multiply_matvec(IPCmat_data, y, n_con_data, ybuf); prob = -0.5 * cblas_ddot(n_con_data, y, 1, ybuf, 1); prob += -0.5*lndet; prob_con_particles_perturb[which_particle_update] = prob; } else { prob = prob_con_particles[which_particle_update]; } return prob; } /*! * this function calculates likelihood * * using fast algorithm for semiseparable matrices */ double prob_con_variability_semiseparable(const void *model) { double prob = 0.0; int i, info; double *pm = (double *)model; double tau, sigma2, lndet, syserr; double *Lbuf, *ybuf, *y, *yq, *Cq, *W, *D, *phi; which_particle_update = dnest_get_which_particle_update(); if( which_parameter_update < num_params_var) { syserr = (exp(pm[0])-1.0)*con_error_mean; tau = exp(pm[2]); sigma2 = exp(2.0*pm[1]) * tau; Lbuf = workspace; ybuf = Lbuf + n_con_data*nq; y = ybuf + n_con_data; yq = y + n_con_data; Cq = yq + nq; W = Cq + nq*nq; D = W + n_con_data; phi = D + n_con_data; compute_semiseparable_drw(Tcon_data, n_con_data, sigma2, 1.0/tau, Fcerrs_data, syserr, W, D, phi); lndet = 0.0; for(i=0; i<n_con_data; i++) lndet += log(D[i]); /* calculate L^T*C^-1*L */ multiply_mat_semiseparable_drw(Larr_data, W, D, phi, n_con_data, nq, sigma2, Lbuf); multiply_mat_MN_transposeA(Larr_data, Lbuf, Cq, nq, nq, n_con_data); /* calculate L^T*C^-1*y */ multiply_matvec_semiseparable_drw(Fcon_data, W, D, phi, n_con_data, sigma2, ybuf); multiply_mat_MN_transposeA(Larr_data, ybuf, yq, nq, 1, n_con_data); /* calculate (L^T*C^-1*L)^-1 * L^T*C^-1*y */ inverse_pomat(Cq, nq, &info); multiply_mat_MN(Cq, yq, ybuf, nq, 1, nq); Chol_decomp_L(Cq, nq, &info); multiply_matvec(Cq, &pm[3], nq, yq); for(i=0; i<nq; i++) yq[i] += ybuf[i]; multiply_matvec_MN(Larr_data, n_con_data, nq, yq, ybuf); for(i=0; i<n_con_data; i++) { y[i] = Fcon_data[i] - ybuf[i]; } /* y^T x C^-1 x y*/ multiply_matvec_semiseparable_drw(y, W, D, phi, n_con_data, sigma2, ybuf); prob = -0.5 * cblas_ddot(n_con_data, y, 1, ybuf, 1); prob += -0.5*lndet; prob_con_particles_perturb[which_particle_update] = prob; } else { prob = prob_con_particles[which_particle_update]; } return prob; } /*! * this function calculates likelihood at initital step. */ double prob_con_variability_initial(const void *model) { double prob = 0.0; int i, info; double *pm = (double *)model; double tau, sigma, alpha, lndet, syserr; double *Lbuf, *ybuf, *y, *yq, *Cq; syserr = (exp(pm[0])-1.0)*con_error_mean; tau = exp(pm[2]); sigma = exp(pm[1]) * sqrt(tau); alpha = 1.0; Lbuf = workspace; ybuf = Lbuf + n_con_data*nq; y = ybuf + n_con_data; yq = y + n_con_data; Cq = yq + nq; set_covar_Pmat_data(sigma, tau, alpha, syserr); memcpy(IPCmat_data, PCmat_data, n_con_data*n_con_data*sizeof(double)); lndet = lndet_mat(PCmat_data, n_con_data, &info); inverse_pomat(IPCmat_data, n_con_data, &info); multiply_mat_MN(IPCmat_data, Larr_data, Lbuf, n_con_data, nq, n_con_data); multiply_mat_MN_transposeA(Larr_data, Lbuf, Cq, nq, nq, n_con_data); multiply_matvec(IPCmat_data, Fcon_data, n_con_data, ybuf); multiply_mat_MN_transposeA(Larr_data, ybuf, yq, nq, 1, n_con_data); inverse_pomat(Cq, nq, &info); multiply_mat_MN(Cq, yq, ybuf, nq, 1, nq); Chol_decomp_L(Cq, nq, &info); multiply_matvec(Cq, &pm[3], nq, yq); for(i=0; i<nq; i++) yq[i] += ybuf[i]; multiply_matvec_MN(Larr_data, n_con_data, nq, yq, ybuf); for(i=0; i<n_con_data; i++) { y[i] = Fcon_data[i] - ybuf[i]; } multiply_matvec(IPCmat_data, y, n_con_data, ybuf); prob = -0.5 * cblas_ddot(n_con_data, y, 1, ybuf, 1); prob += -0.5*lndet; prob_con_particles[which_particle_update] = prob; return prob; } /*! * this function calculates likelihood at initital step. * * using fast algorithm for semiseparable matrices */ double prob_con_variability_initial_semiseparable(const void *model) { double prob = 0.0; int i, info; double *pm = (double *)model; double tau, sigma2, lndet, syserr; double *Lbuf, *ybuf, *y, *yq, *Cq, *W, *D, *phi; syserr = (exp(pm[0])-1.0)*con_error_mean; tau = exp(pm[2]); sigma2 = exp(2.0*pm[1]) * tau; Lbuf = workspace; ybuf = Lbuf + n_con_data*nq; y = ybuf + n_con_data; yq = y + n_con_data; Cq = yq + nq; W = Cq + nq*nq; D = W + n_con_data; phi = D + n_con_data; compute_semiseparable_drw(Tcon_data, n_con_data, sigma2, 1.0/tau, Fcerrs_data, syserr, W, D, phi); lndet = 0.0; for(i=0; i<n_con_data; i++) lndet += log(D[i]); /* calculate L^T*C^-1*L */ multiply_mat_semiseparable_drw(Larr_data, W, D, phi, n_con_data, nq, sigma2, Lbuf); multiply_mat_MN_transposeA(Larr_data, Lbuf, Cq, nq, nq, n_con_data); /* calculate L^T*C^-1*y */ multiply_matvec_semiseparable_drw(Fcon_data, W, D, phi, n_con_data, sigma2, ybuf); multiply_mat_MN_transposeA(Larr_data, ybuf, yq, nq, 1, n_con_data); inverse_pomat(Cq, nq, &info); multiply_mat_MN(Cq, yq, ybuf, nq, 1, nq); Chol_decomp_L(Cq, nq, &info); multiply_matvec(Cq, &pm[3], nq, yq); for(i=0; i<nq; i++) yq[i] += ybuf[i]; multiply_matvec_MN(Larr_data, n_con_data, nq, yq, ybuf); for(i=0; i<n_con_data; i++) { y[i] = Fcon_data[i] - ybuf[i]; } /* y^T x C^-1 x y*/ multiply_matvec_semiseparable_drw(y, W, D, phi, n_con_data, sigma2, ybuf); prob = -0.5 * cblas_ddot(n_con_data, y, 1, ybuf, 1); prob += -0.5*lndet; prob_con_particles[which_particle_update] = prob; return prob; } /*! * this function sets the covariance matrix at time points for reconstruction. * store into PSmat. */ void set_covar_Pmat(double sigma, double tau, double alpha) { double t1, t2; int i, j; for(i=0; i<parset.n_con_recon; i++) { t1 = Tcon[i]; for(j=0; j<=i; j++) { t2 = Tcon[j]; PSmat[i*parset.n_con_recon+j] = sigma*sigma* exp (- pow (fabs(t1-t2) / tau, alpha)); PSmat[j*parset.n_con_recon+i] = PSmat[i*parset.n_con_recon+j]; } } return; } /*! * this function sets the covariance matrix at data time points */ void set_covar_Pmat_data(double sigma, double tau, double alpha, double syserr) { double t1, t2, err2; int i, j; for(i=0; i<n_con_data; i++) { t1 = Tcon_data[i]; for(j=0; j<i; j++) { t2 = Tcon_data[j]; PSmat_data[i*n_con_data+j] = sigma*sigma* exp (- pow (fabs(t1-t2) / tau, alpha)); PSmat_data[j*n_con_data+i] = PSmat_data[i*n_con_data+j]; //PNmat_data[i*n_con_data+j] = PNmat_data[j*n_con_data+i] = 0.0; PCmat_data[i*n_con_data+j] = PCmat_data[j*n_con_data+i] = PSmat_data[i*n_con_data+j]; } PSmat_data[i*n_con_data+i] = sigma * sigma; //PNmat_data[i*n_con_data+i] = Fcerrs_data[i]*Fcerrs_data[i] + syserr*syserr; //PCmat_data[i*n_con_data+i] = PSmat_data[i*n_con_data+i] + PNmat_data[i*n_con_data+i]; err2 = Fcerrs_data[i]*Fcerrs_data[i] + syserr*syserr; PCmat_data[i*n_con_data+i] = PSmat_data[i*n_con_data+i] + err2; } return; } /*! * this function sets the covariance matrix at time of data points and reconstruction points */ void set_covar_Umat(double sigma, double tau, double alpha) { double t1, t2; int i, j; for(i=0; i<parset.n_con_recon; i++) { t1 = Tcon[i]; for(j=0; j<n_con_data; j++) { t2 = Tcon_data[j]; USmat[i*n_con_data+j] = sigma*sigma * exp (- pow (fabs(t1-t2) / tau, alpha) ); } } return; } /*! * this function initializes the continuum reconstruction. */ void reconstruct_con_init() { int i, j; double dT, Tspan; Tspan = Tcon_data[n_con_data -1] - Tcon_data[0]; /* set time array for continuum */ if(parset.time_back > 0.0) Tcon_min = Tcon_data[0] - parset.time_back; else Tcon_min = Tcon_data[0] - fmax(0.05*Tspan, 10.0); Tcon_max = Tcon_data[n_con_data-1] + fmax(0.05*Tspan, 10.0); if(thistask == roottask) printf("Tcon_min_max: %f %f\n", Tcon_min - Tcon_data[0], Tcon_max - Tcon_data[n_con_data-1]); dT = (Tcon_max - Tcon_min)/(parset.n_con_recon -1); for(i=0; i<parset.n_con_recon; i++) { Tcon[i] = Tcon_min + i*dT; } /* set Larr_rec */ for(i=0;i<parset.n_con_recon;i++) { Larr_rec[i*nq + 0]=1.0; for(j=1; j<nq; j++) Larr_rec[i*nq + j] = pow(Tcon[i], j); } sprintf(dnest_options_file, "%s/%s", parset.file_dir, "src/OPTIONSCON"); if(thistask == roottask) { get_num_particles(dnest_options_file); } MPI_Bcast(&parset.num_particles, 1, MPI_INT, roottask, MPI_COMM_WORLD); Fcon = malloc(parset.n_con_recon * sizeof(double *)); prob_con_particles = malloc(parset.num_particles * sizeof(double)); prob_con_particles_perturb = malloc(parset.num_particles * sizeof(double)); return; } /*! * this function finalize the continuum reconstruction. */ void reconstruct_con_end() { int i; for(i=0; i<num_params; i++) { free(par_range_model[i]); free(par_prior_gaussian[i]); } free(par_range_model); free(par_prior_gaussian); free(par_prior_model); free(Fcon); free(prob_con_particles); free(prob_con_particles_perturb); free(best_model_con); free(best_model_std_con); return; } /*! * create continuum from random number generate based on damped random walk model. */ void create_con_from_random(double sigma_hat, double tau, double alpha, double syserr) { int i, info; double *Prandvec; double sigma = sigma_hat * sqrt(tau); double mean; Prandvec = malloc(parset.n_con_recon*sizeof(double)); set_covar_Pmat(sigma, tau, alpha); for(i=0; i<parset.n_con_recon; i++) { Prandvec[i] = gsl_ran_ugaussian(gsl_r); } Chol_decomp_L(PSmat, parset.n_con_recon, &info); multiply_matvec(PSmat, Prandvec, parset.n_con_recon, Fcon); mean = 0.0; for(i=0; i<parset.n_con_recon; i++) { Fcon[i] += sigma*3.0; /* shift light curve to have positive fluxes*/ mean += Fcon[i]; } mean /= parset.n_con_recon; for(i=0; i<parset.n_con_recon; i++) { Fcon[i] /= mean; } for(i=0; i<parset.n_con_recon; i++) { Fcon[i] += gsl_ran_ugaussian(gsl_r) * con_error_mean; Fcerrs[i] = con_error_mean; } free(Prandvec); return; }
{ "alphanum_fraction": 0.6373959412, "avg_line_length": 26.6261491318, "ext": "c", "hexsha": "4b159bcac7d0154d3df472c4f52049bdbbb65796", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z", "max_forks_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/BRAINS", "max_forks_repo_path": "src/reconstruct_con.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "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/BRAINS", "max_issues_repo_path": "src/reconstruct_con.c", "max_line_length": 111, "max_stars_count": 6, "max_stars_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/BRAINS", "max_stars_repo_path": "src/reconstruct_con.c", "max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z", "num_tokens": 9037, "size": 26067 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_core_typeutil_h_ #define SQ_INCLUDE_GUARD_core_typeutil_h_ #include <concepts> #include <cstddef> #include <gsl/gsl> #include <range/v3/range/concepts.hpp> #include <stdexcept> #include <string> #include <system_error> #include <type_traits> #include <variant> // The following macros can't be replaced with constexpr functions or constants // so tell clang-tidy not to complain // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define SQ_FWD(x) static_cast<decltype(x) &&>(x) // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define SQ_ND [[nodiscard]] // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define SQ_MU [[maybe_unused]] namespace sq { /** * Concept for types that can be dumped to a std::ostream. */ template <typename T> concept Printable = requires(T x, std::ostream &os) { os << x; }; ///@{ /** * Get whether the type T is a specialization of std::variant. */ template <typename T> struct IsVariant : std::false_type {}; template <typename... Types> struct IsVariant<std::variant<Types...>> : std::true_type {}; template <typename T> inline constexpr bool is_variant_v = IsVariant<T>::value; ///@} ///@{ /** * Get whether the type T is one of the alternative types of the variant V. */ template <typename T, typename V> requires is_variant_v<V> struct IsAlternative : std::false_type {}; template <typename T, typename... Types> struct IsAlternative<T, std::variant<Types...>> : std::disjunction<std::is_same<T, Types>...> {}; template <typename T, typename V> inline constexpr bool is_alternative_v = IsAlternative<T, V>::value; ///@} /** * Concept for types that are alternatives of the variant V. */ template <typename T, typename V> concept Alternative = is_alternative_v<T, V>; ///@{ /** * Get whether T can be converted to one of the variant V's alternatives. */ template <typename T, typename V> requires is_variant_v<V> struct IsConvertibleToAlternative : std::false_type {}; template <typename T, typename... Types> struct IsConvertibleToAlternative<T, std::variant<Types...>> : std::disjunction<std::is_convertible<T, Types>...> {}; template <typename T, typename V> inline constexpr bool is_convertible_to_alternative_v = IsConvertibleToAlternative<T, V>::value; ///@} /** * Concept for types that are convertible to one of the variant V's * alternatives. */ template <typename T, typename V> concept ConvertibleToAlternative = is_convertible_to_alternative_v<T, V>; ///@{ /** * A range whose distance can be obtained without invalidating the range. * * This is different to std::sized_range because it doesn't require: * - that size(rng) is available; * - that distance(rng) is a constant time operation. * * Essentially, it just rules out std::input_ranges without a known size. */ template <typename T> concept SlowSizedRange = ranges::cpp20::forward_range<T> || ranges::cpp20::sized_range<T>; /** * Get the name of the "base type" of the given expression. * * The "base type" is the type with no references or cv qualification. */ SQ_ND std::string base_type_name(const auto &thing); /** * Create a std::error code from a platform dependent error code. */ SQ_ND inline std::error_code make_error_code(int code) { return std::make_error_code(static_cast<std::errc>(code)); } } // namespace sq namespace ranges { // Tell the ranges library that gsl::spans with dynamic extent are views. Note // that the view concept requires a default constructor so sized gsl::spans are // *not* views... template <typename T> inline constexpr bool enable_view<gsl::span<T, gsl::dynamic_extent>> = true; // ... unless the size is zero. template <typename T> inline constexpr bool enable_view<gsl::span<T, 0>> = true; } // namespace ranges #include "core/typeutil.inl.h" #endif // SQ_INCLUDE_GUARD_core_typeutil_h_
{ "alphanum_fraction": 0.698792211, "avg_line_length": 28.7730496454, "ext": "h", "hexsha": "b6d542b8d16ce8f735dfa69c50a1b4794cd61c78", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/core/include/core/typeutil.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/core/include/core/typeutil.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/core/include/core/typeutil.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 951, "size": 4057 }
#include <string.h> #include <stdint.h> #include <mpi.h> #include <gsl/gsl_rng.h> #include <fastpm/libfastpm.h> #include <fastpm/logging.h> #include <fastpm/string.h> #include <fastpm/transfer.h> #include "chealpix.h" #include <mpsort.h> #include "pmpfft.h" #include "pmghosts.h" static double RNDTABLE[8192]; gsl_rng * random_generator; void fastpm_utils_init_randtable() { random_generator = gsl_rng_alloc(gsl_rng_ranlxd1); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); gsl_rng_set(random_generator, 37 * (rank + 1) + 1); /* start-up seed */ int i; for(i = 0; i < 8192; i ++) { RNDTABLE[i] = gsl_rng_uniform(random_generator); } //gsl_rng_free(random_generator); } double fastpm_utils_get_random(uint64_t id) { return gsl_rng_uniform(random_generator); uint64_t ind = 0; ind = id; while(id != 0) { ind += id; id /= 8192; } ind %= 8192; return RNDTABLE[ind]; } void fastpm_utils_dump(PM * pm , const char * filename, FastPMFloat *data) { char fn1[1024]; char fn2[1024]; if(pm->NTask > 1) { sprintf(fn1, "%s.%03d.geometry", filename, pm->ThisTask); sprintf(fn2, "%s.%03d", filename, pm->ThisTask); } else { sprintf(fn1, "%s.geometry", filename); sprintf(fn2, "%s", filename); } fastpm_path_ensure_dirname(filename); FILE * fp; fp = fopen(fn2, "w"); if(pm->allocsize != fwrite(data, sizeof(FastPMFloat), pm->allocsize, fp)) { fastpm_raise(-1, "IO failed.\n"); } fclose(fp); fp = fopen(fn1, "w"); fprintf(fp, "# real\n"); fprintf(fp, "start: %td %td %td\n", pm->IRegion.start[0], pm->IRegion.start[1], pm->IRegion.start[2]); fprintf(fp, "size: %td %td %td\n", pm->IRegion.size[0], pm->IRegion.size[1], pm->IRegion.size[2]); fprintf(fp, "strides: %td %td %td\n", pm->IRegion.strides[0], pm->IRegion.strides[1], pm->IRegion.strides[2]); fprintf(fp, "# complex\n"); fprintf(fp, "start: %td %td %td\n", pm->ORegion.start[0], pm->ORegion.start[1], pm->ORegion.start[2]); fprintf(fp, "size: %td %td %td\n", pm->ORegion.size[0], pm->ORegion.size[1], pm->ORegion.size[2]); fprintf(fp, "strides: %td %td %td\n", pm->ORegion.strides[0], pm->ORegion.strides[1], pm->ORegion.strides[2]); fclose(fp); } void fastpm_utils_load(PM * pm , const char * filename, FastPMFloat *data) { char fn1[1024]; char fn2[1024]; if(pm->NTask > 1) { sprintf(fn1, "%s.%03d.geometry", filename, pm->ThisTask); sprintf(fn2, "%s.%03d", filename, pm->ThisTask); } else { sprintf(fn1, "%s.geometry", filename); sprintf(fn2, "%s", filename); } FILE * fp; fp = fopen(fn2, "r"); if(pm->allocsize != fread(data, sizeof(FastPMFloat), pm->allocsize, fp)) { fastpm_raise(-1, "File was bad\n"); }; fclose(fp); } static double tk_eh(double k, struct fastpm_powerspec_eh_params * params) /* from Martin White */ { double q, theta, ommh2, a, s, gamma, L0, C0; double tmp; double omegam, ombh2, hubble; /* other input parameters */ hubble = params->hubble_param; omegam = params->omegam; ombh2 = params->omegab * hubble * hubble; theta = 2.728 / 2.7; ommh2 = omegam * hubble * hubble; s = 44.5 * log(9.83 / ommh2) / sqrt(1. + 10. * exp(0.75 * log(ombh2))) * hubble; a = 1. - 0.328 * log(431. * ommh2) * ombh2 / ommh2 + 0.380 * log(22.3 * ommh2) * (ombh2 / ommh2) * (ombh2 / ommh2); gamma = a + (1. - a) / (1. + exp(4 * log(0.43 * k * s))); gamma *= omegam * hubble; q = k * theta * theta / gamma; L0 = log(2. * exp(1.) + 1.8 * q); C0 = 14.2 + 731. / (1. + 62.5 * q); tmp = L0 / (L0 + C0 * q * q); return (tmp); } double fastpm_utils_powerspec_eh(double k, struct fastpm_powerspec_eh_params * param) /* Eisenstein & Hu */ { return param->Norm * k * pow(tk_eh(k, param), 2); } double fastpm_utils_powerspec_white(double k, double * amplitude) /* White Noise*/ { return *amplitude; } static void _sort_pix(const void * ptr, void * radix, void * arg) { memcpy(radix, ptr, 8); } /* generate evenly balanced healpix positions that are inside the lightcone. */ void fastpm_utils_healpix_ra_dec ( int nside, double **ra, double **dec, uint64_t **pix, size_t * n, FastPMLightCone * lc, MPI_Comm comm ) { const double rad_to_degree = 180./M_PI; size_t npix = nside2npix (nside); int ThisTask, NTask; MPI_Comm_rank(comm, &ThisTask); MPI_Comm_size(comm, &NTask); //fastpm_info("healpix npix %ld \n",*npix); size_t i = 0; size_t pix_start = ThisTask * npix / NTask; size_t pix_end = (ThisTask + 1) * npix / NTask; uint64_t local_npix = 0; uint64_t * pixels = NULL; /* two iterations; estimate and fill */ while(1) { size_t j = 0; for (i = pix_start; i < pix_end; i++) { double vec[3]; pix2vec_ring(nside, i, vec); if(!fastpm_lc_inside(lc, vec)) continue; if(pixels != NULL) { pixels[j] = i; } j ++; } if(pixels == NULL) { local_npix = j; pixels = malloc(sizeof(uint64_t) * local_npix); } else { break; } } /* count total */ uint64_t valid_npix = local_npix; MPI_Allreduce(MPI_IN_PLACE, &valid_npix, 1, MPI_LONG, MPI_SUM, comm); /* redistribute / balance */ size_t localsize = (ThisTask + 1) * valid_npix / NTask - (ThisTask ) * valid_npix / NTask; uint64_t * recv_buffer = malloc(sizeof(uint64_t) * localsize); mpsort_mpi_newarray(pixels, local_npix, recv_buffer, localsize, sizeof(uint64_t), _sort_pix, 8, NULL, comm); free(pixels); *ra = malloc(sizeof(double) * localsize); *dec = malloc(sizeof(double) * localsize); for(i = 0; i < localsize; i ++) { double phi, theta; pix2ang_ring(nside, recv_buffer[i], &theta, &phi); phi *= rad_to_degree; theta*= rad_to_degree; (*ra)[i] = phi; (*dec)[i]= 90 - theta; recv_buffer[i] += (((uint64_t)nside) << 48); } *n = localsize; *pix = recv_buffer; } void fastpm_gldot(double glmatrix[4][4], double xi[4], double xo[4]) { int i, j; for(i = 0; i < 4; i ++) { xo[i] = 0; for(j = 0; j < 4; j ++) { xo[i] += glmatrix[i][j] * xi[j]; } } } void fastpm_gldotf(double glmatrix[4][4], float vi[4], float vo[4]) { int i, j; for(i = 0; i < 4; i ++) { vo[i] = 0; for(j = 0; j < 4; j ++) { vo[i] += glmatrix[i][j] * vi[j]; } } } /* returns MPI_LOR reduction */ int MPIU_Any(MPI_Comm comm, int value) { MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_INT, MPI_LOR, comm); return value; } /* returns MPI_LAND reduction */ int MPIU_All(MPI_Comm comm, int value) { MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_INT, MPI_LAND, comm); return value; } /* * Compute the standard statistics of a value over communicator. * fmt is a string, describing the list of stats to return: * < : minimum (double) * , : rank of minimum (int) * > : maximum (double) * . : rank of maximum (int) * - : mean (double) * s : std (biased standard derivation) * v : variance (biased variance) * S : unbiased std * V : unbiased variance * * e.g. * * double min, max; * MPIU_stats(comm, r, "<>", &min, &max); * * returns number of items converted; * if a fmt char is unknown, the input variable is unmodified. * * */ int MPIU_stats(MPI_Comm comm, const double value, const char * fmt, ...) { va_list va; va_start(va, fmt); int NTask; MPI_Comm_size(comm, &NTask); int ThisTask; MPI_Comm_rank(comm, &ThisTask); double sum = value; struct { double value; int rank; } min = {value, ThisTask}, max = {value, ThisTask}; double sumsq = value * value; MPI_Allreduce(MPI_IN_PLACE, &sum, 1, MPI_DOUBLE, MPI_SUM, comm); MPI_Allreduce(MPI_IN_PLACE, &sumsq, 1, MPI_DOUBLE, MPI_SUM, comm); MPI_Allreduce(MPI_IN_PLACE, &min, 1, MPI_DOUBLE_INT, MPI_MINLOC, comm); MPI_Allreduce(MPI_IN_PLACE, &max, 1, MPI_DOUBLE_INT, MPI_MAXLOC, comm); double avg = (sum) / NTask; double avg_sq = (sumsq) / NTask; double var = avg_sq - avg * avg; double std = sqrt(avg_sq - avg * avg); int i; int c = 0; for(i = 0; i < strlen(fmt); i ++) { void * r = va_arg(va, void *); int * ir = (int * ) r; double * dr = (double * ) r; c++; switch(fmt[i]) { case '-': *dr = avg; break; case '<': *dr = min.value; break; case '>': *dr = max.value; break; case ',': *ir = min.rank; break; case '.': *ir = max.rank; break; case 's': *dr = std; break; case 'S': *dr = std * sqrt(1.0 * NTask / (NTask - 1.0)); break; case 'v': *dr = var; break; case 'V': *dr = var * 1.0 * NTask / (NTask - 1.0); break; default: c--; } } va_end(va); return c; } /* * * create a copy of string src and broadcast it to all ranks. * * Every rank receives a copy of src as the return value, including the root. * * if free is not NULL, the function is called as free(src) * */ char * MPIU_Bcast_string(MPI_Comm comm, char * src, int root, void(*free)(void * ptr)) { int srcNULL = src == NULL; MPI_Bcast(&srcNULL, 1, MPI_INT, root, comm); if(srcNULL) return NULL; int rank; int N; MPI_Comm_rank(comm, &rank); if(rank == root) { N = strlen(src) + 1; } MPI_Bcast(&N, 1, MPI_INT, root, comm); char * ret = malloc(N); if(rank == root) { strcpy(ret, src); } if(free && rank == root) free(src); MPI_Bcast(ret, N, MPI_BYTE, root, comm); return ret; }
{ "alphanum_fraction": 0.5282632949, "avg_line_length": 25.0139534884, "ext": "c", "hexsha": "3c4ebed2f98a9509f59bd0939ade4a0ac512945f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_path": "fastpm/libfastpm/utils.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_path": "fastpm/libfastpm/utils.c", "max_line_length": 112, "max_stars_count": null, "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_path": "fastpm/libfastpm/utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3211, "size": 10756 }
/* filter/test_impulse.c * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_filter.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_test.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> static int vector_sum(const gsl_vector_int * v) { size_t i; int sum = 0; for (i = 0; i < v->size; ++i) { int vi = gsl_vector_int_get(v, i); sum += vi; } return sum; } static void test_impulse_proc(const double tol, const size_t n, const size_t K, const double nsigma, const gsl_filter_end_t etype, const gsl_filter_scale_t stype, const double outlier_percentage, gsl_rng * r) { gsl_vector * x = gsl_vector_alloc(n); gsl_vector * y = gsl_vector_alloc(n); gsl_vector * z = gsl_vector_alloc(n); gsl_vector * y_med = gsl_vector_alloc(n); gsl_vector * xmedian = gsl_vector_alloc(n); gsl_vector * xsigma = gsl_vector_alloc(n); size_t noutlier; gsl_vector_int * ioutlier = gsl_vector_int_alloc(n); gsl_vector_int * ioutlier_exact = gsl_vector_int_alloc(n); size_t i; gsl_filter_impulse_workspace *impulse_p = gsl_filter_impulse_alloc(K); gsl_filter_median_workspace *median_p = gsl_filter_median_alloc(K); size_t noutlier_exact = 0; char buf[1024]; gsl_vector_int_set_zero(ioutlier_exact); for (i = 0; i < n; ++i) { double xi = gsl_ran_gaussian(r, 1.0); double vi = gsl_rng_uniform(r); if (vi <= outlier_percentage) { xi += 15.0 * GSL_SIGN(xi); ++noutlier_exact; gsl_vector_int_set(ioutlier_exact, i, 1); } gsl_vector_set(x, i, xi); } /* first test that median filter is equal to impulse filter with nsigma = 0 */ gsl_filter_median(etype, x, y_med, median_p); gsl_filter_impulse(etype, stype, 0.0, x, y, xmedian, xsigma, &noutlier, ioutlier, impulse_p); sprintf(buf, "impulse nsigma=0 smf comparison, etype=%u stype=%u", etype, stype); compare_vectors(tol, y, y_med, buf); /* second test: filter y = impulse(x) with given nsigma */ gsl_filter_impulse(etype, stype, nsigma, x, y, xmedian, xsigma, &noutlier, ioutlier, impulse_p); /* test correct number of outliers detected */ gsl_test(noutlier != noutlier_exact, "impulse [n=%zu,K=%zu,nsigma=%g,outlier_percentage=%g] noutlier=%zu exact=%zu", n, K, nsigma, outlier_percentage, noutlier, noutlier_exact); #if 0 { for (i = 0; i < n; ++i) { printf("%.12e %.12e %d %.12e %.12e\n", gsl_vector_get(x, i), gsl_vector_get(y, i), gsl_vector_int_get(ioutlier, i), gsl_vector_get(xmedian, i) + nsigma * gsl_vector_get(xsigma, i), gsl_vector_get(xmedian, i) - nsigma * gsl_vector_get(xsigma, i)); } } #endif /* test outliers found in correct locations */ for (i = 0; i < n; ++i) { int val = gsl_vector_int_get(ioutlier, i); int val_exact = gsl_vector_int_get(ioutlier_exact, i); gsl_test(val != val_exact, "test_impulse: outlier mismatch [i=%zu,K=%zu,nsigma=%g,outlier_percentage=%g] ioutlier=%d ioutlier_exact=%d", i, K, nsigma, outlier_percentage, val, val_exact); } /* test noutlier = sum(ioutlier) */ { size_t iout_sum = vector_sum(ioutlier); gsl_test(noutlier != iout_sum, "impulse [K=%zu,nsigma=%g,outlier_percentage=%g] noutlier=%zu sum(ioutlier)=%zu", K, nsigma, outlier_percentage, noutlier, iout_sum); } /* third test: test in-place filter z = impulse(z) */ gsl_vector_memcpy(z, x); gsl_filter_impulse(etype, stype, nsigma, z, z, xmedian, xsigma, &noutlier, ioutlier, impulse_p); sprintf(buf, "impulse in-place nsigma=%g,n=%zu,K=%zu,etype=%u stype=%u", nsigma, n, K, etype, stype); compare_vectors(GSL_DBL_EPSILON, z, y, buf); gsl_vector_free(x); gsl_vector_free(y); gsl_vector_free(z); gsl_vector_free(y_med); gsl_vector_free(xmedian); gsl_vector_free(xsigma); gsl_vector_int_free(ioutlier); gsl_vector_int_free(ioutlier_exact); gsl_filter_impulse_free(impulse_p); gsl_filter_median_free(median_p); } static void test_impulse(gsl_rng * r) { const double tol = 1.0e-10; test_impulse_proc(tol, 1000, 21, 6.0, GSL_FILTER_END_TRUNCATE, GSL_FILTER_SCALE_QN, 0.05, r); test_impulse_proc(tol, 1000, 21, 6.0, GSL_FILTER_END_TRUNCATE, GSL_FILTER_SCALE_SN, 0.05, r); test_impulse_proc(tol, 1000, 21, 6.0, GSL_FILTER_END_TRUNCATE, GSL_FILTER_SCALE_MAD, 0.05, r); test_impulse_proc(tol, 1000, 21, 6.0, GSL_FILTER_END_TRUNCATE, GSL_FILTER_SCALE_IQR, 0.05, r); }
{ "alphanum_fraction": 0.6829635201, "avg_line_length": 33.872611465, "ext": "c", "hexsha": "c3abfdddad23178c21c60a627c0499a10f734023", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/filter/test_impulse.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/filter/test_impulse.c", "max_line_length": 142, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/filter/test_impulse.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": 1584, "size": 5318 }
/** */ #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_interp.h> #include "aXe_utils.h" #include "aXe_errors.h" #include "fringe_conf.h" #include "fringe_model.h" #define MAX(x,y) (((x)>(y))?(x):(y)) #define MIN(x,y) (((x)<(y))?(x):(y)) /** * Function: compute_fringe_amplitude * The function computes the fringe image for a CCD setup stored * in a fringe configuration structure. This fringe configuration * structure completely describes the problem, and this function * executes the loops for every pixel over the wavelength * range spanned by the filter. * * Parameters * @param fconf - the fringe configuration structure * * Returns: * @return fringe_image - the image with the computed fringe amplitudes */ gsl_matrix * compute_fringe_amplitude(fringe_conf *fconf) { gsl_matrix *fringe_image; gsl_vector **filter_vectors; int index=0; int ii=0; int jj=0; double lambda_mean; double pixel_ampl; //double phase_number; optical_property *optprops; // allocate the fringe image fringe_image = alloc_fringe_image(fconf->opt_layers); // allocate memory for the optical property structure optprops = alloc_optprops_list(fconf); // find the exact wavelength range, // and define the wavelength values and // normalized fiter throughput there filter_vectors = evaluate_wavelength_steps(fconf); //filter_vectors = get_PET_calibration_data(); // compute the mean wavelength lambda_mean = gsl_vector_get(filter_vectors[0],filter_vectors[0]->size-1)/2.0 + gsl_vector_get(filter_vectors[0],0)/2.0; // initialize some values in the optical property list init_optprops_list(fconf, lambda_mean, optprops); for (ii=0; ii < (int)fringe_image->size1; ii++) // for (ii=0; ii < 2; ii++) { fprintf(stderr, "Computing row No.: %i\n", ii); for (jj=0; jj < (int)fringe_image->size2; jj++) //for (jj=0; jj < 2; jj++) { // fill the optical thickness of the layers // into the structure fill_optprops_thickness(fconf->opt_layers, ii, jj, optprops); pixel_ampl = 0.0; for (index=0; index < (int)filter_vectors[0]->size; index++) { // fill all information in the optical // property list fill_optprops_all(fconf->opt_layers, gsl_vector_get(filter_vectors[0],index), optprops); // compute and add the contribution at a wavelength pixel_ampl += gsl_vector_get(filter_vectors[1],index)* fringe_contrib_single(optprops, fconf); } // finally set the pixel value // in the output image gsl_matrix_set(fringe_image, ii, jj, fconf->fringe_amp * pixel_ampl + 1.0); } } // release the memory in the vectors gsl_vector_free(filter_vectors[0]); gsl_vector_free(filter_vectors[1]); free(filter_vectors); // free the optical property structure free_optprops_list(optprops); // return the fringe image return fringe_image; } /** * Function: alloc_fringe_image * The function browses through the the structure for the CCD layers * and extracts all information on image sizes stored there in * one or several thickness images. This information is checked * for consistency. * Finally, a matrix for a fringe image is allocated, initialized * and returned. * * Parameters: * @param opt_layers - the optical layers in the CCD * * Returns: * @return fringe_image - the allocated matrix for the fringe image */ gsl_matrix * alloc_fringe_image(const ccd_layers *opt_layers) { int n1 = 0; int n2 = 0; int n1_new = 0; int n2_new = 0; int index = 0; int is_defined = 0; gsl_matrix *fringe_image=NULL; // go through all CCD layers for (index=0; index < opt_layers->num_layers; index++) { // check whether the thickness information // is represented by an image if (opt_layers->opt_layer[index]->thickness2D != NULL) { // mark that an image was found is_defined=1; // get the dimension of the image n1_new = opt_layers->opt_layer[index]->thickness2D->size1; n2_new = opt_layers->opt_layer[index]->thickness2D->size2; // check the frst axix value against // previous values, if possible if (n1 && n1_new != n1) // give an error if the new value is different aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Thickness image of layer %i " "has %i pixels in first axis." "This differs from the previous value %i\n", index, n1_new, n1); else // store the new value n1 = n1_new; // check the frst axix value against // previous values, if possible if (n2 && n2_new != n2) // give an error if the new value is different aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Thickness image of layer %i " "has %i pixels in second axis." "This differs from the previous value %i\n", index, n2_new, n2); else // store the new value n2 = n2_new; } } #ifdef DEBUGFCONF fprintf(stdout, "Allocating an image with size: (%i, %i)\n", n1, n2); #endif // check whether at least one image was // found as thickness information if (is_defined) { // allocate the image fringe_image = gsl_matrix_alloc(n1, n2); // set all vallues to zero gsl_matrix_set_all(fringe_image, 0.0); } else { // no image found; report the error aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "The size of the fringe image is unknown\n" "since none of the layers has an image " "to specify its thickness!\n"); } // return the image return fringe_image; } /** * Function: get_calibration_data() * This function is a data storage for filter throughput values * as computed by the orioginal program 'final.f' of J.Walsh. * The cubic spline routine used there turned out to give * (slightly) different results than the gsl-routine used * here. To be able making a in-depth comparison the throughuts * were computed for the filter 'ccd_ref.fits' and stored here. * * Parameters: * * Returns: * @return double_vector - interpolated standard filter throughputs */ gsl_vector ** get_calibration_data() { gsl_vector *lambda_values; gsl_vector *through_values; gsl_vector **double_vector; // allocate space for the return vector double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *)); // allocate the space for the vectors lambda_values = gsl_vector_alloc(43); through_values = gsl_vector_alloc(43); // what follows is the wavelength steps as well as the normalized // filter throughputs which were computed in the original // program 'final.f' of J.Walsh. // The gsl-cubic spline routine yields slightly different values. // The values fixed here are good for a detailed cross-check // of the two programs. gsl_vector_set(through_values, 0, 0.0000000000000000);gsl_vector_set(lambda_values, 0, 0.9179); gsl_vector_set(through_values, 1, 0.0095066184313808);gsl_vector_set(lambda_values, 1, 0.9180); gsl_vector_set(through_values, 2, 0.0176006475945001);gsl_vector_set(lambda_values, 2, 0.9181); gsl_vector_set(through_values, 3, 0.0240259215044616);gsl_vector_set(lambda_values, 3, 0.9182); gsl_vector_set(through_values, 4, 0.0289185490230508);gsl_vector_set(lambda_values, 4, 0.9183); gsl_vector_set(through_values, 5, 0.0324146730103703);gsl_vector_set(lambda_values, 5, 0.9184); gsl_vector_set(through_values, 6, 0.0346504181940869);gsl_vector_set(lambda_values, 6, 0.9185); gsl_vector_set(through_values, 7, 0.0357619115684218);gsl_vector_set(lambda_values, 7, 0.9186); gsl_vector_set(through_values, 8, 0.0358852710613785);gsl_vector_set(lambda_values, 8, 0.9187); gsl_vector_set(through_values, 9, 0.0351566282002872);gsl_vector_set(lambda_values, 9, 0.9188); gsl_vector_set(through_values,10, 0.0337121099793692);gsl_vector_set(lambda_values,10, 0.9189); gsl_vector_set(through_values,11, 0.0316878433928458);gsl_vector_set(lambda_values,11, 0.9190); gsl_vector_set(through_values,12, 0.0292199509018293);gsl_vector_set(lambda_values,12, 0.9191); gsl_vector_set(through_values,13, 0.0264445572339866);gsl_vector_set(lambda_values,13, 0.9192); gsl_vector_set(through_values,14, 0.0234977916500934);gsl_vector_set(lambda_values,14, 0.9193); gsl_vector_set(through_values,15, 0.0205157811443709);gsl_vector_set(lambda_values,15, 0.9194); gsl_vector_set(through_values,16, 0.0176346504444861);gsl_vector_set(lambda_values,16, 0.9195); gsl_vector_set(through_values,17, 0.0149905288112146);gsl_vector_set(lambda_values,17, 0.9196); gsl_vector_set(through_values,18, 0.0127195375723916);gsl_vector_set(lambda_values,18, 0.9197); gsl_vector_set(through_values,19, 0.0109578003224067);gsl_vector_set(lambda_values,19, 0.9198); gsl_vector_set(through_values,20, 0.0098414542549762);gsl_vector_set(lambda_values,20, 0.9199); gsl_vector_set(through_values,21, 0.0095066184313808);gsl_vector_set(lambda_values,21, 0.9200); gsl_vector_set(through_values,22, 0.0100435357173845);gsl_vector_set(lambda_values,22, 0.9201); gsl_vector_set(through_values,23, 0.0113589226644173);gsl_vector_set(lambda_values,23, 0.9202); gsl_vector_set(through_values,24, 0.0133136264280558);gsl_vector_set(lambda_values,24, 0.9203); gsl_vector_set(through_values,25, 0.0157684646986687);gsl_vector_set(lambda_values,25, 0.9204); gsl_vector_set(through_values,26, 0.0185842800987238);gsl_vector_set(lambda_values,26, 0.9205); gsl_vector_set(through_values,27, 0.0216219095843027);gsl_vector_set(lambda_values,27, 0.9206); gsl_vector_set(through_values,28, 0.0247421844451007);gsl_vector_set(lambda_values,28, 0.9207); gsl_vector_set(through_values,29, 0.0278059450370313);gsl_vector_set(lambda_values,29, 0.9208); gsl_vector_set(through_values,30, 0.0306740203832353);gsl_vector_set(lambda_values,30, 0.9209); gsl_vector_set(through_values,31, 0.0332072463065172);gsl_vector_set(lambda_values,31, 0.9210); gsl_vector_set(through_values,32, 0.0352664608962358);gsl_vector_set(lambda_values,32, 0.9211); gsl_vector_set(through_values,33, 0.0367124999751954);gsl_vector_set(lambda_values,33, 0.9212); gsl_vector_set(through_values,34, 0.0374061970996460);gsl_vector_set(lambda_values,34, 0.9213); gsl_vector_set(through_values,35, 0.0372083835592830);gsl_vector_set(lambda_values,35, 0.9214); gsl_vector_set(through_values,36, 0.0359798997100196);gsl_vector_set(lambda_values,36, 0.9215); gsl_vector_set(through_values,37, 0.0335815745749970);gsl_vector_set(lambda_values,37, 0.9216); gsl_vector_set(through_values,38, 0.0298742553097917);gsl_vector_set(lambda_values,38, 0.9217); gsl_vector_set(through_values,39, 0.0247187709375447);gsl_vector_set(lambda_values,39, 0.9218); gsl_vector_set(through_values,40, 0.0179759414151792);gsl_vector_set(lambda_values,40, 0.9219); gsl_vector_set(through_values,41, 0.0095066184313808);gsl_vector_set(lambda_values,41, 0.9220); gsl_vector_set(through_values,42, 0.0000000000000000);gsl_vector_set(lambda_values,42, 0.9221); // build up the output array double_vector[0] = lambda_values; double_vector[1] = through_values; // return the two vectors return double_vector; } /** * Function: get_PET_calibration_data() */ gsl_vector ** get_PET_calibration_data() { gsl_vector *lambda_values; gsl_vector *through_values; gsl_vector **double_vector; // allocate space for the return vector double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *)); // allocate the space for the vectors lambda_values = gsl_vector_alloc(21); through_values = gsl_vector_alloc(21); gsl_vector_set(lambda_values, 0,1.069460); gsl_vector_set(through_values, 0, 0.000000); gsl_vector_set(lambda_values, 1,1.069653); gsl_vector_set(through_values, 1, 0.012630); gsl_vector_set(lambda_values, 2,1.069846); gsl_vector_set(through_values, 2, 0.025261); gsl_vector_set(lambda_values, 3,1.070039); gsl_vector_set(through_values, 3, 0.037891); gsl_vector_set(lambda_values, 4,1.070232); gsl_vector_set(through_values, 4, 0.050522); gsl_vector_set(lambda_values, 5,1.070424); gsl_vector_set(through_values, 5, 0.063152); gsl_vector_set(lambda_values, 6,1.070617); gsl_vector_set(through_values, 6, 0.069010); gsl_vector_set(lambda_values, 7,1.070810); gsl_vector_set(through_values, 7, 0.069010); gsl_vector_set(lambda_values, 8,1.071003); gsl_vector_set(through_values, 8, 0.069010); gsl_vector_set(lambda_values, 9,1.071196); gsl_vector_set(through_values, 9, 0.069010); gsl_vector_set(lambda_values, 10,1.071389); gsl_vector_set(through_values, 10, 0.069010); gsl_vector_set(lambda_values, 11,1.071582); gsl_vector_set(through_values, 11, 0.069010); gsl_vector_set(lambda_values, 12,1.071775); gsl_vector_set(through_values, 12, 0.069010); gsl_vector_set(lambda_values, 13,1.071967); gsl_vector_set(through_values, 13, 0.069010); gsl_vector_set(lambda_values, 14,1.072160); gsl_vector_set(through_values, 14, 0.069010); gsl_vector_set(lambda_values, 15,1.072353); gsl_vector_set(through_values, 15, 0.063152); gsl_vector_set(lambda_values, 16,1.072546); gsl_vector_set(through_values, 16, 0.050522); gsl_vector_set(lambda_values, 17,1.072739); gsl_vector_set(through_values, 17, 0.037891); gsl_vector_set(lambda_values, 18,1.072932); gsl_vector_set(through_values, 18, 0.025261); gsl_vector_set(lambda_values, 19,1.073125); gsl_vector_set(through_values, 19, 0.012630); gsl_vector_set(lambda_values, 20,1.073318); gsl_vector_set(through_values, 20, 0.000000); //Wavelength: 10713.888672, fringe factor: 1.097945, (x,y): (18, 745) // build up the output array double_vector[0] = lambda_values; double_vector[1] = through_values; // return the two vectors return double_vector; } /** * Function: evaluate_wavelength_steps * The function defines and computes the wavelength steps and the * filter throughputs which are used to compute the fringe amplitude * for all pixels. The basis for the wavelength data are the * filter data and the general are where fringing is significant * and computed, which is defined in the fringe * configuration structure. * First all throughput values below a certain value are discarded * at the short and long wavelength edge. Then the final wavelength * range is determined using the fringing range. Then all wavelength * values and the filter throughputs are determined and returned * as two gsl-vectors. * * Parameters: * @param fconf - the fringe configuration structure * * Returns: * @return double_vector - a set of two gsl-vectors with wavlength and throughput */ gsl_vector ** evaluate_wavelength_steps(fringe_conf *fconf) { int index=0; int lower=0; int upper=0; int nsteps; double lambda_min; double lambda_max; double lambda_act; double through_act=0.0; double through_tot=0.0; gsl_vector *lambda_values; gsl_vector *through_values; gsl_vector **double_vector; // allocate space for the return vector double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *)); // search through the filter data // to narrow the usable range from below lower=0; while (lower < fconf->filter_through->nvals && fconf->filter_through->yvals[lower] < FILTER_THRESHOLD) lower++; lower = MAX(0,lower-1); // search through the filter data // to narrow the usable range from above upper=fconf->filter_through->nvals - 1; while (upper > -1 && fconf->filter_through->yvals[upper] < FILTER_THRESHOLD) upper--; upper = MIN(fconf->filter_through->nvals - 1, upper+1); #ifdef DEBUGFCONF fprintf(stderr, "New lower range index: %i, new upper: %i, old number: %i\n", lower, upper, fconf->filter_through->nvals); #endif // replace the old filter interpolator // with a new one, if necessary if (lower != 0 || upper != (fconf->filter_through->nvals - 1)) fconf->filter_through = redefine_filter_throughput(lower, upper, fconf); // compute the lower wavelength range by comparing // the filter throughput with the range important // for fringing; the latter is given in AA!! lambda_min = MAX(gsl_vector_get(fconf->fringe_range, 0), fconf->filter_through->xmin); // compute the upper wavelength range by comparing // the filter throughput with the range important // for fringing; the latter is given in AA!! lambda_max = MIN(gsl_vector_get(fconf->fringe_range, 1), fconf->filter_through->xmax); // find the number of steps to cover the wavelength range nsteps = (int)ceil((lambda_max-lambda_min)/(fconf->fringe_step)) + 1; // allocate the space for the vectors lambda_values = gsl_vector_alloc(nsteps); through_values = gsl_vector_alloc(nsteps); // fill the vectors with the wavelength steps and the // filter throughput at those wavelengths. lambda_act = lambda_min; for (index=0; index < nsteps-1; index+=1) { gsl_vector_set(lambda_values, index, lambda_act); through_act = eval_interp(fconf->filter_through, lambda_act); through_tot += through_act; gsl_vector_set(through_values, index, through_act); lambda_act += fconf->fringe_step; } // add also the values at lambda_amax gsl_vector_set(lambda_values, nsteps-1, lambda_max); through_act = eval_interp(fconf->filter_through, lambda_max); through_tot += through_act; gsl_vector_set(through_values, nsteps-1, through_act); for (index=0; index < (int)through_values->size; index++) { // normalize the filter throughput values gsl_vector_set(through_values, index, gsl_vector_get(through_values, index)/through_tot); // convert the wavelength from AA to micron gsl_vector_set(lambda_values, index, gsl_vector_get(lambda_values, index)*1.0e-04); } #ifdef DEBUGFCONF through_tot = 0.0; for (index=0; index < through_values->size; index++) { fprintf(stderr, "Wavelength: %f, Throughput: %f\n", gsl_vector_get(lambda_values, index), gsl_vector_get(through_values, index)); through_tot += gsl_vector_get(through_values, index); } fprintf(stderr, "Total throughput: %f\n", through_tot); #endif // build up the output array double_vector[0] = lambda_values; double_vector[1] = through_values; return double_vector; } /** * Function: redefine_filter_throughput * The function re-defines an existing interpolator using only the * existing data values in an index range given as parameters. * * Parameters: * @param lower - index with the lowest data point * @param upper - index with the highest data point * * Returns: * @return new_interp - the new interpolator */ interpolator * redefine_filter_throughput(const int lower, const int upper, fringe_conf *fconf) { int new_nvals; int index; double *new_x; double *new_y; interpolator *new_interp; // allocate space for the return structure; // complain if this fails new_interp = (interpolator *)malloc (sizeof (interpolator)); if (new_interp == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Could not allocate memory for interpolator"); // compute the new length of the data arrays new_nvals = upper-lower+1; // allocate space for the new data arrays new_x = (double *)malloc(new_nvals*sizeof(double)); new_y = (double *)malloc(new_nvals*sizeof(double)); // transfer the data for (index=lower; index < upper+1; index++) { new_x[index-lower] = fconf->filter_through->xvals[index]; new_y[index-lower] = fconf->filter_through->yvals[index]; } // free the old structure free_interp(fconf->filter_through); // build up the interpolator structure new_interp->xmin = new_x[0]; new_interp->xmax = new_x[new_nvals-1]; new_interp->nvals = new_nvals; new_interp->xvals = new_x; new_interp->yvals = new_y; new_interp->acc = gsl_interp_accel_alloc(); new_interp->interp = gsl_interp_alloc(FILTER_INTERP_TYPE, new_interp->nvals); // initialize the cubic spline gsl_interp_init(new_interp->interp, new_interp->xvals, new_interp->yvals, new_interp->nvals); // return the new structure return new_interp; } /** * Function: eval_linear_interp * The function computes and returns the interpolated value * at a given position for a linear interpolator. * * Parameters: * @param lin_int - the linear interpolator * @param xval - the position to evaluate the linear interpolator * * Returns: * @return (value) - the interpolated data value */ double eval_linear_interp(linear_interp *lin_int, const double xval) { double factor=0.0; // check whether the x-value is within // the range spanned by the data; // complain if the x-value is outside if (xval < lin_int->xmin || xval > lin_int->xmax) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "independent linear interpolation value %f " "is outside interval (%f, %f)\n", xval, lin_int->xmin, lin_int->xmax); // check whether you have to search upwards or downwards if (xval >= gsl_vector_get(lin_int->xvals, lin_int->act_index)) { // in case that you search upwards, go up // the independent values until you find the right interval lin_int->act_index += 1; while(xval > gsl_vector_get(lin_int->xvals, lin_int->act_index)) lin_int->act_index++; } else { // in case that you search downwards, go down // the independent values until you find the right interval // while(wavelength < resp->spec[nact-1].lambda_mean) while(xval < gsl_vector_get(lin_int->xvals, lin_int->act_index-1)) lin_int->act_index--; } // interpolate within the interval to calculate the // sensitivity factor = (xval - gsl_vector_get(lin_int->xvals, lin_int->act_index-1))/ (gsl_vector_get(lin_int->xvals, lin_int->act_index) - gsl_vector_get(lin_int->xvals, lin_int->act_index-1)); // compute and terutn the interpolated value return (gsl_vector_get(lin_int->yvals, lin_int->act_index-1) + factor * (gsl_vector_get(lin_int->yvals, lin_int->act_index)-gsl_vector_get(lin_int->yvals, lin_int->act_index-1))); } /** * Function: get_layer_thickness * The function determines the thickness of an individual layer * at a given pixel position. * * Parameters: * @param opt_layer - the optical layer * @param ii - the first pixel index * @param jj - the second pixel index * * Returns: * @return (value) - the thickness of the layer at the requested position */ double get_layer_thickness(const ccd_layer *opt_layer, const int ii, const int jj) { // check whether the thickness is 2D if (opt_layer->thickness2D) // return the 2D value return gsl_matrix_get(opt_layer->thickness2D, ii, jj); else // return the constant value return opt_layer->thickness; } /** * Function: get_complex_refindex * The function computes and returns the complex refraction index of * a given CCD layer at a given wavelength. * * Parameters: * @param opt_layer - the optical layer * @param lambda - the wavelength * * Returns: * @return (value) - the complex refraction index */ gsl_complex get_complex_refindex(const ccd_layer *opt_layer, const double lambda) { double re; double im; // compute the real part re = eval_interp(opt_layer->re_refraction, lambda); // comute the imaginary part im = eval_interp(opt_layer->im_refraction, lambda); // return the complex number return gsl_complex_rect(re, im); } /** * Function: compute_reflection * The function computes and returns the reflection index (in %) * for two complex refraction indices at a given wavelength. * * Parameters: * @param refract_l1 - refraction index of one layer * @param refract_l2 - refraction index of the second layer * * Returns: * @return (value) - the reflection index */ double compute_reflection(const gsl_complex refract_l1, const gsl_complex refract_l2) { gsl_complex conj_l1; gsl_complex conj_l2; gsl_complex refl_compl; // get the comlex conjugated values of the input conj_l1 = gsl_complex_conjugate(refract_l1); conj_l2 = gsl_complex_conjugate(refract_l2); // compute the complex reflection refl_compl = gsl_complex_div(gsl_complex_sub(conj_l1, conj_l2), gsl_complex_add(conj_l1, conj_l2)); // return the magnitude of the complex reflection return gsl_complex_abs2(refl_compl); } /** * Function: compute_transmission * The function computes and returns the transmission index (in %) * for two complex refraction indices at a given wavelength. * * Parameters: * @param refract_l1 - refraction index of one layer * @param refract_l2 - refraction index of the second layer * * Returns: * @return (value) - the trnasmission index */ double compute_transmission(const gsl_complex refract_l1, const gsl_complex refract_l2) { gsl_complex conj_l1; gsl_complex conj_l2; gsl_complex trans_compl; // get the comlex conjugated values of the input conj_l1 = gsl_complex_conjugate(refract_l1); conj_l2 = gsl_complex_conjugate(refract_l2); // compute the complex transmission trans_compl = gsl_complex_div(gsl_complex_sqrt(gsl_complex_mul(conj_l1, conj_l2)), gsl_complex_add(conj_l1, conj_l2)); // finish the computation of the complex transmission trans_compl = gsl_complex_mul_real (trans_compl, 2.0); // return the magnitude of the complex transmission return gsl_complex_abs2(trans_compl); } /** * Function: compute_attenuation * The function computes the attenuation/damping of a plane wave * with a given inverse wavelelength (phase number) traversing * TWO TIMES a layer of a given thickness and complex refraction * index. * * Parameters: * @param refract - the complex refraction index * @param thickness - the thickness of the layer * @param phase_number - the inverse wavelength * * Returns: * @return (value) - the attenuation */ double compute_attenuation(const gsl_complex refract, const double thickness, const double phase_number) { // check if there is something to compute if (GSL_IMAG(refract)) // compute and return the value return exp(-2.0*GSL_IMAG(refract)*thickness*phase_number); else // return the value for exp(0.0) return 1.0; } /** * Function: compute_pshift * The function computes the phase shift of a plane wave * with a given inverse wavelelength (phase number) traversing * TWO TIMES a layer of a given thickness and complex refraction * index. * * Parameters: * @param refract - the complex refraction index * @param thickness - the thickness of the layer * @param phase_number - the inverse wavelength * * Returns: * @return (value) - the complex phase shift */ gsl_complex compute_pshift(const gsl_complex refract, const double thickness, const double phase_number) { // all in one line: return gsl_complex_exp(gsl_complex_rect(0.0,2.0*GSL_REAL(refract)*thickness*phase_number)); } /** * Function: alloc_optprops_list * The function allocates space for a list of optical property * elements. the size of the list is derived from a fringe * configuration structure given in the input. * * Parameters: * @param fconf - the fringe configuration file * * Returns: * @return optprops - the list of optical properties */ optical_property * alloc_optprops_list(const fringe_conf *fconf) { optical_property *optprops; // allocate large enough memory optprops = (optical_property *)malloc(fconf->opt_layers->num_layers*sizeof(ap_pixel)); // return the pointer return optprops; } /** * Function: print_optprops_list * The function prints the content of an optical property * list onto the screen. * * Parameters: * @param optprops - the optical property list * * Returns: * @return - */ void print_optprops_list(const optical_property *optprops, const int num_entries) { int index; for (index = 0; index < num_entries; index++) { fprintf(stdout, "#%i: %f %f %f %f %f %f \n",index, optprops[index].trans_upper, optprops[index].reflect_upper, GSL_REAL(optprops[index].double_phshift), GSL_IMAG(optprops[index].double_phshift), optprops[index].trans_lower, optprops[index].reflect_lower); } } /** * Function: free_optprops_list * The function releases the space allocated in an * optical property list. * * Parameters: * @param optprops - the optical property list * * Returns: * @return - */ void free_optprops_list(optical_property *optprops) { if (optprops != NULL) { // free the structure free(optprops); // set it to NULL optprops = NULL; } } /* * Function: init_optprops_list * The function initializes an optical property list. This means * it computes and stores values for the list elements. Here * only elements are fixed, which will not change during the * whole fringe computation and remain constant for all pixels * at all wavelengths. * * Parameters: * @params fconf - the fringe configuration structure * @params lambda_mean - the mean wavelength of analyzed waveband * @params optprops - the list of optical property elements * * Returns: * @return - */ void init_optprops_list(const fringe_conf *fconf, const double lambda_mean, optical_property *optprops) { int num_layers; int index; double n1; double n2; // determine the number of layers num_layers = fconf->opt_layers->num_layers; if (num_layers > 0) { // set the transmission and reflection // vacuum -- first CCD layer // that's a bit heuristic, since // the true value using the true // refration index for vacuum would // give a different result optprops[0].trans_upper = 1.0; optprops[0].reflect_upper = 0.0; // also that one is a bit heuristic // but assuming n(vacuum)=1.0 its also true optprops[0].sign_upper = 1.0; // set the sign of the lowest layer -- substrate // this is purely heuristic and works // only for the HRC/WFC fringing models!! optprops[num_layers-1].sign_lower = -1.0; } for (index=0; index < num_layers-1; index++) { // get the real part of the refraction index // of the upper layer n1 = GSL_REAL(get_complex_refindex(fconf->opt_layers->opt_layer[index], lambda_mean)); // get the real part of the refraction index // of the lower layer n2 = GSL_REAL(get_complex_refindex(fconf->opt_layers->opt_layer[index+1], lambda_mean)); // distribute the signs // for the upper and lower layer if (n1 < n2) { optprops[index].sign_lower = 1.0; optprops[index+1].sign_upper = -1.0; } else { optprops[index].sign_lower = -1.0; optprops[index+1].sign_upper = 1.0; } } } /* * Function: fill_optprops_thickness * The function fills the thickness of the optival layers * at a given pixel into a list of optical properties. * * Parameters: * @params opt_layers - the structure for the optical layers * @params ii - the mean wavelength of analyzed waveband * @params jj - the list of optical property elements * @params optprops - the list of optical property elements * * Returns: * @return - */ void fill_optprops_thickness(const ccd_layers *opt_layers, const int ii, const int jj, optical_property *optprops) { int index; // go over all layers for (index=0; index < opt_layers->num_layers; index++) // get and store the thickness optprops[index].thickness = get_layer_thickness(opt_layers->opt_layer[index], ii, jj); } /* * Function: fill_optprops_all * This function computes and fills in all pixel AND wavelength * dependent values into a list of optical properties. The completely * filled list can then be used to determine the fringe contribution * at that wavelength according to a certain model which defines * the various light-paths. * * Parameters: * @params opt_layers - the structure for the optical layers * @params lambda - the actual wavelength * @params optprops - the list of optical property elements * * Returns: * @return - */ void fill_optprops_all(const ccd_layers *opt_layers, const double lambda, optical_property *optprops) { int index; double phase_number; gsl_complex compl_upp; gsl_complex compl_low; int num_layers; // store the number of layers num_layers = opt_layers->num_layers; // compute the phase number phase_number = 2.0*M_PI / lambda; // get the complex refractive index for the first layer compl_upp = get_complex_refindex(opt_layers->opt_layer[0],lambda); for (index=0; index < num_layers-1; index++) { // get the refractive index for the next layer compl_low = get_complex_refindex(opt_layers->opt_layer[index+1],lambda); // compute the reflection and transmission // to the lower layers optprops[index].reflect_lower = compute_reflection(compl_upp, compl_low); optprops[index].trans_lower = 1.0 - optprops[index].reflect_lower; // compute the reflection and transmission // to the upper layers optprops[index+1].reflect_upper = optprops[index].reflect_lower; optprops[index+1].trans_upper = 1.0 - optprops[index+1].reflect_upper; // compute the attenuation optprops[index].double_attenuation = compute_attenuation(compl_upp,optprops[index].thickness,phase_number); // compute the phase shift optprops[index].double_phshift = compute_pshift(compl_upp, optprops[index].thickness, phase_number); // prepare the next iteration: // the now upper layer will then be the lower compl_upp = compl_low; } // compute the attenuation for the last layer optprops[num_layers-1].double_attenuation = compute_attenuation(compl_upp,optprops[num_layers-1].thickness,phase_number); // compute the phase shift for the last layer optprops[num_layers-1].double_phshift = compute_pshift(compl_upp, optprops[num_layers-1].thickness, phase_number); // compute the transmission of the last layer // towards the substrate optprops[num_layers-1].trans_lower = eval_interp(opt_layers->substrate, lambda); // compute the reflection of the last layer // towards the substrate optprops[num_layers-1].reflect_lower = 1.0 - optprops[num_layers-1].trans_lower; } /* * Function: fill_contrib_single * The function computes the contribution to the fringe amplitude * on the basis of an appropriately filled list of optical properties. * In the properties the ingredients such as phase shifts and * attenuation and transmissions and reflections are defined. * This function just combines the ingredients using a model * which includes all single reflected beam combinations * as contributors to the fringing. * * Parameters: * @params optprops - the list of optical property elements * @params fconf - the fringe configuration structure * * Returns: * @return (value) - the fringe contribution */ double fringe_contrib_single(const optical_property *optprops, const fringe_conf *fconf) { int index=2; gsl_complex amp_tmp; gsl_complex amp_tot; // compute the initial phase at the top of the // first layer amp_tot = gsl_complex_mul_real(gsl_complex_exp(gsl_complex_rect(0.0,fconf->fringe_phase*M_PI/180.0)), 1.0); // transfer the intitial value // to the running variable amp_tmp = amp_tot; // pile up the amplitude, // also putting in the transmission amp_tmp = gsl_complex_mul(amp_tmp, gsl_complex_mul_real(optprops[0].double_phshift, 1.0*1.0*optprops[0].double_attenuation)); // compute the intermediate result // for the first layer amp_tot = gsl_complex_add(amp_tot, gsl_complex_mul_real(amp_tmp, optprops[0].sign_lower*optprops[0].reflect_lower)); // go over layer 2 to the end for (index=1; index < fconf->opt_layers->num_layers; index++) { // pile up the amplitude // to that layer amp_tmp = gsl_complex_mul(amp_tmp, gsl_complex_mul_real(optprops[index].double_phshift, optprops[index-1].trans_lower*optprops[index].trans_upper*optprops[index].double_attenuation)); // compute the intermediate result // for the that layer amp_tot = gsl_complex_add(amp_tot, gsl_complex_mul_real(amp_tmp, optprops[index].sign_lower*optprops[index].reflect_lower)); // if (index==3) // fprintf(stdout,"ccc:%f, %f\n", GSL_REAL(amp_tmp),GSL_IMAG(amp_tmp) ); } // return the final value return (GSL_REAL(amp_tot) - 1.0); }
{ "alphanum_fraction": 0.7185638471, "avg_line_length": 32.2550218341, "ext": "c", "hexsha": "29d00f8d926b2342a9925e54fb81bfb8272ace06", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/fringe_model.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/fringe_model.c", "max_line_length": 122, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/fringe_model.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10108, "size": 36932 }
#pragma once #include <bitset> #include <type_traits> #include <thrust/execution_policy.h> #include <thrust/gather.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/scatter.h> #include <cuda/define_specifiers.hpp> #include <gsl-lite/gsl-lite.hpp> #include <thrustshift/bit.h> #include <thrustshift/gather.h> #include <thrustshift/managed-vector.h> #include <thrustshift/not-a-vector.h> #include <thrustshift/scatter.h> namespace thrustshift { namespace permutation { /*! \brief Return \f$ P_b P_a^T \f$ * * \param result `result[i]` is the index of element \f$ a_i \f$ * after permutation \f$ P_b \f$ is applied to the natural order. */ template <class PermutationA, class PermutationB, class ResultPermutation, class MemoryResource> void multiply(PermutationA&& a, PermutationB&& b, ResultPermutation&& result, MemoryResource& memory_resource) { gsl_Expects(a.size() == b.size()); gsl_Expects(result.size() == a.size()); using ResultIndex = typename std::remove_reference<ResultPermutation>::type::value_type; auto [__, tmp] = make_not_a_vector_and_span<ResultIndex>(result.size(), memory_resource); auto cit_begin = thrust::make_counting_iterator(ResultIndex(0)); auto cit_end = thrust::make_counting_iterator( gsl_lite::narrow<ResultIndex>(result.size())); // Rather use `.data()` in case the iterator class is not defined // in device code thrust::scatter(thrust::device, cit_begin, cit_end, b.data(), tmp.data()); thrust::gather(thrust::device, a.data(), a.data() + a.size(), tmp.data(), result.data()); } /*! \brief Multiply successive permutations * * Assume you have \f$N\f$ permutations \f$P_{N-1},...,P_0\f$ * and \f$N\f$ linear maps \f$M_{N-1},...,M_0\f$ where each * linear map \f$M_i\f$ operates on the new order described by * \f$P_i\f$ relatively to the natural order. If every * linear map is applied to a vector \f$x\f$ in natural order * it yields to: * * \f[ * P_{N-1}^T M_{N-1} P_{N-1} P_{N-2}^T M^{N-2} ... P_0^T M_0 P_0 x * \f] * * The \f$P_i\f$ permutation matrices are given in vectorial form \f$p_i\f$ * such that \f$(P_i)_mn = 1\f$ if \f$(p_i)_m = n\f$. * * \param input_permutations Range of size N with ranges of length L each * \param merged_permutations Range of size N - 1 with ranges of length L each. * merged_permutations[i] = \f$P_{i+1} P_{i}^T\f$ */ template <class InputPermutations, class MergedPermutations, class MemoryResource> void multiply_successive(InputPermutations&& input_permutations, MergedPermutations&& multiplied_permutations, MemoryResource& memory_resource) { const auto N = input_permutations.size(); if (N == 0) { return; } gsl_Expects(N > 0); gsl_Expects(N == multiplied_permutations.size() + 1); for (size_t i = 0; i < input_permutations.size() - 1; ++i) { multiply(input_permutations[i], input_permutations[i + 1], multiplied_permutations[i], memory_resource); } } /*! \brief Bitoptimized successive pairwise permutation * * This class saves a permutation of `I = {0,...,N-1}`, which * is created by successive pairwise swaps of the sequence `I`: * * ```cpp * for (int j = 1; j < N; ++j) { * if (do_swap[j - 1]) { * swap(I[j - 1], I[j]); * } * } * ``` * * The array `do_swap[]` saves if two values are swapped and is saved in * a bit pattern within this class. * This can also be seen as a path in a binary tree with `N` levels because * the internal representation is a bit pattern, which sets the bit if the * swap is not done. `N` is limited by the amount of Bits in `BitPatternT`. * If `operator[]` is called once, no function to change the `do_swap` * array should be called by the user. The state of the class is then a * read-only mode. Moreover the array `I` can only be read successively * by the `operator[]`. Thus reading the pattern starts with the last element * `i = N - 1` and in the next call `i = i - 1` must be used as a function argument. * This is an highly unsafe class design, which is chosen to avoid the * usage of additional registers. E.g. the safety of the class can be * greatly improved if one register is added, which is avoided here * due to performance reasons. * * \note When `std::bitset` is supported for device code. This should be * used to save the bit pattern * \note When compiled for device code CUDA currently supports built-in * function to count leading zeros `clz` for `int` and `long long int`, which * then must be used for `BitPatternT`. */ template <class BitPatternT> class bit_successive_permutation_t { public: CUDA_FHD bit_successive_permutation_t(int N) : bit_pattern_(BitPatternT(1) << (N - 1)) { gsl_Expects(N <= sizeof(BitPatternT) * 8); #ifndef NDEBUG N_ = N; #endif } CUDA_FHD void do_swap(int j) { gsl_Expects(j < sizeof(BitPatternT) * 8); #ifndef NDEBUG gsl_Expects(!read_only_mode_); gsl_Expects(j < N_ - 1); #endif bit_pattern_ &= ~(BitPatternT(1) << j); } CUDA_FHD void do_not_swap(int j) { gsl_Expects(j < sizeof(BitPatternT) * 8); #ifndef NDEBUG gsl_Expects(!read_only_mode_); gsl_Expects(j < N_ - 1); #endif bit_pattern_ |= (BitPatternT(1) << j); } CUDA_FHD void set(int j, bool do_swap_) { if (do_swap_) { do_swap(j); } else { do_not_swap(j); } } CUDA_FHD int operator[](int i) { gsl_Expects(i < sizeof(BitPatternT) * 8); #ifndef NDEBUG gsl_Expects(i < N_); if (!read_only_mode_) { read_only_mode_ = true; last_i_ = N_; } gsl_Expects(i == last_i_ - 1); last_i_ = i; #endif gsl_Expects(i >= 0); const bool flag = (1ll << i) & bit_pattern_; bit_pattern_ &= ~(1ll << i); if (flag) { const int lz = count_leading_zeros(bit_pattern_); return sizeof(BitPatternT) * 8 - lz; } else { return i + 1; } } private: #ifndef NDEBUG bool read_only_mode_ = false; int N_; int last_i_; #endif BitPatternT bit_pattern_; }; } // namespace permutation } // namespace thrustshift
{ "alphanum_fraction": 0.6550951848, "avg_line_length": 29.0744186047, "ext": "h", "hexsha": "924738cf1ac8422f2ae7fd582082fcd254b58779", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_path": "include/thrustshift/permutation.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_path": "include/thrustshift/permutation.h", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_path": "include/thrustshift/permutation.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "num_tokens": 1785, "size": 6251 }
/* * halo.h * * Created on: Oct 23, 2012 * Author: cgiocoli * * This class implement the non-linear power spectrum using the Halo Model */ #ifndef POWERCDMHM_H_ #define POWERCDMHM_H_ #include <math.h> #include <cosmo.h> #include <halo.h> #include <utilities.h> #ifdef ENABLE_GSL #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_math.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_rng.h> /** * \brief Class for calculating the non-linear power spectrum using ****** Halo Model. * To use this class you must enable GSL. */ class POWERCDMHM{ public: POWERCDMHM(COSMOLOGY *co, double redshift, double minHalomass, double sigma=0.25,int cmRelation=0,double slope=-0.1); double nonlinpowerCDMHM(double k); double nonlinpowerCDMHM1Halo(double k); double nonlinpowerCDMHM2Halo(double k); double nonlinKAPPApowerCDMHM(double l, double zs); double nonlinKAPPApowerCDMHM1Halo(double l, double zs); double nonlinKAPPApowerCDMHM2Halo(double l, double zs); double linKAPPApowerCDMHM(double l, double zs); double nonlinfitKAPPApowerCDMHM(double l, double zs); virtual ~POWERCDMHM (); protected: gsl_function intPk1,intPk2; double Pklin,Pk1,Pk2; double Pk20; double weight (double z1, double z2); double weight (double z0); struct weightfnc{ std::vector<double> ai; std::vector<double> wi; }; weightfnc wgf; // weight function void Initweight(double zs); private: float *xf,*wf; }; #endif #endif /* POWERCDMHM_H_ */
{ "alphanum_fraction": 0.7165913493, "avg_line_length": 22.7794117647, "ext": "h", "hexsha": "55e5c7b2e9ffbefc5b243dd837cd16fdcebdddab", "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": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "glenco/CosmoLib", "max_forks_repo_path": "include/powerCDMHM.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_issues_repo_issues_event_max_datetime": "2016-09-29T10:27:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-09-29T10:22:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "glenco/CosmoLib", "max_issues_repo_path": "include/powerCDMHM.h", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "glenco/CosmoLib", "max_stars_repo_path": "include/powerCDMHM.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 476, "size": 1549 }
#if !defined(PETIGAFTN_H) #define PETIGAFTN_H #include <petsc.h> EXTERN_C_BEGIN extern void IGA_Quadrature_1D(PetscInt,const PetscReal[],const PetscReal[],const PetscReal*, PetscReal[],PetscReal[],PetscReal[]); extern void IGA_Quadrature_2D(PetscInt,const PetscReal[],const PetscReal[],const PetscReal*, PetscInt,const PetscReal[],const PetscReal[],const PetscReal*, PetscReal[],PetscReal[],PetscReal[]); extern void IGA_Quadrature_3D(PetscInt,const PetscReal[],const PetscReal[],const PetscReal*, PetscInt,const PetscReal[],const PetscReal[],const PetscReal*, PetscInt,const PetscReal[],const PetscReal[],const PetscReal*, PetscReal[],PetscReal[],PetscReal[]); EXTERN_C_END EXTERN_C_BEGIN extern void IGA_BasisFuns_1D(PetscInt, PetscInt,PetscInt,const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_BasisFuns_2D(PetscInt, PetscInt,PetscInt,const PetscReal[], PetscInt,PetscInt,const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_BasisFuns_3D(PetscInt, PetscInt,PetscInt,const PetscReal[], PetscInt,PetscInt,const PetscReal[], PetscInt,PetscInt,const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); EXTERN_C_END EXTERN_C_BEGIN extern void IGA_Rationalize_1D(PetscInt,PetscInt,PetscInt,const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_Rationalize_2D(PetscInt,PetscInt,PetscInt,const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_Rationalize_3D(PetscInt,PetscInt,PetscInt,const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); EXTERN_C_END EXTERN_C_BEGIN extern void IGA_GeometryMap_1D(PetscInt,PetscInt,PetscInt,const PetscReal[], const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_GeometryMap_2D(PetscInt,PetscInt,PetscInt,const PetscReal[], const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_GeometryMap_3D(PetscInt,PetscInt,PetscInt,const PetscReal[], const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_GeometryMap (PetscInt,PetscInt,PetscInt,PetscInt,PetscInt,const PetscReal[], const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); EXTERN_C_END EXTERN_C_BEGIN extern void IGA_InverseMap_1D(PetscInt,PetscInt, const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_InverseMap_2D(PetscInt,PetscInt, const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_InverseMap_3D(PetscInt,PetscInt, const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[],PetscReal[]); EXTERN_C_END EXTERN_C_BEGIN extern void IGA_ShapeFuns_1D(PetscInt,PetscInt,PetscInt, const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_ShapeFuns_2D(PetscInt,PetscInt,PetscInt, const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[]); extern void IGA_ShapeFuns_3D(PetscInt,PetscInt,PetscInt, const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], const PetscReal[],const PetscReal[],const PetscReal[],const PetscReal[], PetscReal[],PetscReal[],PetscReal[],PetscReal[]); EXTERN_C_END #endif/*PETIGAFTN_H*/
{ "alphanum_fraction": 0.6073328267, "avg_line_length": 58.4888888889, "ext": "h", "hexsha": "be2fd90719f7f3adf99cbbe958f4be74b84c3827", "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/petigaftn.h", "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/petigaftn.h", "max_line_length": 121, "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/petigaftn.h", "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": 1230, "size": 5264 }
/** * 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> #if SCRAPS_APPLE #include <scraps/apple/HMAC.h> namespace scraps { using HMACSHA256 = apple::HMAC<apple::HMACAlgorithmType::SHA256>; } #else #include <scraps/sodium/HMACSHA256.h> namespace scraps { using HMACSHA256 = sodium::HMACSHA256; } #endif #include <gsl.h> namespace scraps { template <typename BaseByteType> struct HMACSHA256ByteTag {}; template <typename BaseByteType> using HMACSHA256Byte = StrongByte<HMACSHA256ByteTag<BaseByteType>>; template <typename KeyByteType, std::ptrdiff_t KeySize, typename ByteT, std::ptrdiff_t DataSize> std::array<HMACSHA256Byte<std::remove_const_t<ByteT>>, HMACSHA256::kResultSize> GetHMACSHA256(gsl::span<KeyByteType, KeySize> key, gsl::span<ByteT, DataSize> data) { std::array<HMACSHA256Byte<std::remove_const_t<ByteT>>, HMACSHA256::kResultSize> ret; HMACSHA256 hmac(key.data(), key.size()); hmac.update(data.data(), data.size()); hmac.finish(ret.data()); return ret; } } // namespace scraps
{ "alphanum_fraction": 0.7451713396, "avg_line_length": 31.4705882353, "ext": "h", "hexsha": "58b85bbe8678435e1a5a094b52fb65dafc6336f3", "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/HMACSHA256.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/HMACSHA256.h", "max_line_length": 96, "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/HMACSHA256.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 412, "size": 1605 }
/** * author: Jochen K"upper * created: Jan 2002 * file: pygsl/src/statistics/longmodule.c * $Id: intmodule.c,v 1.6 2004/03/24 08:40:45 schnizer Exp $ * * *" */ #include <Python.h> #include <pygsl/error_helpers.h> #include <pygsl/block_helpers.h> #include <gsl/gsl_statistics.h> /* include real functions for different data-types */ #define STATMOD_APPEND_PY_TYPE(X) X ## Int #define STATMOD_APPEND_PYC_TYPE(X) X ## INT #define STATMOD_FUNC_EXT(X, Y) X ## _int ## Y #define STATMOD_PY_AS_C PyInt_AsLong #define STATMOD_C_TYPE int #define PyGSL_STATISTICS_IMPORT_API #include "functions.c" /* initialization */ PyGSL_STATISTICS_INIT(int, "int") /* * Local Variables: * mode: c * c-file-style: "Stroustrup" * End: */
{ "alphanum_fraction": 0.7086720867, "avg_line_length": 18.45, "ext": "c", "hexsha": "fbc35429f21fb2822ca576bdb581fad6610b037d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/intmodule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/intmodule.c", "max_line_length": 60, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/intmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 218, "size": 738 }
#ifndef VECTORBOOST #define VECTORBOOST #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/qvm/mat_operations.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/io.hpp> #include <lapacke.h> #include <random> #include <iostream> class matrixBoost{ private: boost::numeric::ublas::matrix<double> value; boost::numeric::ublas::range r1; boost::numeric::ublas::range r2; boost::numeric::ublas::matrix<double>valBack; bool subMatrixCopy = false; //http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion bool InvertMatrix(const boost::numeric::ublas::matrix<double>& input, boost::numeric::ublas::matrix<double>& inverse) { using namespace boost::numeric::ublas; typedef permutation_matrix<std::size_t> pmatrix; // create a working copy of the input matrix<double> A(input); // create a permutation matrix for the LU-factorization pmatrix pm(A.size1()); // perform LU-factorization int res = lu_factorize(A,pm); if( res != 0 ) return false; // create identity matrix of "inverse" inverse.assign(boost::numeric::ublas::identity_matrix<double>(A.size1())); // backsubstitute to get the inverse lu_substitute(A, pm, inverse); return true; } void setSystemValue(boost::numeric::ublas::matrix<double> v){ value = v; } public: matrixBoost(){} matrixBoost(int rowCount, int colCount){ value = boost::numeric::ublas::zero_matrix<double>(rowCount,colCount); } matrixBoost(boost::numeric::ublas::matrix<double> value):value(value){} static matrixBoost Identity(int dimension,int dimension2){ return matrixBoost(boost::numeric::ublas::identity_matrix<double>(dimension,dimension2)); } matrixBoost transpose(){ matrixBoost t(boost::numeric::ublas::trans(value)); return t; } matrixBoost inverse(){ boost::numeric::ublas::matrix<double> inverse(value.size1(),value.size2()); InvertMatrix(value,inverse); matrixBoost t(inverse); return t; } boost::numeric::ublas::matrix<double> getSystemValue() const{ return value; } matrixBoost & block(int i1, int i2, int l1, int l2){ if(subMatrixCopy){ std::swap(valBack,value); } subMatrixCopy = true; r1 = boost::numeric::ublas::range(i1,i1+l1); r2 = boost::numeric::ublas::range(i2,i2+l2); valBack = boost::numeric::ublas::project(value,r1,r2); std::swap(valBack,value); return *this; } matrixBoost &operator=( const matrixBoost other){ if(subMatrixCopy){ subMatrixCopy = false; boost::numeric::ublas::project(valBack,r1,r2) = other.getSystemValue(); std::swap(valBack,value); }else{ value = other.getSystemValue(); } return *this;//better be no chaining of equal signs } static void lowerTriangulate(matrixBoost & val){ boost::numeric::ublas::matrix<double> in= val.getSystemValue(); int rows = in.size1(); int cols = in.size2(); for(int i = 0; i < rows; i++){ int length = cols - i; boost::numeric::ublas::vector<double> v = (row(in,i)); v = boost::numeric::ublas::subrange(v,i,cols); double mew = boost::numeric::ublas::norm_2(v); if(mew!=0){ double beta = v(0) + (-2*(v(0) < 0)+1)*mew; v = v/beta; } v(0) = 1; boost::numeric::ublas::range t1(i,rows); boost::numeric::ublas::range t2(i,cols); boost::numeric::ublas::vector<double> w = -2.0/ (boost::numeric::ublas::norm_2(v)*boost::numeric::ublas::norm_2(v))* (prod(project(in,t1,t2),v)); boost::numeric::ublas::matrix<double> vM(v.size(),1); for(int i = 0; i < v.size(); i++){ vM(i,0) = v(i); } boost::numeric::ublas::matrix<double> wM(w.size(),1); for(int i = 0; i < w.size(); i++){ wM(i,0) = w(i); } project(in,t1,t2) = project(in,t1,t2) + prod(wM,boost::numeric::ublas::trans(vM)); } val.setSystemValue(in); } }; class vectorBoost{ private: boost::numeric::ublas::vector<double> value; public: vectorBoost(){ } vectorBoost(boost::numeric::ublas::vector<double> value):value(value){} boost::numeric::ublas::vector<double> getSystemValue() const{ return value; } static vectorBoost randomVector(int dimension,uint32_t seed){ std::mt19937 generator(seed); std::normal_distribution<double> distribution(0.0,1.0); boost::numeric::ublas::vector<double> tmp(dimension); for(int i = 0; i < dimension; i++){ tmp(i) = distribution(generator); } return vectorBoost(tmp); } static vectorBoost solve(matrixBoost A, vectorBoost b){ boost::numeric::ublas::matrix<double> Alocal = A.getSystemValue(); boost::numeric::ublas::vector<double> blocal = b.getSystemValue(); boost::numeric::ublas::permutation_matrix<size_t> pm(Alocal.size1()); boost::numeric::ublas::lu_factorize(Alocal,pm); boost::numeric::ublas::lu_substitute(Alocal, pm, blocal); return vectorBoost(blocal); } }; vectorBoost operator-(const vectorBoost &lhs,const vectorBoost &rhs){ vectorBoost res(lhs.getSystemValue() - rhs.getSystemValue()); return res; }; vectorBoost operator+(const vectorBoost &lhs,const vectorBoost &rhs){ vectorBoost res(lhs.getSystemValue() + rhs.getSystemValue()); return res; }; std::ostream& operator<<(std::ostream& stream, const vectorBoost & vec) { boost::numeric::ublas::vector<double> v = vec.getSystemValue(); for(int i = 0; i < v.size()-1; i++){ stream<<double(v(i))<<'\n'; } stream<<v(v.size()-1); return stream; } matrixBoost operator*(const matrixBoost &lhs, const matrixBoost &rhs){ matrixBoost res(boost::numeric::ublas::prod(lhs.getSystemValue(),rhs.getSystemValue())); return res; } matrixBoost operator+(const matrixBoost &lhs,const matrixBoost &rhs){ matrixBoost res(lhs.getSystemValue() + rhs.getSystemValue()); return res; }; matrixBoost operator-(const matrixBoost &lhs,const matrixBoost &rhs){ matrixBoost res(lhs.getSystemValue() - rhs.getSystemValue()); return res; }; std::ostream& operator<<(std::ostream& stream, const matrixBoost & mat) { boost::numeric::ublas::matrix<double> m = mat.getSystemValue(); for(int i = 0; i < m.size1(); i++){ for(int j = 0; j < m.size2(); j++){ stream<<m(i,j)<<" "; }stream<<'\n'; } return stream; } vectorBoost operator*(const matrixBoost &lhs, const vectorBoost &rhs){ vectorBoost res(boost::numeric::ublas::prod(lhs.getSystemValue(),rhs.getSystemValue())); return res; } vectorBoost operator*(const vectorBoost &lhs, const matrixBoost &rhs){ vectorBoost res(boost::numeric::ublas::prod(lhs.getSystemValue(),rhs.getSystemValue())); return res; } #endif
{ "alphanum_fraction": 0.6325200998, "avg_line_length": 31.0948275862, "ext": "h", "hexsha": "a1d9bd984fdb80d3177f71cbb3a4a60bbcf574c7", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-12-18T15:22:08.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-03T09:05:46.000Z", "max_forks_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mannyray/KalmanFilter", "max_forks_repo_path": "c++_implementation/include/mathWrapper/boost.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_issues_repo_issues_event_max_datetime": "2020-03-27T02:03:37.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-27T00:49:58.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mannyray/KalmanFilter", "max_issues_repo_path": "c++_implementation/include/mathWrapper/boost.h", "max_line_length": 121, "max_stars_count": 17, "max_stars_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mannyray/KalmanFilter", "max_stars_repo_path": "c++_implementation/include/mathWrapper/boost.h", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:00:09.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-12T04:47:15.000Z", "num_tokens": 1910, "size": 7214 }
/* matrix/gsl_matrix_ulong.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_ULONG_H__ #define __GSL_MATRIX_ULONG_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_ulong.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; unsigned long * data; gsl_block_ulong * block; int owner; } gsl_matrix_ulong; typedef struct { gsl_matrix_ulong matrix; } _gsl_matrix_ulong_view; typedef _gsl_matrix_ulong_view gsl_matrix_ulong_view; typedef struct { gsl_matrix_ulong matrix; } _gsl_matrix_ulong_const_view; typedef const _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view; /* Allocation */ GSL_EXPORT gsl_matrix_ulong * gsl_matrix_ulong_alloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_ulong * gsl_matrix_ulong_calloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_ulong * gsl_matrix_ulong_alloc_from_block (gsl_block_ulong * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_EXPORT gsl_matrix_ulong * gsl_matrix_ulong_alloc_from_matrix (gsl_matrix_ulong * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_EXPORT gsl_vector_ulong * gsl_vector_ulong_alloc_row_from_matrix (gsl_matrix_ulong * m, const size_t i); GSL_EXPORT gsl_vector_ulong * gsl_vector_ulong_alloc_col_from_matrix (gsl_matrix_ulong * m, const size_t j); GSL_EXPORT void gsl_matrix_ulong_free (gsl_matrix_ulong * m); /* Views */ GSL_EXPORT _gsl_matrix_ulong_view gsl_matrix_ulong_submatrix (gsl_matrix_ulong * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_ulong_view gsl_matrix_ulong_row (gsl_matrix_ulong * m, const size_t i); GSL_EXPORT _gsl_vector_ulong_view gsl_matrix_ulong_column (gsl_matrix_ulong * m, const size_t j); GSL_EXPORT _gsl_vector_ulong_view gsl_matrix_ulong_diagonal (gsl_matrix_ulong * m); GSL_EXPORT _gsl_vector_ulong_view gsl_matrix_ulong_subdiagonal (gsl_matrix_ulong * m, const size_t k); GSL_EXPORT _gsl_vector_ulong_view gsl_matrix_ulong_superdiagonal (gsl_matrix_ulong * m, const size_t k); GSL_EXPORT _gsl_matrix_ulong_view gsl_matrix_ulong_view_array (unsigned long * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ulong_view gsl_matrix_ulong_view_array_with_tda (unsigned long * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_ulong_view gsl_matrix_ulong_view_vector (gsl_vector_ulong * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ulong_view gsl_matrix_ulong_view_vector_with_tda (gsl_vector_ulong * v, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_submatrix (const gsl_matrix_ulong * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_ulong_const_view gsl_matrix_ulong_const_row (const gsl_matrix_ulong * m, const size_t i); GSL_EXPORT _gsl_vector_ulong_const_view gsl_matrix_ulong_const_column (const gsl_matrix_ulong * m, const size_t j); GSL_EXPORT _gsl_vector_ulong_const_view gsl_matrix_ulong_const_diagonal (const gsl_matrix_ulong * m); GSL_EXPORT _gsl_vector_ulong_const_view gsl_matrix_ulong_const_subdiagonal (const gsl_matrix_ulong * m, const size_t k); GSL_EXPORT _gsl_vector_ulong_const_view gsl_matrix_ulong_const_superdiagonal (const gsl_matrix_ulong * m, const size_t k); GSL_EXPORT _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view_array (const unsigned long * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view_array_with_tda (const unsigned long * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view_vector (const gsl_vector_ulong * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ulong_const_view gsl_matrix_ulong_const_view_vector_with_tda (const gsl_vector_ulong * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_EXPORT unsigned long gsl_matrix_ulong_get(const gsl_matrix_ulong * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x); GSL_EXPORT unsigned long * gsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j); GSL_EXPORT const unsigned long * gsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_ulong_set_zero (gsl_matrix_ulong * m); GSL_EXPORT void gsl_matrix_ulong_set_identity (gsl_matrix_ulong * m); GSL_EXPORT void gsl_matrix_ulong_set_all (gsl_matrix_ulong * m, unsigned long x); GSL_EXPORT int gsl_matrix_ulong_fread (FILE * stream, gsl_matrix_ulong * m) ; GSL_EXPORT int gsl_matrix_ulong_fwrite (FILE * stream, const gsl_matrix_ulong * m) ; GSL_EXPORT int gsl_matrix_ulong_fscanf (FILE * stream, gsl_matrix_ulong * m); GSL_EXPORT int gsl_matrix_ulong_fprintf (FILE * stream, const gsl_matrix_ulong * m, const char * format); GSL_EXPORT int gsl_matrix_ulong_memcpy(gsl_matrix_ulong * dest, const gsl_matrix_ulong * src); GSL_EXPORT int gsl_matrix_ulong_swap(gsl_matrix_ulong * m1, gsl_matrix_ulong * m2); GSL_EXPORT int gsl_matrix_ulong_swap_rows(gsl_matrix_ulong * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_ulong_swap_columns(gsl_matrix_ulong * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_ulong_swap_rowcol(gsl_matrix_ulong * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_ulong_transpose (gsl_matrix_ulong * m); GSL_EXPORT int gsl_matrix_ulong_transpose_memcpy (gsl_matrix_ulong * dest, const gsl_matrix_ulong * src); GSL_EXPORT unsigned long gsl_matrix_ulong_max (const gsl_matrix_ulong * m); GSL_EXPORT unsigned long gsl_matrix_ulong_min (const gsl_matrix_ulong * m); GSL_EXPORT void gsl_matrix_ulong_minmax (const gsl_matrix_ulong * m, unsigned long * min_out, unsigned long * max_out); GSL_EXPORT void gsl_matrix_ulong_max_index (const gsl_matrix_ulong * m, size_t * imax, size_t *jmax); GSL_EXPORT void gsl_matrix_ulong_min_index (const gsl_matrix_ulong * m, size_t * imin, size_t *jmin); GSL_EXPORT void gsl_matrix_ulong_minmax_index (const gsl_matrix_ulong * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_EXPORT int gsl_matrix_ulong_isnull (const gsl_matrix_ulong * m); GSL_EXPORT int gsl_matrix_ulong_add (gsl_matrix_ulong * a, const gsl_matrix_ulong * b); GSL_EXPORT int gsl_matrix_ulong_sub (gsl_matrix_ulong * a, const gsl_matrix_ulong * b); GSL_EXPORT int gsl_matrix_ulong_mul_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b); GSL_EXPORT int gsl_matrix_ulong_div_elements (gsl_matrix_ulong * a, const gsl_matrix_ulong * b); GSL_EXPORT int gsl_matrix_ulong_scale (gsl_matrix_ulong * a, const double x); GSL_EXPORT int gsl_matrix_ulong_add_constant (gsl_matrix_ulong * a, const double x); GSL_EXPORT int gsl_matrix_ulong_add_diagonal (gsl_matrix_ulong * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_EXPORT int gsl_matrix_ulong_get_row(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t i); GSL_EXPORT int gsl_matrix_ulong_get_col(gsl_vector_ulong * v, const gsl_matrix_ulong * m, const size_t j); GSL_EXPORT int gsl_matrix_ulong_set_row(gsl_matrix_ulong * m, const size_t i, const gsl_vector_ulong * v); GSL_EXPORT int gsl_matrix_ulong_set_col(gsl_matrix_ulong * m, const size_t j, const gsl_vector_ulong * v); /* inline functions if you are using GCC */ #ifdef HAVE_INLINE extern inline unsigned long gsl_matrix_ulong_get(const gsl_matrix_ulong * 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_ulong_set(gsl_matrix_ulong * m, const size_t i, const size_t j, const unsigned long x) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif m->data[i * m->tda + j] = x ; } extern inline unsigned long * gsl_matrix_ulong_ptr(gsl_matrix_ulong * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (unsigned long *) (m->data + (i * m->tda + j)) ; } extern inline const unsigned long * gsl_matrix_ulong_const_ptr(const gsl_matrix_ulong * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const unsigned long *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_ULONG_H__ */
{ "alphanum_fraction": 0.682328907, "avg_line_length": 34.250728863, "ext": "h", "hexsha": "00d51818981ce88ea3b2b3b7e2150358a7c22770", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ulong.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ulong.h", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ulong.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2810, "size": 11748 }
/** @file */ #ifndef __CCL_CORE_H_INCLUDED__ #define __CCL_CORE_H_INCLUDED__ #include <stdbool.h> #include <stdio.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include <gsl/gsl_const_mksa.h> #include "ccl_utils.h" #include "ccl_f1d.h" #include "ccl_f2d.h" CCL_BEGIN_DECLS /** * Struct to hold physical constants. */ typedef struct ccl_physical_constants { /** * Lightspeed / H0 in units of Mpc/h (from CODATA 2014) */ double CLIGHT_HMPC; /** * Newton's gravitational constant in units of m^3/Kg/s^2 */ double GNEWT; /** * Solar mass in units of kg (from GSL) */ double SOLAR_MASS; /** * Mpc to meters (from PDG 2013) */ double MPC_TO_METER; /** * pc to meters (from PDG 2013) */ double PC_TO_METER; /** * Rho critical in units of M_sun/h / (Mpc/h)^3 */ double RHO_CRITICAL; /** * Boltzmann constant in units of J/K */ double KBOLTZ; /** * Stefan-Boltzmann constant in units of kg/s^3 / K^4 */ double STBOLTZ; /** * Planck's constant in units kg m^2 / s */ double HPLANCK; /** * The speed of light in m/s */ double CLIGHT; /** * Electron volt to Joules convestion */ double EV_IN_J; /** * Temperature of the CMB in K */ double T_CMB; /** * T_ncdm, as taken from CLASS, explanatory.ini */ double TNCDM; /** * neutrino mass splitting differences * See Lesgourgues and Pastor, 2012 for these values. * Adv. High Energy Phys. 2012 (2012) 608515, * arXiv:1212.6154, page 13 */ double DELTAM12_sq; double DELTAM13_sq_pos; double DELTAM13_sq_neg; } ccl_physical_constants; extern ccl_physical_constants ccl_constants; /** * Struct that contains all the parameters needed to create certain splines. * This includes splines for the scale factor, masses, and power spectra. */ typedef struct ccl_spline_params { // scale factor splines int A_SPLINE_NA; double A_SPLINE_MIN; double A_SPLINE_MINLOG_PK; double A_SPLINE_MIN_PK; double A_SPLINE_MINLOG_SM; double A_SPLINE_MIN_SM; double A_SPLINE_MAX; double A_SPLINE_MINLOG; int A_SPLINE_NLOG; //Mass splines double LOGM_SPLINE_DELTA; int LOGM_SPLINE_NM; double LOGM_SPLINE_MIN; double LOGM_SPLINE_MAX; //PS a and k spline int A_SPLINE_NA_SM; int A_SPLINE_NLOG_SM; int A_SPLINE_NA_PK; int A_SPLINE_NLOG_PK; //k-splines and integrals double K_MAX_SPLINE; double K_MAX; double K_MIN; double DLOGK_INTEGRATION; int N_K; int N_K_3DCOR; //Correlation function parameters double ELL_MIN_CORR; double ELL_MAX_CORR; int N_ELL_CORR; // interpolation types const gsl_interp_type* A_SPLINE_TYPE; const gsl_interp_type* K_SPLINE_TYPE; const gsl_interp_type* M_SPLINE_TYPE; const gsl_interp_type* D_SPLINE_TYPE; const gsl_interp2d_type* PNL_SPLINE_TYPE; const gsl_interp2d_type* PLIN_SPLINE_TYPE; const gsl_interp_type* CORR_SPLINE_TYPE; } ccl_spline_params; extern const ccl_spline_params default_spline_params; /** * Struct that contains parameters that control the accuracy of various GSL * routines. */ typedef struct ccl_gsl_params { // General parameters size_t N_ITERATION; // Integration int INTEGRATION_GAUSS_KRONROD_POINTS; double INTEGRATION_EPSREL; // Limber integration int INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS; double INTEGRATION_LIMBER_EPSREL; // Distance integrals double INTEGRATION_DISTANCE_EPSREL; // sigma_R integral double INTEGRATION_SIGMAR_EPSREL; // k_NL integral double INTEGRATION_KNL_EPSREL; // Root finding double ROOT_EPSREL; int ROOT_N_ITERATION; // ODE double ODE_GROWTH_EPSREL; // growth double EPS_SCALEFAC_GROWTH; // halo model double HM_MMIN; double HM_MMAX; double HM_EPSABS; double HM_EPSREL; size_t HM_LIMIT; int HM_INT_METHOD; } ccl_gsl_params; extern const ccl_gsl_params default_gsl_params; /** * Struct containing the parameters defining a cosmology */ typedef struct ccl_parameters { // Densities: CDM, baryons, total matter, neutrinos, curvature double Omega_c; /**< Density of CDM relative to the critical density*/ double Omega_b; /**< Density of baryons relative to the critical density*/ double Omega_m; /**< Density of all matter relative to the critical density*/ double Omega_k; /**< Density of curvature relative to the critical density*/ double sqrtk; /**< Square root of the magnitude of curvature, k */ //TODO check int k_sign; /**<Sign of the curvature k */ // Dark Energy double w0; double wa; // Hubble parameters double H0; double h; // Neutrino properties double Neff; // Effective number of relativistic neutrino species in the early universe. int N_nu_mass; // Number of species of neutrinos which are nonrelativistic today double N_nu_rel; // Number of species of neutrinos which are relativistic today double *m_nu; // total mass of massive neutrinos (This is a pointer so that it can hold multiple masses.) double sum_nu_masses; // sum of the neutrino masses. double Omega_nu_mass; // Omega_nu for MASSIVE neutrinos double Omega_nu_rel; // Omega_nu for MASSLESS neutrinos // Primordial power spectra double A_s; double n_s; // Radiation parameters double Omega_g; double T_CMB; // BCM baryonic model parameters double bcm_log10Mc; double bcm_etab; double bcm_ks; // mu / Sigma quasistatica parameterisation of modified gravity params double mu_0; double sigma_0; // Derived parameters double sigma8; double Omega_l; double z_star; //Modified growth rate bool has_mgrowth; int nz_mgrowth; double *z_mgrowth; double *df_mgrowth; } ccl_parameters; /** * Struct containing references to gsl splines for distance and acceleration calculations */ typedef struct ccl_data { // These are all functions of the scale factor a. // Distances are defined in Mpc double growth0; gsl_spline * chi; gsl_spline * growth; gsl_spline * fgrowth; gsl_spline * E; gsl_spline * achi; // Function of Halo mass M gsl_spline2d * logsigma; // real-space splines for RSD ccl_f1d_t* rsd_splines[3]; double rsd_splines_scalefactor; } ccl_data; /** * Sturct containing references to instances of the above structs, and boolean flags of precomputed values. */ typedef struct ccl_cosmology { ccl_parameters params; ccl_configuration config; ccl_data data; ccl_spline_params spline_params; ccl_gsl_params gsl_params; bool computed_distances; bool computed_growth; bool computed_sigma; int status; //this is optional - less tedious than tracking all numerical values for status in error handler function char status_message[500]; // other flags? } ccl_cosmology; // Initialization and life cycle of objects ccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config); /* Internal function to set the status message safely. */ void ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * status_message, ...); // User-facing creation routines /** * Create a cosmology * @param Omega_c Omega_c * @param Omega_b Omega_b * @param Omega_k Omega_k * @param Neff Number of relativistic neutrino species in the early universe * @param mnu neutrino mass, either sum or list of length 3 * @param mnu_type determines neutrino mass convention (ccl_mnu_list, ccl_mnu_sum, ccl_mnu_sum_inverted, ccl_mnu_sum_equal) * @param w0 Dark energy EoS parameter * @param wa Dark energy EoS parameter * @param h Hubble constant in units of 100 km/s/Mpc * @param norm_pk the normalization of the power spectrum, either A_s or sigma8 * @param n_s the power-law index of the power spectrum * @param bcm_log10Mc log10 cluster mass, one of the parameters of the BCM model * @param bcm_etab ejection radius parameter, one of the parameters of the BCM model * @param bcm_ks wavenumber for the stellar profile, one of the parameters of the BCM model * @param nz_mgrowth the number of redshifts where the modified growth is provided * @param zarr_mgrowth the array of redshifts where the modified growth is provided * @param dfarr_mgrowth the modified growth function vector provided * @param status Status flag. 0 if there are no errors, nonzero otherwise. * For specific cases see documentation for ccl_error.c * @return void */ ccl_parameters ccl_parameters_create(double Omega_c, double Omega_b, double Omega_k, double Neff, double* mnu, int n_mnu, double w0, double wa, double h, double norm_pk, double n_s, double bcm_log10Mc, double bcm_etab, double bcm_ks, double mu_0, double sigma_0, int nz_mgrowth, double *zarr_mgrowth, double *dfarr_mgrowth, int *status); /** * Free a parameters struct * @param params ccl_parameters struct * @return void */ void ccl_parameters_free(ccl_parameters * params); /** * Write a cosmology parameters object to a file in yaml format, . * @param params Cosmological parameters * @param filename Name of file to create and write * @param status Status flag. 0 if there are no errors, nonzero otherwise. * @return void */ void ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int * status); /** * Read a cosmology parameters object from a file in yaml format, . * @param filename Name of existing file to read from * @param status Status flag. 0 if there are no errors, nonzero otherwise. * @return cosmo Cosmological parameters */ ccl_parameters ccl_parameters_read_yaml(const char * filename, int *status); /** * Free a cosmology struct * @param cosmo Cosmological parameters * @return void */ void ccl_cosmology_free(ccl_cosmology * cosmo); int ccl_get_pk_spline_na(ccl_cosmology *cosmo); int ccl_get_pk_spline_nk(ccl_cosmology *cosmo); void ccl_get_pk_spline_a_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status); void ccl_get_pk_spline_lk_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status); CCL_END_DECLS #endif
{ "alphanum_fraction": 0.7386488374, "avg_line_length": 26.4406332454, "ext": "h", "hexsha": "4e536aa6c74b6e01dd605f1cefd1f240a04cd9ae", "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": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "borisbolliet/CCL", "max_forks_repo_path": "include/ccl_core.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "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": "borisbolliet/CCL", "max_issues_repo_path": "include/ccl_core.h", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "borisbolliet/CCL", "max_stars_repo_path": "include/ccl_core.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2783, "size": 10021 }
#pragma once #include <gsl/gsl> #include <Metal/Metal.h> namespace Halley { class MetalVideo; class MetalBuffer { public: enum class Type { Vertex, Index, Constant }; MetalBuffer(MetalVideo& video, Type type, size_t initialSize = 0); MetalBuffer(MetalBuffer&& other) noexcept; ~MetalBuffer(); MetalBuffer(const MetalBuffer& other) = delete; MetalBuffer& operator=(const MetalBuffer& other) = delete; MetalBuffer& operator=(MetalBuffer&& other) = delete; void setData(gsl::span<const gsl::byte> data); void bindVertex(id<MTLRenderCommandEncoder> encoder, int bindPoint); void bindFragment(id<MTLRenderCommandEncoder> encoder, int bindPoint); id<MTLBuffer> getBuffer(); private: MetalVideo& video; Type type; id<MTLBuffer> buffer = nil; }; }
{ "alphanum_fraction": 0.717884131, "avg_line_length": 20.8947368421, "ext": "h", "hexsha": "7b7383327c5f962084729427b0a08bf89c8131b4", "lang": "C", "max_forks_count": 193, "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_path": "src/plugins/metal/src/metal_buffer.h", "max_issues_count": 53, "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "code-disaster/halley", "max_issues_repo_path": "src/plugins/metal/src/metal_buffer.h", "max_line_length": 72, "max_stars_count": 3262, "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_path": "src/plugins/metal/src/metal_buffer.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "num_tokens": 224, "size": 794 }
/* randist/exppow.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006 James Theiler, Brian Gough * Copyright (C) 2006 Giulio Bottazzi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The exponential power probability distribution is p(x) dx = (1/(2 a Gamma(1+1/b))) * exp(-|x/a|^b) dx for -infty < x < infty. For b = 1 it reduces to the Laplace distribution. The exponential power distribution is related to the gamma distribution by E = a * pow(G(1/b),1/b), where E is an exponential power variate and G is a gamma variate. We use this relation for b < 1. For b >=1 we use rejection methods based on the laplace and gaussian distributions which should be faster. For b>4 we revert to the gamma method. See P. R. Tadikamalla, "Random Sampling from the Exponential Power Distribution", Journal of the American Statistical Association, September 1980, Volume 75, Number 371, pages 683-686. */ double gsl_ran_exppow (const gsl_rng * r, const double a, const double b) { if (b < 1 || b > 4) { double u = gsl_rng_uniform (r); double v = gsl_ran_gamma (r, 1 / b, 1.0); double z = a * pow (v, 1 / b); if (u > 0.5) { return z; } else { return -z; } } else if (b == 1) { /* Laplace distribution */ return gsl_ran_laplace (r, a); } else if (b < 2) { /* Use laplace distribution for rejection method, from Tadikamalla */ double x, h, u; double B = pow (1 / b, 1 / b); do { x = gsl_ran_laplace (r, B); u = gsl_rng_uniform_pos (r); h = -pow (fabs (x), b) + fabs (x) / B - 1 + (1 / b); } while (log (u) > h); return a * x; } else if (b == 2) { /* Gaussian distribution */ return gsl_ran_gaussian (r, a / sqrt (2.0)); } else { /* Use gaussian for rejection method, from Tadikamalla */ double x, h, u; double B = pow (1 / b, 1 / b); do { x = gsl_ran_gaussian (r, B); u = gsl_rng_uniform_pos (r); h = -pow (fabs (x), b) + (x * x) / (2 * B * B) + (1 / b) - 0.5; } while (log (u) > h); return a * x; } } double gsl_ran_exppow_pdf (const double x, const double a, const double b) { double p; double lngamma = gsl_sf_lngamma (1 + 1 / b); p = (1 / (2 * a)) * exp (-pow (fabs (x / a), b) - lngamma); return p; }
{ "alphanum_fraction": 0.5962002413, "avg_line_length": 26.9593495935, "ext": "c", "hexsha": "c307e4c11677f7661076e1d7d6551e97cc4ba3d1", "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/randist/exppow.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/randist/exppow.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/randist/exppow.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": 1006, "size": 3316 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "Data/Data.h" #include <Eigen/Dense> #include <opencv2/core/eigen.hpp> #include <opencv2/calib3d.hpp> #include <opencv2/imgproc.hpp> #include <assert.h> #include <array> #include <gsl/gsl> #include "eigen.h" namespace mage { using Quaternion = Eigen::Quaternionf; inline Quaternion ToQuat(const cv::Matx33f& rotation) { Eigen::Matrix3f eigenMat; cv::cv2eigen(rotation, eigenMat); Quaternion eigenQuat(eigenMat); // TODO validate if this normalize is even necessary, eigen might already be doing this eigenQuat.normalize(); return eigenQuat; } template<int N> inline Eigen::Map<Eigen::Matrix<float, N, 1>> ToMap(cv::Vec<float, N>& vec) { return Eigen::Map<Eigen::Vector3f>{ vec.val }; } template<int N> inline Eigen::Map<const Eigen::Matrix<float, N, 1>> ToCMap(const cv::Vec<float, N>& vec) { return Eigen::Map<const Eigen::Matrix<float, N, 1>>{ vec.val }; } inline Eigen::Map<Eigen::Vector3f> ToMap(cv::Matx31f& vec) { return Eigen::Map<Eigen::Vector3f>{ vec.val }; } inline Eigen::Map<const Eigen::Vector3f> ToCMap(const cv::Matx31f& vec) { return Eigen::Map<const Eigen::Vector3f>{ vec.val }; } inline Eigen::Map<Eigen::Vector3f> ToMap(cv::Point3f& vec) { return Eigen::Map<Eigen::Vector3f>{ &vec.x }; } inline Eigen::Map<const Eigen::Vector3f> ToCMap(const cv::Point3f& vec) { return Eigen::Map<const Eigen::Vector3f>{ &vec.x }; } inline Eigen::Map<Eigen::Vector2f> ToMap(cv::Point2f& vec) { return Eigen::Map<Eigen::Vector2f>{ &vec.x }; } inline Eigen::Map<const Eigen::Vector2f> ToCMap(const cv::Point2f& vec) { return Eigen::Map<const Eigen::Vector2f>{ &vec.x }; } template<size_t N> inline cv::Vec<float, N> ToVec(gsl::span<const float, N> values) { return cv::Vec<float, N>(values.data()); } inline Quaternion QuatFromTwoVectors(const cv::Vec3f& from, const cv::Vec3f& to) { Quaternion quat; quat.setFromTwoVectors(Eigen::Vector3f{ from(0), from(1), from(2) }, Eigen::Vector3f{ to(0), to(1), to(2) }); return quat; } inline cv::Matx33f ToMat(const Quaternion& quat) { cv::Matx33f mat; cv::eigen2cv(quat.toRotationMatrix(), mat); return mat; } inline cv::Matx33f ToMat(float pitchRads, float rollRads, float yawRads) { // Formula for (Pitch * Roll * Yaw) from http://www.songho.ca/opengl/gl_anglestoaxes.html float a = pitchRads; float b = yawRads; float c = rollRads; float sa = sinf(a); float sb = sinf(b); float sc = sinf(c); float ca = cosf(a); float cb = cosf(b); float cc = cosf(c); return cv::Matx33f{ cc * cb, -sc, cc * sb, ca * sc * cb + sa * sb, ca * cc, ca * sc * sb - sa * cb, sa * sc * cb - ca * sb, sa * cc, sa * sc * sb + ca * cb }; } inline cv::Matx44f To4x4(const cv::Matx34f& mat) { return{ mat(0, 0), mat(0, 1), mat(0, 2), mat(0, 3), mat(1, 0), mat(1, 1), mat(1, 2), mat(1, 3), mat(2, 0), mat(2, 1), mat(2, 2), mat(2, 3), 0, 0, 0, 1 }; } inline cv::Matx34f To3x4(const cv::Matx44f& mat) { return{ mat(0, 0), mat(0, 1), mat(0, 2), mat(0, 3), mat(1, 0), mat(1, 1), mat(1, 2), mat(1, 3), mat(2, 0), mat(2, 1), mat(2, 2), mat(2, 3) }; } inline cv::Matx44f To4x4(const cv::Matx33f& rot, const cv::Vec3f& trans) { return{ rot(0, 0), rot(0, 1), rot(0, 2), trans(0), rot(1, 0), rot(1, 1), rot(1, 2), trans(1), rot(2, 0), rot(2, 1), rot(2, 2), trans(2), 0, 0, 0, 1 }; } inline cv::Matx44f FromQuatAndTrans(const Quaternion& quat, const cv::Vec3f& trans) { return To4x4(ToMat(quat), trans); } inline cv::Matx33f Rotation(const cv::Matx44f& mat) { return{ mat(0, 0), mat(0, 1), mat(0, 2), mat(1, 0), mat(1, 1), mat(1, 2), mat(2, 0), mat(2, 1), mat(2, 2) }; } inline cv::Matx33f Rotation(const cv::Matx34f& mat) { return{ mat(0, 0), mat(0, 1), mat(0, 2), mat(1, 0), mat(1, 1), mat(1, 2), mat(2, 0), mat(2, 1), mat(2, 2) }; } inline cv::Vec3f Translation(const cv::Matx44f& mat) { return{ mat(0, 3), mat(1, 3), mat(2, 3) }; } inline cv::Vec3f Translation(const cv::Matx34f& mat) { return{ mat(0, 3), mat(1, 3), mat(2, 3) }; } //Swap the returned parameters to suppress x64 compile warning c4324 //c:\program files(x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.11.25503\include\utility(271) : warning C4324 : 'std::pair<mage::Quaternion,cv::Vec3f>' : structure was padded due to alignment specifier inline std::pair<cv::Vec3f, Quaternion> Decompose(const cv::Matx44f& matrix) { return std::make_pair(Translation(matrix), ToQuat(matrix.get_minor<3, 3>(0, 0))); } template<int ROWS, int COLS> inline bool MatxEqual(const cv::Matx<float, ROWS, COLS>& mat0, const cv::Matx<float, ROWS, COLS>& mat1) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { if (mat0(i,j) != mat1(i,j)) return false; } } return true; } inline bool MatEqual(const cv::Mat& mat0, const cv::Mat& mat1) { if (mat0.size != mat1.size) return false; for (int i = 0; i < mat0.rows; i++) { for (int j = 0; j < mat0.cols; j++) { if (mat0.at<float>(i, j) != mat1.at<float>(i, j)) return false; } } return true; } template<int ROWS, int COLS> inline cv::Matx44f Invert(const cv::Matx<float, ROWS, COLS>& transform) { static_assert((ROWS == 3 || ROWS == 4) && COLS == 4, "Invert only supports 3x4 or 4x4 matrices"); //invert rotation by transpose on copy of upper 3x3 for inverse rotation cv::Matx44f invRotation{ transform(0, 0), transform(1, 0), transform(2, 0), 0, transform(0, 1), transform(1, 1), transform(2, 1), 0, transform(0, 2), transform(1, 2), transform(2, 2), 0, 0, 0, 0, 1 }; #ifndef NDEBUG // this approach would only work if the upper 3x3 was a pure rotation matrix (no scale) // that would mean all rows and columns were unit length and orthogonal. this tests for the former. for(int idx=0; idx < 3; idx++) { assert(abs(1.0 - cv::norm(invRotation.col(idx))) <= 0.001 && "Expecting unit length (no scale) for rotation matrix"); assert(abs(1.0 - cv::norm(invRotation.row(idx))) <= 0.001 && "Expecting unit length (no scale) for rotation matrix"); } //a valid rotation matrix has determinant 1 (a mirror would be -1) assert(abs(1.0 - cv::determinant(invRotation)) < 0.001 && "Expecting determinant of 1 for rotation matrix"); #endif //invert translation by negation on copy cv::Matx44f invTranslation{ 1, 0, 0, -transform(0, 3), 0, 1, 0, -transform(1, 3), 0, 0, 1, -transform(2, 3), 0, 0, 0, 1 }; //inverse matrix return invRotation * invTranslation; } inline cv::Matx44f ComputeFrameTransform(const cv::Matx44f& from, const cv::Matx44f& to) { return to * Invert(from); } inline cv::Point3f UnProject(const cv::Matx33f& invCameraMatrix, const cv::Matx44f& viewMatrix, const cv::Point2i& point, float depth) { cv::Matx31f pixelSpace{ static_cast<float>(point.x), static_cast<float>(point.y), 1.f }; cv::Matx31f cameraSpace = invCameraMatrix * pixelSpace; cameraSpace *= depth; cv::Matx41f world = Invert(viewMatrix) * cv::Matx41f{ cameraSpace(0), cameraSpace(1), cameraSpace(2), 1 }; return{ world(0), world(1), world(2) }; } const float NRM_EPSILON = 0.00001f; inline float Length(const cv::Vec3f& vec) { return std::sqrtf(vec.dot(vec)); } inline cv::Vec3f Normalize(const cv::Vec3f& vec) { float distance = Length(vec); if (distance == 0) return vec; cv::Vec3f normVec = (vec / distance); assert(abs(sqrt(normVec.dot(normVec)) - 1.0f) < NRM_EPSILON); return normVec; } //rightHanded, column vec convention, intended for rotation of vectors (active) //https://en.wikipedia.org/wiki/Rotation_matrix //vs http://mathworld.wolfram.com/RotationMatrix.html intended for rotation of coordinate frames inline cv::Matx44f RotationXForVectors(float radians) { float cosR = std::cosf(radians); float sinR = std::sinf(radians); return{ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, cosR, -sinR, 0.0f, 0.0f, sinR, cosR, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; } //rightHanded, column vec convention, intended for rotation of vectors (active) //https://en.wikipedia.org/wiki/Rotation_matrix //vs http://mathworld.wolfram.com/RotationMatrix.html intended for rotation of coordinate frames inline cv::Matx44f RotationYForVectors(float radians) { float cosR = std::cosf(radians); float sinR = std::sinf(radians); return{ cosR, 0.0f, sinR, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -sinR, 0.0f, cosR, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; } //rightHanded, column vec convention, intended for rotation of vectors (active) //https://en.wikipedia.org/wiki/Rotation_matrix //vs http://mathworld.wolfram.com/RotationMatrix.html intended for rotation of coordinate frames inline cv::Matx44f RotationZForVectors(float radians) { float cosR = std::cosf(radians); float sinR = std::sinf(radians); return{ cosR, -sinR, 0.0f, 0.0f, sinR, cosR, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; } //rightHanded, column vec convention, intended for rotation of coordinate frames (passive) //https://en.wikipedia.org/wiki/Rotation_matrix //ala http://mathworld.wolfram.com/RotationMatrix.html inline cv::Matx44f RotationXForCoordinateFrames(float radians) { float cosR = std::cosf(radians); float sinR = std::sinf(radians); return{ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, cosR, sinR, 0.0f, 0.0f, -sinR, cosR, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; } //rightHanded, column vec convention,intended for rotation of coordinate frames (passive) //https://en.wikipedia.org/wiki/Rotation_matrix //ala http://mathworld.wolfram.com/RotationMatrix.html inline cv::Matx44f RotationYForCoordinateFrames(float radians) { float cosR = std::cosf(radians); float sinR = std::sinf(radians); return{ cosR, 0.0f, -sinR, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, sinR, 0.0f, cosR, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; } //rightHanded, column vec convention, intended for rotation of coordinate frames (passive) //https://en.wikipedia.org/wiki/Rotation_matrix //ala http://mathworld.wolfram.com/RotationMatrix.html inline cv::Matx44f RotationZForCoordinateFrames(float radians) { float cosR = std::cosf(radians); float sinR = std::sinf(radians); return{ cosR, sinR, 0.0f, 0.0f, -sinR, cosR, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; } // encoding of axis/angle in a vec3f // http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#rodrigues inline cv::Matx33f RotationFromRodrigues(const cv::Matx31f& rotation) { cv::Matx33f rotationMat; cv::Rodrigues(rotation, rotationMat); return rotationMat; } template<typename T, size_t M, size_t N> inline std::array<T, M*N> ArrayFromMat(const cv::Matx<T, M, N>& mat) { std::array<T, M * N> out; std::copy(std::begin(mat.val), std::end(mat.val), out.begin()); return out; } inline cv::Matx44f ToCVMat4x4(const mage::Matrix& matrix) { return cv::Matx44f(&matrix.M11); } inline bool IsEntirelyOffscreen(const cv::Rect& rect, const cv::Size& screenResPixels) { assert(rect.width > 0 && "invalid rect"); assert(rect.height > 0 && "invalid rect"); assert(screenResPixels.width > 0 && "invalid screenResPixels"); assert(screenResPixels.height > 0 && "invalid screenResPixels"); int maxHorizPixel = rect.width + rect.x - 1; int maxVerticalPixel = rect.height + rect.y - 1; bool offscreenX = (maxHorizPixel < 0) || (rect.x >(int)(screenResPixels.width - 1)); bool offscreenY = (maxVerticalPixel < 0) || (rect.y >(int)(screenResPixels.height - 1)); return (offscreenX || offscreenY); } inline bool IsWithinArea(const cv::Point2f& pt, const cv::Rect& crop) { assert(crop.width > 0 && "width must be positive nonzero"); assert(crop.height > 0 && "height must be positive nonzero"); return (pt.x >= crop.x && pt.x < (crop.x+crop.width)) && (pt.y >= crop.y && pt.y <= (crop.y + crop.height)); } inline cv::Rect ToCVRect(const mage::Rect& rect) { return { (int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height }; } cv::Mat CreateGrayCVMat(const cv::Size& resolution, const PixelFormat& format, const gsl::span<const uint8_t> imageBytes); cv::Mat CreateBGRCVMat(const cv::Mat& source, const PixelFormat& format); }
{ "alphanum_fraction": 0.5634105731, "avg_line_length": 32.9839816934, "ext": "h", "hexsha": "87a6e1fee57ac7cd4e58dc31223a9beeb9661f26", "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/cv.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/cv.h", "max_line_length": 219, "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/cv.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": 4529, "size": 14414 }
#pragma once #include <map> #include <vector> #ifndef _NOGSL #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #else #include "FakeGSL.h" #endif #include "BooleanNodes.h" #include "CommandLineArgs.h" class Util { public: static map<int, int> getNodeToValMap(map<int, int>& inputMap, vector<int>& inputs) { map<int, int> res; for(auto i = 0; i < inputs.size(); i++) { if (inputs[i] == 0 || inputs[i] == 1) { res[inputMap[i]] = inputs[i]; } } return res; } static bool isAbsolute(bool_node* n) { if (n->type != bool_node::LT) { return false; } bool_node* v; if (n->mother()->type == bool_node::CONST && ((CONST_node*) (n->mother()))->getFval() == 0) { v = n->father(); } else if (n->father()->type == bool_node::CONST && ((CONST_node*) (n->father()))->getFval() == 0) { v = n->mother(); } else { return false; } FastSet<bool_node>& children = n->children; if (children.size() > 1) return false; for(child_iter it = children.begin(); it != children.end(); ++it) { if ((*it)->type == bool_node::ARRACC) { ARRACC_node* ac = (ARRACC_node*)(*it); if (ac->mother() != n) { return false; } bool_node* m = ac->arguments(0); bool_node* f = ac->arguments(1); if (m != v && f != v) { return false; } if (m == v) { if (f->type != bool_node::NEG || f->mother() != v) { return false; } } if (f == v) { if (m->type != bool_node::NEG || m->mother() != v) { return false; } } } else { return false; } } cout << "Absolute node: " << n->lprint() << endl; return true; } static bool isSqrt(bool_node* n) { if (n->type != bool_node::UFUN) { return false; } UFUN_node* un = (UFUN_node*) n; if (un->get_ufname() == "sqrt_math") { return true; } return false; } static bool hasArraccChild(bool_node* n) { FastSet<bool_node>& children = n->children; for(child_iter it = children.begin(); it != children.end(); ++it) { if ((*it)->type == bool_node::ARRACC && (*it)->mother() == n) { return true; } } return false; } static bool hasAssertChild(bool_node& n) { FastSet<bool_node>& children = n.children; if (children.size() > 1) return false; for(child_iter it = children.begin(); it != children.end(); ++it) { if ((*it)->type == bool_node::ASSERT) { return true; } } return false; } static bool hasNotAssertChild(bool_node& n) { FastSet<bool_node>& children = n.children; if (children.size() > 1) return false; for(child_iter it = children.begin(); it != children.end(); ++it) { if ((*it)->type == bool_node::NOT) { FastSet<bool_node>& grandChildren = (*it)->children; if (grandChildren.size() > 1) return false; for (child_iter it1 = grandChildren.begin(); it1 != grandChildren.end(); ++it1) { if ((*it1)->type == bool_node::ASSERT) { return true; } } } } return false; } static bool hasAssertChild(bool_node* n) { return hasAssertChild(*n); } static bool hasNotAssertChild(bool_node* n) { return hasNotAssertChild(*n); } static set<int> getRelevantNodes(bool_node* n) { set<int> ids; set<int> visitedIds; vector<bool_node*> toVisit; toVisit.push_back(n); while(toVisit.size() > 0) { bool_node* node = toVisit.back(); toVisit.pop_back(); if (visitedIds.find(node->id) == visitedIds.end()) { visitedIds.insert(node->id); ids.insert(node->id); for (auto it = node->p_begin(); it != node->p_end(); ++it) { toVisit.push_back(*it); } } } return ids; } static string print(const gsl_vector* v) { stringstream s; for (int i = 0; i < v->size; i++) { s << gsl_vector_get(v, i) << ";"; } return s.str(); } static string print(const gsl_vector* v, string delimiter) { stringstream s; for (int i = 0; i < v->size; i++) { s << gsl_vector_get(v, i) << delimiter; } return s.str(); } static string print(double* arr, int len) { stringstream s; for (int i = 0; i < len; i++) { s << arr[i] << ";"; } return s.str(); } static string print(const vector<int>& v) { stringstream s; for (auto it = v.begin(); it != v.end(); it++) { s << *it << ";"; } return s.str(); } static string print(const vector<double>& v) { stringstream s; for (auto it = v.begin(); it != v.end(); it++) { s << *it << ";"; } return s.str(); } static string print(const set<int>& v) { stringstream s; for (auto it = v.begin(); it != v.end(); it++) { s << *it << ";"; } return s.str(); } static double getMin(const vector<double>& vals) { double minval = 1e30; for (int i = 0; i < vals.size(); i++) { if (vals[i] < minval) { minval = vals[i]; } } return minval; } static double norm(const gsl_vector* v) { return gsl_blas_dnrm2(v); } static bool sameDir(const gsl_vector* v1, const gsl_vector* v2) { double dp = 0.0; gsl_blas_ddot(v1, v2, &dp); dp = dp/(norm(v1) * norm(v2)); //cout << "dot product: " << dp << endl; if (dp > 0.9) return true; return false; } static string benchName() { string s = PARAMS->inputFname; int x1 = s.rfind(".sk"); int x2 = s.rfind("/tmp/"); return s.substr(x2+5, x1-x2 - 5); } static vector<string> split(string &text, string sep) { vector<string> tokens; size_t start = 0, end = 0; while ((end = text.find(sep, start)) != string::npos) { tokens.push_back(text.substr(start, end - start)); start = end + 1; } tokens.push_back(text.substr(start)); return tokens; } };
{ "alphanum_fraction": 0.4614829775, "avg_line_length": 29.2489451477, "ext": "h", "hexsha": "5603afd18cc63e1e8cf67c2d4660f291c661e071", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/Util.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/Util.h", "max_line_length": 108, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/Util.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 1743, "size": 6932 }
/* * 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:44:25 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2real 14 */ /* * This function contains 62 FP additions, 38 FP multiplications, * (or, 60 additions, 36 multiplications, 2 fused multiply/add), * 24 stack variables, and 28 memory accesses */ static const fftw_real K445041867 = FFTW_KONST(+0.445041867912628808577805128993589518932711138); static const fftw_real K1_801937735 = FFTW_KONST(+1.801937735804838252472204639014890102331838324); static const fftw_real K1_246979603 = FFTW_KONST(+1.246979603717467061050009768008479621264549462); static const fftw_real K867767478 = FFTW_KONST(+0.867767478235116240951536665696717509219981456); static const fftw_real K1_949855824 = FFTW_KONST(+1.949855824363647214036263365987862434465571601); static const fftw_real K1_563662964 = FFTW_KONST(+1.563662964936059617416889053348115500464669037); static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000); /* * Generator Id's : * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $ * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $ * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $ */ void fftw_hc2real_14(const fftw_real *real_input, const fftw_real *imag_input, fftw_real *output, int real_istride, int imag_istride, int ostride) { fftw_real tmp3; fftw_real tmp13; fftw_real tmp6; fftw_real tmp14; fftw_real tmp26; fftw_real tmp35; fftw_real tmp23; fftw_real tmp34; fftw_real tmp12; fftw_real tmp16; fftw_real tmp20; fftw_real tmp33; fftw_real tmp9; fftw_real tmp15; fftw_real tmp1; fftw_real tmp2; ASSERT_ALIGNED_DOUBLE; tmp1 = real_input[0]; tmp2 = real_input[7 * real_istride]; tmp3 = tmp1 - tmp2; tmp13 = tmp1 + tmp2; { fftw_real tmp4; fftw_real tmp5; fftw_real tmp24; fftw_real tmp25; ASSERT_ALIGNED_DOUBLE; tmp4 = real_input[2 * real_istride]; tmp5 = real_input[5 * real_istride]; tmp6 = tmp4 - tmp5; tmp14 = tmp4 + tmp5; tmp24 = imag_input[2 * imag_istride]; tmp25 = imag_input[5 * imag_istride]; tmp26 = tmp24 - tmp25; tmp35 = tmp24 + tmp25; } { fftw_real tmp21; fftw_real tmp22; fftw_real tmp10; fftw_real tmp11; ASSERT_ALIGNED_DOUBLE; tmp21 = imag_input[6 * imag_istride]; tmp22 = imag_input[imag_istride]; tmp23 = tmp21 - tmp22; tmp34 = tmp21 + tmp22; tmp10 = real_input[6 * real_istride]; tmp11 = real_input[real_istride]; tmp12 = tmp10 - tmp11; tmp16 = tmp10 + tmp11; } { fftw_real tmp18; fftw_real tmp19; fftw_real tmp7; fftw_real tmp8; ASSERT_ALIGNED_DOUBLE; tmp18 = imag_input[4 * imag_istride]; tmp19 = imag_input[3 * imag_istride]; tmp20 = tmp18 - tmp19; tmp33 = tmp18 + tmp19; tmp7 = real_input[4 * real_istride]; tmp8 = real_input[3 * real_istride]; tmp9 = tmp7 - tmp8; tmp15 = tmp7 + tmp8; } { fftw_real tmp38; fftw_real tmp37; fftw_real tmp29; fftw_real tmp28; ASSERT_ALIGNED_DOUBLE; output[7 * ostride] = tmp3 + (K2_000000000 * (tmp6 + tmp9 + tmp12)); tmp38 = (K1_563662964 * tmp35) + (K1_949855824 * tmp33) + (K867767478 * tmp34); tmp37 = tmp3 + (K1_246979603 * tmp6) - (K1_801937735 * tmp12) - (K445041867 * tmp9); output[ostride] = tmp37 - tmp38; output[13 * ostride] = tmp37 + tmp38; { fftw_real tmp40; fftw_real tmp39; fftw_real tmp36; fftw_real tmp32; ASSERT_ALIGNED_DOUBLE; tmp40 = (K867767478 * tmp33) + (K1_563662964 * tmp34) - (K1_949855824 * tmp35); tmp39 = tmp3 + (K1_246979603 * tmp12) - (K1_801937735 * tmp9) - (K445041867 * tmp6); output[5 * ostride] = tmp39 - tmp40; output[9 * ostride] = tmp39 + tmp40; tmp36 = (K1_563662964 * tmp33) - (K1_949855824 * tmp34) - (K867767478 * tmp35); tmp32 = tmp3 + (K1_246979603 * tmp9) - (K445041867 * tmp12) - (K1_801937735 * tmp6); output[11 * ostride] = tmp32 - tmp36; output[3 * ostride] = tmp32 + tmp36; } output[0] = tmp13 + (K2_000000000 * (tmp14 + tmp15 + tmp16)); tmp29 = (K867767478 * tmp20) + (K1_563662964 * tmp23) - (K1_949855824 * tmp26); tmp28 = tmp13 + (K1_246979603 * tmp16) - (K1_801937735 * tmp15) - (K445041867 * tmp14); output[12 * ostride] = tmp28 - tmp29; output[2 * ostride] = tmp28 + tmp29; { fftw_real tmp31; fftw_real tmp30; fftw_real tmp27; fftw_real tmp17; ASSERT_ALIGNED_DOUBLE; tmp31 = (K1_563662964 * tmp26) + (K1_949855824 * tmp20) + (K867767478 * tmp23); tmp30 = tmp13 + (K1_246979603 * tmp14) - (K1_801937735 * tmp16) - (K445041867 * tmp15); output[8 * ostride] = tmp30 - tmp31; output[6 * ostride] = tmp30 + tmp31; tmp27 = (K1_563662964 * tmp20) - (K1_949855824 * tmp23) - (K867767478 * tmp26); tmp17 = tmp13 + (K1_246979603 * tmp15) - (K445041867 * tmp16) - (K1_801937735 * tmp14); output[4 * ostride] = tmp17 - tmp27; output[10 * ostride] = tmp17 + tmp27; } } } fftw_codelet_desc fftw_hc2real_14_desc = { "fftw_hc2real_14", (void (*)()) fftw_hc2real_14, 14, FFTW_BACKWARD, FFTW_HC2REAL, 323, 0, (const int *) 0, };
{ "alphanum_fraction": 0.6687460013, "avg_line_length": 35.5227272727, "ext": "c", "hexsha": "748e36d472ad94d6693b17e0dc6596f06fafe1a2", "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/fcr_14.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/fcr_14.c", "max_line_length": 146, "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/fcr_14.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": 2145, "size": 6252 }
/* siman/siman_tsp.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <math.h> #include <string.h> #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_siman.h> #include <gsl/gsl_ieee_utils.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 2000 /* 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 5000.0 /* initial temperature */ #define MU_T 1.002 /* damping factor for temperature */ #define T_MIN 5.0e-1 gsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN}; struct s_tsp_city { const char * name; double lat, longitude; /* coordinates */ }; typedef struct s_tsp_city Stsp_city; void prepare_distance_matrix(void); void exhaustive_search(void); void print_distance_matrix(void); double city_distance(Stsp_city c1, Stsp_city c2); double Etsp(void *xp); double Mtsp(void *xp, void *yp); void Stsp(const gsl_rng * r, void *xp, double step_size); void Ptsp(void *xp); /* in this table, latitude and longitude are obtained from the US Census Bureau, at http://www.census.gov/cgi-bin/gazetteer */ Stsp_city cities[] = {{"Santa Fe", 35.68, 105.95}, {"Phoenix", 33.54, 112.07}, {"Albuquerque", 35.12, 106.62}, {"Clovis", 34.41, 103.20}, {"Durango", 37.29, 107.87}, {"Dallas", 32.79, 96.77}, {"Tesuque", 35.77, 105.92}, {"Grants", 35.15, 107.84}, {"Los Alamos", 35.89, 106.28}, {"Las Cruces", 32.34, 106.76}, {"Cortez", 37.35, 108.58}, {"Gallup", 35.52, 108.74}}; #define N_CITIES (sizeof(cities)/sizeof(Stsp_city)) double distance_matrix[N_CITIES][N_CITIES]; /* distance between two cities */ double city_distance(Stsp_city c1, Stsp_city c2) { const double earth_radius = 6375.000; /* 6000KM approximately */ /* sin and cos of lat and long; must convert to radians */ double sla1 = sin(c1.lat*M_PI/180), cla1 = cos(c1.lat*M_PI/180), slo1 = sin(c1.longitude*M_PI/180), clo1 = cos(c1.longitude*M_PI/180); double sla2 = sin(c2.lat*M_PI/180), cla2 = cos(c2.lat*M_PI/180), slo2 = sin(c2.longitude*M_PI/180), clo2 = cos(c2.longitude*M_PI/180); double x1 = cla1*clo1; double x2 = cla2*clo2; double y1 = cla1*slo1; double y2 = cla2*slo2; double z1 = sla1; double z2 = sla2; double dot_product = x1*x2 + y1*y2 + z1*z2; double angle = acos(dot_product); /* distance is the angle (in radians) times the earth radius */ return angle*earth_radius; } /* energy for the travelling salesman problem */ double Etsp(void *xp) { /* an array of N_CITIES integers describing the order */ int *route = (int *) xp; double E = 0; unsigned int i; for (i = 0; i < N_CITIES; ++i) { /* use the distance_matrix to optimize this calculation; it had better be allocated!! */ E += distance_matrix[route[i]][route[(i + 1) % N_CITIES]]; } return E; } double Mtsp(void *xp, void *yp) { int *route1 = (int *) xp, *route2 = (int *) yp; double distance = 0; unsigned int i; for (i = 0; i < N_CITIES; ++i) { distance += ((route1[i] == route2[i]) ? 0 : 1); } return distance; } /* take a step through the TSP space */ void Stsp(const gsl_rng * r, void *xp, double step_size) { int x1, x2, dummy; int *route = (int *) xp; step_size = 0 ; /* prevent warnings about unused parameter */ /* pick the two cities to swap in the matrix; we leave the first city fixed */ x1 = (gsl_rng_get (r) % (N_CITIES-1)) + 1; do { x2 = (gsl_rng_get (r) % (N_CITIES-1)) + 1; } while (x2 == x1); dummy = route[x1]; route[x1] = route[x2]; route[x2] = dummy; } void Ptsp(void *xp) { unsigned int i; int *route = (int *) xp; printf(" ["); for (i = 0; i < N_CITIES; ++i) { printf(" %d ", route[i]); } printf("] "); } int main(void) { int x_initial[N_CITIES]; unsigned int i; const gsl_rng * r = gsl_rng_alloc (gsl_rng_env_setup()) ; gsl_ieee_env_setup (); prepare_distance_matrix(); /* set up a trivial initial route */ printf("# initial order of cities:\n"); for (i = 0; i < N_CITIES; ++i) { printf("# \"%s\"\n", cities[i].name); x_initial[i] = i; } printf("# distance matrix is:\n"); print_distance_matrix(); printf("# initial coordinates of cities (longitude and latitude)\n"); /* this can be plotted with */ /* ./siman_tsp > hhh ; grep city_coord hhh | awk '{print $2 " " $3}' | xyplot -ps -d "xy" > c.eps */ for (i = 0; i < N_CITIES+1; ++i) { printf("###initial_city_coord: %g %g \"%s\"\n", -cities[x_initial[i % N_CITIES]].longitude, cities[x_initial[i % N_CITIES]].lat, cities[x_initial[i % N_CITIES]].name); } /* exhaustive_search(); */ gsl_siman_solve(r, x_initial, Etsp, Stsp, Mtsp, Ptsp, NULL, NULL, NULL, N_CITIES*sizeof(int), params); printf("# final order of cities:\n"); for (i = 0; i < N_CITIES; ++i) { printf("# \"%s\"\n", cities[x_initial[i]].name); } printf("# final coordinates of cities (longitude and latitude)\n"); /* this can be plotted with */ /* ./siman_tsp > hhh ; grep city_coord hhh | awk '{print $2 " " $3}' | xyplot -ps -d "xy" > c.eps */ for (i = 0; i < N_CITIES+1; ++i) { printf("###final_city_coord: %g %g %s\n", -cities[x_initial[i % N_CITIES]].longitude, cities[x_initial[i % N_CITIES]].lat, cities[x_initial[i % N_CITIES]].name); } printf("# "); fflush(stdout); #if 0 system("date"); #endif /* 0 */ fflush(stdout); return 0; } void prepare_distance_matrix() { unsigned int i, j; double dist; for (i = 0; i < N_CITIES; ++i) { for (j = 0; j < N_CITIES; ++j) { if (i == j) { dist = 0; } else { dist = city_distance(cities[i], cities[j]); } distance_matrix[i][j] = dist; } } } void print_distance_matrix() { unsigned int i, j; for (i = 0; i < N_CITIES; ++i) { printf("# "); for (j = 0; j < N_CITIES; ++j) { printf("%15.8f ", distance_matrix[i][j]); } printf("\n"); } } /* [only works for 12] search the entire space for solutions */ static double best_E = 1.0e100, second_E = 1.0e100, third_E = 1.0e100; static int best_route[N_CITIES]; static int second_route[N_CITIES]; static int third_route[N_CITIES]; static void do_all_perms(int *route, int n); void exhaustive_search() { static int initial_route[N_CITIES] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; printf("\n# "); fflush(stdout); #if 0 system("date"); #endif fflush(stdout); do_all_perms(initial_route, 1); printf("\n# "); fflush(stdout); #if 0 system("date"); #endif /* 0 */ fflush(stdout); printf("# exhaustive best route: "); Ptsp(best_route); printf("\n# its energy is: %g\n", best_E); printf("# exhaustive second_best route: "); Ptsp(second_route); printf("\n# its energy is: %g\n", second_E); printf("# exhaustive third_best route: "); Ptsp(third_route); printf("\n# its energy is: %g\n", third_E); } /* James Theiler's recursive algorithm for generating all routes */ static void do_all_perms(int *route, int n) { if (n == (N_CITIES-1)) { /* do it! calculate the energy/cost for that route */ double E; E = Etsp(route); /* TSP energy function */ /* now save the best 3 energies and routes */ if (E < best_E) { third_E = second_E; memcpy(third_route, second_route, N_CITIES*sizeof(*route)); second_E = best_E; memcpy(second_route, best_route, N_CITIES*sizeof(*route)); best_E = E; memcpy(best_route, route, N_CITIES*sizeof(*route)); } else if (E < second_E) { third_E = second_E; memcpy(third_route, second_route, N_CITIES*sizeof(*route)); second_E = E; memcpy(second_route, route, N_CITIES*sizeof(*route)); } else if (E < third_E) { third_E = E; memcpy(route, third_route, N_CITIES*sizeof(*route)); } } else { int new_route[N_CITIES]; unsigned int j; int swap_tmp; memcpy(new_route, route, N_CITIES*sizeof(*route)); for (j = n; j < N_CITIES; ++j) { swap_tmp = new_route[j]; new_route[j] = new_route[n]; new_route[n] = swap_tmp; do_all_perms(new_route, n+1); } } }
{ "alphanum_fraction": 0.6251639703, "avg_line_length": 27.7212121212, "ext": "c", "hexsha": "5a44a8ed106d82ca7a39e509b7117d6447d8ea26", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/siman/siman_tsp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/siman/siman_tsp.c", "max_line_length": 104, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/siman/siman_tsp.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": 2828, "size": 9148 }
/* adept_source.h - Source code for the Adept library Copyright (C) 2012-2015 The University of Reading Copyright (C) 2015-2017 European Centre for Medium-Range Weather Forecasts 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. This file was created automatically by script ./create_adept_source_header on Sun 28 Jan 21:05:14 GMT 2018 It contains a concatenation of the source files from the Adept library. The idea is that a program may #include this file in one of its source files (typically the one containing the main function), and then the Adept library will be built into the executable without the need to link to an external library. All other source files should just #include <adept.h> or <adept_arrays.h>. The ability to use Adept in this way makes it easier to distribute an Adept package that is usable on non-Unix platforms that are unable to use the autoconf configure script to build external libraries. If HAVE_BLAS is defined below then matrix multiplication will be enabled; the BLAS library should be provided at the link stage although no header file is required. If HAVE_LAPACK is defined below then linear algebra routines will be enabled (matrix inverse and solving linear systems of equations); again, the LAPACK library should be provided at the link stage although no header file is required. */ /* Feel free to delete this warning: */ #ifdef _MSC_FULL_VER #pragma message("warning: the adept_source.h header file has not been edited so BLAS matrix multiplication and LAPACK linear-algebra support have been disabled") #else #warning "The adept_source.h header file has not been edited so BLAS matrix multiplication and LAPACK linear-algebra support have been disabled" #endif /* Uncomment this if you are linking to the BLAS library (header file not required) to enable matrix multiplication */ #define HAVE_BLAS 1 /* Uncomment this if you are linking to the LAPACK library (header file not required) */ //#define HAVE_LAPACK 1 /* Uncomment this if you have the cblas.h header from OpenBLAS */ //#define HAVE_OPENBLAS_CBLAS_HEADER /* The individual source files now follow. */ #ifndef AdeptSource_H #define AdeptSource_H 1 // ================================================================= // Contents of config_platform_independent.h // ================================================================= /* config_platform_independent.h. Generated from config_platform_independent.h.in by configure. */ /* config_platform_independent.h.in. */ /* Name of package */ #define PACKAGE "adept" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "r.j.hogan@ecmwf.int" /* Define to the full name of this package. */ #define PACKAGE_NAME "adept" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "adept 2.0.5" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "adept" /* Define to the home page for this package. */ #define PACKAGE_URL "http://www.met.reading.ac.uk/clouds/adept/" /* Define to the version of this package. */ #define PACKAGE_VERSION "2.0.5" /* Version number of package */ #define VERSION "2.0.5" // ================================================================= // Contents of cpplapack.h // ================================================================= /* cpplapack.h -- C++ interface to LAPACK Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #ifndef AdeptCppLapack_H #define AdeptCppLapack_H 1 #include <vector> #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_LAPACK extern "C" { // External LAPACK Fortran functions void sgetrf_(const int* m, const int* n, float* a, const int* lda, int* ipiv, int* info); void dgetrf_(const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info); void sgetri_(const int* n, float* a, const int* lda, const int* ipiv, float* work, const int* lwork, int* info); void dgetri_(const int* n, double* a, const int* lda, const int* ipiv, double* work, const int* lwork, int* info); void ssytrf_(const char* uplo, const int* n, float* a, const int* lda, int* ipiv, float* work, const int* lwork, int* info); void dsytrf_(const char* uplo, const int* n, double* a, const int* lda, int* ipiv, double* work, const int* lwork, int* info); void ssytri_(const char* uplo, const int* n, float* a, const int* lda, const int* ipiv, float* work, int* info); void dsytri_(const char* uplo, const int* n, double* a, const int* lda, const int* ipiv, double* work, int* info); void ssysv_(const char* uplo, const int* n, const int* nrhs, float* a, const int* lda, int* ipiv, float* b, const int* ldb, float* work, const int* lwork, int* info); void dsysv_(const char* uplo, const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, double* work, const int* lwork, int* info); void sgesv_(const int* n, const int* nrhs, float* a, const int* lda, int* ipiv, float* b, const int* ldb, int* info); void dgesv_(const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, int* info); } namespace adept { // Overloaded functions provide both single & // double precision versions, and prevents the huge lapacke.h having // to be included in all user code namespace internal { typedef int lapack_int; // Factorize a general matrix inline int cpplapack_getrf(int n, float* a, int lda, int* ipiv) { int info; sgetrf_(&n, &n, a, &lda, ipiv, &info); return info; } inline int cpplapack_getrf(int n, double* a, int lda, int* ipiv) { int info; dgetrf_(&n, &n, a, &lda, ipiv, &info); return info; } // Invert a general matrix inline int cpplapack_getri(int n, float* a, int lda, const int* ipiv) { int info; float work_query; int lwork = -1; // Find out how much work memory required sgetri_(&n, a, &lda, ipiv, &work_query, &lwork, &info); lwork = static_cast<int>(work_query); std::vector<float> work(static_cast<size_t>(lwork)); // Do full calculation sgetri_(&n, a, &lda, ipiv, &work[0], &lwork, &info); return info; } inline int cpplapack_getri(int n, double* a, int lda, const int* ipiv) { int info; double work_query; int lwork = -1; // Find out how much work memory required dgetri_(&n, a, &lda, ipiv, &work_query, &lwork, &info); lwork = static_cast<int>(work_query); std::vector<double> work(static_cast<size_t>(lwork)); // Do full calculation dgetri_(&n, a, &lda, ipiv, &work[0], &lwork, &info); return info; } // Factorize a symmetric matrix inline int cpplapack_sytrf(char uplo, int n, float* a, int lda, int* ipiv) { int info; float work_query; int lwork = -1; // Find out how much work memory required ssytrf_(&uplo, &n, a, &lda, ipiv, &work_query, &lwork, &info); lwork = static_cast<int>(work_query); std::vector<float> work(static_cast<size_t>(lwork)); // Do full calculation ssytrf_(&uplo, &n, a, &lda, ipiv, &work[0], &lwork, &info); return info; } inline int cpplapack_sytrf(char uplo, int n, double* a, int lda, int* ipiv) { int info; double work_query; int lwork = -1; // Find out how much work memory required dsytrf_(&uplo, &n, a, &lda, ipiv, &work_query, &lwork, &info); lwork = static_cast<int>(work_query); std::vector<double> work(static_cast<size_t>(lwork)); // Do full calculation dsytrf_(&uplo, &n, a, &lda, ipiv, &work[0], &lwork, &info); return info; } // Invert a symmetric matrix inline int cpplapack_sytri(char uplo, int n, float* a, int lda, const int* ipiv) { int info; std::vector<float> work(n); ssytri_(&uplo, &n, a, &lda, ipiv, &work[0], &info); return info; } inline int cpplapack_sytri(char uplo, int n, double* a, int lda, const int* ipiv) { int info; std::vector<double> work(n); dsytri_(&uplo, &n, a, &lda, ipiv, &work[0], &info); return info; } // Solve system of linear equations with general matrix inline int cpplapack_gesv(int n, int nrhs, float* a, int lda, int* ipiv, float* b, int ldb) { int info; sgesv_(&n, &nrhs, a, &lda, ipiv, b, &lda, &info); return info; } inline int cpplapack_gesv(int n, int nrhs, double* a, int lda, int* ipiv, double* b, int ldb) { int info; dgesv_(&n, &nrhs, a, &lda, ipiv, b, &lda, &info); return info; } // Solve system of linear equations with symmetric matrix inline int cpplapack_sysv(char uplo, int n, int nrhs, float* a, int lda, int* ipiv, float* b, int ldb) { int info; float work_query; int lwork = -1; // Find out how much work memory required ssysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work_query, &lwork, &info); lwork = static_cast<int>(work_query); std::vector<float> work(static_cast<size_t>(lwork)); // Do full calculation ssysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work[0], &lwork, &info); return info; } inline int cpplapack_sysv(char uplo, int n, int nrhs, double* a, int lda, int* ipiv, double* b, int ldb) { int info; double work_query; int lwork = -1; // Find out how much work memory required dsysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work_query, &lwork, &info); lwork = static_cast<int>(work_query); std::vector<double> work(static_cast<size_t>(lwork)); // Do full calculation dsysv_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &work[0], &lwork, &info); return info; } } } #endif #endif // ================================================================= // Contents of Array.cpp // ================================================================= /* Array.cpp -- Functions and global variables controlling array behaviour Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <adept/Array.h> namespace adept { namespace internal { bool array_row_major_order = true; // bool array_print_curly_brackets = true; // Variables describing how arrays are written to a stream ArrayPrintStyle array_print_style = PRINT_STYLE_CURLY; std::string vector_separator = ", "; std::string vector_print_before = "{"; std::string vector_print_after = "}"; std::string array_opening_bracket = "{"; std::string array_closing_bracket = "}"; std::string array_contiguous_separator = ", "; std::string array_non_contiguous_separator = ",\n"; std::string array_print_before = "\n{"; std::string array_print_after = "}"; std::string array_print_empty_before = "(empty rank-"; std::string array_print_empty_after = " array)"; bool array_print_indent = true; bool array_print_empty_rank = true; } void set_array_print_style(ArrayPrintStyle ps) { using namespace internal; switch (ps) { case PRINT_STYLE_PLAIN: vector_separator = " "; vector_print_before = ""; vector_print_after = ""; array_opening_bracket = ""; array_closing_bracket = ""; array_contiguous_separator = " "; array_non_contiguous_separator = "\n"; array_print_before = ""; array_print_after = ""; array_print_empty_before = "(empty rank-"; array_print_empty_after = " array)"; array_print_indent = false; array_print_empty_rank = true; break; case PRINT_STYLE_CSV: vector_separator = ", "; vector_print_before = ""; vector_print_after = ""; array_opening_bracket = ""; array_closing_bracket = ""; array_contiguous_separator = ", "; array_non_contiguous_separator = "\n"; array_print_before = ""; array_print_after = ""; array_print_empty_before = "empty"; array_print_empty_after = ""; array_print_indent = false; array_print_empty_rank = false; break; case PRINT_STYLE_MATLAB: vector_separator = " "; vector_print_before = "["; vector_print_after = "]"; array_opening_bracket = ""; array_closing_bracket = ""; array_contiguous_separator = " "; array_non_contiguous_separator = ";\n"; array_print_before = "["; array_print_after = "]"; array_print_empty_before = "["; array_print_empty_after = "]"; array_print_indent = true; array_print_empty_rank = false; break; case PRINT_STYLE_CURLY: vector_separator = ", "; vector_print_before = "{"; vector_print_after = "}"; array_opening_bracket = "{"; array_closing_bracket = "}"; array_contiguous_separator = ", "; array_non_contiguous_separator = ",\n"; array_print_before = "\n{"; array_print_after = "}"; array_print_empty_before = "(empty rank-"; array_print_empty_after = " array)"; array_print_indent = true; array_print_empty_rank = true; break; default: //throw invalid_operation("Array print style not understood"); printf("invalid operation\n"); assert(false); } array_print_style = ps; } } // ================================================================= // Contents of Stack.cpp // ================================================================= /* Stack.cpp -- Stack for storing automatic differentiation information Copyright (C) 2012-2014 University of Reading Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <iostream> #include <cstring> // For memcpy #ifdef _OPENMP #include <omp.h> #endif #include <adept/Stack.h> namespace adept { using namespace internal; // Global pointers to the current thread, the second of which is // thread safe. The first is only used if ADEPT_STACK_THREAD_UNSAFE // is defined. ADEPT_THREAD_LOCAL Stack* _stack_current_thread = 0; Stack* _stack_current_thread_unsafe = 0; // MEMBER FUNCTIONS OF THE STACK CLASS // Destructor: frees dynamically allocated memory (if any) Stack::~Stack() { // If this is the currently active stack then set to NULL as // "this" is shortly to become invalid if (is_thread_unsafe_) { if (_stack_current_thread_unsafe == this) { _stack_current_thread_unsafe = 0; } } else if (_stack_current_thread == this) { _stack_current_thread = 0; } #ifndef ADEPT_STACK_STORAGE_STL if (gradient_) { delete[] gradient_; } #endif } // Make this stack "active" by copying its "this" pointer to a // global variable; this makes it the stack that aReal objects // subsequently interact with when being created and participating // in mathematical expressions void Stack::activate() { // Check that we don't already have an active stack in this thread if ((is_thread_unsafe_ && _stack_current_thread_unsafe && _stack_current_thread_unsafe != this) || ((!is_thread_unsafe_) && _stack_current_thread && _stack_current_thread != this)) { //throw(stack_already_active()); printf("stack already active\n"); assert(false); } else { if (!is_thread_unsafe_) { _stack_current_thread = this; } else { _stack_current_thread_unsafe = this; } } } // Set the maximum number of threads to be used in Jacobian // calculations, if possible. A value of 1 indicates that OpenMP // will not be used, while a value of 0 indicates that the number // will match the number of available processors. Returns the // maximum that will be used, which will be 1 if the Adept library // was compiled without OpenMP support. Note that a value of 1 will // disable the use of OpenMP with Adept, so Adept will then use no // OpenMP directives or function calls. Note that if in your program // you use OpenMP with each thread performing automatic // differentiaion with its own independent Adept stack, then // typically only one OpenMP thread is available for each Jacobian // calculation, regardless of whether you call this function. int Stack::set_max_jacobian_threads(int n) { #ifdef _OPENMP if (have_openmp_) { if (n == 1) { openmp_manually_disabled_ = true; return 1; } else if (n < 1) { openmp_manually_disabled_ = false; omp_set_num_threads(omp_get_num_procs()); return omp_get_max_threads(); } else { openmp_manually_disabled_ = false; omp_set_num_threads(n); return omp_get_max_threads(); } } #endif return 1; } // Return maximum number of OpenMP threads to be used in Jacobian // calculation int Stack::max_jacobian_threads() const { #ifdef _OPENMP if (have_openmp_) { if (openmp_manually_disabled_) { return 1; } else { return omp_get_max_threads(); } } #endif return 1; } // Perform to adjoint computation (reverse mode). It is assumed that // some gradients have been assigned already, otherwise the function // returns with an error. void Stack::compute_adjoint() { if (gradients_are_initialized()) { // Loop backwards through the derivative statements for (uIndex ist = n_statements_-1; ist > 0; ist--) { const Statement& statement = statement_[ist]; // We copy the RHS gradient (LHS in the original derivative // statement but swapped in the adjoint equivalent) to "a" in // case it appears on the LHS in any of the following statements Real a = gradient_[statement.index]; gradient_[statement.index] = 0.0; // By only looping if a is non-zero we gain a significant speed-up if (a != 0.0) { // Loop over operations for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { gradient_[index_[i]] += multiplier_[i]*a; } } } } else { //throw(gradients_not_initialized()); printf("gradients not initialized\n"); assert(false); } } // Perform tangent linear computation (forward mode). It is assumed // that some gradients have been assigned already, otherwise the // function returns with an error. void Stack::compute_tangent_linear() { if (gradients_are_initialized()) { // Loop forward through the statements for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; // We copy the LHS to "a" in case it appears on the RHS in any // of the following statements Real a = 0.0; for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { a += multiplier_[i]*gradient_[index_[i]]; } gradient_[statement.index] = a; } } else { //throw(gradients_not_initialized()); printf("gradients not initialized\n"); assert(false); } } // Register n gradients uIndex Stack::do_register_gradients(const uIndex& n) { n_gradients_registered_ += n; if (!gap_list_.empty()) { uIndex return_val; // Insert in a gap, if there is one big enough for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { uIndex len = it->end + 1 - it->start; if (len > n) { // Gap a bit larger than needed: reduce its size return_val = it->start; it->start += n; return return_val; } else if (len == n) { // Gap exactly the size needed: fill it and remove from list return_val = it->start; if (most_recent_gap_ == it) { gap_list_.erase(it); most_recent_gap_ = gap_list_.end(); } else { gap_list_.erase(it); } return return_val; } } } // No suitable gap found; instead add to end of gradient vector i_gradient_ += n; if (i_gradient_ > max_gradient_) { max_gradient_ = i_gradient_; } return i_gradient_ - n; } // If an aReal object is deleted, its gradient_index is // unregistered from the stack. If this is at the top of the stack // then this is easy and is done inline; this is the usual case // since C++ trys to deallocate automatic objects in the reverse // order to that in which they were allocated. If it is not at the // top of the stack then a non-inline function is called to ensure // that the gap list is adjusted correctly. void Stack::unregister_gradient_not_top(const uIndex& gradient_index) { enum { ADDED_AT_BASE, ADDED_AT_TOP, NEW_GAP, NOT_FOUND } status = NOT_FOUND; // First try to find if the unregistered element is at the // start or end of an existing gap if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) { // We have a "most recent" gap - check whether the gradient // to be unregistered is here Gap& current_gap = *most_recent_gap_; if (gradient_index == current_gap.start - 1) { current_gap.start--; status = ADDED_AT_BASE; } else if (gradient_index == current_gap.end + 1) { current_gap.end++; status = ADDED_AT_TOP; } // Should we check for erroneous removal from middle of gap? } if (status == NOT_FOUND) { // Search other gaps for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { if (gradient_index <= it->end + 1) { // Gradient to unregister is either within the gap // referenced by iterator "it", or it is between "it" // and the previous gap in the list if (gradient_index == it->start - 1) { status = ADDED_AT_BASE; it->start--; most_recent_gap_ = it; } else if (gradient_index == it->end + 1) { status = ADDED_AT_TOP; it->end++; most_recent_gap_ = it; } else { // Insert a new gap of width 1; note that list::insert // inserts *before* the specified location most_recent_gap_ = gap_list_.insert(it, Gap(gradient_index)); status = NEW_GAP; } break; } } if (status == NOT_FOUND) { gap_list_.push_back(Gap(gradient_index)); most_recent_gap_ = gap_list_.end(); most_recent_gap_--; } } // Finally check if gaps have merged if (status == ADDED_AT_BASE && most_recent_gap_ != gap_list_.begin()) { // Check whether the gap has merged with the next one GapListIterator it = most_recent_gap_; it--; if (it->end == most_recent_gap_->start - 1) { // Merge two gaps most_recent_gap_->start = it->start; gap_list_.erase(it); } } else if (status == ADDED_AT_TOP) { GapListIterator it = most_recent_gap_; it++; if (it != gap_list_.end() && it->start == most_recent_gap_->end + 1) { // Merge two gaps most_recent_gap_->end = it->end; gap_list_.erase(it); } } } // Unregister n gradients starting at gradient_index void Stack::unregister_gradients(const uIndex& gradient_index, const uIndex& n) { n_gradients_registered_ -= n; if (gradient_index+n == i_gradient_) { // Gradient to be unregistered is at the top of the stack i_gradient_ -= n; if (!gap_list_.empty()) { Gap& last_gap = gap_list_.back(); if (i_gradient_ == last_gap.end+1) { // We have unregistered the elements between the "gap" of // unregistered element and the top of the stack, so can set // the variables indicating the presence of the gap to zero i_gradient_ = last_gap.start; GapListIterator it = gap_list_.end(); it--; if (most_recent_gap_ == it) { most_recent_gap_ = gap_list_.end(); } gap_list_.pop_back(); } } } else { // Gradients to be unregistered not at top of stack. enum { ADDED_AT_BASE, ADDED_AT_TOP, NEW_GAP, NOT_FOUND } status = NOT_FOUND; // First try to find if the unregistered element is at the start // or end of an existing gap if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) { // We have a "most recent" gap - check whether the gradient // to be unregistered is here Gap& current_gap = *most_recent_gap_; if (gradient_index == current_gap.start - n) { current_gap.start -= n; status = ADDED_AT_BASE; } else if (gradient_index == current_gap.end + 1) { current_gap.end += n; status = ADDED_AT_TOP; } /* else if (gradient_index > current_gap.start - n && gradient_index < current_gap.end + 1) { std::cout << "** Attempt to find " << gradient_index << " in gaps "; print_gaps(); std::cout << "\n"; throw invalid_operation("Gap list corruption"); } */ // Should we check for erroneous removal from middle of gap? } if (status == NOT_FOUND) { // Search other gaps for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { if (gradient_index <= it->end + 1) { // Gradient to unregister is either within the gap // referenced by iterator "it", or it is between "it" and // the previous gap in the list if (gradient_index == it->start - n) { status = ADDED_AT_BASE; it->start -= n; most_recent_gap_ = it; } else if (gradient_index == it->end + 1) { status = ADDED_AT_TOP; it->end += n; most_recent_gap_ = it; } /* else if (gradient_index > it->start - n) { std::cout << "*** Attempt to find " << gradient_index << " in gaps "; print_gaps(); std::cout << "\n"; throw invalid_operation("Gap list corruption"); } */ else { // Insert a new gap; note that list::insert inserts // *before* the specified location most_recent_gap_ = gap_list_.insert(it, Gap(gradient_index, gradient_index+n-1)); status = NEW_GAP; } break; } } if (status == NOT_FOUND) { gap_list_.push_back(Gap(gradient_index, gradient_index+n-1)); most_recent_gap_ = gap_list_.end(); most_recent_gap_--; } } // Finally check if gaps have merged if (status == ADDED_AT_BASE && most_recent_gap_ != gap_list_.begin()) { // Check whether the gap has merged with the next one GapListIterator it = most_recent_gap_; it--; if (it->end == most_recent_gap_->start - 1) { // Merge two gaps most_recent_gap_->start = it->start; gap_list_.erase(it); } } else if (status == ADDED_AT_TOP) { GapListIterator it = most_recent_gap_; it++; if (it != gap_list_.end() && it->start == most_recent_gap_->end + 1) { // Merge two gaps most_recent_gap_->end = it->end; gap_list_.erase(it); } } } } // Print each derivative statement to the specified stream (standard // output if omitted) void Stack::print_statements(std::ostream& os) const { for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; os << ist << ": d[" << statement.index << "] = "; if (statement_[ist-1].end_plus_one == statement_[ist].end_plus_one) { os << "0\n"; } else { for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { os << " + " << multiplier_[i] << "*d[" << index_[i] << "]"; } os << "\n"; } } } // Print the current gradient list to the specified stream (standard // output if omitted) bool Stack::print_gradients(std::ostream& os) const { if (gradients_are_initialized()) { for (uIndex i = 0; i < max_gradient_; i++) { if (i%10 == 0) { if (i != 0) { os << "\n"; } os << i << ":"; } os << " " << gradient_[i]; } os << "\n"; return true; } else { os << "No gradients initialized\n"; return false; } } // Print the list of gaps in the gradient list to the specified // stream (standard output if omitted) void Stack::print_gaps(std::ostream& os) const { for (std::list<Gap>::const_iterator it = gap_list_.begin(); it != gap_list_.end(); it++) { os << it->start << "-" << it->end << " "; } } #ifndef ADEPT_STACK_STORAGE_STL // Initialize the vector of gradients ready for the adjoint // calculation void Stack::initialize_gradients() { if (max_gradient_ > 0) { if (n_allocated_gradients_ < max_gradient_) { if (gradient_) { delete[] gradient_; } gradient_ = new Real[max_gradient_]; n_allocated_gradients_ = max_gradient_; } for (uIndex i = 0; i < max_gradient_; i++) { gradient_[i] = 0.0; } } gradients_initialized_ = true; } #else void Stack::initialize_gradients() { gradient_.resize(max_gradient_+10, 0.0); gradients_initialized_ = true; } #endif // Report information about the stack to the specified stream, or // standard output if omitted; note that this is synonymous with // sending the Stack object to a stream using the "<<" operator. void Stack::print_status(std::ostream& os) const { os << "Automatic Differentiation Stack (address " << this << "):\n"; if ((!is_thread_unsafe_) && _stack_current_thread == this) { os << " Currently attached - thread safe\n"; } else if (is_thread_unsafe_ && _stack_current_thread_unsafe == this) { os << " Currently attached - thread unsafe\n"; } else { os << " Currently detached\n"; } os << " Recording status:\n"; if (is_recording_) { os << " Recording is ON\n"; } else { os << " Recording is PAUSED\n"; } // Account for the null statement at the start by subtracting one os << " " << n_statements()-1 << " statements (" << n_allocated_statements() << " allocated)"; os << " and " << n_operations() << " operations (" << n_allocated_operations() << " allocated)\n"; os << " " << n_gradients_registered() << " gradients currently registered "; os << "and a total of " << max_gradients() << " needed (current index " << i_gradient() << ")\n"; if (gap_list_.empty()) { os << " Gradient list has no gaps\n"; } else { os << " Gradient list has " << gap_list_.size() << " gaps ("; print_gaps(os); os << ")\n"; } os << " Computation status:\n"; if (gradients_are_initialized()) { os << " " << max_gradients() << " gradients assigned (" << n_allocated_gradients() << " allocated)\n"; } else { os << " 0 gradients assigned (" << n_allocated_gradients() << " allocated)\n"; } os << " Jacobian size: " << n_dependents() << "x" << n_independents() << "\n"; if (n_dependents() <= 10 && n_independents() <= 10) { os << " Independent indices:"; for (std::size_t i = 0; i < independent_index_.size(); ++i) { os << " " << independent_index_[i]; } os << "\n Dependent indices: "; for (std::size_t i = 0; i < dependent_index_.size(); ++i) { os << " " << dependent_index_[i]; } os << "\n"; } #ifdef _OPENMP if (have_openmp_) { if (openmp_manually_disabled_) { os << " Parallel Jacobian calculation manually disabled\n"; } else { os << " Parallel Jacobian calculation can use up to " << omp_get_max_threads() << " threads\n"; os << " Each thread treats " << ADEPT_MULTIPASS_SIZE << " (in)dependent variables\n"; } } else { #endif os << " Parallel Jacobian calculation not available\n"; #ifdef _OPENMP } #endif } } // End namespace adept // ================================================================= // Contents of StackStorageOrig.cpp // ================================================================= /* StackStorageOrig.cpp -- Original storage of stacks using STL containers Copyright (C) 2014-2015 University of Reading Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. The Stack class inherits from a class providing the storage (and interface to the storage) for the derivative statements that are accumulated during the execution of an algorithm. The derivative statements are held in two stacks described by Hogan (2014): the "statement stack" and the "operation stack". This file provides one of the original storage engine, which used std::vector to hold the two stacks. Note that these stacks are contiguous in memory, which is not ideal for very large algorithms. */ #include <cstring> #include <adept/StackStorageOrig.h> namespace adept { namespace internal { StackStorageOrig::~StackStorageOrig() { if (statement_) { delete[] statement_; } if (multiplier_) { delete[] multiplier_; } if (index_) { delete[] index_; } } // Double the size of the operation stack, or grow it even more if // the requested minimum number of extra entries (min) is greater // than this would allow void StackStorageOrig::grow_operation_stack(uIndex min) { uIndex new_size = 2*n_allocated_operations_; if (min > 0 && new_size < n_allocated_operations_+min) { new_size += min; } Real* new_multiplier = new Real[new_size]; uIndex* new_index = new uIndex[new_size]; std::memcpy(new_multiplier, multiplier_, n_operations_*sizeof(Real)); std::memcpy(new_index, index_, n_operations_*sizeof(uIndex)); delete[] multiplier_; delete[] index_; multiplier_ = new_multiplier; index_ = new_index; n_allocated_operations_ = new_size; } // ... likewise for the statement stack void StackStorageOrig::grow_statement_stack(uIndex min) { uIndex new_size = 2*n_allocated_statements_; if (min > 0 && new_size < n_allocated_statements_+min) { new_size += min; } Statement* new_statement = new Statement[new_size]; std::memcpy(new_statement, statement_, n_statements_*sizeof(Statement)); delete[] statement_; statement_ = new_statement; n_allocated_statements_ = new_size; } } } // ================================================================= // Contents of Storage.cpp // ================================================================= /* Storage.cpp -- Global variables recording use of Storage objects Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <adept/Storage.h> namespace adept { namespace internal { Index n_storage_objects_created_; Index n_storage_objects_deleted_; } } // ================================================================= // Contents of cppblas.cpp // ================================================================= /* cppblas.cpp -- C++ interface to BLAS functions Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. This file provides a C++ interface to selected Level-2 and -3 BLAS functions in which the precision of the arguments (float versus double) is inferred via overloading */ #include <adept/exception.h> #include <adept/cppblas.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_BLAS extern "C" { void sgemm_(const char* TransA, const char* TransB, const int* M, const int* N, const int* K, const float* alpha, const float* A, const int* lda, const float* B, const int* ldb, const float* beta, const float* C, const int* ldc); void dgemm_(const char* TransA, const char* TransB, const int* M, const int* N, const int* K, const double* alpha, const double* A, const int* lda, const double* B, const int* ldb, const double* beta, const double* C, const int* ldc); void sgemv_(const char* TransA, const int* M, const int* N, const float* alpha, const float* A, const int* lda, const float* X, const int* incX, const float* beta, const float* Y, const int* incY); void dgemv_(const char* TransA, const int* M, const int* N, const double* alpha, const double* A, const int* lda, const double* X, const int* incX, const double* beta, const double* Y, const int* incY); void ssymm_(const char* side, const char* uplo, const int* M, const int* N, const float* alpha, const float* A, const int* lda, const float* B, const int* ldb, const float* beta, float* C, const int* ldc); void dsymm_(const char* side, const char* uplo, const int* M, const int* N, const double* alpha, const double* A, const int* lda, const double* B, const int* ldb, const double* beta, double* C, const int* ldc); void ssymv_(const char* uplo, const int* N, const float* alpha, const float* A, const int* lda, const float* X, const int* incX, const float* beta, const float* Y, const int* incY); void dsymv_(const char* uplo, const int* N, const double* alpha, const double* A, const int* lda, const double* X, const int* incX, const double* beta, const double* Y, const int* incY); void sgbmv_(const char* TransA, const int* M, const int* N, const int* kl, const int* ku, const float* alpha, const float* A, const int* lda, const float* X, const int* incX, const float* beta, const float* Y, const int* incY); void dgbmv_(const char* TransA, const int* M, const int* N, const int* kl, const int* ku, const double* alpha, const double* A, const int* lda, const double* X, const int* incX, const double* beta, const double* Y, const int* incY); }; namespace adept { namespace internal { // Matrix-matrix multiplication for general dense matrices #define ADEPT_DEFINE_GEMM(T, FUNC, FUNC_COMPLEX) \ void cppblas_gemm(BLAS_ORDER Order, \ BLAS_TRANSPOSE TransA, \ BLAS_TRANSPOSE TransB, \ int M, int N, \ int K, T alpha, const T *A, \ int lda, const T *B, int ldb, \ T beta, T *C, int ldc) { \ if (Order == BlasColMajor) { \ FUNC(&TransA, &TransB, &M, &N, &K, &alpha, A, &lda, \ B, &ldb, &beta, C, &ldc); \ } \ else { \ FUNC(&TransB, &TransA, &N, &M, &K, &alpha, B, &ldb, \ A, &lda, &beta, C, &ldc); \ } \ } ADEPT_DEFINE_GEMM(double, dgemm_, zgemm_); ADEPT_DEFINE_GEMM(float, sgemm_, cgemm_); #undef ADEPT_DEFINE_GEMM // Matrix-vector multiplication for a general dense matrix #define ADEPT_DEFINE_GEMV(T, FUNC, FUNC_COMPLEX) \ void cppblas_gemv(const BLAS_ORDER Order, \ const BLAS_TRANSPOSE TransA, \ const int M, const int N, \ const T alpha, const T *A, const int lda, \ const T *X, const int incX, const T beta, \ T *Y, const int incY) { \ if (Order == BlasColMajor) { \ FUNC(&TransA, &M, &N, &alpha, A, &lda, X, &incX, \ &beta, Y, &incY); \ } \ else { \ BLAS_TRANSPOSE TransNew \ = TransA == BlasTrans ? BlasNoTrans : BlasTrans; \ FUNC(&TransNew, &N, &M, &alpha, A, &lda, X, &incX, \ &beta, Y, &incY); \ } \ } ADEPT_DEFINE_GEMV(double, dgemv_, zgemv_); ADEPT_DEFINE_GEMV(float, sgemv_, cgemv_); #undef ADEPT_DEFINE_GEMV // Matrix-matrix multiplication where matrix A is symmetric // FIX! CHECK ROW MAJOR VERSION IS RIGHT #define ADEPT_DEFINE_SYMM(T, FUNC, FUNC_COMPLEX) \ void cppblas_symm(const BLAS_ORDER Order, \ const BLAS_SIDE Side, \ const BLAS_UPLO Uplo, \ const int M, const int N, \ const T alpha, const T *A, const int lda, \ const T *B, const int ldb, const T beta, \ T *C, const int ldc) { \ if (Order == BlasColMajor) { \ FUNC(&Side, &Uplo, &M, &N, &alpha, A, &lda, \ B, &ldb, &beta, C, &ldc); \ } \ else { \ BLAS_SIDE SideNew = Side == BlasLeft ? BlasRight : BlasLeft; \ BLAS_UPLO UploNew = Uplo == BlasUpper ? BlasLower : BlasUpper; \ FUNC(&SideNew, &UploNew, &N, &M, &alpha, A, &lda, \ B, &ldb, &beta, C, &ldc); \ } \ } ADEPT_DEFINE_SYMM(double, dsymm_, zsymm_); ADEPT_DEFINE_SYMM(float, ssymm_, csymm_); #undef ADEPT_DEFINE_SYMM // Matrix-vector multiplication where the matrix is symmetric #define ADEPT_DEFINE_SYMV(T, FUNC, FUNC_COMPLEX) \ void cppblas_symv(const BLAS_ORDER Order, \ const BLAS_UPLO Uplo, \ const int N, const T alpha, const T *A, \ const int lda, const T *X, const int incX, \ const T beta, T *Y, const int incY) { \ if (Order == BlasColMajor) { \ FUNC(&Uplo, &N, &alpha, A, &lda, X, &incX, &beta, Y, &incY); \ } \ else { \ BLAS_UPLO UploNew = Uplo == BlasUpper ? BlasLower : BlasUpper; \ FUNC(&UploNew, &N, &alpha, A, &lda, X, &incX, &beta, Y, &incY); \ } \ } ADEPT_DEFINE_SYMV(double, dsymv_, zsymv_); ADEPT_DEFINE_SYMV(float, ssymv_, csymv_); #undef ADEPT_DEFINE_SYMV // Matrix-vector multiplication for a general band matrix #define ADEPT_DEFINE_GBMV(T, FUNC, FUNC_COMPLEX) \ void cppblas_gbmv(const BLAS_ORDER Order, \ const BLAS_TRANSPOSE TransA, \ const int M, const int N, \ const int KL, const int KU, const T alpha,\ const T *A, const int lda, const T *X, \ const int incX, const T beta, T *Y, \ const int incY) { \ if (Order == BlasColMajor) { \ FUNC(&TransA, &M, &N, &KL, &KU, &alpha, A, &lda, \ X, &incX, &beta, Y, &incY); \ } \ else { \ BLAS_TRANSPOSE TransNew \ = TransA == BlasTrans ? BlasNoTrans : BlasTrans; \ FUNC(&TransNew, &N, &M, &KU, &KL, &alpha, A, &lda, \ X, &incX, &beta, Y, &incY); \ } \ } ADEPT_DEFINE_GBMV(double, dgbmv_, zgbmv_); ADEPT_DEFINE_GBMV(float, sgbmv_, cgbmv_); #undef ADEPT_DEFINE_GBMV } // End namespace internal } // End namespace adept #else // Don't have BLAS namespace adept { namespace internal { // Matrix-matrix multiplication for general dense matrices #define ADEPT_DEFINE_GEMM(T, FUNC, FUNC_COMPLEX) \ void cppblas_gemm(BLAS_ORDER Order, \ BLAS_TRANSPOSE TransA, \ BLAS_TRANSPOSE TransB, \ int M, int N, \ int K, T alpha, const T *A, \ int lda, const T *B, int ldb, \ T beta, T *C, int ldc) { \ throw feature_not_available("Cannot perform matrix-matrix multiplication because compiled without BLAS"); \ } ADEPT_DEFINE_GEMM(double, dgemm_, zgemm_); ADEPT_DEFINE_GEMM(float, sgemm_, cgemm_); #undef ADEPT_DEFINE_GEMM // Matrix-vector multiplication for a general dense matrix #define ADEPT_DEFINE_GEMV(T, FUNC, FUNC_COMPLEX) \ void cppblas_gemv(const BLAS_ORDER Order, \ const BLAS_TRANSPOSE TransA, \ const int M, const int N, \ const T alpha, const T *A, const int lda, \ const T *X, const int incX, const T beta, \ T *Y, const int incY) { \ throw feature_not_available("Cannot perform matrix-vector multiplication because compiled without BLAS"); \ } ADEPT_DEFINE_GEMV(double, dgemv_, zgemv_); ADEPT_DEFINE_GEMV(float, sgemv_, cgemv_); #undef ADEPT_DEFINE_GEMV // Matrix-matrix multiplication where matrix A is symmetric // FIX! CHECK ROW MAJOR VERSION IS RIGHT #define ADEPT_DEFINE_SYMM(T, FUNC, FUNC_COMPLEX) \ void cppblas_symm(const BLAS_ORDER Order, \ const BLAS_SIDE Side, \ const BLAS_UPLO Uplo, \ const int M, const int N, \ const T alpha, const T *A, const int lda, \ const T *B, const int ldb, const T beta, \ T *C, const int ldc) { \ throw feature_not_available("Cannot perform symmetric matrix-matrix multiplication because compiled without BLAS"); \ } ADEPT_DEFINE_SYMM(double, dsymm_, zsymm_); ADEPT_DEFINE_SYMM(float, ssymm_, csymm_); #undef ADEPT_DEFINE_SYMM // Matrix-vector multiplication where the matrix is symmetric #define ADEPT_DEFINE_SYMV(T, FUNC, FUNC_COMPLEX) \ void cppblas_symv(const BLAS_ORDER Order, \ const BLAS_UPLO Uplo, \ const int N, const T alpha, const T *A, \ const int lda, const T *X, const int incX, \ const T beta, T *Y, const int incY) { \ throw feature_not_available("Cannot perform symmetric matrix-vector multiplication because compiled without BLAS"); \ } ADEPT_DEFINE_SYMV(double, dsymv_, zsymv_); ADEPT_DEFINE_SYMV(float, ssymv_, csymv_); #undef ADEPT_DEFINE_SYMV // Matrix-vector multiplication for a general band matrix #define ADEPT_DEFINE_GBMV(T, FUNC, FUNC_COMPLEX) \ void cppblas_gbmv(const BLAS_ORDER Order, \ const BLAS_TRANSPOSE TransA, \ const int M, const int N, \ const int KL, const int KU, const T alpha,\ const T *A, const int lda, const T *X, \ const int incX, const T beta, T *Y, \ const int incY) { \ throw feature_not_available("Cannot perform band matrix-vector multiplication because compiled without BLAS"); \ } ADEPT_DEFINE_GBMV(double, dgbmv_, zgbmv_); ADEPT_DEFINE_GBMV(float, sgbmv_, cgbmv_); #undef ADEPT_DEFINE_GBMV } } #endif // ================================================================= // Contents of index.cpp // ================================================================= /* index.cpp -- Definitions of "end" and "__" for array indexing Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <adept/RangeIndex.h> namespace adept { ::adept::internal::EndIndex end; ::adept::internal::AllIndex __; } // ================================================================= // Contents of inv.cpp // ================================================================= /* inv.cpp -- Invert matrices Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <vector> #include <adept/Array.h> #include <adept/SpecialMatrix.h> #ifndef AdeptSource_H #include "cpplapack.h" #endif #ifdef HAVE_LAPACK namespace adept { // ------------------------------------------------------------------- // Invert general square matrix A // ------------------------------------------------------------------- template <typename Type> Array<2,Type,false> inv(const Array<2,Type,false>& A) { using internal::cpplapack_getrf; using internal::cpplapack_getri; if (A.dimension(0) != A.dimension(1)) { //throw invalid_operation("Only square matrices can be inverted" // ADEPT_EXCEPTION_LOCATION); printf("invalid operation\n"); assert(false); } Array<2,Type,false> A_; // LAPACKE is more efficient with column-major input A_.resize_column_major(A.dimensions()); A_ = A; std::vector<lapack_int> ipiv(A_.dimension(0)); // lapack_int status = LAPACKE_dgetrf(LAPACK_COL_MAJOR, A_.dimension(0), A_.dimension(1), // A_.data(), A_.offset(1), &ipiv[0]); lapack_int status = cpplapack_getrf(A_.dimension(0), A_.data(), A_.offset(1), &ipiv[0]); if (status != 0) { std::stringstream s; s << "Failed to factorize matrix: LAPACK ?getrf returned code " << status; //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); printf("matrix ill conditioned\n"); assert(false); } // status = LAPACKE_dgetri(LAPACK_COL_MAJOR, A_.dimension(0), // A_.data(), A_.offset(1), &ipiv[0]); status = cpplapack_getri(A_.dimension(0), A_.data(), A_.offset(1), &ipiv[0]); if (status != 0) { std::stringstream s; s << "Failed to invert matrix: LAPACK ?getri returned code " << status; //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); printf("matrix ill conditioned\n"); assert(false); } return A_; } // ------------------------------------------------------------------- // Invert symmetric matrix A // ------------------------------------------------------------------- template <typename Type, SymmMatrixOrientation Orient> SpecialMatrix<Type,SymmEngine<Orient>,false> inv(const SpecialMatrix<Type,SymmEngine<Orient>,false>& A) { using internal::cpplapack_sytrf; using internal::cpplapack_sytri; SpecialMatrix<Type,SymmEngine<Orient>,false> A_; A_.resize(A.dimension()); A_ = A; // Treat symmetric matrix as column-major char uplo; if (Orient == ROW_LOWER_COL_UPPER) { uplo = 'U'; } else { uplo = 'L'; } std::vector<lapack_int> ipiv(A_.dimension(0)); // lapack_int status = LAPACKE_dsytrf(LAPACK_COL_MAJOR, uplo, A_.dimension(), // A_.data(), A_.offset(), &ipiv[0]); lapack_int status = cpplapack_sytrf(uplo, A_.dimension(), A_.data(), A_.offset(), &ipiv[0]); if (status != 0) { std::stringstream s; s << "Failed to factorize symmetric matrix: LAPACK ?sytrf returned code " << status; //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); printf("matrix ill conditioned\n"); assert(false); } // status = LAPACKE_dsytri(LAPACK_COL_MAJOR, uplo, A_.dimension(), // A_.data(), A_.offset(), &ipiv[0]); status = cpplapack_sytri(uplo, A_.dimension(), A_.data(), A_.offset(), &ipiv[0]); if (status != 0) { std::stringstream s; s << "Failed to invert symmetric matrix: LAPACK ?sytri returned code " << status; //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); printf("matrix ill conditioned\n"); assert(false); } return A_; } } #else // LAPACK not available namespace adept { // ------------------------------------------------------------------- // Invert general square matrix A // ------------------------------------------------------------------- template <typename Type> Array<2,Type,false> inv(const Array<2,Type,false>& A) { //throw feature_not_available("Cannot invert matrix because compiled without LAPACK"); printf("feature not available\n"); assert(false); } // ------------------------------------------------------------------- // Invert symmetric matrix A // ------------------------------------------------------------------- template <typename Type, SymmMatrixOrientation Orient> SpecialMatrix<Type,SymmEngine<Orient>,false> inv(const SpecialMatrix<Type,SymmEngine<Orient>,false>& A) { //throw feature_not_available("Cannot invert matrix because compiled without LAPACK"); printf("feature not available\n"); assert(false); } } #endif namespace adept { // ------------------------------------------------------------------- // Explicit instantiations // ------------------------------------------------------------------- #define ADEPT_EXPLICIT_INV(TYPE) \ template Array<2,TYPE,false> \ inv(const Array<2,TYPE,false>& A); \ template SpecialMatrix<TYPE,SymmEngine<ROW_LOWER_COL_UPPER>,false> \ inv(const SpecialMatrix<TYPE,SymmEngine<ROW_LOWER_COL_UPPER>,false>&); \ template SpecialMatrix<TYPE,SymmEngine<ROW_UPPER_COL_LOWER>,false> \ inv(const SpecialMatrix<TYPE,SymmEngine<ROW_UPPER_COL_LOWER>,false>&) ADEPT_EXPLICIT_INV(float); ADEPT_EXPLICIT_INV(double); #undef ADEPT_EXPLICIT_INV } // ================================================================= // Contents of jacobian.cpp // ================================================================= /* jacobian.cpp -- Computation of Jacobian matrix Copyright (C) 2012-2014 University of Reading Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #ifdef _OPENMP #include <omp.h> #endif #include "adept/Stack.h" #include "adept/Packet.h" #include "adept/traits.h" namespace adept { namespace internal { static const int MULTIPASS_SIZE = ADEPT_REAL_PACKET_SIZE == 1 ? ADEPT_MULTIPASS_SIZE : ADEPT_REAL_PACKET_SIZE; } using namespace internal; template <typename T> T _check_long_double() { // The user may have requested Real to be of type "long double" by // specifying ADEPT_REAL_TYPE_SIZE=16. If the present system can // only support double then sizeof(long double) will be 8, but // Adept will not be emitting the best code for this, so it is // probably better to fail forcing the user to specify // ADEPT_REAL_TYPE_SIZE=8. ADEPT_STATIC_ASSERT(ADEPT_REAL_TYPE_SIZE != 16 || ADEPT_REAL_TYPE_SIZE == sizeof(Real), COMPILER_DOES_NOT_SUPPORT_16_BYTE_LONG_DOUBLE); return 1; } /* void Stack::jacobian_forward_kernel(Real* gradient_multipass_b) const { static const int MULTIPASS_SIZE = Packet<Real>::size; // Loop forward through the derivative statements for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; // We copy the LHS to "a" in case it appears on the RHS in any // of the following statements Block<MULTIPASS_SIZE,Real> a; // Initialized to zero automatically // Loop through operations for (uIndex iop = statement_[ist-1].end_plus_one; iop < statement.end_plus_one; iop++) { Real* __restrict grad = gradient_multipass_b+index_[iop]*MULTIPASS_SIZE; // Loop through columns within this block; we hope the // compiler can optimize this loop. Note that it is faster // to always use MULTIPASS_SIZE, always known at // compile time, than to use block_size, which is not, even // though in the last iteration this may involve redundant // computations. if (multiplier_[iop] == 1.0) { // if (__builtin_expect(multiplier_[iop] == 1.0,0)) { for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { // for (uIndex i = 0; i < block_size; i++) { a[i] += grad[i]; } } else { for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { // for (uIndex i = 0; i < block_size; i++) { a[i] += multiplier_[iop]*grad[i]; } } } // Copy the results for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { gradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i]; } } // End of loop over statements } */ #if ADEPT_REAL_PACKET_SIZE > 1 void Stack::jacobian_forward_kernel(Real* __restrict gradient_multipass_b) const { // Loop forward through the derivative statements for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; // We copy the LHS to "a" in case it appears on the RHS in any // of the following statements Packet<Real> a; // Zeroed automatically // Loop through operations for (uIndex iop = statement_[ist-1].end_plus_one; iop < statement.end_plus_one; iop++) { Packet<Real> g(gradient_multipass_b+index_[iop]*MULTIPASS_SIZE); Packet<Real> m(multiplier_[iop]); a += m * g; } // Copy the results a.put(gradient_multipass_b+statement.index*MULTIPASS_SIZE); } // End of loop over statements } #else void Stack::jacobian_forward_kernel(Real* __restrict gradient_multipass_b) const { // Loop forward through the derivative statements for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; // We copy the LHS to "a" in case it appears on the RHS in any // of the following statements Block<MULTIPASS_SIZE,Real> a; // Zeroed automatically // Loop through operations for (uIndex iop = statement_[ist-1].end_plus_one; iop < statement.end_plus_one; iop++) { for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { a[i] += multiplier_[iop]*gradient_multipass_b[index_[iop]*MULTIPASS_SIZE+i]; } } // Copy the results for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { gradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i]; } } // End of loop over statements } #endif void Stack::jacobian_forward_kernel_extra(Real* __restrict gradient_multipass_b, uIndex n_extra) const { // Loop forward through the derivative statements for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; // We copy the LHS to "a" in case it appears on the RHS in any // of the following statements Block<MULTIPASS_SIZE,Real> a; // Zeroed automatically // Loop through operations for (uIndex iop = statement_[ist-1].end_plus_one; iop < statement.end_plus_one; iop++) { for (uIndex i = 0; i < n_extra; i++) { a[i] += multiplier_[iop]*gradient_multipass_b[index_[iop]*MULTIPASS_SIZE+i]; } } // Copy the results for (uIndex i = 0; i < n_extra; i++) { gradient_multipass_b[statement.index*MULTIPASS_SIZE+i] = a[i]; } } // End of loop over statements } // Compute the Jacobian matrix, parallelized using OpenMP. Normally // the user would call the jacobian or jacobian_forward functions, // and the OpenMP version would only be called if OpenMP is // available and the Jacobian matrix is large enough for // parallelization to be worthwhile. Note that jacobian_out must be // allocated to be of size m*n, where m is the number of dependent // variables and n is the number of independents. The independents // and dependents must have already been identified with the // functions "independent" and "dependent", otherwise this function // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the // resulting matrix, the "m" dimension of the matrix varies // fastest. This is implemented using a forward pass, appropriate // for m>=n. void Stack::jacobian_forward_openmp(Real* jacobian_out) const { // Number of blocks to cycle through, including a possible last // block containing fewer than MULTIPASS_SIZE variables int n_block = (n_independent() + MULTIPASS_SIZE - 1) / MULTIPASS_SIZE; uIndex n_extra = n_independent() % MULTIPASS_SIZE; int iblock; #pragma omp parallel { // std::vector<Block<MULTIPASS_SIZE,Real> > // gradient_multipass_b(max_gradient_); uIndex gradient_multipass_size = max_gradient_*MULTIPASS_SIZE; Real* __restrict gradient_multipass_b = alloc_aligned<Real>(gradient_multipass_size); #pragma omp for schedule(static) for (iblock = 0; iblock < n_block; iblock++) { // Set the index to the dependent variables for this block uIndex i_independent = MULTIPASS_SIZE * iblock; uIndex block_size = MULTIPASS_SIZE; // If this is the last iteration and the number of extra // elements is non-zero, then set the block size to the number // of extra elements. If the number of extra elements is zero, // then the number of independent variables is exactly divisible // by MULTIPASS_SIZE, so the last iteration will be the // same as all the rest. if (iblock == n_block-1 && n_extra > 0) { block_size = n_extra; } // Set the initial gradients all to zero for (std::size_t i = 0; i < gradient_multipass_size; i++) { gradient_multipass_b[i] = 0.0; } // Each seed vector has one non-zero entry of 1.0 for (uIndex i = 0; i < block_size; i++) { gradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0; } jacobian_forward_kernel(gradient_multipass_b); // Copy the gradients corresponding to the dependent variables // into the Jacobian matrix for (uIndex idep = 0; idep < n_dependent(); idep++) { for (uIndex i = 0; i < block_size; i++) { jacobian_out[(i_independent+i)*n_dependent()+idep] = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i]; } } } // End of loop over blocks free_aligned(gradient_multipass_b); } // End of parallel section } // End of jacobian function // Compute the Jacobian matrix; note that jacobian_out must be // allocated to be of size m*n, where m is the number of dependent // variables and n is the number of independents. The independents // and dependents must have already been identified with the // functions "independent" and "dependent", otherwise this function // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the // resulting matrix, the "m" dimension of the matrix varies // fastest. This is implemented using a forward pass, appropriate // for m>=n. void Stack::jacobian_forward(Real* jacobian_out) { if (independent_index_.empty() || dependent_index_.empty()) { //throw(dependents_or_independents_not_identified()); printf("dependents or independents not identified\n"); assert(false); } #ifdef _OPENMP if (have_openmp_ && !openmp_manually_disabled_ && n_independent() > MULTIPASS_SIZE && omp_get_max_threads() > 1) { // Call the parallel version jacobian_forward_openmp(jacobian_out); return; } #endif // For optimization reasons, we process a block of // MULTIPASS_SIZE columns of the Jacobian at once; calculate // how many blocks are needed and how many extras will remain uIndex n_block = n_independent() / MULTIPASS_SIZE; uIndex n_extra = n_independent() % MULTIPASS_SIZE; ///gradient_multipass_.resize(max_gradient_); uIndex gradient_multipass_size = max_gradient_*MULTIPASS_SIZE; Real* __restrict gradient_multipass_b = alloc_aligned<Real>(gradient_multipass_size); // Loop over blocks of MULTIPASS_SIZE columns for (uIndex iblock = 0; iblock < n_block; iblock++) { // Set the index to the dependent variables for this block uIndex i_independent = MULTIPASS_SIZE * iblock; // Set the initial gradients all to zero ///zero_gradient_multipass(); for (std::size_t i = 0; i < gradient_multipass_size; i++) { gradient_multipass_b[i] = 0.0; } // Each seed vector has one non-zero entry of 1.0 for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { gradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0; } jacobian_forward_kernel(gradient_multipass_b); // Copy the gradients corresponding to the dependent variables // into the Jacobian matrix for (uIndex idep = 0; idep < n_dependent(); idep++) { for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { jacobian_out[(i_independent+i)*n_dependent()+idep] = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i]; } } i_independent += MULTIPASS_SIZE; } // End of loop over blocks // Now do the same but for the remaining few columns in the matrix if (n_extra > 0) { uIndex i_independent = MULTIPASS_SIZE * n_block; ///zero_gradient_multipass(); for (std::size_t i = 0; i < gradient_multipass_size; i++) { gradient_multipass_b[i] = 0.0; } for (uIndex i = 0; i < n_extra; i++) { gradient_multipass_b[independent_index_[i_independent+i]*MULTIPASS_SIZE+i] = 1.0; } jacobian_forward_kernel_extra(gradient_multipass_b, n_extra); for (uIndex idep = 0; idep < n_dependent(); idep++) { for (uIndex i = 0; i < n_extra; i++) { jacobian_out[(i_independent+i)*n_dependent()+idep] = gradient_multipass_b[dependent_index_[idep]*MULTIPASS_SIZE+i]; } } } free_aligned(gradient_multipass_b); } // Compute the Jacobian matrix, parallelized using OpenMP. Normally // the user would call the jacobian or jacobian_reverse functions, // and the OpenMP version would only be called if OpenMP is // available and the Jacobian matrix is large enough for // parallelization to be worthwhile. Note that jacobian_out must be // allocated to be of size m*n, where m is the number of dependent // variables and n is the number of independents. The independents // and dependents must have already been identified with the // functions "independent" and "dependent", otherwise this function // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the // resulting matrix, the "m" dimension of the matrix varies // fastest. This is implemented using a reverse pass, appropriate // for m<n. void Stack::jacobian_reverse_openmp(Real* jacobian_out) const { // Number of blocks to cycle through, including a possible last // block containing fewer than MULTIPASS_SIZE variables int n_block = (n_dependent() + MULTIPASS_SIZE - 1) / MULTIPASS_SIZE; uIndex n_extra = n_dependent() % MULTIPASS_SIZE; int iblock; // Inside the OpenMP loop, the "this" pointer may be NULL if the // adept::Stack pointer is declared as thread-local and if the // OpenMP memory model uses thread-local storage for private // data. If this is the case then local pointers to or copies of // the following members of the adept::Stack object may need to be // made: dependent_index_ n_statements_ statement_ multiplier_ // index_ independent_index_ n_dependent() n_independent(). // Limited testing implies this is OK though. #pragma omp parallel { std::vector<Block<MULTIPASS_SIZE,Real> > gradient_multipass_b(max_gradient_); #pragma omp for schedule(static) for (iblock = 0; iblock < n_block; iblock++) { // Set the index to the dependent variables for this block uIndex i_dependent = MULTIPASS_SIZE * iblock; uIndex block_size = MULTIPASS_SIZE; // If this is the last iteration and the number of extra // elements is non-zero, then set the block size to the number // of extra elements. If the number of extra elements is zero, // then the number of independent variables is exactly divisible // by MULTIPASS_SIZE, so the last iteration will be the // same as all the rest. if (iblock == n_block-1 && n_extra > 0) { block_size = n_extra; } // Set the initial gradients all to zero for (std::size_t i = 0; i < gradient_multipass_b.size(); i++) { gradient_multipass_b[i].zero(); } // Each seed vector has one non-zero entry of 1.0 for (uIndex i = 0; i < block_size; i++) { gradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0; } // Loop backward through the derivative statements for (uIndex ist = n_statements_-1; ist > 0; ist--) { const Statement& statement = statement_[ist]; // We copy the RHS to "a" in case it appears on the LHS in any // of the following statements Real a[MULTIPASS_SIZE]; #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK // For large blocks, we only process the ones where a[i] is // non-zero uIndex i_non_zero[MULTIPASS_SIZE]; #endif uIndex n_non_zero = 0; for (uIndex i = 0; i < block_size; i++) { a[i] = gradient_multipass_b[statement.index][i]; gradient_multipass_b[statement.index][i] = 0.0; if (a[i] != 0.0) { #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK i_non_zero[n_non_zero++] = i; #else n_non_zero = 1; #endif } } // Only do anything for this statement if any of the a values // are non-zero if (n_non_zero) { // Loop through the operations for (uIndex iop = statement_[ist-1].end_plus_one; iop < statement.end_plus_one; iop++) { // Try to minimize pointer dereferencing by making local // copies Real multiplier = multiplier_[iop]; Real* __restrict gradient_multipass = &(gradient_multipass_b[index_[iop]][0]); #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK // For large blocks, loop over only the indices // corresponding to non-zero a for (uIndex i = 0; i < n_non_zero; i++) { gradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]]; } #else // For small blocks, do all indices for (uIndex i = 0; i < block_size; i++) { // for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { gradient_multipass[i] += multiplier*a[i]; } #endif } } } // End of loop over statement // Copy the gradients corresponding to the independent // variables into the Jacobian matrix for (uIndex iindep = 0; iindep < n_independent(); iindep++) { for (uIndex i = 0; i < block_size; i++) { jacobian_out[iindep*n_dependent()+i_dependent+i] = gradient_multipass_b[independent_index_[iindep]][i]; } } } // End of loop over blocks } // end #pragma omp parallel } // end jacobian_reverse_openmp // Compute the Jacobian matrix; note that jacobian_out must be // allocated to be of size m*n, where m is the number of dependent // variables and n is the number of independents. The independents // and dependents must have already been identified with the // functions "independent" and "dependent", otherwise this function // will fail with FAILURE_XXDEPENDENT_NOT_IDENTIFIED. In the // resulting matrix, the "m" dimension of the matrix varies // fastest. This is implemented using a reverse pass, appropriate // for m<n. void Stack::jacobian_reverse(Real* jacobian_out) { if (independent_index_.empty() || dependent_index_.empty()) { //throw(dependents_or_independents_not_identified()); printf("dependents or independents not identified\n"); assert(false); } #ifdef _OPENMP if (have_openmp_ && !openmp_manually_disabled_ && n_dependent() > MULTIPASS_SIZE && omp_get_max_threads() > 1) { // Call the parallel version jacobian_reverse_openmp(jacobian_out); return; } #endif // gradient_multipass_.resize(max_gradient_); std::vector<Block<MULTIPASS_SIZE,Real> > gradient_multipass_b(max_gradient_); // For optimization reasons, we process a block of // MULTIPASS_SIZE rows of the Jacobian at once; calculate // how many blocks are needed and how many extras will remain uIndex n_block = n_dependent() / MULTIPASS_SIZE; uIndex n_extra = n_dependent() % MULTIPASS_SIZE; uIndex i_dependent = 0; // uIndex of first row in the block we are // currently computing // Loop over the of MULTIPASS_SIZE rows for (uIndex iblock = 0; iblock < n_block; iblock++) { // Set the initial gradients all to zero // zero_gradient_multipass(); for (std::size_t i = 0; i < gradient_multipass_b.size(); i++) { gradient_multipass_b[i].zero(); } // Each seed vector has one non-zero entry of 1.0 for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { gradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0; } // Loop backward through the derivative statements for (uIndex ist = n_statements_-1; ist > 0; ist--) { const Statement& statement = statement_[ist]; // We copy the RHS to "a" in case it appears on the LHS in any // of the following statements Real a[MULTIPASS_SIZE]; #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK // For large blocks, we only process the ones where a[i] is // non-zero uIndex i_non_zero[MULTIPASS_SIZE]; #endif uIndex n_non_zero = 0; for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { a[i] = gradient_multipass_b[statement.index][i]; gradient_multipass_b[statement.index][i] = 0.0; if (a[i] != 0.0) { #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK i_non_zero[n_non_zero++] = i; #else n_non_zero = 1; #endif } } // Only do anything for this statement if any of the a values // are non-zero if (n_non_zero) { // Loop through the operations for (uIndex iop = statement_[ist-1].end_plus_one; iop < statement.end_plus_one; iop++) { // Try to minimize pointer dereferencing by making local // copies Real multiplier = multiplier_[iop]; Real* __restrict gradient_multipass = &(gradient_multipass_b[index_[iop]][0]); #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK // For large blocks, loop over only the indices // corresponding to non-zero a for (uIndex i = 0; i < n_non_zero; i++) { gradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]]; } #else // For small blocks, do all indices for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { gradient_multipass[i] += multiplier*a[i]; } #endif } } } // End of loop over statement // Copy the gradients corresponding to the independent variables // into the Jacobian matrix for (uIndex iindep = 0; iindep < n_independent(); iindep++) { for (uIndex i = 0; i < MULTIPASS_SIZE; i++) { jacobian_out[iindep*n_dependent()+i_dependent+i] = gradient_multipass_b[independent_index_[iindep]][i]; } } i_dependent += MULTIPASS_SIZE; } // End of loop over blocks // Now do the same but for the remaining few rows in the matrix if (n_extra > 0) { for (std::size_t i = 0; i < gradient_multipass_b.size(); i++) { gradient_multipass_b[i].zero(); } // zero_gradient_multipass(); for (uIndex i = 0; i < n_extra; i++) { gradient_multipass_b[dependent_index_[i_dependent+i]][i] = 1.0; } for (uIndex ist = n_statements_-1; ist > 0; ist--) { const Statement& statement = statement_[ist]; Real a[MULTIPASS_SIZE]; #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK uIndex i_non_zero[MULTIPASS_SIZE]; #endif uIndex n_non_zero = 0; for (uIndex i = 0; i < n_extra; i++) { a[i] = gradient_multipass_b[statement.index][i]; gradient_multipass_b[statement.index][i] = 0.0; if (a[i] != 0.0) { #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK i_non_zero[n_non_zero++] = i; #else n_non_zero = 1; #endif } } if (n_non_zero) { for (uIndex iop = statement_[ist-1].end_plus_one; iop < statement.end_plus_one; iop++) { Real multiplier = multiplier_[iop]; Real* __restrict gradient_multipass = &(gradient_multipass_b[index_[iop]][0]); // if (index_[iop] > max_gradient_-1 // || index_[iop] < 0) { // std::cerr << "AAAAAA: iop=" << iop << " index_[iop]=" << index_[iop] << " max_gradient_=" << max_gradient_ << " ist=" << ist << "\n"; // } #if MULTIPASS_SIZE > MULTIPASS_SIZE_ZERO_CHECK for (uIndex i = 0; i < n_non_zero; i++) { gradient_multipass[i_non_zero[i]] += multiplier*a[i_non_zero[i]]; } #else for (uIndex i = 0; i < n_extra; i++) { // std::cerr << "BBBBB: i=" << i << " gradient_multipass[i]=" << gradient_multipass[i] << " multiplier=" << multiplier << " a[i]=" << a[i] << "\n"; gradient_multipass[i] += multiplier*a[i]; } #endif } } } for (uIndex iindep = 0; iindep < n_independent(); iindep++) { for (uIndex i = 0; i < n_extra; i++) { jacobian_out[iindep*n_dependent()+i_dependent+i] = gradient_multipass_b[independent_index_[iindep]][i]; } } } } // Compute the Jacobian matrix; note that jacobian_out must be // allocated to be of size m*n, where m is the number of dependent // variables and n is the number of independents. In the resulting // matrix, the "m" dimension of the matrix varies fastest. This is // implemented by calling one of jacobian_forward and // jacobian_reverse, whichever would be faster. void Stack::jacobian(Real* jacobian_out) { // std::cout << ">>> Computing " << n_dependent() << "x" << n_independent() // << " Jacobian from " << n_statements_ << " statements, " // << n_operations() << " operations and " << max_gradient_ << " gradients\n"; if (n_independent() <= n_dependent()) { jacobian_forward(jacobian_out); } else { jacobian_reverse(jacobian_out); } } } // End namespace adept // ================================================================= // Contents of settings.cpp // ================================================================= /* settings.cpp -- View/change the overall Adept settings Copyright (C) 2016 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <sstream> #include <cstring> #include <adept/base.h> #include <adept/settings.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_OPENBLAS_CBLAS_HEADER #include <cblas.h> #endif namespace adept { // ------------------------------------------------------------------- // Get compile-time settings // ------------------------------------------------------------------- // Return the version of Adept at compile time std::string version() { return ADEPT_VERSION_STR; } // Return the compiler used to compile the Adept library (e.g. "g++ // [4.3.2]" or "Microsoft Visual C++ [1800]") std::string compiler_version() { #ifdef CXX std::string cv = CXX; // Defined in config.h #elif defined(_MSC_VER) std::string cv = "Microsoft Visual C++"; #else std::string cv = "unknown"; #endif #ifdef __GNUC__ #define STRINGIFY3(A,B,C) STRINGIFY(A) "." STRINGIFY(B) "." STRINGIFY(C) #define STRINGIFY(A) #A cv += " [" STRINGIFY3(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__) "]"; #undef STRINGIFY #undef STRINGIFY3 #elif defined(_MSC_VER) #define STRINGIFY1(A) STRINGIFY(A) #define STRINGIFY(A) #A cv += " [" STRINGIFY1(_MSC_VER) "]"; #undef STRINGIFY #undef STRINGIFY1 #endif return cv; } // Return the compiler flags used when compiling the Adept library // (e.g. "-Wall -g -O3") std::string compiler_flags() { #ifdef CXXFLAGS return CXXFLAGS; // Defined in config.h #else return "unknown"; #endif } // Return a multi-line string listing numerous aspects of the way // Adept has been configured. std::string configuration() { std::stringstream s; s << "Adept version " << adept::version() << ":\n"; s << " Compiled with " << adept::compiler_version() << "\n"; s << " Compiler flags \"" << adept::compiler_flags() << "\"\n"; #ifdef BLAS_LIBS if (std::strlen(BLAS_LIBS) > 2) { const char* blas_libs = BLAS_LIBS + 2; s << " BLAS support from " << blas_libs << " library\n"; } else { s << " BLAS support from built-in library\n"; } #endif #ifdef HAVE_OPENBLAS_CBLAS_HEADER s << " Number of BLAS threads may be specified up to maximum of " << max_blas_threads() << "\n"; #endif s << " Jacobians processed in blocks of size " << ADEPT_MULTIPASS_SIZE << "\n"; return s.str(); } // ------------------------------------------------------------------- // Get/set number of threads for array operations // ------------------------------------------------------------------- // Get the maximum number of threads available for BLAS operations int max_blas_threads() { #ifdef HAVE_OPENBLAS_CBLAS_HEADER return openblas_get_num_threads(); #else return 1; #endif } // Set the maximum number of threads available for BLAS operations // (zero means use the maximum sensible number on the current // system), and return the number actually set. Note that OpenBLAS // uses pthreads and the Jacobian calculation uses OpenMP - this can // lead to inefficient behaviour so if you are computing Jacobians // then you may get better performance by setting the number of // array threads to one. int set_max_blas_threads(int n) { #ifdef HAVE_OPENBLAS_CBLAS_HEADER openblas_set_num_threads(n); return openblas_get_num_threads(); #else return 1; #endif } // Was the library compiled with matrix multiplication support (from // BLAS)? bool have_matrix_multiplication() { #ifdef HAVE_BLAS return true; #else return false; #endif } // Was the library compiled with linear algebra support (e.g. inv // and solve from LAPACK) bool have_linear_algebra() { #ifdef HAVE_LAPACK return true; #else return false; #endif } } // End namespace adept // ================================================================= // Contents of solve.cpp // ================================================================= /* solve.cpp -- Solve systems of linear equations using LAPACK Copyright (C) 2015-2016 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <vector> #include <adept/solve.h> #include <adept/Array.h> #include <adept/SpecialMatrix.h> // If ADEPT_SOURCE_H is defined then we are in a header file generated // from all the source files, so cpplapack.h will already have been // included #ifndef AdeptSource_H #include "cpplapack.h" #endif #ifdef HAVE_LAPACK namespace adept { // ------------------------------------------------------------------- // Solve Ax = b for general square matrix A // ------------------------------------------------------------------- template <typename T> Array<1,T,false> solve(const Array<2,T,false>& A, const Array<1,T,false>& b) { Array<2,T,false> A_; Array<1,T,false> b_; // LAPACKE is more efficient with column-major input // if (A.is_row_contiguous()) { A_.resize_column_major(A.dimensions()); A_ = A; // } // else { // A_.link(A); // } // if (b_.offset(0) != 0) { b_ = b; // } // else { // b_.link(b); // } std::vector<lapack_int> ipiv(A_.dimension(0)); // lapack_int status = LAPACKE_dgesv(LAPACK_COL_MAJOR, A_.dimension(0), 1, // A_.data(), A_.offset(1), &ipiv[0], // b_.data(), b_.dimension(0)); lapack_int status = cpplapack_gesv(A_.dimension(0), 1, A_.data(), A_.offset(1), &ipiv[0], b_.data(), b_.dimension(0)); if (status != 0) { std::stringstream s; s << "Failed to solve general system of equations: LAPACK ?gesv returned code " << status; //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); printf("matrix ill conditioned\n"); assert(false); } return b_; } // ------------------------------------------------------------------- // Solve AX = B for general square matrix A and rectangular matrix B // ------------------------------------------------------------------- template <typename T> Array<2,T,false> solve(const Array<2,T,false>& A, const Array<2,T,false>& B) { Array<2,T,false> A_; Array<2,T,false> B_; // LAPACKE is more efficient with column-major input // if (A.is_row_contiguous()) { A_.resize_column_major(A.dimensions()); A_ = A; // } // else { // A_.link(A); // } // if (B.is_row_contiguous()) { B_.resize_column_major(B.dimensions()); B_ = B; // } // else { // B_.link(B); // } std::vector<lapack_int> ipiv(A_.dimension(0)); // lapack_int status = LAPACKE_dgesv(LAPACK_COL_MAJOR, A_.dimension(0), B.dimension(1), // A_.data(), A_.offset(1), &ipiv[0], // B_.data(), B_.offset(1)); lapack_int status = cpplapack_gesv(A_.dimension(0), B.dimension(1), A_.data(), A_.offset(1), &ipiv[0], B_.data(), B_.offset(1)); if (status != 0) { std::stringstream s; s << "Failed to solve general system of equations for matrix RHS: LAPACK ?gesv returned code " << status; //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); printf("matrix ill conditioned\n"); assert(false); } return B_; } // ------------------------------------------------------------------- // Solve Ax = b for symmetric square matrix A // ------------------------------------------------------------------- template <typename T, SymmMatrixOrientation Orient> Array<1,T,false> solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A, const Array<1,T,false>& b) { SpecialMatrix<T,SymmEngine<Orient>,false> A_; Array<1,T,false> b_; // Not sure why the original code copies A... A_.resize(A.dimension()); A_ = A; // A_.link(A); // if (b.offset(0) != 1) { b_ = b; // } // else { // b_.link(b); // } // Treat symmetric matrix as column-major char uplo; if (Orient == ROW_LOWER_COL_UPPER) { uplo = 'U'; } else { uplo = 'L'; } std::vector<lapack_int> ipiv(A_.dimension()); // lapack_int status = LAPACKE_dsysv(LAPACK_COL_MAJOR, uplo, A_.dimension(0), 1, // A_.data(), A_.offset(), &ipiv[0], // b_.data(), b_.dimension(0)); lapack_int status = cpplapack_sysv(uplo, A_.dimension(0), 1, A_.data(), A_.offset(), &ipiv[0], b_.data(), b_.dimension(0)); if (status != 0) { // std::stringstream s; // s << "Failed to solve symmetric system of equations: LAPACK ?sysv returned code " << status; // throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); std::cerr << "Warning: LAPACK solve symmetric system failed (?sysv): trying general (?gesv)\n"; return solve(Array<2,T,false>(A_),b_); } return b_; } // ------------------------------------------------------------------- // Solve AX = B for symmetric square matrix A // ------------------------------------------------------------------- template <typename T, SymmMatrixOrientation Orient> Array<2,T,false> solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A, const Array<2,T,false>& B) { SpecialMatrix<T,SymmEngine<Orient>,false> A_; Array<2,T,false> B_; A_.resize(A.dimension()); A_ = A; // A_.link(A); // if (B.is_row_contiguous()) { B_.resize_column_major(B.dimensions()); B_ = B; // } // else { // B_.link(B); // } // Treat symmetric matrix as column-major char uplo; if (Orient == ROW_LOWER_COL_UPPER) { uplo = 'U'; } else { uplo = 'L'; } std::vector<lapack_int> ipiv(A_.dimension()); // lapack_int status = LAPACKE_dsysv(LAPACK_COL_MAJOR, uplo, A_.dimension(0), B.dimension(1), // A_.data(), A_.offset(), &ipiv[0], // B_.data(), B_.offset(1)); lapack_int status = cpplapack_sysv(uplo, A_.dimension(0), B.dimension(1), A_.data(), A_.offset(), &ipiv[0], B_.data(), B_.offset(1)); if (status != 0) { std::stringstream s; s << "Failed to solve symmetric system of equations with matrix RHS: LAPACK ?sysv returned code " << status; //throw(matrix_ill_conditioned(s.str() ADEPT_EXCEPTION_LOCATION)); printf("matrix ill conditioned\n"); assert(false); } return B_; } } #else namespace adept { // ------------------------------------------------------------------- // Solve Ax = b for general square matrix A // ------------------------------------------------------------------- template <typename T> Array<1,T,false> solve(const Array<2,T,false>& A, const Array<1,T,false>& b) { //throw feature_not_available("Cannot solve linear equations because compiled without LAPACK"); printf("feature not available\n"); assert(false); } // ------------------------------------------------------------------- // Solve AX = B for general square matrix A and rectangular matrix B // ------------------------------------------------------------------- template <typename T> Array<2,T,false> solve(const Array<2,T,false>& A, const Array<2,T,false>& B) { //throw feature_not_available("Cannot solve linear equations because compiled without LAPACK"); printf("feature not available\n"); assert(false); } // ------------------------------------------------------------------- // Solve Ax = b for symmetric square matrix A // ------------------------------------------------------------------- template <typename T, SymmMatrixOrientation Orient> Array<1,T,false> solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A, const Array<1,T,false>& b) { //throw feature_not_available("Cannot solve linear equations because compiled without LAPACK"); printf("feature not available\n"); assert(false); } // ------------------------------------------------------------------- // Solve AX = B for symmetric square matrix A // ------------------------------------------------------------------- template <typename T, SymmMatrixOrientation Orient> Array<2,T,false> solve(const SpecialMatrix<T,SymmEngine<Orient>,false>& A, const Array<2,T,false>& B) { //throw feature_not_available("Cannot solve linear equations because compiled without LAPACK"); printf("feature not available\n"); assert(false); } } #endif namespace adept { // ------------------------------------------------------------------- // Explicit instantiations // ------------------------------------------------------------------- #define ADEPT_EXPLICIT_SOLVE(TYPE,RRANK) \ template Array<RRANK,TYPE,false> \ solve(const Array<2,TYPE,false>& A, const Array<RRANK,TYPE,false>& b); \ template Array<RRANK,TYPE,false> \ solve(const SpecialMatrix<TYPE,SymmEngine<ROW_LOWER_COL_UPPER>,false>& A, \ const Array<RRANK,TYPE,false>& b); \ template Array<RRANK,TYPE,false> \ solve(const SpecialMatrix<TYPE,SymmEngine<ROW_UPPER_COL_LOWER>,false>& A, \ const Array<RRANK,TYPE,false>& b); ADEPT_EXPLICIT_SOLVE(float,1) ADEPT_EXPLICIT_SOLVE(float,2) ADEPT_EXPLICIT_SOLVE(double,1) ADEPT_EXPLICIT_SOLVE(double,2) #undef ADEPT_EXPLICIT_SOLVE } // ================================================================= // Contents of vector_utilities.cpp // ================================================================= /* vector_utilities.cpp -- Vector utility functions Copyright (C) 2016 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <adept/vector_utilities.h> namespace adept { Array<1,Real,false> linspace(Real x1, Real x2, Index n) { Array<1,Real,false> ans(n); if (n > 1) { for (Index i = 0; i < n; ++i) { ans(i) = x1 + (x2-x1)*i / static_cast<Real>(n-1); } } else if (n == 1 && x1 == x2) { ans(0) = x1; return ans; } else if (n == 1) { //throw(invalid_operation("linspace(x1,x2,n) with n=1 only valid if x1=x2")); printf("invalid operation\n"); assert(false); } return ans; } } #endif
{ "alphanum_fraction": 0.6181001004, "avg_line_length": 32.5294535131, "ext": "h", "hexsha": "e1abf1a0e86440a7c68f2f19aa860a19d1862d57", "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": "f6c4312dfec9a014c9db2e8d1c875476880dc363", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "timkaler/ligra-gcn", "max_forks_repo_path": "apps_enzymetest/adept-serial/include/adept_source.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6c4312dfec9a014c9db2e8d1c875476880dc363", "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": "timkaler/ligra-gcn", "max_issues_repo_path": "apps_enzymetest/adept-serial/include/adept_source.h", "max_line_length": 161, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6c4312dfec9a014c9db2e8d1c875476880dc363", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "timkaler/ligra-gcn", "max_stars_repo_path": "apps_enzymetest/adept-serial/include/adept_source.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 24474, "size": 91668 }
#include "stdlib.h" #include "stdio.h" #include "/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h" #include <gsl/gsl_sf.h> int main(int argc, const char * argv[]) { unsigned long int hexdouble; unsigned int a; a = atoi(argv[1]); double result = gsl_sf_airy_zero_Ai(a); //printf("%.15f\n", result); VALGRIND_PRINT_VALUES("result", 1, &result); return 0; }
{ "alphanum_fraction": 0.7211796247, "avg_line_length": 28.6923076923, "ext": "c", "hexsha": "cf3444e4a5cae897a1013f7a296beee57372fcfb", "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": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "floatfeather/FpGenetic", "max_forks_repo_path": "others/sf/gsl_sf_airy_zero_Ai.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "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": "floatfeather/FpGenetic", "max_issues_repo_path": "others/sf/gsl_sf_airy_zero_Ai.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "floatfeather/FpGenetic", "max_stars_repo_path": "others/sf/gsl_sf_airy_zero_Ai.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 114, "size": 373 }
/* roots/secant.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* secant.c -- secant root finding algorithm The secant algorithm is a variant of the Newton algorithm with the derivative term replaced by a numerical estimate from the last two function evaluations. x[i+1] = x[i] - f(x[i]) / f'_est where f'_est = (f(x[i]) - f(x[i-1])) / (x[i] - x[i-1]) The exact derivative is used for the initial value of f'_est. */ #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; double df; } secant_state_t; static int secant_init (void * vstate, gsl_function_fdf * fdf, double * root); static int secant_iterate (void * vstate, gsl_function_fdf * fdf, double * root); static int secant_init (void * vstate, gsl_function_fdf * fdf, double * root) { secant_state_t * state = (secant_state_t *) vstate; const double x = *root; GSL_FN_FDF_EVAL_F_DF (fdf, x, &(state->f), &(state->df)); return GSL_SUCCESS; } static int secant_iterate (void * vstate, gsl_function_fdf * fdf, double * root) { secant_state_t * state = (secant_state_t *) vstate; const double x = *root ; const double f = state->f; const double df = state->df; double x_new, f_new, df_new; if (state->df == 0.0) { GSL_ERROR("derivative is zero", GSL_EZERODIV); } x_new = x - (f / df); f_new = GSL_FN_FDF_EVAL_F(fdf, x_new) ; df_new = (f_new - f) / (x_new - x) ; *root = x_new ; state->f = f_new ; state->df = df_new ; if (!finite (f_new)) { GSL_ERROR ("function value is not finite", GSL_EBADFUNC); } if (!finite (df_new)) { GSL_ERROR ("derivative value is not finite", GSL_EBADFUNC); } return GSL_SUCCESS; } static const gsl_root_fdfsolver_type secant_type = {"secant", /* name */ sizeof (secant_state_t), &secant_init, &secant_iterate}; const gsl_root_fdfsolver_type * gsl_root_fdfsolver_secant = &secant_type;
{ "alphanum_fraction": 0.6739055498, "avg_line_length": 24.5847457627, "ext": "c", "hexsha": "c44eea59945de36829fbfb65365125eaab3f7b0a", "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/roots/secant.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/roots/secant.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/roots/secant.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": 832, "size": 2901 }
#ifndef _COGOPTIMIZER_H_ #define _COGOPTIMIZER_H_ #include <gsl/gsl_math.h> #include <gsl/gsl_multimin.h> class GP; class CGOptimizer { public: CGOptimizer(void *gp); void Initialize(const Col<REAL> &init, double (*f_eval)(const gsl_vector*, void*), void (*df_eval)(const gsl_vector*, void*, gsl_vector*), void (*fdf_eval)(const gsl_vector*, void*, double*, gsl_vector*), double step=10.0, double eps=0.1); int Optimize(Col<REAL> &soln, int max_iterations=10); private: void *gp; const gsl_multimin_fdfminimizer_type *T; gsl_multimin_fdfminimizer *s; gsl_multimin_function_fdf my_func; gsl_vector *x; }; #endif
{ "alphanum_fraction": 0.7123287671, "avg_line_length": 21.1935483871, "ext": "h", "hexsha": "527d5bad9548add0dd17f3eeb4e7a54a52802fa5", "lang": "C", "max_forks_count": 25, "max_forks_repo_forks_event_max_datetime": "2022-03-15T15:01:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-28T23:03:17.000Z", "max_forks_repo_head_hexsha": "0015c066521b9412ebac4cda11559e44094ffdd9", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "RobustFieldAutonomyLab/GP", "max_forks_repo_path": "src/CGOptimizer.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "0015c066521b9412ebac4cda11559e44094ffdd9", "max_issues_repo_issues_event_max_datetime": "2015-08-05T14:31:01.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-02T12:19:12.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "RobustFieldAutonomyLab/GP", "max_issues_repo_path": "src/CGOptimizer.h", "max_line_length": 69, "max_stars_count": 41, "max_stars_repo_head_hexsha": "0015c066521b9412ebac4cda11559e44094ffdd9", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "jonfink/GP", "max_stars_repo_path": "src/CGOptimizer.h", "max_stars_repo_stars_event_max_datetime": "2022-03-25T00:59:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-02T12:20:54.000Z", "num_tokens": 198, "size": 657 }
/* This file is a part of NNTL project (https://github.com/Arech/nntl) Copyright (c) 2015-2021, Arech (aradvert@gmail.com; https://github.com/Arech) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NNTL 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. */ #pragma once #include <cblas.h> //TODO: function definitions (like dgemm()) conflicts with similar function definitions in ACML. It builds successfully, but //links to wrong library and access violation happens in run-time. #include <complex> #define lapack_complex_float ::std::complex<float> #define lapack_complex_double ::std::complex<double> #include <lapacke.h> //#include "../../../utils/denormal_floats.h" #pragma comment(lib,"libopenblas.dll.a") //what else to do to use OpenBLAS: // -in the Solution's VC++ Directories property page set parameter Library Directories to point to a folder with the libopenblas.dll.a file // -copy correct libopenblas.dll and another dlls that the libopenblas.dll require to the debug/release solution's folder // -if you're going to use any calling convetion except for __cdecl, then most likely, you'll have to update function declarations // within the cblas.h and other blas's .h files included to contain the __cdecl keyword (it's absent for some reason). // Check the b_OpenBLAS:: methods to find out which function definitions should be changed. //http://www.christophlassner.de/using-blas-from-c-with-row-major-data.html // BTW: lda,ldb,ldc is a "major stride". The stride represents the distance in memory between elements in adjacent rows // (if row-major) or in adjacent columns (if column-major). This means that the stride is usually equal to the number // of rows/columns in the matrix. // Matrix A = [1 2 3] // [4 5 6] // Row-major stores values as {1,2,3,4,5,6} Stride here is 3 // Col-major stores values as {1,4,2,5,3,6} Stride here is 2 // (https://www.physicsforums.com/threads/understanding-blas-dgemm-in-c.543110/) namespace nntl { namespace math { // wrapper around BLAS API. Should at least isolate from double/float differences // Also, we are going to use ColMajor ordering in all math libraries (most of them use it by default) // EXPECTING data to be in COL-MAJOR mode! // // NB: Leading dimension is the number of elements in major dimension. We're using Col-Major ordering, // therefore it is the number of ROWs of a matrix struct b_OpenBLAS { private: typedef utils::_scoped_restore_FPU _restoreFPU; public: //TODO: beware that sz_t type used as substitution of blasint can overflow blasint and silencing conversion warnings here can make it difficult to debug! //TODO: May be there should be some preliminary check for this condition. ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // LEVEL 1 // AXPY y=a*x+y template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value > axpy( const sz_t n, const fl_t alpha, const fl_t *x, const sz_t incx, fl_t *y, const sz_t incy) { _restoreFPU r; cblas_daxpy(static_cast<blasint>(n), alpha, x, static_cast<blasint>(incx), y, static_cast<blasint>(incy)); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value > axpy( const sz_t n, const fl_t alpha, const fl_t *x, const sz_t incx, fl_t *y, const sz_t incy) { _restoreFPU r; cblas_saxpy(static_cast<blasint>(n), alpha, x, static_cast<blasint>(incx), y, static_cast<blasint>(incy)); } ////////////////////////////////////////////////////////////////////////// // cblas_?dot // Computes a vector - vector dot product. // Input Parameters // n - Specifies the number of elements in vectors x and y. // x - Array, size at least(1 + (n - 1)*abs(incx)). // incx - Specifies the increment for the elements of x. // y - Array, size at least(1 + (n - 1)*abs(incy)). // incy - Specifies the increment for the elements of y. // Return Values - The result of the dot product of x and y, if n is positive.Otherwise, returns 0. //https://software.intel.com/en-us/mkl-developer-reference-c-cblas-dot template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value, double > dot(const sz_t n, const fl_t *x, const sz_t incx, const fl_t *y, const sz_t incy) { _restoreFPU r; return cblas_ddot(static_cast<blasint>(n), x, static_cast<blasint>(incx), y, static_cast<blasint>(incy)); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value, float > dot(const sz_t n, const fl_t *x, const sz_t incx, const fl_t *y, const sz_t incy) { _restoreFPU r; return cblas_sdot(static_cast<blasint>(n), x, static_cast<blasint>(incx), y, static_cast<blasint>(incy)); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // LEVEL 2 ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // LEVEL 3 // ////////////////////////////////////////////////////////////////////////// // General matrix multiplication // GEMM C := alpha*op(A)*op(B) + beta*C // https://software.intel.com/en-us/node/520775 // where: // op(X) is one of op(X) = X, or op(X) = XT, or op(X) = XH, // alpha and beta are scalars, // A, B and C are matrices : // op(A) is an m - by - k matrix, // op(B) is a k - by - n matrix, // C is an m - by - n matrix. // // M - Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero. // N - Specifies the number of columns of the matrix op(B) and the number of columns of the matrix C. The value of n must be at least zero. // K - Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). The value of k must be at least zero. // A - {transa=CblasNoTrans : Array, size lda*k. Before entry, the leading m-by-k part of the array a must contain the matrix A. // transa=CblasTrans : Array, size lda*m. Before entry, the leading k-by-m part of the array a must contain the matrix A.} // lda - Specifies the leading dimension of A as declared in the calling (sub)program. // {transa=CblasNoTrans, lda must be at least max(1, m). // transa=CblasTrans, lda must be at least max(1, k)} // B - {transb=CblasNoTrans : Array, size ldb by n. Before entry, the leading k-by-n part of the array b must contain the matrix B. // transb=CblasTrans : Array, size ldb by k. Before entry the leading n-by-k part of the array b must contain the matrix B.} // ldb - Specifies the leading dimension of B as declared in the calling (sub)program. // {transb = CblasNoTrans : ldb must be at least max(1, k). // transb=CblasTrans : ldb must be at least max(1, n).} // C - Array, size ldc by n. Before entry, the leading m-by-n part of the array c must contain the matrix C, except when beta is // equal to zero, in which case c need not be set on entry. // ldc - Specifies the leading dimension of c as declared in the calling (sub)program. ldc must be at least max(1, m). template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value > gemm( //const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const bool bTransposeA, const bool bTransposeB, const sz_t M, const sz_t N, const sz_t K, const fl_t alpha, const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc) { _restoreFPU r; cblas_dgemm(CblasColMajor, bTransposeA ? CblasTrans : CblasNoTrans, bTransposeB ? CblasTrans : CblasNoTrans, static_cast<blasint>(M), static_cast<blasint>(N), static_cast<blasint>(K), alpha, A, static_cast<blasint>(lda), B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc)); //global_denormalized_floats_mode(); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value > gemm( //const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const bool bTransposeA, const bool bTransposeB, const sz_t M, const sz_t N, const sz_t K, const fl_t alpha, const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc) { _restoreFPU r; cblas_sgemm(CblasColMajor, bTransposeA ? CblasTrans: CblasNoTrans, bTransposeB ? CblasTrans : CblasNoTrans, static_cast<blasint>(M), static_cast<blasint>(N), static_cast<blasint>(K), alpha, A, static_cast<blasint>(lda), B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc)); //global_denormalized_floats_mode(); } ////////////////////////////////////////////////////////////////////////// // cblas_?syrk, https://software.intel.com/en-us/node/520780 // Performs a symmetric rank-k update. // The ?syrk routines perform a rank-k matrix-matrix operation for a symmetric matrix C using a general matrix A. // The operation is defined as: // C := alpha*A*A' + beta*C, // or // C : = alpha*A'*A + beta*C, // where : // alpha and beta are scalars, // C is an n-by-n symmetric matrix, // A is an n-by-k matrix in the first case and a k-by-n matrix in the second case. template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value > syrk( const bool bCLowerTriangl, const bool bFirstATransposed, const sz_t N, const sz_t K, const fl_t alpha , const fl_t *A, const sz_t lda, const fl_t beta, fl_t *C, const sz_t ldc) { _restoreFPU r; cblas_dsyrk(CblasColMajor, bCLowerTriangl ? CblasLower : CblasUpper, bFirstATransposed ? CblasTrans : CblasNoTrans , static_cast<blasint>(N), static_cast<blasint>(K), alpha, A, static_cast<blasint>(lda), beta, C, static_cast<blasint>(ldc)); //global_denormalized_floats_mode(); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value > syrk(const bool bCLowerTriangl, const bool bFirstATransposed, const sz_t N, const sz_t K, const fl_t alpha , const fl_t *A, const sz_t lda, const fl_t beta, fl_t *C, const sz_t ldc) { _restoreFPU r; cblas_ssyrk(CblasColMajor, bCLowerTriangl ? CblasLower : CblasUpper, bFirstATransposed ? CblasTrans : CblasNoTrans , static_cast<blasint>(N), static_cast<blasint>(K), alpha, A, static_cast<blasint>(lda), beta, C, static_cast<blasint>(ldc)); //global_denormalized_floats_mode(); } ////////////////////////////////////////////////////////////////////////// // cblas_?symm, https://software.intel.com/en-us/node/520779 // Computes a matrix - matrix product where one input matrix is symmetric. // The ?symm routines compute a scalar-matrix-matrix product with one symmetric matrix and add the // result to a scalar-matrix product. The operation is defined as // C: = alpha*A*B + beta*C, // or // C : = alpha*B*A + beta*C, // where : // alpha and beta are scalars, // A is a symmetric matrix, // B and C are m - by - n matrices. template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value > symm(const bool bSymmAatLeft, const bool bALowerTriangl, const sz_t M, const sz_t N, const fl_t alpha , const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc) { _restoreFPU r; cblas_dsymm(CblasColMajor, bSymmAatLeft ? CblasLeft : CblasRight, bALowerTriangl ? CblasLower : CblasUpper , static_cast<blasint>(M), static_cast<blasint>(N), alpha, A, static_cast<blasint>(lda) , B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc)); //global_denormalized_floats_mode(); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value > symm(const bool bSymmAatLeft, const bool bALowerTriangl, const sz_t M, const sz_t N, const fl_t alpha , const fl_t *A, const sz_t lda, const fl_t *B, const sz_t ldb, const fl_t beta, fl_t *C, const sz_t ldc) { _restoreFPU r; cblas_ssymm(CblasColMajor, bSymmAatLeft ? CblasLeft : CblasRight, bALowerTriangl ? CblasLower : CblasUpper , static_cast<blasint>(M), static_cast<blasint>(N), alpha, A, static_cast<blasint>(lda) , B, static_cast<blasint>(ldb), beta, C, static_cast<blasint>(ldc)); //global_denormalized_floats_mode(); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // LAPACKE // ?gesvd // https://software.intel.com/en-us/node/521150 template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value, int> gesvd(/*int matrix_layout,*/ const char jobu, const char jobvt, const sz_t m, const sz_t n, fl_t* A, const sz_t lda, fl_t* S, fl_t* U, const sz_t ldu, fl_t* Vt, const sz_t ldvt, fl_t* superb) { _restoreFPU r; return static_cast<int>(LAPACKE_dgesvd(LAPACK_COL_MAJOR, jobu, jobvt, static_cast<lapack_int>(m), static_cast<lapack_int>(n) , A, static_cast<lapack_int>(lda), S, U, static_cast<lapack_int>(ldu), Vt, static_cast<lapack_int>(ldvt), superb)); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value, int> gesvd(/*int matrix_layout,*/ const char jobu, const char jobvt, const sz_t m, const sz_t n, fl_t* A, const sz_t lda, fl_t* S, fl_t* U, const sz_t ldu, fl_t* Vt, const sz_t ldvt, fl_t* superb) { _restoreFPU r; return static_cast<int>(LAPACKE_sgesvd(LAPACK_COL_MAJOR, jobu, jobvt, static_cast<lapack_int>(m), static_cast<lapack_int>(n) , A, static_cast<lapack_int>(lda), S, U, static_cast<lapack_int>(ldu), Vt, static_cast<lapack_int>(ldvt), superb)); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Extensions // The omatcopy routine performs scaling and out-of-place transposition/copying of matrices. A transposition // operation can be a normal matrix copy, a transposition, a conjugate transposition, or just a conjugation. // The operation is defined as follows: // B : = alpha*op(A) // // Parameters // rows - The number of rows in the source matrix. // cols - The number of columns in the source matrix. // alpha - This parameter scales the input matrix by alpha. // pA - Array. // lda - Distance between the first elements in adjacent columns(in the case of the column - major order) // or rows(in the case of the row - major order) in the source matrix; measured in the number of elements. // This parameter must be at least max(1, rows) if ordering = 'C' or 'c', and max(1, cols) otherwise. // b - Array. // ldb - Distance between the first elements in adjacent columns(in the case of the column - major order) // or rows(in the case of the row - major order) in the destination matrix; measured in the number of elements. // To determine the minimum value of ldb on output, consider the following guideline : // If ordering = 'C' or 'c', then // If trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1, cols) // If trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1, rows) // If ordering = 'R' or 'r', then // If trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1, rows) // If trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1, cols) // // #warning current OpenBLAS implementation is slower, than it can be. See TEST(TestPerfDecisions, mTranspose) in test_perf_decisions.cpp //and https://github.com/xianyi/OpenBLAS/issues/1243 // https://github.com/xianyi/OpenBLAS/issues/2532 // https://stackoverflow.com/questions/16737298/what-is-the-fastest-way-to-transpose-a-matrix-in-c/16743203#16743203 template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value > omatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha, const fl_t* pA, const sz_t lda, fl_t* pB, const sz_t ldb) { _restoreFPU r; cblas_domatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans, static_cast<blasint>(rows), static_cast<blasint>(cols), alpha, pA, static_cast<blasint>(lda), pB, static_cast<blasint>(ldb)); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value > omatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha, const fl_t* pA, const sz_t lda, fl_t* pB, const sz_t ldb) { _restoreFPU r; cblas_somatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans, static_cast<blasint>(rows), static_cast<blasint>(cols), alpha, pA, static_cast<blasint>(lda), pB, static_cast<blasint>(ldb)); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, double>::value > imatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha, fl_t* pA, const sz_t lda, const sz_t ldb) { _restoreFPU r; cblas_dimatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans, static_cast<blasint>(rows), static_cast<blasint>(cols), alpha, pA, static_cast<blasint>(lda), static_cast<blasint>(ldb)); } template<typename sz_t, typename fl_t> static typename ::std::enable_if_t< ::std::is_same< ::std::remove_pointer_t<fl_t>, float>::value > imatcopy(const bool bTranspose, const sz_t rows, const sz_t cols, const fl_t alpha, fl_t* pA, const sz_t lda, const sz_t ldb) { _restoreFPU r; cblas_simatcopy(CblasColMajor, bTranspose ? CblasTrans : CblasNoTrans, static_cast<blasint>(rows), static_cast<blasint>(cols), alpha, pA, static_cast<blasint>(lda), static_cast<blasint>(ldb)); } }; } }
{ "alphanum_fraction": 0.6642867694, "avg_line_length": 54.7412398922, "ext": "h", "hexsha": "7ee5d5aaa1f71f31b636368f557dda80c62f1e4a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-10-15T11:12:33.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-15T11:12:33.000Z", "max_forks_repo_head_hexsha": "fdcd7f33216c6414547acea3c4c172734ef9412a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Arech/nntl", "max_forks_repo_path": "nntl/interface/math/bindings/b_open_blas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fdcd7f33216c6414547acea3c4c172734ef9412a", "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": "Arech/nntl", "max_issues_repo_path": "nntl/interface/math/bindings/b_open_blas.h", "max_line_length": 156, "max_stars_count": 12, "max_stars_repo_head_hexsha": "fdcd7f33216c6414547acea3c4c172734ef9412a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Arech/nntl", "max_stars_repo_path": "nntl/interface/math/bindings/b_open_blas.h", "max_stars_repo_stars_event_max_datetime": "2020-05-28T13:10:19.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-22T19:55:56.000Z", "num_tokens": 5755, "size": 20309 }
#pragma once #include <gsl-lite/gsl-lite.hpp> #include <cuda/define_specifiers.hpp> #include <cuda/runtime_api.hpp> #include <thrustshift/math.h> namespace thrustshift { namespace device_function { namespace explicit_unroll { /*! \brief Fill range of length `N` with `x`. * * \param N length of the range * \param p pointer to the range * \param x value * \param tid ID of the thread which enters the function * \param num_threads total amount of threads which enter the function */ template <typename T, int num_threads, int N> CUDA_FD void fill(T* p, T x, int tid) { constexpr int num_elements_per_thread = N / num_threads; #pragma unroll for (int i = 0; i < num_elements_per_thread; ++i) { p[i * num_threads + tid] = x; } constexpr int num_rest = N % num_threads; if (tid < num_rest) { p[num_elements_per_thread * num_threads + tid] = x; } } } // namespace explicit_unroll namespace implicit_unroll { template <typename T0, typename T1, typename I0, typename I1, typename I2> CUDA_FD void fill(T0* p, T1 x, I0 tid, I1 num_threads, I2 N) { auto num_elements_per_thread = N / num_threads; #pragma unroll for (int i = 0; i < num_elements_per_thread; ++i) { p[i * num_threads + tid] = x; } auto num_rest = N % num_threads; if (tid < num_rest) { p[num_elements_per_thread * num_threads + tid] = x; } } } // namespace implicit_unroll } // namespace device_function namespace kernel { template <typename T, class Range> __global__ void fill(Range r, T val) { const auto gtid = threadIdx.x + blockIdx.x * blockDim.x; if (gtid < r.size()) { r[gtid] = val; } } } // namespace kernel namespace async { template <typename T, class Range> void fill(cuda::stream_t& stream, Range&& r, T val) { constexpr cuda::grid::block_dimension_t block_dim = 256; const cuda::grid::dimension_t grid_dim = ceil_divide(r.size(), gsl_lite::narrow<decltype(r.size())>(block_dim)); using RangeT = typename std::remove_reference<Range>::type::value_type; if (!r.empty()) { cuda::enqueue_launch(kernel::fill<T, gsl_lite::span<RangeT>>, stream, cuda::make_launch_config(grid_dim, block_dim), r, val); } } } // namespace async } // namespace thrustshift
{ "alphanum_fraction": 0.673380035, "avg_line_length": 24.5591397849, "ext": "h", "hexsha": "85b293d17e1d3b76bed2786b635dddbf7d640cd7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_path": "include/thrustshift/fill.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_path": "include/thrustshift/fill.h", "max_line_length": 76, "max_stars_count": 1, "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_path": "include/thrustshift/fill.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "num_tokens": 607, "size": 2284 }
/** * Simple and fast kmeans-implementation making use of multithreading. * * Author: Anders Bennehag * * The MIT License (MIT) * * Copyright (c) 2016 Anders Bennehag * */ #ifndef FASTKMEANS_H_ #define FASTKMEANS_H_ #include <gsl/gsl_matrix.h> int fkm_kmeans(const gsl_matrix* points, gsl_matrix* clusters, size_t max_iter, int num_threads); gsl_matrix* fkm_matrix_load(FILE* fout); int fkm_matrix_save(FILE* fout, gsl_matrix* mat); #define WHERESTR "[%s:%d]: " #define WHEREARG __FILE__, __LINE__ #define DEBUGPRINT2(...) fprintf(stderr, __VA_ARGS__) #define FKM_LOGFMT(_fmt, ...) DEBUGPRINT2(WHERESTR _fmt "\n", WHEREARG, __VA_ARGS__) #define FKM_LOG(_s) DEBUGPRINT2(WHERESTR "%s\n", WHEREARG, _s) #define FKM_LOGTYPE(_tp, _s) DEBUGPRINT2(WHERESTR "%s: %s" "\n", WHEREARG, _tp, _s) #define FKM_LOGTYPEFMT(_tp, _fmt, ...) DEBUGPRINT2(WHERESTR "%s: " _fmt "\n", WHEREARG, _tp, __VA_ARGS__) #if (ISDEBUG + 0) #define FKM_DEBUGFMT(_fmt, ...) FKM_LOGTYPEFMT("DEBUG", _fmt, __VA_ARGS__) #define FKM_DEBUG(_s) FKM_LOGTYPE("DEBUG", _s) #else #define FKM_DEBUGFMT(...) #define FKM_DEBUG(...) #endif #define FKM_INFOFMT(_fmt, ...) FKM_LOGTYPEFMT("INFO", _fmt, __VA_ARGS__) #define FKM_WARNFMT(_fmt, ...) FKM_LOGTYPEFMT("WARN", _fmt, __VA_ARGS__) #define FKM_ERRORFMT(_fmt, ...) FKM_LOGTYPEFMT("ERROR", _fmt, __VA_ARGS__) #define FKM_INFO(_s) FKM_LOGTYPE("INFO", _s) #define FKM_WARN(_s) FKM_LOGTYPE("WARN", _s) #define FKM_ERROR(_s) FKM_LOGTYPE("ERROR", _s) #endif
{ "alphanum_fraction": 0.7013071895, "avg_line_length": 31.875, "ext": "h", "hexsha": "8d7b7bafd0d6c441be58d444e0797e2dfe427c17", "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": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "PureW/fast-kmeans", "max_forks_repo_path": "include/fastkmeans/fastkmeans.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "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": "PureW/fast-kmeans", "max_issues_repo_path": "include/fastkmeans/fastkmeans.h", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "PureW/fast-kmeans", "max_stars_repo_path": "include/fastkmeans/fastkmeans.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 500, "size": 1530 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" double cblas_ddot (const int N, const double *X, const int incX, const double *Y, const int incY) { #define INIT_VAL 0.0 #define ACC_TYPE double #define BASE double #include "source_dot_r.h" #undef ACC_TYPE #undef BASE #undef INIT_VAL }
{ "alphanum_fraction": 0.731629393, "avg_line_length": 18.4117647059, "ext": "c", "hexsha": "dd5d12ad2a9a9b07b50d561edd7134b2e6a9f5f6", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/ddot.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/ddot.c", "max_line_length": 74, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/ddot.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": 94, "size": 313 }
/* * Copyright 2020-2021 OpenDR European Project * * 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 SCANMATCHERPROCESSOR_H #define SCANMATCHERPROCESSOR_H #include <gmapping/log/sensorlog.h> #include <gmapping/sensor/sensor_range/rangereading.h> #include <gmapping/sensor/sensor_range/rangesensor.h> //#include <gsl/gsl_eigen.h> #include "gmapping/scanmatcher/scanmatcher.h" namespace GMapping { class ScanMatcherProcessor { public: ScanMatcherProcessor(const ScanMatcherMap &m); ScanMatcherProcessor(double xmin, double ymin, double xmax, double ymax, double delta, double patchdelta); virtual ~ScanMatcherProcessor(); virtual void processScan(const RangeReading &reading); void setSensorMap(const SensorMap &smap, std::string sensorName = "FLASER"); void init(); void setMatchingParameters(double urange, double range, double sigma, int kernsize, double lopt, double aopt, int iterations, bool computeCovariance = false); void setRegistrationParameters(double regScore, double critScore); OrientedPoint getPose() const; inline const ScanMatcherMap &getMap() const { return m_map; } inline ScanMatcher &matcher() { return m_matcher; } inline void setmaxMove(double mmove) { m_maxMove = mmove; } bool useICP; protected: ScanMatcher m_matcher; bool m_computeCovariance; bool m_first; SensorMap m_sensorMap; double m_regScore, m_critScore; unsigned int m_beams; double m_maxMove; // state ScanMatcherMap m_map; OrientedPoint m_pose; OrientedPoint m_odoPose; int m_count; // gsl_eigen_symmv_workspace * m_eigenspace; }; }; // namespace GMapping #endif
{ "alphanum_fraction": 0.7315105334, "avg_line_length": 29.3552631579, "ext": "h", "hexsha": "439fe9689d36cebdf488c9a74407460bbd8f4f09", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-12-12T16:18:47.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-04T07:38:50.000Z", "max_forks_repo_head_hexsha": "07dee3b59d3487b9c5a93d6946317178a02c9890", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "makistsantekidis/opendr", "max_forks_repo_path": "projects/perception/slam/full_map_posterior_gmapping/src/openslam_gmapping/include/gmapping/scanmatcher/scanmatcherprocessor.h", "max_issues_count": 79, "max_issues_repo_head_hexsha": "07dee3b59d3487b9c5a93d6946317178a02c9890", "max_issues_repo_issues_event_max_datetime": "2021-12-16T07:59:42.000Z", "max_issues_repo_issues_event_min_datetime": "2021-06-23T10:40:10.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "makistsantekidis/opendr", "max_issues_repo_path": "projects/perception/slam/full_map_posterior_gmapping/src/openslam_gmapping/include/gmapping/scanmatcher/scanmatcherprocessor.h", "max_line_length": 113, "max_stars_count": 3, "max_stars_repo_head_hexsha": "07dee3b59d3487b9c5a93d6946317178a02c9890", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "makistsantekidis/opendr", "max_stars_repo_path": "projects/perception/slam/full_map_posterior_gmapping/src/openslam_gmapping/include/gmapping/scanmatcher/scanmatcherprocessor.h", "max_stars_repo_stars_event_max_datetime": "2021-12-12T16:21:24.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-24T01:54:25.000Z", "num_tokens": 533, "size": 2231 }
/* ** Implementation of LISA algorithm ** for statistical inference of fMRI images ** ** 2nd level inference (one-sample test) ** ** G.Lohmann, 2017 */ #include <viaio/Vlib.h> #include <viaio/file.h> #include <viaio/mu.h> #include <viaio/option.h> #include <viaio/os.h> #include <viaio/VImage.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_histogram.h> #include <math.h> #include <stdio.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /*_OPENMP*/ #define ABS(x) ((x) > 0 ? (x) : -(x)) extern void VIsolatedVoxels(VImage src,float threshold); extern void VHistogram(gsl_histogram *histogram,VString filename); extern void VCheckImage(VImage src); extern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double); extern double ttest1(double *data1,int n); extern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax); extern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int); extern double VImageVar(VImage src); extern void VImageCount(VImage src); extern void VGetHistRange(VImage src,double *hmin,double *hmax); extern void VZScale(VImage src,float mode,float stddev); extern float VGetMode(VImage src); extern double t2z(double,double); extern void HistoUpdate(VImage,gsl_histogram *); /* generate permutation table */ int **genperm(gsl_rng *rx,int n,int numperm) { int i,j; int **table = (int **) VCalloc(numperm,sizeof(int *)); for (i = 0; i < numperm; i++) { table[i] = (int *) VCalloc(n,sizeof(int)); for (j=0; j<n; j++) { table[i][j] = 0; if (gsl_ran_bernoulli (rx,(double)0.5) == 1) table[i][j] = 1; } } return table; } /* onesample t-test */ void OnesampleTest(VImage *src1,VImage dest,int *permtable,int n) { int i,k,b,r,c,nslices,nrows,ncols; double nx,ave,var,u,t,z,df; double tiny=1.0e-8; extern void avevar(double *data,int n,double *a,double *v); nslices = VImageNBands(src1[0]); nrows = VImageNRows(src1[0]); ncols = VImageNColumns(src1[0]); VFillImage(dest,VAllBands,0); double *data = (double *) VCalloc(n,sizeof(double)); for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { k = 0; for (i=0; i<n; i++) { u = (double)VPixel(src1[i],b,r,c,VFloat); if (ABS(u) > tiny) { if (permtable[i] > 0) u = -u; data[k] = u; k++; } } if (k < n-2) continue; avevar(data,k,&ave,&var); if (var < tiny) continue; nx = (double)k; t = sqrt(nx) * ave/sqrt(var); df = nx - 1.0; z = t2z(t,df); if (t < 0) z = -z; VPixel(dest,b,r,c,VFloat) = z; } } } VFree(data); } int main (int argc, char *argv[]) { static VArgVector in_files1; static VString out_filename=""; static VString mask_filename=""; static VFloat alpha = 0.05; static VShort radius = 2; static VFloat rvar = 2.0; static VFloat svar = 2.0; static VShort numiter = 2; static VShort numperm = 5000; static VLong seed = 99402622; static VBoolean centering = FALSE; static VBoolean cleanup = TRUE; static VShort nproc = 0; static VOptionDescRec options[] = { {"in", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,"Input files" }, {"out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,"Output file" }, {"alpha",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,"FDR significance level"}, {"perm",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,"Number of permutations"}, {"mask", VStringRepn, 1, (VPointer) &mask_filename, VRequiredOpt, NULL, "Mask"}, {"seed",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,"Seed for random number generation"}, {"radius",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,"Bilateral parameter (radius in voxels)"}, {"rvar",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,"Bilateral parameter (radiometric)"}, {"svar",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,"Bilateral parameter (spatial)"}, {"filteriterations",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,"Bilateral parameter (number of iterations)"}, {"cleanup",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,"Whether to remove isloated voxels"}, {"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"}, }; FILE *fp=NULL; VString in_filename; VAttrList list1=NULL,out_list=NULL,geolist=NULL; VImage *src1; int i,nimages,npix=0; char *prg_name=GetLipsiaName("vlisa_onesample"); fprintf (stderr, "%s\n", prg_name); /* parse command line */ if (! VParseCommand (VNumber (options), options, & argc, argv)) { VReportUsage (argv[0], VNumber (options), options, NULL); exit (EXIT_FAILURE); } if (argc > 1) { VReportBadArgs (argc, argv); exit (EXIT_FAILURE); } /* omp-stuff */ #ifdef _OPENMP int num_procs=omp_get_num_procs(); if (nproc > 0 && nproc < num_procs) num_procs = nproc; fprintf(stderr," using %d cores\n",(int)num_procs); omp_set_num_threads(num_procs); #endif /* _OPENMP */ /* images */ VImage mask = VReadImageFile(mask_filename); if (mask==NULL) VError("Error reading mask file %s",mask_filename); nimages = in_files1.number; src1 = (VImage *) VCalloc(nimages,sizeof(VImage)); for (i = 0; i < nimages; i++) { in_filename = ((VString *) in_files1.vector)[i]; list1 = VReadAttrList(in_filename,0L,TRUE,FALSE); VMaskMinval(list1,mask,0.0); src1[i] = VReadImage(list1); if (src1[i] == NULL) VError(" no input image found"); if (VPixelRepn(src1[i]) != VFloatRepn) VError(" input pixel repn must be float"); if (i == 0) npix = VImageNPixels(src1[i]); else if (npix != VImageNPixels(src1[i])) VError(" inconsistent image dimensions"); /* use geometry info from 1st file */ if (geolist == NULL) { geolist = VGetGeoInfo(list1); double *D = VGetGeoPixdim(geolist,NULL); if (fabs(D[0]-4.0) < TINY) VError(" The input must be a list of separate 3D images, not one 4D file"); } } /* ini random permutations */ size_t n = nimages; gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *rx = gsl_rng_alloc(T); gsl_rng_set(rx,(unsigned long int)seed); int nperm=0; int **permtable = genperm(rx,(int)n,(int)numperm); /* estimate null variance based on first 30 permutations */ double hmin=0,hmax=0; float stddev=1.0; if (numperm > 0) { int tstperm = 30; if (tstperm > numperm) tstperm = numperm; double varsum=0,nx=0; #pragma omp parallel for shared(src1,permtable) schedule(dynamic) for (nperm = 0; nperm < tstperm; nperm++) { VImage zmap = VCreateImageLike(src1[0]); OnesampleTest(src1,zmap,permtable[nperm],nimages); #pragma omp critical { varsum += VImageVar(zmap); nx++; } VDestroyImage(zmap); } double meanvar = varsum/nx; stddev = sqrt(meanvar); } /* no permutation */ int *nopermtable = (int *) VCalloc(n,sizeof(int)); VImage dst1 = VCreateImageLike (src1[0]); VImage zmap1 = VCreateImageLike(src1[0]); OnesampleTest(src1,zmap1,nopermtable,nimages); if (numperm == 0) { double z = VImageVar(zmap1); stddev = (float)(sqrt(z)); /* update stddev */ } float mode=0; if (centering) mode = VGetMode(zmap1); if (numperm > 0) VZScale(zmap1,mode,stddev); VBilateralFilter(zmap1,dst1,(int)radius,(double)(rvar),(double)svar,(int)numiter); /* ini histograms */ VGetHistRange(dst1,&hmin,&hmax); size_t nbins = 20000; gsl_histogram *hist0 = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (hist0,hmin,hmax); gsl_histogram *histz = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (histz,hmin,hmax); HistoUpdate(dst1,histz); /* random permutations */ #pragma omp parallel for shared(src1,permtable) schedule(dynamic) for (nperm = 0; nperm < numperm; nperm++) { if (nperm%20 == 0) fprintf(stderr," perm %4d of %d\r",nperm,(int)numperm); VImage zmap = VCreateImageLike(src1[0]); VImage dst = VCreateImageLike (zmap); OnesampleTest(src1,zmap,permtable[nperm],nimages); float mode=0; if (centering) mode = VGetMode(zmap); VZScale(zmap,mode,stddev); VBilateralFilter(zmap,dst,(int)radius,(double)(rvar),(double)svar,(int)numiter); #pragma omp critical { HistoUpdate(dst,hist0); } VDestroyImage(dst); VDestroyImage(zmap); } /* apply fdr */ VImage fdrimage = VCopyImage (dst1,NULL,VAllBands); if (numperm > 0) { FDR(dst1,fdrimage,hist0,histz,(double)alpha); if (cleanup && alpha < 1.0) { VIsolatedVoxels(fdrimage,(float)(1.0-alpha)); } if (alpha < 1.0) VImageCount(fdrimage); } /* write output to disk */ out_list = VCreateAttrList (); VHistory(VNumber(options),options,prg_name,&list1,&out_list); VSetGeoInfo(geolist,out_list); VAppendAttr (out_list,"image",NULL,VImageRepn,fdrimage); fp = VOpenOutputFile (out_filename, TRUE); if (! VWriteFile (fp, out_list)) exit (1); fclose(fp); fprintf (stderr, "\n%s: done.\n", argv[0]); exit(0); }
{ "alphanum_fraction": 0.6632886564, "avg_line_length": 30.2871287129, "ext": "c", "hexsha": "00f5db5e2f8350e4983370ca33aacaab71a29ba3", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/vlisa_onesample/vlisa_onesample.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/vlisa_onesample/vlisa_onesample.c", "max_line_length": 121, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/vlisa_onesample/vlisa_onesample.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 2927, "size": 9177 }
#ifndef TRACKER_GMD_H #define TRACKER_GMD_H #include "tracker.h" #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* GAUSSIAN*/ #include "helper/Constants.h" #include <limits.h> #include "helper/high_res_timer.h" #include "helper/bounding_box_regressor.h" class TrackerGMD : public Tracker { public: TrackerGMD(const bool show_tracking, ExampleGenerator* example_generator, RegressorTrainBase* regressor_train); // Estimate the location of the target object in the current image. virtual void Track(const cv::Mat& image_curr, RegressorBase* regressor, BoundingBox* bbox_estimate_uncentered); // After tracking for this frame, update internal state virtual void UpdateState(const cv::Mat& image_curr, BoundingBox &bbox_estimate, RegressorBase* regressor, bool is_last_frame); // Initialize the tracker with the ground-truth bounding box of the first frame. virtual void Init(const cv::Mat& image_curr, const BoundingBox& bbox_gt, RegressorBase* regressor); virtual void Init(const std::string& image_curr_path, const VOTRegion& region, RegressorBase* regressor); // Online fine tune, given the networks and example_generators virtual void FineTuneOnline(ExampleGenerator* example_generator, RegressorTrainBase* regressor_train, bool success_frame, bool is_last_frame); // Actual worker to do the finetune void FineTuneWorker(ExampleGenerator* example_generator, RegressorTrainBase* regressor_train, std::vector<int> &this_bag, const int pos_candidate_upper_bound = INT_MAX, const int neg_candidate_upper_bound = INT_MAX); // Motion Model around bbox_curr_prior_tight_ void GetCandidates(BoundingBox &cur_bbox, int W, int H, std::vector<BoundingBox> &candidate_bboxes); // Check if generated candidate is valid or not bool ValidCandidate(BoundingBox &candidate_bbox, int W, int H); // Get one moved box, according to the Gaussian Motion Model BoundingBox GenerateOneGaussianCandidate(int W, int H, BoundingBox &bbox, double sd_x = SD_X, double sd_y = SD_Y, double sd_scale = SD_SCALE, double sd_ap = SD_AP); // Create and Enqueue Training Samples given already set up example_generator virtual void EnqueueOnlineTraningSamples(ExampleGenerator* example_generator, const cv::Mat &image_curr, const BoundingBox &estimate, bool success_frame); // check if the current estimate is success, needed as flag to pass to EnqueueOnlineTraningSamples virtual bool IsSuccessEstimate(); // clear all the related storage for tracking net video virtual void Reset(RegressorBase *regressor); private: gsl_rng *rng_; // Used to generate additional training examples through synthetic transformations. ExampleGenerator* example_generator_; // Neural network. RegressorTrainBase* regressor_train_; // this prediction scores for candidates std::vector<float> candidate_probabilities_; std::vector<BoundingBox> candidates_bboxes_; std::vector<int> sorted_idxes_; // the sorted indexes of probabilities from high to low // samples collected along each frame std::vector<BoundingBox> gts_; std::vector<cv::Mat> image_currs_; std::vector<cv::Mat> images_finetune_; std::vector<cv::Mat> targets_finetune_; std::vector<std::vector<BoundingBox> > candidates_finetune_pos_; std::vector<std::vector<BoundingBox> > candidates_finetune_neg_; // std::vector<std::vector<double> > labels_finetune_pos_; // std::vector<std::vector<double> > labels_finetune_neg_; // long term and short term std::vector<int> short_term_bag_; std::vector<int> long_term_bag_; std::mt19937 engine_; // for motion model candidates double sd_trans_; double sd_scale_; double sd_ap_; // timer HighResTimer hrt_; // Bbox regressor BoundingBoxRegressor bbox_finetuner_; }; #endif
{ "alphanum_fraction": 0.7256723716, "avg_line_length": 37.8703703704, "ext": "h", "hexsha": "a503929b6d07b7834110fb81d978710052ea3915", "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": "6c522b26f664c259bd371214e44c9c2cd32c51d0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Jim61C/GMD_Tracker", "max_forks_repo_path": "src/tracker/tracker_gmd.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6c522b26f664c259bd371214e44c9c2cd32c51d0", "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": "Jim61C/GMD_Tracker", "max_issues_repo_path": "src/tracker/tracker_gmd.h", "max_line_length": 157, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6c522b26f664c259bd371214e44c9c2cd32c51d0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Jim61C/GMD_Tracker", "max_stars_repo_path": "src/tracker/tracker_gmd.h", "max_stars_repo_stars_event_max_datetime": "2018-06-19T21:49:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-14T14:33:30.000Z", "num_tokens": 951, "size": 4090 }