Search is not available for this dataset
text
string
meta
dict
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "compearth.h" #ifdef COMPEARTH_USE_MKL #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wstrict-prototypes" #endif #include <mkl_cblas.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #else #include <cblas.h> #endif /*! * @brief Computes the omega angles between two moment tensors. * * @param[in] nmt1 Number of moment tensors in M1. This can be 1 otherwise * it must be equal to nmt2. If it is 1 then the angle will * be between M1 and all the moment tensors in M2. * @param[in] M1 First array of moment tensors. M1 is packed * \f$ M = \{M_{11} M_{22} M_{33} M_{12} M_{13} M_{23}\} \f$. * This is an array of dimension [6 x nmt1] with leading * dimension 6. * @param[in] nmt2 Number of moment tensors in M2. This can be 1 otherwise * it must be equal to nmt1. If it is 1 then the angle will * be between M2 and all the moment tensors in M1. * @param[in] M2 Second array of moment tensors. M2 is packed * \f$ M = \{M_{11} M_{22} M_{33} M_{12} M_{13} M_{23}\} \f$. * This is an array of dimension [6 x nmt2] with leading * dimension 6. * * @param[out] omega This is a measure between two moment tensors and combines * differences in eigenvalues (source types) and orientation * but not magnitude. * This is an array of dimension [MAX(nmt1, nmt2)]. * * @author Carl Tape and translated to C by Ben Baker * * @copyright MIT * */ int compearth_CMT2omega(const int nmt1, const double *__restrict__ M1, const int nmt2, const double *__restrict__ M2, double *__restrict__ omega) { double Mwork[6*CE_CHUNKSIZE] __attribute__((aligned(64))); int ierr, imt, nmtLoc; const double pi180i = 180.0/M_PI; ierr = 0; if (nmt1 < 1 || M1 == NULL || nmt2 < 1 || M2 == NULL || omega == NULL) { if (nmt1 < 1) { fprintf(stderr, "%s: Error nmt1 must be positive\n", __func__); } if (nmt2 < 1) { fprintf(stderr, "%s: Error nmt2 must be positive\n", __func__); } if (M1 == NULL){fprintf(stderr, "%s: Error M1 is NULL\n", __func__);} if (M2 == NULL){fprintf(stderr, "%s: Error M2 is NULL\n", __func__);} if (omega == NULL) { fprintf(stderr, "%s: Error omega is NULL\n", __func__); } return -1; } // Straight compuation if (nmt1 == nmt2) { ierr = compearth_angleMT(nmt1, M1, M2, omega); if (ierr != 0) { fprintf(stderr, "%s: Error computing angleMT 1\n", __func__); } // Convert to degrees cblas_dscal(nmt1, pi180i, omega, 1); return ierr; } else { if (nmt1 == 1 || nmt2 == 1) { // Copy nmt1 and repeat computation with it if (nmt1 == 1) { for (imt=0; imt<CE_CHUNKSIZE; imt++) { cblas_dcopy(6, &M1[0], 1, &Mwork[6*imt], 1); } for (imt=0; imt<nmt2; imt=imt+CE_CHUNKSIZE) { nmtLoc = MIN(CE_CHUNKSIZE, nmt2 - imt); ierr = compearth_angleMT(nmtLoc, Mwork, &M2[6*imt], &omega[imt]); if (ierr != 0) { fprintf(stderr, "%s: Error calling angleMT at %d\n", __func__, __LINE__); return ierr; } // Convert to degrees cblas_dscal(nmtLoc, pi180i, &omega[imt], 1); } } // Copy nmt2 and repeat computation with it else { for (imt=0; imt<CE_CHUNKSIZE; imt++) { cblas_dcopy(6, &M2[0], 1, &Mwork[6*imt], 1); } for (imt=0; imt<nmt1; imt=imt+CE_CHUNKSIZE) { nmtLoc = MIN(CE_CHUNKSIZE, nmt1 - imt); ierr = compearth_angleMT(nmtLoc, &M1[6*imt], Mwork, &omega[imt]); if (ierr != 0) { fprintf(stderr, "%s: Error calling angleMT at %d\n", __func__, __LINE__); return ierr; } // Convert to degrees cblas_dscal(nmtLoc, pi180i, &omega[imt], 1); } } } else { fprintf(stderr, "%s: nmt1=%d /= nmt2=%d; this is invalid\n", __func__, nmt1, nmt2); return -1; } } return ierr; }
{ "alphanum_fraction": 0.4770571152, "avg_line_length": 35.8680555556, "ext": "c", "hexsha": "931b71af7e4926e83d0bc215a0c0f2db21d95680", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_path": "c_src/CMT2omega.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_path": "c_src/CMT2omega.c", "max_line_length": 80, "max_stars_count": 9, "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_path": "c_src/CMT2omega.c", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "num_tokens": 1380, "size": 5165 }
#ifndef BATCH_EXTRACTOR_H_IVH3CLLQ #define BATCH_EXTRACTOR_H_IVH3CLLQ #include <algorithm> #include <gsl/gsl> #include <opencv2/core/types.hpp> #include <opencv2/features2d.hpp> #include <opencv2/xfeatures2d.hpp> #include <optional> #include <sens_loc/util/correctness_util.h> using namespace std; using namespace cv; namespace sens_loc::apps { /// Helper class that visits a list of images and extracts features with the /// provided detectors. /// \ingroup feature-extractor-driver class batch_extractor { public: using filter_func = function<vector<KeyPoint>::iterator(vector<KeyPoint>&)>; /// \param detector,descriptor Algorithms used for detection and /// description. /// \param input_pattern,output_pattern Formattable string for IO. /// \param keypoint_filter Callable that determines if a keypoint shall be /// dropped from consideration. All keypoints with 'keypoint_filter(kp) == /// true' are removed. batch_extractor(Ptr<Feature2D> detector, Ptr<Feature2D> descriptor, string_view input_pattern, string_view output_pattern, vector<filter_func> keypoint_filter) : _detector{move(detector)} , _descriptor{move(descriptor)} , _input_pattern{input_pattern} , _ouput_pattern{output_pattern} , _keypoint_filter{move(keypoint_filter)} { Expects(!_input_pattern.empty()); Expects(!_ouput_pattern.empty()); Expects(!_detector.empty()); } /// Process a whole batch of files in the range [start, end]. [[nodiscard]] bool process_batch(int start, int end) const noexcept; private: /// Detect and describe one single index. Handles the IO as well. [[nodiscard]] bool process_index(int idx) const noexcept; /// Do IO and handle detection down to \c compute_features. bool process_detector(const math::image<uchar>& image, const string& out_file, const string& in_file) const noexcept; /// Compute and filter keypoints and run the descriptor on them /// afterwards. [[nodiscard]] pair<vector<KeyPoint>, Mat> compute_features(const math::image<uchar>& img) const noexcept; mutable Ptr<Feature2D> _detector; mutable Ptr<Feature2D> _descriptor; string_view _input_pattern; string_view _ouput_pattern; vector<filter_func> _keypoint_filter; }; } // namespace sens_loc::apps #endif /* end of include guard: BATCH_EXTRACTOR_H_IVH3CLLQ */
{ "alphanum_fraction": 0.6706197399, "avg_line_length": 36.3055555556, "ext": "h", "hexsha": "016faa725d9629c154719ab2cec092bab63979d3", "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/feature_extractor/batch_extractor.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/feature_extractor/batch_extractor.h", "max_line_length": 80, "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/feature_extractor/batch_extractor.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": 572, "size": 2614 }
#include "fg_interface.h" #include <gsl/gsl_rng.h> #include <math.h> #include <stdio.h> int main(int argc, char *argv[]) { fg_func test = fg_init_7_4096(log, 1E-15, 1000, 1E-12, 1E-15, 0); int n_el = 100000; gsl_rng *r = gsl_rng_alloc(gsl_rng_taus); gsl_rng_set(r, 1); double *x = (double *)malloc(n_el * sizeof(double)); for (int i = 0; i < n_el; ++i) { x[i] = gsl_rng_uniform(r) * 1000; } double sum = 0.0; for (int i_loop = 0; i_loop < 5000; ++i_loop) { for (int i = 0; i < n_el; i++) { sum += fg_eval(&test, x[i]); } } printf("%g\n", sum); return 0; }
{ "alphanum_fraction": 0.5386996904, "avg_line_length": 22.275862069, "ext": "c", "hexsha": "5c47525a24a34e0af1c3bd3fed2a7490460d0128", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-11-09T01:07:00.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-13T18:17:45.000Z", "max_forks_repo_head_hexsha": "789c67b42838e609516d93f95f962189e7dd96f5", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ahbarnett/function_generator", "max_forks_repo_path": "src/c_example.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "789c67b42838e609516d93f95f962189e7dd96f5", "max_issues_repo_issues_event_max_datetime": "2021-11-09T13:34:03.000Z", "max_issues_repo_issues_event_min_datetime": "2021-11-09T13:34:03.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ahbarnett/function_generator", "max_issues_repo_path": "src/c_example.c", "max_line_length": 69, "max_stars_count": 9, "max_stars_repo_head_hexsha": "789c67b42838e609516d93f95f962189e7dd96f5", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ahbarnett/function_generator", "max_stars_repo_path": "src/c_example.c", "max_stars_repo_stars_event_max_datetime": "2021-12-09T19:24:49.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-12T20:31:07.000Z", "num_tokens": 234, "size": 646 }
/* integration/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * Copyright (C) 2017, 2018 Patrick Alken * Copyright (C) 2017 Konrad Griessinger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_sf_gamma.h> #include "tests.h" #define SQRT15 3.8729833462074168852 #define SQRT30 5.4772255750516611346 #define SQRT70 8.3666002653407554798 #define CONST1 0.86113631159405257522 /* sqrt((3+2*sqrt(6./5))/7) */ #define CONST2 0.33998104358485626480 /* sqrt((3-2*sqrt(6./5))/7) */ #define CONST3 0.90617984593866399280 /* sqrt((5+2*sqrt(10./7)))/3 */ #define CONST4 0.53846931010568309104 /* sqrt((5-2*sqrt(10./7)))/3 */ gsl_function make_function (double (* f) (double, void *), double * p); gsl_function make_function (double (* f) (double, void *), double * p) { gsl_function f_new; f_new.function = f ; f_new.params = p ; return f_new; } struct counter_params { gsl_function * f; int neval; } ; double counter (double x, void * params); gsl_function make_counter (gsl_function * f, struct counter_params * p); double counter (double x, void * params) { struct counter_params * p = (struct counter_params *) params; p->neval++ ; /* increment counter */ return GSL_FN_EVAL(p->f, x); } gsl_function make_counter (gsl_function * f, struct counter_params * p) { gsl_function f_new; p->f = f; p->neval = 0 ; f_new.function = &counter ; f_new.params = p ; return f_new; } void my_error_handler (const char *reason, const char *file, int line, int err); static int test_fixed_quadrature(const gsl_integration_fixed_type * T, const size_t n, const double a, const double b, const double alpha, const double beta, const double tol, const double exact, const gsl_function * f, const char * desc) { int status = GSL_SUCCESS; gsl_integration_fixed_workspace * w = gsl_integration_fixed_alloc(T, n, a, b, alpha, beta); char buf[2048]; double result; sprintf(buf, "%s a=%g b=%g alpha=%g beta=%g", desc, a, b, alpha, beta); gsl_integration_fixed(f, &result, w); gsl_test_rel (result, exact, tol, "%s", buf); gsl_integration_fixed_free(w); return status; } int main (void) { gsl_ieee_env_setup (); gsl_set_error_handler (&my_error_handler); /* Test the basic Gauss-Kronrod rules with a smooth positive function. */ { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 7.716049357767090777E-02; double exp_abserr = 2.990224871000550874E-06; double exp_resabs = 7.716049357767090777E-02; double exp_resasc = 4.434273814139995384E-02; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha) ; gsl_integration_qk15 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk15(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk15(f1) smooth abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk15(f1) smooth resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk15(f1) smooth resasc") ; gsl_integration_qk15 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk15(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk15(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk15(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk15(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 7.716049379303084599E-02; double exp_abserr = 9.424302194248481445E-08; double exp_resabs = 7.716049379303084599E-02; double exp_resasc = 4.434311425038358484E-02; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk21 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk21(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk21(f1) smooth abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk21(f1) smooth resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk21(f1) smooth resasc") ; gsl_integration_qk21 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk21(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk21(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk21(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk21(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 7.716049382494900855E-02; double exp_abserr = 1.713503193600029893E-09; double exp_resabs = 7.716049382494900855E-02; double exp_resasc = 4.427995051868838933E-02; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk31 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk31(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk31(f1) smooth abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk31(f1) smooth resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk31(f1) smooth resasc") ; gsl_integration_qk31 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk31(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk31(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk31(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk31(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 7.716049382681375302E-02; double exp_abserr = 9.576386660975511224E-11; double exp_resabs = 7.716049382681375302E-02; double exp_resasc = 4.421521169637691873E-02; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk41 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk41(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk41(f1) smooth abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk41(f1) smooth resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk41(f1) smooth resasc") ; gsl_integration_qk41 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk41(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk41(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk41(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk41(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 7.716049382708510540E-02; double exp_abserr = 1.002079980317363772E-11; double exp_resabs = 7.716049382708510540E-02; double exp_resasc = 4.416474291216854892E-02; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk51 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk51(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qk51(f1) smooth abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk51(f1) smooth resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk51(f1) smooth resasc") ; gsl_integration_qk51 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk51(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qk51(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk51(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk51(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 7.716049382713800753E-02; double exp_abserr = 1.566060362296155616E-12; double exp_resabs = 7.716049382713800753E-02; double exp_resasc = 4.419287685934316506E-02; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk61 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk61(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qk61(f1) smooth abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk61(f1) smooth resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk61(f1) smooth resasc") ; gsl_integration_qk61 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk61(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qk61(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk61(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk61(f1) reverse resasc") ; } /* Now test the basic rules with a positive function that has a singularity. This should give large values of abserr which would find discrepancies in the abserr calculation. */ { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 1.555688196612745777E+01; double exp_abserr = 2.350164577239293706E+01; double exp_resabs = 1.555688196612745777E+01; double exp_resasc = 2.350164577239293706E+01; double alpha = -0.9 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk15 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk15(f1) singular result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk15(f1) singular abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk15(f1) singular resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk15(f1) singular resasc") ; gsl_integration_qk15 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk15(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk15(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk15(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk15(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 1.799045317938126232E+01; double exp_abserr = 2.782360287710622515E+01; double exp_resabs = 1.799045317938126232E+01; double exp_resasc = 2.782360287710622515E+01; double alpha = -0.9 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk21 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk21(f1) singular result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk21(f1) singular abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk21(f1) singular resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk21(f1) singular resasc") ; gsl_integration_qk21 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk21(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk21(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk21(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk21(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 2.081873305159121657E+01; double exp_abserr = 3.296500137482590276E+01; double exp_resabs = 2.081873305159121301E+01; double exp_resasc = 3.296500137482590276E+01; double alpha = -0.9 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk31 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk31(f1) singular result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk31(f1) singular abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk31(f1) singular resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk31(f1) singular resasc") ; gsl_integration_qk31 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk31(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk31(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk31(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk31(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 2.288677623903126701E+01; double exp_abserr = 3.671538820274916048E+01; double exp_resabs = 2.288677623903126701E+01; double exp_resasc = 3.671538820274916048E+01; double alpha = -0.9 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk41 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk41(f1) singular result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk41(f1) singular abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk41(f1) singular resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk41(f1) singular resasc") ; gsl_integration_qk41 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk41(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk41(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk41(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk41(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 2.449953612016972215E+01; double exp_abserr = 3.967771249391228849E+01; double exp_resabs = 2.449953612016972215E+01; double exp_resasc = 3.967771249391228849E+01; double alpha = -0.9 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk51 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk51(f1) singular result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk51(f1) singular abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk51(f1) singular resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk51(f1) singular resasc") ; gsl_integration_qk51 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk51(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk51(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk51(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk51(f1) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result = 2.583030240976628988E+01; double exp_abserr = 4.213750493076978643E+01; double exp_resabs = 2.583030240976628988E+01; double exp_resasc = 4.213750493076978643E+01; double alpha = -0.9 ; gsl_function f = make_function(&f1, &alpha); gsl_integration_qk61 (&f, 0.0, 1.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk61(f1) singular result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk61(f1) singular abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk61(f1) singular resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk61(f1) singular resasc") ; gsl_integration_qk61 (&f, 1.0, 0.0, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk61(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk61(f1) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk61(f1) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk61(f1) reverse resasc") ; } /* Test the basic Gauss-Kronrod rules with a smooth oscillating function, over an unsymmetric range. This should find any discrepancies in the abscissae. */ { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result =-7.238969575483799046E-01; double exp_abserr = 8.760080200939757174E-06; double exp_resabs = 1.165564172429140788E+00; double exp_resasc = 9.334560307787327371E-01; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); gsl_integration_qk15 (&f, 0.3, 2.71, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk15(f3) oscill result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk15(f3) oscill abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk15(f3) oscill resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk15(f3) oscill resasc") ; gsl_integration_qk15 (&f, 2.71, 0.3, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk15(f3) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk15(f3) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk15(f3) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk15(f3) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result =-7.238969575482959717E-01; double exp_abserr = 7.999213141433641888E-11; double exp_resabs = 1.150829032708484023E+00; double exp_resasc = 9.297591249133687619E-01; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); gsl_integration_qk21 (&f, 0.3, 2.71, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk21(f3) oscill result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qk21(f3) oscill abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk21(f3) oscill resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk21(f3) oscill resasc") ; gsl_integration_qk21 (&f, 2.71, 0.3, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk21(f3) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qk21(f3) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk21(f3) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk21(f3) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result =-7.238969575482959717E-01; double exp_abserr = 1.285805464427459261E-14; double exp_resabs = 1.158150602093290571E+00; double exp_resasc = 9.277828092501518853E-01; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); gsl_integration_qk31 (&f, 0.3, 2.71, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk31(f3) oscill result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk31(f3) oscill abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk31(f3) oscill resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk31(f3) oscill resasc") ; gsl_integration_qk31 (&f, 2.71, 0.3, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk31(f3) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk31(f3) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk31(f3) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk31(f3) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result =-7.238969575482959717E-01; double exp_abserr = 1.286535726271015626E-14; double exp_resabs = 1.158808363486595328E+00; double exp_resasc = 9.264382258645686985E-01; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); gsl_integration_qk41 (&f, 0.3, 2.71, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk41(f3) oscill result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk41(f3) oscill abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk41(f3) oscill resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk41(f3) oscill resasc") ; gsl_integration_qk41 (&f, 2.71, 0.3, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk41(f3) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk41(f3) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk41(f3) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk41(f3) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result =-7.238969575482961938E-01; double exp_abserr = 1.285290995039385778E-14; double exp_resabs = 1.157687209264406381E+00; double exp_resasc = 9.264666884071264263E-01; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); gsl_integration_qk51 (&f, 0.3, 2.71, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk51(f3) oscill result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk51(f3) oscill abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk51(f3) oscill resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk51(f3) oscill resasc") ; gsl_integration_qk51 (&f, 2.71, 0.3, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk51(f3) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk51(f3) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk51(f3) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk51(f3) reverse resasc") ; } { double result = 0, abserr = 0, resabs = 0, resasc = 0 ; double exp_result =-7.238969575482959717E-01; double exp_abserr = 1.286438572027470736E-14; double exp_resabs = 1.158720854723590099E+00; double exp_resasc = 9.270469641771273972E-01; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); gsl_integration_qk61 (&f, 0.3, 2.71, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,exp_result,1e-15,"qk61(f3) oscill result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk61(f3) oscill abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk61(f3) oscill resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk61(f3) oscill resasc") ; gsl_integration_qk61 (&f, 2.71, 0.3, &result, &abserr, &resabs, &resasc) ; gsl_test_rel(result,-exp_result,1e-15,"qk61(f3) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qk61(f3) reverse abserr") ; gsl_test_rel(resabs,exp_resabs,1e-15,"qk61(f3) reverse resabs") ; gsl_test_rel(resasc,exp_resasc,1e-15,"qk61(f3) reverse resasc") ; } /* Test the non-adaptive gaussian integrator QNG */ { int status = 0; size_t neval = 0 ; double result = 0, abserr = 0 ; double exp_result = 7.716049379303083211E-02; double exp_abserr = 9.424302199601294244E-08; int exp_neval = 21; int exp_ier = 0; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); status = gsl_integration_qng (&f, 0.0, 1.0, 1e-1, 0.0, &result, &abserr, &neval) ; gsl_test_rel(result,exp_result,1e-15,"qng(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f1) smooth abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f1) smooth neval") ; gsl_test_int(status,exp_ier,"qng(f1) smooth status") ; status = gsl_integration_qng (&f, 1.0, 0.0, 1e-1, 0.0, &result, &abserr, &neval) ; gsl_test_rel(result,-exp_result,1e-15,"qng(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f1) reverse abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f1) reverse neval") ; gsl_test_int(status,exp_ier,"qng(f1) reverse status") ; } { int status = 0; size_t neval = 0 ; double result = 0, abserr = 0 ; double exp_result = 7.716049382706505200E-02; double exp_abserr = 2.666893044866214501E-12; int exp_neval = 43; int exp_ier = 0; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); status = gsl_integration_qng (&f, 0.0, 1.0, 0.0, 1e-9, &result, &abserr, &neval) ; gsl_test_rel(result,exp_result,1e-15,"qng(f1) smooth 43pt result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qng(f1) smooth 43pt abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f1) smooth 43pt neval") ; gsl_test_int(status,exp_ier,"qng(f1) smooth 43pt status") ; status = gsl_integration_qng (&f, 1.0, 0.0, 0.0, 1e-9, &result, &abserr, &neval) ; gsl_test_rel(result,-exp_result,1e-15,"qng(f1) reverse 43pt result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qng(f1) reverse 43pt abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f1) reverse 43pt neval") ; gsl_test_int(status,exp_ier,"qng(f1) reverse 43pt status") ; } { int status; size_t neval = 0 ; double result = 0, abserr = 0 ; double exp_result =-7.238969575482961938E-01; double exp_abserr = 1.277676889520056369E-14; int exp_neval = 43; int exp_ier = 0; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); status = gsl_integration_qng (&f, 0.3, 2.71, 0.0, 1e-12, &result, &abserr, &neval) ; gsl_test_rel(result,exp_result,1e-15,"qnq(f3) oscill result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f3) oscill abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f3) oscill neval") ; gsl_test_int(status,exp_ier,"qng(f3) oscill status") ; status = gsl_integration_qng (&f, 2.71, 0.3, 0.0, 1e-12, &result, &abserr, &neval) ; gsl_test_rel(result,-exp_result,1e-15,"qnq(f3) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f3) reverse abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f3) reverse neval") ; gsl_test_int(status,exp_ier,"qng(f3) reverse status") ; } { int status = 0; size_t neval = 0 ; double result = 0, abserr = 0 ; double exp_result = 7.716049382716029525E-02; double exp_abserr = 8.566535680046930668E-16; int exp_neval = 87; int exp_ier = 0; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); status = gsl_integration_qng (&f, 0.0, 1.0, 0.0, 1e-13, &result, &abserr, &neval) ; gsl_test_rel(result,exp_result,1e-15,"qng(f1) 87pt smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f1) 87pt smooth abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f1) 87pt smooth neval") ; gsl_test_int(status,exp_ier,"qng(f1) 87pt smooth status") ; status = gsl_integration_qng (&f, 1.0, 0.0, 0.0, 1e-13, &result, &abserr, &neval) ; gsl_test_rel(result,-exp_result,1e-15,"qng(f1) 87pt reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f1) 87pt reverse abserr") ; gsl_test_int((int)neval,exp_neval,"qng(f1) 87pt reverse neval") ; gsl_test_int(status,exp_ier,"qng(f1) 87pt reverse status") ; } { int status = 0; size_t neval = 0 ; double result = 0, abserr = 0 ; double exp_result = 3.222948711817264211E+01; double exp_abserr = 2.782360287710622870E+01; int exp_neval = 87; int exp_ier = GSL_ETOL; double alpha = -0.9 ; gsl_function f = make_function(&f1, &alpha); status = gsl_integration_qng (&f, 0.0, 1.0, 0.0, 1e-3, &result, &abserr, &neval) ; gsl_test_rel(result,exp_result,1e-15,"qng(f1) sing beyond 87pt result"); gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f1) sing beyond 87pt abserr"); gsl_test_int((int)neval,exp_neval,"qng(f1) sing beyond 87pt neval") ; gsl_test_int(status,exp_ier,"qng(f1) sing beyond 87pt status") ; status = gsl_integration_qng (&f, 1.0, 0.0, 0.0, 1e-3, &result, &abserr, &neval) ; gsl_test_rel(result,-exp_result,1e-15,"qng(f1) reverse beyond 87pt result"); gsl_test_rel(abserr,exp_abserr,1e-7,"qng(f1) rev beyond 87pt abserr"); gsl_test_int((int)neval,exp_neval,"qng(f1) rev beyond 87pt neval") ; gsl_test_int(status,exp_ier,"qng(f1) rev beyond 87pt status") ; } /* Test the adaptive integrator QAG */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; double exp_result = 7.716049382715854665E-02 ; double exp_abserr = 6.679384885865053037E-12 ; int exp_neval = 165; int exp_ier = 0; int exp_last = 6; double a[6] = { 0, 0.5, 0.25, 0.125, 0.0625, 0.03125 } ; double b[6] = { 0.03125, 1, 0.5, 0.25, 0.125, 0.0625 } ; double r[6] = { 3.966769831709074375E-06, 5.491842501998222409E-02, 1.909827770934243926E-02, 2.776531175604360531E-03, 3.280661030752063693E-04, 3.522704932261797744E-05 } ; double e[6] = { 6.678528276336181873E-12, 6.097169993333454062E-16, 2.120334764359736934E-16, 3.082568839745514608E-17, 3.642265412331439511E-18, 3.910988124757650942E-19 } ; int order[6] = { 1, 2, 3, 4, 5, 6 } ; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha) ; gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qag (&fc, 0.0, 1.0, 0.0, 1e-10, w->limit, GSL_INTEG_GAUSS15, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-15,"qag(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f1) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qag(f1) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f1) smooth last") ; gsl_test_int(status,exp_ier,"qag(f1) smooth status") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qag(f1) smooth alist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qag(f1) smooth blist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qag(f1) smooth rlist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->elist[i],e[i],1e-6,"qag(f1) smooth elist") ; for (i = 0; i < 6 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qag(f1) smooth order") ; p.neval = 0; status = gsl_integration_qag (&fc, 1.0, 0.0, 0.0, 1e-10, w->limit, GSL_INTEG_GAUSS15, w, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-15,"qag(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f1) reverse abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qag(f1) reverse neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f1) reverse last") ; gsl_test_int(status,exp_ier,"qag(f1) reverse status") ; gsl_integration_workspace_free (w) ; } /* Test the same function using an absolute error bound and the 21-point rule */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; double exp_result = 7.716049382716050342E-02 ; double exp_abserr = 2.227969521869139532E-15 ; int exp_neval = 315; int exp_ier = 0; int exp_last = 8; double a[8] = { 0, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125 } ; double b[8] = { 0.0078125, 1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625 } ; double r[8] = { 3.696942726831556522E-08, 5.491842501998223103E-02, 1.909827770934243579E-02, 2.776531175604360097E-03, 3.280661030752062609E-04, 3.522704932261797744E-05, 3.579060884684503576E-06, 3.507395216921808047E-07 } ; double e[8] = { 1.371316364034059572E-15, 6.097169993333454062E-16, 2.120334764359736441E-16, 3.082568839745514608E-17, 3.642265412331439511E-18, 3.910988124757650460E-19, 3.973555800712018091E-20, 3.893990926286736620E-21 } ; int order[8] = { 1, 2, 3, 4, 5, 6, 7, 8 } ; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qag (&fc, 0.0, 1.0, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS21, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-15,"qag(f1,21pt) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f1,21pt) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qag(f1,21pt) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f1,21pt) smooth last") ; gsl_test_int(status,exp_ier,"qag(f1,21pt) smooth status") ; for (i = 0; i < 8 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qag(f1,21pt) smooth alist") ; for (i = 0; i < 8 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qag(f1,21pt) smooth blist") ; for (i = 0; i < 8 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qag(f1,21pt) smooth rlist") ; for (i = 0; i < 8 ; i++) gsl_test_rel(w->elist[i],e[i],1e-6,"qag(f1,21pt) smooth elist") ; for (i = 0; i < 8 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qag(f1,21pt) smooth order"); p.neval = 0; status = gsl_integration_qag (&fc, 1.0, 0.0, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS21, w, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-15,"qag(f1,21pt) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f1,21pt) reverse abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qag(f1,21pt) reverse neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f1,21pt) reverse last") ; gsl_test_int(status,exp_ier,"qag(f1,21pt) reverse status") ; gsl_integration_workspace_free (w) ; } /* Adaptive integration of an oscillatory function which terminates because of roundoff error, uses the 31-pt rule */ { int status = 0; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; double exp_result = -7.238969575482959717E-01; double exp_abserr = 1.285805464427459261E-14; int exp_neval = 31; int exp_ier = GSL_EROUND; int exp_last = 1; double alpha = 1.3 ; gsl_function f = make_function(&f3, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qag (&fc, 0.3, 2.71, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS31, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-15,"qag(f3,31pt) oscill result"); gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f3,31pt) oscill abserr"); gsl_test_int((int)(p.neval),exp_neval,"qag(f3,31pt) oscill neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f3,31pt) oscill last") ; gsl_test_int(status,exp_ier,"qag(f3,31pt) oscill status") ; p.neval = 0; status = gsl_integration_qag (&fc, 2.71, 0.3, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS31, w, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-15,"qag(f3,31pt) reverse result"); gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f3,31pt) reverse abserr"); gsl_test_int((int)(p.neval),exp_neval,"qag(f3,31pt) reverse neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f3,31pt) reverse last") ; gsl_test_int(status,exp_ier,"qag(f3,31pt) reverse status") ; gsl_integration_workspace_free (w) ; } /* Check the singularity detection (singularity at x=-0.1 in this example) */ { int status = 0; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; int exp_neval = 5151; int exp_ier = GSL_ESING; int exp_last = 51; double alpha = 2.0 ; gsl_function f = make_function(&f16, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qag (&fc, -1.0, 1.0, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS51, w, &result, &abserr) ; gsl_test_int((int)(p.neval),exp_neval,"qag(f16,51pt) sing neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f16,51pt) sing last") ; gsl_test_int(status,exp_ier,"qag(f16,51pt) sing status") ; p.neval = 0; status = gsl_integration_qag (&fc, 1.0, -1.0, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS51, w, &result, &abserr) ; gsl_test_int((int)(p.neval),exp_neval,"qag(f16,51pt) rev neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f16,51pt) rev last") ; gsl_test_int(status,exp_ier,"qag(f16,51pt) rev status") ; gsl_integration_workspace_free (w) ; } /* Check for hitting the iteration limit */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (3) ; double exp_result = 9.565151449233894709 ; double exp_abserr = 1.570369823891028460E+01; int exp_neval = 305; int exp_ier = GSL_EMAXITER; int exp_last = 3; double a[3] = { -5.000000000000000000E-01, 0.000000000000000000, -1.000000000000000000 } ; double b[3] = { 0.000000000000000000, 1.000000000000000000, -5.000000000000000000E-01 } ; double r[3] = { 9.460353469435913709, 9.090909090909091161E-02, 1.388888888888888812E-02 } ; double e[3] = { 1.570369823891028460E+01, 1.009293658750142399E-15, 1.541976423090495140E-16 } ; int order[3] = { 1, 2, 3 } ; double alpha = 1.0 ; gsl_function f = make_function(&f16, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qag (&fc, -1.0, 1.0, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS61, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-15,"qag(f16,61pt) limit result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f16,61pt) limit abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qag(f16,61pt) limit neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f16,61pt) limit last") ; gsl_test_int(status,exp_ier,"qag(f16,61pt) limit status") ; for (i = 0; i < 3 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qag(f16,61pt) limit alist") ; for (i = 0; i < 3 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qag(f16,61pt) limit blist") ; for (i = 0; i < 3 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qag(f16,61pt) limit rlist") ; for (i = 0; i < 3 ; i++) gsl_test_rel(w->elist[i],e[i],1e-6,"qag(f16,61pt) limit elist") ; for (i = 0; i < 3 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qag(f16,61pt) limit order"); p.neval = 0; status = gsl_integration_qag (&fc, 1.0, -1.0, 1e-14, 0.0, w->limit, GSL_INTEG_GAUSS61, w, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-15,"qag(f16,61pt) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qag(f16,61pt) reverse abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qag(f16,61pt) reverse neval") ; gsl_test_int((int)(w->size),exp_last,"qag(f16,61pt) reverse last") ; gsl_test_int(status,exp_ier,"qag(f16,61pt) reverse status") ; gsl_integration_workspace_free (w) ; } /* Test the adaptive integrator with extrapolation QAGS */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; double exp_result = 7.716049382715789440E-02 ; double exp_abserr = 2.216394961010438404E-12 ; int exp_neval = 189; int exp_ier = 0; int exp_last = 5; double a[5] = { 0, 0.5, 0.25, 0.125, 0.0625 } ; double b[5] = { 0.0625, 1, 0.5, 0.25, 0.125 } ; double r[5] = { 3.919381915366914693E-05, 5.491842501998223103E-02, 1.909827770934243579E-02, 2.776531175604360097E-03, 3.280661030752062609E-04 } ; double e[5] = { 2.215538742580964735E-12, 6.097169993333454062E-16, 2.120334764359736441E-16, 3.082568839745514608E-17, 3.642265412331439511E-18 } ; int order[5] = { 1, 2, 3, 4, 5 } ; double alpha = 2.6 ; gsl_function f = make_function(&f1, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qags (&fc, 0.0, 1.0, 0.0, 1e-10, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-15,"qags(f1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qags(f1) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qags(f1) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qags(f1) smooth last") ; gsl_test_int(status,exp_ier,"qags(f1) smooth status") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qags(f1) smooth alist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qags(f1) smooth blist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qags(f1) smooth rlist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->elist[i],e[i],1e-6,"qags(f1) smooth elist") ; for (i = 0; i < 5 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qags(f1) smooth order") ; p.neval = 0; status = gsl_integration_qags (&fc, 1.0, 0.0, 0.0, 1e-10, w->limit, w, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-15,"qags(f1) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qags(f1) reverse abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qags(f1) reverse neval") ; gsl_test_int((int)(w->size),exp_last,"qags(f1) reverse last") ; gsl_test_int(status,exp_ier,"qags(f1) reverse status") ; gsl_integration_workspace_free (w) ; } /* Test f11 using an absolute error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = -5.908755278982136588E+03 ; double exp_abserr = 1.299646281053874554E-10 ; int exp_neval = 357; int exp_ier = 0; int exp_last = 9; double a[9] = { 1.000000000000000000E+00, 5.005000000000000000E+02, 2.507500000000000000E+02, 1.258750000000000000E+02, 6.343750000000000000E+01, 3.221875000000000000E+01, 1.660937500000000000E+01, 8.804687500000000000E+00, 4.902343750000000000E+00 } ; double b[9] = { 4.902343750000000000E+00, 1.000000000000000000E+03, 5.005000000000000000E+02, 2.507500000000000000E+02, 1.258750000000000000E+02, 6.343750000000000000E+01, 3.221875000000000000E+01, 1.660937500000000000E+01, 8.804687500000000000E+00 } ; double r[9] = { -3.890977835520834649E+00, -3.297343675805121620E+03, -1.475904154146372775E+03, -6.517404019686431411E+02, -2.829354222635842007E+02, -1.201692001973227519E+02, -4.959999906099650246E+01, -1.971441499411640308E+01, -7.457032710459004399E+00 } ; double e[9] = { 6.448276035006137169E-11, 3.660786868980994028E-11, 1.638582774073219226E-11, 7.235772003440423011E-12, 3.141214202790722909E-12, 1.334146129098576244E-12, 5.506706097890446534E-13, 2.188739744348345039E-13, 8.278969410534525339E-14 } ; int order[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ; double alpha = 2.0 ; gsl_function f = make_function(&f11, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qags (&fc, 1.0, 1000.0, 1e-7, 0.0, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-15,"qags(f11) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-3,"qags(f11) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qags(f11) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qags(f11) smooth last") ; gsl_test_int(status,exp_ier,"qags(f11) smooth status") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qags(f11) smooth alist") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qags(f11) smooth blist") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qags(f11) smooth rlist") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->elist[i],e[i],1e-5,"qags(f11) smooth elist") ; for (i = 0; i < 9 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qags(f11) smooth order"); p.neval = 0; status = gsl_integration_qags (&fc, 1000.0, 1.0, 1e-7, 0.0, w->limit, w, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-15,"qags(f11) reverse result") ; gsl_test_rel(abserr,exp_abserr,1e-3,"qags(f11) reverse abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qags(f11) reverse neval") ; gsl_test_int((int)(w->size),exp_last,"qags(f11) reverse last") ; gsl_test_int(status,exp_ier,"qags(f11) reverse status") ; gsl_integration_workspace_free (w) ; } /* Test infinite range integral f455 using a relative error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = -3.616892186127022568E-01 ; double exp_abserr = 3.016716913328831851E-06; int exp_neval = 285; int exp_ier = 0; int exp_last = 10; double a[10] = { 9.687500000000000000E-01, 0.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 7.500000000000000000E-01, 1.250000000000000000E-01, 8.750000000000000000E-01, 6.250000000000000000E-02, 9.375000000000000000E-01, 3.125000000000000000E-02 } ; double b[10] = { 1.000000000000000000E+00, 3.125000000000000000E-02, 7.500000000000000000E-01, 5.000000000000000000E-01, 8.750000000000000000E-01, 2.500000000000000000E-01, 9.375000000000000000E-01, 1.250000000000000000E-01, 9.687500000000000000E-01, 6.250000000000000000E-02 } ; double r[10] = { -1.390003415539725340E-01, 1.429785306003466313E-03, -1.229943369113085765E-02, 2.995321156568048898E-03, -4.980050133751051655E-02, 2.785385934678596704E-03, -8.653752279614615461E-02, 1.736218164975512294E-03, -8.398745675010892142E-02, 1.041689192004495576E-03 } ; double e[10] = { 2.395037249893453013E-02, 2.161214992172538524E-04, 5.720644840858777846E-14, 3.325474514168701167E-17, 3.147380432198176412E-14, 3.092399597147240624E-17, 9.607595030230581153E-16, 1.927589382528252344E-17, 9.324480826368044019E-16, 1.156507325466566521E-17 } ; int order[10] = { 1, 2, 3, 5, 7, 9, 4, 6, 8, 10 } ; gsl_function f = make_function(&f455, 0); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qagiu (&fc, 0.0, 0.0, 1.0e-3, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qagiu(f455) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qagiu(f455) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qagiu(f455) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qagiu(f455) smooth last") ; gsl_test_int(status,exp_ier,"qagiu(f455) smooth status") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qagiu(f455) smooth alist") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qagiu(f455) smooth blist") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qagiu(f455) smooth rlist") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qagiu(f455) smooth elist") ; for (i = 0; i < 10 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qagiu(f455) smooth order"); gsl_integration_workspace_free (w) ; } /* Test infinite range integral f15 using a relative error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = 6.553600000000024738E+04; double exp_abserr = 7.121667111456009280E-04; int exp_neval = 285; int exp_ier = 0; int exp_last = 10; double a[10] = { 0.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02, 3.125000000000000000E-02, 1.562500000000000000E-02, 7.812500000000000000E-03, 3.906250000000000000E-03, 1.953125000000000000E-03 } ; double b[10] = { 1.953125000000000000E-03, 1.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02, 3.125000000000000000E-02, 1.562500000000000000E-02, 7.812500000000000000E-03, 3.906250000000000000E-03 } ; double r[10] = { 1.099297665754340292E+00, 3.256176475185617591E-01, 8.064694554185326325E+00, 8.873128656118993263E+01, 6.977679035845269482E+02, 4.096981198511257389E+03, 1.574317583220441520E+04, 2.899418134793237914E+04, 1.498314766425578091E+04, 9.225251570832365360E+02 } ; double e[10] = { 7.101865971621337814E-04, 1.912660677170175771E-08, 9.167763417119923333E-08, 3.769501719163865578E-07, 6.973493131275552509E-07, 1.205653952340679711E-07, 1.380003928453846583E-07, 1.934652413547325474E-07, 3.408933028357320364E-07, 2.132473175465897029E-09 } ; int order[10] = { 1, 5, 4, 9, 8, 7, 6, 3, 2, 10 } ; double alpha = 5.0; gsl_function f = make_function(&f15, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qagiu (&fc, 0.0, 0.0, 1.0e-7, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qagiu(f15) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qagiu(f15) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qagiu(f15) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qagiu(f15) smooth last") ; gsl_test_int(status,exp_ier,"qagiu(f15) smooth status") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qagiu(f15) smooth alist") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qagiu(f15) smooth blist") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qagiu(f15) smooth rlist") ; for (i = 0; i < 10 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qagiu(f15) smooth elist") ; for (i = 0; i < 10 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qagiu(f15) smooth order"); gsl_integration_workspace_free (w) ; } /* Test infinite range integral f16 using an absolute error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = 1.000000000006713292E-04; double exp_abserr = 3.084062020905636316E-09; int exp_neval = 165; int exp_ier = 0; int exp_last = 6; double a[6] = { 0.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02, 3.125000000000000000E-02 } ; double b[6] = { 3.125000000000000000E-02, 1.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02 } ; double r[6] = { 7.633587786326674618E-05, 9.900990099009899620E-07, 1.922522349322310737E-06, 3.629434715543053753E-06, 6.501422186103209199E-06, 1.062064387653501389E-05 } ; double e[6] = { 3.084061858351569051E-09, 3.112064814755089674E-17, 4.543453652226561245E-17, 4.908618166361344548E-17, 3.014338672269481784E-17, 6.795996738013555461E-18 } ; int order[6] = { 1, 4, 3, 2, 5, 6 } ; double alpha = 1.0; gsl_function f = make_function(&f16, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qagiu (&fc, 99.9, 1.0e-7, 0.0, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qagiu(f16) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qagiu(f16) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qagiu(f16) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qagiu(f16) smooth last") ; gsl_test_int(status,exp_ier,"qagiu(f16) smooth status") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qagiu(f16) smooth alist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qagiu(f16) smooth blist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-15,"qagiu(f16) smooth rlist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qagiu(f16) smooth elist") ; for (i = 0; i < 6 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qagiu(f16) smooth order"); gsl_integration_workspace_free (w) ; } /* Test infinite range integral myfn1 using an absolute error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = 2.275875794468747770E+00; double exp_abserr = 7.436490118267390744E-09; int exp_neval = 270; int exp_ier = 0; int exp_last = 5; double a[5] = { 1.250000000000000000E-01, 5.000000000000000000E-01, 2.500000000000000000E-01, 0.000000000000000000E+00, 3.750000000000000000E-01 } ; double b[5] = { 2.500000000000000000E-01, 1.000000000000000000E+00, 3.750000000000000000E-01, 1.250000000000000000E-01, 5.000000000000000000E-01 } ; double r[5] = { 4.639317228058405717E-04, 1.691664195356748834E+00, 1.146307471900291086E-01, 4.379392477350953574E-20, 4.691169201991640669E-01 } ; double e[5] = { 3.169263960393051137E-09, 4.265988974874425043E-09, 1.231954072964969637E-12, 8.360902986775307673E-20, 5.208244060463541433E-15 } ; int order[5] = { 2, 1, 3, 5, 4 } ; gsl_function f = make_function(&myfn1, 0); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qagi (&fc, 1.0e-7, 0.0, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qagiu(myfn1) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qagiu(myfn1) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qagiu(myfn1) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qagiu(myfn1) smooth last") ; gsl_test_int(status,exp_ier,"qagiu(myfn1) smooth status") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qagiu(myfn1) smooth alist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qagiu(myfn1) smooth blist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-14,"qagiu(myfn1) smooth rlist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qagiu(myfn1) smooth elist") ; for (i = 0; i < 5 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qagiu(myfn1) smooth order"); gsl_integration_workspace_free (w) ; } /* Test infinite range integral myfn1 using an absolute error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = 2.718281828459044647E+00; double exp_abserr = 1.588185109253204805E-10; int exp_neval = 135; int exp_ier = 0; int exp_last = 5; double a[5] = { 0.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02 } ; double b[5] = { 6.250000000000000000E-02, 1.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01 } ; double r[5] = { 8.315287189746029816E-07, 1.718281828459045091E+00, 8.646647167633871867E-01, 1.328565310599463256E-01, 2.477920647947255521E-03 } ; double e[5] = { 1.533437090413525935E-10, 4.117868247943567505E-12, 7.802455785301941044E-13, 5.395586026138397182E-13, 3.713312434866150125E-14 } ; int order[5] = { 1, 2, 3, 4, 5 } ; double alpha = 1.0 ; gsl_function f = make_function(&myfn2, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qagil (&fc, 1.0, 1.0e-7, 0.0, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qagiu(myfn2) smooth result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qagiu(myfn2) smooth abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qagiu(myfn2) smooth neval") ; gsl_test_int((int)(w->size),exp_last,"qagiu(myfn2) smooth last") ; gsl_test_int(status,exp_ier,"qagiu(myfn2) smooth status") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qagiu(myfn2) smooth alist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qagiu(myfn2) smooth blist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-14,"qagiu(myfn2) smooth rlist") ; for (i = 0; i < 5 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qagiu(myfn2) smooth elist") ; for (i = 0; i < 5 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qagiu(myfn2) smooth order"); gsl_integration_workspace_free (w) ; } /* Test integral f454 with integrable singular points */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = 5.274080611672716401E+01; double exp_abserr = 1.755703848687062418E-04; int exp_neval = 777; int exp_ier = 0; int exp_last = 20; double a[20] = { 9.687500000000000000E-01, 1.401269388548935790E+00, 1.414213562373095145E+00, 1.000000000000000000E+00, 0.000000000000000000E+00, 2.207106781186547462E+00, 1.810660171779821415E+00, 1.207106781186547462E+00, 5.000000000000000000E-01, 1.103553390593273731E+00, 1.612436867076458391E+00, 1.310660171779821415E+00, 7.500000000000000000E-01, 1.051776695296636976E+00, 1.513325214724776657E+00, 1.362436867076458391E+00, 8.750000000000000000E-01, 1.463769388548935790E+00, 1.388325214724776657E+00, 9.375000000000000000E-01} ; double b[20] = { 1.000000000000000000E+00, 1.414213562373095145E+00, 1.463769388548935790E+00, 1.051776695296636976E+00, 5.000000000000000000E-01, 3.000000000000000000E+00, 2.207106781186547462E+00, 1.310660171779821415E+00, 7.500000000000000000E-01, 1.207106781186547462E+00, 1.810660171779821415E+00, 1.362436867076458391E+00, 8.750000000000000000E-01, 1.103553390593273731E+00, 1.612436867076458391E+00, 1.388325214724776657E+00, 9.375000000000000000E-01, 1.513325214724776657E+00, 1.401269388548935790E+00, 9.687500000000000000E-01} ; double r[20] = { -1.125078814079027711E-01, -1.565132123531515207E-01, -4.225328513207429193E-01, -1.830392049835374568E-01, 6.575875041899758092E-03, 4.873920540843067783E+01, 6.032891565603589079E+00, -2.991531901645863023E-01, -7.326282608704996063E-03, -2.431894410706912923E-01, 5.911661670635662835E-01, -2.236786562536174916E-01, -5.647871991778510847E-02, -1.305470403178642658E-01, -1.721363984401322045E-01, -1.589345454585119055E-01, -7.406626263352669715E-02, -2.208730668000830344E-01, -1.048692749517999567E-01, -6.302287584527696551E-02} ; double e[20] = { 2.506431410088378817E-02, 2.730454695485963826E-02, 1.017446081816190118E-01, 3.252808038935910834E-02, 7.300687878575027348E-17, 5.411138804637469780E-13, 6.697855121200013106E-14, 3.321267596107916554E-15, 1.417509685426979386E-16, 2.699945168224041491E-15, 6.573952690524728748E-15, 2.483331942899818875E-15, 6.270397525408045936E-16, 1.449363299575615261E-15, 1.911097929242846383E-15, 1.764527917763735212E-15, 8.223007012367522077E-16, 2.452183642810224359E-15, 1.164282836272345215E-15, 6.996944784151910810E-16} ; int order[20] = { 3, 4, 2, 1, 6, 7, 11, 8, 10, 12, 18, 15, 16, 14, 19, 17, 20, 13, 9, 5 } ; gsl_function f = make_function(&f454, 0); gsl_function fc = make_counter(&f, &p) ; double pts[4] ; pts[0] = 0.0; pts[1] = 1.0; pts[2] = sqrt(2.0); pts[3] = 3.0; status = gsl_integration_qagp (&fc, pts, 4, 0.0, 1.0e-3, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qagp(f454) singular result") ; gsl_test_rel(abserr,exp_abserr,1e-5,"qagp(f454) singular abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qagp(f454) singular neval") ; gsl_test_int((int)(w->size),exp_last,"qagp(f454) singular last") ; gsl_test_int(status,exp_ier,"qagp(f454) singular status") ; for (i = 0; i < 20 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qagp(f454) singular alist") ; for (i = 0; i < 20 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qagp(f454) singular blist") ; for (i = 0; i < 20 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-14,"qagp(f454) singular rlist") ; for (i = 0; i < 20 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qagp(f454) singular elist") ; for (i = 0; i < 20 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qagp(f454) singular order"); gsl_integration_workspace_free (w) ; } /* Test cauchy integration using a relative error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = -8.994400695837000137E-02; double exp_abserr = 1.185290176227023727E-06; int exp_neval = 215; int exp_ier = 0; int exp_last = 6; double a[6] = { -1.000000000000000000E+00, 2.500000000000000000E+00, 1.250000000000000000E+00, 6.250000000000000000E-01, -5.000000000000000000E-01, -7.500000000000000000E-01} ; double b[6] = { -7.500000000000000000E-01, 5.000000000000000000E+00, 2.500000000000000000E+00, 1.250000000000000000E+00, 6.250000000000000000E-01, -5.000000000000000000E-01} ; double r[6] = { -1.234231128040012976E-01, 3.579970394639702888E-03, 2.249831615049339983E-02, 7.214232992127905808E-02, 2.079093855884046535E-02, -8.553244917962132821E-02} ; double e[6] = { 1.172832717970022565E-06, 9.018232896137375412E-13, 1.815172652101790755E-12, 1.006998195150956048E-13, 1.245463873006391609E-08, 1.833082948207153514E-15 } ; int order[6] = { 1, 5, 3, 2, 4, 6 } ; double alpha = 1.0 ; gsl_function f = make_function(&f459, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qawc (&fc, -1.0, 5.0, 0.0, 0.0, 1.0e-3, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qawc(f459) result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qawc(f459) abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qawc(f459) neval") ; gsl_test_int((int)(w->size),exp_last,"qawc(f459) last") ; gsl_test_int(status,exp_ier,"qawc(f459) status") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qawc(f459) alist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qawc(f459) blist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-14,"qawc(f459) rlist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qawc(f459) elist") ; for (i = 0; i < 6 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qawc(f459) order"); p.neval = 0; status = gsl_integration_qawc (&fc, 5.0, -1.0, 0.0, 0.0, 1.0e-3, w->limit, w, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-14,"qawc(f459) rev result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qawc(f459) rev abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qawc(f459) rev neval") ; gsl_test_int((int)(w->size),exp_last,"qawc(f459) rev last") ; gsl_test_int(status,exp_ier,"qawc(f459) rev status") ; gsl_integration_workspace_free (w) ; } /* Test QAWS singular integration using a relative error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_qaws_table * t = gsl_integration_qaws_table_alloc (0.0, 0.0, 1, 0); gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = -1.892751853489401670E-01; double exp_abserr = 1.129133712015747658E-08; int exp_neval = 280; int exp_ier = 0; int exp_last = 8; double a[8] = { 0.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02, 3.125000000000000000E-02, 1.562500000000000000E-02, 7.812500000000000000E-03} ; double b[8] = { 7.812500000000000000E-03, 1.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02, 3.125000000000000000E-02, 1.562500000000000000E-02} ; double r[8] = { -4.126317299834445824E-05, -1.076283950172247789E-01, -6.240573216173390947E-02, -1.456169844189576269E-02, -3.408925115926728436E-03, -8.914083918175634211E-04, -2.574191402137795482E-04, -8.034390712936630608E-05} ; double e[8] = { 1.129099387465713953E-08, 3.423394967694403596E-13, 6.928428071454762659E-16, 1.616673288784094320E-16, 3.784667152924835070E-17, 9.896621209399419425E-18, 2.857926564445496100E-18, 8.919965558336773736E-19} ; int order[8] = { 1, 2, 3, 4, 5, 6, 7, 8 } ; double alpha = 1.0 ; gsl_function f = make_function(&f458, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qaws (&fc, 0.0, 1.0, t, 0.0, 1.0e-7, w->limit, w, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qaws(f458) ln(x-a) result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qaws(f458) ln(x-a) abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qaws(f458) ln(x-a) neval") ; gsl_test_int((int)(w->size),exp_last,"qaws(f458) ln(x-a) last") ; gsl_test_int(status,exp_ier,"qaws(f458) ln(x-a) status") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qaws(f458) ln(x-a) alist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qaws(f458) ln(x-a) blist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-14,"qaws(f458) ln(x-a) rlist") ; for (i = 0; i < 6 ; i++) gsl_test_rel(w->elist[i],e[i],1e-4,"qaws(f458) ln(x-a) elist") ; for (i = 0; i < 6 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qaws(f458) ln(x-a) order"); /* Test without logs */ gsl_integration_qaws_table_set (t, -0.5, -0.3, 0, 0); status = gsl_integration_qaws (&fc, 0.0, 1.0, t, 0.0, 1.0e-7, w->limit, w, &result, &abserr) ; exp_result = 9.896686656601706433E-01; exp_abserr = 5.888032513201251628E-08; gsl_test_rel(result,exp_result,1e-14,"qaws(f458) AB result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qaws(f458) AB abserr") ; /* Test with ln(x - a) */ gsl_integration_qaws_table_set (t, -0.5, -0.3, 1, 0); status = gsl_integration_qaws (&fc, 0.0, 1.0, t, 0.0, 1.0e-7, w->limit, w, &result, &abserr) ; exp_result = -3.636679470586539620E-01; exp_abserr = 2.851348775257054093E-08; gsl_test_rel(result,exp_result,1e-14,"qaws(f458) AB ln(x-a) result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qaws(f458) AB ln(x-a) abserr") ; /* Test with ln(b - x) */ gsl_integration_qaws_table_set (t, -0.5, -0.3, 0, 1); status = gsl_integration_qaws (&fc, 0.0, 1.0, t, 0.0, 1.0e-7, w->limit, w, &result, &abserr) ; exp_result = -1.911489253363409802E+00; exp_abserr = 9.854016753016499034E-09; gsl_test_rel(result,exp_result,1e-14,"qaws(f458) AB ln(b-x) result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qaws(f458) AB ln(b-x) abserr") ; /* Test with ln(x - a) ln(b - x) */ gsl_integration_qaws_table_set (t, -0.5, -0.3, 1, 1); status = gsl_integration_qaws (&fc, 0.0, 1.0, t, 0.0, 1.0e-7, w->limit, w, &result, &abserr) ; exp_result = 3.159922862811048172E-01; exp_abserr = 2.336183482198144595E-08; gsl_test_rel(result,exp_result,1e-14,"qaws(f458) AB ln(x-a)ln(b-x) result") ; gsl_test_rel(abserr,exp_abserr,1e-6,"qaws(f458) AB ln(x-a)ln(b-x) abserr") ; gsl_integration_workspace_free (w) ; gsl_integration_qaws_table_free (t) ; } /* Test oscillatory integration using a relative error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; gsl_integration_qawo_table * wo = gsl_integration_qawo_table_alloc (10.0 * M_PI, 1.0, GSL_INTEG_SINE, 1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = -1.281368483991674190E-01; double exp_abserr = 6.875028324415666248E-12; int exp_neval = 305; int exp_ier = 0; int exp_last = 9; double a[9] = { 0.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02, 3.125000000000000000E-02, 1.562500000000000000E-02, 7.812500000000000000E-03, 3.906250000000000000E-03 } ; double b[9] = { 3.906250000000000000E-03, 1.000000000000000000E+00, 5.000000000000000000E-01, 2.500000000000000000E-01, 1.250000000000000000E-01, 6.250000000000000000E-02, 3.125000000000000000E-02, 1.562500000000000000E-02, 7.812500000000000000E-03 } ; double r[9] = { -1.447193692377651136E-03, 2.190541162282139478E-02, -2.587726479625663753E-02, 5.483209176363500886E-02, -3.081695575172510582E-02, -9.178321994387816929E-02, -3.886716016498160953E-02, -1.242306301902117854E-02, -3.659495117871544145E-03} ; double e[9] = { 8.326506625798146465E-07, 1.302638552580516100E-13, 7.259224351945759794E-15, 1.249770395036711102E-14, 7.832180081562836579E-16, 1.018998440559284116E-15, 4.315121611695628020E-16, 1.379237060008662177E-16, 4.062855738364339357E-17 } ; int order[9] = { 1, 2, 4, 3, 6, 5, 7, 8, 9 } ; double alpha = 1.0 ; gsl_function f = make_function(&f456, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qawo (&fc, 0.0, 0.0, 1e-7, w->limit, w, wo, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qawo(f456) result") ; gsl_test_rel(abserr,exp_abserr,1e-3,"qawo(f456) abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qawo(f456) neval") ; gsl_test_int((int)(w->size),exp_last,"qawo(f456) last") ; gsl_test_int(status,exp_ier,"qawo(f456) status") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->alist[i],a[i],1e-15,"qawo(f456) alist") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->blist[i],b[i],1e-15,"qawo(f456) blist") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-14,"qawo(f456) rlist") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->elist[i],e[i],1e-2,"qawo(f456) elist") ; for (i = 0; i < 9 ; i++) gsl_test_int((int)w->order[i],order[i]-1,"qawo(f456) order"); /* In reverse, flip limit and sign of length */ gsl_integration_qawo_table_set_length (wo, -1.0); p.neval = 0; status = gsl_integration_qawo (&fc, 1.0, 0.0, 1e-7, w->limit, w, wo, &result, &abserr) ; gsl_test_rel(result,-exp_result,1e-14,"qawo(f456) rev result") ; gsl_test_rel(abserr,exp_abserr,1e-3,"qawo(f456) rev abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qawo(f456) rev neval") ; gsl_test_int((int)(w->size),exp_last,"qawo(f456) rev last") ; gsl_test_int(status,exp_ier,"qawo(f456) rev status") ; gsl_integration_qawo_table_free (wo) ; gsl_integration_workspace_free (w) ; } /* Test fourier integration using an absolute error bound */ { int status = 0, i; struct counter_params p; double result = 0, abserr=0; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000) ; gsl_integration_workspace * wc = gsl_integration_workspace_alloc (1000) ; gsl_integration_qawo_table * wo = gsl_integration_qawo_table_alloc (M_PI / 2.0, 1.0, GSL_INTEG_COSINE, 1000) ; /* All results are for GSL_IEEE_MODE=double-precision */ double exp_result = 9.999999999279802765E-01; double exp_abserr = 1.556289974669056164E-08; int exp_neval = 590; int exp_ier = 0; int exp_last = 12; double r[12] = { 1.013283128125232802E+00, -1.810857954748607349E-02, 7.466754034900931897E-03, -4.360312526786496237E-03, 2.950184068216192904E-03, -2.168238443073697373E-03, 1.680910783140869081E-03, -1.352797860944863345E-03, 1.119354921991485901E-03, -9.462367583691360827E-04, 8.136341270731781887E-04, -7.093931338504278145E-04 } ; double e[12] = { 1.224798040766472695E-12, 1.396565155187268456E-13, 1.053844511655910310E-16, 6.505213034913026604E-19, 7.155734338404329264E-18, 1.105886215935214523E-17, 9.757819552369539906E-18, 5.854691731421723944E-18, 4.553649124439220312E-18, 7.643625316022806260E-18, 2.439454888092388058E-17, 2.130457268934021451E-17 } ; double alpha = 1.0 ; gsl_function f = make_function(&f457, &alpha); gsl_function fc = make_counter(&f, &p) ; status = gsl_integration_qawf (&fc, 0.0, 1e-7, w->limit, w, wc, wo, &result, &abserr) ; gsl_test_rel(result,exp_result,1e-14,"qawf(f457) result") ; gsl_test_rel(abserr,exp_abserr,1e-3,"qawf(f457) abserr") ; gsl_test_int((int)(p.neval),exp_neval,"qawf(f457) neval") ; gsl_test_int((int)(w->size),exp_last,"qawf(f457) last") ; gsl_test_int(status,exp_ier,"qawf(f457) status") ; for (i = 0; i < 9 ; i++) gsl_test_rel(w->rlist[i],r[i],1e-12,"qawf(f457) rlist") ; /* We can only get within two orders of magnitude on the error here, which is very sensitive to the floating point precision */ for (i = 0; i < 9 ; i++) gsl_test_rel(w->elist[i],e[i],50.0,"qawf(f457) elist") ; gsl_integration_qawo_table_free (wo) ; gsl_integration_workspace_free (wc) ; gsl_integration_workspace_free (w) ; } /* test Romberg integration */ { int status = 0; double result; size_t neval; double exp_result; int exp_ier = 0; gsl_function f; gsl_integration_romberg_workspace * w = gsl_integration_romberg_alloc (20); f = make_function(&f_sin, NULL); exp_result = 1.0; status = gsl_integration_romberg(&f, 0.0, M_PI_2, 0.0, 1e-10, &result, &neval, w); gsl_test_int(status, exp_ier, "romberg(f_sin) status") ; gsl_test_rel(result, exp_result, 1e-15, "romberg(f_sin) result") ; status = gsl_integration_romberg(&f, M_PI_2, 0.0, 0.0, 1e-10, &result, &neval, w); gsl_test_int(status, exp_ier, "romberg(f_sin) reverse status") ; gsl_test_rel(result, -exp_result, 1e-15, "romberg(f_sin) reverse result") ; f = make_function(&cqf11, NULL); exp_result = 5.0; status = gsl_integration_romberg(&f, -5.0, 5.0, 0.0, 1e-10, &result, &neval, w); gsl_test_int(status, exp_ier, "romberg(cqf11) status") ; gsl_test_rel(result, exp_result, 1e-15, "romberg(cqf11) result") ; status = gsl_integration_romberg(&f, 5.0, -5.0, 0.0, 1e-10, &result, &neval, w); gsl_test_int(status, exp_ier, "romberg(cqf11) reverse status") ; gsl_test_rel(result, -exp_result, 1e-15, "romberg(cqf11) reverse result") ; gsl_integration_romberg_free(w); } /* Sanity check monomial test function for fixed Gauss-Legendre rules */ { struct monomial_params params; gsl_function f; f.function = &f_monomial; f.params = &params; params.degree = 2; params.constant = 1.0; gsl_test_abs(GSL_FN_EVAL(&f, 2.0), 4.0, 8*GSL_DBL_EPSILON, "f_monomial sanity check 1"); params.degree = 1; params.constant = 2.0; gsl_test_abs(GSL_FN_EVAL(&f, 2.0), 4.0, 8*GSL_DBL_EPSILON, "f_monomial sanity check 2"); params.degree = 2; params.constant = 2.0; gsl_test_abs(integ_f_monomial(1.0, 2.0, &params), (2.0/3.0)*(2.0*2.0*2.0 - 1.0*1.0*1.0), 8*GSL_DBL_EPSILON, "integ_f_monomial sanity check"); } /* Test the fixed-order Gauss-Legendre rules with a monomial. */ { int n; struct monomial_params params; gsl_function f; const double a = 0.0, b = 1.2; f.function = &f_monomial; f.params = &params; params.constant = 1.0; for (n = 1; n < 1025; ++n) { double expected, result; gsl_integration_glfixed_table * tbl = gsl_integration_glfixed_table_alloc(n); params.degree = 2*n-1; /* n point rule exact for 2n-1 degree poly */ expected = integ_f_monomial(a, b, &params); result = gsl_integration_glfixed(&f, a, b, tbl); if (tbl->precomputed) { gsl_test_rel(result, expected, 1.0e-12, "glfixed %d-point: Integrating (%g*x^%d) over [%g,%g]", n, params.constant, params.degree, a, b); } else { gsl_test_rel(result, expected, 1.0e-7, "glfixed %d-point: Integrating (%g*x^%d) over [%g,%g]", n, params.constant, params.degree, a, b); } gsl_integration_glfixed_table_free(tbl); } } /* Sanity check sin(x) test function for fixed Gauss-Legendre rules */ { gsl_function f = { f_sin, NULL }; gsl_test_abs(GSL_FN_EVAL(&f, 2.0), sin(2.0), 0.0, "f_sin sanity check 1"); gsl_test_abs(GSL_FN_EVAL(&f, 7.0), sin(7.0), 0.0, "f_sin sanity check 2"); gsl_test_abs(integ_f_sin(0.0, M_PI), 2.0, GSL_DBL_EPSILON, "integ_f_sin sanity check"); } /* Test the fixed-order Gauss-Legendre rules against sin(x) on [0, pi] */ { const int n_max = 1024; const gsl_function f = { f_sin, NULL }; const double a = 0.0, b = M_PI; const double expected = integ_f_sin(a, b); double result, abserr, prev_abserr = 0.0; int n; for (n = 1; n <= n_max; ++n) { gsl_integration_glfixed_table * const tbl = gsl_integration_glfixed_table_alloc(n); result = gsl_integration_glfixed(&f, a, b, tbl); abserr = fabs(expected - result); if (n == 1) { gsl_test_abs(result, GSL_FN_EVAL(&f,(b+a)/2)*(b-a), 0.0, "glfixed %d-point: behavior for n == 1", n); } else if (n < 9) { gsl_test(! (abserr < prev_abserr), "glfixed %d-point: observed drop in absolute error versus %d-points", n, n-1); } else if (tbl->precomputed) { gsl_test_abs(result, expected, 2.0 * n * GSL_DBL_EPSILON, "glfixed %d-point: very low absolute error for high precision coefficients", n); } else { gsl_test_abs(result, expected, 1.0e6 * GSL_DBL_EPSILON, "glfixed %d-point: acceptable absolute error for on-the-fly coefficients", n); } prev_abserr = abserr; gsl_integration_glfixed_table_free(tbl); } } /* Test some fixed-order Gauss-Legendre rule points and weights on [-1, 1] */ /* This verifies the (point, weight) retrieval API behaves sanely */ { const double eps = GSL_DBL_EPSILON; gsl_integration_glfixed_table *tbl; int n, i; double xi, wi; /* Analytical results for points and weights on [-1, 1] Pulled from http://en.wikipedia.org/wiki/Gaussian_quadrature Sorted in increasing order of Gauss points */ const double e1[1][2] = { {0, 2 } }; const double e2[2][2] = { {-1.0/M_SQRT3, 1}, { 1.0/M_SQRT3, 1} }; const double e3[3][2] = { {-SQRT15/5, 5./9}, { 0, 8./9}, { SQRT15/5, 5./9} }; const double e4[4][2] = { {-CONST1, (18-SQRT30)/36}, {-CONST2, (18+SQRT30)/36}, { CONST2, (18+SQRT30)/36}, { CONST1, (18-SQRT30)/36} }; const double e5[5][2] = { {-CONST3, (322-13*SQRT70)/900}, {-CONST4, (322+13*SQRT70)/900}, { 0, 128./225 }, { CONST4, (322+13*SQRT70)/900}, { CONST3, (322-13*SQRT70)/900} }; n = 1; tbl = gsl_integration_glfixed_table_alloc(n); for (i = 0; i < n; ++i) { gsl_integration_glfixed_point(-1, 1, i, &xi, &wi, tbl); gsl_test_abs(xi, e1[i][0], eps, "glfixed %d-point lookup: x(%d)", n, i); gsl_test_abs(wi, e1[i][1], eps, "glfixed %d-point lookup: w(%d)", n, i); } gsl_integration_glfixed_table_free(tbl); n = 2; tbl = gsl_integration_glfixed_table_alloc(n); for (i = 0; i < n; ++i) { gsl_integration_glfixed_point(-1, 1, i, &xi, &wi, tbl); gsl_test_abs(xi, e2[i][0], eps, "glfixed %d-point lookup: x(%d)", n, i); gsl_test_abs(wi, e2[i][1], eps, "glfixed %d-point lookup: w(%d)", n, i); } gsl_integration_glfixed_table_free(tbl); n = 3; tbl = gsl_integration_glfixed_table_alloc(n); for (i = 0; i < n; ++i) { gsl_integration_glfixed_point(-1, 1, i, &xi, &wi, tbl); gsl_test_abs(xi, e3[i][0], eps, "glfixed %d-point lookup: x(%d)", n, i); gsl_test_abs(wi, e3[i][1], eps, "glfixed %d-point lookup: w(%d)", n, i); } gsl_integration_glfixed_table_free(tbl); n = 4; tbl = gsl_integration_glfixed_table_alloc(n); for (i = 0; i < n; ++i) { gsl_integration_glfixed_point(-1, 1, i, &xi, &wi, tbl); gsl_test_abs(xi, e4[i][0], eps, "glfixed %d-point lookup: x(%d)", n, i); gsl_test_abs(wi, e4[i][1], eps, "glfixed %d-point lookup: w(%d)", n, i); } gsl_integration_glfixed_table_free(tbl); n = 5; tbl = gsl_integration_glfixed_table_alloc(n); for (i = 0; i < n; ++i) { gsl_integration_glfixed_point(-1, 1, i, &xi, &wi, tbl); gsl_test_abs(xi, e5[i][0], eps, "glfixed %d-point lookup: x(%d)", n, i); gsl_test_abs(wi, e5[i][1], eps, "glfixed %d-point lookup: w(%d)", n, i); } gsl_integration_glfixed_table_free(tbl); } /* Test some fixed-order Gauss-Legendre rule points and weights on [-2, 3] */ /* This verifies the (point, weight) retrieval API is okay on non-[-1,1] */ { gsl_integration_glfixed_table *tbl; double result, x, w; int i; /* Odd n = 3, f(x) = x**5 + x**4 + x**3 + x**2 + x**1 + 1 */ result = 0; tbl = gsl_integration_glfixed_table_alloc(3); for (i = 0; i < 3; ++i) { gsl_integration_glfixed_point(-2, 3, i, &x, &w, tbl); result += w * (1 + x*(1 + x*(1 + x*(1 + x*(1 + x))))); } gsl_test_rel(result, 805./4, 1e-8, "glfixed %d-point xi,wi eval", 3); gsl_integration_glfixed_table_free(tbl); /* Even n = 4, f(x) = x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x**1 + 1 */ result = 0; tbl = gsl_integration_glfixed_table_alloc(4); for (i = 0; i < 4; ++i) { gsl_integration_glfixed_point(-2, 3, i, &x, &w, tbl); result += w * (1 + x*(1 + x*(1 + x*(1 + x*(1 + x*(1 + x*(1 + x))))))); } gsl_test_rel(result, 73925./56, 1e-8, "glfixed %d-point xi,wi eval", 4); gsl_integration_glfixed_table_free(tbl); } { typedef double (*fptr) ( double , void * ); const fptr funs[25] = { &cqf1 , &cqf2 , &cqf3 , &cqf4 , &cqf5 , &cqf6 , &cqf7 , &cqf8 , &cqf9 , &cqf10 , &cqf11 , &cqf12 , &cqf13 , &cqf14 , &cqf15 , &cqf16 , &cqf17 , &cqf18 , &cqf19 , &cqf20 , &cqf21 , &cqf22 , &cqf23 , &cqf24 , &cqf25 }; const double ranges[50] = { 0, 1 , 0, 1 , 0, 1 , -1, 1 , -1, 1 , 0, 1 , 0, 1 , 0, 1 , 0, 1 , 0, 1 , 0, 1 , 0, 1 , 0, 1 , 0, 10 , 0, 10 , 0, 10 , 0, 1 , 0, M_PI , 0, 1 , -1, 1 , 0, 1 , 0, 1 , 0, 1 , 0, 3 , 0, 5 }; const double f_exact[25] = { 1.7182818284590452354 , 0.7 , 2.0/3 , 0.4794282266888016674 , 1.5822329637296729331 , 0.4 , 2 , 0.86697298733991103757 , 1.1547005383792515290 , 0.69314718055994530942 , 0.3798854930417224753 , 0.77750463411224827640 , 0.49898680869304550249 , 0.5 , 1 , 0.13263071079267703209e+08 , 0.49898680869304550249 , 0.83867634269442961454 , -1 , 1.5643964440690497731 , 0.16349494301863722618 , -0.63466518254339257343 , 0.013492485649467772692 , 17.664383539246514971 , 7.5 }; double result, abserr; size_t neval; int fid; /* Loop over the functions... */ for ( fid = 0 ; fid < 25 ; fid++ ) { gsl_integration_cquad_workspace *ws = gsl_integration_cquad_workspace_alloc ( 200 ); gsl_function f = make_function(funs[fid], NULL); double exact = f_exact[fid]; /* Call our quadrature routine. */ int status = gsl_integration_cquad (&f, ranges[2*fid] , ranges[2*fid+1] , 0.0 , 1.0e-12 , ws , &result , &abserr , &neval); gsl_test_rel (result, exact, 1e-12, "cquad f%d", fid); gsl_test (fabs(result - exact) > 5.0 * abserr, "cquad f%d error (%g actual vs %g estimated)", fid, fabs(result-exact), abserr); gsl_test_int (status, GSL_SUCCESS, "cquad return code"); gsl_integration_cquad_workspace_free(ws); } } /* test fixed quadrature */ { size_t n; struct monomial_params params; gsl_function f; double exact; double a, b; int deg = 5; /* monomial degree */ double dterm = (deg % 2) == 0 ? 1.0 : -1.0; f.function = &f_monomial; f.params = &params; params.degree = deg; params.constant = 1.0; n = 15; for (b = 1.1; b <= 4.0; b += 0.1) { /* test with a < b */ a = b - 1.0; /* Legendre quadrature */ exact = (pow(b,params.degree+1.0) - pow(a,params.degree+1.0))/(params.degree+1.0); test_fixed_quadrature(gsl_integration_fixed_legendre, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "legendre monomial"); /* Chebyshev type 1 quadrature */ exact = GSL_SIGN(b-a)*M_PI*pow(0.5*(a+b),params.degree)*gsl_sf_hyperg_2F1(0.5*(1-params.degree),-0.5*params.degree,1.0,(b-a)*(b-a)/((b+a)*(b+a))); test_fixed_quadrature(gsl_integration_fixed_chebyshev, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "chebyshev monomial"); /* Laguerre quadrature */ exact = pow(b, -1.0 - deg) * exp(a * b) * gsl_sf_gamma_inc(1.0 + deg, a * b); test_fixed_quadrature(gsl_integration_fixed_laguerre, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "laguerre monomial"); /* Hermite quadrature */ exact = 0.5 * pow(b, -0.5*deg) * (-(-1.0 + dterm) * a * deg * gsl_sf_gamma(0.5*deg) * gsl_sf_hyperg_1F1(0.5 - 0.5*deg, 1.5, -a*a*b) + (1.0 + dterm) * gsl_sf_gamma(0.5*(1.0+deg)) * gsl_sf_hyperg_1F1(-0.5*deg, 0.5, -a*a*b) / sqrt(b)); test_fixed_quadrature(gsl_integration_fixed_hermite, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "hermite monomial"); /* Chebyshev type 2 quadrature */ exact = GSL_SIGN(b-a)*M_PI_2*pow(0.5*(a+b),params.degree)*gsl_sf_hyperg_2F1(0.5*(1-params.degree),-0.5*params.degree,2.0,(b-a)*(b-a)/((b+a)*(b+a)))*0.25*(b-a)*(b-a); test_fixed_quadrature(gsl_integration_fixed_chebyshev2, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "chebyshev2 monomial"); /* now test with a > b */ a = b + 1.0; /* Legendre quadrature */ exact = (pow(b,params.degree+1.0) - pow(a,params.degree+1.0))/(params.degree+1.0); test_fixed_quadrature(gsl_integration_fixed_legendre, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "legendre monomial"); /* Laguerre quadrature */ exact = pow(b, -1.0 - deg) * exp(a * b) * gsl_sf_gamma_inc(1.0 + deg, a * b); test_fixed_quadrature(gsl_integration_fixed_laguerre, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "laguerre monomial"); /* Hermite quadrature */ exact = 0.5 * pow(b, -0.5*deg) * (-(-1.0 + dterm) * a * deg * gsl_sf_gamma(0.5*deg) * gsl_sf_hyperg_1F1(0.5 - 0.5*deg, 1.5, -a*a*b) + (1.0 + dterm) * gsl_sf_gamma(0.5*(1.0+deg)) * gsl_sf_hyperg_1F1(-0.5*deg, 0.5, -a*a*b) / sqrt(b)); test_fixed_quadrature(gsl_integration_fixed_hermite, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "hermite monomial"); #if 0 /* FIXME: Chebyshev doesn't work when a > b */ /* Chebyshev type 1 quadrature */ exact = -M_PI / 8.0 * (3.0*a*a + 2.0*a*b + 3.0*b*b); test_fixed_quadrature(gsl_integration_fixed_chebyshev, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "chebyshev monomial"); /* Chebyshev type 2 quadrature */ exact = -M_PI / 128.0 * (a - b) * (a - b) *(5.0*a*a + 6.0*a*b + 5.0*b*b); test_fixed_quadrature(gsl_integration_fixed_chebyshev2, n, a, b, 0.0, 0.0, 1.0e-12, exact, &f, "chebyshev2 monomial"); #endif } /* now test on myfn1 */ f = make_function(&myfn1, 0); n = 200; test_fixed_quadrature(gsl_integration_fixed_legendre, n, 1.2, 1.6, 0.0, 0.0, 1.0e-12, 0.01505500344456001, &f, "legendre myfn1"); test_fixed_quadrature(gsl_integration_fixed_chebyshev, n, 1.2, 2.6, 0.0, 0.0, 1.0e-12, 0.0582346516219999, &f, "chebyshev myfn1"); test_fixed_quadrature(gsl_integration_fixed_gegenbauer, n, 1.2, 1.6, 2.0, 0.0, 1.0e-12, 1.2279468957162412661311711271e-5, &f, "gegenbauer myfn1"); test_fixed_quadrature(gsl_integration_fixed_gegenbauer, n, 1.2, 1.6, -0.5, 0.0, 1.0e-12, 1.228256086101808986e-1, &f, "gegenbauer myfn1"); test_fixed_quadrature(gsl_integration_fixed_jacobi, n, 1.2, 1.6, 2.0, 1.5, 1.0e-12, 3.173064776410033e-5, &f, "jacobi myfn1"); test_fixed_quadrature(gsl_integration_fixed_jacobi, n, 1.2, 1.6, -0.5, -0.5, 1.0e-12, 1.228256086101808986e-1, &f, "jacobi myfn1"); test_fixed_quadrature(gsl_integration_fixed_laguerre, n, 1.2, 0.6, 0.5, 0.0, 1.0e-12, 0.006604180366378123, &f, "laguerre myfn1"); test_fixed_quadrature(gsl_integration_fixed_hermite, n, 1.2, 0.6, 1.0, 0.0, 1.0e-12, 0.6542819629825344, &f, "hermite myfn1"); test_fixed_quadrature(gsl_integration_fixed_exponential, n, 1.2, 1.6, 2.0, 0.0, 1.0e-12, 2.1315535492168832898083633e-4, &f, "exponential myfn1"); test_fixed_quadrature(gsl_integration_fixed_rational, 15, 1.2, 1.6, 2.0, -33.4, 1.0e-9, 4.8457468060064844e-20, &f, "rational myfn1"); test_fixed_quadrature(gsl_integration_fixed_chebyshev2, n, 1.2, 2.6, 0.0, 0.0, 1.0e-12, 0.0081704088896491, &f, "chebyshev2 myfn1"); } /* test Gegenbauer quadrature */ { size_t n, k; struct monomial_params params; gsl_function f; const double exactarray[5] = {4.15933612154155020161400717857e-7, 744697.808572324010134504819452, 55.2024994284578980512106835228, 7.95574829722734114107142857143, 0.00179653588816666666666666666667}; const double aarray[5] = {0.123,7.747,1.47,-1.47,0.0}; const double barray[5] = {0.456,12.0,2.0,2.0,0.47}; const double alphaarray[5] = {2.0,0.5,-0.5,1.0,0.0}; f.function = &f_monomial; f.params = &params; params.degree = 5; params.constant = 1.0; n = 50; for ( k = 0; k < 5; k++) { test_fixed_quadrature(gsl_integration_fixed_gegenbauer, n, aarray[k], barray[k], alphaarray[k], 0.0, 1.0e-12, exactarray[k], &f, "gegenbauer monomial"); } } /* test Jacobi quadrature */ { size_t n, k; struct monomial_params params; gsl_function f; const double exactarray[5] = {9.052430592016123480501898e-7,3.131716150347619771233591755e6,0.04435866422797298224404592896,5.287059602300844442782407,2.5337038518475893688512749675e-6}; const double aarray[5] = {0.123,7.747,1.47,-1.47,0.0}; const double barray[5] = {0.456,12.0,2.0,2.0,0.47}; double alpha, beta; f.function = &f_monomial; f.params = &params; params.degree = 5; params.constant = 1.0; alpha = 2.0; beta = 1.5; n = 50; for ( k = 0; k < 5; k++) { test_fixed_quadrature(gsl_integration_fixed_jacobi, n, aarray[k], barray[k], alpha, beta, 1.0e-12, exactarray[k], &f, "jacobi monomial"); } } /* test Exponential quadrature */ { size_t n, k; struct monomial_params params; gsl_function f; const double exactarray[5] = {1.598864206823942764921875e-4, 624615.81848571833291063083819, 0.222578063871903188095238095238, 28.8968950008739567709168294271, 4.62725113500425479890950520833e-7}; const double aarray[5] = {0.123,7.747,1.47,-1.47,0.0}; const double barray[5] = {0.456,12.0,2.0,2.0,0.47}; const double alphaarray[5] = {1.0,1.5,2.0,3.0,5.0}; f.function = &f_monomial; f.params = &params; params.degree = 5; params.constant = 1.0; n = 50; for ( k = 0; k < 5; k++) { test_fixed_quadrature(gsl_integration_fixed_exponential, n, aarray[k], barray[k], alphaarray[k], 0.0, 1.0e-12, exactarray[k], &f, "exponential monomial"); } } /* test Rational quadrature */ { size_t n, k; struct monomial_params params; gsl_function f; const double exactarray[6] = {1.312245361412108703130374957e-10,0.0170362044485924082779613124672, 8.93065131938394658578136414201e-11, 7.17990217357447544326794457270e-13, -11.0760676986664098133970869634, 0.00290392485414197833688178206557}; const double aarray[6] = {0.0,0.123,7.747,1.47,-1.47,0.0}; const double barray[6] = {2.0,0.456,12.0,2.0,2.0,0.47}; const double alphaarray[6] = {0.0,1.0,1.5,2.0,3.0,5.0}; const double betaarray[6] = {-21.0,-12.0,-13.0,-22.0,-21.0,-16.0}; f.function = &f_monomial; f.params = &params; params.degree = 5; params.constant = 1.0; n = 5; for ( k = 0; k < 5; k++) { test_fixed_quadrature(gsl_integration_fixed_rational, n, aarray[k], barray[k], alphaarray[k], betaarray[k], 1.0e-12, exactarray[k], &f, "rational monomial"); } } exit (gsl_test_summary()); } void my_error_handler (const char *reason, const char *file, int line, int err) { if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err) ; }
{ "alphanum_fraction": 0.583750463, "avg_line_length": 39.8648239303, "ext": "c", "hexsha": "5cc008544c3dbc390740519e6cbe486e837b826e", "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/integration/test.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/integration/test.c", "max_line_length": 247, "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/integration/test.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": 36770, "size": 105283 }
#pragma once #include <string_view> #include <gsl/span> namespace kab_advent { auto day(gsl::span<std::string_view const> args) -> int; }
{ "alphanum_fraction": 0.7214285714, "avg_line_length": 17.5, "ext": "h", "hexsha": "733c19fe53d22bffa2454a13a5cd861af00ae4c6", "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": "204da8c589ed6290b919cc23d1cfbe083b61bbc4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "KABoissonneault/AdventOfCode2017", "max_forks_repo_path": "src/day.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "204da8c589ed6290b919cc23d1cfbe083b61bbc4", "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": "KABoissonneault/AdventOfCode2017", "max_issues_repo_path": "src/day.h", "max_line_length": 57, "max_stars_count": null, "max_stars_repo_head_hexsha": "204da8c589ed6290b919cc23d1cfbe083b61bbc4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "KABoissonneault/AdventOfCode2017", "max_stars_repo_path": "src/day.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 37, "size": 140 }
#ifndef VEC_WRAPPER_H #define VEC_WRAPPER_H #include <atomic> #include <gsl/gsl_vector.h> class Vector { public: Vector(); // null Vector(gsl_vector *wrap); Vector(const size_t length); Vector(const Vector& copy); virtual ~Vector(); gsl_vector *get() const; void set(gsl_vector *newVector); void reset(gsl_vector *newVector); void reset(const size_t length); explicit operator bool() const; Vector &operator =(const Vector& copy); void operator *=(const Vector& other); double operator [](const size_t i) const; double& operator [](const size_t i); void coords(); void uncoords(); void basis(size_t i); private: gsl_vector *m_vec; std::atomic<unsigned int> m_delCount; }; #endif // VEC_WRAPPER_H
{ "alphanum_fraction": 0.6603295311, "avg_line_length": 17.152173913, "ext": "h", "hexsha": "e410c41ce21b7556d5575b8acf38566273c03075", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_path": "inc/vector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "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": "ichi-rika/glottal-inverse", "max_issues_repo_path": "inc/vector.h", "max_line_length": 45, "max_stars_count": 6, "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_path": "inc/vector.h", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "num_tokens": 191, "size": 789 }
#ifndef SNPINFER_DATASTRUCTURE #define SNPINFER_DATASTRUCTURE #define NUMPRECISION 1e-6 #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <vector> #include <algorithm> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <iterator> #include <omp.h> #include <sys/stat.h> using namespace std; #define GSL_DLL #include <gsl/gsl_sys.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_fit.h> typedef struct SNPINFO { string chr; int posst, posed;//, label; //int err, info, st, ed, shift; string snpid; //double qual; //vector<char> alleles; } SNPINFO; #define MINUSINFINITE -1000000000 #define PI 3.14159265359 typedef struct MYDATA { int indN, totalN, L, ploidity; //indN = N*plodity, totalN = N, but if replicates > 1, then totalN > N int *indIndex; //index of individuals (true individuals, not haploids, length+1 for total copies, =totalN) (necessary when there are replicates per individual) float *data; //length = indindex[last]*ploidity*L; int *asz; vector<vector<int> > fixState; //fix states, ~ pop, indN of them vector<vector<bool> > fixAllele; //fix data without imputation, ~ data, totalN of them; NOTE: false is fix, true is to impute! vector<vector<int> > breaks; //must contain start and end position as double breaks //additional info vector<SNPINFO> snpinfo; vector<string> indinfo; vector<string> fyinfo, fxinfo; } MYDATA; typedef struct PARAUNIT { vector<float> allele; int lapseN, popN; } PARAUNIT; typedef struct TENSORPARA { //recombination parameters double priorW, probAlpha, defmut, *rPrior, *popr; //priorW is for recomb rate //probAlpha is for states proportion bool *rec, *lapse; float *recombN, trueindN; float *indWeight, *idw; //parameter for states int maxK, maxHapK; //maxHapK is used if number of states is fixed;//12/18/15: maxK is current number of cluster? and maxHapK is the maximum allowed if >0? int *pop; float *nh; vector<vector<PARAUNIT> > param; //LxKxZ, where K=maxK, Z=asz vector<vector<int> > flips; double *Vh, *Q, A; //control parameters int burnin, mcmc; bool shrinkclass, singlecall, imputedata; bool addsample; //graudually add samples, used for haplotype inference bool samplefull; //true for haplotype inference char changeAlpha; //add (>0) or reduce (<0) probAlpha at the begining, add used for haplotype inference, reduce used for stratification mapping int splitstop; //# of pops, beyond which no more splitting int refweight; //weight of reference data with known states char maximum; //sample or maximize, 3bits abc: a: maximum recomb, b: maximum state, c: maximum allele bool samplemaximum; //indicating if first sample and then take maximum, used for pop inference bool logscale; //indicating if probability is in local scale, used for popinfer double recrate; //recombination rate to be used for set up recomb priors int recombcut; //above which position specific recomb is counted double heteroVh; //0 if Vh is global, > 0 if locally Vh changes. Only implemented for ploidity = 1, and not implemented in greedyswitch function } TENSORPARA; typedef struct TENSORPARAP0 { float *recombN0; float *nh0; //*nh0pp; double *Q0; unsigned short *param0;//, *param0pp; int clustersz0, popn0, unitsz0, totalN0; } TENSORPARA0; inline float fast_log2(float val) { int * const exp_ptr = reinterpret_cast <int *> (&val); int x = *exp_ptr; const int log_2 = ((x >> 23) & 255) - 128; x &= ~(255 << 23); x += 127 << 23; *exp_ptr = x; val = ((-1.0f/3) * val + 2) * val - 2.0f/3; // (1) return (val + log_2); } inline float fast_log(const float &val) { return (fast_log2 (val) * 0.69314718f); } //void call_IDEAS(int, char *argv[]); #endif
{ "alphanum_fraction": 0.711053316, "avg_line_length": 31.2601626016, "ext": "h", "hexsha": "487c223b8856c26aed0bdda1abf42d94369f662e", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2022-01-17T23:26:07.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-13T21:03:24.000Z", "max_forks_repo_head_hexsha": "c0b1720344aefbdc257c02ceb70b9fc06e52b4b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "guanjue/S3V2_IDEAS_ESMP", "max_forks_repo_path": "bin/IDEAS_2018/IDEAS_APP/datastructure.h", "max_issues_count": 14, "max_issues_repo_head_hexsha": "5881efae8e42ce711766d021a88e2cfe309a1f52", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:59:06.000Z", "max_issues_repo_issues_event_min_datetime": "2018-07-19T04:03:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "guanjue/IDEAS_2018", "max_issues_repo_path": "IDEAS_APP/datastructure.h", "max_line_length": 160, "max_stars_count": 8, "max_stars_repo_head_hexsha": "c0b1720344aefbdc257c02ceb70b9fc06e52b4b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "guanjue/S3V2_IDEAS_ESMP", "max_stars_repo_path": "python_pipe/bin/IDEAS_2018/IDEAS_APP/datastructure.h", "max_stars_repo_stars_event_max_datetime": "2021-08-31T18:47:56.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-09T18:59:03.000Z", "num_tokens": 1138, "size": 3845 }
//im_clam.c -- // A. Kern 3/20/15 // // Composite Likelihood estimation of canonical IM models via AFS //going to use NLopt for optimization #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <nlopt.h> #include "AFS.h" #include "adkGSL.h" #include "cs.h" #include "time.h" #include <unistd.h> #include "adkCSparse.h" #include "AFS_ctmc.h" #include <slepcmfn.h> #include "AFS_ctmc_petsc.h" #include "im_clam.h" void import2DSFSData(const char *fileName, gsl_matrix *obsData); PetscInt n1, n2; afsStateSpace *stateSpace, *reducedStateSpace; clam_lik_params *currentParams, *nextParams; gsl_matrix *transMat; double *res; double lowerBounds[5] = {0.01,0.01,0.0,0.0,0.001}; double upperBounds[5] = {10.0,10.0,20.0,20.0,10.0}; PetscBool vbse = PETSC_FALSE; static char help[] = "im_clam\n\ Example: mpiexec -n <np> ./im_clam -s <stateSpace file> -m <mats file> -d <data file> \n\n\toptions:\n\ \t-exp expected value mode (requires -x flag too)\n\ \t-GIM uncertainty estimation mode (requires -x flag too)\n\ \t-mo multiple optimizations from different start points\n\ \t-global multi-level optimization (MLSL algo.)\n\ \t-x <theta_2, theta_A, mig12, mig21, t_div> parameter starting values\n\ \t-obs (prints out observed AFS as well as that expected from MLE params)\n\ \t-u mutation rate per base pair per generation (only used to unscale parameters; default 1e-8)\n\ \t-g generation time (gens/year; default 20)\n\ \t-seqLen sequence length scanned for polymorphisms (used to unscale parameter)\n\ \t-put upper bound for optimization of thetas\n\ \t-pum upper bound for optimization of migration rates\n\ \t-pudt upper bound for optimization of divergence time\n\ \t-r randomSeed\n\ \t-v verbose output\n"; int main(int argc, char **argv){ PetscInt i,j, N,runMode; clock_t time1, time2; PetscInt nnz; PetscInt seed; char filename[PETSC_MAX_PATH_LEN], filename2[PETSC_MAX_PATH_LEN], filename3[PETSC_MAX_PATH_LEN] ; double lik = 0.0; double mle[5] = {0.1,2,1,1,5}; const gsl_rng_type * T; gsl_rng * r; PetscErrorCode ierr; PetscMPIInt rank,size; PetscBool flg,obsFlag; // Vec tmpVec; PetscInt dim=5; double snpNumber, pi_est, p, N0; double u=1e-8; double genPerYear=20; double put = 10.0; double pum = 20.0; double pudt=10.0; double propSnp; PetscInt seqLen; gsl_matrix *fi,*gi; FILE *infile; PetscInt testInt=0; PetscScalar one = 1.0; cs *ident; /////////////////// ///// PETSC / Slepc library version of this code SlepcInitialize(&argc,&argv,(char*)0,help); ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank);CHKERRQ(ierr); ierr = MPI_Comm_size(PETSC_COMM_WORLD, &size);CHKERRQ(ierr); if(rank==0){ printf("\n.___ _____ .__\n| | / \\ ____ | | _____ _____\n| |/ \\ / \\ _/ ___\\| | \\__ \\ / \\\n| / Y \\ \\ \\___| |__/ __ \\| Y Y \\\n|___\\____|__ /____\\___ >____(____ /__|_| /\n \\/_____/ \\/ \\/ \\/\n\n\n"); printf("im_clam -- Isolation with Migration Composite Likelihood Analysis using Markov chains\n"); //printf("A.D. Kern 2015\n///////////////////\n"); printf("\n\n"); } if(argc<2){ printf("%s",help); exit(666); } time1=clock(); ierr = PetscOptionsGetString(NULL,"-s",filename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetString(NULL,"-m",filename2,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetString(NULL,"-d",filename3,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetInt(NULL,"-r",&seed,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-u",&u,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-g",&genPerYear,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetInt(NULL,"-seqLen",&seqLen,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-put",&put,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-pum",&pum,&flg);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-pudt",&pudt,&flg);CHKERRQ(ierr); //set upper bounds upperBounds[0]=put;upperBounds[1]=put;upperBounds[2]=pum;upperBounds[3]=pum;upperBounds[4]=pudt; if(!flg) seed=time(NULL); //printf("rank:%d %d\n",rank,seed); MPI_Bcast(&seed,1,MPI_INT,0,PETSC_COMM_WORLD); //printf("rank:%d %d\n",rank,seed); runMode = 1; obsFlag=PETSC_FALSE; //setup RNG for starting point for optimization gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); gsl_rng_set(r,seed); for(i=0;i<dim;i++){ mle[i] = gsl_ran_flat(r,lowerBounds[i], upperBounds[i]); } PetscOptionsHasName(NULL,"-v",&flg); if(flg) vbse=PETSC_TRUE; PetscOptionsHasName(NULL,"-obs",&flg); if(flg) obsFlag=PETSC_TRUE; PetscOptionsHasName(NULL,"-exp",&flg); if(flg) runMode=2; ierr = PetscOptionsGetRealArray(NULL,"-x",mle,&dim,&flg);CHKERRQ(ierr); //double check we are set for exp mode if(runMode == 2 && !flg){ printf("for exp runmode need to set parameter values using -x flag\n"); exit(1); } PetscOptionsHasName(NULL,"-mo",&flg); if(flg) runMode=3; PetscOptionsHasName(NULL,"-global",&flg); if(flg) runMode=4; PetscOptionsHasName(NULL,"-GIM",&flg); if(flg) runMode=5; //import state space stateSpace = afsStateSpaceImportFromFile(filename); N = stateSpace->nstates; //quick peak at the mats file to set nnz //open file infile = fopen(filename2, "r"); if (infile == NULL){ fprintf(stderr,"Error opening mats file! ARRRRR!!!!\n"); exit(1); } testInt=fscanf(infile,"nnz: %d", &nnz); fclose(infile); //got nnz, time for allocs //setup currentParams struct; alloc all arrays currentParams = malloc(sizeof(clam_lik_params)); currentParams->rng = r; currentParams->n1 = n1 = stateSpace->states[0]->popMats[0]->size1 - 1; currentParams->n2 = n2 = stateSpace->states[0]->popMats[1]->size2 - 1; currentParams->stateSpace = stateSpace; currentParams->rank = rank; // currentParams->snpNumber = snpNumber; currentParams->expAFS = gsl_matrix_alloc(n1+1,n2+1); currentParams->expAFS2 = gsl_matrix_alloc(n1+1,n2+1); currentParams->map = malloc(sizeof(PetscInt)*N); currentParams->reverseMap = malloc(sizeof(PetscInt)*N); currentParams->rates = gsl_vector_alloc(stateSpace->nstates); currentParams->stateVec = gsl_vector_alloc(stateSpace->nstates); currentParams->resVec = gsl_vector_alloc(stateSpace->nstates); gsl_vector_set_zero(currentParams->resVec); // currentParams->paramVector = gsl_vector_alloc(5); // currentParams->paramCIUpper = gsl_vector_alloc(5); // currentParams->paramCILower = gsl_vector_alloc(5); // currentParams->mlParams = gsl_vector_alloc(5); currentParams->top = malloc(sizeof(double) * nnz); currentParams->topA = malloc(sizeof(double) * nnz); currentParams->move = malloc(sizeof(PetscInt) * nnz); currentParams->moveA = malloc(sizeof(PetscInt) * nnz); // printf("allocated moveType...\n"); for(i=0;i< (nnz);i++){ currentParams->move[i]=0; currentParams->top[i]=0; currentParams->moveA[i]=0; currentParams->topA[i]=0; } currentParams->dim1 = malloc(sizeof(PetscInt) * nnz); currentParams->dim2 = malloc(sizeof(PetscInt) * nnz); currentParams->dim1A = malloc(sizeof(PetscInt) * N * 10); currentParams->dim2A = malloc(sizeof(PetscInt) * N * 10); currentParams->b = malloc(N*sizeof(double)); currentParams->expoArray = malloc(N*sizeof(double)); currentParams->st = malloc(N*sizeof(double)); currentParams->paramVector = gsl_vector_alloc(5); gsl_vector_set_all(currentParams->paramVector,1.0); currentParams->fEvals=0; currentParams->triplet = cs_spalloc(N, N, nnz + N , 1, 1); //alloc sparse mat with extra space for nonzero identity mats ident = cs_spalloc(N,N,N,1,1); for(i=0;i<N;i++) cs_entry(ident,i,i,1); currentParams->eye = cs_compress(ident); cs_spfree(ident); //set up some petsc matrices////////////////////////////////////////////////////////////// // // ierr = MatCreate(PETSC_COMM_WORLD,&currentParams->C);CHKERRQ(ierr); // MatSetType(C,MATMPIAIJ); ierr = MatSetSizes(currentParams->C, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr); ierr = MatSetFromOptions(currentParams->C);CHKERRQ(ierr); // MatSetOption(currentParams->C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE); ierr = MatSetUp(currentParams->C);CHKERRQ(ierr); ierr = MatCreateDense(PETSC_COMM_WORLD,PETSC_DECIDE, PETSC_DECIDE, N, N, NULL, &currentParams->denseMat1);CHKERRQ(ierr); ierr = MatSetFromOptions(currentParams->denseMat1);CHKERRQ(ierr); MatAssemblyBegin(currentParams->denseMat1,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(currentParams->denseMat1,MAT_FINAL_ASSEMBLY); ///////// Set up MFN //////////////////////////////////////////////////////////////////////////////////////// ierr = MFNCreate(PETSC_COMM_WORLD,&currentParams->mfn);CHKERRQ(ierr); ierr = MFNSetFunction(currentParams->mfn,SLEPC_FUNCTION_EXP);CHKERRQ(ierr); ierr = MFNSetTolerances(currentParams->mfn,1e-07,PETSC_DEFAULT);CHKERRQ(ierr); //mapping stateSpace to reducedSpace currentParams->reducedStateSpace = afsStateSpaceNew(); afsStateSpaceMapAndReducePopn(currentParams->stateSpace, currentParams->map, currentParams->reducedStateSpace, currentParams->reverseMap); currentParams->Na=currentParams->reducedStateSpace->nstates; VecCreate(PETSC_COMM_WORLD,&currentParams->ancStateVec); VecSetSizes(currentParams->ancStateVec,PETSC_DECIDE,currentParams->Na); VecSetFromOptions(currentParams->ancStateVec); VecDuplicate(currentParams->ancStateVec,&currentParams->ancResVec); //set up more matrices ierr = MatCreate(PETSC_COMM_WORLD,&currentParams->C2);CHKERRQ(ierr); MatSetType(currentParams->C2,MATMPIAIJ); ierr = MatSetSizes(currentParams->C2, PETSC_DECIDE, PETSC_DECIDE,currentParams->Na,currentParams->Na);CHKERRQ(ierr); ierr = MatSetFromOptions(currentParams->C2);CHKERRQ(ierr); ierr = MatSetUp(currentParams->C2);CHKERRQ(ierr); ierr = MatCreateDense(PETSC_COMM_WORLD,PETSC_DECIDE, PETSC_DECIDE, currentParams->Na, currentParams->Na, NULL, &currentParams->denseMat2);CHKERRQ(ierr); ident = cs_spalloc(currentParams->Na,currentParams->Na,currentParams->Na,1,1); for(i=0;i<currentParams->Na;i++) cs_entry(ident,i,i,1); currentParams->eyeAnc = cs_compress(ident); cs_spfree(ident); //DTMC with PETSC ///////////// // ierr = MatCreate(PETSC_COMM_WORLD,&currentParams->D);CHKERRQ(ierr); // ierr = MatSetSizes(currentParams->D, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr); // ierr = MatSetFromOptions(currentParams->D);CHKERRQ(ierr); // ierr = MatSetUp(currentParams->D);CHKERRQ(ierr); // ierr = MatCreate(PETSC_COMM_WORLD,&currentParams->D_copy);CHKERRQ(ierr); // ierr = MatSetSizes(currentParams->D_copy, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr); // ierr = MatSetFromOptions(currentParams->D_copy);CHKERRQ(ierr); // ierr = MatSetUp(currentParams->D_copy);CHKERRQ(ierr); //sparse identity mat // ierr = MatCreate(PETSC_COMM_WORLD,&currentParams->ident);CHKERRQ(ierr); // ierr = MatSetSizes(currentParams->ident, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr); // ierr = MatSetFromOptions(currentParams->ident);CHKERRQ(ierr); // ierr = MatSetUp(currentParams->ident);CHKERRQ(ierr); // MatAssemblyBegin(currentParams->ident,MAT_FINAL_ASSEMBLY); // MatAssemblyEnd(currentParams->ident,MAT_FINAL_ASSEMBLY); // MatShift(currentParams->ident,one); //dense identity mat // ierr = MatCreateDense(PETSC_COMM_WORLD,PETSC_DECIDE, PETSC_DECIDE, N, N, NULL, &currentParams->denseIdent);CHKERRQ(ierr); // ierr = MatSetFromOptions(currentParams->denseIdent);CHKERRQ(ierr); // MatAssemblyBegin(currentParams->denseIdent,MAT_FINAL_ASSEMBLY); // MatAssemblyEnd(currentParams->denseIdent,MAT_FINAL_ASSEMBLY); // MatShift(currentParams->denseIdent,one); // VecCreate(PETSC_COMM_WORLD,&currentParams->xInv); // VecSetSizes(currentParams->xInv,PETSC_DECIDE,N); // VecSetFromOptions(currentParams->xInv); // VecDuplicate(currentParams->xInv,&currentParams->bInv); /////////////////////////////////////// ////////////////////////////// // setup done! /////////////// //////////////////////////////////// //import mats mcMatsImportFromFile(filename2, &nnz, currentParams->top, currentParams->move, currentParams->dim1, currentParams->dim2); currentParams->nnz = nnz; //init snpNumber to avoid compiler warning snpNumber=0; if(runMode != 2){ //alloc data matrix and import data; estimate pi and N1 currentParams->obsData = gsl_matrix_alloc(n1+1,n2+1); import2DSFSData(filename3, currentParams->obsData); snpNumber = gsl_matrix_sum(currentParams->obsData); propSnp = (float) snpNumber / (float) seqLen; // pi_est = 0.0; // for(i=1;i<n1;i++){ // for(j=0;j<n2+1;j++){ // p = (float) i / n1; // pi_est += (2 * p * (1.0 - p)) * gsl_matrix_get(currentParams->obsData,i,j); // } // } // pi_est *= n1 / (n1 - 1) / snpNumber; // N0=pi_est / u / 4; } //////////////////////////// time2=clock(); if(rank==0)printf("setup time:%f secs\n\n",(double) (time2-time1)/CLOCKS_PER_SEC); time1=clock(); //expected AFS //printf("runMode = %d\n",runMode); switch(runMode){ case 1: if(rank==0){ printf("\nParameter estimation run mode\n\n"); printf("now optimizing....\n\n"); printf("initial parameter guess:\n"); for(i=0;i<5;i++)printf("%f ",mle[i]); printf("\n\n"); } maximizeLikNLOpt(&lik, currentParams, mle); fi = getGodambeInfoMatrix(mle, lik, currentParams); //get N0 estimate N0 = propSnp / currentParams->meanTreeLength / 4.0 / u; if(rank == 0){ printf("for scaling:\nu: %e gen: %lf N0:%lf meanTreeLength:%lf seqLen:%d\n",u,genPerYear,N0,currentParams->meanTreeLength,seqLen); printf("Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<5;i++)printf("%f\t",(float)mle[i]); printf("\n\nComposite Likelihood estimates of IM params (unscaled):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<2;i++)printf("%f\t",(float)mle[i]*N0); for(i=2;i<4;i++)printf("%f\t",(float)mle[i]/N0/4); printf("%f\t",(float)mle[i] * N0 * 4.0/ (float)genPerYear); printf("\n\nUncertainty estimates of IM params (scaled by 1/theta_pop1):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<5;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(fi,i,i))); printf("\n\nUncertainty estimates of IM params (unscaled):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<2;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(fi,i,i))*N0); for(i=2;i<4;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(fi,i,i))/N0/4); printf("%f\t",(float)sqrt(gsl_matrix_get(fi,i,i)) * N0 * 4.0/ (float)genPerYear); printf("\n"); printf("\n\nlikelihood: %lf\n",-lik); currentParams->nnz = nnz; printf("\nExpected AFS:\n"); gsl_matrix_prettyPrint(currentParams->expAFS); } break; case 2: if(rank == 0)printf("expected value run mode\n"); for(i=0;i<5;i++){ gsl_vector_set(currentParams->paramVector,i,mle[i]); } calcLogAFS_IM(currentParams); currentParams->nnz = nnz; if(rank == 0){ printf("Expected AFS:\n"); gsl_matrix_prettyPrint(currentParams->expAFS); printf("parameter values used:\n"); for(i=0;i<dim;i++)printf("%f\t",gsl_vector_get(currentParams->paramVector,i)); printf("\n\n"); } time2=clock(); //lik = calcLikNLOpt(5,mle,NULL,currentParams); // //printf("Likelihood: %g\n",lik); //if(rank==0)printf("w/ CSPARSE time:%f secs\n Liklihood Func. Evals: %d\n",(double) (time2-time1)/CLOCKS_PER_SEC,currentParams->fEvals); time1=clock(); break; case 3: if(rank==0){ printf("\nParameter estimation run mode with multiple optimizations\n\n"); printf("now optimizing....\n\n"); printf("initial parameter guess:\n"); for(i=0;i<5;i++)printf("%f ",mle[i]); printf("\n\n"); } for(j = 0; j < 3; j++){ for(i=0;i<5;i++)mle[i] = gsl_ran_flat(r,lowerBounds[i], upperBounds[i]); printf("optimization %d initial parameter guess:\n",j); for(i=0;i<5;i++)printf("%f ",mle[i]); maximizeLikNLOpt(&lik, currentParams, mle); if(rank == 0){ printf("Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<5;i++)printf("%f\t",(float)mle[i]); printf("\n\nlikelihood: %lf\n",-lik); currentParams->nnz = nnz; printf("\nExpected AFS:\n"); gsl_matrix_prettyPrint(currentParams->expAFS); } } break; case 4: if(rank==0){ printf("\nParameter estimation run mode\n\n"); printf("now optimizing....\n\n"); printf("initial parameter guess:\n"); for(i=0;i<5;i++)printf("%f ",mle[i]); printf("\n\n"); } maximizeLikNLOpt_MLSL(&lik, currentParams, mle); fi = getGodambeInfoMatrix(mle, lik, currentParams); if(rank == 0){ N0 = propSnp / currentParams->meanTreeLength / 4.0 / u; printf("Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<5;i++)printf("%f\t",(float)mle[i]); printf("\n\nComposite Likelihood estimates of IM params (unscaled):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<2;i++)printf("%f\t",(float)mle[i]*N0); for(i=2;i<4;i++)printf("%f\t",(float)mle[i]/N0/4); printf("%f\t",(float)mle[i] * N0 * 4.0/ (float)genPerYear); printf("\n\nUncertainty estimates of IM params (scaled by 1/theta_pop1):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<5;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(fi,i,i))); printf("\n\nUncertainty estimates of IM params (unscaled):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<2;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(fi,i,i))*N0); for(i=2;i<4;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(fi,i,i))/N0/4); printf("%f\t",(float)sqrt(gsl_matrix_get(fi,i,i)) * N0 * 4.0/ (float)genPerYear); printf("\n"); printf("\n\nlikelihood: %lf\n",-lik); currentParams->nnz = nnz; printf("\nExpected AFS:\n"); gsl_matrix_prettyPrint(currentParams->expAFS); } break; case 5: for(i=0;i<5;i++){ gsl_vector_set(currentParams->paramVector,i,mle[i]); } if(rank==0){ printf("\nUncertainty estimation (via Godambe Information) run mode\n\n"); printf("MLE parameters:\n"); for(i=0;i<5;i++)printf("%f ",mle[i]); printf("\n"); } lik = calcLikNLOpt(5,mle,NULL,currentParams); gi = getGodambeInfoMatrix(mle, lik, currentParams); N0 = propSnp / currentParams->meanTreeLength / 4.0 / u; // if(rank==0){ // printf("FIM:\n"); // gsl_matrix_prettyPrint(fi); // printf("\nGIM:\n"); // gsl_matrix_prettyPrint(gi); // printf("\n"); // } if(rank==0){ printf("\nlikelihood: %lf\n",-lik); printf("Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<5;i++)printf("%f\t",(float)mle[i]); printf("\n\nComposite Likelihood estimates of IM params (unscaled):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<4;i++)printf("%f\t",(float)mle[i]*N0); printf("%f\t",(float)mle[i] * N0 * 4.0/ (float)genPerYear); printf("\n\nUncertainty estimates of IM params (scaled by 1/theta_pop1):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<5;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(gi,i,i))); printf("\n\nUncertainty estimates of IM params (unscaled):\n"); printf("theta_pop2\ttheta_anc\tmig_1->2\tmig_2->1\tt_div\n"); for(i=0;i<4;i++)printf("%f\t",(float) sqrt(gsl_matrix_get(gi,i,i))*N0); printf("%f\t",(float)sqrt(gsl_matrix_get(gi,i,i)) * N0 * 4.0/ (float)genPerYear); printf("\n"); } break; } if(obsFlag && rank==0){ gsl_matrix_scale(currentParams->obsData,1.0/snpNumber); printf("%f SNPs in dataset\n",snpNumber); printf("Observed AFS:\n"); gsl_matrix_prettyPrint(currentParams->obsData); gsl_matrix_scale(currentParams->obsData,snpNumber); } MatDestroy(&currentParams->denseMat1); MatDestroy(&currentParams->denseMat2); MatDestroy(&currentParams->C); MatDestroy(&currentParams->C2); MatDestroy(&currentParams->D); MatDestroy(&currentParams->D_copy); MatDestroy(&currentParams->denseIdent); MatDestroy(&currentParams->ident); MFNDestroy(&currentParams->mfn); VecDestroy(&currentParams->ancStateVec); VecDestroy(&currentParams->ancResVec); VecDestroy(&currentParams->xInv); VecDestroy(&currentParams->bInv); gsl_rng_free (r); afsStateSpaceFree(currentParams->reducedStateSpace); time2=clock(); if(rank==0)printf("total run time:%f secs\n Liklihood Func. Evals: %d\n",(double) (time2-time1)/CLOCKS_PER_SEC,currentParams->fEvals); ierr = PetscFinalize(); return(0); } //import2DSFSData -- imports a matrix from fileName and stuffs it in prealloc'd obsData void import2DSFSData(const char *fileName, gsl_matrix *obsData){ FILE *infile; //open file infile = fopen(fileName, "r"); if (infile == NULL){ fprintf(stderr,"Error opening data file! ARRRRR!!!!\n"); exit(1); } gsl_matrix_fscanf(infile,obsData); fclose(infile); }
{ "alphanum_fraction": 0.6825837411, "avg_line_length": 37.3567662566, "ext": "c", "hexsha": "0780e0251d4480b37b2425d6c972baa2bd8db582", "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": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_path": "im_clam.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_path": "im_clam.c", "max_line_length": 303, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_path": "im_clam.c", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "num_tokens": 6752, "size": 21256 }
/* * Copyright (C) 2017 Jelmer Ypma. All Rights Reserved. * This code is published under the L-GPL. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * File: nloptrAPI.h * Author: Jelmer Ypma * Date: 3 October 2017 * * This file provides an API for calling internal NLopt code from C within * R packages. The C functions that are registered in init_nloptr.c can be * accessed by external R packages. * * 03/10/2017: Initial version exposing nlopt_version. */ #ifndef __NLOPTRAPI_H__ #define __NLOPTRAPI_H__ #include <R_ext/Rdynload.h> #include <R.h> #include <Rinternals.h> #include <nlopt.h> /* * C functions can be exposed using the following template: * * RET_TYPE FUNCNAME(ARGTYPE_1 ARGNAME 1, ARGTYPE_2 ARGNAME_2) * { * static RET_TYPE(*fun)(ARGTYPE_1, ARGTYPE_2) = NULL; * if (fun == NULL) fun = (RET_TYPE(*)(ARGTYPE_1, ARGTYPE_2)) R_GetCCallable("nloptr","FUNCNAME"); * return fun(ARGNAME_1, ARGNAME_2); * } * */ inline NLOPT_EXTERN(const char *) nlopt_algorithm_name(nlopt_algorithm a) { static const char *(*fun)(nlopt_algorithm) = NULL; if (fun == NULL) fun = (const char *(*)(nlopt_algorithm)) R_GetCCallable("nloptr","nlopt_algorithm_name"); return fun(a); } inline NLOPT_EXTERN(void) nlopt_srand(unsigned long seed) { static void(*fun)(unsigned long) = NULL; if (fun == NULL) fun = (void(*)(unsigned long)) R_GetCCallable("nloptr","nlopt_srand"); return fun(seed); } inline NLOPT_EXTERN(void) nlopt_srand_time(void) { static void(*fun)(void) = NULL; if (fun == NULL) fun = (void(*)(void)) R_GetCCallable("nloptr","nlopt_srand_time"); return fun(); } inline NLOPT_EXTERN(void) nlopt_version(int *major, int *minor, int *bugfix) { static void(*fun)(int *, int *, int *) = NULL; if (fun == NULL) fun = (void(*)(int *, int *, int *)) R_GetCCallable("nloptr","nlopt_version"); return fun(major, minor, bugfix); } inline NLOPT_EXTERN(nlopt_opt) nlopt_create(nlopt_algorithm algorithm, unsigned n) { static nlopt_opt(*fun)(nlopt_algorithm, unsigned) = NULL; if (fun == NULL) fun = (nlopt_opt(*)(nlopt_algorithm, unsigned)) R_GetCCallable("nloptr","nlopt_create"); return fun(algorithm, n); } inline NLOPT_EXTERN(void) nlopt_destroy(nlopt_opt opt) { static void(*fun)(nlopt_opt) = NULL; if (fun == NULL) fun = (void(*)(nlopt_opt)) R_GetCCallable("nloptr","nlopt_destroy"); return fun(opt); } inline NLOPT_EXTERN(nlopt_opt) nlopt_copy(const nlopt_opt opt) { static nlopt_opt(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (nlopt_opt(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_copy"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_optimize(nlopt_opt opt, double *x, double *opt_f) { static nlopt_result(*fun)(nlopt_opt, double *, double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double *, double *)) R_GetCCallable("nloptr","nlopt_optimize"); return fun(opt, x, opt_f); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_min_objective(nlopt_opt opt, nlopt_func f, void *f_data) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *)) R_GetCCallable("nloptr","nlopt_set_min_objective"); return fun(opt, f, f_data); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_max_objective(nlopt_opt opt, nlopt_func f, void *f_data) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *)) R_GetCCallable("nloptr","nlopt_set_max_objective"); return fun(opt, f, f_data); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_precond_min_objective(nlopt_opt opt, nlopt_func f, nlopt_precond pre, void *f_data) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *)) R_GetCCallable("nloptr","nlopt_set_precond_min_objective"); return fun(opt, f, pre, f_data); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_precond_max_objective(nlopt_opt opt, nlopt_func f, nlopt_precond pre, void *f_data) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *)) R_GetCCallable("nloptr","nlopt_set_precond_max_objective"); return fun(opt, f, pre, f_data); } inline NLOPT_EXTERN(nlopt_algorithm) nlopt_get_algorithm(const nlopt_opt opt) { static nlopt_algorithm(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (nlopt_algorithm(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_algorithm"); return fun(opt); } inline NLOPT_EXTERN(unsigned) nlopt_get_dimension(const nlopt_opt opt) { static unsigned(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (unsigned(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_dimension"); return fun(opt); } /* constraints: */ inline NLOPT_EXTERN(nlopt_result) nlopt_set_lower_bounds(nlopt_opt opt, const double *lb) { static nlopt_result(*fun)(nlopt_opt, const double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable("nloptr","nlopt_set_lower_bounds"); return fun(opt, lb); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_lower_bounds1(nlopt_opt opt, double lb) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_lower_bounds1"); return fun(opt, lb); } inline NLOPT_EXTERN(nlopt_result) nlopt_get_lower_bounds(const nlopt_opt opt, double *lb) { static nlopt_result(*fun)(const nlopt_opt, double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(const nlopt_opt, double *)) R_GetCCallable("nloptr","nlopt_get_lower_bounds"); return fun(opt, lb); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_upper_bounds(nlopt_opt opt, const double *ub) { static nlopt_result(*fun)(nlopt_opt, const double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable("nloptr","nlopt_set_upper_bounds"); return fun(opt, ub); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_upper_bounds1(nlopt_opt opt, double ub) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_upper_bounds1"); return fun(opt, ub); } inline NLOPT_EXTERN(nlopt_result) nlopt_get_upper_bounds(const nlopt_opt opt, double *ub) { static nlopt_result(*fun)(const nlopt_opt, double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(const nlopt_opt, double *)) R_GetCCallable("nloptr","nlopt_get_upper_bounds"); return fun(opt, ub); } inline NLOPT_EXTERN(nlopt_result) nlopt_remove_inequality_constraints(nlopt_opt opt) { static nlopt_result(*fun)(nlopt_opt) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt)) R_GetCCallable("nloptr","nlopt_remove_inequality_constraints"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_add_inequality_constraint(nlopt_opt opt, nlopt_func fc, void *fc_data, double tol) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *, double)) R_GetCCallable("nloptr","nlopt_add_inequality_constraint"); return fun(opt, fc, fc_data, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_add_precond_inequality_constraint( nlopt_opt opt, nlopt_func fc, nlopt_precond pre, void *fc_data, double tol) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *, double)) R_GetCCallable("nloptr","nlopt_add_precond_inequality_constraint"); return fun(opt, fc, pre, fc_data, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_add_inequality_mconstraint(nlopt_opt opt, unsigned m, nlopt_mfunc fc, void *fc_data, const double *tol) { static nlopt_result(*fun)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *)) R_GetCCallable("nloptr","nlopt_add_inequality_mconstraint"); return fun(opt, m, fc, fc_data, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_remove_equality_constraints(nlopt_opt opt) { static nlopt_result(*fun)(nlopt_opt) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt)) R_GetCCallable("nloptr","nlopt_remove_equality_constraints"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_add_equality_constraint(nlopt_opt opt, nlopt_func h, void *h_data, double tol) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, void *, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, void *, double)) R_GetCCallable("nloptr","nlopt_add_equality_constraint"); return fun(opt, h, h_data, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_add_precond_equality_constraint( nlopt_opt opt, nlopt_func h, nlopt_precond pre, void *h_data, double tol) { static nlopt_result(*fun)(nlopt_opt, nlopt_func, nlopt_precond, void *, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, nlopt_func, nlopt_precond, void *, double)) R_GetCCallable("nloptr","nlopt_add_precond_equality_constraint"); return fun(opt, h, pre, h_data, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_add_equality_mconstraint(nlopt_opt opt, unsigned m, nlopt_mfunc h, void *h_data, const double *tol) { static nlopt_result(*fun)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned, nlopt_mfunc, void *, const double *)) R_GetCCallable("nloptr","nlopt_add_equality_mconstraint"); return fun(opt, m, h, h_data, tol); } /* stopping criteria: */ inline NLOPT_EXTERN(nlopt_result) nlopt_set_stopval(nlopt_opt opt, double stopval) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_stopval"); return fun(opt, stopval); } inline NLOPT_EXTERN(double) nlopt_get_stopval(const nlopt_opt opt) { static double(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_stopval"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_ftol_rel(nlopt_opt opt, double tol) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_ftol_rel"); return fun(opt, tol); } inline NLOPT_EXTERN(double) nlopt_get_ftol_rel(const nlopt_opt opt) { static double(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_ftol_rel"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_ftol_abs(nlopt_opt opt, double tol) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_ftol_abs"); return fun(opt, tol); } inline NLOPT_EXTERN(double) nlopt_get_ftol_abs(const nlopt_opt opt) { static double(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_ftol_abs"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_xtol_rel(nlopt_opt opt, double tol) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_xtol_rel"); return fun(opt, tol); } inline NLOPT_EXTERN(double) nlopt_get_xtol_rel(const nlopt_opt opt) { static double(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (double(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_xtol_rel"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_xtol_abs1(nlopt_opt opt, double tol) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_xtol_abs1"); return fun(opt, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_xtol_abs(nlopt_opt opt, const double *tol) { static nlopt_result(*fun)(nlopt_opt, const double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable("nloptr","nlopt_set_xtol_abs"); return fun(opt, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_get_xtol_abs(const nlopt_opt opt, double *tol) { static nlopt_result(*fun)(nlopt_opt, double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double *)) R_GetCCallable("nloptr","nlopt_get_xtol_abs"); return fun(opt, tol); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_maxeval(nlopt_opt opt, int maxeval) { static nlopt_result(*fun)(nlopt_opt, int) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, int)) R_GetCCallable("nloptr","nlopt_set_maxeval"); return fun(opt, maxeval); } inline NLOPT_EXTERN(int) nlopt_get_maxeval(const nlopt_opt opt) { static int(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (int(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_maxeval"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_maxtime(nlopt_opt opt, double maxtime) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_maxtime"); return fun(opt, maxtime); } inline NLOPT_EXTERN(double) nlopt_get_maxtime(const nlopt_opt opt) { static double(*fun)(nlopt_opt) = NULL; if (fun == NULL) fun = (double(*)(nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_maxtime"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_force_stop(nlopt_opt opt) { static nlopt_result(*fun)(nlopt_opt) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt)) R_GetCCallable("nloptr","nlopt_force_stop"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_force_stop(nlopt_opt opt, int val) { static nlopt_result(*fun)(nlopt_opt, int) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, int)) R_GetCCallable("nloptr","nlopt_set_force_stop"); return fun(opt, val); } inline NLOPT_EXTERN(int) nlopt_get_force_stop(const nlopt_opt opt) { static int(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (int(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_force_stop"); return fun(opt); } /* more algorithm-specific parameters */ inline NLOPT_EXTERN(nlopt_result) nlopt_set_local_optimizer(nlopt_opt opt, const nlopt_opt local_opt) { static nlopt_result(*fun)(nlopt_opt, const nlopt_opt) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const nlopt_opt)) R_GetCCallable("nloptr","nlopt_set_local_optimizer"); return fun(opt, local_opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_population(nlopt_opt opt, unsigned pop) { static nlopt_result(*fun)(nlopt_opt, unsigned) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned)) R_GetCCallable("nloptr","nlopt_set_population"); return fun(opt, pop); } inline NLOPT_EXTERN(unsigned) nlopt_get_population(const nlopt_opt opt) { static unsigned(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (unsigned(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_population"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_vector_storage(nlopt_opt opt, unsigned dim) { static nlopt_result(*fun)(nlopt_opt, unsigned) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, unsigned)) R_GetCCallable("nloptr","nlopt_set_vector_storage"); return fun(opt, dim); } inline NLOPT_EXTERN(unsigned) nlopt_get_vector_storage(const nlopt_opt opt) { static unsigned(*fun)(const nlopt_opt) = NULL; if (fun == NULL) fun = (unsigned(*)(const nlopt_opt)) R_GetCCallable("nloptr","nlopt_get_vector_storage"); return fun(opt); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_default_initial_step(nlopt_opt opt, const double *x) { static nlopt_result(*fun)(nlopt_opt, const double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable("nloptr","nlopt_set_default_initial_step"); return fun(opt, x); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_initial_step(nlopt_opt opt, const double *dx) { static nlopt_result(*fun)(nlopt_opt, const double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, const double *)) R_GetCCallable("nloptr","nlopt_set_initial_step"); return fun(opt, dx); } inline NLOPT_EXTERN(nlopt_result) nlopt_set_initial_step1(nlopt_opt opt, double dx) { static nlopt_result(*fun)(nlopt_opt, double) = NULL; if (fun == NULL) fun = (nlopt_result(*)(nlopt_opt, double)) R_GetCCallable("nloptr","nlopt_set_initial_step1"); return fun(opt, dx); } inline NLOPT_EXTERN(nlopt_result) nlopt_get_initial_step(const nlopt_opt opt, const double *x, double *dx) { static nlopt_result(*fun)(const nlopt_opt, const double *, double *) = NULL; if (fun == NULL) fun = (nlopt_result(*)(const nlopt_opt, const double *, double *)) R_GetCCallable("nloptr","nlopt_get_initial_step"); return fun(opt, x, dx); } #endif /* __NLOPTRAPI_H__ */
{ "alphanum_fraction": 0.7132733715, "avg_line_length": 39.8804347826, "ext": "h", "hexsha": "74585eac0b9d3d0c692b879fad58de26eeaa1b12", "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": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "robalexclark/SilveR-Dev", "max_forks_repo_path": "SilveR/R/library/nloptr/include/nloptrAPI.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "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": "robalexclark/SilveR-Dev", "max_issues_repo_path": "SilveR/R/library/nloptr/include/nloptrAPI.h", "max_line_length": 166, "max_stars_count": null, "max_stars_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "robalexclark/SilveR-Dev", "max_stars_repo_path": "SilveR/R/library/nloptr/include/nloptrAPI.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5707, "size": 18345 }
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef BITVEC_DECL_H #define BITVEC_DECL_H #include <gsl/gsl_assert> // for Expects #include <gsl/gsl_util> // for narrow_cast, narrow using gsl::narrow_cast; #include <cstddef> // for ptrdiff_t, size_t, nullptr_t #include <iterator> // for reverse_iterator, distance, random_access_... #include <memory> #ifdef _MSC_VER #pragma warning(push) // turn off some warnings that are noisy about our Expects statements #pragma warning(disable : 4127) // conditional expression is constant #pragma warning(disable : 4702) // unreachable code // Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool. #pragma warning( \ disable : 26495) // uninitalized member when constructor calls constructor #pragma warning( \ disable : 26446) // parser bug does not allow attributes on some templates #endif // _MSC_VER namespace gb { // shared_ptr without atomic overhead template <typename T> using shared_ptr_unsynchronized = std::__shared_ptr<T, __gnu_cxx::_S_single>; // [views.constants], constants const std::ptrdiff_t dynamic_extent = -1; template <std::ptrdiff_t Extent = dynamic_extent> class bitvec; // implementation details namespace details { template <class Span, bool IsConst> class span_iterator { using element_type_ = typename Span::element_type; public: #ifdef _MSC_VER // Tell Microsoft standard library that span_iterators are checked. using _Unchecked_type = typename Span::pointer; #endif using iterator_category = std::random_access_iterator_tag; using value_type = std::remove_cv_t<element_type_>; using difference_type = typename Span::index_type; using pointer = shared_ptr_unsynchronized< std::conditional_t<IsConst, const element_type_, element_type_>>; span_iterator() = default; span_iterator(const Span *bitvec, typename Span::index_type idx) noexcept : span_(bitvec), index_(idx) {} friend span_iterator<Span, true>; template <bool B, std::enable_if_t<!B && IsConst> * = nullptr> span_iterator(const span_iterator<Span, B> &other) noexcept : span_iterator(other.span_, other.index_) {} std::conditional_t<IsConst, const bitvec<1>, bitvec<1>> operator*() const { Expects(index_ != span_->size()); return std::conditional_t<IsConst, const bitvec<1>, bitvec<1>>( (*span_)[index_]); } pointer operator->() const { Expects(index_ != span_->size()); return span_->data() + index_; } span_iterator &operator++() { Expects(0 <= index_ && index_ != span_->size()); ++index_; return *this; } span_iterator &operator--() { Expects(index_ != 0 && index_ <= span_->size()); --index_; return *this; } pointer operator[](difference_type n) const { return *(*this + n); } friend bool operator==(span_iterator lhs, span_iterator rhs) noexcept { return lhs.span_ == rhs.span_ && lhs.index_ == rhs.index_; } friend bool operator!=(span_iterator lhs, span_iterator rhs) noexcept { return !(lhs == rhs); } friend bool operator<(span_iterator lhs, span_iterator rhs) noexcept { return lhs.index_ < rhs.index_; } #ifdef _MSC_VER // MSVC++ iterator debugging support; allows STL algorithms in 15.8+ // to unwrap span_iterator to a pointer type after a range check in STL // algorithm calls friend void _Verify_range( span_iterator lhs, span_iterator rhs) noexcept { // test that [lhs, rhs) forms a valid // range inside an STL algorithm Expects(lhs.span_ == rhs.span_ // range spans have to match && lhs.index_ <= rhs.index_); // range must not be transposed } void _Verify_offset(const difference_type n) const noexcept { // test that the iterator *this + n is a valid range in an // STL // algorithm call Expects((index_ + n) >= 0 && (index_ + n) <= span_->size()); } GSL_SUPPRESS(bounds .1) // NO-FORMAT: attribute pointer _Unwrapped() const noexcept { // after seeking *this to a high water // mark, or using one of the // _Verify_xxx functions above, unwrap this span_iterator to a raw // pointer return span_->data() + index_; } // Tell the STL that span_iterator should not be unwrapped if it can't // validate in advance, even in release / optimized builds: static const bool _Unwrap_when_unverified = false; GSL_SUPPRESS(con .3) // NO-FORMAT: attribute // TODO: false positive void _Seek_to(const pointer p) noexcept { // adjust the position of *this to // previously verified location p // after _Unwrapped index_ = p - span_->data(); } #endif protected: const Span *span_ = nullptr; std::ptrdiff_t index_ = 0; }; // Used for empty base class optimization template <std::ptrdiff_t Ext> class extent_type { public: using index_type = std::ptrdiff_t; static_assert(Ext >= 0, "A fixed-size bitvec must be >= 0 in size."); extent_type() noexcept {} template <index_type Other> extent_type(extent_type<Other> ext) { static_assert(Other == Ext || Other == dynamic_extent, "Mismatch between fixed-size extent and size of " "initializing data."); Expects(ext.size() == Ext); } extent_type(index_type size) { Expects(size == Ext); } index_type size() const noexcept { return Ext; } }; template <> class extent_type<dynamic_extent> { public: using index_type = std::ptrdiff_t; template <index_type Other> explicit extent_type(extent_type<Other> ext) : size_(ext.size()) {} explicit extent_type(index_type size) : size_(size) { Expects(size >= 0); } index_type size() const noexcept { return size_; } private: index_type size_; }; template <std::ptrdiff_t Extent, std::ptrdiff_t Offset, std::ptrdiff_t Count> struct calculate_subspan_type { using type = bitvec<Count != dynamic_extent ? Count : (Extent != dynamic_extent ? Extent - Offset : Extent)>; }; } // namespace details } // namespace gb #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #endif // BITVEC_DECL_H
{ "alphanum_fraction": 0.670044882, "avg_line_length": 32.1255813953, "ext": "h", "hexsha": "d5add5ca0543d8c2cf125d49cb238b17c868c56d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "CapacitorSet/Glovebox", "max_forks_repo_path": "include/bitvec_decl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "CapacitorSet/Glovebox", "max_issues_repo_path": "include/bitvec_decl.h", "max_line_length": 80, "max_stars_count": 2, "max_stars_repo_head_hexsha": "1271f2d65b3390c7156606b266b93c5d23ed398a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "CapacitorSet/FHE-tools", "max_stars_repo_path": "include/bitvec_decl.h", "max_stars_repo_stars_event_max_datetime": "2019-02-26T22:06:36.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-28T04:50:57.000Z", "num_tokens": 1626, "size": 6907 }
/* * 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 dnest_con.c * \brief run dnest for continuum analysis */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_interp.h> #include <mpi.h> #include "brains.h" DNestFptrSet *fptrset_con; /*! * This function run dnest sampling for continuum. */ int dnest_con(int argc, char **argv) { int i; num_params = parset.n_con_recon + num_params_var; par_range_model = malloc( num_params * sizeof(double *)); par_prior_gaussian = malloc(num_params * sizeof(double *)); for(i=0; i<num_params; i++) { par_range_model[i] = malloc(2*sizeof(double)); par_prior_gaussian[i] = malloc(2*sizeof(double)); } par_prior_model = malloc( num_params * sizeof(int)); par_fix = (int *) malloc(num_params * sizeof(int)); par_fix_val = (double *) malloc(num_params * sizeof(double)); fptrset_con = dnest_malloc_fptrset(); /* setup functions used for dnest*/ fptrset_con->from_prior = from_prior_con; fptrset_con->perturb = perturb_con; fptrset_con->print_particle = print_particle_con; fptrset_con->restart_action = restart_action_con; fptrset_con->accept_action = accept_action_con; fptrset_con->kill_action = kill_action_con; fptrset_con->read_particle = read_particle_con; if(parset.flag_exam_prior != 1) { fptrset_con->log_likelihoods_cal = log_likelihoods_cal_con; fptrset_con->log_likelihoods_cal_initial = log_likelihoods_cal_initial_con; fptrset_con->log_likelihoods_cal_restart = log_likelihoods_cal_restart_con; } else { fptrset_con->log_likelihoods_cal = log_likelihoods_cal_con_exam; fptrset_con->log_likelihoods_cal_initial = log_likelihoods_cal_con_exam; fptrset_con->log_likelihoods_cal_restart = log_likelihoods_cal_con_exam; } set_par_range_con(); /* setup fixed parameters */ for(i=0; i<num_params; i++) { par_fix[i] = 0; par_fix_val[i] = -DBL_MAX; } /* fix systematic error of continuum */ if(parset.flag_con_sys_err != 1) { par_fix[0] = 1; par_fix_val[0] = log(1.0); } print_par_names_con(); /* if not only print parameter name */ if(parset.flag_para_name != 1) logz_con = dnest(argc, argv, fptrset_con, num_params, dnest_options_file); dnest_free_fptrset(fptrset_con); return 0; } /*! * this function set the parameter range. */ void set_par_range_con() { int i; /* variability parameters */ for(i=0; i<num_params_drw; i++) { par_range_model[i][0] = var_range_model[i][0]; par_range_model[i][1] = var_range_model[i][1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; } /* parameters for long-term trend */ for(i=num_params_drw; i<num_params_drw + num_params_trend; i++) { par_range_model[i][0] = var_range_model[3][0]; par_range_model[i][1] = var_range_model[3][1]; par_prior_model[i] = GAUSSIAN; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 1.0; } /* parameter for trend difference */ for(i= num_params_drw + num_params_trend; i<num_params_var; i++) { par_range_model[i][0] = var_range_model[4 + i - (num_params_drw + num_params_trend)][0]; par_range_model[i][1] = var_range_model[4 + i - (num_params_drw + num_params_trend)][1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; } /* continuum light curve parameters */ for(i=num_params_var; i<num_params; i++) { par_range_model[i][0] = var_range_model[4+num_params_difftrend][0]; par_range_model[i][1] = var_range_model[4+num_params_difftrend][1]; par_prior_model[i] = GAUSSIAN; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 1.0; } return; } /*! * print names and prior ranges for parameters * */ void print_par_names_con() { if(thistask!= roottask) return; int i, j; FILE *fp; char fname[BRAINS_MAX_STR_LENGTH], str_fmt[BRAINS_MAX_STR_LENGTH]; sprintf(fname, "%s/%s", parset.file_dir, "data/para_names_con.txt"); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } strcpy(str_fmt, "%4d %-15s %10.6f %10.6f %4d %4d %15.6e\n"); printf("# Print parameter name in %s\n", fname); fprintf(fp, "#*************************************************\n"); fprint_version(fp); fprintf(fp, "#*************************************************\n"); fprintf(fp, "%4s %-15s %10s %10s %4s %4s %15s\n", "#", "Par", "Min", "Max", "Prior", "Fix", "Val"); i=0; fprintf(fp, str_fmt, i, "sys_err_con", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); i++; fprintf(fp, str_fmt, i, "sigmad", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); i++; fprintf(fp, str_fmt, i, "taud", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); for(j=0; j<num_params_trend; j++) { i++; fprintf(fp, str_fmt, i, "trend", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } for(j=0; j<num_params_difftrend; j++) { i++; fprintf(fp, str_fmt, i, "diff trend", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } for(j=0; j<parset.n_con_recon; j++) { i++; fprintf(fp, str_fmt, i, "time series", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } fclose(fp); } /*! * This function generate a sample from the prior. */ void from_prior_con(void *model) { int i; double *pm = (double *)model; for(i=0; i<num_params; i++) { if(par_prior_model[i] == GAUSSIAN ) { pm[i] = dnest_randn() * par_prior_gaussian[i][1] + par_prior_gaussian[i][0]; dnest_wrap(&pm[i], par_range_model[i][0], par_range_model[i][1]); } else { pm[i] = var_range_model[i][0] + dnest_rand()*(par_range_model[i][1] - par_range_model[i][0]); } } for(i=0; i<num_params_var; i++) { if(par_fix[i] == 1) pm[i] = par_fix_val[i]; } /* all parameters need to update at the initial step */ which_parameter_update = -1; } /*! * This function calculate log likelihood probability. */ double log_likelihoods_cal_con(const void *model) { double logL; logL = prob_con_variability_semiseparable(model); return logL; } /*! * This function calculate log likelihood probability at the initial step. */ double log_likelihoods_cal_initial_con(const void *model) { double logL; logL = prob_con_variability_initial_semiseparable(model); return logL; } /*! * This function calculate log likelihood probability at the restart step. */ double log_likelihoods_cal_restart_con(const void *model) { double logL; logL = prob_con_variability_initial_semiseparable(model); return logL; } /*! * This function generate a new move of parameters. */ double perturb_con(void *model) { double *pm = (double *)model; double logH = 0.0, limit1, limit2, width, rnd; int which, which_level; /* sample variability parameters more frequently */ do { rnd = dnest_rand(); if(rnd < 0.1) which = dnest_rand_int(num_params_var); else which = dnest_rand_int(parset.n_con_recon) + num_params_var; }while(par_fix[which] == 1); which_parameter_update = which; /* level-dependent width */ which_level_update = dnest_get_which_level_update(); which_level = which_level_update > (size_levels - 10)?(size_levels-10):which_level_update; if( which_level > 0) { limit1 = limits[(which_level-1) * num_params *2 + which *2]; limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1]; width = limit2 - limit1; } else { width = ( par_range_model[which][1] - par_range_model[which][0] ); } if(par_prior_model[which] == GAUSSIAN) { logH -= (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) ); pm[which] += dnest_randh() * width; dnest_wrap(&pm[which], par_range_model[which][0], par_range_model[which][1]); logH += (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) ); } else { pm[which] += dnest_randh() * width; dnest_wrap(&(pm[which]), par_range_model[which][0], par_range_model[which][1]); } return logH; } /*! * This function print the particle into the file. */ void print_particle_con(FILE *fp, const void *model) { int i; double *pm = (double *)model; for(i=0; i<num_params; i++) { fprintf(fp, "%e ", pm[i] ); } fprintf(fp, "\n"); } /*! * This function read the particle from the file. */ void read_particle_con(FILE *fp, void *model) { int j; double *psample = (double *)model; for(j=0; j < dnest_num_params; j++) { if(fscanf(fp, "%lf", psample+j) < 1) { printf("%f\n", *psample); fprintf(stderr, "#Error: Cannot read file %s.\n", options.sample_file); exit(0); } } return; } void restart_action_con(int iflag) { return; } void accept_action_con() { int param; param = which_parameter_update; /* only update prob when variability parameters are updated. */ if(param < num_params_var) { prob_con_particles[which_particle_update] = prob_con_particles_perturb[which_particle_update]; } return; } void kill_action_con(int i, int i_copy) { prob_con_particles[i] = prob_con_particles[i_copy]; return; } /*! * exam for prior */ double log_likelihoods_cal_con_exam(const void *model) { return 0.0; }
{ "alphanum_fraction": 0.6492015968, "avg_line_length": 25.5612244898, "ext": "c", "hexsha": "6e95e7238972b59b00aed7d740496f1f6d836ce5", "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": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_path": "src/dnest_con.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "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": "yzxamos/BRAINS", "max_issues_repo_path": "src/dnest_con.c", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_path": "src/dnest_con.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2965, "size": 10020 }
/* * Copyright (c) 2018-2021 Aleksas Mazeliauskas, Stefan Floerchinger, * Eduardo Grossi, and Derek Teaney * All rights reserved. * * FastReso is distributed under MIT license; * see the LICENSE file that should be present in the root * of the source distribution, or alternately available at: * https://github.com/amazeliauskas/FastReso/ */ #ifndef FASTRESO_TFastReso_AZYHYDRO_h #define FASTRESO_TFastReso_AZYHYDRO_h #include "TFastReso.h" #include <fstream> #include <memory> #include <map> #include <vector> #include <string> #include <gsl/gsl_integration.h> // The class storing the properties of particles and their irreducible distrubtion // function components f_i. Printing out routines are also defined there. #include "TParticle_AZYHYDRO.h" // List of parameters for GSL integration procedure. #include "qag_params.h" // List of parameters controlling the momentum discretization of irreducible components // See also TParticle_AZYHYDRO class definition #include "grid_params.h" //! TFastReso_AZYHYDRO class is the top wrapper class of the fast freeze-out implementation. class TFastReso_AZYHYDRO: public TFastReso { private: //! Data vector of TParticle_AZYHYDRO class of all read-in particles //! See TParticle_AZYHYDRO class definition. std::vector <std::unique_ptr<TParticle_AZYHYDRO>> fParticleData; //! Map between the particle name and its position in fParticleData vector; std::map <int, int> fIndexTable; public: //! reads the inputfile of resonances and creates TParticle_AZYHYDRO entry in fParticleData vector. //! This routine should be edited by the user to match their input file format. void read_particles_data(std::string inputname, std::string comps="Feq Fshear Fbulk Ftemp Fvel", bool verbose=false) override; //! The function call to initialized the particle distribution functions in fParticleData. Input parameters //! are the freeze-out temperature, chemical potential and (optionally), speed of sound (only needed for bulk perturbations). void do_thermal(double Tfo, double MuB=0, double MuI3=0, double MuS=0, double MuC=0, double Cs2=0.14) override; void do_thermal(int pi, double Tfo, double QMu=0, double Cs2 = 0.14 ); //! Read in the input file of resonance decays and perfom the decays on the fly. It is important that decays //! are mass ordered to included all feeddown contributions to lower mass resonances. //! The table format is the same as decays.data in THERMINATOR 2 [arXiv:1102.0273] //! Father Child1 Child2 (optional Child3) BranchingRatio ClebschGordanCoeff //! Note that ClebschGordanCoeff term is 0 or 1 identifying if the branching ration needs //! to be reweighted by actual Clebsch Gordon coefficients. void do_decays(std::string inputname, bool verbose=false) override; public: //! routine to get the pointer to TParticle_AZYHYDRO class for a particle particle name" TParticle_AZYHYDRO * getParticleByPDG(int pdgid){return fParticleData[fIndexTable[pdgid]].get();}; TParticle_AZYHYDRO * getParticle(int i){return (i<0) ? fParticleData[fParticleData.size()+i].get() : fParticleData[i].get();}; int getParticleIndexByPDG(int pdgid){return fIndexTable[pdgid];}; //! The printout of the calculated components is done by printing procedures in TParticle_AZYHYDRO class }; #endif
{ "alphanum_fraction": 0.7539097079, "avg_line_length": 47.7323943662, "ext": "h", "hexsha": "d0aa1033203d4d8e91de367ad908576d54dd3b79", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "amazeliauskas/FastReso", "max_forks_repo_path": "TFastReso_AZYHYDRO.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "amazeliauskas/FastReso", "max_issues_repo_path": "TFastReso_AZYHYDRO.h", "max_line_length": 131, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "amazeliauskas/FastReso", "max_stars_repo_path": "TFastReso_AZYHYDRO.h", "max_stars_repo_stars_event_max_datetime": "2020-09-22T14:25:58.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-11T02:48:59.000Z", "num_tokens": 878, "size": 3389 }
#ifndef TETRA_DOS_DOS_VALUES_H #define TETRA_DOS_DOS_VALUES_H #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include "ctetra/dos.h" #include "elHamiltonian.h" #include "environment.h" gsl_matrix* cubicRecipLat(double a); double* DosValues(Environment *env, int n, double *Es, double num_dos); #endif // TETRA_DOS_DOS_VALUES_H
{ "alphanum_fraction": 0.7769953052, "avg_line_length": 23.6666666667, "ext": "h", "hexsha": "ec88f7fa7d6637b5e9cdb9d07ebf02cf0a22eb4c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-18T15:11:23.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-18T15:11:23.000Z", "max_forks_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/vo2mft", "max_forks_repo_path": "tetra_dos/DosValues.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tflovorn/vo2mft", "max_issues_repo_path": "tetra_dos/DosValues.h", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/vo2mft", "max_stars_repo_path": "tetra_dos/DosValues.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 133, "size": 426 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "Map.h" #include "MapPoint.h" #include "MappingKeyframe.h" #include "InitializationData.h" #include "Tracking\KeyframeBuilder.h" #include "Mapping\MapPointKeyframeAssociations.h" #include "BoW\OnlineBow.h" #include "BoW\BaseFeatureMatcher.h" #include "BundleAdjustment\BundleAdjust.h" #include "Data\Types.h" #include "Data\Pose.h" #include "Data\Data.h" #include "Data\MapState.h" #include "Utils\historical_queue.h" #include "Utils\collection.h" #include <arcana\threading\blocking_concurrent_queue.h> #include <gsl\gsl> #include <shared_mutex> #include <vector> #include <set> // forward-declare the friend class method for accessing the root map in unit tests namespace UnitTests { class TestHelperFunctions; } namespace mage { class ThreadSafeMap { friend class ::UnitTests::TestHelperFunctions; public: ThreadSafeMap( const MageSlamSettings& settings, BaseBow& bagOfWords); ~ThreadSafeMap(); void InitializeMap(const InitializationData& initializationData, thread_memory memory); void GetConnectedMapPoints( const collection<Proxy<MapPoint>>& points, thread_memory memory, loop::vector<KeyframeReprojection>& repro) const; // returns a sampling of mappoints void GetSampleOfMapPoints(temp::vector<MapPointProxy>& mapPoints, uint32_t max, uint32_t offset = 0) const; /* Inserts a new keyframe and returns all the keyframes that are connected to this one by the covisibility graph. */ Proxy<Keyframe, proxy::Image> InsertKeyframe( const std::shared_ptr<const KeyframeBuilder>& kb, thread_memory memory); /* Inserts a new keyframe and returns all the keyframes that are connected to this one by the covisibility graph. */ Proxy<Keyframe, proxy::Image> InsertKeyframe( const std::shared_ptr<const KeyframeBuilder>& keyframe, const gsl::span<MapPointAssociations<MapPointTrackingProxy>::Association>& extraAssociation, thread_memory memory); std::unique_ptr<KeyframeProxy> GetKeyFrameProxy(const Id<Keyframe>& kId) const; /* Merge information from a set of posited keyframes into the actual keyframes. */ void UpdateKeyframesFromProxies( gsl::span<const KeyframeProxy> proxies, const OrbMatcherSettings& mergeSettings, std::unordered_map<Id<MapPoint>, MapPointTrackingProxy>& mapPointMerges, thread_memory memory); /* Updates the state of the map points in the KeyframeProxy based on the current information in the map. */ void UpdateMapPoints(KeyframeProxy& proxy) const; /* Builds a global bundle adjust dataset of everything in the map. NOTE: Fixes the position of fixed and distance-tethered keyframes to preserve some semblance of consistent scale. */ void BuildGlobalBundleAdjustData(AdjustableData& data) const; /* Retrieves keyframes similar to the image provided. */ void FindSimilarKeyframes(const std::shared_ptr<const AnalyzedImage>& image, std::vector<KeyframeProxy>& output) const; void FindNonCovisibleSimilarKeyframeClusters(const KeyframeProxy& proxy, thread_memory memory, std::vector<std::vector<KeyframeProxy>>& output) const; /* Culls map points based on requirements related to number of keyframes they are visibile in and the results found in tracking Takes a list of points that have failed to appear where predicted during tracking to remove as well */ void CullRecentMapPoints( const Id<Keyframe>& ki, const mira::unique_vector<Id<MapPoint>>& recentFailedMapPoints, thread_memory memory); /* Return the collection of all the map points */ void GetMapPointsAsPositions(std::vector<Position>& positions) const; /* Return the number of map points in the map */ size_t GetMapPointsCount() const; /* Return the number of keyframes in the map */ size_t GetKeyframesCount() const; /* Return the collection of all the keyframes */ void GetKeyframeViewMatrices(std::vector<Matrix>& viewMatrices) const; /* Creates the map points passed in and returns the keyframes that were added to the frames connected to Ki through the covis graph */ std::vector<MappingKeyframe> CreateMapPoints( const Id<Keyframe>& keyframeId, const gsl::span<const MapPointKeyframeAssociations >& toCreate, thread_memory memory); /* Returns all the map points seen by this keyframe and the ones seen by it's neighbours in the covisibility graph. It then returns all the keyframes that see those points and aren't in Ki's covis graph. */ unsigned int GetMapPointsAndDistantKeyframes( const Id<Keyframe>& Ki, unsigned int coVisTheta, thread_memory memory, std::vector<MapPointTrackingProxy>& mapPoints, std::vector<Proxy<Keyframe, proxy::Pose, proxy::Intrinsics, proxy::PoseConstraints>>& keyframes, std::vector<MapPointAssociation>& mapPointAssociations, std::vector<Id<Keyframe>>& externallyTetheredKeyframes) const; /* Updates all the map point positions and keyframe poses and destroys all the MapPoint outliers (Not sure if we actually destroy them or not). */ void AdjustPosesAndMapPoints( const AdjustableData& adjusted, gsl::span<const std::pair<Id<MapPoint>, Id<Keyframe>>> outlierAssociations, thread_memory memory); /* Discards the duplicate keyframes that are connected to Ki in the covisibility graph. Returns the KeyframeIds that were removed as well as the covisability which lead to the removal decision if argument provided */ void CullLocalKeyframes( Id<Keyframe> Ki, thread_memory memory, std::vector<std::pair<const Id<Keyframe>, const std::vector<Id<Keyframe>>>>* cullingDecisions = nullptr); /* gets keyframes connected to KId in the covisibility graph (more than the minimum required map points in common to be entered as a link in the covisibility graph) */ void GetCovisibilityConnectedKeyframes( const Id<Keyframe>& kId, thread_memory memory, std::vector<MappingKeyframe>& kc) const; /* gets the list of recent points the mapping thread is still carefully evaluating. track local map will use this to collect more information on these points for use by the mapping thread, and the age of each of these map points */ std::map<Id<MapPoint>, unsigned int> GetRecentlyCreatedMapPoints() const; /* * Will attempt to match the set of map points into the set of keyframes if matching criterea are met */ void TryConnectMapPoints(gsl::span<const MapPointAssociations<MapPointTrackingProxy>::Association> mapPointAssociations, const Id<Keyframe>& insertedKeyframe, const TrackLocalMapSettings& trackLocalMapSettings, const OrbMatcherSettings& orbMatcherSettings, float searchRadius, thread_memory memory); /* Delete the state of the entire map */ void Clear(thread_memory memory); /* Returns all the information pertinent when saving the map */ MapState GetMapData() const; float GetMedianTetherDistance() const; float GetMapScale() const; /* Returns all the keyframes in the map */ std::vector<KeyframeProxy> GetAllKeyframes() const; /* Destroys this instance of the thread safe map and returns it's internal map for use in another context. */ static std::unique_ptr<Map> Release(std::unique_ptr<ThreadSafeMap> tsm); private: void UnSafeGetCovisibilityConnectedKeyframes( const Id<Keyframe>& kId, thread_memory memory, std::vector<MappingKeyframe>& kc) const; // the int value is the number of Keyframes this map point has existed for std::map<Id<MapPoint>, unsigned int> UnSafeGetRecentlyCreatedMapPoints() const; /* Performs all the logic for AdjustPosesAndMapPoints, but does not take its own lock and so can be used by other methods as well. */ void UnSafeAdjustPosesAndMapPoints( const AdjustableData& adjusted, gsl::span<const std::pair<Id<MapPoint>, Id<Keyframe>>> outlierAssociations, thread_memory memory); // vector to record map point creations for map point culling historical_queue<std::vector<Proxy<MapPoint>>, 3> m_pointHistory; const KeyframeSettings& m_keyframeSettings; const MappingSettings& m_mappingSettings; const CovisibilitySettings& m_covisibilitySettings; const BundleAdjustSettings& m_bundleAdjustSettings; mutable std::shared_mutex m_mutex; std::unique_ptr<Map> m_map; BaseBow& m_bow; float m_mapScale; }; }
{ "alphanum_fraction": 0.6617891241, "avg_line_length": 35.4264705882, "ext": "h", "hexsha": "383dff40232a2f5697dfc34ae81bbfd487c3dd0c", "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/Map/ThreadSafeMap.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/Map/ThreadSafeMap.h", "max_line_length": 158, "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/Map/ThreadSafeMap.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": 2044, "size": 9636 }
#include <gsl/gsl_vector.h> #include <math.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include "verif.h" #include "data.h" #include "prob_functions.h" void EM (Dataset *data) { int i, j; const double THRESHOLD = 1E-10; double Q, lastQ; srand(time(NULL)); /* Initialize parameters to starting values */ for (i = 0; i < data->numLabelers * data->numWorkflows; i++) { data->alpha[i] = data->priorAlpha[i]; /*data->alpha[i] = (double) rand() / RAND_MAX * 4 - 2;*/ } for (j = 0; j < data->numImages * data->numWorkflows; j++) { data->beta[j] = data->priorBeta[j]; /*data->beta[j] = (double) rand() / RAND_MAX * 3;*/ } Q = 0; EStep(data); Q = computeQ(data); /*printf("Q = %f\n", Q);*/ int iter = 0; do { printf("Iteration %d ", iter++); lastQ = Q; printf("old Q: %f", lastQ); /* Re-estimate P(Z|L,alpha,beta) */ EStep(data); Q = computeQ(data); /*printf("Q = %f; L = %f\n", Q, 0.0 computeLikelihood(data));*/ printf("\tafter E: %f", Q); /*outputResults(data);*/ MStep(data); Q = computeQ(data); printf("\tafter M: %f\n", Q); /*printf("Q = %f; L = %f\n", Q, 0.0 computeLikelihood(data));*/ } while (fabs((Q - lastQ)/lastQ) > THRESHOLD); outputResults(data); } int main (int argc, char *argv[]) { Dataset data; if (argc < 2) { fprintf(stdout, "Usage: em <data>\n"); fprintf(stdout, "where the specified data file is formatted as described in the README file.\n"); exit(1); } //These used to be 1 //double prioralpha[2] = {1.0, 0.5}; int NUMBER_OF_WORKER_POOLS; FILE *fi = fopen("../simulation.info", "r"); fscanf(fi, "%d\n", &NUMBER_OF_WORKER_POOLS); double *prioralpha = (double *) malloc(sizeof(double) * NUMBER_OF_WORKER_POOLS); double temp1,temp2,temp3; fscanf(fi,"%lf\n",&temp1); fscanf(fi,"%lf,%lf\n",&temp2,&temp3); fscanf(fi,"%lf,%lf\n",&prioralpha[0],&prioralpha[1]); fclose(fi); prioralpha[0] = 0.5; prioralpha[1] = 0.5; double priorbeta = 0.5; //double prioralpha = 1.0; //double priorbeta = 1.0; //This code will now break, if extra arguments are passed, since prioralpha is // now an array. /* if ( argc > 2 ) prioralpha = atof(argv[2]); if ( argc > 3 ) priorbeta = atof(argv[3]);*/ //printf("BLAH\n"); readData(argv[1], &data, prioralpha, priorbeta); // printf("LOADING TRUTH\n"); //Load_truth(&data); //printf("STARTING EM\n"); EM(&data); /* Accuracy(&data); int size; int s, samples = 50000; for ( size = 3; size <= 11; size+=2 ) { double acc = 0; for ( s = 0; s < samples; ++s ) { Randomizer( size); acc += Posterior( &data, size ); } acc /= samples; printf("%d %f\n", size, acc); } free(data.priorAlpha); free(data.priorBeta); free(data.labels); free(data.alpha); free(data.beta); free(data.probZ1); free(data.probZ0); */ }
{ "alphanum_fraction": 0.5916230366, "avg_line_length": 22.3828125, "ext": "c", "hexsha": "63134ca34f4c78c69361ce90cd94250c74e8fc88", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z", "max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ShreyaR/WorkerPoolSelection", "max_forks_repo_path": "EM/em.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "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": "ShreyaR/WorkerPoolSelection", "max_issues_repo_path": "EM/em.c", "max_line_length": 99, "max_stars_count": null, "max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ShreyaR/WorkerPoolSelection", "max_stars_repo_path": "EM/em.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 946, "size": 2865 }
static char help[] = "ODE system solver example using TS. Models two\n" "equal-mass balls (particles) moving in the plane with either no\n" "connection (free) or connected by a spring. Solved via a Newtonian\n" "formulation in cartesian coordinates (x,y) and velocities\n" "(v=dx/dt,w=dy/dt). The system has dimension 8.\n\n"; // DEBUG check BDF2 convergence in free problem using Lagrangian formulation: //for T in 2 3 4 5 7 8 9 10 11 12; do ./loose -ts_type bdf -ts_rtol 1.0e-$T -ts_atol 1.0e-$T; done #include <petsc.h> typedef struct { PetscBool spring; PetscReal g, // m s-2; acceleration of gravity m, // kg; ball mass l, // m; spring or rod length k; // N m-1; spring constant } LooseCtx; extern PetscErrorCode SetInitial(Vec, LooseCtx*); extern PetscErrorCode FreeExact(Vec, PetscReal, Vec, LooseCtx*); extern PetscErrorCode NewtonRHSFcn(TS, PetscReal, Vec, Vec, void*); int main(int argc,char **argv) { PetscErrorCode ierr; PetscInt steps; PetscReal t0 = 0.0, tf = 2.0, dt = 0.1, errnorm; Vec u, u0, uexact; TS ts; LooseCtx user; char fstr[20] = "free"; ierr = PetscInitialize(&argc, &argv, NULL, help); if (ierr) return ierr; user.spring = PETSC_FALSE; user.g = 9.81; user.m = 58.0e-3; // 58 g for a tennis ball user.l = 0.5; // spring length user.k = 20.0; // spring constant (ignored by free) ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "lse_", "options for loose", ""); CHKERRQ(ierr); ierr = PetscOptionsReal("-g", "acceleration of gravity (m s-2)", "loose.c", user.g, &user.g, NULL); CHKERRQ(ierr); ierr = PetscOptionsReal("-k", "spring constant (N m-1)", "loose.c", user.k, &user.k, NULL); CHKERRQ(ierr); ierr = PetscOptionsReal("-l", "spring length (m)", "loose.c", user.l, &user.l, NULL); CHKERRQ(ierr); ierr = PetscOptionsReal("-m", "mass of each ball (kg)", "loose.c", user.m, &user.m, NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-spring","spring case (not free)", "loose.c", user.spring, &user.spring, NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); ierr = VecCreate(PETSC_COMM_WORLD,&u); CHKERRQ(ierr); ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); // set time axis ierr = TSSetTime(ts,t0); CHKERRQ(ierr); ierr = TSSetMaxTime(ts,tf); CHKERRQ(ierr); ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); // set up vecs and solver type ierr = VecSetSizes(u,PETSC_DECIDE,8); CHKERRQ(ierr); ierr = TSSetEquationType(ts, TS_EQ_ODE_EXPLICIT); CHKERRQ(ierr); ierr = TSSetRHSFunction(ts,NULL,NewtonRHSFcn,&user); CHKERRQ(ierr); ierr = TSSetType(ts,TSRK); CHKERRQ(ierr); // set-up of u, ts is complete ierr = VecSetFromOptions(u); CHKERRQ(ierr); ierr = TSSetFromOptions(ts); CHKERRQ(ierr); // set initial values and solve ierr = SetInitial(u, &user); CHKERRQ(ierr); ierr = TSSolve(ts, u); CHKERRQ(ierr); ierr = TSGetTime(ts, &tf); CHKERRQ(ierr); // numerical error in free case if (!user.spring) { ierr = VecDuplicate(u, &uexact); CHKERRQ(ierr); // get initial condition for evaluating exact solution ierr = VecDuplicate(u, &u0); CHKERRQ(ierr); ierr = SetInitial(u0, &user); CHKERRQ(ierr); ierr = FreeExact(u0, tf, uexact, &user); CHKERRQ(ierr); ierr = VecAXPY(u, -1.0, uexact); CHKERRQ(ierr); // u <- u - uexact ierr = VecNorm(u, NORM_INFINITY, &errnorm); CHKERRQ(ierr); VecDestroy(&u0); VecDestroy(&uexact); ierr = PetscPrintf(PETSC_COMM_WORLD, "numerical error at tf in free problem: |u-uexact|_inf = %.5e\n", errnorm); CHKERRQ(ierr); } // report ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr); if (user.spring) strcpy(fstr, "spring"); ierr = PetscPrintf(PETSC_COMM_WORLD, "%s problem solved to tf = %.3f (%d steps)\n", fstr, tf, steps); CHKERRQ(ierr); VecDestroy(&u); TSDestroy(&ts); return PetscFinalize(); } /* Variable order used in the following functions: u[0] = q_1 (= x_1) u[1] = q_2 (= y_1) u[2] = q_3 (= x_2) u[3] = q_4 (= y_2) u[4] = v_1 (= dx_1/dt) u[5] = v_2 (= dy_1/dt) u[6] = v_3 (= dx_2/dt) u[7] = v_4 (= dy_2/dt) */ PetscErrorCode SetInitial(Vec u, LooseCtx *user) { /* Set initial conditions. */ PetscErrorCode ierr; PetscReal *au; ierr = VecGetArray(u,&au); CHKERRQ(ierr); au[0] = 0.0; // q1 = x1 au[1] = 1.0; // q2 = y1 au[2] = 0.0; // q3 = x2 au[3] = au[1] + user->l; // q4 = y2; satisfies (1) au[4] = 10.0; // v1 au[5] = 10.0; // v2 au[6] = 15.0; // v3 au[7] = au[5]; // v4; satisfies (2) ierr = VecRestoreArray(u,&au); CHKERRQ(ierr); return 0; } PetscErrorCode FreeExact(Vec u0, PetscReal tf, Vec uexact, LooseCtx *user) { /* Exact solution based on parabolic motion. Problem m x'' = 0, x(0) = x0, x'(0) = v0 m y'' = - m g, y(0) = y0, y'(0) = w0 has solution x(t) = x0 + v0 t, x'(t) = v0, y(t) = y0 + w0 t - (g/2) t^2, y'(t) = w0 - g t */ PetscErrorCode ierr; PetscReal *au0, *auex; if (user->spring) { SETERRQ(PETSC_COMM_SELF,7,"exact solution only implemented for free\n"); } ierr = VecGetArray(u0, &au0); CHKERRQ(ierr); ierr = VecGetArray(uexact, &auex); CHKERRQ(ierr); auex[0] = au0[0] + au0[4] * tf; auex[1] = au0[1] + au0[5] * tf - 0.5 * user->g * tf * tf; auex[2] = au0[2] + au0[6] * tf; auex[3] = au0[3] + au0[7] * tf - 0.5 * user->g * tf * tf; auex[4] = au0[4]; auex[5] = au0[5] - user->g * tf; auex[6] = au0[6]; auex[7] = au0[7] - user->g * tf; ierr = VecRestoreArray(u0, &au0); CHKERRQ(ierr); ierr = VecRestoreArray(uexact, &auex); CHKERRQ(ierr); return 0; } PetscErrorCode NewtonRHSFcn(TS ts, PetscReal t, Vec u, Vec G, void *ctx) { PetscErrorCode ierr; LooseCtx *user = (LooseCtx*)ctx; const PetscReal *au; PetscReal *aG; PetscReal dspring = 0.0, cspring = 0.0, Fx1, Fy1, Fx2, Fy2; PetscFunctionBeginUser; ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr); ierr = VecGetArray(G,&aG); CHKERRQ(ierr); Fx1 = 0.0; Fy1 = - user->m * user->g; Fx2 = 0.0; Fy2 = - user->m * user->g; if (user->spring) { dspring = PetscSqrtReal( (au[0] - au[2]) * (au[0] - au[2]) + (au[1] - au[3]) * (au[1] - au[3]) ); if (dspring == 0.0) { SETERRQ(PETSC_COMM_SELF,1,"exact ball collision (unlikely?)\n"); } cspring = user->k * (1.0 - user->l / dspring); Fx1 -= cspring * (au[0] - au[2]); Fy1 -= cspring * (au[1] - au[3]); Fx2 += cspring * (au[0] - au[2]); Fy2 += cspring * (au[1] - au[3]); } aG[0] = au[4]; aG[1] = au[5]; aG[2] = au[6]; aG[3] = au[7]; aG[4] = Fx1 / user->m; aG[5] = Fy1 / user->m; aG[6] = Fx2 / user->m; aG[7] = Fy2 / user->m; ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr); ierr = VecRestoreArray(G,&aG); CHKERRQ(ierr); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.5544925663, "avg_line_length": 38.4825870647, "ext": "c", "hexsha": "516b1cf86cfd9fb10ac21021eb7458bd06aecf58", "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": "fffd181c719e97fe1e28d01a41678357a9abde6a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bueler/dae-examples", "max_forks_repo_path": "petsc/loose.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a", "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": "bueler/dae-examples", "max_issues_repo_path": "petsc/loose.c", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bueler/dae-examples", "max_stars_repo_path": "petsc/loose.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2589, "size": 7735 }
#ifndef NOVUGNO_IMI_INCLUDE_GNOIMI_H_ #define NOVUGNO_IMI_INCLUDE_GNOIMI_H_ #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <string> #include <thread> #include <functional> #include <vector> #include <ctime> #include <chrono> #include <mutex> #include <cblas.h> struct threadInfo; class GNOIMI { public: private: int D; int K; int totalLearnCount; int learnIterationsCount; int L; int threadsCount; int totalPoints_perThread; int Init_chunkSize; int* coarseAssigns; int* fineAssigns; float* alphaNum; float* alphaDen; float* alpha; vector<float*> alphaNumerators; vector<float*> alphaDenominators; float* coarseVocab; float* fineVocab; float* fineVocabNum; float* fineVocabDen; float* coarseVocabNum; float* coarseVocabDen; vector<float*> fineVocabNumerators; vector<float*> fineVocabDenominators; vector<float*> coarseVocabNumerators; vector<float*> coarseVocabDenominators; float* coarseNorms; float* fineNorms; float* coarseFineProducts; float* errors; string output_prefix; }; using namespace std; int D = 512; int K = 657; int totalLearnCount = 260000; int learnIterationsCount = 20; int L = 6; string learnFilename = "./normalized_features_260k.fvecs"; string initCoarseFilename = "./coarse_260k.fvecs"; string initFineFilename = "./fine_260k.fvecs"; string outputFilesPrefix = "./260K_new_"; int threadsCount = 3; int totalPoints_perThread = 0; const int Init_chunkSize = 3000; int* coarseAssigns = (int*)malloc(totalLearnCount * sizeof(int)); int* fineAssigns = (int*)malloc(totalLearnCount * sizeof(int)); float* alphaNum = (float*)malloc(K * K * sizeof(float)); float* alphaDen = (float*)malloc(K * K * sizeof(float)); float* alpha = (float*)malloc(K * K * sizeof(float)); vector<float*> alphaNumerators(threadsCount); vector<float*> alphaDenominators(threadsCount); float* coarseVocab = (float*)malloc(D * K * sizeof(float)); float* fineVocab = (float*)malloc(D * K * sizeof(float)); float* fineVocabNum = (float*)malloc(D * K * sizeof(float)); float* fineVocabDen = (float*)malloc(K * sizeof(float)); float* coarseVocabNum = (float*)malloc(D * K * sizeof(float)); float* coarseVocabDen = (float*)malloc(K * sizeof(float)); vector<float*> fineVocabNumerators(threadsCount); vector<float*> fineVocabDenominators(threadsCount); vector<float*> coarseVocabNumerators(threadsCount); vector<float*> coarseVocabDenominators(threadsCount); float* coarseNorms = (float*)malloc(K * sizeof(float)); float* fineNorms = (float*)malloc(K * sizeof(float)); float* coarseFineProducts = (float*)malloc(K * K * sizeof(float)); float* errors = (float*)malloc(threadsCount * sizeof(float)); mutex mtx; struct threadInfo { long long startId; int pointsCount; int chunksCount; int trainThreadChunkSize; int extra_ChunkSize; }; threadInfo get_threadInfo(const int& threadId) { threadInfo t_info; t_info.startId = totalPoints_perThread * threadId; t_info.trainThreadChunkSize = Init_chunkSize; if (totalPoints_perThread * (threadId + 1) <= totalLearnCount) { t_info.pointsCount = totalPoints_perThread; } else { t_info.pointsCount = totalLearnCount - totalPoints_perThread * threadId; } t_info.extra_ChunkSize = 0; if (t_info.pointsCount % t_info.trainThreadChunkSize == 0) { t_info.chunksCount = t_info.pointsCount / t_info.trainThreadChunkSize; } else { t_info.extra_ChunkSize = t_info.pointsCount % t_info.trainThreadChunkSize; t_info.chunksCount = (t_info.pointsCount - t_info.extra_ChunkSize) / t_info.trainThreadChunkSize + 1; } return t_info; } void computeOptimalAssignsSubset(int threadId) { threadInfo cur_t_info = get_threadInfo(threadId); int trainThreadChunkSize = cur_t_info.trainThreadChunkSize; errors[threadId] = 0.0; FILE* learnStream = fopen(learnFilename.c_str(), "r"); fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET); float* pointsCoarseTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float)); float* pointsFineTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float)); float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); std::vector<std::pair<float, int> > coarseScores(K); for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) { std::cout << "[Assigns][Thread " << threadId << "] " << "processing chunk " << chunkId << " of " << cur_t_info.chunksCount << "\n"; if (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) { free(pointsCoarseTerms); free(pointsFineTerms); free(chunkPoints); trainThreadChunkSize = cur_t_info.extra_ChunkSize; pointsCoarseTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float)); pointsFineTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float)); chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); } fvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D); fmat_mul_full(coarseVocab, chunkPoints, K, trainThreadChunkSize, D, "TN", pointsCoarseTerms); fmat_mul_full(fineVocab, chunkPoints, K, trainThreadChunkSize, D, "TN", pointsFineTerms); for(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) { cblas_saxpy(K, -1.0, coarseNorms, 1, pointsCoarseTerms + pointId * K, 1); for(int k = 0; k < K; ++k) { coarseScores[k].first = (-1.0) * pointsCoarseTerms[pointId * K + k]; coarseScores[k].second = k; } std::sort(coarseScores.begin(), coarseScores.end()); float currentMinScore = 999999999.0; int currentMinCoarseId = -1; int currentMinFineId = -1; for(int l = 0; l < L; ++l) { //examine cluster l int currentCoarseId = coarseScores[l].second; float currentCoarseTerm = coarseScores[l].first; for(int currentFineId = 0; currentFineId < K; ++currentFineId) { float alphaFactor = alpha[currentCoarseId * K + currentFineId]; float score = currentCoarseTerm + alphaFactor * coarseFineProducts[currentCoarseId * K + currentFineId] + (-1.0) * alphaFactor * pointsFineTerms[pointId * K + currentFineId] + alphaFactor * alphaFactor * fineNorms[currentFineId]; if(score < currentMinScore) { currentMinScore = score; currentMinCoarseId = currentCoarseId; currentMinFineId = currentFineId; } } } coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId] = currentMinCoarseId; fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId] = currentMinFineId; errors[threadId] += currentMinScore * 2 + 1.0; // point has a norm equals 1.0 } } fclose(learnStream); free(chunkPoints); free(pointsCoarseTerms); free(pointsFineTerms); } void computeOptimalAlphaSubset(int threadId) { memset(alphaNumerators[threadId], 0, K * K * sizeof(float)); memset(alphaDenominators[threadId], 0, K * K * sizeof(float)); threadInfo cur_t_info = get_threadInfo(threadId); int trainThreadChunkSize = cur_t_info.trainThreadChunkSize; FILE* learnStream = fopen(learnFilename.c_str(), "r"); fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET); float* residual = (float*)malloc(D * sizeof(float)); float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) { std::cout << "[Alpha][Thread " << threadId << "] " << "processing chunk " << chunkId << " of " << cur_t_info.chunksCount << "\n"; if (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) { free(chunkPoints); trainThreadChunkSize = cur_t_info.extra_ChunkSize; chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); } fvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D); for(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) { //S_k int coarseAssign = coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId]; //T_l int fineAssign = fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId]; memcpy(residual, chunkPoints + pointId * D, D * sizeof(float)); //P_i - S_k cblas_saxpy(D, -1.0, coarseVocab + coarseAssign * D, 1, residual, 1); //<P_i - S_k, T_l> alphaNumerators[threadId][coarseAssign * K + fineAssign] += cblas_sdot(D, residual, 1, fineVocab + fineAssign * D, 1); //||T||^2 alphaDenominators[threadId][coarseAssign * K + fineAssign] += fineNorms[fineAssign] * 2; // we keep halves of norms } } fclose(learnStream); free(chunkPoints); free(residual); } void computeOptimalFineVocabSubset(int threadId) { memset(fineVocabNumerators[threadId], 0, K * D * sizeof(float)); memset(fineVocabDenominators[threadId], 0, K * sizeof(float)); threadInfo cur_t_info = get_threadInfo(threadId); int trainThreadChunkSize = cur_t_info.trainThreadChunkSize; FILE* learnStream = fopen(learnFilename.c_str(), "r"); fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET); float* residual = (float*)malloc(D * sizeof(float)); float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) { //std::cout << "[Fine vocabs][Thread " << threadId << "] " << "processing chunk " << chunkId << " of " << chunksCount << "\n"; if (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) { free(chunkPoints); trainThreadChunkSize = cur_t_info.extra_ChunkSize; chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); } fvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D); for(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) { int coarseAssign = coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId]; int fineAssign = fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId]; float alphaFactor = alpha[coarseAssign * K + fineAssign]; memcpy(residual, chunkPoints + pointId * D, D * sizeof(float)); cblas_saxpy(D, -1.0, coarseVocab + coarseAssign * D, 1, residual, 1); cblas_saxpy(D, alphaFactor, residual, 1, fineVocabNumerators[threadId] + fineAssign * D, 1); fineVocabDenominators[threadId][fineAssign] += alphaFactor * alphaFactor; } } fclose(learnStream); free(chunkPoints); free(residual); } void computeOptimalCoarseVocabSubset(int threadId) { memset(coarseVocabNumerators[threadId], 0, K * D * sizeof(float)); memset(coarseVocabDenominators[threadId], 0, K * sizeof(float)); threadInfo cur_t_info = get_threadInfo(threadId); int trainThreadChunkSize = cur_t_info.trainThreadChunkSize; FILE* learnStream = fopen(learnFilename.c_str(), "r"); fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET); float* residual = (float*)malloc(D * sizeof(float)); float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) { //std::cout << "[Coarse vocabs][Thread " << threadId << "] " << "processing chunk " << chunkId << " of " << chunksCount << "\n"; if (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) { free(chunkPoints); trainThreadChunkSize = cur_t_info.extra_ChunkSize; chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float)); } fvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D); for(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) { int coarseAssign = coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId]; int fineAssign = fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId]; float alphaFactor = alpha[coarseAssign * K + fineAssign]; memcpy(residual, chunkPoints + pointId * D, D * sizeof(float)); cblas_saxpy(D, -1.0 * alphaFactor, fineVocab + fineAssign * D, 1, residual, 1); cblas_saxpy(D, 1, residual, 1, coarseVocabNumerators[threadId] + coarseAssign * D, 1); coarseVocabDenominators[threadId][coarseAssign] += 1.0; } } fclose(learnStream); free(chunkPoints); free(residual); } int main() { totalPoints_perThread = totalLearnCount / threadsCount; //increase the threadCount if (totalLearnCount % threadsCount != 0) { threadsCount += 1; alphaNumerators.resize(threadsCount); alphaDenominators.resize(threadsCount); fineVocabNumerators.resize(threadsCount); fineVocabDenominators.resize(threadsCount); coarseVocabNumerators.resize(threadsCount); coarseVocabDenominators.resize(threadsCount); free(errors); errors = (float*)malloc(threadsCount * sizeof(float)); } for(int threadId = 0; threadId < threadsCount; ++threadId) { alphaNumerators[threadId] = (float*)malloc(K * K * sizeof(float*)); alphaDenominators[threadId] = (float*)malloc(K * K * sizeof(float*)); } for(int threadId = 0; threadId < threadsCount; ++threadId) { fineVocabNumerators[threadId] = (float*)malloc(K * D * sizeof(float*)); fineVocabDenominators[threadId] = (float*)malloc(K * sizeof(float*)); } for(int threadId = 0; threadId < threadsCount; ++threadId) { coarseVocabNumerators[threadId] = (float*)malloc(K * D * sizeof(float)); coarseVocabDenominators[threadId] = (float*)malloc(K * sizeof(float)); } // init vocabs fvecs_read(initCoarseFilename.c_str(), D, K, coarseVocab); fvecs_read(initFineFilename.c_str(), D, K, fineVocab); // init alpha for(int i = 0; i < K * K; ++i) { alpha[i] = 1.0f; } // learn iterations std::cout << "Start learning iterations...\n"; for(int it = 0; it < learnIterationsCount; ++it) { cout << "learning iteration " << it << endl; for(int k = 0; k < K; ++k) { coarseNorms[k] = cblas_sdot(D, coarseVocab + k * D, 1, coarseVocab + k * D, 1) / 2; fineNorms[k] = cblas_sdot(D, fineVocab + k * D, 1, fineVocab + k * D, 1) / 2; } fmat_mul_full(fineVocab, coarseVocab, K, K, D, "TN", coarseFineProducts); // update Assigns vector<std::thread> workers; memset(errors, 0, threadsCount * sizeof(float)); for(int threadId = 0; threadId < threadsCount; ++threadId) { workers.push_back(std::thread(computeOptimalAssignsSubset, threadId)); } for(int threadId = 0; threadId < threadsCount; ++threadId) { workers[threadId].join(); } float totalError = 0.0; for(int threadId = 0; threadId < threadsCount; ++threadId) { cout << "threadId " << threadId << ": err " << errors[threadId] << endl; totalError += errors[threadId]; } std::cout << "Current reconstruction error... " << totalError / totalLearnCount << "\n"; // update alpha workers.clear(); for(int threadId = 0; threadId < threadsCount; ++threadId) { workers.push_back(std::thread(computeOptimalAlphaSubset, threadId)); } for(int threadId = 0; threadId < threadsCount; ++threadId) { workers[threadId].join(); } // update fine Vocabs workers.clear(); memset(alphaNum, 0, K * K * sizeof(float)); memset(alphaDen, 0, K * K * sizeof(float)); for(int threadId = 0; threadId < threadsCount; ++threadId) { cblas_saxpy(K * K, 1, alphaNumerators[threadId], 1, alphaNum, 1); cblas_saxpy(K * K, 1, alphaDenominators[threadId], 1, alphaDen, 1); } for(int i = 0; i < K * K; ++i) { alpha[i] = (alphaDen[i] == 0) ? 1.0 : alphaNum[i] / alphaDen[i]; } for(int threadId = 0; threadId < threadsCount; ++threadId) { workers.push_back(std::thread(computeOptimalFineVocabSubset, threadId)); } for(int threadId = 0; threadId < threadsCount; ++threadId) { workers[threadId].join(); } // update coarse Vocabs workers.clear(); memset(fineVocabNum, 0, K * D * sizeof(float)); memset(fineVocabDen, 0, K * sizeof(float)); for(int threadId = 0; threadId < threadsCount; ++threadId) { cblas_saxpy(K * D, 1, fineVocabNumerators[threadId], 1, fineVocabNum, 1); cblas_saxpy(K, 1, fineVocabDenominators[threadId], 1, fineVocabDen, 1); } for(int i = 0; i < K * D; ++i) { fineVocab[i] = (fineVocabDen[i / D] == 0) ? 0 : fineVocabNum[i] / fineVocabDen[i / D]; } for(int threadId = 0; threadId < threadsCount; ++threadId) { workers.push_back(std::thread(computeOptimalCoarseVocabSubset, threadId)); } for(int threadId = 0; threadId < threadsCount; ++threadId) { workers[threadId].join(); } workers.clear(); memset(coarseVocabNum, 0, K * D * sizeof(float)); memset(coarseVocabDen, 0, K * sizeof(float)); for(int threadId = 0; threadId < threadsCount; ++threadId) { cblas_saxpy(K * D, 1, coarseVocabNumerators[threadId], 1, coarseVocabNum, 1); cblas_saxpy(K, 1, coarseVocabDenominators[threadId], 1, coarseVocabDen, 1); } for(int i = 0; i < K * D; ++i) { coarseVocab[i] = (coarseVocabDen[i / D] == 0) ? 0 : coarseVocabNum[i] / coarseVocabDen[i / D]; } // save current alpha and vocabs std::stringstream alphaFilename; alphaFilename << outputFilesPrefix << "alpha_" << it << ".fvecs"; fvecs_write(alphaFilename.str().c_str(), K, K, alpha); std::stringstream fineVocabFilename; fineVocabFilename << outputFilesPrefix << "fine_" << it << ".fvecs"; fvecs_write(fineVocabFilename.str().c_str(), D, K, fineVocab); std::stringstream coarseVocabFilename; coarseVocabFilename << outputFilesPrefix << "coarse_" << it << ".fvecs"; fvecs_write(coarseVocabFilename.str().c_str(), D, K, coarseVocab); cout << "iteration " << it << " finished!" << endl; } free(coarseAssigns); free(fineAssigns); free(alphaNum); free(alphaDen); free(alpha); free(coarseVocab); free(coarseVocabNum); free(coarseVocabDen); free(fineVocab); free(fineVocabNum); free(fineVocabDen); free(coarseNorms); free(fineNorms); free(coarseFineProducts); free(errors); return 0; } #endif //NOVUGNO_IMI_INCLUDE_GNOIMI_H_
{ "alphanum_fraction": 0.6926509476, "avg_line_length": 35.0424710425, "ext": "h", "hexsha": "b1abdac519ddb0b771bbbd7dbd101e5ccd8abbb1", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-06-02T06:49:54.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-01T08:18:10.000Z", "max_forks_repo_head_hexsha": "befa71ab0c774a6c878c8a45ab77248cdc2be089", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "5ace/GNOIMI-1", "max_forks_repo_path": "include/GNOIMI.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "befa71ab0c774a6c878c8a45ab77248cdc2be089", "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": "5ace/GNOIMI-1", "max_issues_repo_path": "include/GNOIMI.h", "max_line_length": 133, "max_stars_count": 1, "max_stars_repo_head_hexsha": "befa71ab0c774a6c878c8a45ab77248cdc2be089", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "5ace/GNOIMI-1", "max_stars_repo_path": "include/GNOIMI.h", "max_stars_repo_stars_event_max_datetime": "2021-05-26T07:54:33.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-26T07:54:33.000Z", "num_tokens": 5253, "size": 18152 }
#ifndef KEYPOINT_TRANSFORM_H_ARXFM8VJ #define KEYPOINT_TRANSFORM_H_ARXFM8VJ #include <gsl/gsl> #include <sens_loc/camera_models/pinhole.h> #include <sens_loc/camera_models/projection.h> #include <sens_loc/math/pointcloud.h> namespace sens_loc::apps { template <template <typename> typename Model = sens_loc::camera_models::pinhole, typename Real = float> math::pointcloud<Real> keypoints_to_pointcloud(const std::vector<cv::KeyPoint>& kps, const math::image<ushort>& depth_image, const Model<Real>& c, float unit_factor) noexcept { using camera_models::keypoint_to_coords; math::imagepoints<Real> pts = keypoint_to_coords(kps); math::pointcloud<Real> c_pts = project_to_sphere(c, pts); for (std::size_t i = 0; i < c_pts.size(); ++i) { auto orig_depth = depth_image.at(pts[i]); auto t_d = unit_factor * gsl::narrow_cast<float>(orig_depth); c_pts[i] = t_d * c_pts[i]; } return c_pts; } /// Transform the pointcloud \c points_in_other_frame into the coordinate /// frame of \c c and project these points into \c c's image plane. /// \returns the backprojected points /// \sa project_to_image template <template <typename> typename Model = sens_loc::camera_models::pinhole, typename Real = float> math::imagepoints<Real> project_to_other_camera(const math::pose_t& pose, const math::pointcloud<Real>& points_in_other_frame, const Model<Real>& c) noexcept { math::pointcloud<Real> transformed = pose * points_in_other_frame; math::imagepoints<Real> backprojected = project_to_image(c, transformed); return backprojected; } } // namespace sens_loc::apps #endif /* end of include guard: KEYPOINT_TRANSFORM_H_ARXFM8VJ */
{ "alphanum_fraction": 0.6405529954, "avg_line_length": 39.06, "ext": "h", "hexsha": "fed380f82342617fb7de966f36f23dbac37220dd", "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/feature_performance/keypoint_transform.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/feature_performance/keypoint_transform.h", "max_line_length": 80, "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/feature_performance/keypoint_transform.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": 454, "size": 1953 }
/* ** Copyright (C) 2004 Jonathan G. Underwood <j.underwood@open.ac.uk> ** ** 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. */ /* Things to check: Not sure I'm using the correct error macros - should I be using the ones in the GSL manual? Based the ones here on what i see in coupling.c. */ #include <config.h> #include <stdlib.h> #include <error.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_result.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_wigner.h> /* Static prototypes. */ static int istriangle (const int two_ja, const int two_jb, const int two_jc); static int lndelta_e (const int two_j1, const int two_j2, const int two_j3, gsl_sf_result * lndelta); /* This macro returns 1 if n is even, -1 if n is odd. */ #define PHASE(n) (GSL_IS_ODD(n) ? -1.0 : 1.0) static int istriangle (const int two_ja, const int two_jb, const int two_jc) /* Returns 0 if the triangle condition is met, and the sum of twice the angular momenta is even. Arguments are twice the value of the angular momenta. */ { if ((two_jc <= two_ja + two_jb) && (two_jc >= abs (two_ja - two_jb)) && (GSL_IS_EVEN (two_ja + two_jb + two_jc))) return 1; else return 0; } static int lndelta_e (const int two_j1, const int two_j2, const int two_j3, gsl_sf_result * lndelta) /* Calculates the natural log of the delta function - Zare Eq. A-2. Note: values returned from gsl_sf_ln_fact_e are always positive. */ { gsl_sf_result a1, a2, a3, a4; int status; status = gsl_sf_lnfact_e ((two_j1 + two_j2 - two_j3) / 2, &a1); status += gsl_sf_lnfact_e ((two_j1 - two_j2 + two_j3) / 2, &a2); status += gsl_sf_lnfact_e ((-two_j1 + two_j2 + two_j3) / 2, &a3); status += gsl_sf_lnfact_e ((two_j1 + two_j2 + two_j3) / 2 + 1, &a4); if (status != GSL_SUCCESS) OVERFLOW_ERROR (lndelta); lndelta->val = 0.5 * (a1.val + a2.val + a3.val - a4.val); lndelta->err = 0.5 * (a1.err + a2.err + a3.err + a4.err); lndelta->err += 2.0 * GSL_DBL_EPSILON * (a1.val + a2.val + a3.val + a4.val); return GSL_SUCCESS; } int gsl_sf_wigner_3j_e (const int two_j1, const int two_j2, const int two_j3, const int two_m1, const int two_m2, const int two_m3, gsl_sf_result * result) /* Returns the value of the wigner 3j symbol - Zare Eq. A-1. Note that in Zare's book, this equation contains typos. */ { int v, vmin, vmax, t1, t2, t3, t4, t5, status; gsl_sf_result a, a1, a2, a3, a4, a5, a6, a7, a8; if ((two_j1 < 0) || (two_j2 < 0) || (two_j3 < 0) || (abs (two_m1) > two_j1) || (abs (two_m2) > two_j2) || (abs (two_m3) > two_j3) || GSL_IS_ODD (two_j1 + two_m1) || GSL_IS_ODD (two_j2 + two_m2) || GSL_IS_ODD (two_j3 + two_m3)) DOMAIN_ERROR (result); result->val = 0.0; result->err = 0.0; if ((!istriangle (two_j1, two_j2, two_j3)) || (two_m1 + two_m2 + two_m3) != 0) return GSL_SUCCESS; t1 = (two_j1 + two_j2 - two_j3) / 2; t2 = (two_j1 - two_m1) / 2; t3 = (two_j2 + two_m2) / 2; t4 = (two_j3 - two_j2 + two_m1) / 2; t5 = (two_j3 - two_j1 - two_m2) / 2; vmin = (t4 < t5) ? -t4 : -t5; vmin = (vmin < 0) ? 0 : vmin; vmax = t1; vmax = (t2 < vmax) ? t2 : vmax; vmax = (t3 < vmax) ? t3 : vmax; if (vmin > vmax) return GSL_SUCCESS; status = gsl_sf_lnfact_e ((two_j1 + two_m1) / 2, &a1); status += gsl_sf_lnfact_e (t2, &a2); status += gsl_sf_lnfact_e (t3, &a3); status += gsl_sf_lnfact_e ((two_j2 - two_m2) / 2, &a4); status += gsl_sf_lnfact_e ((two_j3 + two_m3) / 2, &a5); status += gsl_sf_lnfact_e ((two_j3 - two_m3) / 2, &a6); status += lndelta_e (two_j1, two_j2, two_j3, &a7); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); a.val = 0.5 * (a1.val + a2.val + a3.val + a4.val + a5.val + a6.val) + a7.val; a.err = 0.5 * (a1.err + a2.err + a3.err + a4.err + a5.err + a6.err) + a7.err; a.err += 2.0 * GSL_DBL_EPSILON * a.val; for (v = vmin; v <= vmax; v++) { status += gsl_sf_lnfact_e (v, &a1); status += gsl_sf_lnfact_e (t1 - v, &a2); status += gsl_sf_lnfact_e (t2 - v, &a3); status += gsl_sf_lnfact_e (t3 - v, &a4); status += gsl_sf_lnfact_e (t4 + v, &a5); status += gsl_sf_lnfact_e (t5 + v, &a6); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); a7.val = a.val - (a1.val + a2.val + a3.val + a4.val + a5.val + a6.val); a7.err = (a.err + a1.err + a2.err + a3.err + a4.err + a5.err + a6.err); a7.err += 2.0 * GSL_DBL_EPSILON * (a.val + a1.val + a2.val + a3.val + a4.val + a5.val + a6.val); status += gsl_sf_exp_err_e (a7.val, a7.err, &a8); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); result->val += PHASE (v) * a8.val; result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val); } result->val *= PHASE ((two_j1 - two_j2 - two_m3) / 2); result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val); return GSL_SUCCESS; } int gsl_sf_wigner_6j_e (const int two_j1, const int two_j2, const int two_j3, const int two_j4, const int two_j5, const int two_j6, gsl_sf_result * result) /* Returns the value of the 6j symbol - Zare Eq. A-4 */ { int v, vmin, vmax, t1, t2, t3, t4, t5, t6, t7, status; gsl_sf_result a, a1, a2, a3, a4; if ((two_j1 < 0) || (two_j2 < 0) || (two_j3 < 0) || (two_j4 < 0) || (two_j5 < 0) || (two_j6 < 0)) DOMAIN_ERROR (result); result->val = 0.0; result->err = 0.0; if (!istriangle (two_j1, two_j2, two_j3) || !istriangle (two_j1, two_j5, two_j6) || !istriangle (two_j4, two_j2, two_j6) || !istriangle (two_j4, two_j5, two_j3)) return GSL_SUCCESS; t1 = (two_j1 + two_j2 + two_j3) / 2; t2 = (two_j1 + two_j5 + two_j6) / 2; t3 = (two_j4 + two_j2 + two_j6) / 2; t4 = (two_j4 + two_j5 + two_j3) / 2; t5 = (two_j1 + two_j2 + two_j4 + two_j5) / 2; t6 = (two_j2 + two_j3 + two_j5 + two_j6) / 2; t7 = (two_j3 + two_j1 + two_j6 + two_j4) / 2; vmin = t1; vmin = (t2 > vmin) ? t2 : vmin; vmin = (t3 > vmin) ? t3 : vmin; vmin = (t4 > vmin) ? t4 : vmin; vmax = t5; vmax = (t6 < vmax) ? t6 : vmax; vmax = (t7 < vmax) ? t7 : vmax; if (vmin > vmax) return GSL_SUCCESS; status = lndelta_e (two_j1, two_j2, two_j3, &a1); status += lndelta_e (two_j1, two_j5, two_j6, &a2); status += lndelta_e (two_j4, two_j2, two_j6, &a3); status += lndelta_e (two_j4, two_j5, two_j3, &a4); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); a.val = a1.val + a2.val + a3.val + a4.val; a.err = a1.err + a2.err + a3.err + a4.err; a.err += 2.0 * GSL_DBL_EPSILON * a.val; for (v = vmin; v <= vmax; v++) { gsl_sf_result b1, b2, b3, b4, b5, b6, b7, b8, b9, b10; status += gsl_sf_lnfact_e (v + 1, &b1); status += gsl_sf_lnfact_e (v - t1, &b2); status += gsl_sf_lnfact_e (v - t2, &b3); status += gsl_sf_lnfact_e (v - t3, &b4); status += gsl_sf_lnfact_e (v - t4, &b5); status += gsl_sf_lnfact_e (t5 - v, &b6); status += gsl_sf_lnfact_e (t6 - v, &b7); status += gsl_sf_lnfact_e (t7 - v, &b8); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); b9.val = a.val + b1.val - b2.val - b3.val - b4.val - b5.val - b6.val - b7.val - b8.val; b9.err = a.err + b1.err + b2.err + b3.err + b4.err + b5.err + b6.err + b7.err + b8.err; b9.err += 2.0 * GSL_DBL_EPSILON * (a.val + b1.val + b2.val + b3.val + b4.val + b5.val + b6.val + b7.val + b8.val); status += gsl_sf_exp_err_e (b9.val, b9.err, &b10); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); result->val += b10.val * PHASE (v); result->err += b10.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val); } return GSL_SUCCESS; } int gsl_sf_wigner_9j_e (const int two_j1, const int two_j2, const int two_j3, const int two_j4, const int two_j5, const int two_j6, const int two_j7, const int two_j8, const int two_j9, gsl_sf_result * result) /* Returns the value of 9j symbol - Zare Eq. 4.24 */ { int two_k, two_kmin, two_kmax, status = GSL_SUCCESS; if ((two_j1 < 0) || (two_j2 < 0) || (two_j3 < 0) || (two_j4 < 0) || (two_j5 < 0) || (two_j6 < 0) || (two_j7 < 0) || (two_j8 < 0) || (two_j9 < 0)) DOMAIN_ERROR (result); result->val = 0.0; result->err = 0.0; if (!istriangle (two_j1, two_j2, two_j3) || !istriangle (two_j4, two_j5, two_j6) || !istriangle (two_j7, two_j8, two_j9) || !istriangle (two_j1, two_j4, two_j7) || !istriangle (two_j2, two_j5, two_j8) || !istriangle (two_j3, two_j6, two_j9)) return GSL_SUCCESS; two_kmin = abs (two_j1 - two_j9); two_kmin = (abs (two_j8 - two_j4) < two_kmin) ? abs (two_j8 - two_j4) : two_kmin; two_kmin = (abs (two_j6 - two_j2) < two_kmin) ? abs (two_j6 - two_j2) : two_kmin; two_kmax = (two_j1 + two_j9); two_kmax = (two_j8 + two_j4 > two_kmax) ? two_j8 + two_j4 : two_kmax; two_kmax = (two_j6 + two_j2 > two_kmax) ? two_j6 + two_j2 : two_kmax; if (two_kmax < two_kmin) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } for (two_k = two_kmin; two_k <= two_kmax; two_k += 2) { gsl_sf_result a1, a2, a3; status += gsl_sf_wigner_6j_e (two_j1, two_j4, two_j7, two_j8, two_j9, two_k, &a1); status += gsl_sf_wigner_6j_e (two_j2, two_j5, two_j8, two_j4, two_k, two_j6, &a2); status += gsl_sf_wigner_6j_e (two_j3, two_j6, two_j9, two_k, two_j1, two_j2, &a3); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); result->val += (two_k + 1.0) * PHASE (two_k) * a1.val * a2.val * a3.val; result->err += result->val * (fabs (a1.err / a1.val) + fabs (a2.err / a2.val) + fabs (a3.err / a3.val)); result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val); } return GSL_SUCCESS; } int gsl_sf_wigner_drot_e (const int two_j, const int two_m1, const int two_m2, const double theta, gsl_sf_result * result) /* Returns the value of the reduced rotation matrix - Zare Eq. 3.57. (which contains typos). Angle theta is in radians. */ { int v, vmin, vmax, t1, t2, t3, t4, tv, status = GSL_SUCCESS; gsl_sf_result a, a1, a2, a3, a4, st, ct; if ((two_j) < 0 || abs (two_m1) > two_j || abs (two_m2) > two_j || (GSL_IS_ODD (two_j + two_m1)) || (GSL_IS_ODD (two_j + two_m2))) DOMAIN_ERROR (result); result->val = 0.0; result->err = 0.0; t1 = (two_j + two_m1) / 2; t2 = (two_j - two_m2) / 2; t3 = (two_m2 - two_m1) / 2; t4 = (2 * two_j + two_m1 - two_m2) / 2; vmin = (-t3 < 0) ? 0 : -t3; vmax = (t2 < t1) ? t2 : t1; if (vmin > vmax) return GSL_SUCCESS; status += gsl_sf_cos_e (theta * 0.5, &ct); status += gsl_sf_sin_e (theta * 0.5, &st); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); status += gsl_sf_lnfact_e (t1, &a1); status += gsl_sf_lnfact_e (t2, &a2); status += gsl_sf_lnfact_e ((two_j - two_m1) / 2, &a3); status += gsl_sf_lnfact_e ((two_j + two_m2) / 2, &a4); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); a.val = 0.5 * (a1.val + a2.val + a3.val + a4.val); a.err = 0.5 * (a1.err + a2.err + a3.err + a4.err); a.err += 2.0 * GSL_DBL_EPSILON * a.val; for (v = vmin; v <= vmax; v++) { gsl_sf_result b1, b2, b3, b4, b5, b6, b7, b8; int i1, i2; status += gsl_sf_lnfact_e (t1 - v, &b1); status += gsl_sf_lnfact_e (t2 - v, &b2); status += gsl_sf_lnfact_e (t3 + v, &b3); status += gsl_sf_lnfact_e (v, &b4); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); b5.val = a.val - b1.val - b2.val - b3.val - b4.val; b5.err = a.err + b1.err + b2.err + b3.err + b4.err; b5.err += 2.0 * GSL_DBL_EPSILON * (a.val + b1.val + b2.val + b3.val + b4.val); status += gsl_sf_exp_err_e (b5.val, b5.err, &b6); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); tv = 2 * v; i1 = t4 - tv; i2 = t3 + tv; status += gsl_sf_pow_int_e (ct.val, i1, &b7); status += gsl_sf_pow_int_e (st.val, i2, &b8); if (status != GSL_SUCCESS) OVERFLOW_ERROR (result); /* Bolt on error in pow_int for the error in the input values */ b7.err += i1 * fabs (ct.err); b8.err += i2 * fabs (st.err); result->val += PHASE (v) * b6.val * b7.val * b8.val; result->err += fabs (result->val) * (fabs (b6.err / b6.val) + fabs (b7.err / b7.val) + fabs (b8.err / b8.val)); result->err += 2.0 * GSL_DBL_EPSILON * fabs (result->val); } return GSL_SUCCESS; } #include "eval.h" double gsl_sf_wigner_3j (const int two_j1, const int two_j2, const int two_j3, const int two_m1, const int two_m2, const int two_m3) { EVAL_RESULT (gsl_sf_wigner_3j_e (two_j1, two_j2, two_j3, two_m1, two_m2, two_m3, &result)); } double gsl_sf_wigner_6j (const int two_j1, const int two_j2, const int two_j3, const int two_j4, const int two_j5, const int two_j6) { EVAL_RESULT (gsl_sf_wigner_6j_e (two_j1, two_j2, two_j3, two_j4, two_j5, two_j6, &result)); } double gsl_sf_wigner_9j (const int two_j1, const int two_j2, const int two_j3, const int two_j4, const int two_j5, const int two_j6, const int two_j7, const int two_j8, const int two_j9) { EVAL_RESULT (gsl_sf_wigner_9j_e (two_j1, two_j2, two_j3, two_j4, two_j5, two_j6, two_j7, two_j8, two_j9, &result)); } double gsl_sf_wigner_drot (const int two_j, const int two_m1, const int two_m2, const double theta) { EVAL_RESULT (gsl_sf_wigner_drot_e (two_j, two_m1, two_m2, theta, &result)); } #undef PHASE
{ "alphanum_fraction": 0.5835949502, "avg_line_length": 33.7184684685, "ext": "c", "hexsha": "9754d7bf37ee1fce52bf61f35682a68a6e7fb853", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/wigner.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/wigner.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/contrib/wigner.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": 5455, "size": 14971 }
/* matrix/test.c * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #define M 53 #define N 107 int status = 0; #ifndef DESC #define DESC "" #endif #define BASE_GSL_COMPLEX_LONG #include "templates_on.h" #include "test_complex_source.c" #include "templates_off.h" #undef BASE_GSL_COMPLEX_LONG #define BASE_GSL_COMPLEX #include "templates_on.h" #include "test_complex_source.c" #include "templates_off.h" #undef BASE_GSL_COMPLEX #define BASE_GSL_COMPLEX_FLOAT #include "templates_on.h" #include "test_complex_source.c" #include "templates_off.h" #undef BASE_GSL_COMPLEX_FLOAT #define BASE_LONG_DOUBLE #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_LONG_DOUBLE #define BASE_DOUBLE #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_FLOAT #define BASE_ULONG #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_ULONG #define BASE_LONG #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_LONG #define BASE_UINT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_UINT #define BASE_INT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_INT #define BASE_USHORT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_USHORT #define BASE_SHORT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_SHORT #define BASE_UCHAR #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_UCHAR #define BASE_CHAR #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_CHAR void my_error_handler (const char *reason, const char *file, int line, int err); int main (void) { gsl_ieee_env_setup (); test_func (); test_float_func (); test_long_double_func (); test_ulong_func (); test_long_func (); test_uint_func (); test_int_func (); test_ushort_func (); test_short_func (); test_uchar_func (); test_char_func (); test_complex_func (); test_complex_float_func (); test_complex_long_double_func (); test_text (); test_float_text (); #ifdef HAVE_PRINTF_LONGDOUBLE test_long_double_text (); #endif test_ulong_text (); test_long_text (); test_uint_text (); test_int_text (); test_ushort_text (); test_short_text (); test_uchar_text (); test_char_text (); test_complex_text (); test_complex_float_text (); #ifdef HAVE_PRINTF_LONGDOUBLE test_complex_long_double_text (); #endif test_binary (); test_float_binary (); test_long_double_binary (); test_ulong_binary (); test_long_binary (); test_uint_binary (); test_int_binary (); test_ushort_binary (); test_short_binary (); test_uchar_binary (); test_char_binary (); test_complex_binary (); test_complex_float_binary (); test_complex_long_double_binary (); gsl_warnings_off = 1; gsl_set_error_handler (&my_error_handler); test_trap (); test_float_trap (); test_long_double_trap (); test_ulong_trap (); test_long_trap (); test_uint_trap (); test_int_trap (); test_ushort_trap (); test_short_trap (); test_uchar_trap (); test_char_trap (); test_complex_trap (); test_complex_float_trap (); test_complex_long_double_trap (); exit (gsl_test_summary ()); } void my_error_handler (const char *reason, const char *file, int line, int err) { if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err); status = 1; }
{ "alphanum_fraction": 0.7388864912, "avg_line_length": 22.2788461538, "ext": "c", "hexsha": "cffc98911cb1ca5ccdffad54aecccd2239c1b5a5", "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/matrix/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/matrix/test.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/matrix/test.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 1127, "size": 4634 }
#include <config.h> #include <stddef.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_fft_halfcomplex_float.h> #define BASE_DOUBLE #include "templates_on.h" #include "hc_pass.h" #include "hc_init.c" #include "hc_main.c" #include "hc_pass_2.c" #include "hc_pass_3.c" #include "hc_pass_4.c" #include "hc_pass_5.c" #include "hc_pass_n.c" #include "hc_radix2.c" #include "hc_unpack.c" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "hc_pass.h" #include "hc_init.c" #include "hc_main.c" #include "hc_pass_2.c" #include "hc_pass_3.c" #include "hc_pass_4.c" #include "hc_pass_5.c" #include "hc_pass_n.c" #include "hc_radix2.c" #include "hc_unpack.c" #include "templates_off.h" #undef BASE_FLOAT
{ "alphanum_fraction": 0.7482352941, "avg_line_length": 20.7317073171, "ext": "c", "hexsha": "284e864c26bfa52cf42aa9f0c68176b15264aa33", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/hc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/hc.c", "max_line_length": 42, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/fft/hc.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": 245, "size": 850 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_statistics_double.h> #include <math.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_voxel_graphics.h" #include "tz_neurotrace.h" #include "tz_stack_math.h" #include "tz_stack_utils.h" #include "tz_objdetect.h" #include "tz_voxeltrans.h" #include "tz_stack_stat.h" #include "tz_stack_draw.h" #include "tz_stack_io.h" #include "tz_stack_bwmorph.h" #include "tz_stack_bwdist.h" #include "tz_stack_threshold.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { char neuron_name[100]; if (argc == 1) { strcpy(neuron_name, "fly_neuron"); } else { strcpy(neuron_name, argv[1]); } char file_path[100]; sprintf(file_path, "../data/%s.tif", neuron_name); Stack *signal = Read_Stack(file_path); Translate_Stack(signal, GREY, 1); Stack *stack = Translate_Stack(signal, COLOR, 0); sprintf(file_path, "../data/%s/soma.tif", neuron_name); Stack *label = Read_Stack(file_path); Stack *label2 = Copy_Stack(label); Stack_Threshold(label, 2); Stack_Binarize(label); Stack_Threshold(label2, 1); Stack_Binarize(label2); Stack_Xor(label, label2, label2); Print_Stack_Info(signal); Stack_Label_Color(stack, label, 0.0, 1.0, signal); Stack_Label_Color(stack, label2, 4.0, 1.0, signal); int i; for (i = 0; i < 3; i++) { Stack_Channel_Extraction(stack, i, signal); sprintf(file_path, "../data/%s/label_%d.tif", neuron_name, i); Write_Stack(file_path, signal); } Kill_Stack(signal); Kill_Stack(stack); Kill_Stack(label); Kill_Stack(label2); sprintf(file_path, "../data/%s/traced.tif", neuron_name); Stack *canvas = Read_Stack(file_path); sprintf(file_path, "../data/%s/soma.tif", neuron_name); Stack *soma = Read_Stack(file_path); Stack_Blend_Mc_L(canvas, soma, 2, 4.0); Stack_Blend_Mc_L(canvas, soma, 3, 1.0); sprintf(file_path, "../data/%s/label_color.tif", neuron_name); Write_Stack(file_path, canvas); return 0; }
{ "alphanum_fraction": 0.7060794639, "avg_line_length": 25.7901234568, "ext": "c", "hexsha": "65e6b6a1a1ac467b717b63d8422e6b60dc195660", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_label2.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_label2.c", "max_line_length": 66, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_label2.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 619, "size": 2089 }
/* blas/gsl_blas.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * Author: G. Jungman */ #ifndef __GSL_BLAS_H__ #define __GSL_BLAS_H__ #include <gsl/vector/gsl_vector.h> #include <gsl/matrix/gsl_matrix.h> #include <gsl/blas/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 /** MODIFIED BY STELIAN: - only keep a subset of the methods that I think are important - link to an external blas library */ /* ======================================================================== * Level 1 * ======================================================================== */ /** * forms the dot product of two vectors. */ GSL_FUNC int gsl_blas_ddot (const gsl_vector * X, const gsl_vector * Y, double * result); /** * DNRM2 returns the euclidean norm of a vector via the function * name, so that * * DNRM2 := sqrt( x'*x ) */ GSL_FUNC double gsl_blas_dnrm2 (const gsl_vector * X); /** * interchanges two vectors. */ GSL_FUNC int gsl_blas_dswap (gsl_vector * X, gsl_vector * Y); /** * copies a vector, x, to a vector, y. */ GSL_FUNC int gsl_blas_dcopy (const gsl_vector * X, gsl_vector * Y); /* =========================================================================== * Level 2 * =========================================================================== */ /** * DGEMV performs one of the matrix-vector operations * * y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y, * * where alpha and beta are scalars, x and y are vectors and A is an * m by n matrix. */ GSL_FUNC int gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA, double alpha, const gsl_matrix * A, const gsl_vector * X, double beta, gsl_vector * Y); /* * =========================================================================== * Prototypes for level 3 BLAS * =========================================================================== */ /** * DGEMM performs one of the matrix-matrix operations * * C := alpha*op( A )*op( B ) + beta*C, * * where op( X ) is one of * * op( X ) = X or op( X ) = X', * * alpha and beta are scalars, and A, B and C are matrices, with op( A ) * an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. */ GSL_FUNC int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, double alpha, const gsl_matrix * A, const gsl_matrix * B, double beta, gsl_matrix * C); __END_DECLS #endif /* __GSL_BLAS_H__ */
{ "alphanum_fraction": 0.5915238954, "avg_line_length": 28.6810344828, "ext": "h", "hexsha": "d8b6a2084f847aa70c0dd82b478bc43144c25245", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/gsl_blas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/gsl_blas.h", "max_line_length": 169, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/gsl_blas.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 864, "size": 3327 }
/* * Copyright 2020 Makani Technologies LLC * * 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 SIM_MATH_ODE_SOLVER_H_ #define SIM_MATH_ODE_SOLVER_H_ #include <stdint.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> #include <vector> namespace sim { // Enumeration for return codes. enum class OdeSolverStatus { kSuccess, kError, kOutOfPhysics }; // Interface representing a system of ordinary differential equations. class OdeSystem { public: virtual ~OdeSystem() {} // Get the number of states for the ODE. virtual int32_t num_states() const = 0; // Calculate the state derivative for a given time and state. virtual void CalcDerivatives(double t, const std::vector<double> &x, std::vector<double> *dx) const = 0; }; // Interface for ODE solvers. class OdeSolver { public: virtual ~OdeSolver() {} // Integrate the ODE with initial condition x0 at time t0 until time tf. // // Args: // t0: Initial time. // tf: Final time (>= t0). // x0: Initial state. // t_int: Null pointer or output time at which the integrator terminated. // x: Terminal state. It should be safe to reuse x0 as x. // // Returns: // kSuccess on success (indicating *t_int = tf) and kError otherwise. virtual OdeSolverStatus Integrate(double t0, double tf, const std::vector<double> &x0, double *t_int, std::vector<double> *x) = 0; }; } // namespace sim #endif // SIM_MATH_ODE_SOLVER_H_
{ "alphanum_fraction": 0.6773722628, "avg_line_length": 29.7826086957, "ext": "h", "hexsha": "dde812e030b103635de3508d0c75c29b5f22c1ac", "lang": "C", "max_forks_count": 107, "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "leozz37/makani", "max_forks_repo_path": "sim/math/ode_solver.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "leozz37/makani", "max_issues_repo_path": "sim/math/ode_solver.h", "max_line_length": 79, "max_stars_count": 1178, "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "leozz37/makani", "max_stars_repo_path": "sim/math/ode_solver.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "num_tokens": 509, "size": 2055 }
#ifndef __CCL_CONSTANTS_H_INCLUDED__ #define __CCL_CONSTANTS_H_INCLUDED__ #include <gsl/gsl_const_mksa.h> //Spline types #define A_SPLINE_TYPE gsl_interp_akima #define K_SPLINE_TYPE gsl_interp_akima #define L_SPLINE_TYPE gsl_interp_akima #define M_SPLINE_TYPE gsl_interp_akima #define D_SPLINE_TYPE gsl_interp_akima #define PNL_SPLINE_TYPE gsl_interp2d_bicubic #define PLIN_SPLINE_TYPE gsl_interp2d_bicubic #define CORR_SPLINE_TYPE gsl_interp_akima /** @file */ #ifndef M_PI /** * PI (in case it's not defined from math.h) */ #define M_PI 3.14159265358979323846 #endif /** * k pivot. These are in units of Mpc (no factor of h) */ #define K_PIVOT 0.05 /** * Lightspeed / H0 in units of Mpc/h (from CODATA 2014) */ #define CLIGHT_HMPC 2997.92458 //H0^-1 in Mpc/h /** * Newton's gravitational constant in units of m^3/Kg/s^2 */ //#define GNEWT 6.6738e-11 /(from PDG 2013) in m^3/Kg/s^2 //#define GNEWT 6.67428e-11 // CLASS VALUE #define GNEWT 6.67408e-11 // from CODATA 2014 /** * Solar mass in units of kg (from GSL) */ //#define SOLAR_MASS GSL_CONST_MKSA_SOLAR_MASS //#define SOLAR_MASS 1.9885e30 //(from PDG 2015) in Kg #define SOLAR_MASS 1.9884754153381438e+30 //from IAU 2015 /** * Mpc to meters (from PDG 2013) */ #define MPC_TO_METER 3.08567758149e22 /** * pc to meters (from PDG 2013) */ #define PC_TO_METER 3.08567758149e16 /** * Rho critical in units of M_sun/h / (Mpc/h)^3 */ #define RHO_CRITICAL ((3*100*100)/(8*M_PI*GNEWT)) * (1000*1000*MPC_TO_METER/SOLAR_MASS) /** * Boltzmann constant in units of J/K */ //#define KBOLTZ GSL_CONST_MKSA_BOLTZMANN #define KBOLTZ 1.38064852e-23 //from CODATA 2014 /** * Stefan-Boltzmann constant in units of kg/s^3 / K^4 */ //#define STBOLTZ GSL_CONST_MKSA_STEFAN_BOLTZMANN_CONSTANT #define STBOLTZ 5.670367e-8 //from CODATA 2014 /** * Planck's constant in units kg m^2 / s */ //#define HPLANCK GSL_CONST_MKSA_PLANCKS_CONSTANT_H #define HPLANCK 6.626070040e-34 //from CODATA 2014 /** * The speed of light in m/s */ //#define CLIGHT GSL_CONST_MKSA_SPEED_OF_LIGHT #define CLIGHT 299792458.0 //from CODATA 2014 /** * Electron volt to Joules convestion */ //#define EV_IN_J GSL_CONST_MKSA_ELECTRON_VOLT #define EV_IN_J 1.6021766208e-19 //from CODATA 2014 /** * Temperature of the CMB in K */ #define TCMB 2.725 //#define TCMB 2.7255 // CLASS value /** * T_ncdm, as taken from CLASS, explanatory.ini */ #define TNCDM 0.71611 /** * neutrino mass splitting differences * See Lesgourgues and Pastor, 2012 for these values. * Adv. High Energy Phys. 2012 (2012) 608515, * arXiv:1212.6154, page 13 */ #define DELTAM12_sq 7.62E-5 #define DELTAM13_sq_pos 2.55E-3 #define DELTAM13_sq_neg -2.43E-3 //Precision parameters /** * Default relative precision if not otherwise specified */ #define GSL_EPSREL 1E-4 /** * Default number of iterations for integration and root-finding if not otherwise * specified */ #define GSL_N_ITERATION 1000 /** * Default number of Gauss-Kronrod points in QAG integration if not otherwise * specified */ #define GSL_INTEGRATION_GAUSS_KRONROD_POINTS GSL_INTEG_GAUSS41 /** * Absolute precision in neutrino root finding */ #define GSL_EPSABS_NU 1E-7 /** * Relative precision in neutrino root finding */ #define GSL_EPSREL_NU 1E-7 /** * Number of iterations for neutrino root finding */ #define GSL_N_ITERATION_NU 1000 /** * Relative precision in sigma_R calculations */ #define GSL_EPSREL_SIGMAR 1E-5 /** * Relative precision in distance calculations */ #define GSL_EPSREL_DIST 1E-6 /** * Relative precision in growth calculations */ #define GSL_EPSREL_GROWTH 1E-6 /** * Relative precision in dNdz calculations */ #define GSL_EPSREL_DNDZ 1E-6 /** * Absolute precision in growth calculations */ #define EPS_SCALEFAC_GROWTH 1E-6 #endif
{ "alphanum_fraction": 0.7363013699, "avg_line_length": 21.816091954, "ext": "h", "hexsha": "33e7889f23c8f99085580d091ee459a952093296", "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": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_path": "include/ccl_constants.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "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": "vrastil/CCL", "max_issues_repo_path": "include/ccl_constants.h", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_path": "include/ccl_constants.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1229, "size": 3796 }
/* movstat/madacc.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. */ /* * This module contains routines for computing the median absolute deviation (MAD) * of a moving fixed-sized window. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_statistics.h> typedef double madacc_type_t; typedef madacc_type_t ringbuf_type_t; #include "ringbuf.c" typedef struct { size_t n; /* window size */ const gsl_movstat_accum *medacc; /* median accumulator */ void *median_state; /* median accumulator workspace */ ringbuf *rbuf; /* ring buffer storing current window, size n */ madacc_type_t *work; /* workspace, size n */ } madacc_state_t; static size_t madacc_size(const size_t n); static int madacc_init(const size_t n, void * vstate); static int madacc_insert(const madacc_type_t x, void * vstate); static int madacc_delete(void * vstate); static int madacc_medmad(void * params, madacc_type_t * result, const void * vstate); static size_t madacc_size(const size_t n) { size_t size = 0; const gsl_movstat_accum * acc = gsl_movstat_accum_median; size += sizeof(madacc_state_t); size += (acc->size)(n); /* median accumulator */ size += ringbuf_size(n); /* rbuf */ size += n * sizeof(madacc_type_t); /* work */ return size; } static int madacc_init(const size_t n, void * vstate) { madacc_state_t * state = (madacc_state_t *) vstate; state->n = n; state->medacc = gsl_movstat_accum_median; state->median_state = (void *) ((unsigned char *) vstate + sizeof(madacc_state_t)); state->rbuf = (ringbuf *) ((unsigned char *) state->median_state + (state->medacc->size)(n)); state->work = (madacc_type_t *) ((unsigned char *) state->rbuf + ringbuf_size(n)); (state->medacc->init)(n, state->median_state); ringbuf_init(n, state->rbuf); return GSL_SUCCESS; } static int madacc_insert(const madacc_type_t x, void * vstate) { madacc_state_t * state = (madacc_state_t *) vstate; /* insert element into median accumulator */ (state->medacc->insert)(x, state->median_state); /* insert element into ring buffer */ ringbuf_insert(x, state->rbuf); return GSL_SUCCESS; } static int madacc_delete(void * vstate) { madacc_state_t * state = (madacc_state_t *) vstate; if (!ringbuf_is_empty(state->rbuf)) ringbuf_pop_back(state->rbuf); return GSL_SUCCESS; } static int madacc_medmad(void * params, madacc_type_t * result, const void * vstate) { const madacc_state_t * state = (const madacc_state_t *) vstate; if (ringbuf_is_empty(state->rbuf)) { GSL_ERROR("no samples yet added to workspace", GSL_EINVAL); } else { int status; const double scale = *(double *) params; const int n = ringbuf_n(state->rbuf); int i; double median, mad; /* compute median of current window */ status = (state->medacc->get)(NULL, &median, state->median_state); if (status) return status; /* compute current window absolute deviations from median */ for (i = 0; i < n; ++i) { double xi = state->rbuf->array[(state->rbuf->head + i) % state->rbuf->size]; state->work[i] = fabs(xi - median); } /* compute MAD of current window */ mad = gsl_stats_median(state->work, 1, n); result[0] = median; result[1] = scale * mad; return GSL_SUCCESS; } } static const gsl_movstat_accum mad_accum_type = { madacc_size, madacc_init, madacc_insert, NULL, /*XXX*/ madacc_medmad }; const gsl_movstat_accum *gsl_movstat_accum_mad = &mad_accum_type;
{ "alphanum_fraction": 0.6753480018, "avg_line_length": 28.0125786164, "ext": "c", "hexsha": "ad0595c411bd0608446ba537b0895d3bfff9a3bc", "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/movstat/madacc.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/movstat/madacc.c", "max_line_length": 95, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/movstat/madacc.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": 1173, "size": 4454 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> #include "ccl.h" /* * Spline the linear power spectrum for mu-Sigma MG cosmologies. * @param cosmo Cosmological parameters ^ @param psp The linear power spectrum to spline. * @param status, integer indicating the status */ void ccl_cosmology_spline_linpower_musigma(ccl_cosmology* cosmo, ccl_f2d_t *psp, int rescaled_mg_flag, int* status) { double kmin, kmax, ndecades, amin, amax, ic, sigma8, log_sigma8; int nk, na, s; double *lk = NULL, *aa = NULL, *lpk_ln = NULL, *lpk_nl = NULL; double norm_pk; double *mnu_list = NULL; ccl_parameters params_GR; params_GR.m_nu = NULL; params_GR.z_mgrowth = NULL; params_GR.df_mgrowth = NULL; ccl_cosmology * cosmo_GR = NULL; double *D_mu = NULL; double *D_GR = NULL; if (*status == 0) { //calculations done - now allocate CCL splines kmin = 2*exp(psp->lkmin); kmax = cosmo->spline_params.K_MAX_SPLINE; //Compute nk from number of decades and N_K = # k per decade ndecades = log10(kmax) - log10(kmin); nk = (int)ceil(ndecades*cosmo->spline_params.N_K); amin = cosmo->spline_params.A_SPLINE_MINLOG_PK; amax = cosmo->spline_params.A_SPLINE_MAX; na = cosmo->spline_params.A_SPLINE_NA_PK+cosmo->spline_params.A_SPLINE_NLOG_PK-1; // The lk array is initially k, but will later // be overwritten with log(k) lk = ccl_log_spacing(kmin, kmax, nk); if (lk == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\n"); } } if (*status == 0) { aa = ccl_linlog_spacing( amin, cosmo->spline_params.A_SPLINE_MIN_PK, amax, cosmo->spline_params.A_SPLINE_NLOG_PK, cosmo->spline_params.A_SPLINE_NA_PK); if (aa == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\n"); } } if (*status == 0) { lpk_ln = malloc(nk * na * sizeof(double)); if (lpk_ln == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\n"); } } if (*status == 0) { lpk_nl = malloc(nk * na * sizeof(double)); if(lpk_nl == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\n"); } } if (*status == 0) { // After this loop lk will contain log(k), // lpk_ln will contain log(P_lin), all in Mpc, not Mpc/h units! double psout_l; s = 0; // If scale-independent mu / Sigma modified gravity is in use // and mu ! = 0 : get the unnormalized growth factor in MG and for // corresponding GR case, to rescale CLASS power spectrum if (fabs(cosmo->params.mu_0) > 1e-14) { // Set up another cosmology which is exactly the same as the // current one but with mu_0 and Sigma_0=0, for scaling P(k) // Get a list of the three neutrino masses already calculated mnu_list = malloc(3*sizeof(double)); if (mnu_list == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\n"); } if (*status == 0) { for (int i=0; i< cosmo->params.N_nu_mass; i=i+1) { mnu_list[i] = cosmo->params.m_nu[i]; } if (cosmo->params.N_nu_mass < 3) { for (int j=cosmo->params.N_nu_mass; j<3; j=j+1) { mnu_list[j] = 0.; } } if (isfinite(cosmo->params.A_s)) { norm_pk = cosmo->params.A_s; } else if (isfinite(cosmo->params.sigma8)) { norm_pk = cosmo->params.sigma8; } else { *status = CCL_ERROR_PARAMETERS; strcpy( cosmo->status_message, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): neither A_s nor sigma8 defined.\n"); } } if (*status == 0) { params_GR = ccl_parameters_create( cosmo->params.Omega_c, cosmo->params.Omega_b, cosmo->params.Omega_k, cosmo->params.Neff, mnu_list, cosmo->params.N_nu_mass, cosmo->params.w0, cosmo->params.wa, cosmo->params.h, norm_pk, cosmo->params.n_s, cosmo->params.bcm_log10Mc, cosmo->params.bcm_etab, cosmo->params.bcm_ks, 0., 0., cosmo->params.nz_mgrowth, cosmo->params.z_mgrowth, cosmo->params.df_mgrowth, status); if (*status) { *status = CCL_ERROR_PARAMETERS; strcpy( cosmo->status_message, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): could not make MG params.\n"); } } if (*status == 0) { cosmo_GR = ccl_cosmology_create(params_GR, cosmo->config); D_mu = malloc(na * sizeof(double)); D_GR = malloc(na * sizeof(double)); if (cosmo_GR == NULL || D_mu == NULL || D_GR == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message( cosmo, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\n"); } } if (*status == 0) { ccl_cosmology_compute_growth(cosmo_GR, status); if (*status) { *status = CCL_ERROR_PARAMETERS; strcpy( cosmo->status_message, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): could not init GR growth.\n"); } } if (*status == 0) { for (int i=0; i<na; i++) { D_mu[i] = ccl_growth_factor_unnorm(cosmo, aa[i], status); D_GR[i] = ccl_growth_factor_unnorm(cosmo_GR, aa[i], status); } if (*status) { *status = CCL_ERROR_PARAMETERS; strcpy( cosmo->status_message, "ccl_power.c: ccl_cosmology_spline_linpower_musigma(): could not make MG and GR growth.\n"); } } if (*status == 0) { for (int i=0; i<nk; i++) { lk[i] = log(lk[i]); for (int j = 0; j < na; j++) { //The 2D interpolation routines access the function values pk_{k_ia_j} with the following ordering: //pk_ij = pk[j*N_k + i] //with i = 0,...,N_k-1 and j = 0,...,N_a-1. psout_l = ccl_f2d_t_eval(psp, lk[i], aa[j], cosmo, status); if (rescaled_mg_flag == 0) { lpk_ln[j*nk+i] = log(psout_l) ; } else { lpk_ln[j*nk+i] = log(psout_l) + 2 * log(D_mu[j]) - 2 * log(D_GR[j]); } } } } } else { // This is the normal GR case. for (int i=0; i<nk; i++) { lk[i] = log(lk[i]); for (int j = 0; j<na; j++) { //The 2D interpolation routines access the function values pk_{k_ia_j} with the following ordering: //pk_ij = pk[j*N_k + i] //with i = 0,...,N_k-1 and j = 0,...,N_a-1. psout_l = ccl_f2d_t_eval(psp, lk[i], aa[j], cosmo, status); lpk_ln[j*nk+i] = log(psout_l); } } } } if (*status == 0) { cosmo->data.p_lin = ccl_f2d_t_new( na, aa, nk, lk, lpk_ln, NULL, NULL, 0, 1, 2, ccl_f2d_cclgrowth, 1, NULL, 0, 2, ccl_f2d_3,status); } // if desried, renomalize to a given sigma8 if (isfinite(cosmo->params.sigma8) && (!isfinite(cosmo->params.A_s))) { if (*status == 0) { cosmo->computed_linear_power = true; sigma8 = ccl_sigma8(cosmo, status); cosmo->computed_linear_power = false; } if (*status == 0) { // Calculate normalization factor using computed value of sigma8, then // recompute P(k, a) using this normalization log_sigma8 = 2*(log(cosmo->params.sigma8) - log(sigma8)); for(int j = 0; j<na*nk; j++) lpk_ln[j] += log_sigma8; } if (*status == 0) { // Free the previous P(k,a) spline, and allocate a new one to store the // properly-normalized P(k,a) ccl_f2d_t_free(cosmo->data.p_lin); cosmo->data.p_lin = ccl_f2d_t_new( na, aa, nk, lk, lpk_ln, NULL, NULL, 0, 1, 2, ccl_f2d_cclgrowth, 1, NULL, 0, 2, ccl_f2d_3,status); } } free(D_mu); free(D_GR); free(mnu_list); ccl_parameters_free(&params_GR); ccl_cosmology_free(cosmo_GR); free(lk); free(aa); free(lpk_nl); free(lpk_ln); }
{ "alphanum_fraction": 0.5938468603, "avg_line_length": 32.3828996283, "ext": "c", "hexsha": "344f85a89e03597af0bda10978d8b8220b726a9d", "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": "46692a38afd249946ac004cec391f47fd7c34f63", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "timothydmorton/CCL", "max_forks_repo_path": "src/ccl_musigma.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "timothydmorton/CCL", "max_issues_repo_path": "src/ccl_musigma.c", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "timothydmorton/CCL", "max_stars_repo_path": "src/ccl_musigma.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2672, "size": 8711 }
#include <string.h> #include <mpi.h> #include <pfft.h> #include <gsl/gsl_rng.h> #include <fastpm/libfastpm.h> #include <fastpm/logging.h> #include "pmpfft.h" #define HAS(a, b) ((a & b) != 0) static void pack_any(FastPMStore * p, ptrdiff_t index, int ci, void * packed) { size_t elsize = p->_column_info[ci].elsize; memcpy(packed, p->columns[ci] + index * elsize, elsize); } static void unpack_any(FastPMStore * p, ptrdiff_t index, int ci, void * packed) { size_t elsize = p->_column_info[ci].elsize; memcpy(p->columns[ci] + index * elsize, packed, elsize); } void FastPMReduceOverwriteAny(FastPMStore * p, ptrdiff_t index, int ci, void * packed, void * userdata) { size_t elsize = p->_column_info[ci].elsize; memcpy(p->columns[ci] + index * elsize, packed, elsize); } void FastPMReduceAddFloat(FastPMStore * src, ptrdiff_t isrc, FastPMStore * dest, ptrdiff_t idest, int ci, void * userdata) { size_t nmemb = dest->_column_info[ci].nmemb ; size_t elsize = dest->_column_info[ci].elsize; float * pdest = (float*) (dest->columns[ci] + idest * elsize); float * psrc = (float*) (src ->columns[ci] + isrc * elsize); int d; for(d = 0; d < nmemb; d ++) { pdest[d] += psrc[d]; } } static double to_double_f4 (FastPMStore * p, ptrdiff_t index, int ci, int memb) { size_t nmemb = p->_column_info[ci].nmemb ; if(memb > nmemb) { fastpm_raise(-1, "memb %d greater than nmemb %d", memb, nmemb); } size_t elsize = p->_column_info[ci].elsize; float * ptr = (float*) (p->columns[ci] + index * elsize); return ptr[memb]; } static double to_double_f8 (FastPMStore * p, ptrdiff_t index, int ci, int memb) { size_t nmemb = p->_column_info[ci].nmemb ; if(memb > nmemb) { fastpm_raise(-1, "memb %d greater than nmemb %d", memb, nmemb); } size_t elsize = p->_column_info[ci].elsize; double * ptr = (double*) (p->columns[ci] + index * elsize); return ptr[memb]; } static void from_double_f4 (FastPMStore * p, ptrdiff_t index, int ci, int memb, const double value) { size_t nmemb = p->_column_info[ci].nmemb ; if(memb > nmemb) { fastpm_raise(-1, "memb %d greater than nmemb %d", memb, nmemb); } size_t elsize = p->_column_info[ci].elsize; float * ptr = (float*) (p->columns[ci] + index * elsize); ptr[memb] = value; } const char * fastpm_species_get_name(enum FastPMSpecies species) { switch(species) { case FASTPM_SPECIES_BARYON: return "0"; case FASTPM_SPECIES_CDM: return "1"; case FASTPM_SPECIES_NCDM: return "2"; } return "UNKNOWN"; } void fastpm_store_get_position(FastPMStore * p, ptrdiff_t index, double pos[3]) { pos[0] = p->x[index][0]; pos[1] = p->x[index][1]; pos[2] = p->x[index][2]; } void fastpm_store_get_lagrangian_position(FastPMStore * p, ptrdiff_t index, double pos[3]) { pos[0] = p->q[index][0]; pos[1] = p->q[index][1]; pos[2] = p->q[index][2]; } double fastpm_store_get_mass(FastPMStore * p, ptrdiff_t index) { /* total mass is the sum of the base and the extra */ if(p->mass) { return p->meta.M0 + p->mass[index]; } else { return p->meta.M0; } } static ptrdiff_t _alignsize(ptrdiff_t size) { /* align sizes */ return ((size + 1024) / 1024) * 1024; } void fastpm_store_init_details(FastPMStore * p, const char * name, size_t np_upper, FastPMColumnTags attributes, enum FastPMMemoryLocation loc, const char * file, const int line) { p->mem = _libfastpm_get_gmem(); /* only set the name if name is not NULL; this is to allow setting the name before calling init. * */ if(name) { strcpy(p->name, name); } p->attributes = attributes; p->np = 0; p->np_upper = np_upper; /* clear the column pointers. */ memset(p->columns, 0, sizeof(p->columns)); memset(p->_column_info, 0, sizeof(p->_column_info)); /* clear the meta */ memset(&p->meta, 0, sizeof(p->meta)); int it; p->_base = NULL; /* first loop initialize the _column_info struct for corresponding items in the pointer union; * second loop initialize the pointers */ #define DEFINE_COLUMN(column, attr_, dtype_, nmemb_) \ { \ int ci = FASTPM_STORE_COLUMN_INDEX(column); \ if(attr_ != (1 << ci)) { fastpm_raise(-1, "attr and column are out of order for %s\n", # column ); } \ strcpy(p->_column_info[ci].dtype, dtype_); \ strcpy(p->_column_info[ci].name, # column); \ p->_column_info[ci].elsize = sizeof(p->column[0]); \ p->_column_info[ci].nmemb = nmemb_; \ p->_column_info[ci].membsize = sizeof(p->column[0]) / nmemb_; \ p->_column_info[ci].attribute = attr_; \ p->_column_info[ci].pack = pack_any; \ p->_column_info[ci].unpack = unpack_any; \ p->_column_info[ci].from_double = NULL; \ p->_column_info[ci].to_double = NULL; \ } #define COLUMN_INFO(column) (p->_column_info[FASTPM_STORE_COLUMN_INDEX(column)]) DEFINE_COLUMN(x, COLUMN_POS, "f8", 3); DEFINE_COLUMN(q, COLUMN_Q, "f4", 3); DEFINE_COLUMN(v, COLUMN_VEL, "f4", 3); DEFINE_COLUMN(acc, COLUMN_ACC, "f4", 3); DEFINE_COLUMN(dx1, COLUMN_DX1, "f4", 3); DEFINE_COLUMN(dx2, COLUMN_DX2, "f4", 3); DEFINE_COLUMN(dv1, COLUMN_DV1, "f4", 3); DEFINE_COLUMN(aemit, COLUMN_AEMIT, "f4", 1); DEFINE_COLUMN(rho, COLUMN_DENSITY, "f4", 1); DEFINE_COLUMN(potential, COLUMN_POTENTIAL, "f4", 1); DEFINE_COLUMN(tidal, COLUMN_TIDAL, "f4", 6); DEFINE_COLUMN(id, COLUMN_ID, "i8", 1); DEFINE_COLUMN(pgdc, COLUMN_PGDC, "f4", 3); DEFINE_COLUMN(mask, COLUMN_MASK, "i1", 1); DEFINE_COLUMN(minid, COLUMN_MINID, "i8", 1); DEFINE_COLUMN(task, COLUMN_TASK, "i4", 1); DEFINE_COLUMN(length, COLUMN_LENGTH, "i4", 1); DEFINE_COLUMN(rdisp, COLUMN_RDISP, "f4", 6); DEFINE_COLUMN(vdisp, COLUMN_VDISP, "f4", 6); DEFINE_COLUMN(rvdisp, COLUMN_RVDISP, "f4", 9); DEFINE_COLUMN(mass, COLUMN_MASS, "f4", 1); COLUMN_INFO(x).to_double = to_double_f8; COLUMN_INFO(v).to_double = to_double_f4; COLUMN_INFO(rho).to_double = to_double_f4; COLUMN_INFO(dx1).to_double = to_double_f4; COLUMN_INFO(dx2).to_double = to_double_f4; COLUMN_INFO(dv1).to_double = to_double_f4; COLUMN_INFO(acc).to_double = to_double_f4; COLUMN_INFO(mass).to_double = to_double_f4; COLUMN_INFO(rho).from_double = from_double_f4; COLUMN_INFO(acc).from_double = from_double_f4; COLUMN_INFO(pgdc).from_double = from_double_f4; COLUMN_INFO(dx1).from_double = from_double_f4; COLUMN_INFO(dx2).from_double = from_double_f4; COLUMN_INFO(dv1).from_double = from_double_f4; COLUMN_INFO(potential).from_double = from_double_f4; COLUMN_INFO(tidal).from_double = from_double_f4; ptrdiff_t size = 0; ptrdiff_t offset = 0; for(it = 0; it < 2; it ++) { int ci; for(ci = 0; ci < 32; ci ++) { if(it == 0) { size += ((attributes & p->_column_info[ci].attribute) != 0) * (_alignsize(p->_column_info[ci].elsize * np_upper)); \ } else { \ if(attributes & p->_column_info[ci].attribute) { \ p->columns[ci] = (void*) (((char*) p->_base) + offset); \ offset += _alignsize(p->_column_info[ci].elsize * np_upper); \ } else { \ p->columns[ci] = NULL; \ } \ } } if(it == 0) { p->_base = fastpm_memory_alloc_details(p->mem, "FastPMStore", size, loc, file, line); /* zero out all memory */ memset(p->_base, 0, size); } }; } void fastpm_store_set_name(FastPMStore * p, const char * name) { strcpy(p->name, name); } size_t fastpm_store_init_evenly_details(FastPMStore * p, const char * name, size_t np_total, FastPMColumnTags attributes, double alloc_factor, MPI_Comm comm, const char * file, const int line) { /* allocate for np_total cross all */ /* name means name of species*/ int NTask; MPI_Comm_size(comm, &NTask); size_t np_upper = (size_t)(1.0 * np_total / NTask * alloc_factor); MPI_Bcast(&np_upper, 1, MPI_LONG, 0, comm); fastpm_store_init_details(p, name, np_upper, attributes, FASTPM_MEMORY_HEAP, file, line); return 0; } size_t fastpm_store_get_np_total(FastPMStore * p, MPI_Comm comm) { long long np = p->np; MPI_Allreduce(MPI_IN_PLACE, &np, 1, MPI_LONG_LONG, MPI_SUM, comm); return np; } size_t fastpm_store_get_mask_sum(FastPMStore * p, MPI_Comm comm) { long long np = 0; ptrdiff_t i; for(i = 0; i < p->np; i ++) { np += p->mask[i] != 0; } MPI_Allreduce(MPI_IN_PLACE, &np, 1, MPI_LONG_LONG, MPI_SUM, comm); return np; } void fastpm_packing_plan_init(FastPMPackingPlan * plan, FastPMStore * p, FastPMColumnTags attributes) { int ci; int i = 0; plan->elsize = 0; plan->attributes = attributes; for (ci = 0; ci < 32; ci ++) { if (!(p->_column_info[ci].attribute & attributes)) continue; plan->_ci[i] = ci; plan->_offsets[ci] = plan->elsize; ptrdiff_t elsize = p->_column_info[ci].elsize; plan->elsize += elsize; plan->_column_info[ci] = p->_column_info[ci]; i++; } /* Pad the elsize to 8 bytes. This ensures anything goes to the MPI wire is 8 byte aligned, * and minimizes the chances of hitting an implementation bug. */ if (plan->elsize % 8 != 0) { plan->elsize += (8 - plan->elsize % 8); } plan->Ncolumns = i; } void fastpm_packing_plan_pack(FastPMPackingPlan * plan, FastPMStore * p, ptrdiff_t i, void * packed) { int t; memset(packed, 0, plan->elsize); for (t = 0; t < plan->Ncolumns; t ++) { int ci = plan->_ci[t]; ptrdiff_t offset = plan->_offsets[ci]; plan->_column_info[ci].pack(p, i, ci, ((char*) packed) + offset); } } void fastpm_packing_plan_unpack(FastPMPackingPlan * plan, FastPMStore * p, ptrdiff_t i, void * packed) { int t; for (t = 0; t < plan->Ncolumns; t ++) { int ci = plan->_ci[t]; fastpm_packing_plan_unpack_ci(plan, ci, p, i, packed); } } /* unpack a single column from the offset in packed data. */ void fastpm_packing_plan_unpack_ci(FastPMPackingPlan * plan, int ci, FastPMStore * p, ptrdiff_t i, void * packed) { ptrdiff_t offset = plan->_offsets[ci]; plan->_column_info[ci].unpack(p, i, ci, ((char*) packed) + offset); } int fastpm_store_find_column_id(FastPMStore * p, FastPMColumnTags attribute) { int ci; for (ci = 0; ci < 32; ci ++) { if (p->_column_info[ci].attribute == attribute) { return ci; } } fastpm_raise(-1, "Unknown column %x", attribute); return -1; } void fastpm_store_destroy(FastPMStore * p) { fastpm_memory_free(p->mem, p->_base); } static void permute(void * data, int np, size_t elsize, int * ind) { void * tmp = malloc(elsize * np); if(!tmp) { fastpm_raise(-1, "No memory for permuting\n"); } int i; for(i = 0; i < np; i ++) { memcpy(((char*) tmp) + i * elsize, ((char*) data) + ind[i] * elsize, elsize); } memcpy(data, tmp, np * elsize); free(tmp); } void fastpm_store_permute(FastPMStore * p, int * ind) { int c; for(c = 0; c < 32; c ++) { if(!p->columns[c]) continue; permute(p->columns[c], p->np, p->_column_info[c].elsize, ind); } } static FastPMStore * _fastpm_store_sort_store; static int (*_fastpm_store_sort_cmp_func)(const int i1, const int i2, FastPMStore * p); int _sort_by_id_cmpfunc(const void * p1, const void * p2) { const int * i1 = (const int*) p1; const int * i2 = (const int*) p2; return _fastpm_store_sort_cmp_func(*i1, *i2, _fastpm_store_sort_store); } int FastPMLocalSortByID(const int i1, const int i2, FastPMStore * p) { int v1 = (p->id[i1] < p->id[i2]); int v2 = (p->id[i1] > p->id[i2]); return v2 - v1; } /* sort a store locally with in the MPI rank. * * cmp_func is called with three arguments. * */ void fastpm_store_sort(FastPMStore * p, int (*cmp_func)(const int i1, const int i2, FastPMStore * p)) { int * arg = fastpm_memory_alloc(p->mem, "Temp", sizeof(int) * p->np, FASTPM_MEMORY_HEAP); int i; for(i = 0; i < p->np; i ++) { arg[i] = i; } /* FIXME: copy some version of qsort_r */ _fastpm_store_sort_store = p; _fastpm_store_sort_cmp_func = cmp_func; qsort(arg, p->np, sizeof(arg[0]), _sort_by_id_cmpfunc); fastpm_store_permute(p, arg); fastpm_memory_free(p->mem, arg); } void fastpm_store_wrap(FastPMStore * p, double BoxSize[3]) { int i; int d; for(i = 0; i < p->np; i ++) { for(d = 0; d < 3; d ++) { double n = abs(p->x[i][d] / BoxSize[d]); double x1 = remainder(p->x[i][d], BoxSize[d]); while(x1 < 0) x1 += BoxSize[d]; while(x1 > BoxSize[d]) x1 -= BoxSize[d]; p->x[i][d] = x1; if(n > 10000) { double q[3]; if(fastpm_store_has_q(p)) { fastpm_store_get_q_from_id(p, p->id[i], q); } fastpm_raise(-1, "Particle at %g %g %g (q = %g %g %g) is too far from the bounds. Wrapping failed.\n", p->x[i][0], p->x[i][1], p->x[i][2], q[0], q[1], q[2] ); } } } } int FastPMTargetPM (FastPMStore * p, ptrdiff_t i, PM * pm) { double pos[3]; fastpm_store_get_position(p, i, pos); return pm_pos_to_rank(pm, pos); } int fastpm_store_decompose(FastPMStore * p, fastpm_store_target_func target_func, void * data, MPI_Comm comm) { if(fastpm_store_get_np_total(p, comm) == 0) return 0 ; VALGRIND_CHECK_MEM_IS_DEFINED(p->x, sizeof(p->x[0]) * p->np); FastPMPackingPlan plan[1]; fastpm_packing_plan_init(plan, p, p->attributes); size_t elsize = plan->elsize; size_t Nsend_limit = 1000 * 1024 * 1024 / elsize; // this large number effectively prevents throttling int NTask, ThisTask; MPI_Comm_rank(comm, &ThisTask); MPI_Comm_size(comm, &NTask); if(p->np > p->np_upper) { fastpm_raise(-1, "Particle buffer overrun detected np = %td > np_upper %td.\n", p->np, p->np_upper); } /* do a bincount; offset by -1 because -1 is for self */ int * count = calloc(NTask + 1, sizeof(int)); int * offsets = calloc(NTask + 1, sizeof(int)); int * sendcount = count + 1; int * recvcount = malloc(sizeof(int) * (NTask)); int * recvoffset = malloc(sizeof(int) * (NTask)); int * sendoffset = malloc(sizeof(int) * (NTask)); int incomplete = 1; int iter = 0; /* terminate based on incomplete for throttling*/ while(1) { incomplete = 0; int * target = fastpm_memory_alloc(p->mem, "Target", sizeof(int) * p->np, FASTPM_MEMORY_HEAP); size_t Nsend_all = 0; ptrdiff_t i; for(i = 0; i < p->np; i ++) { target[i] = target_func(p, i, data); if(ThisTask == target[i]) { target[i] = -1; } else { Nsend_all++; /* Throttling: never send more than this many particles. */ if(Nsend_all >= Nsend_limit) { incomplete = 1; target[i] = -1; } else { } } } for(i = 0; i < NTask + 1; i ++) { count[i] = 0; offsets[i] = 0; } for(i = 0; i < NTask; i ++) { sendoffset[i] = 0; recvoffset[i] = 0; } for(i = 0; i < p->np; i ++) { sendcount[target[i]] ++; } cumsum(offsets, count, NTask + 1); int * arg = fastpm_memory_alloc(p->mem, "PermArg", sizeof(int) * p->np, FASTPM_MEMORY_HEAP); for(i = 0; i < p->np; i ++) { int offset = offsets[target[i] + 1] ++; arg[offset] = i; } fastpm_store_permute(p, arg); VALGRIND_CHECK_MEM_IS_DEFINED(p->x, sizeof(p->x[0]) * p->np); fastpm_memory_free(p->mem, arg); fastpm_memory_free(p->mem, target); MPI_Alltoall(sendcount, 1, MPI_INT, recvcount, 1, MPI_INT, comm); size_t Nsend = cumsum(sendoffset, sendcount, NTask); size_t Nrecv = cumsum(recvoffset, recvcount, NTask); volatile size_t neededsize = p->np + Nrecv - Nsend; if(neededsize > p->np_upper) { fastpm_ilog(INFO, "Need %td particles on rank %d; %td allocated\n", neededsize, ThisTask, p->np_upper); } if(MPIU_Any(comm, neededsize > p->np_upper)) { goto fail_oom; } p->np -= Nsend; void * send_buffer = fastpm_memory_alloc(p->mem, "SendBuf", elsize * Nsend, FASTPM_MEMORY_HEAP); void * recv_buffer = fastpm_memory_alloc(p->mem, "RecvBuf", elsize * Nrecv, FASTPM_MEMORY_HEAP); { double nmin, nmax, nmean, nstd; MPIU_stats(comm, elsize * Nsend, "<>-s", &nmin, &nmax, &nmean, &nstd); fastpm_info("Send buffer size : min=%g max=%g mean=%g, std=%g bytes", nmin, nmax, nmean, nstd); MPIU_stats(comm, elsize * Nrecv, "<>-s", &nmin, &nmax, &nmean, &nstd); fastpm_info("Recv buffer size : min=%g max=%g mean=%g, std=%g bytes", nmin, nmax, nmean, nstd); } int ipar = 0; int j; for(i = 0; i < NTask; i ++) { for(j = sendoffset[i]; j < sendoffset[i] + sendcount[i]; j ++, ipar++) { fastpm_packing_plan_pack(plan, p, j + p->np, (char*) send_buffer + ipar * elsize); } } size_t Nsendsum; size_t Nsendallsum; MPI_Allreduce(&Nsend, &Nsendsum, 1, MPI_LONG, MPI_SUM, comm); MPI_Allreduce(&Nsend_all, &Nsendallsum, 1, MPI_LONG, MPI_SUM, comm); fastpm_info("Decomposition iter %d, exchange of %td particles; need %td", iter, Nsendsum, Nsendallsum); MPI_Datatype PTYPE; MPI_Type_contiguous(elsize, MPI_BYTE, &PTYPE); MPI_Type_commit(&PTYPE); MPI_Alltoallv_sparse( send_buffer, sendcount, sendoffset, PTYPE, recv_buffer, recvcount, recvoffset, PTYPE, comm); MPI_Type_free(&PTYPE); ipar = 0; for(i = 0; i < NTask; i ++) { for(j = recvoffset[i]; j < recvoffset[i] + recvcount[i]; j++, ipar ++) { fastpm_packing_plan_unpack(plan, p, j + p->np, (char*) recv_buffer + ipar * elsize); } } fastpm_memory_free(p->mem, recv_buffer); fastpm_memory_free(p->mem, send_buffer); p->np += Nrecv; iter++; if(MPIU_Any(comm, incomplete)) continue; else break; } free(recvcount); free(recvoffset); free(sendoffset); free(offsets); free(count); return 0; fail_oom: free(recvcount); free(recvoffset); free(sendoffset); free(offsets); free(count); return -1; } int fastpm_store_has_q(FastPMStore * p) { return p->meta._q_size != 0; } void fastpm_store_get_q_from_id(FastPMStore * p, uint64_t id, double q[3]) { ptrdiff_t pabs[3]; int d; id = id % p->meta._q_size; for(d = 0; d < 3; d++) { pabs[d] = id / p->meta._q_strides[d]; id -= pabs[d] * p->meta._q_strides[d]; } for(d = 0; d < 3; d++) { q[d] = pabs[d] * p->meta._q_scale[d]; q[d] += p->meta._q_shift[d]; } }//if all 0 drop void fastpm_store_get_iq_from_id(FastPMStore * p, uint64_t id, ptrdiff_t pabs[3]) { /* integer version of the initial position q i.e. the lattice coordinates of the cells. */ int d; for(d = 0; d < 3; d++) { pabs[d] = id / p->meta._q_strides[d]; id -= pabs[d] * p->meta._q_strides[d]; } } void fastpm_store_fill(FastPMStore * p, PM * pm, double * shift, ptrdiff_t * Nc) { /* fill p with a uniform grid, respecting domain given by pm. use a subsample ratio. * (every subsample grid points) */ if(Nc == NULL) { Nc = pm_nmesh(pm); } int d; p->np = 1; for(d = 0; d < 3; d++) { int start = pm->IRegion.start[d] * Nc[d] / pm->Nmesh[d]; int end = (pm->IRegion.start[d] + pm->IRegion.size[d]) * Nc[d] / pm->Nmesh[d]; p->np *= end - start; } if(p->np > p->np_upper) { fastpm_raise(-1, "Need %td particles; %td allocated\n", p->np, p->np_upper); } ptrdiff_t ptr = 0; for(d = 0; d < 3; d ++) { if(shift) p->meta._q_shift[d] = shift[d]; else p->meta._q_shift[d] = 0; p->meta._q_scale[d] = pm->BoxSize[d] / Nc[d]; } p->meta._q_size = Nc[0] * Nc[1] * Nc[2]; p->meta._q_strides[0] = Nc[1] * Nc[2]; p->meta._q_strides[1] = Nc[2]; p->meta._q_strides[2] = 1; PMXIter iter; for(pm_xiter_init(pm, &iter); !pm_xiter_stop(&iter); pm_xiter_next(&iter)){ ptrdiff_t pabs_start[3]; ptrdiff_t pabs_end[3]; ptrdiff_t ii, jj, kk; for(d = 0; d < 3; d ++) { pabs_start[d] = iter.iabs[d] * Nc[d] / pm->Nmesh[d]; pabs_end[d] = (iter.iabs[d] + 1) * Nc[d] / pm->Nmesh[d]; } for(ii = pabs_start[0]; ii < pabs_end[0]; ii ++) for(jj = pabs_start[1]; jj < pabs_end[1]; jj ++) for(kk = pabs_start[2]; kk < pabs_end[2]; kk ++) { ptrdiff_t pabs[3] = {ii, jj, kk}; uint64_t id = pabs[2] * p->meta._q_strides[2] + pabs[1] * p->meta._q_strides[1] + pabs[0] * p->meta._q_strides[0] ; if(p->id) p->id[ptr] = id; if(p->mask) p->mask[ptr] = 0; fastpm_store_get_q_from_id(p, id, &p->x[ptr][0]); if(p->q) { /* set q if it is allocated. */ for(d = 0; d < 3; d ++) { p->q[ptr][d] = p->x[ptr][d]; } } ptr ++; } } if(ptr != p->np) { fastpm_raise(-1, "This is an internal error, particle number mismatched with grid. %td != %td, allocsize=%td, shape=(%td %td %td)\n", ptr, p->np, pm->allocsize, pm->IRegion.size[0], pm->IRegion.size[1], pm->IRegion.size[2] ); } p->meta.a_x = p->meta.a_v = 0.; } void fastpm_store_summary(FastPMStore * p, FastPMColumnTags attribute, MPI_Comm comm, const char * fmt, ...) { va_list va; va_start(va, fmt); int ci = fastpm_store_find_column_id(p, attribute); size_t nmemb = p->_column_info[ci].nmemb; double rmin[nmemb], rmax[nmemb], rsum1[nmemb], rsum2[nmemb]; if (NULL == p->_column_info[ci].to_double) { fastpm_raise(-1, "Column %s didnot set to_double virtual function\n", p->_column_info[ci].name); } int d; for(d = 0; d < nmemb; d ++) { rmin[d] = 1e20; rmax[d] = -1e20; rsum1[d] = 0; rsum2[d] = 0; } ptrdiff_t i; #pragma omp parallel { double tmin[nmemb], tmax[nmemb], tsum1[nmemb], tsum2[nmemb]; int d; for(d = 0; d < nmemb; d ++) { tmin[d] = 1e20; tmax[d] = -1e20; tsum1[d] = 0; tsum2[d] = 0; } #pragma omp for for(i = 0; i < p->np; i ++) { int d; for(d =0; d < nmemb; d++) { double value = p->_column_info[ci].to_double(p, i, ci, d); tsum1[d] += value; tsum2[d] += value * value; tmin[d] = fmin(tmin[d], value); tmax[d] = fmax(tmax[d], value); } } #pragma omp critical { int d; for(d =0; d < nmemb; d++) { rsum1[d] += tsum1[d]; rsum2[d] += tsum2[d]; rmin[d] = fmin(rmin[d], tmin[d]); rmax[d] = fmax(rmax[d], tmax[d]); } } } uint64_t Ntot = p->np; MPI_Allreduce(MPI_IN_PLACE, rsum1, nmemb, MPI_DOUBLE, MPI_SUM, comm); MPI_Allreduce(MPI_IN_PLACE, rsum2, nmemb, MPI_DOUBLE, MPI_SUM, comm); MPI_Allreduce(MPI_IN_PLACE, rmin, nmemb, MPI_DOUBLE, MPI_MIN, comm); MPI_Allreduce(MPI_IN_PLACE, rmax, nmemb, MPI_DOUBLE, MPI_MAX, comm); MPI_Allreduce(MPI_IN_PLACE, &Ntot, 1, MPI_LONG, MPI_SUM, comm); for(i = 0; i < strlen(fmt); i ++) { void * r = va_arg(va, void *); double * dr = (double * ) r; for(d = 0; d < 3; d++) { switch(fmt[i]) { case '-': dr[d] = rsum1[d] / Ntot; break; case '<': dr[d] = rmin[d]; break; case '>': dr[d] = rmax[d]; break; case 's': dr[d] = sqrt(rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2)); break; case 'S': dr[d] = sqrt(1.0 * Ntot / (Ntot - 1.)) * sqrt(rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2)); break; case 'v': dr[d] = (rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2)); break; case 'V': dr[d] = (1.0 * Ntot / (Ntot - 1.)) * (rsum2[d] / Ntot - pow(rsum1[d] / Ntot, 2)); break; default: fastpm_raise(-1, "Unknown format str. Use '<->sSvV'\n"); } } } va_end(va); } void fastpm_store_steal(FastPMStore * p, FastPMStore * po, FastPMColumnTags attributes) { int c; for(c = 0; c < 32; c ++) { if (!(p->_column_info[c].attribute & attributes)) continue; po->columns[c] = p->columns[c]; } po->np = p->np; po->meta = p->meta; } static void _fastpm_store_copy(FastPMStore * p, ptrdiff_t start, FastPMStore * po, ptrdiff_t offset, size_t ncopy) { if(ncopy + start > p->np) { fastpm_raise(-1, "Copy out of bounds from source FastPMStore: asking for %td but has %td\n", ncopy + start, p->np); } if(ncopy + offset > po->np_upper) { fastpm_raise(-1, "Not enough storage in target FastPMStore: asking for %td but has %td\n", ncopy + offset, po->np_upper); } int c; for(c = 0; c < 32; c ++) { if(!po->columns[c]) continue; size_t elsize = po->_column_info[c].elsize; memcpy(po->columns[c] + offset * elsize, p->columns[c] + start * elsize, elsize * ncopy); } po->np = offset + ncopy; po->meta = p->meta; } void fastpm_store_copy(FastPMStore * p, FastPMStore * po) { _fastpm_store_copy(p, 0, po, 0, p->np); } void fastpm_store_take(FastPMStore * p, ptrdiff_t i, FastPMStore * po, ptrdiff_t j) { _fastpm_store_copy(p, i, po, j, 1); } /* extends p by extra. */ void fastpm_store_extend(FastPMStore * p, FastPMStore * extra) { _fastpm_store_copy(extra, 0, p, p->np, extra->np); } void fastpm_store_fill_subsample_mask(FastPMStore * p, double fraction, FastPMParticleMaskType * mask, MPI_Comm comm) { gsl_rng * random_generator = gsl_rng_alloc(gsl_rng_ranlxd1); int ThisTask; MPI_Comm_rank(comm, &ThisTask); /* set uncorrelated seeds */ double seed=1231584; //FIXME: set this properly. gsl_rng_set(random_generator, seed); int d; for(d = 0; d < ThisTask * 8; d++) { seed = 0x7fffffff * gsl_rng_uniform(random_generator); } gsl_rng_set(random_generator, seed); memset(mask, 0, p->np * sizeof(mask[0])); ptrdiff_t i; for(i=0; i < p->np; i++) { double rand_i = gsl_rng_uniform(random_generator); int flag = fraction > 1 || rand_i <= fraction; mask[i] = flag; } gsl_rng_free(random_generator); } void fastpm_store_fill_subsample_mask_every_dim(FastPMStore * p, int every, /* take 1 every 'every' per dimension */ FastPMParticleMaskType * mask) { if(!fastpm_store_has_q(p)) { /* This can be relaxed by using a less strict subsample algorithm, e.g. subsample by a hash of ID. */ fastpm_raise(-1, "Subsample is not supported if the store does not have meta.q."); } /* UNUSED */ memset(mask, 0, p->np * sizeof(mask[0])); ptrdiff_t i, d; for(i = 0; i < p->np; i++) { ptrdiff_t pabs[3]; //pabs is the iq index. move out of loop? uint64_t id = p->id[i]; fastpm_store_get_iq_from_id(p, id, pabs); int flag = 1; for(d = 0; d < 3; d++) { flag *= !(pabs[d] % every); } mask[i] = flag; } } /* * Create a subsample, keeping only those with mask == True; * * if po is NULL, only return number of items. * */ size_t fastpm_store_subsample(FastPMStore * p, FastPMParticleMaskType * mask, FastPMStore * po) { ptrdiff_t i; ptrdiff_t j; j = 0; for(i = 0; i < p->np; i ++) { if(!mask[i]) continue; /* just counting */ if(po == NULL) { j++; continue; } /* avoid memcpy of same address if we are doing subsample inplace */ if(p == po && j == i) {j ++; continue; } int c; for(c = 0; c < 32; c ++) { if (!po->columns[c]) continue; size_t elsize = po->_column_info[c].elsize; memcpy(po->columns[c] + j * elsize, p->columns[c] + i * elsize, elsize); } j ++; } if(po) { po->np = j; po->meta = p->meta; ///???? } return j; } #if 0 static ptrdiff_t binary_search(double foo, double a[], size_t n) { ptrdiff_t left = 0, right = n; ptrdiff_t mid; /* find the right side, because hist would count the number < edge, not <= edge */ if(a[left] > foo) { return 0; } if(a[right - 1] <= foo) { return n; } while(right - left > 1) { mid = left + ((right - left - 1) >> 1); double pivot = a[mid]; if(pivot > foo) { right = mid + 1; /* a[right - 1] > foo; */ } else { left = mid + 1; /* a[left] <= foo; */ } } return left; } #endif /* this is cumulative */ void fastpm_store_histogram_aemit_sorted(FastPMStore * store, int64_t * hist, double * aedges, size_t nedges, MPI_Comm comm) { ptrdiff_t i; int64_t * hist1 = malloc(sizeof(hist1[0]) * (nedges + 1)); memset(hist1, 0, sizeof(hist1[0]) * (nedges + 1)); #pragma omp parallel { /* FIXME: use standard reduction with OpenMP 4.7 */ int64_t * hist2 = malloc(sizeof(hist2[0]) * (nedges + 1)); memset(hist2, 0, sizeof(hist2[0]) * (nedges + 1)); int iedge = 0; /* this works because openmp will send each thread at most 1 * chunk with the static scheduling; thus a thread never sees * out of order aemit */ #pragma omp for schedule(static) for(i = 0; i < store->np; i ++) { while(iedge < nedges && store->aemit[i] >= aedges[iedge]) iedge ++; // int ibin = binary_search(store->aemit[i], aedges, nedges); // if(ibin != iedge) abort(); hist2[iedge] ++; } #pragma omp critical { for(i = 0; i < nedges + 1; i ++) { hist1[i] += hist2[i]; } } free(hist2); } MPI_Allreduce(MPI_IN_PLACE, hist1, nedges + 1, MPI_LONG, MPI_SUM, comm); for(i = 0; i < nedges + 1; i ++) { hist[i] += hist1[i]; } free(hist1); }
{ "alphanum_fraction": 0.5471130278, "avg_line_length": 29.1419529837, "ext": "c", "hexsha": "520d999737bc533abdcc8f30c8482e567a050681", "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/store.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/store.c", "max_line_length": 142, "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/store.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9779, "size": 32231 }
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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: parse_exp.c 13079 2015-02-18 16:06:42Z dstrubbe $ */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include "liboct_parser.h" #include "symbols.h" static char *par_string; static int par_pos; parse_result par_res; static int oct_parser_lex(void); static int oct_parser_error (char *s) /* Called by oct_parser_parse on error */ { /* Do nothing */ /* printf("%s\n", s); */ return 0; } /* include the parser */ #include "grammar.c" int parse_exp(char *exp, parse_result *r) { int o; par_string = exp; par_pos = 0; o = oct_parser_parse(); if(o == 0){ r->type = par_res.type; if(r->type == PR_CMPLX) r->value.c = par_res.value.c; else r->value.s = par_res.value.s; } return o; } int get_real(char *s, double *d) { int n=0; sscanf(s, "%lg", d); while(*s && (isdigit(*s) || *s=='.' || *s=='e' || *s=='E')){ if((*s=='e' || *s=='E') && (*(s+1)=='+' || *(s+1)=='-')) {s++; n++;} s++; n++; } return n; } static int oct_parser_lex (){ int c; char *symbuf = 0, *symbuf2 = 0; int length = 0; /* Ignore whitespace, get first nonwhite character. */ while ((c = par_string[par_pos++]) == ' ' || c == '\t'); if (c == '\0') return '\n'; /* Char starts a number => parse the number. */ if (c == '.' || isdigit (c)){ par_pos--; par_pos += get_real(&par_string[par_pos], &GSL_REAL(yylval.val)); return NUM; } /* get the logical operators */ if (c == '<' && par_string[par_pos] == '='){ par_pos++; return LE; } if (c == '>' && par_string[par_pos] == '='){ par_pos++; return GE; } if (c == '=' && par_string[par_pos] == '='){ par_pos++; return EQUAL; } /* if (c == ':' && par_string[par_pos] == '='){ par_pos++; return SET; } */ if (c == '&' && par_string[par_pos] == '&'){ par_pos++; return LAND; } if (c == '|' && par_string[par_pos] == '|'){ par_pos++; return LOR; } /* Char starts an identifier => read the name. */ if (isalpha (c) || c == '\'' || c == '\"'){ symrec *s; char startc = (char)c; int i; /* Initially make the buffer long enough for a 40-character symbol name. */ if (length == 0) length = 40, symbuf = (char *)malloc (length + 1); if(startc == '\'' || startc == '\"') c = par_string[par_pos++]; else startc = 0; /* false */ i = 0; do{ /* If buffer is full, make it larger. */ if (i == length){ length *= 2; symbuf2 = (char *)realloc (symbuf, length + 1); if (symbuf2 == NULL) { fprintf(stderr, "Parser error: failed to reallocate buffer to size %i.\n", length); exit(1); } else { symbuf = symbuf2; } } /* Add this character to the buffer. */ symbuf[i++] = (char)c; /* Get another character. */ c = par_string[par_pos++]; }while (c != '\0' && ((startc && c!=startc) || (!startc && (isalnum(c) || c == '_' )))); if(!startc) par_pos--; symbuf[i] = '\0'; if(!startc){ s = getsym (symbuf); if (s == 0){ int jj; for (jj = 0; reserved_symbols[jj] != 0; jj++){ if(strcmp(symbuf, reserved_symbols[jj]) == 0){ fprintf(stderr, "Parser error: trying to redefine reserved symbol '%s'.\n", symbuf); exit(1); } } s = putsym (symbuf, S_CMPLX); } yylval.tptr = s; free(symbuf); if(s->type == S_CMPLX) return VAR; else return FNCT; }else{ yylval.str = strdup(symbuf); free(symbuf); return STR; } } /* Any other character is a token by itself. */ return c; }
{ "alphanum_fraction": 0.5570826868, "avg_line_length": 22.8984771574, "ext": "c", "hexsha": "b1dd98f258c11b7c27f106785ec5be933ce8b366", "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": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "gimunu/octopus-metric", "max_forks_repo_path": "liboct_parser/parse_exp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "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": "gimunu/octopus-metric", "max_issues_repo_path": "liboct_parser/parse_exp.c", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "gimunu/octopus-metric", "max_stars_repo_path": "liboct_parser/parse_exp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1361, "size": 4511 }
/* * 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 Mon Mar 8 17:44:42 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -notwiddle 15 */ /* * This function contains 156 FP additions, 56 FP multiplications, * (or, 128 additions, 28 multiplications, 28 fused multiply/add), * 62 stack variables, and 60 memory accesses */ static const fftw_real K587785252 = FFTW_KONST(+0.587785252292473129168705954639072768597652438); static const fftw_real K951056516 = FFTW_KONST(+0.951056516295153572116439333379382143405698634); static const fftw_real K250000000 = FFTW_KONST(+0.250000000000000000000000000000000000000000000); static const fftw_real K559016994 = FFTW_KONST(+0.559016994374947424102293417182819058860154590); static const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000); static const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627); /* * Generator Id's : * $Id: exprdag.ml,v 1.36 1999/02/19 17:22:11 athena Exp $ * $Id: fft.ml,v 1.41 1999/02/19 17:22:13 athena Exp $ * $Id: to_c.ml,v 1.24 1999/02/19 17:22:17 athena Exp $ */ void fftw_no_twiddle_15(const fftw_complex *input, fftw_complex *output, int istride, int ostride) { fftw_real tmp5; fftw_real tmp33; fftw_real tmp57; fftw_real tmp145; fftw_real tmp100; fftw_real tmp124; fftw_real tmp21; fftw_real tmp26; fftw_real tmp27; fftw_real tmp49; fftw_real tmp54; fftw_real tmp55; fftw_real tmp136; fftw_real tmp137; fftw_real tmp147; fftw_real tmp61; fftw_real tmp62; fftw_real tmp63; fftw_real tmp112; fftw_real tmp113; fftw_real tmp126; fftw_real tmp83; fftw_real tmp88; fftw_real tmp94; fftw_real tmp10; fftw_real tmp15; fftw_real tmp16; fftw_real tmp38; fftw_real tmp43; fftw_real tmp44; fftw_real tmp139; fftw_real tmp140; fftw_real tmp146; fftw_real tmp58; fftw_real tmp59; fftw_real tmp60; fftw_real tmp115; fftw_real tmp116; fftw_real tmp125; fftw_real tmp72; fftw_real tmp77; fftw_real tmp93; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp1; fftw_real tmp97; fftw_real tmp4; fftw_real tmp96; fftw_real tmp32; fftw_real tmp98; fftw_real tmp29; fftw_real tmp99; ASSERT_ALIGNED_DOUBLE(); tmp1 = c_re(input[0]); tmp97 = c_im(input[0]); { fftw_real tmp2; fftw_real tmp3; fftw_real tmp30; fftw_real tmp31; ASSERT_ALIGNED_DOUBLE(); tmp2 = c_re(input[5 * istride]); tmp3 = c_re(input[10 * istride]); tmp4 = tmp2 + tmp3; tmp96 = K866025403 * (tmp3 - tmp2); tmp30 = c_im(input[5 * istride]); tmp31 = c_im(input[10 * istride]); tmp32 = K866025403 * (tmp30 - tmp31); tmp98 = tmp30 + tmp31; } tmp5 = tmp1 + tmp4; tmp29 = tmp1 - (K500000000 * tmp4); tmp33 = tmp29 - tmp32; tmp57 = tmp29 + tmp32; tmp145 = tmp97 + tmp98; tmp99 = tmp97 - (K500000000 * tmp98); tmp100 = tmp96 + tmp99; tmp124 = tmp99 - tmp96; } { fftw_real tmp17; fftw_real tmp20; fftw_real tmp45; fftw_real tmp79; fftw_real tmp80; fftw_real tmp81; fftw_real tmp48; fftw_real tmp82; fftw_real tmp22; fftw_real tmp25; fftw_real tmp50; fftw_real tmp84; fftw_real tmp85; fftw_real tmp86; fftw_real tmp53; fftw_real tmp87; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp18; fftw_real tmp19; fftw_real tmp46; fftw_real tmp47; ASSERT_ALIGNED_DOUBLE(); tmp17 = c_re(input[6 * istride]); tmp18 = c_re(input[11 * istride]); tmp19 = c_re(input[istride]); tmp20 = tmp18 + tmp19; tmp45 = tmp17 - (K500000000 * tmp20); tmp79 = K866025403 * (tmp19 - tmp18); tmp80 = c_im(input[6 * istride]); tmp46 = c_im(input[11 * istride]); tmp47 = c_im(input[istride]); tmp81 = tmp46 + tmp47; tmp48 = K866025403 * (tmp46 - tmp47); tmp82 = tmp80 - (K500000000 * tmp81); } { fftw_real tmp23; fftw_real tmp24; fftw_real tmp51; fftw_real tmp52; ASSERT_ALIGNED_DOUBLE(); tmp22 = c_re(input[9 * istride]); tmp23 = c_re(input[14 * istride]); tmp24 = c_re(input[4 * istride]); tmp25 = tmp23 + tmp24; tmp50 = tmp22 - (K500000000 * tmp25); tmp84 = K866025403 * (tmp24 - tmp23); tmp85 = c_im(input[9 * istride]); tmp51 = c_im(input[14 * istride]); tmp52 = c_im(input[4 * istride]); tmp86 = tmp51 + tmp52; tmp53 = K866025403 * (tmp51 - tmp52); tmp87 = tmp85 - (K500000000 * tmp86); } tmp21 = tmp17 + tmp20; tmp26 = tmp22 + tmp25; tmp27 = tmp21 + tmp26; tmp49 = tmp45 - tmp48; tmp54 = tmp50 - tmp53; tmp55 = tmp49 + tmp54; tmp136 = tmp80 + tmp81; tmp137 = tmp85 + tmp86; tmp147 = tmp136 + tmp137; tmp61 = tmp45 + tmp48; tmp62 = tmp50 + tmp53; tmp63 = tmp61 + tmp62; tmp112 = tmp82 - tmp79; tmp113 = tmp87 - tmp84; tmp126 = tmp112 + tmp113; tmp83 = tmp79 + tmp82; tmp88 = tmp84 + tmp87; tmp94 = tmp83 + tmp88; } { fftw_real tmp6; fftw_real tmp9; fftw_real tmp34; fftw_real tmp68; fftw_real tmp69; fftw_real tmp70; fftw_real tmp37; fftw_real tmp71; fftw_real tmp11; fftw_real tmp14; fftw_real tmp39; fftw_real tmp73; fftw_real tmp74; fftw_real tmp75; fftw_real tmp42; fftw_real tmp76; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp7; fftw_real tmp8; fftw_real tmp35; fftw_real tmp36; ASSERT_ALIGNED_DOUBLE(); tmp6 = c_re(input[3 * istride]); tmp7 = c_re(input[8 * istride]); tmp8 = c_re(input[13 * istride]); tmp9 = tmp7 + tmp8; tmp34 = tmp6 - (K500000000 * tmp9); tmp68 = K866025403 * (tmp8 - tmp7); tmp69 = c_im(input[3 * istride]); tmp35 = c_im(input[8 * istride]); tmp36 = c_im(input[13 * istride]); tmp70 = tmp35 + tmp36; tmp37 = K866025403 * (tmp35 - tmp36); tmp71 = tmp69 - (K500000000 * tmp70); } { fftw_real tmp12; fftw_real tmp13; fftw_real tmp40; fftw_real tmp41; ASSERT_ALIGNED_DOUBLE(); tmp11 = c_re(input[12 * istride]); tmp12 = c_re(input[2 * istride]); tmp13 = c_re(input[7 * istride]); tmp14 = tmp12 + tmp13; tmp39 = tmp11 - (K500000000 * tmp14); tmp73 = K866025403 * (tmp13 - tmp12); tmp74 = c_im(input[12 * istride]); tmp40 = c_im(input[2 * istride]); tmp41 = c_im(input[7 * istride]); tmp75 = tmp40 + tmp41; tmp42 = K866025403 * (tmp40 - tmp41); tmp76 = tmp74 - (K500000000 * tmp75); } tmp10 = tmp6 + tmp9; tmp15 = tmp11 + tmp14; tmp16 = tmp10 + tmp15; tmp38 = tmp34 - tmp37; tmp43 = tmp39 - tmp42; tmp44 = tmp38 + tmp43; tmp139 = tmp69 + tmp70; tmp140 = tmp74 + tmp75; tmp146 = tmp139 + tmp140; tmp58 = tmp34 + tmp37; tmp59 = tmp39 + tmp42; tmp60 = tmp58 + tmp59; tmp115 = tmp71 - tmp68; tmp116 = tmp76 - tmp73; tmp125 = tmp115 + tmp116; tmp72 = tmp68 + tmp71; tmp77 = tmp73 + tmp76; tmp93 = tmp72 + tmp77; } { fftw_real tmp134; fftw_real tmp28; fftw_real tmp133; fftw_real tmp142; fftw_real tmp144; fftw_real tmp138; fftw_real tmp141; fftw_real tmp143; fftw_real tmp135; ASSERT_ALIGNED_DOUBLE(); tmp134 = K559016994 * (tmp16 - tmp27); tmp28 = tmp16 + tmp27; tmp133 = tmp5 - (K250000000 * tmp28); tmp138 = tmp136 - tmp137; tmp141 = tmp139 - tmp140; tmp142 = (K951056516 * tmp138) - (K587785252 * tmp141); tmp144 = (K951056516 * tmp141) + (K587785252 * tmp138); c_re(output[0]) = tmp5 + tmp28; tmp143 = tmp134 + tmp133; c_re(output[9 * ostride]) = tmp143 - tmp144; c_re(output[6 * ostride]) = tmp143 + tmp144; tmp135 = tmp133 - tmp134; c_re(output[12 * ostride]) = tmp135 - tmp142; c_re(output[3 * ostride]) = tmp135 + tmp142; } { fftw_real tmp110; fftw_real tmp56; fftw_real tmp109; fftw_real tmp118; fftw_real tmp120; fftw_real tmp114; fftw_real tmp117; fftw_real tmp119; fftw_real tmp111; ASSERT_ALIGNED_DOUBLE(); tmp110 = K559016994 * (tmp44 - tmp55); tmp56 = tmp44 + tmp55; tmp109 = tmp33 - (K250000000 * tmp56); tmp114 = tmp112 - tmp113; tmp117 = tmp115 - tmp116; tmp118 = (K951056516 * tmp114) - (K587785252 * tmp117); tmp120 = (K951056516 * tmp117) + (K587785252 * tmp114); c_re(output[5 * ostride]) = tmp33 + tmp56; tmp119 = tmp110 + tmp109; c_re(output[14 * ostride]) = tmp119 - tmp120; c_re(output[11 * ostride]) = tmp119 + tmp120; tmp111 = tmp109 - tmp110; c_re(output[2 * ostride]) = tmp111 - tmp118; c_re(output[8 * ostride]) = tmp111 + tmp118; } { fftw_real tmp150; fftw_real tmp148; fftw_real tmp149; fftw_real tmp154; fftw_real tmp156; fftw_real tmp152; fftw_real tmp153; fftw_real tmp155; fftw_real tmp151; ASSERT_ALIGNED_DOUBLE(); tmp150 = K559016994 * (tmp146 - tmp147); tmp148 = tmp146 + tmp147; tmp149 = tmp145 - (K250000000 * tmp148); tmp152 = tmp21 - tmp26; tmp153 = tmp10 - tmp15; tmp154 = (K951056516 * tmp152) - (K587785252 * tmp153); tmp156 = (K951056516 * tmp153) + (K587785252 * tmp152); c_im(output[0]) = tmp145 + tmp148; tmp155 = tmp150 + tmp149; c_im(output[6 * ostride]) = tmp155 - tmp156; c_im(output[9 * ostride]) = tmp156 + tmp155; tmp151 = tmp149 - tmp150; c_im(output[3 * ostride]) = tmp151 - tmp154; c_im(output[12 * ostride]) = tmp154 + tmp151; } { fftw_real tmp129; fftw_real tmp127; fftw_real tmp128; fftw_real tmp123; fftw_real tmp132; fftw_real tmp121; fftw_real tmp122; fftw_real tmp131; fftw_real tmp130; ASSERT_ALIGNED_DOUBLE(); tmp129 = K559016994 * (tmp125 - tmp126); tmp127 = tmp125 + tmp126; tmp128 = tmp124 - (K250000000 * tmp127); tmp121 = tmp49 - tmp54; tmp122 = tmp38 - tmp43; tmp123 = (K951056516 * tmp121) - (K587785252 * tmp122); tmp132 = (K951056516 * tmp122) + (K587785252 * tmp121); c_im(output[5 * ostride]) = tmp124 + tmp127; tmp131 = tmp129 + tmp128; c_im(output[11 * ostride]) = tmp131 - tmp132; c_im(output[14 * ostride]) = tmp132 + tmp131; tmp130 = tmp128 - tmp129; c_im(output[2 * ostride]) = tmp123 + tmp130; c_im(output[8 * ostride]) = tmp130 - tmp123; } { fftw_real tmp95; fftw_real tmp101; fftw_real tmp102; fftw_real tmp106; fftw_real tmp107; fftw_real tmp104; fftw_real tmp105; fftw_real tmp108; fftw_real tmp103; ASSERT_ALIGNED_DOUBLE(); tmp95 = K559016994 * (tmp93 - tmp94); tmp101 = tmp93 + tmp94; tmp102 = tmp100 - (K250000000 * tmp101); tmp104 = tmp58 - tmp59; tmp105 = tmp61 - tmp62; tmp106 = (K951056516 * tmp104) + (K587785252 * tmp105); tmp107 = (K951056516 * tmp105) - (K587785252 * tmp104); c_im(output[10 * ostride]) = tmp100 + tmp101; tmp108 = tmp102 - tmp95; c_im(output[7 * ostride]) = tmp107 + tmp108; c_im(output[13 * ostride]) = tmp108 - tmp107; tmp103 = tmp95 + tmp102; c_im(output[ostride]) = tmp103 - tmp106; c_im(output[4 * ostride]) = tmp106 + tmp103; } { fftw_real tmp65; fftw_real tmp64; fftw_real tmp66; fftw_real tmp90; fftw_real tmp92; fftw_real tmp78; fftw_real tmp89; fftw_real tmp91; fftw_real tmp67; ASSERT_ALIGNED_DOUBLE(); tmp65 = K559016994 * (tmp60 - tmp63); tmp64 = tmp60 + tmp63; tmp66 = tmp57 - (K250000000 * tmp64); tmp78 = tmp72 - tmp77; tmp89 = tmp83 - tmp88; tmp90 = (K951056516 * tmp78) + (K587785252 * tmp89); tmp92 = (K951056516 * tmp89) - (K587785252 * tmp78); c_re(output[10 * ostride]) = tmp57 + tmp64; tmp91 = tmp66 - tmp65; c_re(output[7 * ostride]) = tmp91 - tmp92; c_re(output[13 * ostride]) = tmp91 + tmp92; tmp67 = tmp65 + tmp66; c_re(output[4 * ostride]) = tmp67 - tmp90; c_re(output[ostride]) = tmp67 + tmp90; } } fftw_codelet_desc fftw_no_twiddle_15_desc = { "fftw_no_twiddle_15", (void (*)()) fftw_no_twiddle_15, 15, FFTW_FORWARD, FFTW_NOTW, 241, 0, (const int *) 0, };
{ "alphanum_fraction": 0.6295545038, "avg_line_length": 29.7785234899, "ext": "c", "hexsha": "b12e4ad52f8f7126b74fa5d7a3044771356c9009", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_path": "jlp_numeric/old/fftw2_src/fn_15.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jlprieur/jlplib", "max_issues_repo_path": "jlp_numeric/old/fftw2_src/fn_15.c", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_path": "jlp_numeric/old/fftw2_src/fn_15.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4435, "size": 13311 }
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpRNG.h> #include <gbpMCMC.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_interp.h> void free_MCMC_arrays(MCMC_info *MCMC) { int i_DS; MCMC_DS_info *current_DS; MCMC_DS_info *next_DS; if(MCMC->n_M != NULL) { SID_log("Freeing MCMC target arrays for %d dataset(s)...", SID_LOG_OPEN, MCMC->n_DS); // Free chain arrays i_DS = 0; current_DS = MCMC->DS; while(current_DS != NULL) { next_DS = current_DS->next; SID_free(SID_FARG MCMC->M_new[i_DS]); SID_free(SID_FARG MCMC->M_last[i_DS]); current_DS = next_DS; i_DS++; } SID_free(SID_FARG MCMC->n_M); SID_free(SID_FARG MCMC->M_new); SID_free(SID_FARG MCMC->M_last); MCMC->n_M_total = 0; // Free results arrays SID_free(SID_FARG MCMC->P_min); SID_free(SID_FARG MCMC->P_max); SID_free(SID_FARG MCMC->P_avg); SID_free(SID_FARG MCMC->dP_avg); SID_free(SID_FARG MCMC->P_best); SID_free(SID_FARG MCMC->P_peak); SID_free(SID_FARG MCMC->P_lo_68); SID_free(SID_FARG MCMC->P_hi_68); SID_free(SID_FARG MCMC->P_lo_95); SID_free(SID_FARG MCMC->P_hi_95); SID_free(SID_FARG MCMC->ln_likelihood_DS); SID_free(SID_FARG MCMC->ln_likelihood_DS_best); SID_free(SID_FARG MCMC->ln_likelihood_DS_peak); SID_free(SID_FARG MCMC->n_DoF_DS); SID_free(SID_FARG MCMC->n_DoF_DS_best); SID_free(SID_FARG MCMC->n_DoF_DS_peak); // These only need to be deallocated if we are using MCMC_MODE_MINIMIZE_IO if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_MINIMIZE_IO)) { SID_free(SID_FARG MCMC->flag_success_buffer); SID_free(SID_FARG MCMC->ln_likelihood_new_buffer); SID_free(SID_FARG MCMC->P_new_buffer); SID_free(SID_FARG MCMC->M_new_buffer); } SID_log("Done.", SID_LOG_CLOSE); } }
{ "alphanum_fraction": 0.6271744241, "avg_line_length": 32.7230769231, "ext": "c", "hexsha": "852e847540704dd0cf0bdcd38208c6a471a01caf", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_arrays.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_arrays.c", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_arrays.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 667, "size": 2127 }
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2021 INRIA. * * 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 SiconosBlas_H #define SiconosBlas_H #include "SiconosConfig.h" #if defined(__cplusplus) extern "C" { #endif // tells include-what-you-use to keep this file // and not to suggest cblas.h or alike. // IWYU pragma: begin_exports #if defined(HAS_MKL_CBLAS) #include <mkl_cblas.h> #elif defined(HAS_MATLAB_BLAS) #include <blas.h> #define cblas_daxpy daxpy #define cblas_dcopy dcopy #define cblas_ddot ddot #define cblas_dgemm dgemm #define cblas_dgemv dgemv #define cblas_dnrm2 dnrm2 #define cblas_dscal dscal #else #include <cblas.h> #endif // IWYU pragma: end_exports #ifdef __cplusplus } #undef restrict #define restrict __restrict #endif static inline double* NMD_row_rmajor(double* restrict mat, unsigned ncols, unsigned rindx) { return &mat[rindx*ncols]; } static inline void NMD_copycol_rmajor(int nrows, double* col, double* restrict mat, int ncols, unsigned cindx) { cblas_dcopy(nrows, col, 1, &mat[cindx], ncols); } static inline void NMD_dense_gemv(int nrows, int ncols, double alpha, double* restrict mat, double* restrict y, double beta, double* restrict x) { cblas_dgemv(CblasColMajor, CblasTrans, ncols, nrows, alpha, mat, ncols, y, 1, beta, x, 1); } #endif // SiconosBlas_H
{ "alphanum_fraction": 0.7564439769, "avg_line_length": 26.4027777778, "ext": "h", "hexsha": "8edac9622ae8fa8ac1d34c59e1224345264bcfbe", "lang": "C", "max_forks_count": 30, "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_issues_count": 381, "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_line_length": 144, "max_stars_count": 137, "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_path": "externals/blas_lapack/SiconosBlas.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "num_tokens": 516, "size": 1901 }
/****************************************************************************** * myrng.h: header for abstract random number generator * * Author: Yan Y. Liu <yanliu@illinois.edu> * * Date: 2014/08/17 * * Copyright and license of this source file are specified in LICENSE.TXT * * under the root directory of this software package. * ******************************************************************************/ #ifndef MYRNG_H #define MYRNG_H // macro: random number generator #ifdef GSL_SPRNG #include <gsl/gsl_rng.h> #include "gsl-sprng.h" #include <gsl/gsl_randist.h> #define MYRANDI(kkk) ((int)(gsl_rng_uniform_int(gsl_sprng_r, (unsigned long int)(kkk)))) #define MYRANDF() (gsl_rng_uniform(gsl_sprng_r)) #else #ifdef SPRNG #include "mysprng.h" #define MYRANDI(kkk) ((int)(mysprng() * (kkk))) #define MYRANDF() (mysprng()) #else #define MYRANDI(kkk) ((int)(drand48() * (kkk))) #define MYRANDF() (drand48()) #endif #endif #endif
{ "alphanum_fraction": 0.5175276753, "avg_line_length": 36.1333333333, "ext": "h", "hexsha": "d9c7b9922b992cde23f2b341810d1ebc9d2a80d1", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2021-06-17T14:29:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-28T15:28:48.000Z", "max_forks_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_forks_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_forks_repo_path": "pgap/myrng.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "bb0c21ca479db5ac3ecf789ab280d5e45c3c7805", "max_issues_repo_issues_event_max_datetime": "2016-07-25T17:38:26.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-25T02:25:20.000Z", "max_issues_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-15-00005", "max_issues_repo_path": "pgap/myrng.h", "max_line_length": 88, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9a7d7c02b2f1d7b6bfd1b08fbb2150c30ddd1046", "max_stars_repo_licenses": [ "NCSA", "BSD-3-Clause" ], "max_stars_repo_name": "ElsevierSoftwareX/SOFTX_2018_242", "max_stars_repo_path": "pgap/myrng.h", "max_stars_repo_stars_event_max_datetime": "2021-07-28T15:38:19.000Z", "max_stars_repo_stars_event_min_datetime": "2015-07-16T01:05:44.000Z", "num_tokens": 250, "size": 1084 }
/* linalg/lu.c * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_blas.h> #include "gsl_linalg.h" #define REAL double /* Factorise a general N x N matrix A into, * * P A = L U * * where P is a permutation matrix, L is unit lower triangular and U * is upper triangular. * * L is stored in the strict lower triangular part of the input * matrix. The diagonal elements of L are unity and are not stored. * * U is stored in the diagonal and upper triangular part of the * input matrix. * * P is stored in the permutation p. Column j of P is column k of the * identity matrix, where k = permutation->data[j] * * signum gives the sign of the permutation, (-1)^n, where n is the * number of interchanges in the permutation. * * See Golub & Van Loan, Matrix Computations, Algorithm 3.4.1 (Gauss * Elimination with Partial Pivoting). */ int gsl_linalg_LU_decomp (gsl_matrix * A, gsl_permutation * p, int *signum) { if (A->size1 != A->size2) { GSL_ERROR ("LU decomposition requires square matrix", GSL_ENOTSQR); } else if (p->size != A->size1) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else { const size_t N = A->size1; size_t i, j, k; *signum = 1; gsl_permutation_init (p); for (j = 0; j < N - 1; j++) { /* Find maximum in the j-th column */ REAL ajj, max = fabs (gsl_matrix_get (A, j, j)); size_t i_pivot = j; for (i = j + 1; i < N; i++) { REAL aij = fabs (gsl_matrix_get (A, i, j)); if (aij > max) { max = aij; i_pivot = i; } } if (i_pivot != j) { gsl_matrix_swap_rows (A, j, i_pivot); gsl_permutation_swap (p, j, i_pivot); *signum = -(*signum); } ajj = gsl_matrix_get (A, j, j); if (ajj != 0.0) { for (i = j + 1; i < N; i++) { REAL aij = gsl_matrix_get (A, i, j) / ajj; gsl_matrix_set (A, i, j, aij); for (k = j + 1; k < N; k++) { REAL aik = gsl_matrix_get (A, i, k); REAL ajk = gsl_matrix_get (A, j, k); gsl_matrix_set (A, i, k, aik - aij * ajk); } } } } return GSL_SUCCESS; } } int gsl_linalg_LU_solve (const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LU->size2 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { /* Copy x <- b */ gsl_vector_memcpy (x, b); /* Solve for x */ gsl_linalg_LU_svx (LU, p, x); return GSL_SUCCESS; } } int gsl_linalg_LU_svx (const gsl_matrix * LU, const gsl_permutation * p, gsl_vector * x) { if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != x->size) { GSL_ERROR ("matrix size must match solution/rhs size", GSL_EBADLEN); } else { /* Apply permutation to RHS */ gsl_permute_vector (p, x); /* Solve for c using forward-substitution, L c = P b */ gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasUnit, LU, x); /* Perform back-substitution, U x = c */ gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LU, x); return GSL_SUCCESS; } } int gsl_linalg_LU_refine (const gsl_matrix * A, const gsl_matrix * LU, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x, gsl_vector * residual) { if (A->size1 != A->size2) { GSL_ERROR ("matrix a must be square", GSL_ENOTSQR); } if (LU->size1 != LU->size2) { GSL_ERROR ("LU matrix must be square", GSL_ENOTSQR); } else if (A->size1 != LU->size2) { GSL_ERROR ("LU matrix must be decomposition of a", GSL_ENOTSQR); } else if (LU->size1 != p->size) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else if (LU->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LU->size1 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { /* Compute residual, residual = (A * x - b) */ gsl_vector_memcpy (residual, b); gsl_blas_dgemv (CblasNoTrans, 1.0, A, x, -1.0, residual); /* Find correction, delta = - (A^-1) * residual, and apply it */ gsl_linalg_LU_svx (LU, p, residual); gsl_blas_daxpy (-1.0, residual, x); return GSL_SUCCESS; } } int gsl_linalg_LU_invert (const gsl_matrix * LU, const gsl_permutation * p, gsl_matrix * inverse) { size_t i, n = LU->size1; int status = GSL_SUCCESS; gsl_matrix_set_identity (inverse); for (i = 0; i < n; i++) { gsl_vector_view c = gsl_matrix_column (inverse, i); int status_i = gsl_linalg_LU_svx (LU, p, &(c.vector)); if (status_i) status = status_i; } return status; } double gsl_linalg_LU_det (gsl_matrix * LU, int signum) { size_t i, n = LU->size1; double det = (double) signum; for (i = 0; i < n; i++) { det *= gsl_matrix_get (LU, i, i); } return det; } double gsl_linalg_LU_lndet (gsl_matrix * LU) { size_t i, n = LU->size1; double lndet = 0.0; for (i = 0; i < n; i++) { lndet += log (fabs (gsl_matrix_get (LU, i, i))); } return lndet; } int gsl_linalg_LU_sgndet (gsl_matrix * LU, int signum) { size_t i, n = LU->size1; int s = signum; for (i = 0; i < n; i++) { double u = gsl_matrix_get (LU, i, i); if (u < 0) { s *= -1; } else if (u == 0) { s = 0; break; } } return s; }
{ "alphanum_fraction": 0.6026575225, "avg_line_length": 22.3610223642, "ext": "c", "hexsha": "4b83c82995844be4dc4e7dfa0d9f4ea195befcb2", "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/linalg/lu.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/linalg/lu.c", "max_line_length": 154, "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/linalg/lu.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": 2185, "size": 6999 }
#include "stdio.h" #include "gsl/gsl_integration.h" #include "gsl/gsl_errno.h" #include "limber.h" #include <gsl/gsl_interp2d.h> //#include <gsl/gsl_spline2d.h> //#include <gsl/gsl_spline.h> // This is a workspace size for the gsl integrator #define LIMBER_FIXED_TABLE_SIZE 4096 // data that is passed into the integrator // This is everything we need to compute the // integrand typedef struct IntegrandData{ double chimin; double chimax; double ell; gsl_spline * WbX; //K1 gsl_spline * WfX; //K2 gsl_spline * WmX; //K3 gsl_spline * WbY; //K4 gsl_spline * WfY; //K5 gsl_spline * WmY; //K6 Interpolator2D * P; Interpolator2D * f; //for the f(k,z(x)) Interpolator2D * D; //for the D(k,z(x)) Interpolator2D * BB; //for the b(k,z(x)) gsl_interp_accel * accelerator_xb; gsl_interp_accel * accelerator_yb; gsl_interp_accel * accelerator_xf; gsl_interp_accel * accelerator_yf; gsl_interp_accel * accelerator_xm; gsl_interp_accel * accelerator_ym; } IntegrandData; // the integrand for all static double integrand(double chi, void * data_void) { IntegrandData * data = (IntegrandData*) data_void; // Return 0 if outside range, for convenience. // Important to ensure that ranges are wide enough. if(chi < data->chimin || chi > data->chimax) return 0.0; //exactly the same notation of paperIII double wx0 = gsl_spline_eval(data->WbX,chi,data->accelerator_xb); double wy0 = gsl_spline_eval(data->WbY,chi,data->accelerator_yb); double wx0m = gsl_spline_eval(data->WmX,chi,data->accelerator_xm); double wy0m = gsl_spline_eval(data->WmY,chi,data->accelerator_ym); double wx1 = gsl_spline_eval(data->WfX,chi,data->accelerator_xf); double wy1 = gsl_spline_eval(data->WfY,chi,data->accelerator_yf); double wx2 = gsl_spline_eval(data->WfX,chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0),data->accelerator_xf); double wy2 = gsl_spline_eval(data->WfY,chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0),data->accelerator_yf); double chi5 = chi*(2.0*data->ell+5.0)/(2.0*data->ell+1.0) < data->chimax ? chi*(2.0*data->ell+5.0)/(2.0*data->ell+1.0) : 0.0; double wx3 = gsl_spline_eval(data->WfX, chi5, data->accelerator_xf); double wy3 = gsl_spline_eval(data->WfY, chi5, data->accelerator_yf); double c1 = (2.*data->ell*data->ell+2.*data->ell-1.)/((2.*data->ell-1.)*(2.*data->ell+3.)); double c2 = -((data->ell*(data->ell-1.))/((2.*data->ell-1.)*sqrt((2.*data->ell+1.)*(2.*data->ell-3.)))); double c3 = -(((data->ell+1.)*(data->ell+2.))/((2.*data->ell+3.)*sqrt((2.*data->ell+1.)*(2.*data->ell+5.)))); // Get P(k,0) using k=ell/chi. // The interp_2d interpolator returns 0 if either // parameter is outside its range double ka = (data->ell+0.5) / chi; double pa = interp_2d(ka, chi, data->P); //for the scale dependent bias b(k,z) double b0 = interp_2d(ka, chi, data->BB); //for the scale dependent growth factor D(k,z) double d0 = interp_2d(ka, chi, data->D); double d1 = d0; double d2 = interp_2d(ka, chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0), data->D); double d3 = interp_2d(ka, chi5, data->D); //for the scale dependent growth rate f(k,z) double f1 = interp_2d(ka, chi, data->f); double f2 = interp_2d(ka, chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0), data->f); double f3 = interp_2d(ka, chi5, data->f); double WWX= (wx0*b0*d0 + wx0m*d0 + c1*wx1*f1*d1 + c2*wx2*f2*d2 + c3*wx3*f3*d3); double WWY= (wy0*b0*d0 + wy0m*d0 + c1*wy1*f1*d1 + c2*wy2*f2*d2 + c3*wy3*f3*d3); double result = WWX * WWY * pa / chi / chi; return result; } // These two convenience functions // peer into the internals of the gsl_spline. // This is probably a bit naughty, since they could // in theory change the internals. static double inline limber_gsl_spline_min_x(gsl_spline * s) { return s->x[0]; } static double inline limber_gsl_spline_max_x(gsl_spline * s) { return s->x[s->size-1]; } double get_kernel_peak(gsl_spline * WbX, gsl_spline * WbY, int n_chi) { double chimin_x = limber_gsl_spline_min_x(WbX); double chimin_y = limber_gsl_spline_min_x(WbY); double chimax_x = limber_gsl_spline_max_x(WbX); double chimax_y = limber_gsl_spline_max_x(WbY); double chimin = chimin_x>chimin_y ? chimin_x : chimin_y; double chimax = chimax_x<chimax_y ? chimax_x : chimax_y; double dchi = (chimax - chimin)/n_chi; double chi_peak = chimin; double chi; double kernel_val=0.; double kernel_peak=0.; for (int i_chi=0; i_chi<=n_chi; i_chi++){ chi=chimin+i_chi*dchi; kernel_val = gsl_spline_eval(WbX,chi,NULL) * gsl_spline_eval(WbY,chi,NULL) / chi / chi; if (kernel_val>kernel_peak){ kernel_peak = kernel_val; chi_peak = chi; } } // printf("chi_peak = %f\n",chi_peak); return chi_peak; } gsl_integration_workspace * W = NULL; gsl_integration_glfixed_table *table = NULL; void setup_integration_workspaces(){ if (W==NULL){ W = gsl_integration_workspace_alloc(LIMBER_FIXED_TABLE_SIZE); } if (table==NULL){ table = gsl_integration_glfixed_table_alloc((size_t) LIMBER_FIXED_TABLE_SIZE); } } static void limber_gsl_fallback_integrator(gsl_function * F, double chimin, double chimax, double abstol, double reltol, double * c_ell, double * error){ // Only one warning per process static int fallback_warning_given = 0; // Deactivate error handling - if this one fails we will fall back to a more reliable but slower integrator gsl_error_handler_t * old_handler = gsl_set_error_handler_off(); // Try the fast but flaky integrator. int status = gsl_integration_qag(F, chimin, chimax, abstol, reltol, LIMBER_FIXED_TABLE_SIZE, GSL_INTEG_GAUSS61, W, c_ell, error); // Restore the old error handler gsl_set_error_handler(old_handler); // If the fast integrator failed fall back to the old one. if (status){ IntegrandData * data = (IntegrandData*) F->params; double ell = data->ell; if (fallback_warning_given==0){ fprintf(stderr, "Falling back to the old integrator for ell=%lf (status=%d)\n", ell,status); fallback_warning_given=1; } *c_ell = gsl_integration_glfixed(F,chimin,chimax,table); } } // The only function in this little library callable from the outside // world. The limber_config structure is defined in limber.h but is fairly // obvious. The splines and the interpolator need to be functions of // chi NOT z. gsl_spline * limber_integral(limber_config * config, gsl_spline * WbX, gsl_spline * WfX, gsl_spline * WmX, gsl_spline * WbY, gsl_spline * WfY, gsl_spline * WmY, Interpolator2D * P, Interpolator2D * f, Interpolator2D * D, Interpolator2D * BB) { config->status = LIMBER_STATUS_ERROR; int any_parameter_error=0; if (WbX==NULL){ fprintf(stderr, "NULL WbX parameter in limber_integral\n"); any_parameter_error = 1; } if (WbY==NULL){ fprintf(stderr, "NULL WbY parameter in limber_integral\n"); any_parameter_error = 1; } if (WfX==NULL){ fprintf(stderr, "NULL WfX parameter in limber_integral\n"); any_parameter_error = 1; } if (WfY==NULL){ fprintf(stderr, "NULL WfY parameter in limber_integral\n"); any_parameter_error = 1; } if (WmX==NULL){ fprintf(stderr, "NULL WmX parameter in limber_integral\n"); any_parameter_error = 1; } if (WmY==NULL){ fprintf(stderr, "NULL WmY parameter in limber_integral\n"); any_parameter_error = 1; } if (P==NULL){ fprintf(stderr, "NULL P parameter in limber_integral\n"); any_parameter_error = 1; } if (f==NULL){ fprintf(stderr, "NULL f parameter in limber_integral\n"); any_parameter_error = 1; } if (D==NULL){ fprintf(stderr, "NULL D parameter in limber_integral\n"); any_parameter_error = 1; } if (config->n_ell<0){ fprintf(stderr, "Negative n_ell parameter in limber_integral\n"); any_parameter_error = 1; } if (config->n_ell==0){ fprintf(stderr, "Error: n_ell=0 in limber calculation.\n"); any_parameter_error = 1; } if (any_parameter_error){ return NULL; } config->status = LIMBER_STATUS_OK; // Get the appropriate ranges over which to integrate // It is assumed that (at least one of) the kernel // splines should go to zero in some kind of reasonable // place, so we just use the range they specify IntegrandData data; double chimin_xb = limber_gsl_spline_min_x(WbX); double chimin_yb = limber_gsl_spline_min_x(WbY); double chimax_xb = limber_gsl_spline_max_x(WbX); double chimax_yb = limber_gsl_spline_max_x(WbY); double chimin_xf = limber_gsl_spline_min_x(WfX); double chimin_yf = limber_gsl_spline_min_x(WfY); double chimax_xf = limber_gsl_spline_max_x(WfX); double chimax_yf = limber_gsl_spline_max_x(WfY); double chimin_xm = limber_gsl_spline_min_x(WmX); double chimin_ym = limber_gsl_spline_min_x(WmY); double chimax_xm = limber_gsl_spline_max_x(WmX); double chimax_ym = limber_gsl_spline_max_x(WmY); //my ifs here double chimin_x = chimin_xb > chimin_xf ? chimin_xb : chimin_xf; double chimin_y = chimin_yb > chimin_yf ? chimin_yb : chimin_yf; double chimax_x = chimax_xb < chimax_xf ? chimax_xb : chimax_xf; double chimax_y = chimax_yb < chimax_yf ? chimax_yb : chimax_yf; double c_ell, error; // Workspaces for the main and falback integrators. // Static, so only allocated once as it has a fixed size. setup_integration_workspaces(); double reltol = config->relative_tolerance; double abstol = config->absolute_tolerance; // double reltol = 0.001; // double abstol = 0.00001; // printf("TOLS: %le %le\n",reltol,abstol); // Take the smallest range since we want both the // splines to be valid there. // This range as well as all the data needed to compute // the integrand is put into a struct to be passed // through the integrator to the function above. data.chimin = chimin_x>chimin_y ? chimin_x : chimin_y; data.chimax = chimax_x<chimax_y ? chimax_x : chimax_y; data.WbX = WbX; data.WfX = WfX; data.WmX = WmX; data.WbY = WbY; data.WfY = WfY; data.WmY = WmY; data.P = P; data.f = f;//new data.D = D;//new data.BB = BB;//new data.accelerator_xb = gsl_interp_accel_alloc(); data.accelerator_xf = gsl_interp_accel_alloc(); data.accelerator_xm = gsl_interp_accel_alloc(); data.accelerator_yb = gsl_interp_accel_alloc(); data.accelerator_yf = gsl_interp_accel_alloc(); data.accelerator_ym = gsl_interp_accel_alloc(); // Set up the workspace and inputs to the integrator. // Not entirely sure what the table is. gsl_function F; F.function = integrand; F.params = &data; //gsl_integration_workspace * workspace = gsl_integration_workspace_alloc(2048); // results of the integration go into these arrays. double c_ell_vector[config->n_ell]; double ell_vector[config->n_ell]; // loop through ell values according to the input configuration for (int i_ell = 0; i_ell<config->n_ell; i_ell++){ double ell = config->ell[i_ell]; data.ell=ell; // Perform the main integration. // This particular function is used because that's what Matt Becker // found to work best. //c_ell = gsl_integration_glfixed(&F,data.chimin,data.chimax,table); // New function still attributable to the legacy of Matt Becker's integrator wisdom. // gsl_integration_qag(&F, data.chimin, data.chimax, abstol, reltol, LIMBER_FIXED_TABLE_SIZE, GSL_INTEG_GAUSS61, W, table, &c_ell, &error); //printf("%d %f %f\n",i_ell,c_ell_old,c_ell); limber_gsl_fallback_integrator(&F, data.chimin, data.chimax, abstol, reltol, &c_ell, &error); //Include the prefactor scaling c_ell *= config->prefactor; // Record the results into arrays c_ell_vector[i_ell] = c_ell; ell_vector[i_ell] = ell; } // It is often useful to interpolate into the logs of the functions // This is optional in the config. We move this outside the main loop // since we may have all zeros in the output if (config->xlog) { for (int i_ell = 0; i_ell<config->n_ell; i_ell++){ ell_vector[i_ell] = log(ell_vector[i_ell]); } } if (config->ylog){ for (int i_ell = 0; i_ell<config->n_ell; i_ell++){ if (c_ell_vector[i_ell]<0){ config->status = LIMBER_STATUS_NEGATIVE; } // negative is worse than zero so only set to zero it not already negative else if ((c_ell_vector[i_ell]==0) && (config->status<LIMBER_STATUS_ZERO)){ config->status = LIMBER_STATUS_ZERO; } } // If none of the values are <= 0 then we are okay to go ahead and take the logs. if (config->status == LIMBER_STATUS_OK){ for (int i_ell = 0; i_ell<config->n_ell; i_ell++) c_ell_vector[i_ell] = log(c_ell_vector[i_ell]); } } // Create a spline of the arrays as the output gsl_spline * output = gsl_spline_alloc(gsl_interp_akima, (size_t) config->n_ell); gsl_spline_init(output, ell_vector, c_ell_vector, (size_t) config->n_ell); // Tidy up gsl_interp_accel_free(data.accelerator_xb); gsl_interp_accel_free(data.accelerator_yb); gsl_interp_accel_free(data.accelerator_xf); gsl_interp_accel_free(data.accelerator_yf); gsl_interp_accel_free(data.accelerator_xm); gsl_interp_accel_free(data.accelerator_ym); // These two are not deallocated because they are static and only initialized once. // gsl_integration_glfixed_table_free(table); // gsl_integration_workspace_free(W); // And that's it return output; }
{ "alphanum_fraction": 0.699739098, "avg_line_length": 34.6640826873, "ext": "c", "hexsha": "4a64ea7f76e1b8def2916d857b95842d2f210e5a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/limber.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "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": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/limber.c", "max_line_length": 141, "max_stars_count": 1, "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/limber.c", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "num_tokens": 4231, "size": 13415 }
/* ################################################################################## */ /* ### ### */ /* ### Gadgetmp2 ### */ /* ### ### */ /* ### Original: Gadget2 in the version used in Amuse ### */ /* ### Author: Gadget2 and Amuse contributors ### */ /* ### ### */ /* ### Modified: July 2020 ### */ /* ### Author: Thomas Schano ### */ /* ### ### */ /* ### Changes are intended to enable precise calculations in ### */ /* ### non periodic small domain simulations in which comoving parts ### */ /* ### are simulated in std precision ### */ /* ### ### */ /* ################################################################################## */ #include "src/tags.hpp" #include <gsl/gsl_rng.h> #include "src/proto.hpp" typedef struct { my_float mass; /// mass my_float x, y, z; /// position my_float vx, vy, vz; /// velocity my_float radius; /// radius } dynamics_state; typedef struct { my_float mass; /// mass my_float x, y, z; /// position my_float vx, vy, vz; /// velocity my_float u; /// entropy #ifdef MORRIS97VISC my_float alpha, dalphadt; ///viscosity #endif } sph_state; //void gadgetmp2::begrun(void); //double gadgetmp2::second(void); int found_particle(int index_of_the_particle, int *local_index); void update_particle_map(void); /*void gadgetmp2::hydro_state_at_point(double pos[3], double vel[3], double *h_out, double *ngb_out, double *dhsml_out, double *rho_out, double *rhov_out, double *rhov2_out, double *rhoe_out); */
{ "alphanum_fraction": 0.3321212121, "avg_line_length": 51.5625, "ext": "h", "hexsha": "040f6887cc61fb37647f02e4abaf1f95f01f578f", "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": "ff9e1ff6904e191f6b5a2e6f84c078062f553293", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "GFTwrt/amuse", "max_forks_repo_path": "src/amuse/community/gadgetmp2/interface.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ff9e1ff6904e191f6b5a2e6f84c078062f553293", "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": "GFTwrt/amuse", "max_issues_repo_path": "src/amuse/community/gadgetmp2/interface.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "ff9e1ff6904e191f6b5a2e6f84c078062f553293", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "GFTwrt/amuse", "max_stars_repo_path": "src/amuse/community/gadgetmp2/interface.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 395, "size": 2475 }
//! \file heat_driver.h //! Driver for Magnolia's heat transfer solver #ifndef ENRICO_SURROGATE_HEAT_DRIVER_H #define ENRICO_SURROGATE_HEAT_DRIVER_H #include "enrico/geom.h" #include "enrico/heat_fluids_driver.h" #include <gsl/gsl> #include <mpi.h> #include <pugixml.hpp> #include <xtensor/xtensor.hpp> #include <cstddef> namespace enrico { //! Struct containing geometric information for a flow channel struct Channel { //! Channel index int index_; //! Channel flow area double area_; //! Vector of rod IDs connected to this channel, all with a fractional perimeter //! in contact with the channel equal to 0.25 std::vector<std::size_t> rod_ids_; }; //! Struct containing geometry information for a cylindrical solid rod struct Rod { //! Rod index int index_; //! Rod cladding outer radius double clad_outer_radius_; //! Rod cladding inner radius double clad_inner_radius_; //! Rod pellet radius double pellet_radius_; //! Vector of channel IDs connected to this rod, all with a fractional perimeter //! in contact with the rod equal to 0.25 std::vector<std::size_t> channel_ids_; }; //! Class to construct flow channels for a Cartesian lattice of pins class ChannelFactory { public: ChannelFactory(double pitch, double rod_radius) : pitch_(pitch) , radius_(rod_radius) , interior_area_(pitch_ * pitch_ - M_PI * radius_ * radius_) {} //! Make a corner subchannel connected to given rods Channel make_corner(const std::vector<std::size_t>& rods) const { Channel c; c.index_ = index_++; c.area_ = 0.25 * interior_area_; c.rod_ids_ = rods; return c; } //! Make an edge subchannel connected to given rods Channel make_edge(const std::vector<std::size_t>& rods) const { Channel c; c.index_ = index_++; c.area_ = 0.5 * interior_area_; c.rod_ids_ = rods; return c; } //! Make an interior subchannel connected to given rods Channel make_interior(const std::vector<std::size_t>& rods) const { Channel c; c.index_ = index_++; c.area_ = interior_area_; c.rod_ids_ = rods; return c; } private: //! rod pitch double pitch_; //! rod outer radius double radius_; //! interior channel flow area, which is proportional to flow areas for all //! other channel types double interior_area_; //! index of constructed channel static int index_; }; class RodFactory { public: RodFactory(double clad_OR, double clad_IR, double pellet_OR) : clad_outer_r_(clad_OR) , clad_inner_r_(clad_IR) , pellet_outer_r_(pellet_OR) {} //! Make a rod connected to given channels Rod make_rod(const std::vector<std::size_t>& channels) const { Rod r; r.index_ = index_++; r.clad_inner_radius_ = clad_inner_r_; r.clad_outer_radius_ = clad_outer_r_; r.pellet_radius_ = pellet_outer_r_; r.channel_ids_ = channels; return r; } private: //! Cladding outer radius double clad_outer_r_; //! Cladding inner radius double clad_inner_r_; //! Pellet outer radius double pellet_outer_r_; //! Index of constructed rod static int index_; }; /** * Class providing surrogate thermal-hydraulic solution for a Cartesian * bundle of rods with upwards-flowing coolant. A conduction model is used * for the solid phase, with axial conduction neglected. The solid phase is * linked to the fluid phase by conjugate heat transfer, which is treated * here with a pseudo-steady-state approach where the power entering the fluid * matches the power in the rod at that axial elevation. It is assumed that * there is zero thermal resistance between the rod and the fluid. * * The fluid solution is obtained with a very simplified "subchannel" method * that neglects all crossflow terms between channels such that the method * is more akin to a single-pin analysis in a coolant-centered basis. The * enthalpy is solved by simply axial energy balance, while the axial momentum * equation is solved for pressure (the mass flow rate in each channel being * fixed) while neglecting friction effects. */ class SurrogateHeatDriver : public HeatFluidsDriver { public: //! Initializes heat-fluids surrogate with the given MPI communicator. //! //! \param comm The MPI communicator used to initialze the surrogate //! \param node XML node containing settings for surrogate explicit SurrogateHeatDriver(MPI_Comm comm, pugi::xml_node node); //! Verbosity options for printing simulation results enum class verbose { NONE, LOW, HIGH }; bool has_coupling_data() const final { return comm_.rank == 0; } //! Get the number of local mesh elements //! \return Number of local mesh elements int n_local_elem() const override; //! Get the number of global mesh elements //! \return Number of global mesh elements std::size_t n_global_elem() const override; //! Set the heat source for a given local element //! //! \param local_elem A local element ID //! \param heat A heat source term //! \return Error code int set_heat_source_at(int32_t local_elem, double heat) override; //! Solves the heat-fluids surrogate solver void solve_step() final; void solve_heat(); void solve_fluid(); //! Returns Number of rings in fuel and clad std::size_t n_rings() const { return n_fuel_rings_ + n_clad_rings_; } //! Returns cladding inner radius double clad_inner_radius() const { return clad_inner_radius_; } //! Returns cladding outer radius double clad_outer_radius() const { return clad_outer_radius_; } //! Returns pellet outer radius double pellet_radius() const { return pellet_radius_; } //! Returns number of fuel rings std::size_t n_fuel_rings() const { return n_fuel_rings_; } //! Returns number of clad rings std::size_t n_clad_rings() const { return n_clad_rings_; } //! Returns number of pins in x-direction std::size_t n_pins_x() const { return n_pins_x_; } //! Returns number of pins in y-direction std::size_t n_pins_y() const { return n_pins_y_; } //! Returns pin pitch double pin_pitch() const { return pin_pitch_; } //! Returns inlet temperature boundary condition in [K] double inlet_temperature() const { return inlet_temperature_; } //! Returns inlet mass flowrate boundary condition in [kg/s] double mass_flowrate() const { return mass_flowrate_; } //! Returns maximum number of subchannel iterations std::size_t max_subchannel_its() const { return max_subchannel_its_; } //! Returns subchannel convergence tolerance for enthalpy double subchannel_tol_h() const { return subchannel_tol_h_; } //! Returns subchannel convergence tolerance for pressure double subchannel_tol_p() const { return subchannel_tol_p_; } //! Returns convergence tolerance for solid energy equation double heat_tol() const { return heat_tol_; } //! Write data to VTK void write_step(int timestep, int iteration) final; //! Returns solid temperature in [K] for given region double solid_temperature(std::size_t pin, std::size_t axial, std::size_t ring) const; //! Returns fluid density in [g/cm^3] for given region double fluid_density(std::size_t pin, std::size_t axial) const; //! Returns fluid temperature in [K] for given region double fluid_temperature(std::size_t pin, std::size_t axial) const; // Data on fuel pins xt::xtensor<double, 2> pin_centers_; //!< (x,y) values for center of fuel pins xt::xtensor<double, 1> z_; //!< Bounding z-values for axial segments std::size_t n_axial_; //!< number of axial segments std::size_t n_azimuthal_{4}; //!< number of azimuthal segments //! Total number of pins std::size_t n_pins_; // Dimensions for a single fuel pin axial segment double clad_outer_radius_; //!< clad outer radius in [cm] double clad_inner_radius_; //!< clad inner radius in [cm] double pellet_radius_; //!< fuel pellet radius in [cm] std::size_t n_fuel_rings_{20}; //!< number of fuel rings std::size_t n_clad_rings_{2}; //!< number of clad rings //!< Channels in the domain std::vector<Channel> channels_; //!< Rods in the domain std::vector<Rod> rods_; //! Mass flowrate for coolant-centered channels; this is determine by distributing //! a total inlet mass flowrate among the channels based on the fractional flow area. xt::xtensor<double, 1> channel_flowrates_; // solver variables and settings xt::xtensor<double, 4> source_; //!< heat source for each (pin, axial segment, ring, azimuthal segment) xt::xtensor<double, 1> r_grid_clad_; //!< radii of each clad ring in [cm] xt::xtensor<double, 1> r_grid_fuel_; //!< radii of each fuel ring in [cm] //! Cross-sectional areas of rings in fuel and cladding xt::xtensor<double, 1> solid_areas_; // visualization std::string viz_basename_{ "heat_surrogate"}; //!< base filename for visualization files (default: magnolia) std::string viz_iterations_{ "none"}; //!< visualization iterations to write (none, all, final) std::string viz_data_{"all"}; //!< visualization data to write std::string viz_regions_{"all"}; //!< visualization regions to write size_t vtk_radial_res_{20}; //!< radial resolution of resulting vtk files private: //! Get temperature of local mesh elements //! \return Temperature of local mesh elements in [K] std::vector<double> temperature_local() const override; //! Get density of local mesh elements //! \return Density of local mesh elements in [g/cm^3] std::vector<double> density_local() const override; //! States whether each local region is in fluid //! \return For each local region, 1 if region is in fluid and 0 otherwise std::vector<int> fluid_mask_local() const override; //! Get centroids of local mesh elements //! \return Centroids of local mesh elements std::vector<Position> centroid_local() const override; //! Get volumes of local mesh elements //! \return Volumes of local mesh elements std::vector<double> volume_local() const override; //! Create internal arrays used for heat equation solver void generate_arrays(); //! Channel index in terms of row, column index int channel_index(int row, int col) const { return row * (n_pins_x_ + 1) + col; } //! Rod power at a given node in a given pin, computed by integrating the heat source //! (assumed constant in each ring) over the pin. //! \param pin pin index //! \param axial axial index double rod_axial_node_power(const int pin, const int axial) const; //! Diagnostic function to assess whether the mass is conserved by the subchannel //! solver by comparing the mass flowrate in each axial plane (at cell-centered //! positions) to the specified inlet mass flowrate. //! \param rho density in a cell-centered basis //! \param u axial velocity in a face-centered basis bool is_mass_conserved(const xt::xtensor<double, 2>& rho, const xt::xtensor<double, 2>& u) const; //! Diagnostic function to assess whether the energy is conserved by the subchannel //! solver by comparing the energy deposition in each channel in each axial plane //! (at cell-centered positions) to the powers of the rods connected to that channel. //! \param rho density in a cell-centered basis //! \param u axial velocity in a face-centered basis //! \param h enthalpy in a face-centered basis //! \param q powers in each channel in a cell-centered basis bool is_energy_conserved(const xt::xtensor<double, 2>& rho, const xt::xtensor<double, 2>& u, const xt::xtensor<double, 2>& h, const xt::xtensor<double, 2>& q) const; //!< solid temperature in [K] for each (pin, axial segment, ring) xt::xtensor<double, 3> solid_temperature_; //! Flow areas for coolant-centered channels xt::xtensor<double, 1> channel_areas_; //! Fluid temperature in a rod-centered basis indexed by rod ID and axial ID xt::xtensor<double, 2> fluid_temperature_; //! Fluid density in [g/cm^3] in a rod-centered basis indexed by rod ID and axial ID xt::xtensor<double, 2> fluid_density_; //! Number of pins in the x-direction in a Cartesian grid std::size_t n_pins_x_; //! Number of pins in the y-direction in a Cartesian grid std::size_t n_pins_y_; //! Pin pitch, assumed the same for the x and y directions double pin_pitch_; //! Inlet fluid temperature [K] double inlet_temperature_; //! Mass flowrate of fluid into the domain [kg/s] double mass_flowrate_; //! Number of channels std::size_t n_channels_; //! Maximum number of iterations for subchannel solution, set to a default value //! of 100 if not set by the user int max_subchannel_its_ = 100; //! Convergence tolerance on enthalpy for the subchannel solution for use in //! convergence based on the L-1 norm, set to a default value of 1e-2 double subchannel_tol_h_ = 1e-2; //! Convergence tolerance on pressure for the subchannel solution for use in //! convergence based on the L-1 norm, set to a default value of 1e-2 double subchannel_tol_p_ = 1e-2; //! Convergence tolerance for solid temperature solution, set to a default value //! of 1e-4 double heat_tol_ = 1e-4; //! Gravitational acceleration const double g_ = 9.81; //! Verbosity setting for printing simulation results; defaults to NONE verbose verbosity_ = verbose::NONE; }; // end SurrogateHeatDriver } // namespace enrico #endif // ENRICO_SURROGATE_HEAT_DRIVER_H
{ "alphanum_fraction": 0.71087181, "avg_line_length": 33.895, "ext": "h", "hexsha": "4fa134e88c81e6b5de66c28e254de49c266845b8", "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": "edd04f1e02caf1c3fae2992e55d9a47e4429655c", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "lebuller/enrico", "max_forks_repo_path": "include/enrico/surrogate_heat_driver.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_issues_repo_issues_event_max_datetime": "2020-06-15T15:30:51.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-14T18:14:35.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pshriwise/enrico", "max_issues_repo_path": "include/enrico/surrogate_heat_driver.h", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pshriwise/enrico", "max_stars_repo_path": "include/enrico/surrogate_heat_driver.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3366, "size": 13558 }
#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 <gsl/gsl_statistics_float.h> #include "rank.h" #include "stattest.h" #include "num.h" typedef float con_t; struct ConCovars { /** * Maximum number of samples */ int SAMPLE_CAPACITY; /** * Count of samples pushed since last con_clear. */ int sample_count; /** * The total amount of malloc'ed space (for the purposes * of fast clearing with memset). */ size_t SIZEOF_BUFFERS; /** * Two buffers */ con_t *l, *r; void *rank_scratch; }; #if defined(_UNITTEST_NUM_) static void dbg_dump( struct ConCovars *co, FILE *fp ) { for(unsigned int i = 0; i < co->sample_count; i++ ) fprintf( fp, "%f\t%f\n", co->l[i], co->r[i] ); } #endif void con_destroy( void *pv ) { if( pv ) { struct ConCovars *co = (struct ConCovars *)pv; if( co->rank_scratch ) rank_free( co->rank_scratch ); if( co->l ) free( co->l ); 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 *con_create( unsigned int cap ) { struct ConCovars *co = calloc( 1, sizeof(struct ConCovars) ); if( co ) { co->SAMPLE_CAPACITY = cap; co->SIZEOF_BUFFERS = 2*cap*sizeof(con_t); // Allocate one large buffer and partition it up. co->l = calloc( co->SIZEOF_BUFFERS, sizeof(char) ); co->r = co->l + cap; co->rank_scratch = rank_alloc( cap ); // If -anything- failed clean up any successes. if( (NULL == co->l) || (NULL == co->rank_scratch) ) { con_destroy( co ); return NULL; } return co; } return NULL; } void con_clear( void *pv ) { struct ConCovars *co = (struct ConCovars *)pv; co->sample_count = 0; memset( co->l, 0, co->SIZEOF_BUFFERS ); } void con_push( void *pv, float n1, float n2 ) { struct ConCovars *co = (struct ConCovars *)pv; const int i = co->sample_count++; assert( i <= co->SAMPLE_CAPACITY ); co->l[i] = n1; co->r[i] = n2; } size_t con_size( void *pv ) { return ((struct ConCovars *)pv)->sample_count; } bool con_complete( void *pv ) { return ((struct ConCovars *)pv)->sample_count > 2; // ...otherwise p-value computation will fail. } /** */ int con_spearman_correlation( void *pv, struct Statistic *result ) { struct ConCovars *co = (struct ConCovars *)pv; const int N = co->sample_count; assert( N > 2 ); assert( NULL != co->rank_scratch ); const int rinfo1 = rank_floats( co->l, N, 0, co->rank_scratch ); const int rinfo2 = rank_floats( co->r, N, 0, co->rank_scratch ); if( RANK_STATUS_CONST & rinfo1 ) // vectors were in fact constant! result->extra_value[0] = N-1; if( RANK_STATUS_CONST & rinfo2 ) result->extra_value[1] = N-1; { const double rho = gsl_stats_float_correlation( co->l, 1, co->r, 1, N ); /** * P-value computation for the correlation. */ #ifdef HAVE_FISHER_TRANSFORM const double FisherTransform //= 0.5 * log( (1.+rho) / (1.-rho) ); = atanh(rho); // ...absolute value to simplify CDF use below, since the // transformation is symmetric. const double z = sqrt( (N - 3.0) / 1.06 ) * FisherTransform; // ...z ~ N(0,1) under null hyp of statistical independence. result->name = "Spearman_rho,Fisher_transform"; result->probability = gsl_cdf_ugaussian_Q( fabs(z) ); #else const double t = fabs( rho*sqrt((N-2.0)/(1.0-rho*rho)) ); // ...abs so that I can always test the upper tail. // x2 below to make it a two-tailed test. (t-distribution // is symmetric). result->name = "Spearman_rho,t-distribution"; result->probability = 2* gsl_cdf_tdist_Q(t,N-2.0); #endif result->value = rho; } result->sample_count = N; return 0; } #ifdef HAVE_SCALAR_PEARSON int con_pearson_correlation( void *pv, struct Statistic *result ) { struct ConCovars *co = (struct ConCovars *)pv; const int N = co->sample_count; ps->rho = gsl_stats_float_correlation( co->l, 1, co->r, 1, N ); return 0; } #endif #ifdef _UNITTEST_NUM_ /** * This is intended to be exercised with the following R script * that generates a small table of grouped floating-point values * executes a Kruskal-Wallis test on it, and dumps the table * to a tab-delimited file with the test results as a comment on * the first line. * * x <- data.frame( * cat=as.integer(gl(3,4))-1, * num=c( runif(4)*10, runif(4)*20, 10+runif(4)*10 ) ); * k <- with( x, kruskal.test( num, cat ) ); * cat( sprintf( "# K=%f p-value=%f\n", k$statistic, k$p.value ), file="foo.tab" ); * write.table( x, 'foo.tab', quote=F, sep='\t', row.names=F, col.names=F, append=TRUE ); */ #include <err.h> int main( int argc, char *argv[] ) { if( argc >= 2 ) { struct Statistic result; struct ConCovars *accum = con_create( atoi(argv[1]) ); FILE *fp = argc > 2 ? fopen( argv[2], "r" ) : stdin; char *line = NULL; size_t n = 0; con_clear( accum ); while( getline( &line, &n, fp ) > 0 ) { float l, r; if( line[0] == '#' ) { fputs( line, stdout ); continue; } if( 2 == sscanf( line, "%f\t%f\n", &l, &r ) ) { con_push( accum, l, r ); } else { fprintf( stderr, "Failure parsing line: %s", line ); } } free( line ); fclose( fp ); memset( &result, 0, sizeof(struct Statistic) ); #ifdef HAVE_SCALAR_PEARSON con_pearson_correlation( accum, &result ); printf( "pearson=%f\n", result.value ); #endif memset( &result, 0, sizeof(struct Statistic) ); if( con_spearman_correlation( accum, &result ) == 0 ) { printf( "p-value=%f, spearman=%f\n", result.probability, result.value ); } else printf( "error\n" ); con_destroy( accum ); } else err( -1, "%s <sample count> [ <input file> ]", argv[0] ); return 0; } #endif
{ "alphanum_fraction": 0.631154572, "avg_line_length": 22.76953125, "ext": "c", "hexsha": "cfacd9060e5d05270c34ed3a948f23fd7de5b93e", "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/num.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/num.c", "max_line_length": 89, "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/num.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": 1890, "size": 5829 }
/** \file * This file contains an implementation of a MPMC queue by Dmitry Vyukov. It is * largely the same as the original source except for: minor formatting * changes, movement to a namespace, use of alignas(X) instead of pad variables, * and use of dyn_array from the guideline support library instead of * `new char[size]`. */ /* Multi-producer/multi-consumer bounded queue. * http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue * * Copyright (c) 2010-2011, Dmitry Vyukov. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "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 DMITRY VYUKOV 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of Dmitry Vyukov. */ #include <cassert> #include <atomic> #include <gsl_p/dyn_array.h> namespace dvyukov { /** * A 'lockless' bounded multi-producer, multi-consumer queue * * Has the caveat that the queue can *appear* empty even if there are * returned items within it as a single thread can block progression * of the queue. */ template<typename T> class mpmc_bounded_queue { public: /** * Constructs a bounded multi-producer, multi-consumer queue * * Note: Due to the algorithm used, buffer_size must be a power * of two and must be greater than or equal to two. * * @param buffer_size Number of spaces available in the queue. */ mpmc_bounded_queue(size_t buffer_size) : buffer_(buffer_size), buffer_mask_(buffer_size - 1) { assert((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0)); for (size_t i = 0; i != buffer_size; i += 1) { buffer_[i].sequence_.store(i, std::memory_order_relaxed); } enqueue_pos_.store(0, std::memory_order_relaxed); dequeue_pos_.store(0, std::memory_order_relaxed); } /** * Enqueues an item into the queue * * @param data Argument to place into the array * @return false if the queue was full (and enqueing failed), * true otherwise */ bool enqueue(const T& data) { cell_t *cell; size_t pos = enqueue_pos_.load(std::memory_order_relaxed); for (; ;) { cell = &buffer_[pos & buffer_mask_]; size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = (intptr_t) seq - (intptr_t) pos; if (dif == 0) { if (enqueue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) { break; } } else if (dif < 0) { return false; } else { pos = enqueue_pos_.load(std::memory_order_relaxed); } } cell->data_ = data; cell->sequence_.store(pos + 1, std::memory_order_release); return true; } /** * Dequeues an item from the queue * * @param[out] data Reference to place item into * @return false if the queue was empty (and dequeuing failed), * true if successful */ bool dequeue(T& data) { cell_t *cell; size_t pos = dequeue_pos_.load(std::memory_order_relaxed); for (; ;) { cell = &buffer_[pos & buffer_mask_]; size_t seq = cell->sequence_.load(std::memory_order_acquire); intptr_t dif = (intptr_t) seq - (intptr_t) (pos + 1); if (dif == 0) { if (dequeue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed)) { break; } } else if (dif < 0) { return false; } else { pos = dequeue_pos_.load(std::memory_order_relaxed); } } data = cell->data_; cell->sequence_.store(pos + buffer_mask_ + 1, std::memory_order_release); return true; } private: struct cell_t { std::atomic<size_t> sequence_; T data_; }; static const size_t cacheline_size = 64; typedef char cacheline_pad_t [cacheline_size]; cacheline_pad_t pad0_; gsl_p::dyn_array<cell_t> buffer_; const size_t buffer_mask_; cacheline_pad_t pad1_; std::atomic<size_t> enqueue_pos_; cacheline_pad_t pad2_; std::atomic<size_t> dequeue_pos_; cacheline_pad_t pad3_; mpmc_bounded_queue(mpmc_bounded_queue const &); void operator=(mpmc_bounded_queue const &); }; }
{ "alphanum_fraction": 0.5848256362, "avg_line_length": 38.5818181818, "ext": "h", "hexsha": "cf0a861f8db935b48c204804753e31e8793e99cb", "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": "thirdparty/dvyukov/include/dvyukov/mpmc_bounded_queue.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": "thirdparty/dvyukov/include/dvyukov/mpmc_bounded_queue.h", "max_line_length": 88, "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": "thirdparty/dvyukov/include/dvyukov/mpmc_bounded_queue.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1396, "size": 6366 }
#pragma once #include <gsl/gsl> #include <memory> #include <atlcomcli.h> #include "textures.h" struct ID3D11Texture2D; struct ID3D11DeviceContext; struct ID3D11RenderTargetView; struct ID3D11ShaderResourceView; struct ID3D11DepthStencilView; namespace gfx { enum class BufferFormat; class DynamicTexture : public Texture { friend class RenderingDevice; public: DynamicTexture(ID3D11DeviceContext *context, ID3D11Texture2D *texture, ID3D11ShaderResourceView *resourceView, const Size &size, uint32_t bytesPerPixel); int GetId() const override; const std::string& GetName() const; const ContentRect& GetContentRect() const override { return mContentRect; } const Size& GetSize() const override { return mSize; } TextureType GetType() const override { return TextureType::Dynamic; } // Unloads the device texture (does't prevent it from being loaded again later) void FreeDeviceTexture() override; ID3D11ShaderResourceView* GetResourceView() override { return mResourceView; } uint32_t GetBytesPerPixel() const { return mBytesPerPixel; } template<typename T> void Update(gsl::span<T> data) { UpdateRaw( gsl::span(reinterpret_cast<uint8_t*>(&data[0]), data.size_bytes()), mSize.width * sizeof(T) ); } private: void UpdateRaw(gsl::span<uint8_t> data, size_t pitch); CComPtr<ID3D11DeviceContext> mContext; CComPtr<ID3D11Texture2D> mTexture; CComPtr<ID3D11ShaderResourceView> mResourceView; Size mSize; size_t mBytesPerPixel; ContentRect mContentRect; }; using DynamicTexturePtr = std::shared_ptr<DynamicTexture>; class RenderTargetTexture : public Texture { friend class RenderingDevice; public: RenderTargetTexture(ID3D11Texture2D *texture, ID3D11RenderTargetView *rtView, ID3D11Texture2D *resolvedTexture, ID3D11ShaderResourceView *resourceView, const Size &size, bool multiSampled); int GetId() const override; const std::string& GetName() const; const ContentRect& GetContentRect() const override { return mContentRect; } const Size& GetSize() const override { return mSize; } TextureType GetType() const override { return TextureType::RenderTarget; } // Unloads the device texture (does't prevent it from being loaded again later) void FreeDeviceTexture() override; /** * Only valid for MSAA targets. Will return the texture used to resolve the multisampling * so it can be used as a shader resource. */ ID3D11Texture2D* GetResolvedTexture() const { return mResolvedTexture; } /** * For MSAA targets, this will return the resolvedTexture, while for normal targets, * this will just be the texture itself. */ ID3D11ShaderResourceView* GetResourceView() override { return mResourceView; } bool IsMultiSampled() const { return mMultiSampled; } gfx::BufferFormat GetFormat() const; private: CComPtr<ID3D11RenderTargetView> mRtView; CComPtr<ID3D11Texture2D> mTexture; CComPtr<ID3D11Texture2D> mResolvedTexture; CComPtr<ID3D11ShaderResourceView> mResourceView; Size mSize; ContentRect mContentRect; bool mMultiSampled; }; using RenderTargetTexturePtr = std::shared_ptr<RenderTargetTexture>; class RenderTargetDepthStencil { friend class RenderingDevice; public: RenderTargetDepthStencil(ID3D11Texture2D *textureNew, ID3D11DepthStencilView *dsView, const Size &size); const Size& GetSize() const { return mSize; } private: CComPtr<ID3D11DepthStencilView> mDsView; CComPtr<ID3D11Texture2D> mTextureNew; Size mSize; }; using RenderTargetDepthStencilPtr = std::shared_ptr<RenderTargetDepthStencil>; }
{ "alphanum_fraction": 0.7451033732, "avg_line_length": 21.880952381, "ext": "h", "hexsha": "663755e52fb07f240867ccb699dfe29af15b9722", "lang": "C", "max_forks_count": 25, "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_path": "Infrastructure/include/graphics/dynamictexture.h", "max_issues_count": 457, "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_path": "Infrastructure/include/graphics/dynamictexture.h", "max_line_length": 91, "max_stars_count": 69, "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_path": "Infrastructure/include/graphics/dynamictexture.h", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "num_tokens": 993, "size": 3676 }
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @file pgp.c @brief Interface to pgplot Some usage of pgplot.Functionality goes like this: With filling the struct pgp_gdsc the user defines a layout of a plot, which consists of a number of viewgraphs with the same x-axis range. A default struct of that type is delivered by the routine pgp_default. A pgplot device is activated (and must be activated) by calling the routine pgp_opendev(). Then, a box is drawn by calling the routine pgp_openbox. With a call of that function an appropriate pgplot viewport is defined to enable the user to plot his viewgraph in the box by calling functions pgp_marker(), pgp_lines(), pgp_bars(), and pgp_errby(). With pgp_legend(), a string can be plotted to a legend line. The routine pgp_end() will terminate the plotting process properly. An example can be accessed with testpgp.c. $Source: /Volumes/DATA_J_II/data/CVS/tirific/src/pgp.c,v $ $Date: 2011/05/25 22:25:26 $ $Revision: 1.14 $ $Author: jozsa $ $Log: pgp.c,v $ Revision 1.14 2011/05/25 22:25:26 jozsa Left work Revision 1.13 2011/05/10 00:30:16 jozsa Left work Revision 1.12 2009/05/26 07:56:41 jozsa Left work Revision 1.11 2007/08/22 15:58:43 gjozsa Left work Revision 1.10 2006/11/22 14:16:21 gjozsa Bugfix concerning RASH and horizontal/vertical lines Revision 1.9 2006/11/03 10:49:02 gjozsa Introduced logarithmic scaling, hms dms Revision 1.8 2006/10/05 12:39:58 gjozsa nasty bugfix Revision 1.7 2006/04/03 11:47:57 gjozsa Left work Revision 1.6 2006/02/08 16:13:17 gjozsa Extended graphics routines Revision 1.5 2005/10/12 14:51:25 gjozsa First point gets thick in the polar plot Revision 1.4 2005/10/12 09:53:09 gjozsa Included polar plot facility Revision 1.3 2005/06/24 12:00:29 gjozsa Left work Revision 1.2 2005/05/24 10:42:24 gjozsa Left work Revision 1.1 2005/05/17 12:58:15 gjozsa Added to cvs control */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* EXTERNAL INCLUDES */ /* ------------------------------------------------------------ */ #include <stdio.h> #include <cpgplot.h> #include <math.h> #include <string.h> #include <float.h> #include <stdlib.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* INTERNAL INCLUDES */ /* ------------------------------------------------------------ */ #include <pgp.h> #include <maths.h> /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @def _MEMORY_HERE_ON @brief Controls the use of the memory_here module If you don't want to use the memory_here facility comment this define, otherways it will be included. */ /* ------------------------------------------------------------ */ /* #define _MEMORY_HERE_ON */ /* #include <memory_here.h> */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* PRIVATE SYMBOLIC CONSTANTS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @define DEGTORAD @brief Conversion factor from deg to rad */ /* ------------------------------------------------------------ */ #define DEGTORAD 0.0174532925199433 /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @define LOGFAULT @brief If a logarithm is asked for for a negative number or 0 this should be redurned */ /* ------------------------------------------------------------ */ #define LOGFAULT -40 /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* PRIVATE MACROS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* (PRIVATE) GLOBAL VARIABLES */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* PRIVATE TYPEDEFS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* PRIVATE STRUCTS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* PRIVATE FUNCTION DECLARATIONS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int putalabel(char where, char *overfrac, char underfrac, float charheight, float xmin, float xmax) @brief Puts a label at a viewgraph as a fraction Requires an open viewgraph, and the character height set to the axis numbering height. If both overfrac and underfrac are filled, then a fraction will be plotted. If one of both is an empty string (not NULL), then no fraction bar will be plotted. @param where (char) t, b, l, r position of the label @param overfrac (char *) Text above the fraction bar @param underfrac (char *) Text below the fraction bar @param charheight (float) Character height relative to the actual character height, which should be set to the numbering height. @param dist (float) Distance from the axis baseline in units of the initial height @return (success) int putalabel: 1\\ (error) 0 */ /* ------------------------------------------------------------ */ int putalabel(char where, char *overfrac, char *underfrac, float charheight, float dist); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn float pgp_logf10f(float x) @brief Returns the logarithm on basis 10 and LOGFAULT if x <= 0 @param x (float) number to calculate the logarithm of @return logarithm of the number or, if impossible, LOGFAULT */ /* ------------------------------------------------------------ */ float pgp_logf10f(float x); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn static int pgp_get_interparray(float *x, float *y, int npoints, int interptype, int nout, float **xout, float **yout) @brief Returns an array of interpolated values. Assumes an array of npoints x-y pairs as an input. Checks if x is strictly monotonically increasing. If *xout is not NULL, deallocates *xout. If *yout is not NULL, deallocates *yout. Allocates an array *xout of nout equally-spaced points with xout[0] = x[0] and xout[nout-1] = x[nout-1]. Allocates an array *yout of nout data points where the ith data point is an interpolation between x and y at the position xout[i]. interptype determines the interpolation type, which can be PGP_I_LINEAR: linear; PGP_I_CSPLINE: cubic natural spline; PGP_I_AKIMA: Akima . @param x (float * ) input data points, abscissae, must be strictly increasing @param y (float * ) input data points, ordinate @param npoints ( int ) input number of data points @param interptype ( int ) input interpolation type: PGP_I_LINEAR: linear; PGP_I_CSPLINE: cubic natural spline; PGP_I_AKIMA: Akima @param nout ( int ) input number of output data points @param xout (float **) output data array x-values (equally spaced) @param yout (float **) output data array y-values @return logarithm of the number or, if impossible, LOGFAULT */ /* ------------------------------------------------------------ */ static int pgp_get_interparray(float *x, float *y, int npoints, int interptype, int nout, float **xout, float **yout); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* FUNCTION CODE */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Opens the pgplot device as specified */ int pgp_opendev(char *device_name) { int val; if (device_name) if (device_name[0]) { val = cpgbeg(0,device_name,1,1); /* Has to be set 0 for use in gipsy */ cpgask(1); return val; } return 0; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Returns a default pgp_gdsc struct */ pgp_gdsc *pgp_gdsc_default(int nplots, int legendcols, int legendrows, float charheight) { pgp_gdsc *gdsc; /* int i; Control variable */ float chrhtx; /* Horizontal character width in x-map units, 1 is whole page */ float chrhty; /* Vertical character height in y-map units, 1 is whole page */ float chrhtxref; /* Reference charheight */ float scalexy; /* scale from x size of numbers to y size of numbers (is the same physical size, but in terms of window size they are different) */ float pltheight; /* Allocate */ if (!(gdsc = (pgp_gdsc *) malloc(sizeof(pgp_gdsc)))) return NULL; /* Find the reference */ cpgsch(1.0); cpgqcs(0, &chrhtxref, &chrhty); /* This is a scale */ scalexy = chrhty/chrhtxref; /* Now, the character height in window units is like this */ chrhtx = chrhtxref*charheight; /* Fill with default values */ /* Number of plots */ gdsc -> nplots = nplots; /* Symbols and descriptors in charheight, but at most one third??? of the plot height until the numbering is finished */ /* The height of the plot is 1.0 at the start */ pltheight = 1.0; /* The number is reduced by the axis description + 1 character */ pltheight = pltheight-12.3*chrhty; /* Then, for each legend line, two characters */ pltheight = pltheight-2.0*legendrows*chrhty; /* Then, each plot has only 1/nplots height */ pltheight = pltheight/nplots; /* At the end, each plot has a margin of 4 heights at the top for the numbering */ pltheight = pltheight-4.0*chrhty; /* We could express this as: */ /* (1.0-12.3*chrhty-2.0*legendrows*chrhty)/nplots-4.0*chrhty */ /* If this leaves room for 3 (???) numbers, then we apply the character height else we adjust the height */ if (chrhty*3 > pltheight) chrhty = 1/(12.3+2*legendrows+7.0*nplots); chrhtx= chrhty/scalexy; gdsc -> numberheight = chrhtx/chrhtxref; gdsc -> symbolheight = 1.0; gdsc -> legendheight = 1.0; gdsc -> axdescheight = 1.0; /* legend */ gdsc -> legendcols = legendcols; gdsc -> legendrows = legendrows; /* Horizontal and vertical borders are 2 characters */ gdsc -> verbord = 2.0; gdsc -> horbord = 2.0; /* Stop of the axis numbering is 2 characters, only for the top of the graph */ gdsc -> leftnum = 0.0; gdsc -> rightnum = 0.0; gdsc -> botnum = 0.0; gdsc -> topnum = 1.0; /* Margins */ gdsc -> leftmargin = 7.0; gdsc -> rightmargin = 7.0; gdsc -> bottommargin = 1.8; gdsc -> topmargin = 2.5; /* Linewidths */ gdsc -> graphlw = 1; gdsc -> boxlw = 1; /* reserve and return an initialised array for the axis labelling */ /* if (!(gdsc -> logarcsx = (int *) malloc(gdsc -> nplots*sizeof(int)))){ */ /* free(gdsc); */ /* return 0; */ /* } */ /* for (i = 0; i < gdsc -> nplots; ++i) */ /* gdsc -> logarcsx[i] = 0; */ /* reserve and return an initialised array for the axis labelling */ /* if (!(gdsc -> logarcsy = (int *) malloc(gdsc -> nplots*sizeof(int)))){ */ /* free(gdsc -> logarcsx); */ /* free(gdsc); */ /* return 0; */ /* } */ /* for (i = 0; i < gdsc -> nplots; ++i) */ /* gdsc -> logarcsy[i] = 0; */ gdsc -> logarcsx = 0; gdsc -> logarcsy = 0; gdsc -> interptype_lines = PGP_I_LINEAR; gdsc -> interp_numlines = 500; return gdsc; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Make a polar diagram on an open device */ void pgp_polar(int ndots, float *xarray, float *yarray, int nlines, float *xlarray, float *ylarray, int nradii, float *radiis, float *lineangle, int linewidth, int circlewidth, int symbolwidth, int colour) { int i; float rmax = 0; float twopointsx[2]; float twopointsy[2]; float xv1,yv1; float *radii; rmax = 0; /* Allocte memory for radii */ if (!(radii = (float *) malloc(nradii*sizeof(float)))) return; /* First find out about the extent of the graph */ for (i = 0; i < ndots; ++i) { if (rmax < fabs(xarray[i])) rmax = fabs(xarray[i]); if (rmax < fabs(yarray[i])) rmax = fabs(yarray[i]); } for (i = 0; i < nlines; ++i) { if (rmax < fabs(xlarray[i])) rmax = fabs(xlarray[i]); if (rmax < fabs(ylarray[i])) rmax = fabs(ylarray[i]); } /* We make a local copy of the radii */ for (i = 0; i < nradii; ++i) { radii[i] = fabs(radiis[i]); if (rmax < radii[i]) rmax = radii[i]; } /* Now scale rmax a bit */ rmax = rmax*1.02; /* Define a drawing area, must be quadratic */ cpgenv(-rmax, rmax, -rmax, rmax, 1, -2); /* Check the linewidths */ if (linewidth < 1) linewidth = 1; if (linewidth > 201) linewidth = 201; if (circlewidth < 1) circlewidth = 1; if (circlewidth > 201) circlewidth = 201; if (symbolwidth < 1) symbolwidth = 1; if (symbolwidth > 201) symbolwidth = 201; /* Set the colour index foreground */ cpgsci(1); /* Draw the circles */ if (nradii > 0) { cpgslw(circlewidth); /* Make the circles open */ cpgsfs(2); /* Chose a dashed style */ cpgsls(4); for (i = 0; i < (nradii-1); ++i) cpgcirc(0,0, radii[i]); /* Draw the last circle, solid line with double width, solid */ cpgsls(1); if (circlewidth > 100) circlewidth = 201; else circlewidth = 2*circlewidth; cpgslw(circlewidth); cpgcirc(0,0, radii[nradii-1]); /* Now do the Briggs style thingies */ twopointsx[0] = 0; twopointsx[1] = 0; twopointsy[0] = radii[nradii-1]; twopointsy[1] = radii[nradii-1]-0.05*radii[nradii-1]; cpgline(2, twopointsx, twopointsy); twopointsx[0] = 0; twopointsx[1] = 0; twopointsy[0] = -radii[nradii-1]; twopointsy[1] = -radii[nradii-1]+0.05*radii[nradii-1]; cpgline(2, twopointsx, twopointsy); twopointsy[0] = 0; twopointsy[1] = 0; twopointsx[0] = radii[nradii-1]; twopointsx[1] = radii[nradii-1]-0.05*radii[nradii-1]; cpgline(2, twopointsx, twopointsy); twopointsy[0] = 0; twopointsy[1] = 0; twopointsx[0] = -radii[nradii-1]; twopointsx[1] = -radii[nradii-1]+0.05*radii[nradii-1]; cpgline(2, twopointsx, twopointsy); /* Check whether to plot a point */ for (i = 0; i < (nradii); ++i) { if (radii[i] == 0){ xv1 = yv1 = 0; cpgpt(1, &xv1, &yv1, -1); } } } /* Draw the reference thing */ if ((lineangle)) { cpgslw(linewidth); twopointsy[0] = 0; twopointsy[1] = cos(DEGTORAD*(*lineangle))*radii[nradii-1]; twopointsx[0] = 0; twopointsx[1] = -sin(DEGTORAD*(*lineangle))*radii[nradii-1]; cpgline(2, twopointsx, twopointsy); } /* Plot the points */ /* Set the linewidth */ cpgslw(symbolwidth); /* Set the colour */ cpgsci(colour); /* Plot points, number of points, vectors for x and y, symbol */ if (ndots > 0) cpgpt(ndots, xarray, yarray, -1); /* Make a first dot */ symbolwidth *= 2; if (symbolwidth > 201) symbolwidth = 210; cpgslw(symbolwidth); cpgpt(1, xarray, yarray, -1); /* Draw the lines */ /* Set the linewidth */ if (nlines > 1) { cpgslw(linewidth); cpgline(nlines, xlarray, ylarray); } /* Finished */ return; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Opens a box in an opened window with a few specifications */ int pgp_openbox(pgp_gdsc *gdsc, int nplot, float xmin, float xmax, float ymin, float ymax, char *leftdeschi, char *leftdesclo, char *rightdeschi, char *rightdesclo, char *bottomdeschi, char *bottomdesclo, char *topdeschi, char *topdesclo, float lrzero, float lrscale, float btzero, float btscale, int logarcsx, int logarcsy) { float plotheight; float chrhtxref; /* Horizontal character width in x-map units, 1 is whole page */ float chrhtyref; /* Vertical character height in y-map units, 1 is whole page */ /* float scalexy; */ /* scale from x size of numbers to y size of numbers (or inverse scale of x to y size of area */ float dummy1, dummy2; int slw; /* Standard linewidth */ float xlo; /* Box in window coordinates */ float xhi; float ylo; float yhi; float xulo; /* Box in user coordinates */ float xuhi; float yulo; float yuhi; float xlo2; /* Another box in window coordinates */ float xhi2; float ylo2; float yhi2; float xulo2; /* Another box in user coordinates */ float xuhi2; float yulo2; float yuhi2; float ax, ay, bx, by; /* linear coefficients from window to user coordinates */ void (* boxingx)(const char *xopt, float xtick, int nxsub, const char *yopt, float ytick, int nysub); void (* boxingy)(const char *xopt, float xtick, int nxsub, const char *yopt, float ytick, int nysub); char steringxt[8],steringxb[8],steringyl[8],steringyr[8],steribgxt[8],steribgxb[8],steribgyl[8],steribgyr[8]; /* First calculate the symbol height and width in map units (is the same physical size, but in terms of window size they are different) */ /* Check if there is anything to draw */ if (nplot > gdsc -> nplots || nplot < 1) return 0; /* Check the scaling */ if ((logarcsx < 0) || (logarcsx > 3)) return 0; /* per default the function to draw the box is cpgbox */ boxingx = cpgbox; boxingy = cpgbox; /* Default numbering style */ sprintf(steringyr,"MV"); sprintf(steringyl,"NV"); sprintf(steringxt,"M"); sprintf(steringxb,"N"); sprintf(steribgyr,"CTS"); sprintf(steribgyl,"BTS"); sprintf(steribgxt,"CTS"); sprintf(steribgxb,"BTS"); /* Default scaling */ gdsc -> logarcsx = 0; gdsc -> logarcsy = 0; /* If a different scaling was requested, redefine labelling */ if (logarcsx == 1) { gdsc -> logarcsx = 1; /* if (xmin <= 0) */ /* return 0; */ /* if (xmax <= 0) */ /* return 0; */ /* if ((xmin*btscale+btzero) <= 0) */ /* return 0; */ /* if ((xmax*btscale+btzero) <= 0) */ /* return 0; */ /* Do a trick */ dummy1 = pgp_logf10f(xmin*btscale+btzero); dummy2 = pgp_logf10f(xmax*btscale+btzero); xmin = pgp_logf10f(xmin); xmax = pgp_logf10f(xmax); if (xmin == xmax) { btzero = dummy1-xmin; btscale = 0; } else { btscale = (dummy2-dummy1)/(xmax-xmin); btzero = dummy2-btscale*xmax; } sprintf(steringxt,"ML2"); sprintf(steringxb,"NL2"); sprintf(steribgxt,"CTSL"); sprintf(steribgxb,"BTSL"); } if (logarcsy == 1) { gdsc -> logarcsy = 1; /* if (ymin <= 0) */ /* return 0; */ /* if (ymax <= 0) */ /* return 0; */ /* if ((ymin*btscale+btzero) <= 0) */ /* return 0; */ /* if ((ymax*btscale+btzero) <= 0) */ /* return 0; */ /* Do a trick */ dummy1 = pgp_logf10f(ymin*lrscale+lrzero); dummy2 = pgp_logf10f(ymax*lrscale+lrzero); ymin = pgp_logf10f(ymin); ymax = pgp_logf10f(ymax); if (ymin == ymax) { lrzero = dummy1-ymin; lrscale = 0; } else { lrscale = (dummy2-dummy1)/(ymax-ymin); lrzero = dummy2-lrscale*ymax; } sprintf(steringyr,"MVL2"); sprintf(steringyl,"NVL2"); sprintf(steribgyr,"CTSL"); sprintf(steribgyl,"BTSL"); } /* hms */ if (logarcsx == 2) { gdsc -> logarcsx = 2; /* convert to seconds of time, input is interpreted as deg */ btzero = btzero/240.0; btscale = btscale/240.0; xmin = xmin*240.0; xmax = xmax*240.0; boxingx = cpgtbox; sprintf(steringxt,"M"); sprintf(steringxb,"NZH"); sprintf(steribgxt,"CTS"); sprintf(steribgxb,"BTSZXYH"); } if (logarcsy == 2) { gdsc -> logarcsy = 2; /* convert to seconds of time, input is interpreted as deg */ ymin = ymin*240.0; ymax = ymax*240.0; /* I'm really not sure why this is not the case */ /* lrzero = lrzero/240.0; */ lrscale = lrscale/240.0; boxingy = cpgtbox; sprintf(steringyr,"MV"); sprintf(steringyl,"NVZXYH"); sprintf(steribgyr,"CTS"); sprintf(steribgyl,"BTSZXYH"); } /* dms */ if (logarcsx == 3) { gdsc -> logarcsx = 3; /* convert to seconds of time, input is interpreted as deg */ xmin = xmin*3600.0; xmax = xmax*3600.0; /* I'm really not sure why this is not the case */ /* btzero = btzero/3600.0; */ btscale = btscale/3600.0; boxingx = cpgtbox; sprintf(steringxt,"M"); sprintf(steringxb,"NZD"); sprintf(steribgxt,"CTS"); sprintf(steribgxb,"BTSZYD"); } if (logarcsy == 3) { gdsc -> logarcsy = 3; /* convert to seconds of time, input is interpreted as deg */ ymin = ymin*3600.0; ymax = ymax*3600.0; /* lrzero = lrzero/3600.0; */ lrscale = lrscale/3600.0; boxingy = cpgtbox; sprintf(steringyr,"MV"); sprintf(steringyl,"NVZYD"); sprintf(steribgyr,"CTS"); sprintf(steribgyl,"BTSZYD"); } /* Ensure that minimum and maximum are different */ if(xmin == xmax) { if (xmin != 0.0) { xmin = xmin*0.9; xmax = xmax*1.1; } else { xmin = -1.0; xmax = 1.0; } } if (logarcsx > 1) { if ((xmin-xmax) < 1.0) { xmin = xmin-1.0; xmax = xmax+1.0; } } if(ymin == ymax) { if (ymin != 0.0) { ymin = ymin*0.9; ymax = ymax*1.1; } else { ymin = -1.0; ymax = 1.0; } } if (logarcsy > 1) { if ((ymin-ymax) < 1.0) { ymin = ymin-1.0; ymax = ymax+1.0; } } /**********/ /* scales */ /**********/ /* Standard linewidth */ cpgqlw(&slw); /* Find the reference */ cpgsch(gdsc -> numberheight); cpgqcs(0, &chrhtxref, &chrhtyref); /* The physical size in x is scalexy times the physical size in y */ /* scalexy = chrhtyref/chrhtxref; */ /* plot height */ plotheight = (1.0 - 2.0*(gdsc -> legendrows+1)*gdsc -> legendheight*chrhtyref - 6*gdsc -> axdescheight*chrhtyref-6*chrhtyref)/gdsc -> nplots; /* Position of the plot, whole box */ xlo = gdsc -> leftmargin*chrhtxref+3*gdsc -> axdescheight*chrhtxref; /* changed from 3*gdsc -> axdescheight to 4*gdsc -> axdescheight */ xhi = 1.0-4*gdsc -> axdescheight*chrhtxref-gdsc -> rightmargin*chrhtxref; ylo = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot); yhi = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot-1); /* Check if the specification is wrong and return 0 if it is */ if (xlo >= xhi) return 0; if (ylo >= yhi) return 0; /* Define the linear dependencies of the window scaling and the user scaling */ ax = (xmax-xmin)/((xhi-gdsc -> horbord*gdsc -> symbolheight*chrhtxref) - (xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref)); ay = (ymax-ymin)/((yhi-gdsc -> verbord*gdsc -> symbolheight*chrhtyref) - (ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref)); bx = xmin-ax*(xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref); by = ymin-ay*(ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref); /*************/ /* Numbering */ /*************/ /* Set the symbol size (again) */ cpgsch(gdsc -> numberheight); /* Draw the numbers axis by axis */ /* First define the plot region */ xlo2 = gdsc -> leftmargin*chrhtxref+3*gdsc -> axdescheight*chrhtxref+gdsc -> leftnum*chrhtxref; xhi2 = 1.0-gdsc -> rightmargin*chrhtxref-4*gdsc -> axdescheight*chrhtxref-gdsc -> rightnum*chrhtxref; ylo2 = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot)+gdsc -> botnum*chrhtyref; yhi2 = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot-1)-gdsc -> topnum*chrhtyref; xulo2 = ax*xlo2+bx; xuhi2 = ax*xhi2+bx; yulo2 = ay*ylo2+by; yuhi2 = ay*yhi2+by; /* Top and bottom numbering */ if (nplot == 1) { cpgsvp(xlo2, xhi2, ylo, yhi); cpgswin(xulo2*btscale+btzero, xuhi2*btscale+btzero, yulo2*lrscale+lrzero, yuhi2*lrscale+lrzero); if ((topdeschi) || topdesclo) (*boxingx)(steringxt, 0.0, 0, "", 0.0, 0); } if (nplot == gdsc -> nplots) { cpgsvp(xlo2, xhi2, ylo, yhi); /* BUGFIX: changed from (...,yulo, yuhi) to (...,yulo2, yuhi2) */ cpgswin(xulo2, xuhi2, yulo2, yuhi2); if ((bottomdeschi) || bottomdesclo) (*boxingx)(steringxb, 0.0, 0, "", 0.0, 0); } /* Left and right numbering */ cpgsvp(xlo, xhi, ylo2, yhi2); cpgswin(xulo2*btscale+btzero, xuhi2*btscale+btzero, yulo2*lrscale+lrzero, yuhi2*lrscale+lrzero); if ((rightdeschi) || (rightdesclo)) (*boxingy)("", 0.0, 0, steringyr, 0.0, 0); cpgsvp(xlo, xhi, ylo2, yhi2); cpgswin(xulo2, xuhi2, yulo2, yuhi2); if ((leftdeschi) || (leftdesclo)) (*boxingy)("", 0.0, 0, steringyl, 0.0, 0); /***************/ /* Box drawing */ /***************/ /* Set the line width */ cpgslw(gdsc -> boxlw); /* Define an area of operation PGSVP (XMIN, XMAX, YMIN, YMAX), 0 to 1, y from bottom to top */ cpgsvp(xlo, xhi, ylo, yhi); xulo = ax*xlo+bx; xuhi = ax*xhi+bx; yulo = ay*ylo+by; yuhi = ay*yhi+by; cpgswin(xulo, xuhi, yulo, yuhi); /* draw the box with the tickmarks of the lower and left panel */ (*boxingx)(steribgxb, 0.0, 0, "", 0.0, 0); (*boxingy)("", 0.0, 0, steribgyl, 0.0, 0); /* Now change the user coordinates */ cpgswin(xulo*btscale+btzero, xuhi*btscale+btzero, yulo*lrscale+lrzero, yuhi*lrscale+lrzero); /* draw the box with the tickmarks of the upper and right panel */ (*boxingx)(steribgxt, 0.0, 0, "", 0.0, 0); (*boxingy)("", 0.0, 0, steribgyr, 0.0, 0); /* Reset the linewidth */ cpgslw(slw); /*************/ /* Labelling */ /*************/ /* Set character height (again) to the number value */ cpgsch(gdsc -> numberheight); /* Label top */ if (nplot == 1) putalabel('t', topdeschi, topdesclo, gdsc -> axdescheight, gdsc -> topmargin); /* Label bottom */ if (nplot == gdsc -> nplots) putalabel('b', bottomdeschi, bottomdesclo, gdsc -> axdescheight, gdsc -> bottommargin); /* Label left and right axis */ putalabel('l', leftdeschi, leftdesclo, gdsc -> axdescheight, gdsc -> leftmargin); putalabel('r', rightdeschi, rightdesclo, gdsc -> axdescheight, gdsc -> rightmargin); /* At the end we put the viewport and the window at the right values */ switch (logarcsx) { case 2: xmin = xmin/240.0; xmax = xmax/240.0; break; case 3: xmin = xmin/3600.0; xmax = xmax/3600.0; break; } switch (logarcsy) { case 2: ymin = ymin/240.0; ymax = ymax/240.0; break; case 3: ymin = ymin/3600.0; ymax = ymax/3600.0; break; } /* Redefine */ xlo = gdsc -> leftmargin*chrhtxref+3*gdsc -> axdescheight*chrhtxref; xhi = 1.0-4*gdsc -> axdescheight*chrhtxref-gdsc -> rightmargin*chrhtxref; ylo = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot); yhi = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(nplot-1); ax = (xmax-xmin)/((xhi-gdsc -> horbord*gdsc -> symbolheight*chrhtxref) - (xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref)); ay = (ymax-ymin)/((yhi-gdsc -> verbord*gdsc -> symbolheight*chrhtyref) - (ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref)); bx = xmin-ax*(xlo+gdsc -> horbord*gdsc -> symbolheight*chrhtxref); by = ymin-ay*(ylo+gdsc -> verbord*gdsc -> symbolheight*chrhtyref); xulo = ax*xlo+bx; xuhi = ax*xhi+bx; yulo = ay*ylo+by; yuhi = ay*yhi+by; /* Do the redefinition */ cpgsvp(xlo, xhi, ylo, yhi); cpgswin(xulo, xuhi, yulo, yuhi); return 1; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Puts a label at a viewgraph as a fraction */ int putalabel(char where, char *overfrac, char *underfrac, float charheight, float dist) { float oheight; /* Character height at call time */ int fraclength; char *fracbar; float ovpos; float unpos; float fracpos; char format[3]; float frlen1; float frlen2; float xbox; float ybox; float chrhtxref; float chrhtyref; /* Check if there is anything to put */ if ((overfrac == NULL) && (underfrac == NULL)) return 1; /***********/ /* scaling */ /***********/ /* Find the reference character height */ cpgqch(&oheight); /* Set the character height to the required value */ cpgsch(oheight*charheight); /* If the strings are empty we return a success */ if (!(*overfrac)) { if (!(*underfrac)) return 1; /* If only one of them is empty, we make the one not empty overfrac */ else { fracbar = overfrac; overfrac = underfrac; underfrac = fracbar; } } /* A format string is required */ switch (where) { case 'l': sprintf(format,"L"); /* Calculate the maximum possible distance from the edge of the graph */ ovpos = dist/charheight+2.0; fracpos = dist/charheight+1.4; unpos = dist/charheight; break; case 'r': sprintf(format,"R"); /* Calculate the maximum possible distance from the edge of the graph */ ovpos = dist/charheight+1; fracpos = dist/charheight+1.6; unpos = dist/charheight+3; break; case 't': sprintf(format,"T"); ovpos = dist/charheight+2.0; fracpos = dist/charheight/charheight+1.4; unpos = dist/charheight/charheight+0.0; break; case 'b': sprintf(format,"B"); ovpos = dist/charheight+1.0; fracpos = dist/charheight+1.6; unpos = dist/charheight+3.0; break; default: return 0; } /* To get the length of the fraction bar, first find a bounding box at an arbitrary position */ cpglen(2, overfrac, &xbox, &ybox); frlen1 = ybox; cpglen(2, underfrac, &xbox, &ybox); frlen2 = ybox; frlen1= (frlen1 > frlen2)?frlen1:frlen2; /* Now frlen1 is the length of the string in world coordinates of the x axis, we get the character width of this axis in the same units */ cpgqcs(2, &chrhtxref, &chrhtyref); /* Then, the length of the fraction bar is the uprounded fraction */ fraclength = ((int) (frlen1/chrhtyref))+3; if (!(fracbar = (char *) malloc((fraclength+1)*sizeof(char)))) return 0; fracbar[fraclength] = '\0'; while (fraclength > 0) { fracbar[fraclength-1] = '_'; --fraclength; } /************/ /* plotting */ /************/ /* If there is a fraction bar to plot do this */ if (*underfrac) { /* First plot the character string above the fraction bar */ cpgmtxt(format, ovpos, 0.5, 0.5, overfrac); /* Now draw the fraction bar */ cpgmtxt(format, fracpos, 0.5, 0.5, fracbar); /* At last put the argument below the fraction bar */ cpgmtxt(format, unpos, 0.5, 0.5, underfrac); } /* No fraction bar */ else { cpgmtxt(format, unpos, 0.5, 0.5, overfrac); } /* Deallocate */ free(fracbar); /* Set the character height to the original value */ cpgsch(oheight); return 1; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Puts a string to the specified legend position */ int pgp_legend(pgp_gdsc *gdsc, int nhor, int nver, char *string) { float chrhtxref; /* Horizontal character width in x-map units, 1 is whole page */ float chrhtyref; /* Vertical character height in y-map units, 1 is whole page */ /* float charwidth; */ float posix; float posiy; float plotheight; /* float boxwidth; */ float xlo; /* Box in window coordinates */ float xhi; float ylo; float yhi; /* First check if the intended legend position is available */ if (nver < 1 || nver > gdsc -> legendrows || nhor < 1 || nhor > gdsc -> legendcols) { return 0; } /* Then open a box that nearly spans the whole surface at the bottom position of the graph */ /* Find the reference */ cpgsch(gdsc -> numberheight); cpgqcs(0, &chrhtxref, &chrhtyref); /* plot height */ plotheight = (1.0 - 2.0*(gdsc -> legendrows+1)*gdsc -> legendheight*chrhtyref - 6*gdsc -> axdescheight*chrhtyref-6*chrhtyref)/gdsc -> nplots; ylo = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(gdsc -> nplots); yhi = 1.0-4*gdsc -> axdescheight*chrhtyref-gdsc -> topmargin*chrhtyref-plotheight*(gdsc -> nplots-1); /* At the left hand the box has the distance of one symbol to the border of the plotting surface */ cpgsch(gdsc -> numberheight*gdsc -> legendheight); cpgqcs(0, &chrhtxref, &chrhtyref); xlo = chrhtxref; xhi = 1.0-chrhtxref; /* Check if the specification is wrong and return 0 if it is */ if (xlo >= xhi) return 0; if (ylo >= yhi) return 0; /* Define the surface */ cpgsvp(xlo, xhi, ylo, yhi); /* This is the length of a box element in units of the x-axis, spacing is one character between rows */ /* boxwidth = (1-(gdsc -> legendcols-1)*charwidth)/gdsc -> legendcols; */ /* This is the position of the string in x along the axis */ posix = (nhor-0.5)/gdsc -> legendcols; /* Now in y */ posiy = gdsc -> bottommargin/gdsc -> legendheight+3*gdsc -> axdescheight/gdsc -> legendheight+2*nver; /* Put it on the graph */ cpgmtxt("B", posiy, posix, 0.5, string); /* Reset the character height */ cpgsch(gdsc -> numberheight); return 1; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Puts markers on a predefined viewport */ int pgp_marker(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, int colour, int empty, int symbol, float sizer) { int colourbef; float chrhtxref, chrhtyref; int intlw; float *xposd = NULL; float *yposd = NULL; int i; /* Allocate space if necessary */ if (gdsc -> logarcsx == 1) { if (!(xposd = (float *) malloc(npoints*sizeof(float)))) return 1; for (i=0; i < npoints; ++i) { xposd[i] = pgp_logf10f(xpos[i]); } xpos = xposd; } if (gdsc -> logarcsy == 1) { if (!(yposd = (float *) malloc(npoints*sizeof(float)))) { if ((xposd)) free(xposd); return 2; } for (i=0; i < npoints; ++i) { yposd[i] = pgp_logf10f(ypos[i]); } ypos = yposd; } /* Set the character height */ if (symbol == -1) cpgsch(gdsc -> numberheight*gdsc -> symbolheight*sizer); else if (symbol == 3) cpgsch(gdsc -> numberheight*gdsc -> symbolheight*2*sizer*1.2); else cpgsch(gdsc -> numberheight*gdsc -> symbolheight*2*sizer); /* Inquire the character height in inches */ cpgqcs(1, &chrhtxref, &chrhtyref); /* Set the linewidth as an equivalent */ if (symbol == -1) { intlw = chrhtxref*200.0>201.0?201: (int) (chrhtxref*200.0); } else intlw = 1; cpgslw(intlw); /* Store the colour index */ cpgqci(&colourbef); /* Set the colour index */ cpgsci(colour); /* Plot points, number of points, vectors for x and y, symbol */ cpgpt(npoints, xpos, ypos, symbol); /* If required, plot the same list on top of that with background colour and with a radius that is smaller */ if ((empty)) { cpgslw(((intlw-4*gdsc -> graphlw) > 0)?(intlw-4*gdsc -> graphlw):0); cpgsci(0); cpgpt(npoints, xpos, ypos, symbol); } /* Reset the linewidth */ cpgslw(gdsc -> graphlw); /* Reset the colour index */ cpgsci(colourbef); /* Reset the character height */ cpgsch(gdsc -> numberheight); /* Reset the linewidth */ cpgslw(gdsc -> boxlw); /* Deallocate */ if (gdsc -> logarcsy == 1) { free(yposd); } if (gdsc -> logarcsx == 1) { free(xposd); } return 0; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Puts lines on a predefined viewport */ int pgp_lines(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, int colour) { int i; int colourbef; float *xposd = NULL; float *yposd = NULL; if (gdsc -> interptype_lines != PGP_I_LINEAR) { if (pgp_get_interparray(xpos, ypos, npoints, gdsc -> interptype_lines, gdsc -> interp_numlines+1, &xposd, &yposd)) goto error; npoints = gdsc -> interp_numlines+1; xpos = xposd; ypos = yposd; } /* Allocate space if necessary */ if (gdsc -> logarcsx == 1) { if (!xposd) { if (!(xposd = (float *) malloc(npoints*sizeof(float)))) goto error; } for (i=0; i < npoints; ++i) { xposd[i] = pgp_logf10f(xpos[i]); } xpos = xposd; } if (gdsc -> logarcsy == 1) { if (!yposd) { if (!(yposd = (float *) malloc(npoints*sizeof(float)))) goto error; } for (i=0; i < npoints; ++i) { yposd[i] = pgp_logf10f(ypos[i]); } ypos = yposd; } /* Store the colour index */ cpgqci(&colourbef); /* Set the colour index */ cpgsci(colour); /* Set the linewidth */ cpgslw(gdsc -> graphlw); /* Plot lines, number of points, vectors for x and y, symbol */ cpgline(npoints, xpos, ypos); /* Reset the linewidth */ cpgslw(gdsc -> graphlw); /* Reset the colour index */ cpgsci(colourbef); /* Reset the linewidth */ cpgslw(gdsc -> boxlw); /* Deallocate */ if ((xposd)) free(xposd); if ((yposd)) free(yposd); return 0; error: if ((xposd)) free(xposd); if ((yposd)) free(yposd); return 1; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Puts lines on a predefined viewport */ int pgp_bars(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, float width, int colour) { int colourbef,i; float *xposd = NULL; float *yposd = NULL; /* Allocate space if necessary */ if (gdsc -> logarcsx == 1) { if (!(xposd = (float *) malloc(npoints*sizeof(float)))) return 1; for (i=0; i < npoints; ++i) { xposd[i] = pgp_logf10f(xpos[i]); } xpos = xposd; } if (gdsc -> logarcsy == 1) { if (!(yposd = (float *) malloc(npoints*sizeof(float)))) { if ((xposd)) free(xposd); return 2; } for (i=0; i < npoints; ++i) { yposd[i] = pgp_logf10f(ypos[i]); } ypos = yposd; } /* Store the colour index */ cpgqci(&colourbef); /* Set the colour index */ cpgsci(colour); /* Set the linewidth */ cpgslw(gdsc -> graphlw); /* Plot lines, number of points, vectors for x and y, symbol */ for (i = 0; i < npoints; ++i) cpgerr1(5, xpos[i], ypos[i], width/2, 0.0); /* Reset the linewidth */ cpgslw(gdsc -> graphlw); /* Reset the colour index */ cpgsci(colourbef); /* Reset the linewidth */ cpgslw(gdsc -> boxlw); /* Deallocate */ if (gdsc -> logarcsy == 1) { free(yposd); } if (gdsc -> logarcsx == 1) { free(xposd); } return 0; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Puts lines on a predefined viewport */ int pgp_errby(pgp_gdsc *gdsc, int npoints, float *xpos, float *ypos, float *err, int colour) { int colourbef, i; float *xposd = NULL; float *yposdl = NULL; float *yposdr = NULL; /* Allocate space if necessary */ if (gdsc -> logarcsx == 1) { if (!(xposd = (float *) malloc(npoints*sizeof(float)))) return 1; for (i=0; i < npoints; ++i) { xposd[i] = pgp_logf10f(xpos[i]); } xpos = xposd; } if (gdsc -> logarcsy == 1) { if (!(yposdl = (float *) malloc(npoints*sizeof(float)))) { if ((xposd)) free(xposd); return 1; } if (!(yposdr = (float *) malloc(npoints*sizeof(float)))) { if ((xposd)) free(xposd); free(yposdl); return 1; } for (i=0; i < npoints; ++i) { yposdr[i] = pgp_logf10f(ypos[i]+err[i]); } for (i=0; i < npoints; ++i) { yposdl[i] = pgp_logf10f(ypos[i]-err[i]); } } /* Store the colour index */ cpgqci(&colourbef); /* Set the colour index */ cpgsci(colour); /* Set the linewidth */ cpgslw(gdsc -> graphlw); /* Plot lines, number of points, vectors for x and y, symbol */ if (gdsc -> logarcsy == 1) cpgerry(npoints, xpos, yposdl, yposdr, 2.0); else cpgerrb(6, npoints, xpos, ypos, err, 2.0); /* Reset the linewidth */ cpgslw(gdsc -> graphlw); /* Reset the colour index */ cpgsci(colourbef); /* Reset the linewidth */ cpgslw(gdsc -> boxlw); /* Clean up */ if (gdsc -> logarcsx == 1) free(xposd); if (gdsc -> logarcsy == 1) { free(yposdl); free(yposdr); } return 0; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* End the plotting and close the device */ void pgp_end() { cpgclos(); } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Returns the logarithm on basis 10 and LOGFAULT if x <= 0 */ float pgp_logf10f(float x) { if (x > 0) return log10f(x); else return LOGFAULT; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Returns an array of interpolated values. */ static int pgp_get_interparray(float *x, float *y, int npoints, int interptype, int noutpoints, float **xout, float **yout) { int i, pgp_get_interparray = 0; double *xdouble = NULL, *ydouble = NULL; /* input is float, but gsl requires double */ gsl_interp *gsl_interpv = NULL; /* gsl structs */ gsl_interp_accel *gsl_interp_accelv = NULL; /* gsl structs */ const gsl_interp_type * intytype = NULL; /* interpolation type, internal to gsl */ float dx; /* At least two data points */ if (npoints < 2) { pgp_get_interparray |= 1; goto error; } /* Wipe the input, gone ... */ if (*xout) { free(*xout); *xout = NULL; } if (*yout) { free(*yout); *yout = NULL; } /* Allocate arrays */ if (!(xdouble = (double *) malloc(npoints*sizeof(double)))) { pgp_get_interparray |= 2; goto error; } if (!(ydouble = (double *) malloc(npoints*sizeof(double)))) { pgp_get_interparray |= 2; goto error; } for (i = 0; i < npoints; ++i) { xdouble[i] = x[i]; ydouble[i] = y[i]; } if (!(*xout = (float *) malloc(noutpoints*sizeof(float)))) { pgp_get_interparray |= 2; goto error; } if (!(*yout = (float *) malloc(noutpoints*sizeof(float)))) { pgp_get_interparray |= 2; goto error; } switch(interptype) { case PGP_I_LINEAR: intytype = gsl_interp_linear; break; case PGP_I_CSPLINE: if (npoints > 2) intytype = gsl_interp_cspline; else { printf("Must have at least 3 radii for spline, using linear\n"); intytype = gsl_interp_linear; } break; case PGP_I_AKIMA: if (npoints > 4) { intytype = gsl_interp_akima; } else { printf("Must have at least 5 radii for Akima\n"); if (npoints > 2) { printf("Using natural cubic spline\n"); intytype = gsl_interp_cspline; } else { printf("Using linear\n"); intytype = gsl_interp_linear; } } break; /* No real default, but we set linear */ default: intytype = gsl_interp_linear; break; } /* Attempt to allocate all gsl structures */ if (!(gsl_interpv = gsl_interp_alloc(intytype, npoints))) { pgp_get_interparray |= 2; goto error; } if (!(gsl_interp_accelv = gsl_interp_accel_alloc())) { pgp_get_interparray |= 2; goto error; } gsl_interp_init(gsl_interpv, xdouble, ydouble, npoints); (*xout)[0] = x[0]; (*yout)[0] = y[0]; dx = (x[npoints-1]-x[0])/((float)(noutpoints-1)); /* Bugfix: rounding error could lead to failure of interpolation */ --noutpoints; for (i = 1; i < noutpoints; ++i) { (*xout)[i] = (*xout)[i-1]+dx; (*yout)[i] = gsl_interp_eval(gsl_interpv, xdouble, ydouble, (*xout)[i], gsl_interp_accelv); } (*xout)[i] = x[npoints-1]; (*yout)[i] = y[npoints-1]; /* last points should be identical regardless of rounding errors */ free(xdouble); free(ydouble); gsl_interp_free(gsl_interpv); gsl_interp_accel_free(gsl_interp_accelv); return pgp_get_interparray; error: if (xdouble) free(xdouble); if (ydouble) free(ydouble); if (*xout) { free(*xout); *xout = NULL; } if (*yout) { free(*yout); *yout = NULL; } if (gsl_interpv) gsl_interp_free(gsl_interpv); if (gsl_interp_accelv) gsl_interp_accel_free(gsl_interp_accelv); return pgp_get_interparray; } /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ $Log: pgp.c,v $ Revision 1.14 2011/05/25 22:25:26 jozsa Left work Revision 1.13 2011/05/10 00:30:16 jozsa Left work Revision 1.12 2009/05/26 07:56:41 jozsa Left work Revision 1.11 2007/08/22 15:58:43 gjozsa Left work Revision 1.10 2006/11/22 14:16:21 gjozsa Bugfix concerning RASH and horizontal/vertical lines Revision 1.9 2006/11/03 10:49:02 gjozsa Introduced logarithmic scaling, hms dms Revision 1.8 2006/10/05 12:39:58 gjozsa nasty bugfix Revision 1.7 2006/04/03 11:47:57 gjozsa Left work Revision 1.6 2006/02/08 16:13:17 gjozsa Extended graphics routines Revision 1.5 2005/10/12 14:51:25 gjozsa First point gets thick in the polar plot Revision 1.4 2005/10/12 09:53:09 gjozsa Included polar plot facility Revision 1.3 2005/06/24 12:00:29 gjozsa Left work Revision 1.2 2005/05/24 10:42:24 gjozsa Left work Revision 1.1 2005/05/17 12:58:15 gjozsa Added to cvs control ------------------------------------------------------------ */
{ "alphanum_fraction": 0.5677798325, "avg_line_length": 26.9431418523, "ext": "c", "hexsha": "feadd592f47730b0f5c5b58aeb93846ea908dde0", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-01-03T15:02:35.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-28T03:17:38.000Z", "max_forks_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kernsuite-debian/tirific", "max_forks_repo_path": "src/pgp.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "462a58a8312ce437ac5e2c87060cde751774f1de", "max_issues_repo_issues_event_max_datetime": "2019-08-20T06:37:26.000Z", "max_issues_repo_issues_event_min_datetime": "2017-02-24T12:40:08.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gigjozsa/tirific", "max_issues_repo_path": "src/pgp.c", "max_line_length": 560, "max_stars_count": 4, "max_stars_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kernsuite-debian/tirific", "max_stars_repo_path": "src/pgp.c", "max_stars_repo_stars_event_max_datetime": "2018-01-04T08:22:01.000Z", "max_stars_repo_stars_event_min_datetime": "2015-07-01T12:07:09.000Z", "num_tokens": 14790, "size": 45965 }
/* linalg/bidiag.c * * Copyright (C) 2001, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Factorise a matrix A into * * A = U B V^T * * where U and V are orthogonal and B is upper bidiagonal. * * On exit, B is stored in the diagonal and first superdiagonal of A. * * U is stored as a packed set of Householder transformations in the * lower triangular part of the input matrix below the diagonal. * * V is stored as a packed set of Householder transformations in the * upper triangular part of the input matrix above the first * superdiagonal. * * The full matrix for U can be obtained as the product * * U = U_1 U_2 .. U_N * * where * * U_i = (I - tau_i * u_i * u_i') * * and where u_i is a Householder vector * * u_i = [0, .. , 0, 1, A(i+1,i), A(i+3,i), .. , A(M,i)] * * The full matrix for V can be obtained as the product * * V = V_1 V_2 .. V_(N-2) * * where * * V_i = (I - tau_i * v_i * v_i') * * and where v_i is a Householder vector * * v_i = [0, .. , 0, 1, A(i,i+2), A(i,i+3), .. , A(i,N)] * * See Golub & Van Loan, "Matrix Computations" (3rd ed), Algorithm 5.4.2 * * Note: this description uses 1-based indices. The code below uses * 0-based indices */ #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> int gsl_linalg_bidiag_decomp (gsl_matrix * A, gsl_vector * tau_U, gsl_vector * tau_V) { if (A->size1 < A->size2) { GSL_ERROR ("bidiagonal decomposition requires M>=N", GSL_EBADLEN); } else if (tau_U->size != A->size2) { GSL_ERROR ("size of tau_U must be N", GSL_EBADLEN); } else if (tau_V->size + 1 != A->size2) { GSL_ERROR ("size of tau_V must be (N - 1)", GSL_EBADLEN); } else { const size_t M = A->size1; const size_t N = A->size2; gsl_vector * tmp = gsl_vector_alloc(M); size_t j; for (j = 0 ; j < N; j++) { /* apply Householder transformation to current column */ gsl_vector_view v = gsl_matrix_subcolumn(A, j, j, M - j); double tau_j = gsl_linalg_householder_transform (&v.vector); /* apply the transformation to the remaining columns */ if (j + 1 < N) { gsl_matrix_view m = gsl_matrix_submatrix (A, j, j + 1, M - j, N - j - 1); gsl_vector_view work = gsl_vector_subvector(tau_U, j, N - j - 1); gsl_linalg_householder_left (tau_j, &v.vector, &m.matrix, &work.vector); } gsl_vector_set (tau_U, j, tau_j); /* apply Householder transformation to current row */ if (j + 1 < N) { v = gsl_matrix_subrow (A, j, j + 1, N - j - 1); tau_j = gsl_linalg_householder_transform (&v.vector); /* apply the transformation to the remaining rows */ if (j + 1 < M) { gsl_matrix_view m = gsl_matrix_submatrix (A, j + 1, j + 1, M - j - 1, N - j - 1); gsl_vector_view work = gsl_vector_subvector(tmp, 0, M - j - 1); gsl_linalg_householder_right (tau_j, &v.vector, &m.matrix, &work.vector); } gsl_vector_set (tau_V, j, tau_j); } } gsl_vector_free(tmp); return GSL_SUCCESS; } } /* Form the orthogonal matrices U, V, diagonal d and superdiagonal sd from the packed bidiagonal matrix A */ int gsl_linalg_bidiag_unpack (const gsl_matrix * A, const gsl_vector * tau_U, gsl_matrix * U, const gsl_vector * tau_V, gsl_matrix * V, gsl_vector * diag, gsl_vector * superdiag) { const size_t M = A->size1; const size_t N = A->size2; const size_t K = GSL_MIN(M, N); if (M < N) { GSL_ERROR ("matrix A must have M >= N", GSL_EBADLEN); } else if (tau_U->size != K) { GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN); } else if (tau_V->size + 1 != K) { GSL_ERROR ("size of tau must be MIN(M,N) - 1", GSL_EBADLEN); } else if (U->size1 != M || U->size2 != N) { GSL_ERROR ("size of U must be M x N", GSL_EBADLEN); } else if (V->size1 != N || V->size2 != N) { GSL_ERROR ("size of V must be N x N", GSL_EBADLEN); } else if (diag->size != K) { GSL_ERROR ("size of diagonal must match size of A", GSL_EBADLEN); } else if (superdiag->size + 1 != K) { GSL_ERROR ("size of subdiagonal must be (diagonal size - 1)", GSL_EBADLEN); } else { size_t i, j; /* Copy diagonal into diag */ for (i = 0; i < N; i++) { double Aii = gsl_matrix_get (A, i, i); gsl_vector_set (diag, i, Aii); } /* Copy superdiagonal into superdiag */ for (i = 0; i < N - 1; i++) { double Aij = gsl_matrix_get (A, i, i+1); gsl_vector_set (superdiag, i, Aij); } /* Initialize V to the identity */ gsl_matrix_set_identity (V); for (i = N - 1; i-- > 0;) { /* Householder row transformation to accumulate V */ gsl_vector_const_view h = gsl_matrix_const_subrow (A, i, i + 1, N - i - 1); double ti = gsl_vector_get (tau_V, i); gsl_matrix_view m = gsl_matrix_submatrix (V, i + 1, i + 1, N- i - 1, N - i - 1); gsl_vector_view work = gsl_matrix_subrow(U, 0, 0, N - i - 1); gsl_linalg_householder_left (ti, &h.vector, &m.matrix, &work.vector); } /* Initialize U to the identity */ gsl_matrix_set_identity (U); for (j = N; j-- > 0;) { /* Householder column transformation to accumulate U */ gsl_vector_const_view h = gsl_matrix_const_subcolumn (A, j, j, M - j); double tj = gsl_vector_get (tau_U, j); gsl_matrix_view m = gsl_matrix_submatrix (U, j, j, M - j, N - j); gsl_linalg_householder_hm (tj, &h.vector, &m.matrix); } return GSL_SUCCESS; } } int gsl_linalg_bidiag_unpack2 (gsl_matrix * A, gsl_vector * tau_U, gsl_vector * tau_V, gsl_matrix * V) { const size_t M = A->size1; const size_t N = A->size2; const size_t K = GSL_MIN(M, N); if (M < N) { GSL_ERROR ("matrix A must have M >= N", GSL_EBADLEN); } else if (tau_U->size != K) { GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN); } else if (tau_V->size + 1 != K) { GSL_ERROR ("size of tau must be MIN(M,N) - 1", GSL_EBADLEN); } else if (V->size1 != N || V->size2 != N) { GSL_ERROR ("size of V must be N x N", GSL_EBADLEN); } else { size_t i, j; /* Initialize V to the identity */ gsl_matrix_set_identity (V); for (i = N - 1; i-- > 0;) { /* Householder row transformation to accumulate V */ gsl_vector_const_view r = gsl_matrix_const_row (A, i); gsl_vector_const_view h = gsl_vector_const_subvector (&r.vector, i + 1, N - (i+1)); double ti = gsl_vector_get (tau_V, i); gsl_matrix_view m = gsl_matrix_submatrix (V, i + 1, i + 1, N-(i+1), N-(i+1)); gsl_linalg_householder_hm (ti, &h.vector, &m.matrix); } /* Copy superdiagonal into tau_v */ for (i = 0; i < N - 1; i++) { double Aij = gsl_matrix_get (A, i, i+1); gsl_vector_set (tau_V, i, Aij); } /* Allow U to be unpacked into the same memory as A, copy diagonal into tau_U */ for (j = N; j-- > 0;) { /* Householder column transformation to accumulate U */ double tj = gsl_vector_get (tau_U, j); double Ajj = gsl_matrix_get (A, j, j); gsl_matrix_view m = gsl_matrix_submatrix (A, j, j, M-j, N-j); gsl_vector_set (tau_U, j, Ajj); gsl_linalg_householder_hm1 (tj, &m.matrix); } return GSL_SUCCESS; } } int gsl_linalg_bidiag_unpack_B (const gsl_matrix * A, gsl_vector * diag, gsl_vector * superdiag) { const size_t M = A->size1; const size_t N = A->size2; const size_t K = GSL_MIN(M, N); if (diag->size != K) { GSL_ERROR ("size of diagonal must match size of A", GSL_EBADLEN); } else if (superdiag->size + 1 != K) { GSL_ERROR ("size of subdiagonal must be (matrix size - 1)", GSL_EBADLEN); } else { size_t i; /* Copy diagonal into diag */ for (i = 0; i < K; i++) { double Aii = gsl_matrix_get (A, i, i); gsl_vector_set (diag, i, Aii); } /* Copy superdiagonal into superdiag */ for (i = 0; i < K - 1; i++) { double Aij = gsl_matrix_get (A, i, i+1); gsl_vector_set (superdiag, i, Aij); } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.54785313, "avg_line_length": 28.3181818182, "ext": "c", "hexsha": "d2a15e0317b18dd2b7db2ed46294ac1b88ace725", "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": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/bidiag.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/linalg/bidiag.c", "max_line_length": 99, "max_stars_count": null, "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/bidiag.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2853, "size": 9968 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_statistics.h> #define N (4096*4*16) double g (double *x, int dim); int main (void) { double sum; double s = 12.; int dim = 4; double x[4]; gsl_rng *r; r = gsl_rng_alloc (gsl_rng_taus2); gsl_rng_set (r, 1UL); long i, j, nn; printf ("# Iter Npoints Volume AbsErr\n"); nn = N; for (j = 0; j < 16; j++) { sum = 0.; for (i = 0; i < nn; i++) { // 4-dimensional random point for (int k = 0; k < dim; k++) { x[k] = s * gsl_rng_uniform (r) - s / 2; } sum += g (x, dim); } double integ = (sum * pow (s, (double) dim)) / nn; double exact = M_PI * M_PI; printf ("%3ld %16ld %f %f\n", j, nn, integ, fabs (exact - integ)); nn *= 2; } gsl_rng_free (r); return 0; } double g (double *x, int dim) { double r2 = 0., q; for (int i = 0; i < dim; i++) { q = x[i]; r2 += q * q; } return exp (-r2); }
{ "alphanum_fraction": 0.4871794872, "avg_line_length": 15.6, "ext": "c", "hexsha": "c6e656d9f0774f7b8bddff576b55770532fe8e47", "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": "25ce6ca213186edff973cae42a954e31947514a0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jlichtman13/fin2", "max_forks_repo_path": "gaussian.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "25ce6ca213186edff973cae42a954e31947514a0", "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": "jlichtman13/fin2", "max_issues_repo_path": "gaussian.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "25ce6ca213186edff973cae42a954e31947514a0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jlichtman13/fin2", "max_stars_repo_path": "gaussian.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 376, "size": 1014 }
// Created by BlurringShadow at 2021-02-27-下午 10:24 #pragma once #include <algorithm> #include <chrono> #ifdef __cpp_lib_concepts #include <concepts> #include <ranges> #endif #include <execution> #include <optional> #include <string> #include <type_traits> #include <utility> #include <nameof.hpp> #include <boost/type_traits.hpp> #include <entt/entt.hpp> #include <fmt/ostream.h> #include <glm/ext.hpp> #include <gsl/gsl> #include <range/v3/all.hpp> #include <rxcpp/rx.hpp> #include <tl/expected.hpp> using namespace std::literals; namespace polycumic::utility { #ifndef __cpp_lib_concepts #define SFINAE(...) std::enable_if_t<__VA_ARGS__>* = nullptr #endif using tl::expected; template<typename T> struct auto_cast { T&& t; template<typename U> #ifdef __cpp_lib_concepts requires requires { static_cast<std::decay_t<U>>(std::forward<T>(t)); } #endif [[nodiscard]] constexpr operator U() noexcept(std::is_nothrow_constructible_v<T, std::decay_t<U>>) { return static_cast<std::decay_t<U>>(std::forward<T>(t)); } }; template<typename T> auto_cast(T&& t) -> auto_cast<T>; template<typename T, typename U, typename Comp> constexpr T& set_if(T& left, U&& right, Comp comp) { if(comp(right, left)) left = std::forward<U>(right); return left; } template<typename T, typename U> constexpr T& set_if_greater(T& left, U&& right) { return set_if(left, std::forward<U>(right), std::greater<>{}); } template<typename T, typename U> constexpr T& set_if_lesser(T& left, U&& right) { return set_if(left, std::forward<U>(right), std::less<>{}); } template<typename T, typename Compare> [[nodiscard]] constexpr bool is_between( const T& v, const boost::type_identity_t<T>& min, const boost::type_identity_t<T>& max, Compare cmp ) { return std::addressof(std::clamp(v, min, max, cmp)) == std::addressof(v); } template<typename T> [[nodiscard]] constexpr bool is_between( const T& v, const boost::type_identity_t<T>& min, const boost::type_identity_t<T>& max ) { return is_between(v, min, max, std::less<>{}); } #define AUTO_MEMBER(name, ini) decltype(ini) name = ini #define CONST_AUTO_MEMBER(name, ini) const decltype(ini) name = ini #define CONST_AUTO_REF_MEMBER(name, ini) const decltype(ini)& name = ini namespace details { inline static std::random_device random_device; inline static std::mt19937 random_engine{std::random_device{}()}; } constexpr auto& get_random_device() { return details::random_device; } constexpr auto& get_random_engine() { return details::random_engine; } CPP_template(typename T)(requires std::is_enum_v<T>) constexpr auto to_underlying(const T v) { return static_cast<std::underlying_type_t<T>>(v); } }
{ "alphanum_fraction": 0.6572594356, "avg_line_length": 26.4954954955, "ext": "h", "hexsha": "a5ff54db34b182b6b87ebae4fc570172a876ed1e", "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": "616eac5d99775a9c130bfea7bf856d21d2528002", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BlurringShadow/Polycumic", "max_forks_repo_path": "polycumic/utility/include/utility_core.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "616eac5d99775a9c130bfea7bf856d21d2528002", "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": "BlurringShadow/Polycumic", "max_issues_repo_path": "polycumic/utility/include/utility_core.h", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "616eac5d99775a9c130bfea7bf856d21d2528002", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "BlurringShadow/Polycumic", "max_stars_repo_path": "polycumic/utility/include/utility_core.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 747, "size": 2941 }
#ifndef COMMON_HEADER_H #define COMMON_HEADER_H //Include Standard Headers #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdint.h> #include <stdbool.h> //Math Libraries //#include <math.h> #include <limits.h> //#include <gsl/gsl_sf_bessel.h> //RNG Libraries: #include <linux/random.h> //POSIX libraries: #include <unistd.h> #include <pthread.h> //Ncurses //#include <ncurses.h> #endif
{ "alphanum_fraction": 0.7222222222, "avg_line_length": 17.3076923077, "ext": "h", "hexsha": "224e52c60bf05527712a9fe4e3aaa2ad88ebf72c", "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": "b60cbc404bf3f24b4b70e03d1ea5ce46df7900e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ucarlos/ucarlos-computer-systems-solutions", "max_forks_repo_path": "Third Edition/Chapter 2/common_header.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b60cbc404bf3f24b4b70e03d1ea5ce46df7900e9", "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": "ucarlos/ucarlos-computer-systems-solutions", "max_issues_repo_path": "Third Edition/Chapter 2/common_header.h", "max_line_length": 32, "max_stars_count": null, "max_stars_repo_head_hexsha": "b60cbc404bf3f24b4b70e03d1ea5ce46df7900e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ucarlos/ucarlos-computer-systems-solutions", "max_stars_repo_path": "Third Edition/Chapter 2/common_header.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 117, "size": 450 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stddef.h> #include <unistd.h> #include <math.h> #include "bigfile-mpi.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void usage() { fprintf(stderr, "usage: bigfile-sample-mpi [-r ratio] [-N Nfile] [-f newfilepath] filepath block newblock\n"); exit(1); } #define DONE_TAG 1293 #define ERROR_TAG 1295 #define DIE_TAG 1290 #define WORK_TAG 1291 MPI_Datatype MPI_TYPE_WORK; BigFile bf = {0}; BigFile bfnew = {0}; BigBlock bb = {0}; BigBlock bbnew = {0}; int verbose = 0; int Nfile = -1; size_t CHUNKSIZE = 1 * 1024 * 1024; int ThisTask, NTask; char * newfilepath = NULL; void slave(void); void server(void); double ratio = 1.0; struct work { int64_t offset; int64_t seed; int64_t chunksize; int64_t offsetnew; int64_t nsel; }; static size_t filesize(); int main(int argc, char * argv[]) { MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask); MPI_Comm_size(MPI_COMM_WORLD, &NTask); MPI_Type_contiguous(sizeof(struct work), MPI_BYTE, &MPI_TYPE_WORK); MPI_Type_commit(&MPI_TYPE_WORK); int ch; while(-1 != (ch = getopt(argc, argv, "n:N:vf:r:"))) { switch(ch) { case 'r': ratio = atof(optarg); break; case 'N': case 'n': Nfile = atoi(optarg); break; case 'f': newfilepath = optarg; break; case 'v': verbose = 1; break; default: usage(); } } if(argc - optind + 1 != 4) { usage(); } argv += optind - 1; if(0 != big_file_mpi_open(&bf, argv[1], MPI_COMM_WORLD)) { fprintf(stderr, "failed to open: %s\n", big_file_get_error_message()); exit(1); } if(0 != big_file_mpi_open_block(&bf, &bb, argv[2], MPI_COMM_WORLD)) { fprintf(stderr, "failed to open: %s\n", big_file_get_error_message()); exit(1); } if(Nfile == -1 || bb.Nfile == 0) { Nfile = bb.Nfile; } if(newfilepath == NULL) { newfilepath = argv[1]; } if(0 != big_file_mpi_create(&bfnew, newfilepath, MPI_COMM_WORLD)) { fprintf(stderr, "failed to open: %s\n", big_file_get_error_message()); exit(1); } size_t newsize = filesize(); if(0 != big_file_mpi_create_block(&bfnew, &bbnew, argv[3], bb.dtype, bb.nmemb, Nfile, newsize, MPI_COMM_WORLD)) { fprintf(stderr, "failed to create temp: %s\n", big_file_get_error_message()); exit(1); } /* copy attrs */ size_t nattr; BigAttr * attrs = big_block_list_attrs(&bb, &nattr); int i; for(i = 0; i < nattr; i ++) { BigAttr * attr = &attrs[i]; big_block_set_attr(&bbnew, attr->name, attr->data, attr->dtype, attr->nmemb); } if(bb.nmemb > 0 && bb.size > 0) { /* copy data */ if(ThisTask == 0) { server(); } else { slave(); } } if(0 != big_block_mpi_close(&bbnew, MPI_COMM_WORLD)) { fprintf(stderr, "failed to close new: %s\n", big_file_get_error_message()); exit(1); } big_block_mpi_close(&bb, MPI_COMM_WORLD); big_file_mpi_close(&bf, MPI_COMM_WORLD); big_file_mpi_close(&bfnew, MPI_COMM_WORLD); return 0; } static size_t filesize() { gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(rng, 1984); int64_t offset = 0; int64_t offsetnew = 0; struct work work; for(offset = 0; offset < bb.size; ) { int64_t chunksize = CHUNKSIZE; /* never read beyond my end (read_simple caps at EOF) */ if(offset + chunksize >= bb.size) { /* this is the last chunk */ chunksize = bb.size - offset; } work.offset = offset; work.chunksize = chunksize; work.seed = gsl_rng_get(rng); work.offsetnew = offsetnew; if(ratio == 1.0) { work.nsel = chunksize; } else { work.nsel = gsl_ran_poisson(rng, chunksize * ratio); } offset += chunksize; offsetnew += work.nsel; } return offsetnew; } void server() { int64_t offset = 0; int64_t offsetnew = 0; struct work work; gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(rng, 1984); for(offset = 0; offset < bb.size; ) { int64_t chunksize = CHUNKSIZE; MPI_Status status; int result = 0; MPI_Recv(&result, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); if(status.MPI_TAG == ERROR_TAG) { break; } /* never read beyond my end (read_simple caps at EOF) */ if(offset + chunksize >= bb.size) { /* this is the last chunk */ chunksize = bb.size - offset; } work.offset = offset; work.chunksize = chunksize; work.seed = gsl_rng_get(rng); work.offsetnew = offsetnew; if(ratio == 1.0) { work.nsel = chunksize; } else { work.nsel = gsl_ran_poisson(rng, chunksize * ratio); } MPI_Send(&work, 1, MPI_TYPE_WORK, status.MPI_SOURCE, WORK_TAG, MPI_COMM_WORLD); offset += chunksize; offsetnew += work.nsel; if(verbose) { fprintf(stderr, "%td / %td done (%0.4g%%)\r", offset, bb.size, (100. / bb.size) * offset); } } int i; for(i = 1; i < NTask; i ++) { struct work work; MPI_Send(&work, 1, MPI_TYPE_WORK, i, DIE_TAG, MPI_COMM_WORLD); } } void slave() { gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); int result = 0; MPI_Send(&result, 1, MPI_INT, 0, DONE_TAG, MPI_COMM_WORLD); while(1) { struct work work; MPI_Status status; MPI_Recv(&work, 1, MPI_TYPE_WORK, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); if(status.MPI_TAG == DIE_TAG) { break; } gsl_rng_set(rng, work.seed); int64_t offset = work.offset; int64_t chunksize = work.chunksize; int64_t offsetnew = work.offsetnew; int64_t nsel = work.nsel; BigArray array; BigBlockPtr ptrnew; BigArray arraynew; size_t dims[2]; void * buffer = malloc(dtype_itemsize(bb.dtype) * bb.nmemb * nsel); dims[0] = nsel; dims[1] = bb.nmemb; big_array_init(&arraynew, buffer, bb.dtype, 2, dims, NULL); ptrdiff_t i; size_t step = dtype_itemsize(bb.dtype) * bb.nmemb; size_t leftover = chunksize; char * p = buffer; char * q; if(0 != big_block_read_simple(&bb, offset, chunksize, &array, NULL)) { fprintf(stderr, "failed to read original: %s\n", big_file_get_error_message()); result = -1; goto bad; } q = array.data; // printf("%ld %ld\n", nsel, leftover); for(i = 0; i < chunksize; i ++) { int64_t r = gsl_rng_uniform_int(rng, leftover); if(r < nsel) { memcpy(p, q, step); p += step; nsel --; } if(nsel == 0) break; leftover --; q += step; } if(nsel != 0) abort(); free(array.data); if(0 != big_block_seek(&bbnew, &ptrnew, offsetnew)) { fprintf(stderr, "failed to seek new: %s\n", big_file_get_error_message()); result = -1; free(arraynew.data); goto bad; } if(0 != big_block_write(&bbnew, &ptrnew, &arraynew)) { fprintf(stderr, "failed to write new: %s\n", big_file_get_error_message()); result = -1; free(arraynew.data); goto bad; } free(arraynew.data); MPI_Send(&result, 1, MPI_INT, 0, DONE_TAG, MPI_COMM_WORLD); continue; bad: MPI_Send(&result, 1, MPI_INT, 0, ERROR_TAG, MPI_COMM_WORLD); continue; } return; }
{ "alphanum_fraction": 0.5500061812, "avg_line_length": 28.7864768683, "ext": "c", "hexsha": "3dcf31b6a65d8724fb895c60333ce8bd6af06a67", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2016-10-18T21:31:01.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-28T02:59:23.000Z", "max_forks_repo_head_hexsha": "33e51c9168862fb9913daf74b0b00595ae6894b1", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "rainwoodman/bigfile", "max_forks_repo_path": "utils/bigfile-sample-mpi.c", "max_issues_count": 28, "max_issues_repo_head_hexsha": "33e51c9168862fb9913daf74b0b00595ae6894b1", "max_issues_repo_issues_event_max_datetime": "2021-01-11T16:26:22.000Z", "max_issues_repo_issues_event_min_datetime": "2016-03-08T01:20:26.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "rainwoodman/bigfile", "max_issues_repo_path": "utils/bigfile-sample-mpi.c", "max_line_length": 117, "max_stars_count": 15, "max_stars_repo_head_hexsha": "33e51c9168862fb9913daf74b0b00595ae6894b1", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "rainwoodman/bigfile", "max_stars_repo_path": "utils/bigfile-sample-mpi.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:51:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-28T14:10:33.000Z", "num_tokens": 2198, "size": 8089 }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include "utils.h" #include "norm.h" /* * * Program that reads reference spectra and measure spectra data * and linearly unmixes the data using method of least squares fit. * Assumes readings is set to 400 and file path is preset to: * * syntax: ./linearUnmixer MUfilename ref1filename ref2filename ref3filename ... * returns: completion status, prints composition of ref1, ref2, ... , refn * * * **************************************************************** * * Author Dept. Date Notes * * **************************************************************** * * Jake Z Bio. Eng. Mar 12 2020 Initial version * * Jake Z " Apr 03 2020 It works now! * TODO: investigate the discrepancy between what you set $readings and the amount * of space you allocate to the matrices as you forgot to account for the initial * data clearing of the title headers in the data. * */ const int readings = 1000; //num of data points in each reading const int skip = 50; //num of data points to discard from beginning int main(int argc, char *argv[]) { if ( argc <= 2 ) { fprintf( stderr, "error, incorrect usage.\n correct usage: ./unmix unknown ref1 ref2 ... refn\n"); return 3; } //allocate memory for vars int numRefs = argc - 2; char *filePath = "./assets/"; // create prompt/arg for desired assets gsl_vector *muVector = gsl_vector_alloc(readings); gsl_vector *fVector = gsl_vector_alloc(readings); gsl_vector *x = gsl_vector_alloc(numRefs); gsl_matrix *refMatrix = gsl_matrix_alloc(readings, numRefs); gsl_matrix *C = gsl_matrix_alloc( numRefs, numRefs ); gsl_matrix *Cinverse = gsl_matrix_alloc( numRefs, numRefs ); int s; gsl_permutation *p = gsl_permutation_alloc(numRefs); //initialize vars to 0 gsl_vector_set_zero(muVector); gsl_vector_set_zero(fVector); gsl_vector_set_zero(x); gsl_matrix_set_zero(refMatrix); gsl_matrix_set_zero(C); gsl_permutation_init(p); //INITIALISED THE PERMUTATION readFileVector( muVector, filePath, argv[1] ); //read vals of unknown arg readFileMatrix( refMatrix, filePath, argc, argv ); //read the refs into matrix normalizeVector( muVector ); //create fn that reads the files FILE *csvfile = fopen( "./muVector.csv", "wt" ); gsl_vector_fprintf( csvfile, muVector, "%f" ); fclose(csvfile); FILE *csvfile2 = fopen( "./refVectors.txt", "wt" ); gsl_matrix_fprintf( csvfile2, refMatrix, "%f" ); fclose(csvfile2); //now we have variable muVector with vals and refMatrix with vals. gsl_blas_dgemm( CblasTrans, CblasNoTrans, 1, refMatrix, refMatrix, 0, C); //matrix C is now A^T A gsl_blas_dgemv( CblasTrans, 1, refMatrix, muVector, 0, fVector); //fVector is 'b' gsl_linalg_LU_decomp( C, p, &s); gsl_linalg_LU_invert( C, p, Cinverse ); //TODO maybe implement the other way you can solve for basis using inverse on both sides, (A^T A )^-1 A^T A x = (a^t a)^-1 (a^t b) = x gsl_blas_dgemv( CblasNoTrans, 1, Cinverse, fVector, 0, x); gsl_vector_fprintf( stdout, x, "%f" ); gsl_matrix_free(Cinverse); gsl_matrix_free(C); gsl_matrix_free(refMatrix); gsl_vector_free(muVector); gsl_vector_free(fVector); gsl_vector_free(x); return 0; }
{ "alphanum_fraction": 0.6698858648, "avg_line_length": 33.1747572816, "ext": "c", "hexsha": "602d782d5cb56a477e24316ab17c57fb1049b532", "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": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jakeinater/spectralILU", "max_forks_repo_path": "src/unmixapp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "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": "jakeinater/spectralILU", "max_issues_repo_path": "src/unmixapp.c", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jakeinater/spectralILU", "max_stars_repo_path": "src/unmixapp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 956, "size": 3417 }
/* * kjg_fpca.c * * Created on: Apr 28, 2014 * Author: Kevin */ #include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_blas.h> #include "kjg_fpca.h" #include "kjg_gsl.h" #include "admutils.h" #include "gval.h" size_t KJG_FPCA_ROWS = 256; void kjg_fpca (size_t K, size_t L, size_t I, double *eval, double *evec) { if (K >= L) exit (1); if (I == 0) exit (1); size_t m = get_ncols (); size_t n = get_nrows (); // PART A - compute Q such that X ~ Q * (Q^T) * X gsl_matrix *G1 = gsl_matrix_alloc (n, L); gsl_matrix *G2 = gsl_matrix_alloc (n, L); gsl_matrix *Q = gsl_matrix_alloc (m, (I + 1) * L); gsl_matrix *Gswap; gsl_rng *r = kjg_gsl_rng_init (); kjg_gsl_ran_ugaussian_matrix (r, G1); gsl_rng_free (r); size_t i; for (i = 0; i < I; i++) { gsl_matrix_view Qi = gsl_matrix_submatrix (Q, 0, i * L, m, L); // do the multiplication kjg_fpca_XTXA (G1, &Qi.matrix, G2); // scale to prevent G2 from blowing up gsl_matrix_scale (G2, 1.0 / m); Gswap = G2; G2 = G1; G1 = Gswap; } gsl_matrix_view Qi = gsl_matrix_submatrix (Q, 0, I * L, m, L); kjg_fpca_XA (G1, &Qi.matrix); { gsl_matrix *V = gsl_matrix_alloc (Q->size2, Q->size2); gsl_vector *S = gsl_vector_alloc (Q->size2); kjg_gsl_SVD (Q, V, S); gsl_matrix_free (V); gsl_vector_free (S); } // kjg_gsl_matrix_QR(Q); // QR decomposition is less accurate than SVD gsl_matrix_free (G1); gsl_matrix_free (G2); // PART B - compute B matrix, take SVD and return gsl_matrix *B = gsl_matrix_alloc (n, (I + 1) * L); kjg_fpca_XTB (Q, B); gsl_matrix *Utilda = gsl_matrix_alloc ((I + 1) * L, (I + 1) * L); gsl_vector *Stilda = gsl_vector_alloc ((I + 1) * L); kjg_gsl_SVD (B, Utilda, Stilda); gsl_matrix_view Vk = gsl_matrix_submatrix (B, 0, 0, n, K); gsl_matrix_view evec_view = gsl_matrix_view_array (evec, n, K); gsl_matrix_memcpy (&evec_view.matrix, &Vk.matrix); gsl_vector_view Sk = gsl_vector_subvector (Stilda, 0, K); gsl_vector_view eval_view = gsl_vector_view_array (eval, K); gsl_vector_mul (&Sk.vector, &Sk.vector); gsl_vector_scale (&Sk.vector, 1.0 / m); gsl_vector_memcpy (&eval_view.vector, &Sk.vector); gsl_matrix_free (Q); gsl_matrix_free (B); gsl_matrix_free (Utilda); gsl_vector_free (Stilda); } void kjg_fpca_XTXA (const gsl_matrix * A1, gsl_matrix * B, gsl_matrix * A2) { size_t m = get_ncols (); size_t n = get_nrows (); size_t i, r; // row index double *Y = malloc (sizeof (double) * n * KJG_FPCA_ROWS); // normalized gsl_matrix_view Bi, Xi; gsl_matrix_set_zero (A2); for (i = 0; i < m; i += KJG_FPCA_ROWS) { r = kjg_geno_get_normalized_rows (i, KJG_FPCA_ROWS, Y); Xi = gsl_matrix_view_array (Y, r, n); Bi = gsl_matrix_submatrix (B, i, 0, r, B->size2); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1, &Xi.matrix, A1, 0, &Bi.matrix); gsl_blas_dgemm (CblasTrans, CblasNoTrans, 1, &Xi.matrix, &Bi.matrix, 1, A2); } free (Y); } void kjg_fpca_XA (const gsl_matrix * A, gsl_matrix * B) { size_t n = get_nrows (); size_t m = get_ncols (); size_t i, r; double *Y = malloc (sizeof (double) * n * KJG_FPCA_ROWS); gsl_matrix_view Hmat, Xmat; gsl_matrix_set_zero (B); for (i = 0; i < m; i += KJG_FPCA_ROWS) { r = kjg_geno_get_normalized_rows (i, KJG_FPCA_ROWS, Y); Xmat = gsl_matrix_view_array (Y, r, n); Hmat = gsl_matrix_submatrix (B, i, 0, r, B->size2); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1, &Xmat.matrix, A, 0, &Hmat.matrix); } free (Y); } void kjg_fpca_XTB (const gsl_matrix * B, gsl_matrix * A) { size_t n = get_nrows (); size_t m = get_ncols (); size_t i, r; double *Y = malloc (sizeof (double) * n * KJG_FPCA_ROWS); gsl_matrix_view Xmat; gsl_matrix_set_zero (A); for (i = 0; i < m; i += KJG_FPCA_ROWS) { r = kjg_geno_get_normalized_rows (i, KJG_FPCA_ROWS, Y); Xmat = gsl_matrix_view_array (Y, r, n); gsl_matrix_const_view Hmat = gsl_matrix_const_submatrix (B, i, 0, r, B->size2); gsl_blas_dgemm (CblasTrans, CblasNoTrans, 1, &Xmat.matrix, &Hmat.matrix, 1, A); } free (Y); }
{ "alphanum_fraction": 0.628225994, "avg_line_length": 24.0279329609, "ext": "c", "hexsha": "4fb16ce86baecc5bb7a6a3f0afd280314d48ae8d", "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": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "nevrome/EIG", "max_forks_repo_path": "src/ksrc/kjg_fpca.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "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": "nevrome/EIG", "max_issues_repo_path": "src/ksrc/kjg_fpca.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "nevrome/EIG", "max_stars_repo_path": "src/ksrc/kjg_fpca.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1526, "size": 4301 }
/* interpolation/gsl_spline2d.h * * Copyright 2012 David Zaslavsky * * 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_SPLINE2D_H__ #define __GSL_SPLINE2D_H__ #include <gsl/gsl_interp.h> #include <gsl/gsl_interp2d.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 /* * A 2D interpolation object which stores the arrays defining the function. * In all other respects, this is just like a gsl_interp2d object. */ typedef struct { gsl_interp2d interp_object; /* low-level interpolation object */ double * xarr; /* x data array */ double * yarr; /* y data array */ double * zarr; /* z data array */ } gsl_spline2d; gsl_spline2d * gsl_spline2d_alloc(const gsl_interp2d_type * T, size_t xsize, size_t ysize); int gsl_spline2d_init(gsl_spline2d * interp, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize); void gsl_spline2d_free(gsl_spline2d * interp); double gsl_spline2d_eval(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya); int gsl_spline2d_eval_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya, double * z); double gsl_spline2d_eval_deriv_x(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya); int gsl_spline2d_eval_deriv_x_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya, double * z); double gsl_spline2d_eval_deriv_y(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya); int gsl_spline2d_eval_deriv_y_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya, double * z); double gsl_spline2d_eval_deriv_xx(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya); int gsl_spline2d_eval_deriv_xx_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya, double * z); double gsl_spline2d_eval_deriv_yy(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya); int gsl_spline2d_eval_deriv_yy_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya, double * z); double gsl_spline2d_eval_deriv_xy(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya); int gsl_spline2d_eval_deriv_xy_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel* xa, gsl_interp_accel* ya, double * z); size_t gsl_spline2d_min_size(const gsl_spline2d * interp); const char * gsl_spline2d_name(const gsl_spline2d * interp); int gsl_spline2d_set(const gsl_spline2d * interp, double zarr[], const size_t i, const size_t j, const double z); double gsl_spline2d_get(const gsl_spline2d * interp, const double zarr[], const size_t i, const size_t j); __END_DECLS #endif /* __GSL_SPLINE2D_H__ */
{ "alphanum_fraction": 0.6523623754, "avg_line_length": 40.4736842105, "ext": "h", "hexsha": "2349813e9351698e0f3cf11045f0f4ad590215b1", "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": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_path": "gsl-2.6/gsl/gsl_spline2d.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/gsl/gsl_spline2d.h", "max_line_length": 94, "max_stars_count": null, "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/gsl/gsl_spline2d.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1092, "size": 4614 }
#include <stdio.h> #include <stdlib.h> #include <argp.h> #include <string.h> #include <assert.h> #include <stdint.h> #include "utils.h" #ifdef USE_MKL #pragma message "Using the MKL for BLAS." #include <mkl.h> #else #pragma message "Not using the MKL for BLAS." #include <cblas.h> #endif #define MAX_LINES 2000 #define NB_RUNS 1 #define MAX_NAME_SIZE 256 #define MAX_OFFSET 1000000 #define WRITE_MEMORY_SIZE 100000000 FILE* active_file = NULL; char* basename = "calibration"; char* dir_name = "."; static double *matrix_A; static double *matrix_B; static double *matrix_C; unsigned long long base_time; typedef struct { char* sizefile; int loop; char* resultfile; } my_args; static char doc[] = "Runs BLAS benchmarks to compute values used for SMPI calibration"; static struct argp_option options[] = { {"sizeFile", 's', "SIZEFILE", 0, "filename of the size list"}, {"resultfile", 'o', "RESULTFILE", 0, "filename of the results"}, {"loop", 'l', "NB_LOOPS", 0, "number of (non-recorded) loops to run before and after the execution"}, { 0 } }; static int parse_options (int key, char *arg, struct argp_state *state) { my_args *arguments = state->input; switch (key){ case 'l': arguments->loop = atoi(arg); break; case 's': arguments->sizefile = arg; break; case 'o': arguments->resultfile = arg; break; default: return ARGP_ERR_UNKNOWN; } return 0; } struct argp argp = { options, parse_options, NULL, doc }; my_args arguments; /* * Return 0b000...01...1, with n ones at the end. */ uint64_t __get_mask(unsigned n) { if(n == 0) return 0; assert(n >= 0 && n < 64); uint64_t mask = 1; return (mask << n) - 1; } /* * Return 0b000...01...10...0. * The bits at positions [start, stop] are equal to 1, the others to 0 (start is the lower order). */ uint64_t get_mask(unsigned start, unsigned stop) { assert(0 <= start && start <= stop && stop < 64); uint64_t ones = __get_mask(stop); uint64_t zeroes = ~__get_mask(start); return ones & zeroes; } /* * Apply the given mask to a double. */ double apply_mask(double x, uint64_t mask) { uint64_t *tmp = (uint64_t*)&x; (*tmp) |= mask; return *((double*)tmp); } void __print_bits(uint64_t n, unsigned i) { if(i == 64) return; __print_bits(n / 2, i+1); if(n % 2) printf("1"); else printf("0"); } void print_bits(uint64_t n) { printf("0b"); __print_bits(n, 0); printf("\n"); } void print_bits_f(double x) { uint64_t *tmp = (uint64_t*)&x; print_bits(*tmp); } double *allocate_matrix(size_t size1, size_t size2) { size_t alloc_size = (size1*size2 + MAX_OFFSET) * sizeof(double); double *result = (double*) malloc(alloc_size); if(!result) { perror("malloc"); exit(errno); } #ifdef MASK_SIZE uint64_t mask = get_mask(0, MASK_SIZE); #pragma message "Using a mask for the values of the matrix." #else // Note that this particular mask does not do anything: apply_mask(x, get_mask(0, 0)) == x // One need to change the stop and/or start indices to really apply a mask. uint64_t mask = get_mask(0, 0); #endif printf("Using the mask: "); print_bits(mask); double x = 3.1415926535897932384626433; assert(x == apply_mask(x, get_mask(0, 0))); assert(x != apply_mask(x, get_mask(0, 1))); for(int i = 0; i < size1*size2; i++) { result[i] = apply_mask((double)rand()/(double)(RAND_MAX), mask); } return result; } void write_memory(void) { static char *buff = NULL; if(!buff) { buff = malloc(WRITE_MEMORY_SIZE); if(!buff) { perror("malloc"); exit(errno); } } memset(buff, rand()%256, WRITE_MEMORY_SIZE); } FILE *open_file(const char* filename){ FILE *file = fopen(filename, "w"); if(!file) { perror("open_file"); exit(errno); } return file; } void get_dgemm(FILE *file, int *sizes, int nb_it, unsigned long long base_time, int write_file) { unsigned long long start_time, total_time; double alpha = 1., beta=1.; for(int i=0; i<nb_it; i++) { start_time=get_time(); size_t offset = rand() % MAX_OFFSET; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, sizes[0], sizes[1], sizes[2], alpha, matrix_A+offset, sizes[3], matrix_B+offset, sizes[4], beta, matrix_C+offset, sizes[5]); total_time=get_time()-start_time; if(write_file) print_in_file(file, "dgemm", sizes, 6, start_time-base_time, total_time); } } static const char *names[] = {"dgemm", NULL}; static const void (*functions[])(FILE*, int*, int, unsigned long long, int) = {get_dgemm}; void test_op(FILE *result_file, experiment_t *exp, int nb_runs, unsigned long long base_time, int write_file) { functions[exp->op_id](result_file, exp->sizes, nb_runs, base_time, write_file); } int get_max_size(experiment_t *exp, int nb_exp, int idx) { int max = -1; for(int i = 0; i < nb_exp; i++) { int size = exp[i].sizes[idx]; if(max < size) max = size; } return max; } int main(int argc, char** argv){ srand(42); bzero (&arguments, sizeof(my_args)); if (argp_parse (&argp, argc, argv, 0, 0, &arguments) == ARGP_KEY_ERROR){ fprintf(stderr,"error during the parsing of parameters\n"); return 1; } int nb_loops = arguments.loop; if(arguments.sizefile==NULL){ fprintf(stderr, "Please provide a name for a file containing a list of sizes\n"); return -1; } if(arguments.resultfile==NULL){ fprintf(stderr, "Please provide a name for a result file\n"); return -1; } FILE *result_file = NULL; if(arguments.resultfile) result_file = open_file(arguments.resultfile); int nb_exp, largest_size; experiment_t *experiments = parse_experiment_file(names, arguments.sizefile, &nb_exp, &largest_size, -1, 300000, 6); printf("nb_exp=%d, largest_size=%d\n", nb_exp, largest_size); size_t max_size = (size_t)largest_size*(size_t)largest_size; int max_M = get_max_size(experiments, nb_exp, 0); int max_N = get_max_size(experiments, nb_exp, 1); int max_K = get_max_size(experiments, nb_exp, 2); printf("max(M)=%d | max(N)=%d | max(K)=%d\n", max_M, max_N, max_K); printf("Alloc size: was %.2e bytes\n", (double)(max_size)*sizeof(double)*3); double alloc_size = (double)max_M*(double)max_K; alloc_size += (double)max_K*(double)max_N; alloc_size += (double)max_M*(double)max_N; printf("Alloc size: now %.2e bytes\n", alloc_size*sizeof(double)); matrix_A = allocate_matrix(max_M, max_K); matrix_B = allocate_matrix(max_K, max_N); matrix_C = allocate_matrix(max_M, max_N); //Init time base_time=get_time(); for(int i = 0; i < nb_loops; i++) { for(int j = 0; j < nb_exp; j++) { test_op(result_file, &experiments[j], NB_RUNS, base_time, 0); } } for(int j = 0; j < nb_exp; j++) { test_op(result_file, &experiments[j], NB_RUNS, base_time, 1); } for(int i = 0; i < nb_loops; i++) { for(int j = 0; j < nb_exp; j++) { test_op(result_file, &experiments[j], NB_RUNS, base_time, 0); } } fflush(result_file); fclose(result_file); free(experiments); free(matrix_A); free(matrix_B); free(matrix_C); return 0; }
{ "alphanum_fraction": 0.646051905, "avg_line_length": 26.5347985348, "ext": "c", "hexsha": "7c43bbec5ea4df22297fa0a846a0fe0a1fd60af6", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-11-07T15:52:04.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-07T15:52:04.000Z", "max_forks_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Ezibenroc/platform-calibration", "max_forks_repo_path": "src/calibration/calibrate_blas.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:50:51.000Z", "max_issues_repo_issues_event_min_datetime": "2022-01-13T10:44:10.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Ezibenroc/platform-calibration", "max_issues_repo_path": "src/calibration/calibrate_blas.c", "max_line_length": 120, "max_stars_count": 1, "max_stars_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Ezibenroc/platform-calibration", "max_stars_repo_path": "src/calibration/calibrate_blas.c", "max_stars_repo_stars_event_max_datetime": "2018-11-06T16:12:26.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-06T16:12:26.000Z", "num_tokens": 2136, "size": 7244 }
#if !defined(UTIL_H) #define UTIL_H #include <gsl/gsl_matrix.h> // Flag to set if the program should exit on GSL error const static bool EXIT_ON_GSL_ERROR = false; struct stability_params { double lambda[8]; double l; double u; double m; double v; }; struct integration_params { double M; double m1; double m2; double gamma; }; struct integration_params2 { double M; double x1; double m; double gamma; }; struct integration_params_tt { double M; double mW; double mb; double mt; double x1; double gtop; int h; }; struct integration_params_tb { double M; double mW; double mb; double mt; double x1; double gtop; double md; double Z_u; double Z_d; }; int sign(double x); double stability_fcn(double x, void *params); bool stability_minimum(stability_params &p); void print_gsl_matrix(gsl_matrix *mat,int m,int n); double fint(double x, void* par); double gint(double x, void* par); double Lint_s(double x, void *param); double Lint_p(double x, void *param); double Lint_c(double x, void *param); double hvv_fcn(double y, void *params); double hvv_fcn1(double y, void *params); double hvv_fcn2(double y, void *params); double htt_fcn1(double y, void *params); double htt_fcn2(double y, void *params); double htb_fcn1(double y, void *params); double htb_fcn2(double y, void *params); double cubic(double x, double X[4], double Y[4]); double hvh_fcn(double x, void *params); double L(double x, double y, double z); double DHp(double ui, double uj, double xi, double xj, double sqL); double DHm(double ui, double uj, double xi, double xj, double sqL); double BHp(double ui, double uj, double xi, double xj, double sqL); double sqrtlambda(double a1, double a2, double a3); #endif
{ "alphanum_fraction": 0.7087818697, "avg_line_length": 17.8282828283, "ext": "h", "hexsha": "eaddaaeac2048da1ff46d5bb92a79577955289d0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-11-27T14:59:29.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-27T14:59:29.000Z", "max_forks_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_forks_repo_path": "src/Util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "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": "shiggs90/2HDMC-NLO-master-wei", "max_issues_repo_path": "src/Util.h", "max_line_length": 68, "max_stars_count": null, "max_stars_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_stars_repo_path": "src/Util.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 501, "size": 1765 }
/* * 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 rectpack_89b58399_0f97_4cb9_9160_0226504762b1_h #define rectpack_89b58399_0f97_4cb9_9160_0226504762b1_h #include <ariel/config.h> #include <gslib/bintree.h> #include <gslib/std.h> #include <gslib/math.h> #include <ariel/type.h> __ariel_begin__ struct rp_rect { float x, y; /* left, top */ float width, height; public: rp_rect() { x = y = width = height = 0.f; } rp_rect(float l, float t, float w, float h) { set_rect(l, t, w, h); } void set_rect(float l, float t, float w, float h) { x = l, y = t, width = w, height = h; } float left() const { return x; } float top() const { return y; } float right() const { return x + width; } float bottom() const { return y + height; } void move_to(float destx, float desty) { x = destx, y = desty; } void offset(float cx, float cy) { x += cx, y += cy; } float area() const { return width * height; } }; struct rp_node: public rp_rect { bool transposed; void* bind_ptr; public: rp_node() { transposed = false; bind_ptr = nullptr; } virtual ~rp_node() {} virtual bool is_dynamic() const { return false; } virtual void set_transposed(bool b) { transposed = b; } virtual string to_string() const { return string(); } /* for debug only */ void set_bind_ptr(void* p) { bind_ptr = p; } bool is_empty() const { return !bind_ptr; } }; struct rp_dynamic_node: public rp_node { rp_rect blank; bool has_blank; /* tag of blank. | only valid on a non-leaf node. */ bool is_vert_arrange; /* vertical arrangement? | only valid on a non-leaf node. */ public: rp_dynamic_node() { has_blank = false; } virtual bool is_dynamic() const override { return true; } virtual void set_transposed(bool b) override; virtual string to_string() const override; float get_area() const; void set_no_blank(); void set_blank(const rp_rect& rc); void set_from_local(rp_dynamic_node& p); void set_dimensions(float w, float h); void move_to_pos(float x, float y); void flip_leaf(); void flip_non_leaf(); }; typedef _bintreenode_wrapper<rp_node> rp_wrapper; typedef _bintree_allocator<rp_wrapper> rp_allocator; typedef bintree<rp_node, rp_wrapper, rp_allocator> rp_tree; typedef rp_tree::iterator rp_iterator; typedef rp_tree::const_iterator rp_const_iterator; struct rp_input { float width, height; void* binding; }; typedef list<rp_input> rp_input_list; extern void rp_global_location(rp_const_iterator i, rp_rect& rc); extern bool rp_is_node_transposed(rp_const_iterator i); class rect_packer { public: enum packing_strategy { ps_unknown, ps_compactly, ps_dynamically, }; public: rect_packer(); ~rect_packer(); const rp_node& get_root_node() const { return *_tree.const_root(); } bool is_empty() const { return !_tree.is_valid(); } float get_width() const { return _tree.const_root()->width; } float get_height() const { return _tree.const_root()->height; } int get_pack_times() const { return _pack_times; } void pack_automatically(rp_input_list& inputs); void tracing() const; void trace_total() const; void trace_blank() const; void trace_tree() const; bool checkups() const; public: template<class _lamb> void for_each(rp_iterator i, _lamb fn) { assert(i); _tree.preorder_traversal([&fn](rp_wrapper* w) { assert(w); rp_iterator i(w); if(i.is_leaf() && !i->is_empty()) { rp_rect rc; rp_global_location(i, rc); fn(i->bind_ptr, rc, i->transposed); } }); } template<class _lamb> void for_each(_lamb fn) { if(!_tree.is_valid()) return; for_each(_tree.get_root(), fn); } protected: rp_tree _tree; packing_strategy _strategy; int _pack_times; protected: void initialize_compactly(float w, float h); bool pack_compactly(const rp_input_list& inputs); bool add_rect_compactly(float w, float h, void* binding); void trace_compactly() const; void initialize_dynamically(); void add_rect_dynamically(float w, float h, void* binding); void add_rect_dynamically(rp_tree& rc); bool add_rect_dynamically(rp_tree& rc, rp_tree& xchg); void proc_fill_up(rp_iterator p, rp_tree& t); void proc_combine(rp_iterator p, rp_tree& t); void proc_combine_root(rp_iterator p, rp_tree& t); void proc_combine_non_root(rp_iterator p, rp_iterator i, rp_tree& t); void proc_replace(rp_iterator p, rp_tree& t, rp_tree& xchg); void trace_dynamically() const; }; __ariel_end__ #endif
{ "alphanum_fraction": 0.6360496153, "avg_line_length": 33.6984126984, "ext": "h", "hexsha": "1bbc52eff3699a0db79ff19bd53cec6470276f2f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/ariel/rectpack.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/ariel/rectpack.h", "max_line_length": 124, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/ariel/rectpack.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": 1531, "size": 6369 }
// matrix/snowboy-blas.h // Copyright 2016 KITT.AI (author: Guoguo Chen) #ifndef SNOWBOY_MATRIX_SNOWBOY_BLAS_H_ #define SNOWBOY_MATRIX_SNOWBOY_BLAS_H_ #ifdef HAVE_ATLAS extern "C" { #include <cblas.h> #include <clapack.h> } #elif defined(HAVE_CLAPACK) #ifdef __APPLE__ #ifndef __has_extension #define __has_extension(x) 0 #endif #define vImage_Utilities_h #define vImage_CVUtilities_h #include <Accelerate/Accelerate.h> typedef __CLPK_integer integer; typedef __CLPK_logical logical; // typedef __CLPK_real real; typedef __CLPK_doublereal doublereal; typedef __CLPK_complex complex; typedef __CLPK_doublecomplex doublecomplex; typedef __CLPK_ftnlen ftnlen; #else extern "C" { #include <cblas.h> #include <f2c.h> #include <clapack.h> // Removes dangerous macros from f2c.h. #undef abs #undef dabs #undef min #undef max #undef dmin #undef dmax #undef bit_test #undef bit_clear #undef bit_set } #endif // Defines SnowboyBlasInt type that will be used in SVD. typedef integer SnowboyBlasInt; #elif defined(HAVE_OPENBLAS) #include "cblas.h" #ifndef NO_FORTRAN #include "lapacke.h" #endif #undef I #undef complex // get rid of macros from f2c.h -- these are dangerous. #undef abs #undef dabs #undef min #undef max #undef dmin #undef dmax #undef bit_test #undef bit_clear #undef bit_set #else #error "You have to define HAVE_CLAPACK or HAVE_ATLAS or HAVE_OPENBLAS." #endif #endif // SNOWBOY_MATRIX_SNOWBOY_BLAS_H_
{ "alphanum_fraction": 0.6704750451, "avg_line_length": 23.7571428571, "ext": "h", "hexsha": "9d9c76ade062f1b4bf4afebdc0f1cbd1b26e0dce", "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": "ae5196e8087e79c92b7760c1abb1c53362d671ca", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "songmeixu/bit-matrix", "max_forks_repo_path": "snowboy-blas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ae5196e8087e79c92b7760c1abb1c53362d671ca", "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": "songmeixu/bit-matrix", "max_issues_repo_path": "snowboy-blas.h", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "ae5196e8087e79c92b7760c1abb1c53362d671ca", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "songmeixu/bit-matrix", "max_stars_repo_path": "snowboy-blas.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 508, "size": 1663 }
/*****************************************************************\ __ / / / / __ __ / /______ _______ / / / / ________ __ __ / ______ \ /_____ \ / / / / / _____ | / / / / / / | / _______| / / / / / / /____/ / / / / / / / / / / _____ / / / / / / _______/ / / / / / / / / / /____/ / / / / / / |______ / |______/ / /_/ /_/ |________/ / / / / \_______/ \_______ / /_/ /_/ / / / / 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 "halley/text/halleystring.h" #include "halley/file/path.h" #include <memory> #include <functional> #include <halley/concurrency/future.h> #include <gsl/gsl> #include "metadata.h" namespace Halley { enum class AssetType; class ResourceDataReader { public: virtual ~ResourceDataReader() {} virtual size_t size() const = 0; virtual int read(gsl::span<gsl::byte> dst) = 0; virtual void seek(int64_t pos, int whence) = 0; virtual size_t tell() const = 0; virtual void close() = 0; Bytes readAll(); }; class ResourceData { public: ResourceData(String path); virtual ~ResourceData() {} String getPath() const { return path; } private: String path; }; class ResourceDataStatic : public ResourceData { public: ResourceDataStatic(String path); ResourceDataStatic(const void* data, size_t size, String path, bool owning = true); void set(const void* data, size_t size, bool owning = true); bool isLoaded() const; const void* getData() const; gsl::span<const gsl::byte> getSpan() const; size_t getSize() const; String getString() const; void inflate(); static std::unique_ptr<ResourceDataStatic> loadFromFileSystem(Path path); void writeToFileSystem(String path) const; private: std::shared_ptr<const char> data; size_t size = 0; bool loaded; }; typedef std::function<std::unique_ptr<ResourceDataReader>()> ResourceDataMakeReader; class ResourceDataStream : public ResourceData { public: ResourceDataStream(String path, ResourceDataMakeReader makeReader); std::unique_ptr<ResourceDataReader> getReader() const { return make(); } private: ResourceDataMakeReader make; }; class IResourceLocator { public: virtual ~IResourceLocator() {} virtual const Metadata& getMetaData(const String& resource, AssetType type) const = 0; virtual std::unique_ptr<ResourceDataStatic> getStatic(const String& asset, AssetType type) = 0; virtual std::unique_ptr<ResourceDataStream> getStream(const String& asset, AssetType type) = 0; }; enum class ResourceLoadPriority { Low = 0, Normal = 1, High = 2 }; class HalleyAPI; class Metadata; class ResourceLoader { friend class ResourceCollectionBase; public: const String& getName() const { return name; } ResourceLoadPriority getPriority() const { return priority; } const HalleyAPI& getAPI() const { return *api; } const Metadata& getMeta() const { return *metadata; } std::unique_ptr<ResourceDataStatic> getStatic(); std::unique_ptr<ResourceDataStream> getStream(); Future<std::unique_ptr<ResourceDataStatic>> getAsync() const; private: ResourceLoader(ResourceLoader&& loader) noexcept; ResourceLoader(IResourceLocator& locator, const String& name, AssetType type, ResourceLoadPriority priority, const HalleyAPI* api); ~ResourceLoader(); IResourceLocator& locator; String name; AssetType type; ResourceLoadPriority priority; const HalleyAPI* api; const Metadata* metadata; bool loaded = false; }; }
{ "alphanum_fraction": 0.6435986159, "avg_line_length": 27.0287769784, "ext": "h", "hexsha": "60a26ef432ddc9d826a7b6093c7f94671d32bc68", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "lye/halley", "max_forks_repo_path": "src/engine/utils/include/halley/resources/resource_data.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "lye/halley", "max_issues_repo_path": "src/engine/utils/include/halley/resources/resource_data.h", "max_line_length": 133, "max_stars_count": 1, "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "lye/halley", "max_stars_repo_path": "src/engine/utils/include/halley/resources/resource_data.h", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "num_tokens": 933, "size": 3757 }
#ifndef DATA_PROCESS_H #define DATA_PROCESS_H #include <stdio.h> #include <string.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_statistics.h> #include <math.h> void support_degree_generator(gsl_matrix*, double*); void eigenvec_calc(gsl_vector*, gsl_matrix*, gsl_matrix*); void principal_comp_calc(gsl_matrix*, gsl_matrix*, gsl_matrix*); void contri_rate_calc_kth(gsl_vector*, double*); void major_contri_calc(double*, double*); void integ_supp_score_calc(double*, gsl_matrix*, gsl_vector*); void elliminate_incorrect_data(gsl_vector*, int*); void weight_coeff_calc(gsl_vector*, int*, double*); double fused_output(double*, double*); #endif
{ "alphanum_fraction": 0.7865329513, "avg_line_length": 31.7272727273, "ext": "h", "hexsha": "4f8915e994dbd38fd5e2121b90e2d83f91778a4b", "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": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "include/data_process.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "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": "karanbirsandhu/nu-sense", "max_issues_repo_path": "include/data_process.h", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "karanbirsandhu/nu-sense", "max_stars_repo_path": "include/data_process.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 169, "size": 698 }
#include "airsar.h" #include "asf_meta.h" #include <ctype.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> #define SQR(x) (x*x) static char *get_airsar(char *buf, char *str) { char *p, *q; static char value[51]; memset(value,0,51); q = (char *) CALLOC(51,sizeof(char)); p = strstr(buf, str); if (p) { strncpy(q, p, 50); strcpy(value, q+strlen(str)); //printf("%s: %s\n", str, value); } else strcpy(value, ""); FREE(q); return value; } airsar_header *read_airsar_header(const char *dataFile) { airsar_header *header = NULL; FILE *fp; char buf[4400], *value; double version; printf("\n\ndataFile: %s\n\n", dataFile); // Allocate memory and file handling value = (char *) MALLOC(sizeof(char)*25); header = (airsar_header *) CALLOC(1, sizeof(airsar_header)); fp = FOPEN(dataFile, "r"); if (fgets(buf, 4400, fp) == NULL) asfPrintError("Could not read general header\n"); FCLOSE(fp); // Check for the processor version // We take this as an indicator that we actually deal with AirSAR data version = atof(get_airsar(buf, "JPL AIRCRAFT SAR PROCESSOR VERSION")); // Read general header if (version > 0.0) { header->record_length = atoi(get_airsar(buf, "RECORD LENGTH IN BYTES =")); header->number_records = atoi(get_airsar(buf, "NUMBER OF HEADER RECORDS =")); header->sample_count = atoi(get_airsar(buf, "NUMBER OF SAMPLES PER RECORD =")); header->line_count = atoi(get_airsar(buf, "NUMBER OF LINES IN IMAGE =")); sprintf(header->processor, "%s", trim_spaces(get_airsar(buf, "JPL AIRCRAFT SAR PROCESSOR VERSION"))); value = trim_spaces(get_airsar(buf, "DATA TYPE =")); if (strcmp(value, "INTEGER*2") == 0) header->data_type = INTEGER16; sprintf(header->range_projection, "%s", trim_spaces(get_airsar(buf, "RANGE PROJECTION ="))); header->x_pixel_size = atof(get_airsar(buf, "RANGE PIXEL SPACING (METERS) =")); header->y_pixel_size = atof(get_airsar(buf, "AZIMUTH PIXEL SPACING (METERS) =")); header->first_data_offset = atoi(get_airsar(buf, "BYTE OFFSET OF FIRST DATA RECORD =")); if (header->first_data_offset == 0) header->first_data_offset = header->record_length*header->number_records; header->parameter_header_offset = atoi(get_airsar(buf, "BYTE OFFSET OF PARAMETER HEADER =")); header->calibration_header_offset = atoi(get_airsar(buf, "BYTE OFFSET OF CALIBRATION HEADER =")); header->dem_header_offset = atoi(get_airsar(buf, "BYTE OFFSET OF DEM HEADER =")); } return header; } airsar_param_header *read_airsar_params(const char *dataFile) { airsar_param_header *params=NULL; airsar_header *header = read_airsar_header(dataFile); FILE *fp; char *buf; int size; // Allocate memory and file handling params = (airsar_param_header *) CALLOC(1, sizeof(airsar_param_header)); if (header->calibration_header_offset > 0) size = header->calibration_header_offset - header->parameter_header_offset; else if (header->dem_header_offset > 0) size = header->dem_header_offset - header->parameter_header_offset; else size = header->first_data_offset - header->parameter_header_offset; buf = (char *) MALLOC(sizeof(char)*size); fp = FOPEN(dataFile, "r"); FSEEK(fp, header->parameter_header_offset, 1); if (fgets(buf, size, fp) == NULL) asfPrintError("Could not read parameter header\n"); FCLOSE(fp); // Read parameter header sprintf(params->site_name, "%s", trim_spaces(get_airsar(buf, "SITE NAME"))); sprintf(params->cct_type, "%s", trim_spaces(get_airsar(buf, "CCT TYPE"))); params->cct_id = atoi(get_airsar(buf, "CCT ID")); params->start_lat = atof(get_airsar(buf, "LATITUDE AT START OF SCENE (DEGREES)")); params->start_lon = atof(get_airsar(buf, "LONGITUDE AT START OF SCENE (DEGREES)")); params->end_lat = atof(get_airsar(buf, "LATITUDE AT END OF SCENE (DEGREES)")); params->end_lon = atof(get_airsar(buf, "LONGITUDE AT END OF SCENE (DEGREES)")); sprintf(params->acquisition_date, "%s", trim_spaces(get_airsar(buf, "DATE OF ACQUISITION (GMT)"))); params->acquisition_seconds = atof(get_airsar(buf, "TIME OF ACQUISITION: SECONDS IN DAY")); sprintf(params->frequencies, "%s", trim_spaces(get_airsar(buf, "FREQUENCIES COLLECTED"))); params->prf = atof(get_airsar(buf, "PRF AT START OF TRANSFER (HZ)")); params->range_sampling_rate = atof(get_airsar(buf, "SAMPLING RATE (MHZ)")); params->chirp_bandwidth = atof(get_airsar(buf, "CHIRP BANDWIDTH (MHZ)")); params->pulse_length = atof(get_airsar(buf, "PULSE LENGTH (MICROSECONDS)")); params->wavelength = atof(get_airsar(buf, "PROCESSOR WAVELENGTH (METERS)")); params->near_slant_range = atof(get_airsar(buf, "NEAR SLANT RANGE (METERS)")); params->far_slant_range = atof(get_airsar(buf, "FAR SLANT RANGE (METERS)")); params->near_look_angle = atof(get_airsar(buf, "NEAR LOOK ANGLE (DEGREES)")); params->far_look_angle = atof(get_airsar(buf, "FAR LOOK ANGLE (DEGEES)")); params->azimuth_look_count = atoi(get_airsar(buf, "NUMBER OF LOOKS PROCESSED IN AZIMUTH")); params->range_look_count = atoi(get_airsar(buf, "NUMBER OF LOOKS PROCESSED IN RANGE")); params->deskewed = atoi(get_airsar(buf, "DESKEW FLAG (1=DESKEWED, 2=NOT DESKEWED)")); params->sr_sample_spacing = atof(get_airsar(buf, "SLANT RANGE SAMPLE SPACING (METERS)")); params->slant_range_resolution = atof(get_airsar(buf, "NOMINAL SLANT RANGE RESOLUTION (METERS)")); params->azimuth_sample_spacing = atof(get_airsar(buf, "AZIMUTH SAMPLE SPACING (METERS)")); params->azimuth_resolution = atof(get_airsar(buf, "NOMINAL AZIMUTH RESOLUTION (METERS)")); params->center_lat = atof(get_airsar(buf, "IMAGE CENTER LATITUDE (DEGREES)")); params->center_lon = atof(get_airsar(buf, "IMAGE CENTER LONGITUDE (DEGREES)")); params->scale_factor = atof(get_airsar(buf, "GENERAL SCALE FACTOR")); params->cal_factor_hh = atof(get_airsar(buf, "CALIBRATION FACTOR APPLIED, DB, HH")); params->cal_factor_hv = atof(get_airsar(buf, "CALIBRATION FACTOR APPLIED, DB, HV")); params->cal_factor_vh = atof(get_airsar(buf, "CALIBRATION FACTOR APPLIED, DB, VH")); params->cal_factor_vv = atof(get_airsar(buf, "CALIBRATION FACTOR APPLIED, DB, VV")); params->gps_altitude = atof(get_airsar(buf, "GPS ALTITUDE, M")); params->lat_peg_point = atof(get_airsar(buf, "LATITUDE OF PEG POINT")); params->lon_peg_point = atof(get_airsar(buf, "LONGITUDE OF PEG POINT")); params->head_peg_point = atof(get_airsar(buf, "HEADING AT PEG POINT")); params->along_track_offset = atof(get_airsar(buf, "ALONG-TRACK OFFSET S0 (M)")); params->cross_track_offset = atof(get_airsar(buf, "CROSS-TRACK OFFSET C0 (M)")); return params; } airsar_dem_header *read_airsar_dem(const char *dataFile) { airsar_dem_header *dem = NULL; airsar_header *header = read_airsar_header(dataFile); FILE *fp; char *buf; int size; // Allocate memory and file handling dem = (airsar_dem_header *) CALLOC(1, sizeof(airsar_dem_header)); size = header->first_data_offset - header->dem_header_offset; buf = (char *) MALLOC(sizeof(char)*size); fp = FOPEN(dataFile, "r"); FSEEK(fp, header->dem_header_offset, 1); if (fgets(buf, size, fp) == NULL) asfPrintError("Could not read parameter header\n"); FCLOSE(fp); // Read DEM header dem->elevation_offset = atof(get_airsar(buf, "ELEVATION OFFSET (M) =")); dem->elevation_increment = atof(get_airsar(buf, "ELEVATION INCREMENT (M) =")); dem->corner1_lat = atof(get_airsar(buf, "LATITUDE OF CORNER 1 =")); dem->corner1_lon = atof(get_airsar(buf, "LONGITUDE OF CORNER 1 =")); dem->corner2_lat = atof(get_airsar(buf, "LATITUDE OF CORNER 2 =")); dem->corner2_lon = atof(get_airsar(buf, "LONGITUDE OF CORNER 2 =")); dem->corner3_lat = atof(get_airsar(buf, "LATITUDE OF CORNER 3 =")); dem->corner3_lon = atof(get_airsar(buf, "LONGITUDE OF CORNER 3 =")); dem->corner4_lat = atof(get_airsar(buf, "LATITUDE OF CORNER 4 =")); dem->corner4_lon = atof(get_airsar(buf, "LONGITUDE OF CORNER 4 =")); dem->lat_peg_point = atof(get_airsar(buf, "LATITUDE OF PEG POINT =")); dem->lon_peg_point = atof(get_airsar(buf, "LONGITUDE OF PEG POINT =")); dem->head_peg_point = atof(get_airsar(buf, "HEADING AT PEG POINT (DEGREES) =")); dem->along_track_offset = atof(get_airsar(buf, "ALONG-TRACK OFFSET S0 (M) =")); dem->cross_track_offset = atof(get_airsar(buf, "CROSS-TRACK OFFSET C0 (M) =")); return dem; } airsar_cal_header *read_airsar_cal(const char *dataFile) { airsar_cal_header *cal = NULL; airsar_header *header = read_airsar_header(dataFile); FILE *fp; char *buf; int size; // Allocate memory and file handling cal = (airsar_cal_header *) CALLOC(1, sizeof(airsar_cal_header)); size = header->first_data_offset - header->calibration_header_offset; buf = (char *) MALLOC(sizeof(char)*size); fp = FOPEN(dataFile, "r"); FSEEK(fp, header->calibration_header_offset, 1); if (fgets(buf, size, fp) == NULL) asfPrintError("Could not read parameter header\n"); FCLOSE(fp); // Read DEM header cal->scale_factor = atof(get_airsar(buf, "GENERAL SCALE FACTOR (dB)")); cal->hh_amp_cal_factor = atof(get_airsar(buf, "HH AMPLITUDE CALIBRATION FACTOR (dB)")); cal->hv_amp_cal_factor = atof(get_airsar(buf, "HV AMPLITUDE CALIBRATION FACTOR (dB)")); cal->vh_amp_cal_factor = atof(get_airsar(buf, "VH AMPLITUDE CALIBRATION FACTOR (dB)")); cal->vv_amp_cal_factor = atof(get_airsar(buf, "VV AMPLITUDE CALIBRATION FACTOR (dB)")); cal->hh_phase_cal_factor = atof(get_airsar(buf, "HH PHASE CALIBRATION FACTOR (DEGREES)")); cal->hv_phase_cal_factor = atof(get_airsar(buf, "HV PHASE CALIBRATION FACTOR (DEGREES)")); cal->vh_phase_cal_factor = atof(get_airsar(buf, "VH PHASE CALIBRATION FACTOR (DEGREES)")); cal->vv_phase_cal_factor = atof(get_airsar(buf, "VV PHASE CALIBRATION FACTOR (DEGREES)")); cal->hh_noise_sigma0 = atof(get_airsar(buf, "HH NOISE EQUIVALENT SIGMA ZERO (dB)")); cal->hv_noise_sigma0 = atof(get_airsar(buf, "HV NOISE EQUIVALENT SIGMA ZERO (dB)")); cal->vv_noise_sigma0 = atof(get_airsar(buf, "VV NOISE EQUIVALENT SIGMA ZERO (dB)")); cal->byte_offset_hh_corr = atof(get_airsar(buf, "BYTE OFFSET TO HH CORRECTION VECTOR")); cal->byte_offset_hv_corr = atof(get_airsar(buf, "BYTE OFFSET TO HV CORRECTION VECTOR")); cal->byte_offset_vv_corr = atof(get_airsar(buf, "BYTE OFFSET TO VV CORRECTION VECTOR")); cal->num_bytes_corr = atof(get_airsar(buf, "NUMBER OF BYTES IN CORRECTION VECTORS")); return cal; } static airsar_general *read_airsar_general(const char *inBaseName) { // Read general metadata file airsar_general *general=NULL; char line[256]="", *value, *p, *q; general = (airsar_general *) CALLOC(1, sizeof(airsar_general)); char *metaFile = MALLOC(sizeof(char)*(strlen(inBaseName)+20)); if (!fileExists(inBaseName)) sprintf(metaFile, "%s_meta.airsar", inBaseName); else { strcpy(metaFile, inBaseName); q = strstr(inBaseName, "_meta.airsar"); if (q) *q = '\0'; } FILE *fpIn = FOPEN(metaFile, "r"); while (NULL != fgets(line, 255, fpIn)) { p = strchr(line, '='); if (p) { value = p+1; if (strncmp(line, "SCENE ID", 8) == 0) sprintf(general->scene_id, "%s", value); else if (strncmp(line, "Name of Flight-line", 19) == 0) sprintf(general->flight_line, "%s", value); else if (strncmp(line, "Date of Acquistion", 18) == 0) sprintf(general->date_acquisition, "%s", value); else if (strncmp(line, "Date of Processing", 18) == 0) sprintf(general->date_processing, "%s", value); else if (strncmp(line, "Radar Projection (for highest freq product)", 43) == 0) sprintf(general->radar_projection, "%s", value); else if (strncmp(line, "Width in Km(for highest freq product)", 37) == 0) general->width = atof(value); else if (strncmp(line, "Length in Km(for highest freq product)", 38) == 0) general->length = atof(value); else if (strncmp(line, "Range pixel spacing", 19) == 0) general->range_pixel_spacing = atof(value); else if (strncmp(line, "Azimuth pixel spacing", 21) == 0) general->azimuth_pixel_spacing = atof(value); else if (strncmp(line, "Corner 1 latitude in degrees", 28) == 0) general->corner1_lat = atof(value); else if (strncmp(line, "Corner 1 longitude in degrees", 29) == 0) general->corner1_lon = atof(value); else if (strncmp(line, "Corner 2 latitude in degrees", 28) == 0) general->corner2_lat = atof(value); else if (strncmp(line, "Corner 2 longitude in degrees", 29) == 0) general->corner2_lon = atof(value); else if (strncmp(line, "Corner 3 latitude in degrees", 28) == 0) general->corner3_lat = atof(value); else if (strncmp(line, "Corner 3 longitude in degrees", 29) == 0) general->corner3_lon = atof(value); else if (strncmp(line, "Corner 4 latitude in degrees", 28) == 0) general->corner4_lat = atof(value); else if (strncmp(line, "Corner 4 longitude in degrees", 29) == 0) general->corner4_lon = atof(value); else if (strncmp(line, "C-band Radar Bandwidth in MHZ", 29) == 0) general->c_bandwidth = atof(value); else if (strncmp(line, "L-band Radar Bandwidth in MHZ", 29) == 0) general->l_bandwidth = atof(value); else if (strncmp(line, "P-band Radar Bandwidth in MHZ", 29) == 0) general->p_bandwidth = atof(value); else if (strncmp(line, "AIRSAR Mode", 11) == 0) sprintf(general->mode, "%s", value); else if (strncmp(line, "C-band Polarimetric data", 24) == 0) { if (strncmp(value, "Yes", 3) == 0) general->c_pol_data = TRUE; else if (strncmp(value, "None", 4) == 0) general->c_pol_data = FALSE; } else if (strncmp(line, "L-band Polarimetric data", 24) == 0) { if (strncmp(value, "Yes", 3) == 0) general->l_pol_data = TRUE; else if (strncmp(value, "None", 4) == 0) general->l_pol_data = FALSE; } else if (strncmp(line, "P-band Polarimetric data", 24) == 0) { if (strncmp(value, "Yes", 3) == 0) general->p_pol_data = TRUE; else if (strncmp(value, "None", 4) == 0) general->p_pol_data = FALSE; } else if (strncmp(line, "C-band Cross Track Interferometric data", 39) == 0) { if (strncmp(value, "Yes", 3) == 0) general->c_cross_data = TRUE; else if (strncmp(value, "None", 4) == 0) general->c_cross_data = FALSE; } else if (strncmp(line, "L-band Cross Track Interferometric data", 39) == 0) { if (strncmp(value, "Yes", 3) == 0) general->l_cross_data = TRUE; else if (strncmp(value, "None", 4) == 0) general->l_cross_data = FALSE; } else if (strncmp(line, "C-band Along Track Interferometric data", 39) == 0) { if (strncmp(value, "Yes", 3) == 0) general->c_along_data = TRUE; else if (strncmp(value, "None", 4) == 0) general->c_along_data = FALSE; } else if (strncmp(line, "L-band Along Track Interferometric data", 39) == 0) { if (strncmp(value, "Yes", 3) == 0) general->l_along_data = TRUE; else if (strncmp(value, "None", 4) == 0) general->l_along_data = FALSE; } else if (strncmp(line, "Interferometry Baseline Length", 30) == 0) sprintf(general->baseline, "%s", value); else if (strncmp(line, "Single Frequency/Channel band 1", 31) == 0) sprintf(general->frequency_band1, "%s", value); else if (strncmp(line, "Single Frequency/Channel band 2", 31) == 0) sprintf(general->frequency_band2, "%s", value); else if (strncmp(line, "Single Frequency/Channel band 3", 31) == 0) sprintf(general->frequency_band3, "%s", value); else if (strncmp(line, "Data Format for band 1", 22) == 0) sprintf(general->format_band1, "%s", value); else if (strncmp(line, "Data Format for band 2", 22) == 0) sprintf(general->format_band2, "%s", value); else if (strncmp(line, "Data Format for band 3", 22) == 0) sprintf(general->format_band3, "%s", value); } } FCLOSE(fpIn); free(metaFile); return general; } meta_parameters *import_airsar_meta(const char *dataName, const char *inBaseName, int force) { airsar_general *general = NULL; airsar_header *header = read_airsar_header(dataName); airsar_param_header *params = read_airsar_params(dataName); airsar_dem_header *dem = NULL; airsar_cal_header *cal = NULL; if (!force || inBaseName) general = read_airsar_general(inBaseName); if (!force && (general->c_cross_data || general->l_cross_data)) { // Figure out the whether we have a DEM header char *demFile; demFile = (char *) MALLOC(sizeof(char)*1024); int found_c_dem = FALSE, found_l_dem = FALSE, found_p_dem = FALSE; // The C-Band DEM is the preferred file for extracting the metadata. // Look for that first. If no DEM is around then error out. sprintf(demFile, "%s_c.demi2", inBaseName); if (fileExists(demFile)) found_c_dem = TRUE; sprintf(demFile, "%s_l.demi2", inBaseName); if (fileExists(demFile)) found_l_dem = TRUE; sprintf(demFile, "%s_p.demi2", inBaseName); if (fileExists(demFile)) found_p_dem = TRUE; if (!found_c_dem && !found_l_dem && !found_p_dem) return NULL; // Assign the correct DEM for generating the AirSAR metadata if (found_c_dem) sprintf(demFile, "%s_c.demi2", inBaseName); else if (found_l_dem) sprintf(demFile, "%s_l.demi2", inBaseName); else if (found_p_dem) sprintf(demFile, "%s_p.demi2", inBaseName); dem = read_airsar_dem(demFile); } if (!dem && header->dem_header_offset > 0) dem = read_airsar_dem(dataName); if (header->calibration_header_offset > 0) cal = read_airsar_cal(dataName); meta_parameters *ret = airsar2meta(header, params, dem); // For old AirSAR data, we need to extract the corner coordinates out of the // general header file. If that is not available than we can't do any // geocoding later. if (strcmp_case(ret->general->sensor, "AIRSAR") == 0 && strstr(ret->general->processor, "3.56")) { if (inBaseName) { FREE(ret->airsar); ret->airsar = NULL; ret->location->lat_start_near_range = general->corner1_lat; ret->location->lon_start_near_range = general->corner1_lon; ret->location->lat_start_far_range = general->corner2_lat; ret->location->lon_start_far_range = general->corner2_lon; ret->location->lat_end_near_range = general->corner4_lat; ret->location->lon_end_near_range = general->corner4_lon; ret->location->lat_end_far_range = general->corner3_lat; ret->location->lon_end_far_range = general->corner3_lon; double lat, lon; double yLine, xSamp; meta_get_lineSamp(ret, 37.7697, -122.5218, 0.0, &yLine, &xSamp); printf("center: line: %.3lf, sample: %.3lf\n", yLine, xSamp); meta_get_latLon(ret, 0, 0, 0.0, &lat, &lon); printf("start near - lat: %.4lf, lon: %.4lf\n", lat, lon); meta_get_lineSamp(ret, ret->location->lat_start_near_range, ret->location->lon_start_near_range, 0.0, &yLine, &xSamp); printf("start near - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\n" ,yLine, xSamp, ret->location->lat_start_near_range, ret->location->lon_start_near_range); meta_get_latLon(ret, 0, ret->general->sample_count, 0.0, &lat, &lon); printf("start far - lat: %.4lf, lon: %.4lf\n", lat, lon); meta_get_lineSamp(ret, ret->location->lat_start_far_range, ret->location->lon_start_far_range, 0.0, &yLine, &xSamp); printf("start far - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\n", yLine, xSamp, ret->location->lat_start_far_range, ret->location->lon_start_far_range); meta_get_latLon(ret, ret->general->line_count, 0, 0.0, &lat, &lon); printf("end near - lat: %.4lf, lon: %.4lf\n", lat, lon); meta_get_lineSamp(ret, ret->location->lat_end_near_range, ret->location->lon_end_near_range, 0.0, &yLine, &xSamp); printf("end near - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\n", yLine, xSamp, ret->location->lat_end_near_range, ret->location->lon_end_near_range); meta_get_latLon(ret, ret->general->line_count, ret->general->sample_count, 0.0, &lat, &lon); printf("end far - lat: %.4lf, lon: %.4lf\n", lat, lon); meta_get_lineSamp(ret, ret->location->lat_end_far_range, ret->location->lon_end_far_range, 0.0, &yLine, &xSamp); printf("end far - line: %.3lf, sample: %.3lf, lat: %.4lf, lon: %.4lf\n", yLine, xSamp, ret->location->lat_end_far_range, ret->location->lon_end_far_range); } else asfPrintWarning("No main header file available to extract location " "information. Can't geocode this data later\n"); } if (general) FREE(general); FREE(header); FREE(params); if (dem) FREE(dem); return ret; } //static void fudge_airsar_params(meta_parameters *meta); int ingest_insar_data(const char *inBaseName, const char *outBaseName, char band) { airsar_header *header; meta_parameters *metaIn, *metaOut; FILE *fpIn, *fpOut; char *inFile=NULL, *outFile=NULL; int ii, kk, line_offset, ret=FALSE; float *floatBuf=NULL; // Generate metadata file inFile = (char *) MALLOC(sizeof(char)*255); outFile = (char *) MALLOC(sizeof(char)*255); // Ingest the DEM sprintf(inFile, "%s_%c.demi2", inBaseName, band); if (!fileExists(inFile)) asfPrintStatus(" Could not find DEM file (%s) ...\n", inFile); else { asfPrintStatus(" Ingesting DEM ...\n"); sprintf(outFile, "%s_%c_dem.img", outBaseName, band); header = read_airsar_header(inFile); metaIn = import_airsar_meta(inFile, inBaseName, FALSE); line_offset = header->first_data_offset/metaIn->general->sample_count/2; metaIn->general->line_count += line_offset; metaOut = import_airsar_meta(inFile, inBaseName, FALSE); metaIn->general->data_type = INTEGER16; metaOut->general->data_type = REAL32; floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count); fpIn = FOPEN(inFile, "rb"); fpOut = FOPEN(outFile, "wb"); for (ii=0; ii<metaOut->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii+line_offset, floatBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) floatBuf[kk] = floatBuf[kk]*metaIn->airsar->elevation_increment + metaIn->airsar->elevation_offset; put_float_line(fpOut, metaOut, ii, floatBuf); asfLineMeter(ii, metaOut->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); metaOut->general->image_data_type = DEM; strcpy(metaOut->general->bands, "DEM"); //fudge_airsar_params(metaOut); meta_write(metaOut, outFile); FREE(header); ret = TRUE; } // Ingest amplitude image sprintf(inFile, "%s_%c.vvi2", inBaseName, band); if (!fileExists(inFile)) asfPrintStatus(" Could not find amplitude file (%s) ...\n", inFile); else { asfPrintStatus(" Ingesting amplitude image ...\n"); sprintf(outFile, "%s_%c_vv.img", outBaseName, band); header = read_airsar_header(inFile); line_offset = header->first_data_offset/metaIn->general->sample_count/2; metaIn->general->line_count = metaOut->general->line_count + line_offset; metaIn->general->data_type = INTEGER16; metaOut->general->data_type = REAL32; floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count); fpIn = FOPEN(inFile, "rb"); fpOut = FOPEN(outFile, "wb"); for (ii=0; ii<metaOut->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii+line_offset, floatBuf); put_float_line(fpOut, metaOut, ii, floatBuf); asfLineMeter(ii, metaOut->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); metaOut->general->image_data_type = AMPLITUDE_IMAGE; strcpy(metaOut->general->bands, "AMP"); //fudge_airsar_params(metaOut); meta_write(metaOut, outFile); FREE(header); ret = TRUE; } // Ingest coherence image sprintf(inFile, "%s_%c.corgr", inBaseName, band); if (!fileExists(inFile)) asfPrintStatus(" Could not find coherence image (%s) ...\n", inFile); else { asfPrintStatus(" Ingesting coherence image ...\n"); sprintf(outFile, "%s_%c_coh.img", outBaseName, band); header = read_airsar_header(inFile); line_offset = header->first_data_offset / metaIn->general->sample_count; metaIn->general->line_count = metaOut->general->line_count + line_offset; metaIn->general->data_type = BYTE; metaOut->general->data_type = REAL32; floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count); fpIn = FOPEN(inFile, "rb"); fpOut = FOPEN(outFile, "wb"); for (ii=0; ii<metaOut->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii+line_offset, floatBuf); put_float_line(fpOut, metaOut, ii, floatBuf); asfLineMeter(ii, metaOut->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); metaOut->general->image_data_type = COHERENCE_IMAGE; strcpy(metaOut->general->bands, "COH"); //fudge_airsar_params(metaOut); meta_write(metaOut, outFile); FREE(header); ret = TRUE; } // Clean up if (floatBuf) FREE(floatBuf); if (inFile) FREE(inFile); if (outFile) FREE(outFile); return ret; } static int sign(char byteBuf) { if (byteBuf < 0) return -1; else return 1; } int ingest_polsar_data(const char *inBaseName, const char *outBaseName, radiometry_t radiometry, char band) { FILE *fpIn, *fpOut; char *inFile, *outFile; int ii, kk, ret; char *byteBuf; float *power, *shh_amp, *shh_phase, *shv_amp, *shv_phase, *svh_amp; float *svh_phase, *svv_amp, *svv_phase; float total_power, ysca, amp, phase; float m11, m12, m13, m14, m22, m23, m24, m33, m34, m44; complexFloat cpx; // Allocate memory inFile = (char *) MALLOC(sizeof(char)*255); outFile = (char *) MALLOC(sizeof(char)*255); // Ingest polarimetric data sprintf(inFile, "%s_%c.datgr", inBaseName, band); if (!fileExists(inFile)) sprintf(inFile, "%s_%c.dat", inBaseName, band); if (!fileExists(inFile)) { asfPrintStatus(" Cound not find polarimetric data set (%s_%c) ...\n", inBaseName, band); return FALSE; } else { meta_parameters *meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = POLARIMETRIC_IMAGE; meta->general->band_count = 9; if (radiometry == r_AMP) strcpy(meta->general->bands, "AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH,"\ "AMP_VV,PHASE_VV"); else if (radiometry == r_SIGMA) strcpy(meta->general->bands, "AMP,SIGMA-AMP-HH,SIGMA-PHASE-HH,SIGMA-AMP-HV,SIGMA-PHASE-HV,"\ "SIGMA-AMP-VH,SIGMA-PHASE-VH,SIGMA-AMP-VV,SIGMA-PHASE-VV"); else if (radiometry == r_SIGMA_DB) strcpy(meta->general->bands, "AMP,SIGMA_DB-AMP-HH,SIGMA_DB-PHASE-HH,SIGMA_DB-AMP-HV,"\ "SIGMA_DB-PHASE-HV,SIGMA_DB-AMP-VH,SIGMA_DB-PHASE-VH,"\ "SIGMA_DB-AMP-VV,SIGMA_DB-PHASE-VV"); power = (float *) MALLOC(sizeof(float)*meta->general->sample_count); shh_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count); shh_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count); shv_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count); shv_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count); svh_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count); svh_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count); svv_amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count); svv_phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count); byteBuf = (char *) MALLOC(sizeof(char)*10); airsar_header *header = read_airsar_header(inFile); // airsar_param_header *params = read_airsar_params(inFile); long offset = header->first_data_offset; sprintf(outFile, "%s_%c.img", outBaseName, band); fpIn = FOPEN(inFile, "rb"); fpOut = FOPEN(outFile, "wb"); FSEEK(fpIn, offset, SEEK_SET); for (ii=0; ii<meta->general->line_count; ii++) { for (kk=0; kk<meta->general->sample_count; kk++) { FREAD(byteBuf, sizeof(char), 10, fpIn); // Scale is always 1.0 according to Bruce Chapman m11 = ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]); m12 = (float)byteBuf[2] * m11 / 127.0; m13 = sign(byteBuf[3]) * SQR((float)byteBuf[3] / 127.0) * m11; m14 = sign(byteBuf[4]) * SQR((float)byteBuf[4] / 127.0) * m11; m23 = sign(byteBuf[5]) * SQR((float)byteBuf[5] / 127.0) * m11; m24 = sign(byteBuf[6]) * SQR((float)byteBuf[6] / 127.0) * m11; m33 = (float)byteBuf[7] * m11 / 127.0; m34 = (float)byteBuf[8] * m11 / 127.0; m44 = (float)byteBuf[9] * m11 / 127.0; m22 = 1 - m33 -m44; total_power = ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]); ysca = 2.0 * sqrt(total_power); power[kk] = sqrt(total_power); cpx.real = (float)byteBuf[2] * ysca / 127.0; cpx.imag = (float)byteBuf[3] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { shh_amp[kk] = amp; shh_phase[kk] = phase; } else if (radiometry == r_SIGMA) { shh_amp[kk] = amp*amp; shh_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { shh_amp[kk] = amp; shh_phase[kk] = phase; } cpx.real = (float)byteBuf[4] * ysca / 127.0; cpx.imag = (float)byteBuf[5] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { shv_amp[kk] = amp; shv_phase[kk] = phase; } else if (radiometry == r_SIGMA) { shv_amp[kk] = amp*amp; shv_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { shv_amp[kk] = amp; shv_phase[kk] = phase; } cpx.real = (float)byteBuf[6] * ysca / 127.0; cpx.imag = (float)byteBuf[7] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { svh_amp[kk] = amp; svh_phase[kk] = phase; } else if (radiometry == r_SIGMA) { svh_amp[kk] = amp*amp; svh_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { svh_amp[kk] = amp; svh_phase[kk] = phase; } cpx.real = (float)byteBuf[8] * ysca / 127.0; cpx.imag = (float)byteBuf[9] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { svv_amp[kk] = amp; svv_phase[kk] = phase; } else if (radiometry == r_SIGMA) { svv_amp[kk] = amp*amp; svv_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { svv_amp[kk] = amp; svv_phase[kk] = phase; } } put_band_float_line(fpOut, meta, 0, ii, power); put_band_float_line(fpOut, meta, 1, ii, shh_amp); put_band_float_line(fpOut, meta, 2, ii, shh_phase); put_band_float_line(fpOut, meta, 3, ii, shv_amp); put_band_float_line(fpOut, meta, 4, ii, shv_phase); put_band_float_line(fpOut, meta, 5, ii, svh_amp); put_band_float_line(fpOut, meta, 6, ii, svh_phase); put_band_float_line(fpOut, meta, 7, ii, svv_amp); put_band_float_line(fpOut, meta, 8, ii, svv_phase); asfLineMeter(ii, meta->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(meta, outFile); // Clean up FREE(power); FREE(shh_amp); FREE(shh_phase); FREE(shv_amp); FREE(shv_phase); FREE(svh_amp); FREE(svh_phase); FREE(svv_amp); FREE(svv_phase); FREE(inFile); FREE(outFile); FREE(byteBuf); ret = TRUE; } return ret; } void import_airsar(const char *inBaseName, radiometry_t radiometry, const char *outBaseName) { char inFile[1024]; int found_c_dem = FALSE, found_l_dem = FALSE; // Check radiometry if (radiometry != r_AMP && radiometry != r_SIGMA && radiometry != r_SIGMA_DB) { asfPrintWarning("Radiometry other than AMPLITUDE and SIGMA is not " "supported for AirSAR data.\nDefaulting back to " "AMPLITUDE.\n"); radiometry = r_AMP; } airsar_general *general = read_airsar_general(inBaseName); // Check for existence of DEMs. // The C-Band DEM is the preferred file for extracting the metadata. // Look for that first. If no DEM is around then error out. if (general->c_cross_data || general->l_cross_data) { sprintf(inFile, "%s_c.demi2", inBaseName); if (fileExists(inFile)) found_c_dem = TRUE; sprintf(inFile, "%s_l.demi2", inBaseName); if (fileExists(inFile)) found_l_dem = TRUE; if (!found_c_dem && found_l_dem) asfPrintWarning("Could not find C-band DEM.\nRequired for most reliable " "metadata extraction\n"); if (!found_c_dem && !found_l_dem) asfPrintError("Could not find any DEM.\nCan't reliably import this " "Airsar data.\n"); } // Check for interferometric data if (general->c_cross_data) { asfPrintStatus("\n Ingesting C-band cross track interferometric data ..." "\n\n"); ingest_insar_data(inBaseName, outBaseName, 'c'); } if (general->l_cross_data) { asfPrintStatus("\n Ingesting L-band cross track interferometric data ..." "\n\n"); ingest_insar_data(inBaseName, outBaseName, 'l'); } // Kept out the along-track interferometric data for the moment. // Only a few data sets were acquired that way and we have no real way // to verify the results. // Check for polarimetric data if (general->c_pol_data) { asfPrintStatus("\n Ingesting C-band polarimetric data ...\n\n"); ingest_polsar_data(inBaseName, outBaseName, radiometry, 'c'); } if (general->l_pol_data) { asfPrintStatus("\n Ingesting L-band polarimetric data ...\n\n"); ingest_polsar_data(inBaseName, outBaseName, radiometry, 'l'); } if (general->p_pol_data) { asfPrintStatus("\n Ingesting P-band polarimetric data ...\n\n"); ingest_polsar_data(inBaseName, outBaseName, radiometry, 'p'); } FREE(general); } // The purpose of this code is to refine the values of the along // and cross track offsets, so that the meta_get_latLon() value // returned at the corners of the image matches what the correct // corner lat/lon values are, from the metadata. Why do we believe // the corners locations more than the given along/cross track // offsets? From the data sets we've been looking at, it seems like // the corner coords are good, but the offsets aren't... // We just do a 2-d minimization of the total error (in line/sample // space -- not lat/lon (minimizing in lat/lon coords would favor // minimizing the lon difference near the poles)) between the // corner coordinates. struct fudge_airsar_params { meta_parameters *meta; }; static int getObjective(const gsl_vector *x, void *params, gsl_vector *f) { double c0 = gsl_vector_get(x,0); double s0 = gsl_vector_get(x,1); if (!meta_is_valid_double(c0) || !meta_is_valid_double(s0)) { // This does happen sometimes, when we've already found the root return GSL_FAILURE; } struct fudge_airsar_params *p = (struct fudge_airsar_params *)params; meta_parameters *meta = p->meta; int nl = meta->general->line_count; int ns = meta->general->sample_count; double old_c0 = meta->airsar->cross_track_offset; double old_s0 = meta->airsar->along_track_offset; meta->airsar->cross_track_offset = c0; meta->airsar->along_track_offset = s0; double line, samp, err = 0.; meta_get_lineSamp(meta, meta->location->lat_start_near_range, meta->location->lon_start_near_range, 0., &line, &samp); err += hypot(line,samp); meta_get_lineSamp(meta, meta->location->lat_start_far_range, meta->location->lon_start_far_range, 0., &line, &samp); err += hypot(line,samp-(double)ns); meta_get_lineSamp(meta, meta->location->lat_end_near_range, meta->location->lon_end_near_range, 0., &line, &samp); err += hypot(line-(double)nl,samp); meta_get_lineSamp(meta, meta->location->lat_end_far_range, meta->location->lon_end_far_range, 0., &line, &samp); err += hypot(line-(double)nl,samp-(double)ns); //printf("getObjective> [%f,%f] -> %f\n", c0, s0, err); gsl_vector_set(f,0,err); gsl_vector_set(f,1,err); meta->airsar->cross_track_offset = old_c0; meta->airsar->along_track_offset = old_s0; return GSL_SUCCESS; } /* static void coarse_search(double c0_extent_min, double c0_extent_max, double s0_extent_min, double s0_extent_max, double *c0_min, double *s0_min, meta_parameters *meta) { struct fudge_airsar_params params; params.meta = meta; double the_min = 9999999; double min_c0=99, min_s0=99; int i,j,k=6; double c0_extent = c0_extent_max - c0_extent_min; double s0_extent = s0_extent_max - s0_extent_min; gsl_vector *v = gsl_vector_alloc(2); gsl_vector *u = gsl_vector_alloc(2); //printf(" "); //for (j = 0; j <= k; ++j) { // double s0 = s0_extent_min + ((double)j)/k*s0_extent; // printf("%9.3f ", s0); //} //printf("\n "); //for (j = 0; j <= k; ++j) // printf("--------- "); //printf("\n"); for (i = 0; i <= k; ++i) { double c0 = c0_extent_min + ((double)i)/k*c0_extent; //printf("%9.3f | ", c0); for (j = 0; j <= k; ++j) { double s0 = s0_extent_min + ((double)j)/k*s0_extent; gsl_vector_set(v, 0, c0); gsl_vector_set(v, 1, s0); getObjective(v,(void*)(&params), u); double n = gsl_vector_get(u,0); //printf("%9.3f ", n); if (n<the_min) { the_min=n; min_c0=gsl_vector_get(v,0); min_s0=gsl_vector_get(v,1); } } //printf("\n"); } *c0_min = min_c0; *s0_min = min_s0; gsl_vector_free(v); gsl_vector_free(u); } */ /* static void generate_start(meta_parameters *meta, double c0, double s0, double *start_c0, double *start_s0) { int i; double extent_c0_min = -100000. + c0; double extent_c0_max = 100000. + c0; double extent_s0_min = -100000. + s0; double extent_s0_max = 100000. + s0; double c0_range = extent_c0_max - extent_c0_min; double s0_range = extent_s0_max - extent_s0_min; for (i=0; i<12; ++i) //for (i=0; i<4; ++i) { coarse_search(extent_c0_min, extent_c0_max, extent_s0_min, extent_s0_max, start_c0, start_s0, meta); c0_range /= 3.; s0_range /= 3.; extent_c0_min = *start_c0 - c0_range/2.; extent_c0_max = *start_c0 + c0_range/2.; extent_s0_min = *start_s0 - s0_range/2.; extent_s0_max = *start_s0 + s0_range/2.; //printf("refining search to region: cross: (%9.3f,%9.3f)\n" // " along: (%9.3f,%9.3f)\n", // extent_c0_min, extent_c0_max, // extent_s0_min, extent_s0_max); } } */ /* static void show_error(meta_parameters *meta, const char *descrip) { int nl = meta->general->line_count; int ns = meta->general->sample_count; double line, samp, err=0; asfPrintStatus("Computing known corner coordinates vs. calculated " "metadata differences:\n"); meta_get_lineSamp(meta, meta->location->lat_start_near_range, meta->location->lon_start_near_range, 0., &line, &samp); asfPrintStatus(" Start Near: %f (%d) %f (%d)\n", line, 0, samp, 0); err += hypot(line, samp); meta_get_lineSamp(meta, meta->location->lat_start_far_range, meta->location->lon_start_far_range, 0., &line, &samp); asfPrintStatus(" Start Far: %f (%d) %f (%d)\n", line, 0, samp, ns); err += hypot(line, samp-(double)ns); meta_get_lineSamp(meta, meta->location->lat_end_near_range, meta->location->lon_end_near_range, 0., &line, &samp); asfPrintStatus(" End Near: %f (%d) %f (%d)\n", line, nl, samp, 0); err += hypot(line-(double)nl, samp); meta_get_lineSamp(meta, meta->location->lat_end_far_range, meta->location->lon_end_far_range, 0., &line, &samp); asfPrintStatus(" End Far: %f (%d) %f (%d)\n", line, nl, samp, ns); err += hypot(line-(double)nl, samp-(double)ns); asfPrintStatus("%s, average corner error: %.2f pixels\n", descrip, err/4.); } */ /* static void fudge_airsar_params(meta_parameters *meta) { int status, iter = 0, max_iter = 1000; const gsl_multiroot_fsolver_type *T; gsl_multiroot_fsolver *s; gsl_error_handler_t *prev; struct fudge_airsar_params params; const size_t n = 2; double c0_initial, s0_initial; double out_c0, out_s0; params.meta = meta; asfPrintStatus("Refining airsar cross-track and along-track offsets to " "match corner locations.\n"); show_error(meta, "Prior to airsar geolocation refinement"); asfPrintStatus("Prior to coarse refinement (original metadata values):\n"); asfPrintStatus(" cross track offset: %.1fm\n", meta->airsar->cross_track_offset); asfPrintStatus(" along track offset: %.1fm\n", meta->airsar->along_track_offset); generate_start(meta, meta->airsar->cross_track_offset, meta->airsar->along_track_offset, &c0_initial, &s0_initial); asfPrintStatus("Starting iterative search with:\n"); asfPrintStatus(" cross track offset: %.1fm\n", c0_initial); asfPrintStatus(" along track offset: %.1fm\n", s0_initial); gsl_multiroot_function F = {&getObjective, n, &params}; gsl_vector *x = gsl_vector_alloc(n); gsl_vector_set (x, 0, c0_initial); gsl_vector_set (x, 1, s0_initial); T = gsl_multiroot_fsolver_hybrid; s = gsl_multiroot_fsolver_alloc(T, n); gsl_multiroot_fsolver_set(s, &F, x); prev = gsl_set_error_handler_off(); do { ++iter; status = gsl_multiroot_fsolver_iterate(s); // abort if stuck if (status) break; status = gsl_multiroot_test_residual (s->f, 1e-8); } while (status == GSL_CONTINUE && iter < max_iter); // we allow GSL_ENOPROG (not making progress), since often the coarse // search ends up at or very close to the minimum if (status == GSL_SUCCESS || status == GSL_ENOPROG) { asfPrintStatus("Converged after %d iteration%s.\n", iter, iter==1 ? "" : "s"); out_c0 = gsl_vector_get(s->x, 0); out_s0 = gsl_vector_get(s->x, 1); asfPrintStatus("Final values:\n"); asfPrintStatus(" cross track offset: %.1fm [adjusted by %.1fm]\n", out_c0, fabs(out_c0-meta->airsar->cross_track_offset)); asfPrintStatus(" along track offset: %.1fm [adjusted by %.1fm]\n", out_s0, fabs(out_s0-meta->airsar->along_track_offset)); meta->airsar->cross_track_offset = out_c0; meta->airsar->along_track_offset = out_s0; show_error(meta, "After airsar geolocation refinement"); } else { asfPrintStatus("After %d iterations, failed to converge:\n %s\n" "Metadata parameters left unchanged.\n", iter, gsl_strerror(status)); out_c0 = out_s0 = 0; } gsl_multiroot_fsolver_free(s); gsl_vector_free(x); gsl_set_error_handler(prev); } */ void read_meta_airsar(char *inBaseName, char *outBaseName) { airsar_general *general = read_airsar_general(inBaseName); char *inFile = (char *) MALLOC(sizeof(char)*255); char *outFile = (char *) MALLOC(sizeof(char)*255); airsar_header *header; meta_parameters *meta; int line_offset; if (general->c_cross_data) { sprintf(inFile, "%s_c.demi2", inBaseName); if (fileExists(inFile)) { asfPrintStatus("C-band DEM ...\n"); sprintf(outFile, "%s_c_dem.xml", outBaseName); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = DEM; strcpy(meta->general->bands, "DEM"); meta_write_xml(meta, outFile); meta_free(meta); } sprintf(inFile, "%s_c.vvi2", inBaseName); if (fileExists(inFile)) { asfPrintStatus("C-band amplitude image ...\n"); sprintf(outFile, "%s_c_vv.xml", outBaseName); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = AMPLITUDE_IMAGE; strcpy(meta->general->bands, "AMP"); meta_write_xml(meta, outFile); meta_free(meta); } sprintf(inFile, "%s_c.corgr", inBaseName); if (fileExists(inFile)) { asfPrintStatus("C-band coherence image ...\n"); sprintf(outFile, "%s_c_coh.xml", outBaseName); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = COHERENCE_IMAGE; strcpy(meta->general->bands, "COH"); meta_write_xml(meta, outFile); meta_free(meta); } } if (general->l_cross_data) { sprintf(inFile, "%s_l.demi2", inBaseName); if (fileExists(inFile)) { asfPrintStatus("L-band DEM ...\n"); sprintf(outFile, "%s_l_dem.xml", outBaseName); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = DEM; strcpy(meta->general->bands, "DEM"); meta_write_xml(meta, outFile); meta_free(meta); } sprintf(inFile, "%s_l.vvi2", inBaseName); if (fileExists(inFile)) { asfPrintStatus("L-band amplitude image ...\n"); sprintf(outFile, "%s_l_vv.xml", outBaseName); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = AMPLITUDE_IMAGE; strcpy(meta->general->bands, "AMP"); meta_write_xml(meta, outFile); meta_free(meta); } sprintf(inFile, "%s_l.corgr", inBaseName); if (fileExists(inFile)) { asfPrintStatus("L-band coherence image ...\n"); sprintf(outFile, "%s_l_coh.xml", outBaseName); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = COHERENCE_IMAGE; strcpy(meta->general->bands, "COH"); meta_write_xml(meta, outFile); meta_free(meta); } } if (general->c_pol_data) { sprintf(inFile, "%s_c.datgr", inBaseName); if (!fileExists(inFile)) sprintf(inFile, "%s_c.dat", inBaseName); if (fileExists(inFile)) { asfPrintStatus("C-band polarimetric data set ...\n"); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = POLARIMETRIC_IMAGE; meta->general->band_count = 9; strcpy(meta->general->bands, "AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH," \ "AMP_VV,PHASE_VV"); sprintf(outFile, "%s_c.xml", outBaseName); meta_write_xml(meta, outFile); meta_free(meta); } } if (general->l_pol_data) { sprintf(inFile, "%s_l.datgr", inBaseName); if (!fileExists(inFile)) sprintf(inFile, "%s_l.dat", inBaseName); if (fileExists(inFile)) { asfPrintStatus("L-band polarimetric data set ...\n"); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = POLARIMETRIC_IMAGE; meta->general->band_count = 9; strcpy(meta->general->bands, "AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH," \ "AMP_VV,PHASE_VV"); sprintf(outFile, "%s_l.xml", outBaseName); meta_write_xml(meta, outFile); meta_free(meta); } } if (general->p_pol_data) { sprintf(inFile, "%s_p.datgr", inBaseName); if (!fileExists(inFile)) sprintf(inFile, "%s_p.dat", inBaseName); if (fileExists(inFile)) { asfPrintStatus("P-band polarimetric data set ...\n"); meta = import_airsar_meta(inFile, inBaseName, FALSE); meta->general->data_type = REAL32; meta->general->image_data_type = POLARIMETRIC_IMAGE; meta->general->band_count = 9; strcpy(meta->general->bands, "AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH," \ "AMP_VV,PHASE_VV"); sprintf(outFile, "%s_p.xml", outBaseName); meta_write_xml(meta, outFile); meta_free(meta); } } FREE(general); }
{ "alphanum_fraction": 0.6456763109, "avg_line_length": 36.5059171598, "ext": "c", "hexsha": "b6bdadc179b72e7f484c521e4405a1f74ca1e67f", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_import/import_airsar.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_import/import_airsar.c", "max_line_length": 83, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_import/import_airsar.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 14858, "size": 49356 }
#include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void setupInitialSeed( int id, gsl_rng *rgen ); void createInitialSample( double *x, long N, gsl_rng *rgen, int state_dim );
{ "alphanum_fraction": 0.6380952381, "avg_line_length": 15, "ext": "h", "hexsha": "0c3e81d76437b3e60d18aa72f66ba94a33b5f59e", "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": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_path": "include/randomisation.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "heinekmp/AIRPF", "max_issues_repo_path": "include/randomisation.h", "max_line_length": 28, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_path": "include/randomisation.h", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "num_tokens": 68, "size": 210 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> #define PI 3.1416 #define USAGE "./mcmc_solar.x n_steps n_burn" void likelihood(float *chi, float *y_obs, float *y_model, int n_puntos); void my_model(float *mine, float *anio ,float a, float b, float c, float d, int n_puntos); void mcmc(int n_steps, float *a, float *b, float *c, float *d, float *l, float *x_obs, float *y_obs,int n_puntos, float *mine); void min(float *mine, float *x_obs, float *a, float *b, float *c, float *d, float *l, int n_steps, int n_puntos); void leer(float *anio, float *manc, int n_puntos); float *reserva(int n_puntos); void print_array(float *a, float *b, float *c, float *d , float *l, int n_steps, int n_burn); int main(int argc, char **argv){ srand48(time(NULL)); //Valores que entran int n_steps=atof(argv[1]); int n_burn=atof(argv[2]); //Inicializacion de los arrays que guardan los datos int n_puntos= 4141; float *manc; float *anio; anio=reserva(n_puntos); manc=reserva(n_puntos); leer(anio, manc, n_puntos); //Array con los resultados del ajuste float *mine; mine=reserva(n_puntos); //Arrays que guardan los datos de las variables float *a; float *b; float *c; float *d; float *l; a=reserva(n_steps); b=reserva(n_steps); c=reserva(n_steps); d=reserva(n_steps); l=reserva(n_steps); //Primer paso en la cadena a[0]=drand48(); b[0]=drand48(); c[0]=drand48(); d[0]=drand48(); float chi; my_model(mine,anio,a[0],b[0],c[0],d[0],n_puntos); likelihood(&chi,manc,mine,n_puntos); l[0]=chi; //Iteraciones mcmc(n_steps,a,b,c,d,l,anio,manc,n_puntos,mine); min(mine,anio,a,b,c,d,l,n_steps,n_puntos); print_array(a,b,c,d,l,n_steps,n_burn); free(mine); free(anio); free(manc); free(a); free(b); free(c); free(d); return 0; } //OBTENCION DEL MEJOR AJUSTE void min(float *mine, float *x_obs, float *a, float *b, float *c, float *d, float *l, int n_steps, int n_puntos){ int i; float temp, a2, b2, c2, d2; temp=l[0]; a2=a[0]; b2=b[0]; c2=c[0]; d2=d[0]; for(i=1;i<n_steps;i++){ if(temp > l[i] ){ temp=l[i]; a2=a[i]; b2=b[i]; c2=c[i]; d2=d[i]; } } my_model(mine,x_obs,a2,b2,c2,d2,n_puntos); } //ITERACIONES void mcmc(int n_steps, float *a, float *b, float *c, float *d, float *l, float *x_obs, float *y_obs,int n_puntos, float *mine){ int i; float a2,b2,c2,d2, chi, chi2, alpha, beta; const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for(i=0;i<(n_steps-1);i++){ a2 = a[i] + gsl_ran_gaussian(r, 0.1); b2 = b[i] + gsl_ran_gaussian(r, 0.1); c2 = c[i] + gsl_ran_gaussian(r, 0.1); d2 = c[i] + gsl_ran_gaussian(r, 0.1); float *y_init; float *y_prime; y_init=reserva(n_puntos); y_prime=reserva(n_puntos); my_model(y_init,x_obs,a[i],b[i],c[i],d[i],n_puntos); my_model(y_prime,x_obs,a2,b2,c2,d2,n_puntos); likelihood(&chi,y_obs,y_init,n_puntos); likelihood(&chi2,y_obs,y_prime,n_puntos); alpha = -chi2 + chi; if(alpha >= 0.0){ a[i+1]=a2; b[i+1]=b2; c[i+1]=c2; d[i+1]=d2; l[i+1]=chi2; } else{ beta = drand48(); if(alpha < -6000.0 ){ a[i+1]=a[i]; b[i+1]=b[i]; c[i+1]=c[i]; d[i+1]=d[i]; l[i+1]=chi; } else if(beta <= exp(alpha)){ a[i+1]=a2; b[i+1]=b2; c[i+1]=c2; d[i+1]=d2; l[i+1]=chi2; } else{ a[i+1]=a[i]; b[i+1]=b[i]; c[i+1]=c[i]; d[i+1]=d[i]; l[i+1]=chi; } } free(y_init); free(y_prime); } gsl_rng_free (r); } //LECTURA DEL ARCHIVO void leer(float *anio, float *manc, int n_puntos){ float *mes; mes=reserva(n_puntos); FILE *in; int i; in=fopen("monthrg.dat","r"); if(!in){ printf("problems opening the file %s\n","monthrg.dat"); exit(1); } float temp1; float temp2; for(i=0;i<n_puntos;i++){ do{ fscanf(in, "%f %f %f %f %f\n", &anio[i], &mes[i], &temp1, &manc[i] , &temp2); }while(manc[i] == -99.0); } fclose(in); //Calculo del anio como decimal for(i=0;i<n_puntos;i++){ anio[i] = anio[i] + (mes[i]-1.0)/12.0; } free(mes); } //IMPRESION DE LOS ARRAYS void print_array(float *a, float *b, float *c, float *d , float *l, int n_steps, int n_burn){ int i; for(i=n_burn;i<n_steps;i++){ printf("%f %f %f %f %f\n", a[i], b[i], c[i] , d[i], l[i]); } } //EVALUAR LOS PUNTOS CON EL AJUSTE void my_model(float *mine, float *anio ,float a, float b, float c, float d, int n_puntos){ int i; for(i=0;i<n_puntos;i++){ mine[i] = a * cos((2*PI/d)*anio[i] + b) + c; } } //RESERVA DE MEMORIA float *reserva(int n_puntos){ float *array; int i; if(!(array = malloc(n_puntos * sizeof(float)))){ printf("Problema en reserva\n"); exit(1); } for(i=0;i<n_puntos;i++){ array[i] = 0.0; } return array; } //CALCULO DE LA VARIACION DEL AJUSTE void likelihood(float *chi, float *y_obs, float *y_model, int n_puntos){ int i; float temp=0; for(i=0;i<n_puntos;i++){ temp=temp+pow(y_obs[i]-y_model[i],2.0); } *chi=(1.0/2.0)*temp; }
{ "alphanum_fraction": 0.611133122, "avg_line_length": 21.4808510638, "ext": "c", "hexsha": "95c52158e089bc47abb78976c48dc7232315c369", "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": "307b86e4e85d4c25edc3346a5ce8a23eafbe4e87", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BarreraMonica/HW7_MC", "max_forks_repo_path": "solar/solar.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "307b86e4e85d4c25edc3346a5ce8a23eafbe4e87", "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": "BarreraMonica/HW7_MC", "max_issues_repo_path": "solar/solar.c", "max_line_length": 127, "max_stars_count": null, "max_stars_repo_head_hexsha": "307b86e4e85d4c25edc3346a5ce8a23eafbe4e87", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "BarreraMonica/HW7_MC", "max_stars_repo_path": "solar/solar.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1906, "size": 5048 }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <gsl/gsl_sf_expint.h> #include "SE_trans.h" #define ALPHA 0.99 #define DOMD 3.14 double f(double t) { return 0.25 * ((1+t) * log1p(t) + (1-t) * log1p(-t) - 2 * M_LN2) / M_LN2; } double G(double x) { return 0.25 * x * SE_trans_div(-1, 1, x) / M_LN2; } double J(int j, double h, double x) { return h * (0.5 + M_1_PI * gsl_sf_Si(M_PI * (x / h - j))); } double Fapp(double t, int m) { double h = sqrt(M_PI*DOMD / (ALPHA*m)); int j; double sum1 = 0; double sum2 = 0; for (j = -m; j < 0; j++) { sum1 += G(j*h) * J(j, h, SE_trans_inv(-1, 1, t)); } for (j = m; j >= 0; j--) { sum2 += G(j*h) * J(j, h, SE_trans_inv(-1, 1, t)); } return (sum1 + sum2); } int main() { int i; int n; double t; double err, maxerr; clock_t start, end; double time; int STEP = 1000; for (n = 3; n <= 150; n += 6) { start = clock(); maxerr = 0; for (i = - STEP + 1; i <= STEP - 1; i++) { t = (double)i / (double)(STEP); err = fabs(f(t) - Fapp(t, n)); maxerr = fmax(err, maxerr); } end = clock(); time = (double)(end - start) / CLOCKS_PER_SEC; printf("%d\t%e\t%e\n", n, err, time); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5223285486, "avg_line_length": 17.4166666667, "ext": "c", "hexsha": "7f730e569d99cd4b20465e9f8ab7d35c80905c5c", "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": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "okayamat/sinc-indef", "max_forks_repo_path": "Ex2SE1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9", "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": "okayamat/sinc-indef", "max_issues_repo_path": "Ex2SE1.c", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "okayamat/sinc-indef", "max_stars_repo_path": "Ex2SE1.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 495, "size": 1254 }
// Diagonalization Routines using LAPACK(E) #include <stdio.h> #include <stdlib.h> #include <emscripten.h> #include <lapacke.h> // void ssyevr_(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, // float *vl, float *vu, int *il, int *iu, float *abstol, int *m, // float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, // int *iwork, int *liwork, int *info); void EMSCRIPTEN_KEEPALIVE diagonalize(float *coords, int natoms, int neig, float *evals, float *evecs); void EMSCRIPTEN_KEEPALIVE diagonalize(float *mtx, int natoms, int neig, float *evals, float *evecs) { // int i; // debug // Parameters lapack_int info; lapack_int n = natoms; lapack_int lda = n; lapack_int ldz = neig; // printf("natoms = %d | neig = %d \n", natoms, neig); lapack_int il = 1; // 1st eigval idx lapack_int iu = neig; // last idx. float abstol = -1.0; // default machine value. float vl = 0.0; float vu = 0.0; lapack_int m; lapack_int isuppz[natoms]; // Solve for eigenvalues/eigenvectors info = LAPACKE_ssyevr( LAPACK_ROW_MAJOR, 'V', 'I', 'U', n, mtx, lda, vl, vu, il, iu, abstol, &m, evals, evecs, ldz, isuppz); if (info > 0) { printf("The algorithm failed to compute eigenvalues.\n"); exit(1); } // printf("\n The total number of eigenvalues found:%2i\n", m); // for (i = 0; i < neig; i++) // { // printf("eval %d = %f\n", i, evals[i]); // } }
{ "alphanum_fraction": 0.5818181818, "avg_line_length": 28, "ext": "c", "hexsha": "7cbdf6ee7f939d771182536d5ad3eb02ba534488", "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": "cb63218e4b611aec61b421d31e6eb1828567b382", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JoaoRodrigues/nmaJS", "max_forks_repo_path": "src/xyzdiag.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cb63218e4b611aec61b421d31e6eb1828567b382", "max_issues_repo_issues_event_max_datetime": "2017-12-18T21:42:32.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-18T19:41:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "JoaoRodrigues/nmaJS", "max_issues_repo_path": "src/xyzdiag.c", "max_line_length": 103, "max_stars_count": 2, "max_stars_repo_head_hexsha": "cb63218e4b611aec61b421d31e6eb1828567b382", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JoaoRodrigues/nmaJS", "max_stars_repo_path": "src/xyzdiag.c", "max_stars_repo_stars_event_max_datetime": "2021-01-08T01:08:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-01T02:35:55.000Z", "num_tokens": 519, "size": 1540 }
static const char help[] = "Build and view a tiny three-triangle mesh using DMPlex, and integrate a\n" "scalar function over it. Option prefixes tny_ and plex_view_.\n\n"; /* either build DMPlex via call to DMPlexCreateFromCellList() ./tiny or by directly setting cones "by hand": ./tiny -tny_by_hand compute an integral by symmetric Gauss quadrature: ./tiny -tny_integrate_f ./tiny -tny_integrate_f -tny_quaddegree 1|[2]|3 compare these views: ./tiny -dm_view ./tiny -section_view ./tiny -v_vec_view and -plex_view_xxx options (see plexview.h) parallel refinement works: mpiexec -n 2 ./tiny -dm_refine 1 -plex_view_ranges -plex_view_coords FIXME interpolation of f(x,y) by P2 FIXME interpolate f(x,y) by P2 and integrate it FIXME add option -tny_element P1|P2|P3 */ #include <petsc.h> #include "../../quadrature.h" #include "plexview.h" // Describe the mesh "triangle style" with separate numbering for cells and vertices. static const int dim = 2, ncell = 3, nvert = 5, cells[9] = {0, 3, 2, // 9 = ncell * (dim+1) 0, 2, 1, 2, 3, 4}; static const double coordverts[10] = {0.0, 0.0, // 10 = nvert * dim 0.0, 1.0, 0.5, 1.0, 1.0, 0.0, 1.0, 1.0}; // Describe same mesh, but directly as DMPlex, i.e. by giving cell and // edge cones in DAG. These values are generated by DMPlexCreateFromCellList() // internally, so they are redundant if we use that create method. static const int npoint = 15, ccone[3][3] = {{8,9,10}, {10,11,12}, {9,13,14}}, econe[7][2] = {{3,6}, {5,6}, {3,5}, {4,5}, {3,4}, {6,7}, {5,7}}; static double f(double x, double y) { return exp(- x - 2 * y); } extern PetscErrorCode CreateMeshByHand(DM*); extern PetscErrorCode CreateCoordinateSectionByHand(DM*); extern PetscErrorCode CreateSectionP2(DM,PetscSection*); extern PetscErrorCode IntegrateF(DM,double(double,double),int,double*); extern PetscErrorCode EvaluateFP2(DM,PetscSection,double(double,double),Vec*); int main(int argc,char **argv) { PetscErrorCode ierr; DM dmplex; PetscSection p2section; Vec v; PetscBool by_hand = PETSC_FALSE, integrate_f = PETSC_FALSE; int quaddegree = 2; PetscInitialize(&argc,&argv,NULL,help); ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "tny_", "options for tiny", "");CHKERRQ(ierr); ierr = PetscOptionsBool("-by_hand", "use by-hand construction", "tiny.c", by_hand, &by_hand, NULL);CHKERRQ(ierr); ierr = PetscOptionsBool("-integrate_f", "integrate f(x,y) by summing over cells and using quadrature", "tiny.c", integrate_f, &integrate_f, NULL);CHKERRQ(ierr); ierr = PetscOptionsInt("-quaddegree", "use this quadrature degree for numerical integrations", "tiny.c", quaddegree, &quaddegree, NULL);CHKERRQ(ierr); ierr = PetscOptionsEnd(); // create the DMPlex mesh if (by_hand) { ierr = CreateMeshByHand(&dmplex); CHKERRQ(ierr); ierr = CreateCoordinateSectionByHand(&dmplex); CHKERRQ(ierr); } else { PetscMPIInt rank; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); if (rank == 0) { // create mesh on rank 0 ierr = DMPlexCreateFromCellList(PETSC_COMM_WORLD, dim,ncell,nvert,dim+1, PETSC_TRUE, // "interpolate" flag; TRUE means "topologically-interpolate" // i.e. create edges (1D) from vertices (0D) and cells (2D) cells,dim,coordverts, &dmplex); CHKERRQ(ierr); } else { // empty mesh on rank > 0 ierr = DMPlexCreateFromCellList(PETSC_COMM_WORLD, dim,0,0,dim+1,PETSC_TRUE,NULL,dim,NULL,&dmplex); CHKERRQ(ierr); } } // distribute mesh over processes using default partitioner { DM distributedMesh = NULL; // overlap of 0 is appropriate to P2 etc. FEM: ierr = DMPlexDistribute(dmplex, 0, NULL, &distributedMesh);CHKERRQ(ierr); if (distributedMesh) { ierr = DMDestroy(&dmplex);CHKERRQ(ierr); dmplex = distributedMesh; } } // reset names before viewing ierr = PetscObjectSetName((PetscObject)dmplex, "tiny mesh"); CHKERRQ(ierr); { DM cdm; PetscSection csection; ierr = DMGetCoordinateDM(dmplex, &cdm); CHKERRQ(ierr); ierr = DMGetDefaultSection(cdm, &csection); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)csection, "vertex coordinate section"); CHKERRQ(ierr); } ierr = DMSetFromOptions(dmplex); CHKERRQ(ierr); ierr = DMViewFromOptions(dmplex, NULL, "-dm_view"); CHKERRQ(ierr); ierr = PlexViewFromOptions(dmplex); CHKERRQ(ierr); // integrate f(x,y) by summing over cells and using quadrature if (integrate_f) { double integral; const double intfexact = (1.0 - exp(-1.0)) * 0.5 * (1.0 - exp (-2.0)); ierr = IntegrateF(dmplex,f,quaddegree,&integral); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "integral of f(x,y) is %.12f with error %.2e\n", integral,fabs(integral - intfexact)); CHKERRQ(ierr); } // create nodes (degrees of freedom) for P2 elements using PetscSection ierr = CreateSectionP2(dmplex,&p2section); CHKERRQ(ierr); ierr = DMSetDefaultSection(dmplex, p2section); CHKERRQ(ierr); ierr = PetscObjectViewFromOptions((PetscObject)p2section,NULL,"-tny_view_section"); CHKERRQ(ierr); // put function f(x,y) into v by local calculations using coordinates and p2section ierr = DMCreateGlobalVector(dmplex, &v); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)v, "v"); CHKERRQ(ierr); ierr = EvaluateFP2(dmplex,p2section,f,&v); CHKERRQ(ierr); ierr = PetscObjectViewFromOptions((PetscObject)v,NULL,"-v_vec_view"); CHKERRQ(ierr); VecDestroy(&v); PetscSectionDestroy(&p2section); DMDestroy(&dmplex); return PetscFinalize(); } /* This function is essentially equivalent to using DMPlexCreateFromCellList(). Note that rank 0 gets the actual mesh and other ranks get an empty mesh. See the implementations of DMPlexBuildFromCellList_Private() DMPlexCreateFromCellListParallel() DMPlexInterpolate() DMPlexBuildCoordinates_Private() */ PetscErrorCode CreateMeshByHand(DM *dmplex) { PetscErrorCode ierr; int j; PetscMPIInt rank; ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank); CHKERRQ(ierr); ierr = DMPlexCreate(PETSC_COMM_WORLD,dmplex); CHKERRQ(ierr); ierr = DMSetDimension(*dmplex,dim); CHKERRQ(ierr); if (rank == 0) { // set the total number of points (npoint = ncell + nvert + nedges) ierr = DMPlexSetChart(*dmplex, 0, npoint); CHKERRQ(ierr); // the points are cells, vertices, edges in that order // we only set cones for cells and edges for (j = 0; j < ncell; j++) { ierr = DMPlexSetConeSize(*dmplex, j, dim+1); CHKERRQ(ierr); } for (j = ncell + nvert; j < npoint; j++) { ierr = DMPlexSetConeSize(*dmplex, j, dim); CHKERRQ(ierr); } ierr = DMSetUp(*dmplex); for (j = 0; j < ncell; j++) { ierr = DMPlexSetCone(*dmplex, j, ccone[j]); CHKERRQ(ierr); } for (j = ncell + nvert; j < npoint; j++) { ierr = DMPlexSetCone(*dmplex, j, econe[j-ncell-nvert]); CHKERRQ(ierr); } } else { ierr = DMPlexSetChart(*dmplex, 0, 0); CHKERRQ(ierr); } // with cones we have only upward directions and no labels for the strata // (note: both Symmetrize & Stratify are required, and they must be in this order ierr = DMPlexSymmetrize(*dmplex); CHKERRQ(ierr); ierr = DMPlexStratify(*dmplex); CHKERRQ(ierr); return 0; } // Set up a PetscSection which holds vertex coordinates. PetscErrorCode CreateCoordinateSectionByHand(DM *dmplex) { PetscErrorCode ierr; PetscSection coordSection; DM cdm; Vec coordinates; double *acoord; int j, d, dim, vertexstart, vertexend; // you have to setup the PetscSection returned by DMGetCoordinateSection() first, // or else the Vec returned by DMCreateLocalVector() has zero size // (and thus seg faults) ierr = DMGetDimension(*dmplex, &dim); CHKERRQ(ierr); ierr = DMGetCoordinateSection(*dmplex, &coordSection); CHKERRQ(ierr); ierr = DMPlexGetDepthStratum(*dmplex, 0, &vertexstart, &vertexend); CHKERRQ(ierr); ierr = PetscSectionSetNumFields(coordSection, 1); CHKERRQ(ierr); ierr = PetscSectionSetFieldComponents(coordSection, 0, dim); CHKERRQ(ierr); ierr = PetscSectionSetChart(coordSection, vertexstart, vertexend); CHKERRQ(ierr); for (j = vertexstart; j < vertexend; j++) { ierr = PetscSectionSetDof(coordSection, j, dim); CHKERRQ(ierr); ierr = PetscSectionSetFieldDof(coordSection, j, 0, dim); CHKERRQ(ierr); } ierr = PetscSectionSetUp(coordSection); CHKERRQ(ierr); // now we can actually set up the coordinate Vec ierr = DMGetCoordinateDM(*dmplex, &cdm); CHKERRQ(ierr); ierr = DMCreateLocalVector(cdm, &coordinates); CHKERRQ(ierr); ierr = VecSetBlockSize(coordinates,dim); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) coordinates, "coordinates"); CHKERRQ(ierr); ierr = VecGetArray(coordinates, &acoord); CHKERRQ(ierr); for (j = 0; j < vertexend-vertexstart; j++) { for (d = 0; d < dim; ++d) { acoord[j*dim+d] = coordverts[j*dim+d]; } } ierr = VecRestoreArray(coordinates, &acoord); CHKERRQ(ierr); // finally we tell the DM that it has coordinates ierr = DMSetCoordinatesLocal(*dmplex, coordinates); CHKERRQ(ierr); VecDestroy(&coordinates); return 0; } // use quadrature to integrate a function by summing over cells PetscErrorCode IntegrateF(DM dmplex, double f(double x,double y), int quaddegree, double *fint) { PetscErrorCode ierr; DM cdm; Vec coords; const Quad2DTri q = symmgauss[quaddegree-1]; const double *acoords; double x[3], y[3], xr, yr, dx1, dx2, dy1, dy2, absdetJ, csum, fintloc; int numpts, *pts = NULL, voff, j, p, l, r, vertstart, vertend, cellstart, cellend; MPI_Comm comm; ierr = DMGetCoordinateDM(dmplex, &cdm); CHKERRQ(ierr); ierr = DMGetCoordinatesLocal(dmplex, &coords); CHKERRQ(ierr); ierr = DMPlexGetHeightStratum(dmplex, 0, &cellstart, &cellend); CHKERRQ(ierr); ierr = DMPlexGetDepthStratum(dmplex, 0, &vertstart, &vertend); CHKERRQ(ierr); ierr = VecGetArrayRead(coords, &acoords); CHKERRQ(ierr); // integral by sum over cells fintloc = 0.0; for (j = cellstart; j < cellend; j++) { ierr = DMPlexGetTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts); if (numpts != 7) { SETERRQ(PETSC_COMM_WORLD,1,"wrong: assume closure of triangle has 7 points\n"); } // record vertex coordinates for (l = 0; l < 3; l++) { // loop through vertex points p = 8 + 2 * l; // p=0,1 are cell info; p=2,...,7 are edge info; omit orientations if ((pts[p] < vertstart) || (pts[p] >= vertend)) { SETERRQ(PETSC_COMM_WORLD,2,"wrong: pts[p] should be a vertex\n"); } voff = pts[p] - vertstart; x[l] = acoords[2*voff+0]; y[l] = acoords[2*voff+1]; } // geometry of element (cell) dx1 = x[1] - x[0]; dx2 = x[2] - x[0]; dy1 = y[1] - y[0]; dy2 = y[2] - y[0]; absdetJ = fabs(dx1 * dy2 - dx2 * dy1); // sum over quadrature points on cell csum = 0.0; for (r = 0; r < q.n; r++) { xr = x[0] + dx1 * q.xi[r] + dx2 * q.eta[r]; yr = y[0] + dy1 * q.xi[r] + dy2 * q.eta[r]; csum += q.w[r] * f(xr,yr); } // add cell contribution fintloc += absdetJ * csum; ierr = DMPlexRestoreTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts); CHKERRQ(ierr); } ierr = VecRestoreArrayRead(coords, &acoords); CHKERRQ(ierr); ierr = PetscObjectGetComm((PetscObject)dmplex,&comm); CHKERRQ(ierr); ierr = MPI_Allreduce(&fintloc,fint,1,MPI_DOUBLE,MPI_SUM,comm); CHKERRQ(ierr); return 0; } PetscErrorCode CreateSectionP2(DM dmplex, PetscSection *section) { PetscErrorCode ierr; int j, pstart, pend, vertexstart, edgeend; ierr = PetscSectionCreate(PETSC_COMM_WORLD,section); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)*section, "P2 scalar section"); CHKERRQ(ierr); ierr = PetscSectionSetNumFields(*section, 1); CHKERRQ(ierr); ierr = DMPlexGetChart(dmplex, &pstart, &pend); CHKERRQ(ierr); ierr = PetscSectionSetChart(*section, pstart, pend); CHKERRQ(ierr); ierr = DMPlexGetDepthStratum(dmplex, 0, &vertexstart, NULL); CHKERRQ(ierr); ierr = DMPlexGetDepthStratum(dmplex, 1, NULL, &edgeend); CHKERRQ(ierr); for (j = pstart; j < pend; ++j) { if (j < vertexstart) { ierr = PetscSectionSetDof(*section, j, 0); CHKERRQ(ierr); ierr = PetscSectionSetFieldDof(*section, j, 0, 0); CHKERRQ(ierr); } else { ierr = PetscSectionSetDof(*section, j, 1); CHKERRQ(ierr); ierr = PetscSectionSetFieldDof(*section, j, 0, 1); CHKERRQ(ierr); } } ierr = PetscSectionSetUp(*section); CHKERRQ(ierr); return 0; } PetscErrorCode EvaluateFP2(DM dmplex, PetscSection section, double f(double x,double y), Vec *v) { PetscErrorCode ierr; DM cdm; Vec vloc, coords; double *avloc, x, y; const double *acoords; int numpts, *pts = NULL, dof, off, j, p, vertstart, vertend, edgestart, edgeend, cellstart, cellend; // we put values in a local vector, thus redundantly on overlap ierr = DMGetLocalVector(dmplex, &vloc); CHKERRQ(ierr); ierr = VecGetArray(vloc, &avloc); CHKERRQ(ierr); // need coordinates of P2 nodes (i.e. both vertices and edges) ierr = DMGetCoordinateDM(dmplex, &cdm); CHKERRQ(ierr); ierr = DMGetCoordinatesLocal(dmplex,&coords); CHKERRQ(ierr); ierr = DMPlexGetHeightStratum(dmplex, 0, &cellstart, &cellend); CHKERRQ(ierr); ierr = DMPlexGetDepthStratum(dmplex, 0, &vertstart, &vertend); CHKERRQ(ierr); ierr = DMPlexGetDepthStratum(dmplex, 1, &edgestart, &edgeend); CHKERRQ(ierr); ierr = VecGetArrayRead(coords, &acoords); CHKERRQ(ierr); for (j = cellstart; j < cellend; j++) { ierr = DMPlexGetTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts); for (p = 0; p < numpts*2; p += 2) { // omit orientations PetscSectionGetDof(section, pts[p], &dof); if (dof > 0) { // compute (x,y) for vertex or edge center from coords if (pts[p] < vertstart) { SETERRQ(PETSC_COMM_WORLD,1,"cell center computation not implemented\n"); } else if (pts[p] < edgestart) { int voff; voff = pts[p] - vertstart; x = acoords[2*voff+0]; y = acoords[2*voff+1]; } else { // pts[p] is an edge ... const int *vpts; int voff[2]; ierr = DMPlexGetCone(dmplex, pts[p], &vpts); CHKERRQ(ierr); voff[0] = vpts[0] - vertstart; voff[1] = vpts[1] - vertstart; x = 0.5 * (acoords[2*voff[0]+0] + acoords[2*voff[1]+0]); y = 0.5 * (acoords[2*voff[0]+1] + acoords[2*voff[1]+1]); } // get index "off" into Vec vloc based on P2 scalar section PetscSectionGetOffset(section, pts[p], &off); avloc[off] = f(x,y); } } ierr = DMPlexRestoreTransitiveClosure(dmplex, j, PETSC_TRUE, &numpts, &pts); CHKERRQ(ierr); } ierr = VecRestoreArray(vloc, &avloc); CHKERRQ(ierr); ierr = VecRestoreArrayRead(coords, &acoords); CHKERRQ(ierr); // now we want v global, i.e. only values not duplicate ghosts ierr = DMLocalToGlobalBegin(dmplex,vloc,INSERT_VALUES,*v); CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(dmplex,vloc,INSERT_VALUES,*v); CHKERRQ(ierr); ierr = DMRestoreLocalVector(dmplex, &vloc); CHKERRQ(ierr); return 0; } // FIXME InterpolateFP2()
{ "alphanum_fraction": 0.5996365129, "avg_line_length": 43.7358974359, "ext": "c", "hexsha": "bb051d0384b5b33cd93fc167b424dd66c3ec3d82", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/junk/plex/tiny.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/junk/plex/tiny.c", "max_line_length": 102, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/junk/plex/tiny.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 4739, "size": 17057 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include <timerlib.h> #ifndef NOBLAS #ifdef MKL #include <mkl_cblas.h> #else #include <cblas.h> #endif #endif #include "gdrdgemm.h" #define NMAT 2048 void gdr_check_and_restart(double a[][NMAT], double b[][NMAT], double c[][NMAT]) { int try =0; static int initialized = 0; if (initialized) return; while(1){ int i,j; for(i=0;i<NMAT;i++){ for(j=0;j<NMAT;j++){ a[i][j]=0; b[i][j]=i*NMAT+j; c[i][j]=0; } } for(i=0;i<NMAT;i++)a[i][i]=1; cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, NMAT,NMAT, NMAT, 1.0, a, NMAT, b, NMAT, 0.0, c, NMAT); cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, NMAT,NMAT, NMAT, 1.0, a, NMAT, b, NMAT, 0.0, c, NMAT); mygdrdgemm(NMAT, NMAT, NMAT, 1.0, (double*)a, NMAT, (double*)b, NMAT, 0.0, (double*) c, NMAT); int err = 0; for(i=0;i<NMAT;i++){ for(j=0;j<NMAT;j++){ if (b[i][j] != c[i][j]){ err ++; } } } if (err == 0){ fprintf(stderr,"gdr_check_and_restart passed %d\n", try); initialized=1; return; } try++; fprintf(stderr, "gdr_check_and_restart, err=%d try=%d\n", err, try); gdr_free(); gdr_init(); } } void gdrblas_dgemm ( #ifndef MKL const enum CBLAS_ORDER ORDER, const enum CBLAS_TRANSPOSE TRANSA, const enum CBLAS_TRANSPOSE TRANSB, #else const CBLAS_ORDER ORDER, const CBLAS_TRANSPOSE TRANSA, const CBLAS_TRANSPOSE TRANSB, #endif const int M, const int N, const int K, const double ALPHA, const double * A, const int LDA, const double * B, const int LDB, const double BETA, double * C, const int LDC ) { int NOTA, NOTB,gdrdoneflag; double alpha = ALPHA, beta = BETA; int F77M=M, F77N=N, F77K=K, F77lda=LDA, F77ldb=LDB, F77ldc=LDC; if( TRANSA == CblasNoTrans ){ NOTA = 1; }else{ NOTA = 0; } if( TRANSB == CblasNoTrans ){ NOTB = 1; }else{ NOTB = 0; } if( ORDER == CblasColMajor ){ gdrdoneflag=0; gdr_dgemm_(&NOTA,&NOTB,&F77M,&F77N,&F77K, &alpha, &beta, &F77lda, &F77ldb, &F77ldc,A,B,C, &gdrdoneflag); } else { gdrdoneflag=0; gdr_dgemm_(&NOTA,&NOTB,&F77N,&F77M,&F77K, &alpha, &beta, &F77ldb, &F77lda, &F77ldc,B,A,C, &gdrdoneflag); } if(gdrdoneflag!=1){ cblas_dgemm(ORDER, TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC); } /* * End of HPL_dgemm */ } void dumpcmat(int m, int n, int nc, double c[][nc]) { static int callcount = 0; static FILE* fid; if (callcount == 0){ fid = fopen("/tmp/matdata", "w"); } callcount ++; if(callcount < 8){ fprintf(fid,"\nPrint CMAT callcount=%d\n",callcount); int i, j; for(i=0;i<m;i++){ fprintf(fid,"\ni=%d\n", i); for(j=0;j<n;j++){ if ((j%8)==0 )fprintf(fid,"\n%5d:", j); fprintf(fid," %20.12e",c[i][j]); } } } } double touchcmat(int m, int n, int nc, double c[][nc]) { double sum=0; int i, j; for(i=0;i<m;i++){ for(j=0;j<n;j++){ sum += c[i][j]*c[i][j]; } } return sum; } double ssum = 0.0; void mygdrdgemm(int m, int n, int k, double alpha, double * a, int na, double * b, int nb, double beta, double * c, int nc) { int nota=1, notb=1; int gdrdoneflag = 0; static int first_call = 1; if (first_call){ gdrdgemm_set_procname(MP_myprocid()); first_call=0; init_current_time(); } // char str[128]; // sprintf(str,"before sums = %25.20e %25.20e %25.20e", // touchcmat(m,k,na,a), touchcmat(k,n,nb,b), touchcmat(m,n,nc,c)); // MP_message(str); // dprintf(9,"mygdrdgemm omp_max_threads=%d procs=%d\n", // omp_get_max_threads(),omp_get_num_procs()); double zero=0.0; // int tmp=0; // gdr_dgemm_(&nota, &notb, &n, &m, &k, &zero, &beta, &nb, &na, &nc, // b, a, c, &tmp); gdr_dgemm_(&nota, &notb, &n, &m, &k, &alpha, &beta, &nb, &na, &nc, b, a, c, &gdrdoneflag); // cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, // m,n, k, alpha, a, na, b, nb, beta, c, nc); // gdrdoneflag=1; // fprintf(stderr,"gdrflag=%d\n", gdrdoneflag); if(gdrdoneflag!=1){ cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, m,n, k, alpha, a, na, b, nb, beta, c, nc); } // dumpcmat(m,n,nc,c); // sprintf(str,"after sums = %25.20e %25.20e %25.20e", // touchcmat(m,k,na,a), touchcmat(k,n,nb,b), touchcmat(m,n,nc,c)); // MP_message(str); }
{ "alphanum_fraction": 0.5300266448, "avg_line_length": 24.395, "ext": "c", "hexsha": "ad967758bc3124aabedff6dd06d2a4cfe10f7077", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-13T15:31:32.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-13T15:31:32.000Z", "max_forks_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jmakino/lu2", "max_forks_repo_path": "gdrdgemm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jmakino/lu2", "max_issues_repo_path": "gdrdgemm.c", "max_line_length": 75, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jmakino/lu2", "max_stars_repo_path": "gdrdgemm.c", "max_stars_repo_stars_event_max_datetime": "2020-05-04T05:00:16.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-07T09:18:43.000Z", "num_tokens": 1760, "size": 4879 }
#ifndef STDAFX__H #define STDAFX__H #if defined(_WIN32) #include <SDKDDKVer.h> #if !defined(_STL_EXTRA_DISABLED_WARNINGS) #define _STL_EXTRA_DISABLED_WARNINGS 4061 4324 4365 4514 4571 4582 4583 4623 4625 4626 4710 4774 4820 4987 5026 5027 5039 #endif #if !defined(_SCL_SECURE_NO_WARNINGS) #define _SCL_SECURE_NO_WARNINGS 1 #endif #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS 1 #endif #if !defined(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING) #define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1 #endif #if !defined(_SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING) #define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING 1 #endif #if !defined(_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING) #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 1 #endif #define STRICT #define NOMINMAX #pragma warning(disable: 4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught #pragma warning(disable: 4668) // warning C4668: '%s' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' #pragma warning(disable: 4710) // warning C4710: '%s': function not inlined #pragma warning(disable: 4711) // warning C4711: function '%s' selected for automatic inline expansion #pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s' #pragma warning(disable: 5045) // warning C5045: Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified #include <Windows.h> #pragma warning(push) #pragma warning(disable: 4005) // warning C4005: '%s': macro redefinition #include <Winternl.h> #include <ntstatus.h> #pragma warning(pop) #else // defined(_WIN32) #include <cpuid.h> #endif #if defined(_MSC_VER) // currently broken (triggers on iterators and other objects that are usually unnamed) #pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923). // disable for everything #pragma warning(disable: 4061) // warning C4061: enumerator '%s' in switch of enum '%s' is not explicitly handled by a case label #pragma warning(disable: 4324) // warning C4234: structure was padded due to alignment specifier #pragma warning(disable: 4514) // warning C4514: '%s': unreferenced inline function has been removed #pragma warning(disable: 4623) // warning C4623: '%s': default constructor was implicitly defined as deleted #pragma warning(disable: 4625) // warning C4625: '%s': copy constructor was implicitly defined as deleted #pragma warning(disable: 4626) // warning C4626: '%s': assignment operator was implicitly defined as deleted #pragma warning(disable: 4710) // warning C4710: '%s': function not inlined #pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s' #pragma warning(disable: 5026) // warning C5026: '%s': move constructor was implicitly defined as deleted #pragma warning(disable: 5027) // warning C5027: '%s': move assignment operator was implicitly defined as deleted #pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'no initialization'. #pragma warning(disable: 26426) // warning C26426: Global initializer calls a non-constexpr function '%s' (i.22: http://go.microsoft.com/fwlink/?linkid=853919). #pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413) #pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414). #pragma warning(disable: 26485) // warning C26485: Expression '%s::`vbtable'': No array to pointer decay. (bounds.3: http://go.microsoft.com/fwlink/p/?LinkID=620415) #pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417) #pragma warning(disable: 26499) // warning C26499: Could not find any lifetime tracking information for '%s' // disable for standard headers #pragma warning(push) #pragma warning(disable: 26400) // warning C26400: Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead. (i.11 http://go.microsoft.com/fwlink/?linkid=845474) #pragma warning(disable: 26401) // warning C26401: Do not delete a raw pointer that is not an owner<T>. (i.11: http://go.microsoft.com/fwlink/?linkid=845474) #pragma warning(disable: 26408) // warning C26408: Avoid malloc() and free(), prefer the nothrow version of new with delete. (r.10 http://go.microsoft.com/fwlink/?linkid=845483) #pragma warning(disable: 26409) // warning C26409: Avoid calling new and delete explicitly, use std::make_unique<T> instead. (r.11 http://go.microsoft.com/fwlink/?linkid=845485) #pragma warning(disable: 26411) // warning C26411: The parameter '%s' is a reference to unique pointer and it is never reassigned or reset, use T* or T& instead. (r.33 http://go.microsoft.com/fwlink/?linkid=845479) #pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'end of function scope (local lifetimes end)'. #pragma warning(disable: 26413) // warning C26413: Do not dereference nullptr (lifetimes rule 2). 'nullptr' was pointed to nullptr at line %d. #pragma warning(disable: 26423) // warning C26423: The allocation was not directly assigned to an owner. #pragma warning(disable: 26424) // warning C26424: Failing to delete or assign ownership of allocation at line %d. #pragma warning(disable: 26425) // warning C26425: Assigning '%s' to a static variable. #pragma warning(disable: 26444) // warning C26444: Avoid unnamed objects with custom construction and destruction (es.84: http://go.microsoft.com/fwlink/?linkid=862923). #pragma warning(disable: 26461) // warning C26461: The reference argument '%s' for function %s can be marked as const. (con.3: https://go.microsoft.com/fwlink/p/?LinkID=786684) #pragma warning(disable: 26471) // warning C26471: Don't use reinterpret_cast. A cast from void* can use static_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417). #pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413) #pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions. (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414) #pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417) #pragma warning(disable: 26493) // warning C26493: Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast. (type.4: http://go.microsoft.com/fwlink/p/?LinkID=620420) #pragma warning(disable: 26494) // warning C26494: Variable '%s' is uninitialized. Always initialize an object. (type.5: http://go.microsoft.com/fwlink/p/?LinkID=620421) #pragma warning(disable: 26495) // warning C26495: Variable '%s' is uninitialized. Always initialize a member variable. (type.6: http://go.microsoft.com/fwlink/p/?LinkID=620422) #pragma warning(disable: 26496) // warning C26496: Variable '%s' is assigned only once, mark it as const. (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969) #pragma warning(disable: 26497) // warning C26497: This function %s could be marked constexpr if compile-time evaluation is desired. (f.4: https://go.microsoft.com/fwlink/p/?LinkID=784970) #else // linux warnings go here #endif #include <cstddef> #include <map> #include <set> #include <vector> #include <string> #include <algorithm> #include <iostream> #include <fstream> #include <iomanip> #include <type_traits> #include <utility> #include <memory> #include <tuple> #include <thread> #include <cstdlib> #include <codecvt> #if defined(_MSC_VER) // disable additionally for third-party libraries #pragma warning(push) #pragma warning(disable: 4456) // warning C4456: declaration of '%s' hides previous local declaration #pragma warning(disable: 4458) // warning C4458: declaration of '%s' hides class member #pragma warning(disable: 4459) // warning C4459: declaration of '%s' hides global declaration #pragma warning(disable: 26429) // warning C26429: Symbol '%s' is never tested for nullness, it can be marked as not_null (f.23: http://go.microsoft.com/fwlink/?linkid=853921). #pragma warning(disable: 26432) // warning C26432: If you define or delete any default operation in the type '%s', define or delete them all (c.21: http://go.microsoft.com/fwlink/?linkid=853922). #pragma warning(disable: 26433) // warning C26433: Function '%s' should be marked with 'override' (c.128: http://go.microsoft.com/fwlink/?linkid=853923). #pragma warning(disable: 26434) // warning C26434: Function '%s' hides a non-virtual function '%s' (c.128: http://go.microsoft.com/fwlink/?linkid=853923). #pragma warning(disable: 26436) // warning C26436: The type '%s' with a virtual function needs either public, virtual or protected non-virtual destructor (c.35: http://go.microsoft.com/fwlink/?linkid=853924). #pragma warning(disable: 26439) // warning C26439: This kind of function may not throw. Declare it 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927). #pragma warning(disable: 26440) // warning C26440: Function '%s' can be declared 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927). #pragma warning(disable: 26443) // warning C26443: Overriding destructor should not use explicit 'override' or 'virtual' specifiers (c.128: http://go.microsoft.com/fwlink/?linkid=853923). #pragma warning(disable: 26462) // warning C26462: The value pointed to by '%s' is assigned only once, mark it as a pointer to const (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969). #pragma warning(disable: 26472) // warning C26472: Don't use a static_cast for arithmetic conversions. Use brace initialization, gsl::narrow_cast or gsl::narow (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417). #pragma warning(disable: 26474) // warning C26474: Don't cast between pointer types when the conversion could be implicit (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417). #pragma warning(disable: 26491) // warning C26491: Don't use static_cast downcasts (type.2: http://go.microsoft.com/fwlink/p/?LinkID=620418). #pragma warning(disable: 26498) // warning C26498: The function '%s' is constexpr, mark variable '%s' constexpr if compile-time evaluation is desired (con.5: https://go.microsoft.com/fwlink/p/?LinkID=784974). #endif #ifndef BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE #define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE #endif #include <boost/algorithm/string.hpp> #include <boost/xpressive/xpressive.hpp> #include <gsl/gsl> #include <fmt/format.h> #if defined(_MSC_VER) #pragma warning(pop) #pragma warning(pop) #else // linux warning restoration goes here #endif #endif
{ "alphanum_fraction": 0.7501096395, "avg_line_length": 64.7784090909, "ext": "h", "hexsha": "96cd0edf7421232b3c36892d316e7828e745ec14", "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": "d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "DrPizza/jsm", "max_forks_repo_path": "examples/cpuid/libcpuid/test/src/cpuid/stdafx.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef", "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": "DrPizza/jsm", "max_issues_repo_path": "examples/cpuid/libcpuid/test/src/cpuid/stdafx.h", "max_line_length": 235, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "DrPizza/jsm", "max_stars_repo_path": "examples/cpuid/libcpuid/test/src/cpuid/stdafx.h", "max_stars_repo_stars_event_max_datetime": "2021-06-29T06:46:34.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-29T06:46:34.000Z", "num_tokens": 3006, "size": 11401 }
/* ode-initval/odeiv.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> gsl_odeiv2_step * gsl_odeiv2_step_alloc (const gsl_odeiv2_step_type * T, size_t dim) { gsl_odeiv2_step *s = (gsl_odeiv2_step *) malloc (sizeof (gsl_odeiv2_step)); if (s == 0) { GSL_ERROR_NULL ("failed to allocate space for ode struct", GSL_ENOMEM); }; s->type = T; s->dimension = dim; s->state = s->type->alloc (dim); if (s->state == 0) { free (s); /* exception in constructor, avoid memory leak */ GSL_ERROR_NULL ("failed to allocate space for ode state", GSL_ENOMEM); }; return s; } const char * gsl_odeiv2_step_name (const gsl_odeiv2_step * s) { return s->type->name; } unsigned int gsl_odeiv2_step_order (const gsl_odeiv2_step * s) { return s->type->order (s->state); } int gsl_odeiv2_step_apply (gsl_odeiv2_step * s, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv2_system * dydt) { return s->type->apply (s->state, s->dimension, t, h, y, yerr, dydt_in, dydt_out, dydt); } int gsl_odeiv2_step_reset (gsl_odeiv2_step * s) { return s->type->reset (s->state, s->dimension); } void gsl_odeiv2_step_free (gsl_odeiv2_step * s) { RETURN_IF_NULL (s); s->type->free (s->state); free (s); } int gsl_odeiv2_step_set_driver (gsl_odeiv2_step * s, const gsl_odeiv2_driver * d) { if (d != NULL) { s->type->set_driver (s->state, d); } else { GSL_ERROR ("driver pointer is null", GSL_EFAULT); } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6395214203, "avg_line_length": 24.6761904762, "ext": "c", "hexsha": "0ee5421877b37076e4f1e5bfbd75c0a7cd61906d", "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": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "igormcoelho/optstats", "max_forks_repo_path": "thirdparty/gsl-2.7/ode-initval2/step.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "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": "igormcoelho/optstats", "max_issues_repo_path": "thirdparty/gsl-2.7/ode-initval2/step.c", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "igormcoelho/optstats", "max_stars_repo_path": "thirdparty/gsl-2.7/ode-initval2/step.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 756, "size": 2591 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /* * * * Filename: distance.h * * Description: Distance in trace norm among the stationary and thermal * states. * * Version: 1.0 * Created: 22/06/2014 22:21:50 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include <gsl/gsl_vector.h> #include "funcs.h" /* * FUNCTION * Name: dist * Description: distance between two states in Bloch vector form. It does not * check the positivity of the states * */ double dist ( const gsl_vector* rho1, const gsl_vector* rho2 ); gsl_vector therm_state ( const double beta, const gsl_matrix* H );
{ "alphanum_fraction": 0.7163284133, "avg_line_length": 35.5409836066, "ext": "h", "hexsha": "aff427db49d615cc32361829901abb4543bb51b2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "distance.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_path": "distance.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "distance.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 504, "size": 2168 }
#ifndef GSL_WRAPER_H #define GSL_WRAPER_H #include <gsl/gsl_errno.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_multifit.h> #include "VTypes.h" typedef double (*root_func)(double,void*); typedef double (*multimin_func)(const gsl_vector*, void*); double find_root_gsl_wraper(root_func func, void *params, double x_max, double x_min, double epsabs=1e-8, double epsfrac=1e-10); double find_min_arg_gsl_wraper(root_func func, void *params, double x_max, double x_min, double epsabs=1e-8, double epsfrac=0); VD find_multimin_arg_gsl_wraper(multimin_func func, void *params, VD start, double epsabs=1e-2); class GSL_BSpline_Fit { private: VVD _Y; VVD _Y_transposed; VD _X; int _NFields; int _K; int _NCOEFFS; int _NBREAKS; int _NDataPoints; bool _FIX_ENDS; gsl_bspline_workspace *_bw = nullptr; gsl_multifit_linear_workspace *_mw = nullptr; gsl_vector* _B = nullptr; // Store the coefficients at each x; gsl_matrix* _dB = nullptr; // Store the coefficients at each x gsl_matrix* _XC = nullptr; // Store the coefficients at all x, which then will be used for fitting std::vector<gsl_vector*> _Cs; // The coefficient from fitting // gsl_vector *_Weight; // The weight in fitting std::vector<gsl_matrix*> _COVs; // The covariant matrix void Fitting(); public: GSL_BSpline_Fit(int k, int ncoeffs, bool fix_ends = true); GSL_BSpline_Fit(VVD Y, VD X, int k, int ncoeffs, bool fix_ends = true); ~GSL_BSpline_Fit(); void SetDataX(VD X); void UpdateDataY(VVD Y); VD valAt(double x); VVD valAt(VD X); std::tuple<VD,VD> derivAt(double x); // first and second derivative; std::tuple<VVD,VVD> derivAt(VD X); }; class GSL_Spline_Inter { private: int _size; VD *_Y; // I just keep the point to the data, but not own the data VD *_X; // Since I don't own the data, so I can't guarantee the original data is still there. So I keep some of them first. double _xmin; double _xmax; double _ymin; double _ymax; double _yaver; gsl_interp_accel *_acc = nullptr; gsl_spline *_spline = nullptr; public: GSL_Spline_Inter(); ~GSL_Spline_Inter(); void SetData(VD *Y, VD *X); double valAt(double x,int deri = 0); VD valAt(VD X); }; class GSL_Multi_Spline_Inter { private: int _NDim; int _size; // I just keep the point to the data, but not own the data // The first index of _Y is the same as _X, the second index of _Y is the field index, so it is not convenience for interpolation. So I will transpose it to _Y_transposed VVD *_Y; VD *_X; VVD _Y_transposed; // I keep the transposed data; // Since I don't own the data, so I can't guarantee the original data is still there. So I keep some of them first. double _xmin; double _xmax; VD _ymin; VD _ymax; VD _yaver; gsl_interp_accel *_acc = nullptr; std::vector<gsl_spline*> _splines; public: GSL_Multi_Spline_Inter(); ~GSL_Multi_Spline_Inter(); void SetData(VVD *Y, VD *X); VD valAt(double x,int deri = 0); }; #endif //GSL_WRAPER_H
{ "alphanum_fraction": 0.6896445131, "avg_line_length": 27.8879310345, "ext": "h", "hexsha": "377735749b4024b306891d63b0d5dc1b2ce12970", "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": "76bee3915b26025a607a71c372005ea88b3d1389", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ycwu1030/PhaseTransitions", "max_forks_repo_path": "include/GSL_Wraper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "76bee3915b26025a607a71c372005ea88b3d1389", "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": "ycwu1030/PhaseTransitions", "max_issues_repo_path": "include/GSL_Wraper.h", "max_line_length": 174, "max_stars_count": 1, "max_stars_repo_head_hexsha": "76bee3915b26025a607a71c372005ea88b3d1389", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ycwu1030/PhaseTransitions", "max_stars_repo_path": "include/GSL_Wraper.h", "max_stars_repo_stars_event_max_datetime": "2020-06-05T22:59:34.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-05T22:59:34.000Z", "num_tokens": 979, "size": 3235 }
#include <stdio.h> //#ifndef DARWIN //#include <malloc.h> //#endif #include <stddef.h> #include <Python.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <string.h> #include <math.h> /* * A simple helper function to display the contents of a 2-D gsl matrix */ int print_matrix(FILE *f, const gsl_matrix *m) { int status, n = 0; size_t i, j; for (i = 0; i < m->size1; i++) { for (j = 0; j < m->size2; j++) { if ((status = fprintf(f,"%g ", gsl_matrix_get(m, i, j))) < 0) return -1; n += status; } if ((status = fprintf(f, "\n")) < 0) return -1; n += status; } return n; } /* * A simple helper function to display the contennts of a 1-D gsl vector */ int print_vector(FILE *f, const gsl_vector *m) { int status, n = 0; size_t i; for (i = 0; i < m->size; i++) { if ((status = fprintf(f, "%g ", gsl_vector_get(m, i))) < 0) return -1; n += status; } return n; } void print_mat(double* mat, int dim1, int dim2) { int i, j; printf("\n"); for (i=0; i<dim1; i++) { for (j=0; j<dim2; j++) { printf("%6.2f,", mat[i*dim1 + j]); } printf("\n"); } } void print_vec(double* vec, int dim1) { int i; printf("\n"); for (i=0; i<dim1; i++) { printf("%6.2f,", vec[i]); } printf("\n"); } /* Function: get_lnoverlaps * ------------------------ * Calculates the log overlap (convolution) with a set of 6D Gaussians with * a single 6D Gaussian, each in turn. * * In Chronostar, this is used to see how well the kinematic properties * of stars overlap with a proposed Gaussian distribution. * * Paramaters * name type description * ---------- * gr_cov (6*6 npArray) group's covariance matrix * gr_mn (1*6 npArray) group's central estimate (mean) * st_covs (n*6*6 npArray) array of each star's cov matrix * st_mns: (n*6 npArray) array of each star's central estimate * lnols_output: (n npArray) used to store and return calculated overlaps * nstars: (int) number of stars, used for array dimensions * * Returns * ------- * (nstars) array of calculated log overlaps of every star with component * thanks to Swig magic the result is stored in `lnols_output` which is * returned as output to the python call as a numpy array * * Notes * ----- * For each star calculates: * log(1/sqrt( (2*PI)^6*det(C) ) * exp( -0.5*(b-a)^T*(C)^-1*(b-a) ) * where * C = st_cov + gr_cov * and * a = gr_mn, b = st_mn * Expanding and simplifying this becomes: * -0.5[ 6*ln(2*PI) + ln(|C|) + (b-a)^T*(C^-1)*(b-a) ] * * Stark improvement on previous implementations. Doesn't require input as * inverse covariance matrices. Never performs a matrix inversion. */ void get_lnoverlaps( double* gr_cov, int gr_dim1, int gr_dim2, double* gr_mn, int gr_mn_dim, double* st_covs, int st_dim1, int st_dim2, int st_dim3, double* st_mns, int st_mn_dim1, int st_mn_dim2, double* lnols_output, int n ) { // ALLOCATE MEMORY int star_count = 0; int MAT_DIM = gr_dim1; //Typically set to 6 int i, j, signum; double d_temp, result, ln_det_BpA; gsl_permutation *p1; gsl_matrix *BpA = gsl_matrix_alloc(MAT_DIM, MAT_DIM); //will hold (B+A) gsl_vector *bma = gsl_vector_alloc(MAT_DIM); //will hold b - a gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); p1 = gsl_permutation_alloc(BpA->size1); // Go through each star, calculating and storing overlap for (star_count=0; star_count<n; star_count++) { // INITIALISE STAR MATRIX for (i=0; i<MAT_DIM; i++) for (j=0; j<MAT_DIM; j++) //performing st_cov+gr_cov as part of the initialisation gsl_matrix_set( BpA,i,j, st_covs[star_count*MAT_DIM*MAT_DIM+i*MAT_DIM+j] + gr_cov[i*MAT_DIM+j] ); // INITIALISE CENTRAL ESTIMATES // performing st_mn - gr_mn as part of the initialisation for (i=0; i<MAT_DIM; i++) { gsl_vector_set( bma, i, st_mns[star_count*MAT_DIM + i] - gr_mn[i] ); } // CALCULATE OVERLAPS // Performed in 4 stages // Calc and sum up the inner terms: // 1) 6 ln(2pi) // 2) ln(|C|) // 3) (b-a)^T(C^-1)(b-a) // Then apply -0.5 coefficient // 1) Calc 6 ln(2pi) result = 6*log(2*M_PI); // 2) Get log determiant of C gsl_linalg_LU_decomp(BpA, p1, &signum); ln_det_BpA = log(fabs(gsl_linalg_LU_det(BpA, signum))); result += ln_det_BpA; // 3) Calc (b-a)^T(C^-1)(b-a) gsl_vector_set_zero(v_temp); gsl_linalg_LU_solve(BpA, p1, bma, v_temp); /* v_temp holds (B+A)^-1 (b-a) * * utilises `p1` as calculated * * above */ gsl_blas_ddot(v_temp, bma, &d_temp); //d_temp holds (b-a)^T (B+A)-1 (b-a) result += d_temp; // 4) Apply coefficient result *= -0.5; // STORE RESULT 'lnols_output' lnols_output[star_count] = result; } // DEALLOCATE THE MEMORY gsl_matrix_free(BpA); gsl_vector_free(bma); gsl_vector_free(v_temp); gsl_permutation_free(p1); } /* NOTE: * Everything below this line is left simply for correctness comparisons */ double get_overlap(double* gr_icov, int gr_dim1, int gr_dim2, double* gr_mn, int gr_mn_dim, double gr_icov_det, double* st_icov, int st_dim1, int st_dim2, double* st_mn, int st_mn_dim, double st_icov_det) { int MAT_DIM = gr_dim1; int i, j, signum; double ApB_det, d_temp, result; gsl_permutation *p; gsl_matrix *A = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *B = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *ApB = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_vector *a = gsl_vector_alloc(MAT_DIM); gsl_vector *b = gsl_vector_alloc(MAT_DIM); gsl_vector *AapBb = gsl_vector_alloc(MAT_DIM); gsl_vector *c = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp2 = gsl_vector_alloc(MAT_DIM); gsl_vector *amc = gsl_vector_alloc(MAT_DIM); //will hold a - c gsl_vector *bmc = gsl_vector_alloc(MAT_DIM); //will hold b - c p = gsl_permutation_alloc(A->size1); //for (l=0; l<1; l++){ //DELETE //Inserting values into matricies and vectors for (i=0; i<MAT_DIM; i++) { for (j=0; j<MAT_DIM; j++) { gsl_matrix_set (A, i, j, gr_icov[i*MAT_DIM + j]); gsl_matrix_set (B, i, j, st_icov[i*MAT_DIM + j]); } } for (i=0; i<MAT_DIM; i++) { gsl_vector_set (a, i, gr_mn[i]); gsl_vector_set (b, i, st_mn[i]); } // Adding A and B together and storing in ApB gsl_matrix_set_zero(ApB); gsl_matrix_add(ApB, A); gsl_matrix_add(ApB, B); // Storing the result A*a + B*b in AapBb gsl_vector_set_zero(AapBb); gsl_blas_dsymv(CblasUpper, 1.0, A, a, 1.0, AapBb); gsl_blas_dsymv(CblasUpper, 1.0, B, b, 1.0, AapBb); // Getting determinant of ApB gsl_linalg_LU_decomp(ApB, p, &signum); //ApB_det = gsl_linalg_LU_det(ApB, signum); ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant // Solve for c gsl_linalg_LU_solve(ApB, p, AapBb, c); // Compute the overlap formula gsl_vector_set_zero(v_temp); gsl_blas_dcopy(a, v_temp); //v_temp holds a gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c gsl_blas_dcopy(v_temp, amc); //amc holds a - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, A, v_temp, 0.0, v_temp2); //v_temp2 holds A (a-c) result = 0.0; gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c) result += d_temp; gsl_vector_set_zero(v_temp); gsl_blas_dcopy(b, v_temp); //v_temp holds b gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c gsl_blas_dcopy(v_temp, bmc); //bmc holds b - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, B, v_temp, 0.0, v_temp2); //v_temp2 holds A (b-c) gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c) result += d_temp; result = -0.5 * result; result = exp(result); result *= sqrt((gr_icov_det * st_icov_det/ApB_det) / pow(2*M_PI, MAT_DIM)); //} //DELETE THIS // Freeing memory gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(ApB); gsl_vector_free(a); gsl_vector_free(b); gsl_vector_free(AapBb); gsl_vector_free(c); gsl_vector_free(v_temp); gsl_vector_free(v_temp2); gsl_vector_free(amc); gsl_vector_free(bmc); gsl_permutation_free(p); return result; } double get_overlap2(PyObject *gr_icov, PyObject *gr_mn, double gr_icov_det, PyObject *st_icov, PyObject *st_mn, double st_icov_det) { int MAT_DIM = 6; int i, j, signum; double ApB_det, d_temp, result; PyObject *o1, *o2; gsl_permutation *p; gsl_matrix *A = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *B = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *ApB = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_vector *a = gsl_vector_alloc(MAT_DIM); gsl_vector *b = gsl_vector_alloc(MAT_DIM); gsl_vector *AapBb = gsl_vector_alloc(MAT_DIM); gsl_vector *c = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp2 = gsl_vector_alloc(MAT_DIM); gsl_vector *amc = gsl_vector_alloc(MAT_DIM); //will hold a - c gsl_vector *bmc = gsl_vector_alloc(MAT_DIM); //will hold b - c p = gsl_permutation_alloc(A->size1); //Inserting values into matricies and vectors for (i=0; i<MAT_DIM; i++) { for (j=0; j<MAT_DIM; j++) { o1 = PyList_GetItem(gr_icov, i*MAT_DIM + j); gsl_matrix_set (A, i, j, PyFloat_AS_DOUBLE(o1)); o2 = PyList_GetItem(st_icov, i*MAT_DIM + j); gsl_matrix_set (B, i, j, PyFloat_AS_DOUBLE(o2)); } } for (i=0; i<MAT_DIM; i++) { o1 = PyList_GetItem(gr_mn, i); gsl_vector_set (a, i, PyFloat_AS_DOUBLE(o1)); o2 = PyList_GetItem(st_mn, i); gsl_vector_set (b, i, PyFloat_AS_DOUBLE(o2)); } // Adding A and B together and storing in ApB gsl_matrix_set_zero(ApB); gsl_matrix_add(ApB, A); gsl_matrix_add(ApB, B); // Storing the result A*a + B*b in AapBb gsl_vector_set_zero(AapBb); gsl_blas_dgemv(CblasNoTrans, 1.0, A, a, 1.0, AapBb); gsl_blas_dgemv(CblasNoTrans, 1.0, B, b, 1.0, AapBb); // Getting determinant of ApB gsl_linalg_LU_decomp(ApB, p, &signum); //ApB_det = gsl_linalg_LU_det(ApB, signum); ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant // Solve for c gsl_linalg_LU_solve(ApB, p, AapBb, c); // Compute the overlap formula gsl_vector_set_zero(v_temp); gsl_blas_dcopy(a, v_temp); //v_temp holds a gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c gsl_blas_dcopy(v_temp, amc); //amc holds a - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dgemv(CblasNoTrans, 1.0, A, v_temp, 0.0, v_temp2); //v_temp2 holds A (a-c) result = 0.0; gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c) result += d_temp; gsl_vector_set_zero(v_temp); gsl_blas_dcopy(b, v_temp); //v_temp holds b gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c gsl_blas_dcopy(v_temp, bmc); //bmc holds b - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dgemv(CblasNoTrans, 1.0, B, v_temp, 0.0, v_temp2); //v_temp2 holds A (b-c) gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c) result += d_temp; result = -0.5 * result; result = exp(result); result *= sqrt((gr_icov_det * st_icov_det/ApB_det) / pow(2*M_PI, MAT_DIM)); // Freeing memory gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(ApB); gsl_vector_free(a); gsl_vector_free(b); gsl_vector_free(AapBb); gsl_vector_free(c); gsl_vector_free(v_temp); gsl_vector_free(v_temp2); gsl_vector_free(amc); gsl_vector_free(bmc); gsl_permutation_free(p); return result; } /* Main function which performs fastest so far: * --parameters-- * group_icov (6*6 npyArray) the group's inverse covariance matrix * group_mn (1*6 npyArray) which is the group's mean kinematic info * group_icov_det (flt) the determinent of the group_icov * Bs (nstars*6*6) an array of each star's icov matrix * bs: (nstars*6) an array of each star's mean kinematic info * B_dets: (nstars) an array of the determinent of each icov * nstars: (int) number of stars, used to determine the size * of npyArray which will return calculated overlaps) * * returns: (nstars) array of calculated overlaps of every star with 1 group * * todo: instead of calling internal function actually use cblas functions * this will save time on the reallocation and deallocation */ void get_overlaps(double* gr_icov, int gr_dim1, int gr_dim2, double* gr_mn, int gr_mn_dim, double gr_icov_det, double* st_icovs, int st_dim1, int st_dim2, int st_dim3, double* st_mns, int st_mn_dim1, int st_mn_dim2, double* st_icov_dets, int st_icov_dets_dim, double* rangevec, int n) { // ALLOCATE MEMORY int star_count = 0; int MAT_DIM = gr_dim1; //Typically set to 6 int i, j, signum; double ApB_det, d_temp, result; gsl_permutation *p; gsl_matrix *A = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *B = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_matrix *ApB = gsl_matrix_alloc(MAT_DIM, MAT_DIM); gsl_vector *a = gsl_vector_alloc(MAT_DIM); gsl_vector *b = gsl_vector_alloc(MAT_DIM); gsl_vector *AapBb = gsl_vector_alloc(MAT_DIM); gsl_vector *c = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); gsl_vector *v_temp2 = gsl_vector_alloc(MAT_DIM); gsl_vector *amc = gsl_vector_alloc(MAT_DIM); //will hold a - c gsl_vector *bmc = gsl_vector_alloc(MAT_DIM); //will hold b - c p = gsl_permutation_alloc(A->size1); // INITIALISE GROUP MATRICES for (i=0; i<MAT_DIM; i++) for (j=0; j<MAT_DIM; j++) gsl_matrix_set (A, i, j, gr_icov[i*MAT_DIM + j]); for (i=0; i<MAT_DIM; i++) gsl_vector_set (a, i, gr_mn[i]); for (star_count=0; star_count<n; star_count++) { // INITIALISE STAR MATRICES for (i=0; i<MAT_DIM; i++) for (j=0; j<MAT_DIM; j++) gsl_matrix_set(B,i,j, st_icovs[star_count*MAT_DIM*MAT_DIM+i*MAT_DIM+j]); for (i=0; i<MAT_DIM; i++) gsl_vector_set (b, i, st_mns[star_count*MAT_DIM + i]); // FIND OVERLAP // Adding A and B together and storing in ApB gsl_matrix_set_zero(ApB); gsl_matrix_add(ApB, A); gsl_matrix_add(ApB, B); // Storing the result A*a + B*b in AapBb gsl_vector_set_zero(AapBb); gsl_blas_dsymv(CblasUpper, 1.0, A, a, 1.0, AapBb); gsl_blas_dsymv(CblasUpper, 1.0, B, b, 1.0, AapBb); // Getting determinant of ApB gsl_linalg_LU_decomp(ApB, p, &signum); //ApB_det = gsl_linalg_LU_det(ApB, signum); ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant // Solve for c gsl_linalg_LU_solve(ApB, p, AapBb, c); // Compute the overlap formula gsl_vector_set_zero(v_temp); gsl_blas_dcopy(a, v_temp); //v_temp holds a gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c gsl_blas_dcopy(v_temp, amc); //amc holds a - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, A, v_temp, 0.0, v_temp2); //v_temp2 holds A (a-c) result = 0.0; gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c) result += d_temp; gsl_vector_set_zero(v_temp); gsl_blas_dcopy(b, v_temp); //v_temp holds b gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c gsl_blas_dcopy(v_temp, bmc); //bmc holds b - c // CAN'T HAVE v_temp and v_temp2 be the same vector. // Results in 0's being stored in v_temp2. gsl_blas_dsymv(CblasUpper, 1.0, B, v_temp, 0.0, v_temp2); //v_temp2 holds A (b-c) gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c) result += d_temp; result = -0.5 * result; result = exp(result); result *= sqrt((gr_icov_det * st_icov_dets[star_count]/ApB_det) / pow(2*M_PI, MAT_DIM)); // STORE IN 'rangevec' rangevec[star_count] = result; } // DEALLOCATE THE MEMORY gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(ApB); gsl_vector_free(a); gsl_vector_free(b); gsl_vector_free(AapBb); gsl_vector_free(c); gsl_vector_free(v_temp); gsl_vector_free(v_temp2); gsl_vector_free(amc); gsl_vector_free(bmc); gsl_permutation_free(p); } /* New main function, speed not yet tested * mostly here for debugging reasons * --parameters-- * group_icov (6*6 npyArray) the group's inverse covariance matrix * group_mn (1*6 npyArray) which is the group's mean kinematic info * group_icov_det (flt) the determinent of the group_icov * Bs (nstars*6*6) an array of each star's icov matrix * bs: (nstars*6) an array of each star's mean kinematic info * B_dets: (nstars) an array of the determinent of each icov * nstars: (int) number of stars, used to determine the size * of npyArray which will return calculated overlaps) * * returns: (nstars) array of calculated overlaps of every star with 1 group * * todo: instead of calling internal function actually use cblas functions * this will save time on the reallocation and deallocation * * look up how to find inverse */ double new_get_lnoverlap( double* gr_cov, int gr_dim1, int gr_dim2, double* gr_mn, int gr_mn_dim, double* st_cov, int st_dim1, int st_dim2, double* st_mn, int st_mn_dim ) { //printf("Inside new_get_lnoverlaps function\n"); printf("-----------------------------------------------------------\n"); printf("new_get_lnoverlap(): In c implemntation of Tim's derivation\n"); printf("-----------------------------------------------------------\n"); //printf("Inputs are:\n"); //printf(" A\n"); //print_mat(gr_cov, gr_dim1, gr_dim2); //printf(" a\n"); //print_vec(gr_mn, gr_mn_dim); //printf(" B\n"); //print_mat(st_cov, st_dim1, st_dim2); //printf(" b\n"); //print_vec(st_mn, st_mn_dim); // ALLOCATE MEMORY int MAT_DIM = gr_dim1; //Typically set to 6 int i, j, signum; double d_temp, result, ln_det_BpA; FILE* fout = stdout; gsl_permutation *p1; gsl_matrix *BpA = gsl_matrix_alloc(MAT_DIM, MAT_DIM); //(B+A) //gsl_matrix *BpAi = gsl_matrix_alloc(MAT_DIM, MAT_DIM); //(B+A)^-1 gsl_vector *bma = gsl_vector_alloc(MAT_DIM); //will hold b - a gsl_vector *v_temp = gsl_vector_alloc(MAT_DIM); p1 = gsl_permutation_alloc(BpA->size1); printf("Memory allocated\n"); // INITIALISE STAR MATRICES for (i=0; i<MAT_DIM; i++) for (j=0; j<MAT_DIM; j++) { //perform B+A as part of the initialisation gsl_matrix_set( BpA,i,j, st_cov[i*MAT_DIM+j] + gr_cov[i*MAT_DIM+j] ); printf("Printing BpA\n"); print_matrix(fout, BpA); } for (i=0; i<MAT_DIM; i++) { gsl_vector_set( bma, i, st_mn[i] - gr_mn[i] ); } printf("Printing bma\n"); print_vec(bma->data, 6); printf("Matrices initialised\n\n"); result = 6*log(2*M_PI); printf("Added 6log(2pi):\n%6.2f\n", result); // Get inverse of BpA, this line is wrong, fix when have internet gsl_linalg_LU_decomp(BpA, p1, &signum); ln_det_BpA = log(fabs(gsl_linalg_LU_det(BpA, signum))); printf("Log of det(ApB): %6.2f\n", ln_det_BpA); result += ln_det_BpA; printf("result so far:\n%6.2f\n",result); // gsl_vector_set_zero(v_temp); gsl_linalg_LU_solve(BpA, p1, bma, v_temp); //v_temp holds (B+A)^-1 (b-a) gsl_blas_ddot(v_temp, bma, &d_temp); //d_temp holds (b-a)^T (B+A)-1 (b-a) printf("Printing bma_BpAi_bma\n"); printf("%6.2f\n\n", d_temp); result += d_temp; printf("result after bma_BpAi_bma:\n%6.2f\n",result); result *= -0.5; printf("Everything calculated\n"); printf("Final result:\n%6.8f\n", result); // // DEALLOCATE THE MEMORY gsl_matrix_free(BpA); //gsl_matrix_free(BpAi); gsl_vector_free(bma); gsl_vector_free(v_temp); gsl_permutation_free(p1); return result; //printf("At end of new_get_lnoverlaps function\n"); }
{ "alphanum_fraction": 0.629146301, "avg_line_length": 30.7635036496, "ext": "c", "hexsha": "7e814159d945777f6a3ef0d9526fa4dcc3ad7a80", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-02-25T06:53:52.000Z", "max_forks_repo_forks_event_min_datetime": "2016-04-21T08:25:26.000Z", "max_forks_repo_head_hexsha": "fcf37614e1d145f3a5e265e54512bf8cd98051a0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mikeireland/chronostar", "max_forks_repo_path": "chronostar/overlap/overlap.c", "max_issues_count": 13, "max_issues_repo_head_hexsha": "fcf37614e1d145f3a5e265e54512bf8cd98051a0", "max_issues_repo_issues_event_max_datetime": "2021-11-08T23:44:29.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-14T07:30:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mikeireland/chronostar", "max_issues_repo_path": "chronostar/overlap/overlap.c", "max_line_length": 80, "max_stars_count": 4, "max_stars_repo_head_hexsha": "fcf37614e1d145f3a5e265e54512bf8cd98051a0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mikeireland/chronostar", "max_stars_repo_path": "chronostar/overlap/overlap.c", "max_stars_repo_stars_event_max_datetime": "2021-05-14T01:13:11.000Z", "max_stars_repo_stars_event_min_datetime": "2018-05-28T11:05:42.000Z", "num_tokens": 6902, "size": 21073 }
/* rng/knuthran2.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * This generator is taken from * * Donald E. Knuth * The Art of Computer Programming * Volume 2 * Third Edition * Addison-Wesley * Page 108 * * This implementation copyright (C) 2001 Carlo Perassi * and (C) 2003 Heiko Bauke. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> #include "schrage.c" #define AA1 271828183UL #define AA2 1833324378UL /* = -314159269 mod (2 ^ 31 -1) */ #define MM 0x7fffffffUL /* 2 ^ 31 - 1 */ #define CEIL_SQRT_MM 46341UL /* sqrt(2 ^ 31 - 1) */ static inline unsigned long int ran_get (void *vstate); static double ran_get_double (void *vstate); static void ran_set (void *state, unsigned long int s); typedef struct { unsigned long int x0; unsigned long int x1; } ran_state_t; static inline unsigned long int ran_get (void *vstate) { ran_state_t *state = (ran_state_t *) vstate; const unsigned long int xtmp = state->x1; state->x1 = schrage_mult (AA1, state->x1, MM, CEIL_SQRT_MM) + schrage_mult (AA2, state->x0, MM, CEIL_SQRT_MM); if (state->x1 >= MM) state->x1 -= MM; state->x0 = xtmp; return state->x1; } static double ran_get_double (void *vstate) { ran_state_t *state = (ran_state_t *) vstate; return ran_get (state) / 2147483647.0; } static void ran_set (void *vstate, unsigned long int s) { ran_state_t *state = (ran_state_t *) vstate; if ((s % MM) == 0) s = 1; /* default seed is 1 */ state->x0 = s % MM; state->x1 = s % MM; return; } static const gsl_rng_type ran_type = { "knuthran2", /* name */ MM - 1L, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (ran_state_t), &ran_set, &ran_get, &ran_get_double }; const gsl_rng_type *gsl_rng_knuthran2 = &ran_type;
{ "alphanum_fraction": 0.6577916993, "avg_line_length": 24.5576923077, "ext": "c", "hexsha": "6835672e6edd8a882fcff8e8d47502a148f07af3", "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/rng/knuthran2.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/rng/knuthran2.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/rng/knuthran2.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": 754, "size": 2554 }
#pragma once #include <gsl/gsl> #include <fmt/format.h> #include "temple_enums.h" // Define objHndl as a struct that contains just the handle value #pragma pack(push, 1) struct objHndl { uint64_t handle; explicit operator bool() const { return !!handle; } objHndl& operator=(uint64_t handle) { this->handle = handle; return *this; } uint32_t GetHandleLower() const { return (uint32_t)(handle & 0xffffffff); } uint32_t GetHandleUpper() const { return (uint32_t)((handle >> 32) & 0xffffffff); } static objHndl FromUpperAndLower(uint32_t upper, uint32_t lower) { return{ (((uint64_t) upper) << 32) | (((uint64_t)lower) & 0xFFFFFFFF) }; } static const objHndl null; }; #pragma pack(pop) /** * Compares two object handles for equality. They are equal if their * handle value is equal. */ inline bool operator ==(const objHndl &a, const objHndl &b) { return a.handle == b.handle; } inline bool operator !=(const objHndl &a, const objHndl &b) { return a.handle != b.handle; } inline bool operator <(const objHndl &a, const objHndl &b) { return a.handle < b.handle; } inline bool operator >(const objHndl &a, const objHndl &b) { return a.handle > b.handle; } void format_arg(fmt::BasicFormatter<char> &f, const char *&format_str, const objHndl &s); namespace std { template <> struct hash<objHndl> { size_t operator()(const objHndl &x) const { return std::hash<uint64_t>()(x.handle); } }; } typedef uint32_t _fieldIdx; typedef uint32_t _fieldSubIdx; typedef uint32_t _mapNum; typedef uint32_t _key; #pragma pack(push, 8) enum class ObjectIdKind : uint16_t { Null = 0, Prototype = 1, Permanent = 2, Positional = 3, Handle = 0xFFFE, Blocked = 0xFFFF }; union ObjectIdBody { GUID guid; uint32_t protoId; objHndl handle; struct { int x; int y; int tempId; int mapId; } pos; }; struct ObjectId { ObjectIdKind subtype = ObjectIdKind::Null; int unk = 0; ObjectIdBody body; bool IsNull() const { return subtype == ObjectIdKind::Null; } bool IsPermanent() const { return subtype == ObjectIdKind::Permanent; } bool IsPrototype() const { return subtype == ObjectIdKind::Prototype; } bool IsPositional() const { return subtype == ObjectIdKind::Positional; } bool IsHandle() const { return subtype == ObjectIdKind::Handle; } bool IsBlocked() const { return subtype == ObjectIdKind::Blocked; } // Can this object id be persisted and later restored to a handle? bool IsPersistable() const { return IsNull() || IsPermanent() || IsPrototype() || IsPositional(); } int GetPrototypeId() const { Expects(IsPrototype()); return body.protoId; } objHndl GetHandle() const { Expects(IsHandle()); return body.handle; } operator bool() const { return !IsNull(); } bool operator ==(const ObjectId &other) const; std::string ToString() const; // Randomly generates a GUID and returns an object id that contains it static ObjectId CreatePermanent(); // Creates a positional object id static ObjectId CreatePositional(int mapId, int tileX, int tileY, int tempId); // Creates a prototype object id static ObjectId CreatePrototype(uint16_t prototypeId); // Creates a null object id static ObjectId CreateNull() { ObjectId result; result.subtype = ObjectIdKind::Null; return result; } static ObjectId CreateHandle(objHndl handle); }; #pragma pack(pop) const int testSizeofObjectId = sizeof(ObjectId); // should be 24
{ "alphanum_fraction": 0.7003191181, "avg_line_length": 20.2764705882, "ext": "h", "hexsha": "024ac1f5b999f6376c5beb32041ce89529c05423", "lang": "C", "max_forks_count": 25, "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_path": "TemplePlus/obj_structs.h", "max_issues_count": 457, "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_path": "TemplePlus/obj_structs.h", "max_line_length": 89, "max_stars_count": 69, "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_path": "TemplePlus/obj_structs.h", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "num_tokens": 928, "size": 3447 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "eigenmap.h" #include <cblas.h> #include <lapacke.h> #include <matio.h> #include <memory.h> #include <time.h> /* * lanczos computes the smallest n_eigs eigenvalues for L and the * corresponding eigenvectors using the Lanczos algorithm. * * F: an array (n_patch by n_eigs) to store the eigenvectors * Es: an array (1 by n_eigs) to store the eigenvalues * L: an array (n_patch by n_patch) representing the Laplacian matrix * n_patch: the dimension of L */ /* ---- corresponding Matlab code ---- * [F, Es] = lanczos(L, n_eigs) */ static double norm2(double *v, int length); static void divide_copy(double *dest, const double *src, int length, const double divisor); void lanczos(double *F, double *Es, double *L, int n_eigs, int n_patch, int LANCZOS_ITR) { double *b; double b_norm; double *z; double *alpha, *beta; double *q; int i; double *eigvec; // eigenvectors // generate random b with norm 1. srand((unsigned int)time(NULL)); b = (double *)malloc(n_patch * sizeof(double)); for (i = 0; i < n_patch; i++) b[i] = rand(); b_norm = norm2(b, n_patch); for (i = 0; i < n_patch; i++) b[i] /= b_norm; alpha = (double *)malloc( (LANCZOS_ITR + 1) * sizeof(double) ); beta = (double *)malloc( (LANCZOS_ITR + 1) * sizeof(double) ); beta[0] = 0.0; // beta_0 <- 0 z = (double *)malloc( n_patch * sizeof(double)); q = (double *)malloc( n_patch * (LANCZOS_ITR + 2) * sizeof(double) ); memset(&q[0], 0, n_patch * sizeof(double)); // q_0 <- 0 memcpy(&q[n_patch], b, n_patch * sizeof(double)); // q_1 <- b for (i = 1; i <= LANCZOS_ITR; i++) { // z = L * Q(:, i) cblas_dsymv(CblasColMajor, CblasLower, n_patch, 1.0, L, n_patch, &q[i * n_patch], 1, 0.0, z, 1); // alpha(i) = Q(:, i)' * z; alpha[i] = cblas_ddot(n_patch, &q[i * n_patch], 1, z, 1); // z = z - alpha(i) * Q(:, i) cblas_daxpy(n_patch, -alpha[i], &q[i * n_patch], 1, z, 1); // z = z - beta(i - 1) * Q(:, i - 1); cblas_daxpy(n_patch, -beta[i - 1], &q[(i - 1) * n_patch], 1, z, 1); /* re-orthogonalize twice */ // b = Q(:, 1:i-1)' * z cblas_dgemv(CblasColMajor, CblasTrans, n_patch, i - 1, 1.0, &q[n_patch], n_patch, z, 1, 0.0, b, 1); // z = Q(:, 1:i-1) * b + (-1) * z cblas_dgemv(CblasColMajor, CblasNoTrans, n_patch, i - 1, 1.0, &q[n_patch], n_patch, b, 1, -1.0, z, 1); // b = Q(:, 1:i-1)' * z cblas_dgemv(CblasColMajor, CblasTrans, n_patch, i - 1, 1.0, &q[n_patch], n_patch, z, 1, 0.0, b, 1); // z = Q(:, 1:i-1) * b + (-1) * z cblas_dgemv(CblasColMajor, CblasNoTrans, n_patch, i - 1, 1.0, &q[n_patch], n_patch, b, 1, -1.0, z, 1); // beta(i) = norm(z, 2); beta[i] = cblas_dnrm2(n_patch, z, 1); // Q(:, i + 1) = z / beta(i); divide_copy(&q[(i + 1) * n_patch], z, n_patch, beta[i]); } // compute approximate eigensystem eigvec = (double *)malloc(LANCZOS_ITR * LANCZOS_ITR * sizeof(double)); LAPACKE_dstedc(LAPACK_COL_MAJOR, 'I', LANCZOS_ITR, &alpha[1], &beta[1], eigvec, LANCZOS_ITR); // copy specified number of eigenvalues memcpy(Es, &alpha[1], n_eigs * sizeof(double)); // V = Q(:, 1:k) * U cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n_patch, LANCZOS_ITR, LANCZOS_ITR, 1.0, &q[n_patch], n_patch, eigvec, LANCZOS_ITR, 0.0, L, n_patch); // copy the corresponding eigenvectors memcpy(F, L, n_patch * n_eigs * sizeof(double)); free(b); free(z); free(alpha); free(beta); free(q); free(eigvec); } static double norm2(double *v, int length) { int i; double sum = 0.0; for (i = 0; i < length; i++) sum += v[i] * v[i]; return sqrt(sum); } static void divide_copy(double *dest, const double *src, int length, const double divisor) { double factor = 1.0 / divisor; int i; for (i = 0; i < length; i++) dest[i] = src[i] * factor; }
{ "alphanum_fraction": 0.5459877992, "avg_line_length": 33.5590551181, "ext": "c", "hexsha": "7f5086471146faf7540eb1fd6f121b0cb1250d4e", "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": "add646dbf220da2143f289f058abed172ab8a637", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "hcho3/eigenmap_gpu", "max_forks_repo_path": "C_serial/lanczos.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "add646dbf220da2143f289f058abed172ab8a637", "max_issues_repo_issues_event_max_datetime": "2019-08-23T14:56:32.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-30T09:43:40.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "hcho3/eigenmap_gpu", "max_issues_repo_path": "C_serial/lanczos.c", "max_line_length": 76, "max_stars_count": 3, "max_stars_repo_head_hexsha": "add646dbf220da2143f289f058abed172ab8a637", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "hcho3/eigenmap_gpu", "max_stars_repo_path": "C_serial/lanczos.c", "max_stars_repo_stars_event_max_datetime": "2020-12-28T06:20:14.000Z", "max_stars_repo_stars_event_min_datetime": "2015-07-06T03:40:34.000Z", "num_tokens": 1462, "size": 4262 }
/** * * @file testing_dgels.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Bilel Hadri * @author Hatem Ltaief * @date 2010-11-15 * @generated d Tue Jan 7 11:45:18 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_dmain.h" #undef COMPLEX #define REAL enum blas_order_type { blas_rowmajor = 101, blas_colmajor = 102 }; enum blas_uplo_type { blas_upper = 121, blas_lower = 122 }; enum blas_cmach_type { blas_base = 151, blas_t = 152, blas_rnd = 153, blas_ieee = 154, blas_emin = 155, blas_emax = 156, blas_eps = 157, blas_prec = 158, blas_underflow = 159, blas_overflow = 160, blas_sfmin = 161}; enum blas_norm_type { blas_one_norm = 171, blas_real_one_norm = 172, blas_two_norm = 173, blas_frobenius_norm = 174, blas_inf_norm = 175, blas_real_inf_norm = 176, blas_max_norm = 177, blas_real_max_norm = 178 }; static void BLAS_error(char *rname, int err, int val, int x) { fprintf( stderr, "%s %d %d %d\n", rname, err, val, x ); abort(); } static void BLAS_dsy_norm(enum blas_order_type order, enum blas_norm_type norm, enum blas_uplo_type uplo, int n, const double *a, int lda, double *res) { int i, j; double anorm, v; char rname[] = "BLAS_dsy_norm"; if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 ); if (norm == blas_inf_norm) { anorm = 0.0; if (blas_upper == uplo) { for (i = 0; i < n; ++i) { v = 0.0; for (j = 0; j < i; ++j) { v += fabs( a[j + i * lda] ); } for (j = i; j < n; ++j) { v += fabs( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else { BLAS_error( rname, -3, norm, 0 ); return; } } else { BLAS_error( rname, -2, norm, 0 ); return; } if (res) *res = anorm; } static void BLAS_dge_norm(enum blas_order_type order, enum blas_norm_type norm, int m, int n, const double *a, int lda, double *res) { int i, j; float anorm, v; char rname[] = "BLAS_dge_norm"; if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 ); if (norm == blas_frobenius_norm) { anorm = 0.0f; for (j = n; j; --j) { for (i = m; i; --i) { v = a[0]; anorm += v * v; a++; } a += lda - m; } anorm = sqrt( anorm ); } else if (norm == blas_inf_norm) { anorm = 0.0f; for (i = 0; i < m; ++i) { v = 0.0f; for (j = 0; j < n; ++j) { v += fabs( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else { BLAS_error( rname, -2, norm, 0 ); return; } if (res) *res = anorm; } static double BLAS_dpow_di(double x, int n) { double rv = 1.0; if (n < 0) { n = -n; x = 1.0 / x; } for (; n; n >>= 1, x *= x) { if (n & 1) rv *= x; } return rv; } static double BLAS_dfpinfo(enum blas_cmach_type cmach) { double eps = 1.0, r = 1.0, o = 1.0, b = 2.0; int t = 53, l = 1024, m = -1021; char rname[] = "BLAS_dfpinfo"; if ((sizeof eps) == sizeof(float)) { t = 24; l = 128; m = -125; } else { t = 53; l = 1024; m = -1021; } /* for (i = 0; i < t; ++i) eps *= half; */ eps = BLAS_dpow_di( b, -t ); /* for (i = 0; i >= m; --i) r *= half; */ r = BLAS_dpow_di( b, m-1 ); o -= eps; /* for (i = 0; i < l; ++i) o *= b; */ o = (o * BLAS_dpow_di( b, l-1 )) * b; switch (cmach) { case blas_eps: return eps; case blas_sfmin: return r; default: BLAS_error( rname, -1, cmach, 0 ); break; } return 0.0; } static int check_orthogonality(int, int, int, double*, double); static int check_factorization(int, int, double*, double*, int, double*, double); static int check_solution(int, int, int, double*, int, double*, double*, int, double); int testing_dgels(int argc, char **argv) { int mode = 0; if ( argc < 1 ){ goto usage; } else { mode = atoi(argv[0]); } /* Check for number of arguments*/ if ( ((mode == 0) && (argc != 6)) || ((mode != 0) && (argc != 7)) ){ usage: USAGE("GELS", "MODE M N LDA NRHS LDB [RH]", " - MODE : 0: flat, 1: tree (RH needed)\n" " - M : number of rows of the matrix A\n" " - N : number of columns of the matrix A\n" " - LDA : leading dimension of the matrix A\n" " - NRHS : number of RHS\n" " - LDB : leading dimension of the matrix B\n" " - RH : Size of each subdomains\n"); return -1; } int M = atoi(argv[1]); int N = atoi(argv[2]); int LDA = atoi(argv[3]); int NRHS = atoi(argv[4]); int LDB = atoi(argv[5]); int rh; int K = min(M, N); double eps; int info_ortho, info_solution, info_factorization; int i,j; int LDAxN = LDA*N; int LDBxNRHS = LDB*NRHS; double *A1 = (double *)malloc(LDA*N*sizeof(double)); double *A2 = (double *)malloc(LDA*N*sizeof(double)); double *B1 = (double *)malloc(LDB*NRHS*sizeof(double)); double *B2 = (double *)malloc(LDB*NRHS*sizeof(double)); double *Q = (double *)malloc(LDA*N*sizeof(double)); PLASMA_desc *T; /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!B1)||(!B2)||(!Q)){ printf("Out of Memory \n "); return -2; } if ( mode ) { rh = atoi(argv[6]); PLASMA_Set(PLASMA_HOUSEHOLDER_MODE, PLASMA_TREE_HOUSEHOLDER); PLASMA_Set(PLASMA_HOUSEHOLDER_SIZE, rh); } PLASMA_Alloc_Workspace_dgels(M, N, &T); eps = BLAS_dfpinfo( blas_eps ); /*---------------------------------------------------------- * TESTING DGELS */ /* Initialize A1 and A2 */ LAPACKE_dlarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i] ; /* Initialize B1 and B2 */ LAPACKE_dlarnv_work(IONE, ISEED, LDBxNRHS, B1); for (i = 0; i < M; i++) for (j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i] ; memset((void*)Q, 0, LDA*N*sizeof(double)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; /* PLASMA DGELS */ PLASMA_dgels(PlasmaNoTrans, M, N, NRHS, A2, LDA, T, B2, LDB); /* PLASMA DGELS */ if (M >= N) /* Building the economy-size Q */ PLASMA_dorgqr(M, N, K, A2, LDA, T, Q, LDA); else /* Building the economy-size Q */ PLASMA_dorglq(M, N, K, A2, LDA, T, Q, LDA); printf("\n"); printf("------ TESTS FOR PLASMA DGELS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)&(info_ortho == 0)) { printf("***************************************************\n"); printf(" ---- TESTING DGELS ...................... PASSED !\n"); printf("***************************************************\n"); } else { printf("************************************************\n"); printf(" - TESTING DGELS ... FAILED !\n"); printf("************************************************\n"); } /*------------------------------------------------------------- * TESTING DGEQRF + DGEQRS or DGELQF + DGELQS */ /* Initialize A1 and A2 */ LAPACKE_dlarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i]; /* Initialize B1 and B2 */ LAPACKE_dlarnv_work(IONE, ISEED, LDBxNRHS, B1); for (i = 0; i < M; i++) for (j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i]; memset((void*)Q, 0, LDA*N*sizeof(double)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; if (M >= N) { printf("\n"); printf("------ TESTS FOR PLASMA DGEQRF + DGEQRS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Plasma routines */ PLASMA_dgeqrf(M, N, A2, LDA, T); PLASMA_dorgqr(M, N, K, A2, LDA, T, Q, LDA); PLASMA_dgeqrs(M, N, NRHS, A2, LDA, T, B2, LDB); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)&(info_ortho == 0)) { printf("***************************************************\n"); printf(" ---- TESTING DGEQRF + DGEQRS ............ PASSED !\n"); printf("***************************************************\n"); } else{ printf("***************************************************\n"); printf(" - TESTING DGEQRF + DGEQRS ... FAILED !\n"); printf("***************************************************\n"); } } else { printf("\n"); printf("------ TESTS FOR PLASMA DGELQF + DGELQS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Plasma routines */ PLASMA_dgelqf(M, N, A2, LDA, T); PLASMA_dorglq(M, N, K, A2, LDA, T, Q, LDA); PLASMA_dgelqs(M, N, NRHS, A2, LDA, T, B2, LDB); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ( (info_solution == 0) & (info_factorization == 0) & (info_ortho == 0) ) { printf("***************************************************\n"); printf(" ---- TESTING DGELQF + DGELQS ............ PASSED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING DGELQF + DGELQS ... FAILED !\n"); printf("***************************************************\n"); } } /*---------------------------------------------------------- * TESTING DGEQRF + ZORMQR + DTRSM */ /* Initialize A1 and A2 */ LAPACKE_dlarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i]; /* Initialize B1 and B2 */ memset(B2, 0, LDB*NRHS*sizeof(double)); LAPACKE_dlarnv_work(IONE, ISEED, LDBxNRHS, B1); for (i = 0; i < M; i++) for (j = 0; j < NRHS; j++) B2[LDB*j+i] = B1[LDB*j+i]; /* PLASMA DGEQRF+ DORMQR + DTRSM */ memset((void*)Q, 0, LDA*N*sizeof(double)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; if (M >= N) { printf("\n"); printf("------ TESTS FOR PLASMA DGEQRF + DORMQR + DTRSM ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); PLASMA_dgeqrf(M, N, A2, LDA, T); PLASMA_dorgqr(M, N, K, A2, LDA, T, Q, LDA); PLASMA_dormqr(PlasmaLeft, PlasmaTrans, M, NRHS, N, A2, LDA, T, B2, LDB); PLASMA_dtrsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, N, NRHS, 1.0, A2, LDA, B2, LDB); } else { printf("\n"); printf("------ TESTS FOR PLASMA DGELQF + DORMLQ + DTRSM ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); PLASMA_dgelqf(M, N, A2, LDA, T); PLASMA_dtrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaNonUnit, M, NRHS, 1.0, A2, LDA, B2, LDB); PLASMA_dorglq(M, N, K, A2, LDA, T, Q, LDA); PLASMA_dormlq(PlasmaLeft, PlasmaTrans, N, NRHS, M, A2, LDA, T, B2, LDB); } /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q, eps); info_factorization = check_factorization(M, N, A1, A2, LDA, Q, eps); info_solution = check_solution(M, N, NRHS, A1, LDA, B1, B2, LDB, eps); if ( (info_solution == 0) & (info_factorization == 0) & (info_ortho == 0) ) { if (M >= N) { printf("***************************************************\n"); printf(" ---- TESTING DGEQRF + DORMQR + DTRSM .... PASSED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" ---- TESTING DGELQF + DTRSM + DORMLQ .... PASSED !\n"); printf("***************************************************\n"); } } else { if (M >= N) { printf("***************************************************\n"); printf(" - TESTING DGEQRF + DORMQR + DTRSM ... FAILED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING DGELQF + DTRSM + DORMLQ ... FAILED !\n"); printf("***************************************************\n"); } } free(A1); free(A2); free(B1); free(B2); free(Q); PLASMA_Dealloc_Handle_Tile( &T ); return 0; } /*------------------------------------------------------------------- * Check the orthogonality of Q */ static int check_orthogonality(int M, int N, int LDQ, double *Q, double eps) { double alpha, beta; double normQ; int info_ortho; int i; int minMN = min(M, N); double *work = (double *)malloc(minMN*sizeof(double)); alpha = 1.0; beta = -1.0; /* Build the idendity matrix USE DLASET?*/ double *Id = (double *) malloc(minMN*minMN*sizeof(double)); memset((void*)Id, 0, minMN*minMN*sizeof(double)); for (i = 0; i < minMN; i++) Id[i*minMN+i] = (double)1.0; /* Perform Id - Q'Q */ if (M >= N) cblas_dsyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, alpha, Q, LDQ, beta, Id, N); else cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M); BLAS_dsy_norm( blas_colmajor, blas_inf_norm, blas_upper, minMN, Id, minMN, &normQ ); printf("============\n"); printf("Checking the orthogonality of Q \n"); printf("||Id-Q'*Q||_oo / (N*eps) = %e \n", normQ/(minMN*eps)); if ( isnan(normQ / (minMN * eps)) || isinf(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 60.0) ) { printf("-- Orthogonality is suspicious ! \n"); info_ortho=1; } else { printf("-- Orthogonality is CORRECT ! \n"); info_ortho=0; } free(work); free(Id); return info_ortho; } /*------------------------------------------------------------ * Check the factorization QR */ static int check_factorization(int M, int N, double *A1, double *A2, int LDA, double *Q, double eps ) { double Anorm, Rnorm; double alpha, beta; int info_factorization; int i,j; double *Ql = (double *)malloc(M*N*sizeof(double)); double *Residual = (double *)malloc(M*N*sizeof(double)); double *work = (double *)malloc(max(M,N)*sizeof(double)); alpha=1.0; beta=0.0; if (M >= N) { /* Extract the R */ double *R = (double *)malloc(N*N*sizeof(double)); memset((void*)R, 0, N*N*sizeof(double)); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N); /* Perform Ql=Q*R */ memset((void*)Ql, 0, M*N*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, (alpha), Q, LDA, R, N, (beta), Ql, M); free(R); } else { /* Extract the L */ double *L = (double *)malloc(M*M*sizeof(double)); memset((void*)L, 0, M*M*sizeof(double)); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M); /* Perform Ql=LQ */ memset((void*)Ql, 0, M*N*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, (alpha), L, M, Q, LDA, (beta), Ql, M); free(L); } /* Compute the Residual */ for (i = 0; i < M; i++) for (j = 0 ; j < N; j++) Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i]; BLAS_dge_norm( blas_colmajor, blas_inf_norm, M, N, Residual, M, &Rnorm ); BLAS_dge_norm( blas_colmajor, blas_inf_norm, M, N, A2, LDA, &Anorm ); if (M >= N) { printf("============\n"); printf("Checking the QR Factorization \n"); printf("-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } else { printf("============\n"); printf("Checking the LQ Factorization \n"); printf("-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } if (isnan(Rnorm / (Anorm * N *eps)) || isinf(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 60.0) ) { printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else { printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(work); free(Ql); free(Residual); return info_factorization; } /*-------------------------------------------------------------- * Check the solution */ static int check_solution(int M, int N, int NRHS, double *A, int LDA, double *B, double *X, int LDB, double eps) { int info_solution; double Rnorm, Anorm, Xnorm, Bnorm; double zone, mzone, zzero; double result; double *work = (double *)malloc(max(M, N)* sizeof(double)); zone = 1.0; mzone = -1.0; zzero = 0.0; BLAS_dge_norm( blas_colmajor, blas_inf_norm, M, N, A, LDA, &Anorm ); BLAS_dge_norm( blas_colmajor, blas_inf_norm, M, NRHS, B, LDB, &Bnorm ); BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, NRHS, X, LDB, &Xnorm ); /* Compute Ax - b */ cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, (zone), A, LDA, X, LDB, (mzone), B, LDB); /* Compute A' * (Ax - b) */ cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, N, NRHS, M, (zone), A, LDA, B, LDB, (zzero), X, LDB); BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, NRHS, X, LDB, &Rnorm ); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_oo=%f\n||X||_oo=%f\n||B||_oo=%f\n||A X - B||_oo=%e\n", Anorm, Xnorm, Bnorm, Rnorm ); result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n", result); if ( isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } free(work); return info_solution; }
{ "alphanum_fraction": 0.4888899373, "avg_line_length": 32.2633181126, "ext": "c", "hexsha": "1fc930995b3b165d7398944f9424d4a18a015ff5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_dgels.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_dgels.c", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_dgels.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6667, "size": 21197 }
// Ref: // G.P. Lepage, LQCD for Novices #include "su3_utils.c" #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_fit.h> // globals const gsl_rng_type *T; gsl_rng *r; // random generator su3_matrix links[4*N*N*N*N]; // link variables su3_matrix rands[50]; // random unitary matrices FILE *output; // prototypes void setup(); void cleanup(); int main (int argc, char** argv) { setup(); int O[4]={0,0,0,0}; for(int n=0;n<Ntherm;n++) { //fprintf(output, "%f \n",plaquette(links,0,1,O)); hb_update(links,r,rands); //thermalize } // Confinement phase should have small Polyakov VEV if(confined){ while(polyakov_mean(links) > pol_thres){ hb_update(links,r,rands); //thermalize } } printf("Thermalized! \n"); for(int n=0;n<Ncf;n++){ // Decorrelate for(int k=0;k<Ncor;k++){ hb_update(links,r,rands); } if(n%5==0){printf("%d \n",n);} // Measurement //fprintf(output, "%f %f \n", wloop_mean(1,1,links),wloop_mean(1,2,links)); //fprintf(output, "%f %f %f %f %f %f %f %f\n",twloop2_mean(1,links),twloop2_mean(2,links),twloop2_mean(3,links),twloop2_mean(4,links),twloop2_mean(5,links),twloop2_mean(6,links),twloop2_mean(7,links),twloop2_mean(8,links)); //fprintf(output, "%f %f %f %f %f %f %f %f\n",plaq_corr(1,links),plaq_corr(2,links),plaq_corr(3,links),plaq_corr(4,links),plaq_corr(5,links),plaq_corr(6,links),plaq_corr(7,links),plaq_corr(8,links)); //printf("%f \n",polyakov_mean(links)); printf( "%f \n", plaq_mean_s(0,links)); printf( "%f %f \n", wloop_mean(1,1,links),wloop_mean(1,2,links) ); } printf("acc=%f\n", (double)acc/tot); cleanup(); return 0; } void setup (){ acc=0; tot=0; // ready random num generator gsl_rng_env_setup (); T = gsl_rng_mt19937; r = gsl_rng_alloc (T); // fill in table of rand matrices for(int i=0;i<25;i++){ rands[2*i]=su3_rand(r); rands[2*i+1]=su3_inv(rands[2*i]); } //init links to identities for(int i=0;i<4*N*N*N*N;i++){ links[i]=su3_unit(); } output = fopen("out.txt", "w+"); } void cleanup (){ gsl_rng_free(r); fclose(output); }
{ "alphanum_fraction": 0.627534182, "avg_line_length": 23.5666666667, "ext": "c", "hexsha": "39252f3492e66d654cda74d07dd7e14ce304dde4", "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": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "uchuutamashi/lqcd", "max_forks_repo_path": "su3/su3_gauge_hb.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "uchuutamashi/lqcd", "max_issues_repo_path": "su3/su3_gauge_hb.c", "max_line_length": 227, "max_stars_count": null, "max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "uchuutamashi/lqcd", "max_stars_repo_path": "su3/su3_gauge_hb.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 753, "size": 2121 }
/* * library_def.h * * Created on: 2019. 9. 3. * Author: Misun Yu, Dongsik Choi */ #ifndef LIBRARY_H_ #define LIBRARY_H_ //#define _DEBUG //#define THREAD_MATMUL //#define _USE_OPENBLAS_MATMUL //#define _USE_OPENBLAS_CONV //#define _CONV_ORIGINAL //#define _CONV_GROUP_ORIGINAL //#define _USE_LLVM 1 #ifdef __MACH__ #include <stdlib.h> #else #include <malloc.h> #endif #include <vector> #include <string.h> #include <math.h> #include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <iostream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> //#include <omp.h> #include <time.h> #include <assert.h> #ifdef _USE_OPENBLAS_MATMUL #include <cblas.h> #else #ifdef _USE_OPENBLAS_CONV #include <cblas.h> #else #endif #endif #ifdef __MACH__ #include <dispatch/dispatch.h> #else #include <semaphore.h> #endif using namespace std; //#define FLOAT 0 //#define DOUBLE 1 //#define INT 2 //#define CHAR 3 typedef int8_t i8; typedef uint8_t ui8; typedef int16_t i16; typedef int32_t i32; #if defined(__MACH__) || defined(_USE_LLVM) #define MAX_PAD_SIZE 3 //msyu #endif using namespace std; void read_vector(vector<size_t>* vec, ifstream* readFileBin); /* * * * Batch Normalization * * */ template <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, typename T2> void splat(T1 (&in1)[N1][N2][N3][N4], int axis, T2 (&result)[N1][N2][N3][N4]) { #ifdef _DEBUG cout << "splat()-4D" << endl; #endif // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } template <typename T1, size_t K1, size_t L1, size_t M1, size_t N1, typename T2, size_t K2, size_t L2, size_t M2, size_t N2, typename T3, size_t K3, size_t L3, size_t M3, size_t N3> void concat(int axis, T1 (&in1)[N1][M1][K1][L1], T2 (&in2)[N2][M2][K2][L2], T3 (&result)[N3][M3][K3][L3]) { #ifdef _DEBUG cout << "concat()-4D" << endl; cout << "axis: " << axis << endl; #endif if(axis == 3) { for(size_t i = 0; i < N3; i++) { for(size_t j = 0; j < M3; j++) { for(size_t k = 0; k < K3; k++) { for(size_t l = 0; l < L3; l++) { if(l < L1) { result[i][j][k][l] = in1[i][j][k][l]; } else { result[i][j][k][l] = in2[i][j][k][l-L1]; } } } } } } else { cout << "Not supported. " << axis << endl; } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } template <typename T1, size_t N, size_t M, size_t K, size_t L> void batchNorm(T1 (&in)[N][M][K][L], T1 (&scale)[M], T1 (&bias)[M], T1 (&mean)[M], T1 (&var)[M], unsigned int channelIdx, T1 epsilon, T1 momentum, T1 (&result)[N][M][K][L]) { //NCHW // #ifdef _DEBUG cout << "batchNorm() - 1" << endl; cout << "channel: " << channelIdx << endl; cout << "N: " << N << endl; cout << "M: " << M << endl; cout << "K: " << K << endl; cout << "L: " << L << endl; #endif for(size_t i = 0; i < N; i++) { for(size_t j = 0; j < M; j++) { for(size_t k = 0; k < K; k++) { for(size_t l = 0; l < L; l++) { float norm = (in[i][j][k][l] - mean[j])/sqrtf(epsilon + var[j]); result[i][j][k][l] = scale[j]* norm + bias[j]; } } } } } template <typename T1, size_t N, size_t M, size_t K, size_t L> void batchNorm(T1 (&in)[N][L][K][M], T1 (&scale)[M], T1 (&bias)[M], T1 (&mean)[M], T1 (&var)[M], unsigned int channelIdx, T1 epsilon, T1 momentum, T1 (&result)[N][L][K][M]) { //NCHW // #ifdef _DEBUG cout << "batchNorm() - 2" << endl; cout << "channel: " << channelIdx << endl; cout << "N: " << N << endl; cout << "L: " << L << endl; cout << "K: " << K << endl; cout << "M: " << M << endl; #endif for(size_t i = 0; i < N; i++) { for(size_t j = 0; j < L; j++) { for(size_t k = 0; k < K; k++) { for(size_t l = 0; l < M; l++) { float norm = (in[i][j][k][l] - mean[l])/sqrtf(epsilon + var[l]); result[i][j][k][l] = scale[l]* norm + bias[l]; } } } } } /* * * * Convolution * * */ extern int conv_idx; #ifdef _CONV_ORIGINAL template <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL, typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL, typename T3, size_t N2, typename T4, size_t N3, size_t M3, size_t K3, size_t L3> void conv(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> filter_dim, T3 (&bias)[N2], \ vector<size_t> stride, vector<size_t> pad, int group, T4 (&result)[N3][M3][K3][L3]) { #ifdef _DEBUG cout << conv_idx++ << ": conv()-original" << endl; cout << "BATCH: " << BATCH << endl; cout << "HEIGHT: " << HEIGHT << endl; cout << "WIDTH: " << WIDTH << endl; cout << "CHANNEL: " << CHANNEL << endl; cout << "pad: " << pad.at(0) << endl; cout << "stride: " << stride.at(0) << endl; cout << "FILTER_HEIGHT: " << FILTER_HEIGHT << endl; cout << "FILTER_WIDTH: " << FILTER_WIDTH << endl; cout << "FILTER_CHANNEL: " << FILTER_CHANNEL << endl; //N, H, W, C //N == 1 //group == 1 #endif int pad_xleft = pad.at(0); int pad_xright = pad.at(1); int pad_ytop = pad.at(2); int pad_ybottom = pad.at(3); int xadd = pad_xleft + pad_xright; int yadd = pad_ytop + pad_ybottom; int stride_size = stride.at(0); int filter_h = filter_dim.at(1); int filter_w = filter_dim.at(2); int filter_size = filter_dim.at(0); int out_h = (HEIGHT + yadd - filter_h)/stride_size + 1; int out_w = (WIDTH + xadd - filter_w)/stride_size + 1; #ifdef _DEBUG cout << "FILTER_SIZE: " << FILTER_SIZE << endl; cout << "out_h: " << out_h << endl; cout << "out_w: " << out_w << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif #if defined(__MACH__) || defined(_USE_LLVM) float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); #else float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); #endif for (int b = 0; b < BATCH; b++){ for (size_t c = 0; c < CHANNEL; c++){ for (int h = 0; h < HEIGHT; h++){ for (int w = 0; w < WIDTH; w++){ (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c]; } } } } int new_h_idx = 0, new_w_idx = 0; for (int b = 0; b < BATCH; b++){ for(int fc = 0; fc < filter_size; fc++) { for(int i = 0; i <out_h; i++) { for(int j = 0; j <out_w; j++) { float total = 0.0; for(int fh = 0; fh <filter_h; fh++) { for(int fw = 0; fw <filter_w; fw++) { for(size_t f = 0; f < CHANNEL; f++) { total = total + (*newin)[b][new_h_idx+fh][new_w_idx+fw][f]*filter[fc][fh][fw][f]; } } } result[b][i][j][fc] = total + bias[fc]; new_w_idx += stride_size; } new_h_idx += stride_size; new_w_idx = 0; } new_h_idx = 0; } } #ifdef _DEBUG free(newin); clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== " + to_string(conv_idx++) + " convolution time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } #else #ifdef __MACH__ extern dispatch_semaphore_t semaphore; #else extern sem_t semaphore; #endif // 스레드 수 정의 #define MAX_THREAD 2 //스레드를 사용하기 위한 구조체. template <typename T1, typename T2, typename T3, int tN, int tM, int tM1> struct tTHREAD{ T1(*arrr)[tM]; T2(*brrr1)[tM][tM1]; T3(*crrr1)[tN][tM1]; int b; int cnt; }; // 스레드 함수 template <typename T1, typename T2, typename T3, int tN, int tM, int tM1> void *multi(void *num) { struct tTHREAD<float, float, float, tN, tM, tM1> *numMul = (struct tTHREAD<float, float, float, tN, tM, tM1> *)num; // cnt는 현재 사용되려는 스레드 번호. int core = numMul->cnt; int B = numMul->b; int mN = tN / MAX_THREAD * (core + 1); if (core == MAX_THREAD - 1) mN = tN; for (int i = core * (tN / MAX_THREAD); i < mN; i++) {// 각 스레드는 행렬 행 기준으로 스레드 개수만큼 나눠서 연산 for (int k = 0; k < tM; k++) { for (int j = 0; j < tM1; j++) { numMul->crrr1[B][i][j] += numMul->arrr[i][k] * numMul->brrr1[B][k][j]; } } } #ifdef __MACH__ dispatch_semaphore_signal(semaphore); #else sem_post(&semaphore); #endif return nullptr; } #ifdef _CONV_GROUP_ORIGINAL template <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL, typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL, typename T3, size_t N2, typename T4, size_t N3, size_t M3, size_t K3, size_t L3> void conv_group(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> kernel_dim, T3 (&bias)[N2], \ vector<size_t> stride, vector<size_t> pad, int group, T4 (&result)[N3][M3][K3][L3]) { #ifdef _DEBUG cout << "conv_group()-original" << endl; cout << "BATCH: " << BATCH << endl; cout << "HEIGHT: " << HEIGHT << endl; cout << "WIDTH: " << WIDTH << endl; cout << "CHANNEL: " << CHANNEL << endl; cout << "pad: " << pad.at(0) << endl; cout << "stride: " << stride.at(0) << endl; cout << "FILTER_SIZE: " << FILTER_SIZE << endl; cout << "FILTER_HEIGHT: " << FILTER_HEIGHT << endl; cout << "FILTER_WIDTH: " << FILTER_WIDTH << endl; cout << "FILTER_CHANNEL: " << FILTER_CHANNEL << endl; cout << "OUT BATCH: " << N3 << endl; cout << "OUT HEIGHT: " << M3 << endl; cout << "OUT WIDTH: " << K3 << endl; cout << "OUT CHANNEL: " << L3 << endl; cout << "group: " << group << endl; //N, H, W, C //N == 1 //group == 1 #endif int pad_xleft = pad.at(0); int pad_xright = pad.at(1); int pad_ytop = pad.at(2); int pad_ybottom = pad.at(3); int xadd = pad_xleft + pad_xright; int yadd = pad_ytop + pad_ybottom; int stride_size = stride.at(0); int kernel_h = kernel_dim.at(1); int kernel_w = kernel_dim.at(2); int kernel_size = kernel_dim.at(0); int out_h = (HEIGHT + yadd - kernel_h)/stride_size + 1; int out_w = (WIDTH + xadd - kernel_w)/stride_size + 1; #ifdef _DEBUG cout << "FILTER_SIZE: " << FILTER_SIZE << endl; cout << "out_h: " << out_h << endl; cout << "out_w: " << out_w << endl; cout << "kernel_h: " << kernel_h << endl; cout << "kernel_w: " << kernel_w << endl; cout << "kernel_size: " << kernel_size << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif #if defined(__MACH__) || defined(_USE_LLVM) float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); #else float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); #endif for (int b = 0; b < BATCH; b++){ for (size_t c = 0; c < CHANNEL; c++){ for (int h = 0; h < HEIGHT; h++){ for (int w = 0; w < WIDTH; w++){ (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c]; } } } } int splitKernelSize = kernel_size/group; int new_h_idx = 0, new_w_idx = 0; for (int b = 0; b < BATCH; b++) { for(int g = 0; g < group; g++) { for (int fc = 0; fc < splitKernelSize; fc++) { for (int i = 0; i < out_h; i++) { for (int j = 0; j < out_w; j++) { float total = 0.0; for (int fh = 0; fh < kernel_h; fh++) { for (int fw = 0; fw < kernel_w; fw++) { for (size_t f = 0; f < FILTER_CHANNEL; f++) { total = total + (*newin)[b][new_h_idx + fh][new_w_idx + fw][g*FILTER_CHANNEL + f] * filter[g*splitKernelSize + fc][fh][fw][f]; } } } result[b][i][j][g*splitKernelSize + fc] = total + bias[g*splitKernelSize + fc]; new_w_idx += stride_size; } new_h_idx += stride_size; new_w_idx = 0; } new_h_idx = 0; } } } #ifdef _DEBUG free(newin); clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== " + to_string(conv_idx++) + " convolution time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } #else // //convolution image to columns template <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL, typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL, typename T3, size_t N2, typename T4, size_t N3, size_t M3, size_t K3, size_t L3> void conv_group(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> filter_dim, T3 (&bias)[N2], \ vector<size_t> stride, vector<size_t> pad, size_t group, T4 (&result)[N3][M3][K3][L3]) { // cout << "-- conv() group: " << group << endl; #ifdef _DEBUG cout << "-- conv() -- " << endl; cout << "BATCH: " << BATCH << endl; cout << "HEIGHT: " << HEIGHT << endl; cout << "WIDTH: " << WIDTH << endl; cout << "CHANNEL: " << CHANNEL << endl; cout << "pad: " << pad.at(0) << endl; cout << "stride: " << stride.at(0) << endl; cout << "FILTER_HEIGHT: " << FILTER_HEIGHT << endl; cout << "FILTER_WIDTH: " << FILTER_WIDTH << endl; cout << "FILTER_CHANNEL: " << FILTER_CHANNEL << endl; cout << "BIAS LEN: " << N2 << endl; #endif int pad_xleft = pad.at(0); int pad_xright = pad.at(1); int pad_ytop = pad.at(2); int pad_ybottom = pad.at(3); int xadd = pad_xleft + pad_xright; int yadd = pad_ytop + pad_ybottom; int stride_size = stride.at(0); int out_h = (HEIGHT + yadd - FILTER_HEIGHT)/stride_size + 1; int out_w = (WIDTH + xadd - FILTER_WIDTH)/stride_size + 1; #ifdef _DEBUG cout << "FILTER_SIZE: " << FILTER_SIZE << endl; cout << "out_h: " << out_h << endl; cout << "out_w: " << out_w << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif #if defined(__MACH__) || defined(_USE_LLVM) float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); #else float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); #endif //step 1. 패딩 //int jp, kp; //printf("패딩 변환 중\n"); for (int b = 0; b < BATCH; b++){ for (int h = 0; h < HEIGHT; h++){ for (int w = 0; w < WIDTH; w++){ for (size_t c = 0; c < CHANNEL; c++){ (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c]; } } } } //step 2. 입력값 차원 변환 //printf("입력값 차원 변환 중 \n"); float (*newin2)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3]; newin2 = (float(*)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3])malloc(sizeof(float[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3])); //하나의 스트라이트에 각 채널들을 하나의 행으로 구성 for (int b = 0, p = 0; b < BATCH; b++, p = 0) for (int i = 0; i < out_h; i++) for (int j = 0, q = 0; j < out_w; j++, q = 0, p++) for (int c = 0; c < CHANNEL; c++) for (int ii = i * stride_size; ii < i * stride_size + FILTER_HEIGHT; ii++) for (int jj = j * stride_size; jj < j * stride_size + FILTER_WIDTH; jj++) (*newin2)[b][q++][p] = (*newin)[b][ii][jj][c]; free(newin); // step 3. 필터 평활화 //printf("필터 평활화 중\n"); float (*transFilter)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL]; //패딩 배열 transFilter = (float(*)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL])malloc(sizeof(float[FILTER_SIZE][FILTER_WIDTH*FILTER_HEIGHT*FILTER_CHANNEL])); memset(transFilter, 0x00, sizeof(float[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL])); for (int i1 = 0, q = 0; i1 < FILTER_SIZE; i1++, q = 0) for (int i2 = 0; i2 < FILTER_CHANNEL; i2++) for (int i3 = 0; i3 < FILTER_HEIGHT; i3++) for (int i4 = 0; i4 < FILTER_WIDTH; i4++) (*transFilter)[i1][q++] = filter[i1][i3][i4][i2]; // step 4. 행렬 곱. float (*finalResult)[BATCH][FILTER_SIZE][M3*K3]; finalResult = (float (*)[BATCH][FILTER_SIZE][M3*K3])malloc(sizeof(float[BATCH][FILTER_SIZE][M3*K3])); memset(finalResult, 0x00, sizeof(float[BATCH][FILTER_SIZE][M3*K3])); int div = out_h * out_w; // B * out_h * out_w //int total2 = BATCH * CHANNEL * FILTER_HEIGHT * FILTER_WIDTH * out_h * out_w; int total2 = BATCH * FILTER_CHANNEL * FILTER_HEIGHT * FILTER_WIDTH * out_h * out_w; int total3 = total2 / div; //printf("행렬 곱 중\n"); #ifdef _USE_OPENBLAS_CONV size_t m1len = FILTER_SIZE*total3, m2len = total3*div, m3len = FILTER_SIZE*div; float *m1, *m2, *m3; m1 = (float *)malloc(sizeof(float)*m1len); m2 = (float *)malloc(sizeof(float)*m2len); m3 = (float *)malloc(sizeof(float)*m3len); for (int b = 0; b < BATCH; b++) { for (int i = 0; i < m1len; i++) { m1[i] = (*transFilter)[i/total3][i % total3]; } for (int i = 0; i < m2len; i++) { m2[i] = (*newin2)[b][i/div][i % div]; } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, FILTER_SIZE, div, total3, 1.0, m1, total3, m2, div, 0.0, m3, div); for (int i = 0; i < m3len; i++) { (*finalResult)[b][i/div][i % div] = m3[i]; } } free(m1); free(m2); free(m3); #else #ifdef THREAD_MATMUL //printf("행렬 곱 중\n"); struct tTHREAD<float,float,float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3> p; // 스레드에 연산할 메모리 복사 pthread_t threads[MAX_THREAD]; p.arrr = (*transFilter); p.brrr1 =(*newin2); p.crrr1 =(*finalResult); #ifdef __MACH__ semaphore = dispatch_semaphore_create(1); #else sem_init(&semaphore, 0, 1); #endif for(int b = 0; b < BATCH; b++){ for (int i = 0; i < MAX_THREAD; i++) { #ifdef __MACH__ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); #else //sem_wait(&semaphore); int r; do { r = sem_wait(&semaphore); } while (r == -1 && errno == EINTR); #endif p.cnt = i; p.b = b; // 배치 값 pthread_create(&threads[i], NULL, multi<float, float, float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3>, (void *)&p); // filter_size, total3, div } for (int t = 0; t < MAX_THREAD; t++) pthread_join(threads[t], NULL); // 모든 스레드가 끝날 때까지 결합 및 대기 } #ifdef __MACH__ dispatch_release(semaphore); #else // sem_distroy(&semaphore); #endif #else //total3: BATCH * FILTER_CHANNEL * FILTER_HEIGHT * FILTER_WIDTH //div: out_w * out_h int splitedKernelSize = FILTER_SIZE/group; // k for문과 j for 문을 변경함으로써, 지역성 향상. for (int b = 0; b < BATCH; b++) { for (int i = 0; i < splitedKernelSize; i++) { for(int g = 0; g < group; g++) { for (int k = 0; k < total3; k++) { for (int j = 0; j < div; j++) { (*finalResult)[b][g*splitedKernelSize + i][j] += (*transFilter)[g*splitedKernelSize + i][k] * (*newin2)[b][g*FILTER_CHANNEL*FILTER_WIDTH*FILTER_HEIGHT + k][j]; } } } } } #endif #endif // step 5. 결과 차원 변환및 편향 합 //printf("마지막 차원 변환 중\n"); //int putout_c = (FILTER_SIZE) / (BATCH); for (int i1 = 0; i1 < BATCH; i1++) { for(int g = 0; g < group; g++) { for (int i4 = 0; i4 < splitedKernelSize; i4++) { size_t q = 0; for (int i2 = 0; i2 < out_h; i2++) { for (int i3 = 0; i3 < out_w; i3++) { result[i1][i2][i3][g*splitedKernelSize + i4] = (*finalResult)[i1][g*splitedKernelSize + i4][q++] + bias[g*splitedKernelSize + i4]; } } //cout << (float)bias[i4] << "\t" << endl; } } } free(newin2); free(transFilter); free(finalResult); #ifdef _DEBUG clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== " + to_string(conv_idx++) + " convolution time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } #endif // //convolution image to columns template <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL, typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL, typename T3, size_t N2, typename T4, size_t N3, size_t M3, size_t K3, size_t L3> void conv(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> filter_dim, T3 (&bias)[N2], \ vector<size_t> stride, vector<size_t> pad, size_t group, T4 (&result)[N3][M3][K3][L3]) { cout << "-- conv() group: " << group << endl; #ifdef _DEBUG cout << "-- conv() -- " << endl; cout << "BATCH: " << BATCH << endl; cout << "HEIGHT: " << HEIGHT << endl; cout << "WIDTH: " << WIDTH << endl; cout << "CHANNEL: " << CHANNEL << endl; cout << "pad: " << pad.at(0) << endl; cout << "stride: " << stride.at(0) << endl; cout << "FILTER_HEIGHT: " << FILTER_HEIGHT << endl; cout << "FILTER_WIDTH: " << FILTER_WIDTH << endl; cout << "FILTER_CHANNEL: " << FILTER_CHANNEL << endl; cout << "BIAS LEN: " << N2 << endl; #endif int pad_xleft = pad.at(0); int pad_xright = pad.at(1); int pad_ytop = pad.at(2); int pad_ybottom = pad.at(3); int xadd = pad_xleft + pad_xright; int yadd = pad_ytop + pad_ybottom; int stride_size = stride.at(0); int out_h = (HEIGHT + yadd - FILTER_HEIGHT)/stride_size + 1; int out_w = (WIDTH + xadd - FILTER_WIDTH)/stride_size + 1; #ifdef _DEBUG cout << "FILTER_SIZE: " << FILTER_SIZE << endl; cout << "out_h: " << out_h << endl; cout << "out_w: " << out_w << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif #if defined(__MACH__) || defined(_USE_LLVM) float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); #else float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); #endif //step 1. 패딩 //int jp, kp; //printf("패딩 변환 중\n"); for (int b = 0; b < BATCH; b++){ for (int h = 0; h < HEIGHT; h++){ for (int w = 0; w < WIDTH; w++){ for (size_t c = 0; c < CHANNEL; c++){ (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c]; } } } } //step 2. 입력값 차원 변환 //printf("입력값 차원 변환 중 \n"); float (*newin2)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3]; newin2 = (float(*)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3])malloc(sizeof(float[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3])); //하나의 스트라이트에 각 채널들을 하나의 행으로 구성 for (int b = 0, p = 0; b < BATCH; b++, p = 0) for (int i = 0; i < out_h; i++) for (int j = 0, q = 0; j < out_w; j++, q = 0, p++) for (int c = 0; c < CHANNEL; c++) for (int ii = i * stride_size; ii < i * stride_size + FILTER_HEIGHT; ii++) for (int jj = j * stride_size; jj < j * stride_size + FILTER_WIDTH; jj++) (*newin2)[b][q++][p] = (*newin)[b][ii][jj][c]; free(newin); // step 3. 필터 평활화 //printf("필터 평활화 중\n"); float (*transFilter)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL]; //패딩 배열 transFilter = (float(*)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL])malloc(sizeof(float[FILTER_SIZE][FILTER_WIDTH*FILTER_HEIGHT*FILTER_CHANNEL])); memset(transFilter, 0x00, sizeof(float[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL])); for (int i1 = 0, q = 0; i1 < FILTER_SIZE; i1++, q = 0) for (int i2 = 0; i2 < FILTER_CHANNEL; i2++) for (int i3 = 0; i3 < FILTER_HEIGHT; i3++) for (int i4 = 0; i4 < FILTER_WIDTH; i4++) (*transFilter)[i1][q++] = filter[i1][i3][i4][i2]; // step 4. 행렬 곱. float (*finalResult)[BATCH][FILTER_SIZE][M3*K3]; finalResult = (float (*)[BATCH][FILTER_SIZE][M3*K3])malloc(sizeof(float[BATCH][FILTER_SIZE][M3*K3])); memset(finalResult, 0x00, sizeof(float[BATCH][FILTER_SIZE][M3*K3])); int div = out_h * out_w; // B * out_h * out_w int total2 = BATCH * CHANNEL * FILTER_HEIGHT * FILTER_WIDTH * out_h * out_w; int total3 = total2 / div; //printf("행렬 곱 중\n"); #ifdef _USE_OPENBLAS_CONV size_t m1len = FILTER_SIZE*total3, m2len = total3*div, m3len = FILTER_SIZE*div; float *m1, *m2, *m3; m1 = (float *)malloc(sizeof(float)*m1len); m2 = (float *)malloc(sizeof(float)*m2len); m3 = (float *)malloc(sizeof(float)*m3len); for (int b = 0; b < BATCH; b++) { for (int i = 0; i < m1len; i++) { m1[i] = (*transFilter)[i/total3][i % total3]; } for (int i = 0; i < m2len; i++) { m2[i] = (*newin2)[b][i/div][i % div]; } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, FILTER_SIZE, div, total3, 1.0, m1, total3, m2, div, 0.0, m3, div); for (int i = 0; i < m3len; i++) { (*finalResult)[b][i/div][i % div] = m3[i]; } } free(m1); free(m2); free(m3); #else #ifdef THREAD_MATMUL //printf("행렬 곱 중\n"); struct tTHREAD<float,float,float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3> p; // 스레드에 연산할 메모리 복사 pthread_t threads[MAX_THREAD]; p.arrr = (*transFilter); p.brrr1 =(*newin2); p.crrr1 =(*finalResult); #ifdef __MACH__ semaphore = dispatch_semaphore_create(1); #else sem_init(&semaphore, 0, 1); #endif for(int b = 0; b < BATCH; b++){ for (int i = 0; i < MAX_THREAD; i++) { #ifdef __MACH__ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); #else //sem_wait(&semaphore); int r; do { r = sem_wait(&semaphore); } while (r == -1 && errno == EINTR); #endif p.cnt = i; p.b = b; // 배치 값 pthread_create(&threads[i], NULL, multi<float, float, float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3>, (void *)&p); // filter_size, total3, div } for (int t = 0; t < MAX_THREAD; t++) pthread_join(threads[t], NULL); // 모든 스레드가 끝날 때까지 결합 및 대기 } #ifdef __MACH__ dispatch_release(semaphore); #else // sem_distroy(&semaphore); #endif #else // k for문과 j for 문을 변경함으로써, 지역성 향상. for (int b = 0; b < BATCH; b++) { for (int i = 0; i < FILTER_SIZE; i++) { for (int k = 0; k < total3; k++) { for (int j = 0; j < div; j++) { (*finalResult)[b][i][j] += (*transFilter)[i][k] * (*newin2)[b][k][j]; } } } } #endif #endif // step 5. 결과 차원 변환및 편향 합 //printf("마지막 차원 변환 중\n"); //int putout_c = (FILTER_SIZE) / (BATCH); for (int i1 = 0; i1 < BATCH; i1++) { for (int i4 = 0; i4 < FILTER_SIZE; i4++) { size_t q = 0; for (int i2 = 0; i2 < out_h; i2++) { for (int i3 = 0; i3 < out_w; i3++) { result[i1][i2][i3][i4] = (*finalResult)[i1][i4][q++] + bias[i4]; } } //cout << (float)bias[i4] << "\t" << endl; } } free(newin2); free(transFilter); free(finalResult); #ifdef _DEBUG clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== " + to_string(conv_idx++) + " convolution time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } #endif /* * * * Average Pooling * * */ template <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL, typename T2, size_t N2, size_t M2, size_t K2, size_t L2> void avgpool(T1 (&in)[BATCH][HEIGHT][WIDTH][CHANNEL], vector<size_t> windows_dim, vector<size_t> stride, vector<size_t> pad, T2 (&result)[N2][M2][K2][L2]) { // time_t istart,iend; // time (&istart); //N, H, W, C //N == 1 //group == 1 int pad_xleft = pad.at(0); int pad_xright = pad.at(1); int pad_ytop = pad.at(2); int pad_ybottom = pad.at(3); int xadd = pad_xleft + pad_xright; int yadd = pad_ytop + pad_ybottom; int stride_size = stride.at(0); int window_h = windows_dim.at(0); int window_w = windows_dim.at(1); int out_h = (HEIGHT + yadd - window_h)/stride_size + 1; int out_w = (WIDTH + xadd - window_w)/stride_size + 1; const int new_height = HEIGHT + pad.at(0) + pad.at(1); const int new_width = WIDTH + pad.at(2) + pad.at(3); #ifdef _DEBUG cout << "avgpool()" <<endl; // cout << "BATCH: " << BATCH << endl; // cout << "HEIGHT: " << HEIGHT << endl; // cout << "WIDTH: " << WIDTH << endl; // cout << "CHANNEL: " << CHANNEL << endl; // cout << "pad: " << pad.at(0) << endl; // cout << "stride: " << stride.at(0) << endl; // cout << "WINDOW_HEIGHT: " << window_h << endl; // cout << "WINDOW_WIDTH: " << window_w << endl; #endif #if defined(__MACH__) || defined(_USE_LLVM) float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); #else float (*newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); #endif // float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE][WIDTH+MAX_PAD_SIZE][CHANNEL]; // newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE][WIDTH+MAX_PAD_SIZE][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE][WIDTH+MAX_PAD_SIZE][CHANNEL])); for (int b = 0; b < BATCH; b++){ for (size_t h = 0; h < HEIGHT; h++){ for (size_t w = 0; w < WIDTH; w++){ for (int c = 0; c < CHANNEL; c++){ (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in[b][h][w][c]; } } } } int wnum = window_h*window_w; int new_h_idx = 0, new_w_idx = 0; for (int b = 0; b < BATCH; b++){ for(int c = 0; c < CHANNEL; c++) { for(int i = 0; i <out_h; i++) { for(int j = 0; j <out_w; j++) { int pad_cnt = 0; float total = 0.0; for(int fh = 0; fh <window_h; fh++) { for(int fw = 0; fw <window_w; fw++) { int h_idx = new_h_idx+fh, w_idx = new_w_idx+fw; if(h_idx < pad_ytop || w_idx < pad_xleft || h_idx >= (new_height - pad_ybottom)|| w_idx >= (new_width - pad_xright)) { pad_cnt++; } total = total + (*newin)[b][h_idx][w_idx][c]; } } //cout << "pad_cnt = " << pad_cnt << endl; result[b][i][j][c] = total/(wnum-pad_cnt); new_w_idx += stride_size; } new_h_idx += stride_size; new_w_idx = 0; } new_h_idx = 0; } } free(newin); // time (&iend); // double dif = difftime (iend,istart); // printf ("==> [Avg. pooling time] %.4lf seconds.\n", dif ); } //N H W C /* * * * Max Pooling * * */ template <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL, typename T3, size_t N2, size_t M2, size_t K2, size_t L2> void maxpool(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], vector<size_t> windows_dim, vector<size_t> stride, vector<size_t> pad, T3 (&result)[N2][M2][K2][L2]) { #ifdef _DEBUG cout << "maxpool()" << endl; #endif // time_t istart,iend; // time (&istart); //N, H, W, C //N == 1 //group == 1 int pad_xleft = pad.at(0); int pad_xright = pad.at(1); int pad_ytop = pad.at(2); int pad_ybottom = pad.at(3); int xadd = pad_xleft + pad_xright; int yadd = pad_ytop + pad_ybottom; int stride_size = stride.at(0); int window_h = windows_dim.at(0); int window_w = windows_dim.at(1); int out_h = (HEIGHT + yadd - window_h)/stride_size + 1; int out_w = (WIDTH + xadd - window_w)/stride_size + 1; #if defined(__MACH__) || defined(_USE_LLVM) float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])); #else float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]; newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); #endif // memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])); for (int b = 0; b < BATCH; b++){ for (size_t h = 0; h < HEIGHT; h++){ for (size_t w = 0; w < WIDTH; w++){ for (int c = 0; c < CHANNEL; c++){ (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c]; } } } } int new_h_idx = 0, new_w_idx = 0; for (int b = 0; b < BATCH; b++){ for(int c = 0; c < CHANNEL; c++) { for(int i = 0; i <out_h; i++) { for(int j = 0; j <out_w; j++) { float max = -INFINITY;; for(int fh = 0; fh <window_h; fh++) { for(int fw = 0; fw <window_w; fw++) { float value = (*newin)[b][new_h_idx+fh][new_w_idx+fw][c]; if(max < value) max = value; } } result[b][i][j][c] = max; new_w_idx += stride_size; } new_h_idx += stride_size; new_w_idx = 0; } new_h_idx = 0; } } // if(pad_size > 0) free(newin); // time (&iend); // double dif = difftime (iend,istart); // printf ("==> [Max. pooling time] %.4lf seconds.\n", dif ); } // end maxpool /* * * * Softmax 2D * * */ template <typename T1, size_t N, size_t M, typename T2> void softmax(T1 (&in1)[N][M], int axis, T2 (&result)[N][M]) { #ifdef _DEBUG cout << "softmax()-2D" << endl; #endif //axis // clock_t start, end; // start = clock(); if(axis == 1) { float max[N]; for(size_t i = 0; i < N; i++) { max[i] = -INFINITY; } for (size_t i = 0; i < N; i++) { for (size_t j = 0; j < M; j++) { if (in1[i][j] > max[i]) { max[i] = in1[i][j]; } } } float sum[N]; memset(sum, 0x00, sizeof(float)*N); for (size_t i = 0; i < N; i++) { for (size_t j = 0; j < M; j++) { sum[i] += expf(in1[i][j]- max[i]); } } for (size_t i = 0; i < N; i++) { for (size_t j = 0; j < M; j++) { result[i][j] = expf(in1[i][j]-max[i])/sum[i]; } } } else { float max = -INFINITY; float sum = 0.0; for (size_t i = 0; i < N; i++) { for (size_t j = 0; j < M; j++) { if (in1[i][j] > max) { max = in1[i][j]; } } } for (size_t i = 0; i < N; i++) { for (size_t j = 0; j < M; j++) { sum += expf(in1[i][j]- max); } } for (size_t i = 0; i < N; i++) { for (size_t j = 0; j < M; j++) { result[i][j] = expf(in1[i][j]-max)/sum; } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } /* * * * Softmax 3D * * * */ template <typename T1, size_t N1, size_t N2, size_t N3, typename T2> void softmax(T1 (&in1)[N1][N2][N3], int axis, T2 (&result)[N1][N2][N3]) { #ifdef _DEBUG cout << "softmax()-3D" << endl; #endif //cout << "axis = " << axis << endl; //clock_t start, end; //start = clock(); if(axis == 1) { float max[N1]; for(int i = 0; i < N1; i++) { max[i] = -INFINITY; } for (size_t i = 0; i < N1; i++) { for (size_t k = 0; k < N3; k++) { for (size_t j = 0; j < N2; j++) { if (in1[i][j][k] > max[i]) { max[i] = in1[i][j][k]; } } } } float sum[N1]; memset(sum, 0x00, sizeof(float)*N1); for (size_t i = 0; i < N1; i++) { for (size_t j = 0; j < N2; j++) { for (size_t k = 0; k < N3; k++) { sum[i] += expf(in1[i][j][k]- max[i]); } } } for (size_t i = 0; i < N1; i++) { for (size_t j = 0; j < N2; j++) { for (size_t k = 0; k < N3; k++) { result[i][j][k] = expf(in1[i][j][k]-max[i])/sum[i]; } } } } else { float max = -INFINITY; float sum = 0.0; for (size_t i = 0; i < N1; i++) { for (size_t k = 0; k < N3; k++) { for (size_t j = 0; j < N2; j++) { if (in1[i][j][k] > max) { max = in1[i][j][k]; } } } } for (size_t i = 0; i < N1; i++) { for (size_t j = 0; j < N2; j++) { for (size_t k = 0; k < N3; k++) { sum += expf(in1[i][j][k]- max); } } } for (size_t i = 0; i < N1; i++) { for (size_t j = 0; j < N2; j++) { for (size_t k = 0; k < N3; k++) { result[i][j][k] = expf(in1[i][j][k]-max)/sum; } } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } /* * * * Relu 4D * * * */ template <typename T1, size_t N, size_t M, size_t K, size_t L> void relu(T1 (&in1)[N][M][K][L]) { #ifdef _DEBUG cout << "relu()-4D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i = 0; i < N; i++){ for (size_t j=0; j<M; j++){ for (size_t k=0; k<K; k++){ for (size_t l=0; l<L; l++) { if (in1[i][j][k][l] < 0.0) in1[i][j][k][l] = 0.0; } } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } //end relu /* * * * Relu 2D * * */ template <typename T1, size_t N, size_t M> void relu(T1 (&in1)[N][M]) { #ifdef _DEBUG cout << "relu()-2D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i=0; i < N; i++) { for (size_t j=0; j<M; j++){ if (in1[i][j] <= 0.0) in1[i][j] = 0.0; } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } //end relu /* * * * Add 2D + 2D * * */ template <typename T1, size_t N, size_t M> void add(T1 (&in1)[N][M], T1 (&in2)[N][M], T1 (&result)[N][M]) { #ifdef _DEBUG cout << "add()-2D + 2D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i = 0; i < N; i++){ for (size_t j = 0; j < M; j++){ result[i][j] = in1[i][j] + in2[i][j]; } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; //cout << "[LIB] add end" << endl; } /* * * * Add 2D + 1D * * */ template <typename T1, size_t N, size_t M> void add(T1 (&in1)[N][M], T1 (&in2)[M], T1 (&result)[N][M]) { #ifdef _DEBUG cout << "add()-2D + 1D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i = 0; i < N; i++){ for (size_t j = 0; j < M; j++){ result[i][j] = in1[i][j] + in2[j]; } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; //cout << "[LIB] add end" << endl; } /* * * * Add 2D + 2D * * */ template <typename T1, size_t N, size_t M> void add(T1 (&in1)[N][M], T1 (&in2)[N][M]) { #ifdef _DEBUG cout << "add()-2D + 2D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i = 0; i < N; i++){ for (size_t j = 0; j < M; j++){ in1[i][j] = in1[i][j] + in2[i][j]; } } } /* * * * Add 2D + 1D * * */ template <typename T1, size_t N, size_t M> void add(T1 (&in1)[N][M], T1 (&in2)[M]) { #ifdef _DEBUG cout << "add()-2D + 1D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i = 0; i < N; i++){ for (size_t j = 0; j < M; j++){ in1[i][j] = in1[i][j] + in2[j]; } } } /* * * * Add 4D + 1D * * */ template <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, typename T2, size_t M> void add(T1 (&in1)[N1][N2][N3][N4], T2 (&in2)[M], T1 (&result)[N1][N2][N3][N4]) { #ifdef _DEBUG cout << "add()-2D + 1D" << endl; #endif //clock_t start, end; //start = clock(); for (int i1 = 0; i1 < N1; i1++){ for (int i2 = 0; i2 < N2; i2++){ for (int i3 = 0; i3 < N3; i3++){ for (int i4 = 0; i4 < N4; i4++){ result[i1][i2][i3][i4] = in1[i1][i2][i3][i4] + in2[i2]; } } } } } /* * * * Add 4D + 1D * * */ template <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, typename T2, size_t M> void add(T1 (&in1)[N1][N2][N3][N4], T2 (&in2)[M]) { #ifdef _DEBUG cout << "add()-2D + 1D" << endl; #endif //clock_t start, end; //start = clock(); for (int i1 = 0; i1 < N1; i1++){ for (int i2 = 0; i2 < N2; i2++){ for (int i3 = 0; i3 < N3; i3++){ for (int i4 = 0; i4 < N4; i4++){ in1[i1][i2][i3][i4] = in1[i1][i2][i3][i4] + in2[i2]; } } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; //cout << "[LIB] add end" << endl; } /* * * * Add 4D + 4D * * */ template <typename T1, size_t N, size_t M, size_t K, size_t L> void add(T1 (&in1)[N][M][K][L], T1 (&in2)[N][M][K][L], T1 (&result)[N][M][K][L]) { #ifdef _DEBUG cout << "add()" << endl; #endif // clock_t start, end; // start = clock(); for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ for (int k = 0; k < K; k++){ for (int l = 0; l < L; l++){ result[i][j][k][l] = in1[i][j][k][l] + in2[i][j][k][l]; } } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } //end add /* * * * Add 4D + 4D * * */ template <typename T1, size_t N, size_t M, size_t K, size_t L> void add(T1 (&in1)[N][M][K][L], T1 (&in2)[N][M][K][L]) { #ifdef _DEBUG cout << "add()- 4D +4D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i = 0; i < N; i++){ for (size_t j = 0; j < M; j++){ for (size_t k = 0; k < K; k++){ for (size_t l = 0; l < L; l++){ in1[i][j][k][l] = in1[i][j][k][l] + in2[i][j][k][l]; } } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; // // } template <typename T1, size_t N1, size_t M1, typename T2, size_t N2, size_t M2, typename T3, size_t N3, typename T4, size_t N4, size_t M4> void gemm(T1 (&a)[N1][M1], T2 (&b)[N2][M2], T3 (&c)[N3], float alpha, float beta, int transA, int transB, T4 (&result)[N4][M4]) { #ifdef _DEBUG cout << "gemm()" << endl; // cout << "N: " << N << endl; // cout << "K: " << K << endl; // cout << "M: " << M << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif //#ifdef _USE_OPENBLAS_MATMUL // size_t m1len = N*K, m2len = K*M, m3len = N*M; // float *m1, *m2, *m3; // // m1 = (float *)malloc(sizeof(float)*m1len); // m2 = (float *)malloc(sizeof(float)*m2len); // m3 = (float *)malloc(sizeof(float)*m3len); // // for(int i = 0; i < m1len; i++) { // m1[i] = in1[i/K][i%K]; // } // // for(int i = 0; i < m2len; i++) { // m2[i] = weight[i/M][i%M]; // } // // cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M, K, 1, m1, K, m2, M, 0, m3, M); // // for(int i = 0; i < m3len; i++) { // result[i/M][i%M] = m3[i] + bias[i]; // } // // free(m1); // free(m2); // free(m3); // //#else // cout << "transA = " << transA << " transB = " << transB << endl; if(transA == 0 && transB == 0) { for (size_t i = 0; i < N1; i++){ for (size_t j = 0; j <M1; j++){ for (size_t k = 0; k < M2; k++){ result[i][j] += a[i][k]*b[k][j]; } } } } else if (transA == 0 && transB == 1) { float transposedB[M2][N2]; for (size_t i = 0; i < N2; i++) { for (size_t j = 0; j < M2; j++) { transposedB[j][i] = b[i][j]; } } for (size_t i = 0; i < N1; i++){ for (size_t j = 0; j <M2; j++){ for (size_t k = 0; k < M1; k++){ result[i][j] += a[i][k]*transposedB[k][j]; } } } } else if (transA == 1 && transB == 0) { float transposedA[M1][N1]; for (size_t i = 0; i < N1; i++) { for (size_t j = 0; j < M1; j++) { transposedA[j][i] = a[i][j]; } } for (size_t i = 0; i < M1; i++){ for (size_t j = 0; j <M2; j++){ for (size_t k = 0; k < N1; k++){ result[i][j] += transposedA[i][k]*b[k][j]; } } } } for (size_t i = 0; i < N4; i++){ for (size_t j = 0; j < M4; j++){ result[i][j] = result[i][j] + c[j]; } } //#endif #ifdef _DEBUG clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== gemm time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } //void cblas_sgemm(const enum CBLAS_ORDER __Order, const enum CBLAS_TRANSPOSE __TransA, const enum CBLAS_TRANSPOSE __TransB, // const int __M, const int __N, const int __K, const float __alpha, const float *__A, const int __lda, const float *__B, const int __ldb, const float __beta, float *__C, const int __ldc); template <typename T1, size_t N, size_t K, typename T2, size_t M, typename T3, typename T4> void fullyconnected(T1 (&in1)[N][K], T2 (&weight)[K][M], T3 (&bias)[M], T4 (&result)[N][M]) { #ifdef _DEBUG cout << "fullyconnected()" << endl; // cout << "N: " << N << endl; // cout << "K: " << K << endl; // cout << "M: " << M << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif #ifdef _USE_OPENBLAS_MATMUL size_t m1len = N*K, m2len = K*M, m3len = N*M; float *m1, *m2, *m3; m1 = (float *)malloc(sizeof(float)*m1len); m2 = (float *)malloc(sizeof(float)*m2len); m3 = (float *)malloc(sizeof(float)*m3len); for(int i = 0; i < m1len; i++) { m1[i] = in1[i/K][i%K]; } for(int i = 0; i < m2len; i++) { m2[i] = weight[i/M][i%M]; } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M, K, 1, m1, K, m2, M, 0, m3, M); for(int i = 0; i < m3len; i++) { result[i/M][i%M] = m3[i] + bias[i]; } free(m1); free(m2); free(m3); #else for (size_t i = 0; i < N; i++){ for (size_t j = 0; j <M; j++){ for (size_t k = 0; k < K; k++){ result[i][j] += in1[i][k]*weight[k][j]; } } } for (size_t i = 0; i < N; i++){ for (size_t j = 0; j < M; j++){ result[i][j] = result[i][j] + bias[j]; } } #endif #ifdef _DEBUG clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== fullyconnected time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } template <typename T1, size_t N, size_t K, typename T2, size_t M, typename T3, typename T4> void fullyconnected(T1 (&in1)[N][K], T2 (&weight)[K][M], T3 (&bias)[N][M], T4 (&result)[N][M]) { #ifdef _DEBUG cout << "fullyconnected()" << endl; // cout << "N: " << N << endl; // cout << "K: " << K << endl; // cout << "M: " << M << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif #ifdef _USE_OPENBLAS_MATMUL size_t m1len = N*K, m2len = K*M, m3len = N*M; float *m1, *m2, *m3; m1 = (float *)malloc(sizeof(float)*m1len); m2 = (float *)malloc(sizeof(float)*m2len); m3 = (float *)malloc(sizeof(float)*m3len); for(int i = 0; i < m1len; i++) { m1[i] = in1[i/K][i%K]; } for(int i = 0; i < m2len; i++) { m2[i] = weight[i/M][i%M]; } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M, K, 1, m1, K, m2, M, 0, m3, M); for(int i = 0; i < m3len; i++) { result[i/M][i%M] = m3[i] + bias[i]; } free(m1); free(m2); free(m3); #else for (size_t i = 0; i < N; i++){ for (size_t j = 0; j <M; j++){ for (size_t k = 0; k < K; k++){ result[i][j] += in1[i][k]*weight[k][j]; } } } for (size_t i = 0; i < N; i++){ for (size_t j = 0; j < M; j++){ result[i][j] = result[i][j] + bias[i][j]; } } #endif #ifdef _DEBUG clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== fullyconnected time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } template <typename T1, size_t N, size_t K, typename T2, size_t N1, size_t M1, typename T3, size_t N2, size_t M2> void matmul(T1 (&in1)[N][K], T2 (&in2)[N1][M1], T3 (&result)[N2][M2]) { #ifdef _DEBUG cout << "N: " << N << endl; cout << "K: " << K << endl; cout << "M: " << M1 << endl; struct timespec tp, ep; double timeCheck; clock_gettime(CLOCK_MONOTONIC, &tp); #endif #ifdef _USE_OPENBLAS_MATMUL size_t m1len = N*K, m2len = N1*M1, m3len = N2*M2; float *m1, *m2, *m3; m1 = (float *)malloc(sizeof(float)*m1len); m2 = (float *)malloc(sizeof(float)*m2len); m3 = (float *)malloc(sizeof(float)*m3len); for(int i = 0; i < m1len; i++) { m1[i] = in1[i/K][i%K]; } for(int i = 0; i < m2len; i++) { m2[i] = in2[i/M1][i%M1]; } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M1, K, 1, m1, K, m2, M1, 0, m3, M1); for(int i = 0; i < m3len; i++) { result[i/M2][i%M2] = m3[i]; } free(m1); free(m2); free(m3); #else for (size_t i = 0; i < N; i++){ // for (size_t k = 0; k < M; k++){ for (size_t j = 0; j <M1; j++){ for (size_t k = 0; k < K; k++){ result[i][j] += in1[i][k]*in2[k][j]; } } } #endif #ifdef _DEBUG clock_gettime(CLOCK_MONOTONIC, &ep); timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0); cout << "==================== matmul time : " << timeCheck <<" seconds ====================" << endl << endl; #endif } /* * * * Transpose 2D * * */ template <typename T1, size_t N, size_t M, typename T2, size_t N1, size_t M1> void transpose(T1 (&in1)[N][M], vector<size_t> shuffle, T2 (&result)[N1][M1]) { #ifdef _DEBUG cout << "transpose()-2D-2D" << endl; #endif // clock_t start, end; // start = clock(); for (size_t i=0; i<N; i++){ for (size_t j=0; j<M; j++){ result[j][i] = in1[i][j]; } } // // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } /* * * * Transpose 3D * * */ template <typename T1, size_t M, size_t K, size_t L, typename T2, size_t M1, size_t K1, size_t L1> void transpose(T1 (&in1)[M][K][L], vector<size_t> shuffle, T2 (&result)[M1][K1][L1]) { #ifdef _DEBUG cout << "transpose()-3D" << endl; #endif // // clock_t start, end; // start = clock(); int shuffleType = 0; // int shuffle0 = shuffle.at(0); int shuffle1 = shuffle.at(1); int shuffle2 = shuffle.at(2); int shuffle3 = shuffle.at(3); if(shuffle1 == 1 && shuffle2 == 2 && shuffle3 == 0) { shuffleType = 120; } else if(shuffle1 == 2 && shuffle2 == 0 && shuffle3 == 1) { shuffleType = 201; } else if(shuffle1 == 0 && shuffle2 == 2 && shuffle3 == 1) { shuffleType = 021; } else if(shuffle1 == 1 && shuffle2 == 0 && shuffle3 == 2) { shuffleType = 102; } cout << shuffleType <<endl; for (int j=0; j<M; j++){ for (int k=0; k<K; k++){ for (int l=0; l<L; l++){ if(shuffleType == 120) { result[k][l][j] = in1[j][k][l]; // 1, 2, 0 } else if (shuffleType == 201) { result[l][j][k] = in1[j][k][l]; // 2, 0, 1 } else if (shuffleType == 021) { result[j][l][k] = in1[j][k][l]; // 0, 2, 1 } else if (shuffleType == 102) { result[k][j][l] = in1[j][k][l]; // 1, 0, 2 } else { cout << "No!!!!!!!!!!!!"; } } // cout <<endl; } //cout <<endl; } //cout <<endl; // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } // end transpose /* * * * Transpose 6D * * */ template <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, size_t N5, size_t N6, typename T2, size_t M1, size_t M2, size_t M3, size_t M4, size_t M5, size_t M6> void transpose( T1 (&in1)[N1][N2][N3][N4][N5][N6], vector<size_t> shuffle, T2 (&result)[M1][M2][M3][M4][M5][M6]) { #ifdef _DEBUG cout << "transpose-6D" << endl; #endif // // clock_t start, end; // start = clock(); int shuffleType = 0; int shuffle0 = shuffle.at(0); int shuffle1 = shuffle.at(1); int shuffle2 = shuffle.at(2); int shuffle3 = shuffle.at(3); int shuffle4 = shuffle.at(4); int shuffle5 = shuffle.at(5); if(shuffle0 == 0 &&shuffle1 == 1 && shuffle2 == 4 && shuffle3 == 2 && shuffle4 == 5 && shuffle5 == 3) { shuffleType = 14253; } // cout << shuffleType <<endl; //#pragma omp parallel for for (int i1 = 0; i1 < N1; i1++){ for (int i2 = 0; i2 < N2; i2++){ for (int i3 = 0; i3 < N3; i3++){ for (int i4 = 0; i4 < N4; i4++){ for (int i5 = 0; i5 < N5; i5++){ for (int i6 = 0; i6 < N6; i6++){ if(shuffleType == 14253) { result[i1][i2][i5][i3][i6][i4] = in1[i1][i2][i3][i4][i5][i6]; // 0, 1, 4, 2, 5, 3 } } } } // cout <<endl; } //cout <<endl; } //cout <<endl; } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } /* * * * Transpose 4D * * */ template <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, typename T2, size_t M1, size_t M2, size_t M3, size_t M4> void transpose( T1 (&in1)[N1][N2][N3][N4], vector<size_t> shuffle, T2 (&result)[M1][M2][M3][M4]) { #ifdef _DEBUG cout << "transpose()-4D" << endl; #endif // clock_t start, end; // start = clock(); int shuffleType = 0; // int shuffle0 = shuffle.at(0); int shuffle1 = shuffle.at(1); int shuffle2 = shuffle.at(2); int shuffle3 = shuffle.at(3); if(shuffle1 == 2 && shuffle2 == 3 && shuffle3 == 1) { shuffleType = 231; } else if(shuffle1 == 3 && shuffle2 == 1 && shuffle3 == 2) { shuffleType = 312; } else if(shuffle1 == 1 && shuffle2 == 3 && shuffle3 == 2) { shuffleType = 132; } else if(shuffle1 == 2 && shuffle2 == 1 && shuffle3 == 3) { shuffleType = 213; } else if(shuffle1 == 3 && shuffle2 == 2 && shuffle3 == 1) { shuffleType = 321; }else if(shuffle1 == 1 && shuffle2 == 3 && shuffle3 == 2) { shuffleType = 132; } // cout << "shuffle type = " << shuffleType <<endl; //#pragma omp parallel for for (size_t i1 = 0; i1 < N1; i1++){ for (size_t i2 = 0; i2< N2; i2++){ for (size_t i3 = 0; i3 < N3; i3++){ for (size_t i4 = 0; i4 < N4; i4++){ if(shuffleType == 231) { result[i1][i3][i4][i2] = in1[i1][i2][i3][i4]; // 0, 2, 3, 1 } else if (shuffleType == 312) { result[i1][i4][i2][i3] = in1[i1][i2][i3][i4]; // 0, 3, 1, 2 } else if (shuffleType == 132) { result[i1][i2][i4][i3] = in1[i1][i2][i3][i4]; // 0, 1, 3, 2 } else if (shuffleType == 213) { result[i1][i3][i2][i4] = in1[i1][i2][i3][i4]; // 0, 2, 1, 3 }else if (shuffleType == 321) { result[i1][i4][i3][i2] = in1[i1][i2][i3][i4]; // 0, 2, 1, 3 }else if (shuffleType == 132) { result[i1][i2][i4][i3] = in1[i1][i2][i3][i4]; // 0, 2, 1, 3 } else { cout << "No!!!!!!!!!!!!"; } } // cout <<endl; } //cout <<endl; } //cout <<endl; } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } /* * * * Reshape 4D => 2D * * */ template <typename T1, size_t N, size_t M, size_t L, size_t K, typename T2, size_t N1, size_t M1> void reshape(T1 (&in1)[N][M][L][K], T2 (&result)[N1][M1]) { #ifdef _DEBUG cout << "reshape()-4D -> 2D)" << endl; #endif // // clock_t start, end; // start = clock(); // cout << "^^^^^^^^^^" << endl; // // for(int j = 0; j < M; j++){ // if(j%10 == 0) cout <<endl; // cout << in1[0][j][0][0] << "\t"; // } int total = 0; for(size_t i1 = 0; i1 < N; i1++) { for(size_t i2 = 0; i2 < M; i2++) { for(size_t i3 = 0; i3 < L; i3++) { for(size_t i4 = 0; i4 < K; i4++) { total = i1*M*L*K + i2*L*K + i3*K + i4; int idx1 = total/M1, idx2 = total%M1; result[idx1][idx2] = in1[i1][i2][i3][i4]; } } } } // // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } /* * * * Reshape 6D => 4D * * */ template <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, size_t N5, size_t N6, typename T2, size_t M1, size_t M2, size_t M3, size_t M4> void reshape(T1 (&in1)[N1][N2][N3][N4][N5][N6], T2 (&result)[M1][M2][M3][M4]) { #ifdef _DEBUG cout << "reshape()-6D -> 4D" << endl; #endif // clock_t start, end; // start = clock(); int total = 0; for(int i1 = 0; i1 < N1; i1++) { for(int i2 = 0; i2 < N2; i2++) { for(int i3 = 0; i3 <N3; i3++) { for(int i4 = 0; i4 < N4; i4++) { for(int i5 = 0; i5 < N5; i5++) { for(int i6 = 0; i6 < N6; i6++) { total = i1*N2*N3*N4*N5 + i2*N3*N4*N5 + i3*N4*N5 + i4*N5 + i6; int m1 = M2*M3*M4; int m2 = M3*M4; int idx1 = total/m1; int idx2 = (total%m1)/m2; int idx3 = (total%m1)%m2/M4; int idx4 = (total%m1)%m2%M4; result[idx1][idx2][idx3][idx4] = in1[i1][i2][i3][i4][i5][i6]; } } } } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } /* * * * Reshape 4D => 6D * * */ template <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, typename T2, size_t M1, size_t M2, size_t M3, size_t M4, size_t M5, size_t M6> void reshape(T1 (&in1)[N1][N2][N3][N4], T2 (&result)[M1][M2][M3][M4][M5][M6]) { #ifdef _DEBUG cout << "reshape()4D -> 6D" << endl; #endif // // clock_t start, end; // start = clock(); int total = 0; for(int i1 = 0; i1 < N1; i1++) { for(int i2 = 0; i2 < N2; i2++) { for(int i3 = 0; i3 <N3; i3++) { for(int i4 = 0; i4 < N4; i4++) { total = i1*N2*N3*N4 + i2*N3*N4 + i3*N4 + i4; int m1 = M2*M3*M4*M5*M6; int m2 = M3*M4*M5*M6; int m3 = M4*M5*M6; int m4 = M5*M6; int idx1 = total/m1; int idx2 = (total%m1)/m2; int idx3 = ((total%m1)%m2)/m3; int idx4 = ((total%m1)%m2%m3)/m4; int idx5 = (((total%m1)%m2%m3)%m4)/M6; int idx6 = (((total%m1)%m2%m3)%m4)%M6; result[idx1][idx2][idx3][idx4][idx5][idx6] = in1[i1][i2][i3][i4]; } } } } // // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } template<typename T1> void leakyRelu(T1 in, vector<size_t> idim, T1 result, int type) { cout << "leakyRelu():TBD" << endl; } template<typename T1, typename T2> void LRN(T1 in, vector<size_t> dim, float size, float beta, float bias, float windowSize, T2 result, int type) { cout << "LRN(): TBD" << endl; } template<typename T1, size_t N, size_t M, typename T2> void dropout(T1 (&in)[N][M], vector<size_t> dim, T1 (&result)[N][M], T2 (&mask)[N][M], int type) { cout << "dropout(): TBD" << endl; } template<typename T1, typename T2> void mul(T1 in1, vector<size_t> dim, T2 in2, T1 result, int type) { cout << "mul(): TBD" << endl; } template<typename T1, typename T2, size_t N, size_t M> void splat(T1 value, T2 (&result)[N][M]) { for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { result[i][j] = (T2)value; } } } template <typename T1, size_t N, size_t M, size_t K, size_t L> void channel_shuffle(T1 (&in1)[N][M][K][L], const int group, int kernel, T1 (&result)[N][M][K][L]) { #ifdef _DEBUG cout << "shuffle()-4D" << endl; cout << "group: " << group << endl; cout << "kernel: " << kernel << endl; #endif const int gdim = L/group; T1 rt[N][M][K][group][gdim]; //reshape 4d -> 5d int total = 0; for(int i1 = 0; i1 < N; i1++) { for(int i2 = 0; i2 < M; i2++) { for(int i3 = 0; i3 <K; i3++) { for(int i4 = 0; i4 < L; i4++) { total = i1*M*K*L + i2*K*L + i3*L + i4; int m1 = M*K*group*gdim; int m2 = K*group*gdim; int m3 = group*gdim; int m4 = gdim; int idx1 = total/m1; int idx2 = (total%m1)/m2; int idx3 = ((total%m1)%m2)/m3; int idx4 = ((total%m1)%m2%m3)/m4; int idx5 = ((total%m1)%m2%m3)%m4; rt[idx1][idx2][idx3][idx4][idx5] = in1[i1][i2][i3][i4]; } } } } T1 transrt[N][M][K][gdim][group]; // //transpose for (size_t i1 = 0; i1 < N; i1++){ for (size_t i2 = 0; i2< M; i2++){ for (size_t i3 = 0; i3 < K; i3++){ for (size_t i4 = 0; i4 < group; i4++){ for (size_t i5 = 0; i5 < gdim; i5++) { transrt[i1][i2][i3][i5][i4] = rt[i1][i2][i3][i4][i5]; } } } } } //reshape 5d -> 4d total = 0; for(int i1 = 0; i1 < N; i1++) { for(int i2 = 0; i2 < M; i2++) { for(int i3 = 0; i3 <K; i3++) { for(int i4 = 0; i4 < gdim; i4++) { for(int i5 = 0; i5 < group; i5++) { total = i1*M*K*gdim*group + i2*K*gdim*group + i3*gdim*group + i4*group + i5; int m1 = M*K*L; int m2 = K*L; int idx1 = total/m1; int idx2 = (total%m1)/m2; int idx3 = (total%m1)%m2/L; int idx4 = (total%m1)%m2%L; result[idx1][idx2][idx3][idx4] = transrt[i1][i2][i3][i4][i5]; } } } } } // end = clock(); // cout << "==> [time] : " << (((double)(end - start)) / CLOCKS_PER_SEC) << " seconds" << endl; } #endif /* LIBRARY_H_ */
{ "alphanum_fraction": 0.4898793527, "avg_line_length": 28.6822468225, "ext": "h", "hexsha": "39cdf54b444f40018385fe1ff6131992ff87f5f7", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2022-02-23T02:03:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-08T01:36:26.000Z", "max_forks_repo_head_hexsha": "c6ac790ed12807f2e0855e3aa0170cb149dc237d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "etri/nest-compiler", "max_forks_repo_path": "tests/CCodeGenTest/src/library.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c6ac790ed12807f2e0855e3aa0170cb149dc237d", "max_issues_repo_issues_event_max_datetime": "2022-02-25T05:01:43.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-25T03:36:18.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "etri/nest-compiler", "max_issues_repo_path": "tests/CCodeGenTest/src/library.h", "max_line_length": 188, "max_stars_count": 112, "max_stars_repo_head_hexsha": "c6ac790ed12807f2e0855e3aa0170cb149dc237d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "etri/nest-compiler", "max_stars_repo_path": "tests/CCodeGenTest/src/library.h", "max_stars_repo_stars_event_max_datetime": "2022-03-15T08:12:03.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-16T07:05:39.000Z", "num_tokens": 23234, "size": 69956 }
/* ** libproj -- library of cartographic projections ** ** Copyright (c) 2003, 2006 Gerald I. Evenden */ static const char LIBPROJ_ID[] = "Id"; /* ** Permission is hereby granted, free of charge, to any person obtaining ** a copy of this software and associated documentation files (the ** "Software"), to deal in the Software without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Software, and to ** permit persons to whom the Software is furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define N_TOL 1e-6 #define PROJ_LIB__ #ifdef PROJ_HAVE_GSL #include <gsl/gsl_integration.h> #define GSL_WORK 1000 #define PROJ_PARMS__ \ double n[2]; \ gsl_function func; \ gsl_integration_workspace *work; \ int mode; #include <lib_proj.h> double mayr_kernel(double x, void * n) { return (pow(cos(x), *(double*)n)); } #else #define PROJ_PARMS__ \ int mode; #include <lib_proj.h> #endif PROJ_HEAD(mayr, "Mayr (Tobler Meridian Geometric Mean)") "\n\tPCyl., Sph., NoInv."; /* definition of segment bounds for <1e-7 error (unit sphere) */ #define SEG1 1.4 #define SEG2 1.55 #define SEG3 1.57 #define BASE1 1.151132004484049 #define BASE2 1.196140916241303 #define BASE3 1.19812525384759 #define HALFN 4 /* Gauss Legendre weights/abscissa */ double X[] = { 0.96028985649753618, 0.79666647741362673, 0.52553240991632899, 0.18343464249564981 }; double W[] = { 0.10122853629037638, 0.22238103445337443, 0.31370664587788744, 0.36268378337836199 }; /* Mayr kernel */ #define func(v) sqrt(cos(v)) static double gauss_legendre(double x0, double x1) { int i = 0; double s = 0., *x = X, *w = W, xsize, xmean, arg; xmean = 0.5 * (x1 + x0); xsize = 0.5 * (x1 - x0); while ( i++ < HALFN ) { arg = xsize * *x++; s += *w++ * (func(xmean - arg) + func(xmean + arg)); }; return xsize * s; } static double integrate(double val) { double out; if (val <= SEG1) out = gauss_legendre(0., val); else if (val <= SEG2) out = BASE1 + gauss_legendre(SEG1, val); else if (val <= SEG3) out = BASE2 + gauss_legendre(SEG2, val); else out = BASE3 + gauss_legendre(SEG3, val); return out; } FORWARD(s_forward); /* spheroid */ (void) P; /* avoid warning */ xy.x = lp.lam * func(lp.phi); xy.y = integrate(fabs(lp.phi)); if (lp.phi < 0.) xy.y = -xy.y; return (xy); } #ifdef PROJ_HAVE_GSL FORWARD(s_forwardg); /* numerical integration n <> 0.5 */ double error; gsl_integration_qags(&P->func, 0., fabs(lp.phi), 1e-7, 1e-8, GSL_WORK, P->work, &xy.y, &error); xy.x = lp.lam * pow(cos(lp.phi), P->n[1]); if (lp.phi < 0.) xy.y = -xy.y; return (xy); } #endif FREEUP; if (P) { #if PROJ_HAVE_GSL if (P->mode) gsl_integration_workspace_free(P->work); #endif free(P); } } ENTRY0(mayr) P->es = 0; if (proj_param(P->params, "tn").i) { #if PROJ_HAVE_GSL P->n[0] = proj_param(P->params, "dn").f; if ((P->n[0] < N_TOL) || (P->n[0] > 1.-N_TOL)) E_ERROR(-40) P->fwd = s_forwardg; P->n[1] = 1. - P->n[0]; P->func.function = &mayr_kernel; P->func.params = P->n; P->work = gsl_integration_workspace_alloc (GSL_WORK); P->mode = 1; #else E_ERROR(-47) #endif } else { P->mode = 0; P->fwd = s_forward; } ENDENTRY(P) /* ** Log: proj_mayr.c ** Revision 3.2 2006/01/19 01:52:59 gie ** correct some casting ^)*^&^ ** ** Revision 3.1 2006/01/11 01:38:18 gie ** Initial ** */
{ "alphanum_fraction": 0.6530317613, "avg_line_length": 26.4713375796, "ext": "c", "hexsha": "8c0b83c5d20af24ae2186077b7b9c3e7a234f7b1", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-03T11:15:39.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-23T21:13:19.000Z", "max_forks_repo_head_hexsha": "6bc7b595a4a7f86e8fa969d067360450fa4e0a6a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Armand0s/homemade_vtk", "max_forks_repo_path": "Utilities/vtklibproj4/proj_mayr.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6bc7b595a4a7f86e8fa969d067360450fa4e0a6a", "max_issues_repo_issues_event_max_datetime": "2020-12-02T23:44:43.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-01T23:21:02.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Armand0s/homemade_vtk", "max_issues_repo_path": "Utilities/vtklibproj4/proj_mayr.c", "max_line_length": 84, "max_stars_count": 3, "max_stars_repo_head_hexsha": "b54ac74f4716572862365fbff28cd0ecb8d08c3d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Lin1225/vtk_v5.10.0", "max_stars_repo_path": "Utilities/vtklibproj4/proj_mayr.c", "max_stars_repo_stars_event_max_datetime": "2021-01-11T02:17:16.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-20T23:31:06.000Z", "num_tokens": 1359, "size": 4156 }
#include <stdio.h> #include <gsl/gsl_vector.h> int main (void) { int i; gsl_vector * v = gsl_vector_alloc (100); for (i = 0; i < 100; i++) { gsl_vector_set (v, i, 1.23 + i); } { FILE * f = fopen ("test.dat", "w"); gsl_vector_fprintf (f, v, "%.5g"); fclose (f); } gsl_vector_free (v); return 0; }
{ "alphanum_fraction": 0.5143678161, "avg_line_length": 14.5, "ext": "c", "hexsha": "f25468b895b8be25038a7054e7006e20436c6336", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/vectorw.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/vectorw.c", "max_line_length": 42, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/vectorw.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": 124, "size": 348 }
#ifndef GMM_AGGREGATE_NEWCOMP_H #define GMM_AGGREGATE_NEWCOMP_H #include "Object.h" #include "PDBVector.h" #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> // By Tania, October 2017 using namespace pdb; // This class contains the partial results for the GMM new model, that is, // sumWeights, sumMeans and sumCovars that will be later used to update the new // model. class GmmAggregateNewComp : public Object { private: double logLikelihood; Vector<double> sumWeights; //[k] Vector<Vector<double>> sumMeans; // r*datapoint [dim] Vector<Vector<double>> sumCovars; // r*datapoint*datapoint^T [dim*dim] public: ENABLE_DEEP_COPY GmmAggregateNewComp() {} GmmAggregateNewComp(int k, int dim) { logLikelihood = 0; sumWeights = Vector<double>(k, k); for (int i = 0; i < k; i++) { sumMeans.push_back(Vector<double>(dim, dim)); sumCovars.push_back(Vector<double>(dim * dim, dim * dim)); } } double getLogLikelihood() { return this->logLikelihood; } void setLogLikelihood(double logLikelihood) { this->logLikelihood = logLikelihood; } Vector<double> &getSumWeights() { return sumWeights; } double getSumWeights(int index) { return sumWeights[index]; } void setSumWeights(int index, double val) { sumWeights[index] = val; } Vector<double> &getSumMean(int index) { return sumMeans[index]; } void setSumMean(int index, Vector<double> &sumMean) { this->sumMeans[index] = sumMean; } Vector<double> &getSumCovar(int index) { return sumCovars[index]; } void setSumCovar(int index, Vector<double> &sumCovar) { this->sumCovars[index] = sumCovar; } ~GmmAggregateNewComp() {} }; #endif
{ "alphanum_fraction": 0.7010368664, "avg_line_length": 25.1594202899, "ext": "h", "hexsha": "ec5a23c9804eec3627fbd3be875274ca266e9050", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-03-06T19:28:19.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-18T02:13:53.000Z", "max_forks_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB", "max_forks_repo_path": "src/sharedLibraries/headers/GMM/GmmAggregateNewComp.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4", "max_issues_repo_issues_event_max_datetime": "2022-01-28T23:17:14.000Z", "max_issues_repo_issues_event_min_datetime": "2022-01-28T23:17:14.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB", "max_issues_repo_path": "src/sharedLibraries/headers/GMM/GmmAggregateNewComp.h", "max_line_length": 79, "max_stars_count": 13, "max_stars_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB", "max_stars_repo_path": "src/sharedLibraries/headers/GMM/GmmAggregateNewComp.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:06:04.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-17T16:14:26.000Z", "num_tokens": 505, "size": 1736 }
#include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_chebyshev.h> double f (double x, void *p) { if (x < 0.5) return 0.25; else return 0.75; } int main (void) { int i, n = 10000; gsl_cheb_series *cs = gsl_cheb_alloc (40); gsl_function F; F.function = f; F.params = 0; gsl_cheb_init (cs, &F, 0.0, 1.0); for (i = 0; i < n; i++) { double x = i / (double)n; double r10 = gsl_cheb_eval_n (cs, 10, x); double r40 = gsl_cheb_eval (cs, x); printf ("%g %g %g %g\n", x, GSL_FN_EVAL (&F, x), r10, r40); } gsl_cheb_free (cs); return 0; }
{ "alphanum_fraction": 0.5409309791, "avg_line_length": 15.1951219512, "ext": "c", "hexsha": "58a0c5469914fefb7a50561b6885748a79960df5", "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/doc/examples/cheb.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/doc/examples/cheb.c", "max_line_length": 48, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/cheb.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": 242, "size": 623 }
#ifndef OPENMC_TALLIES_FILTER_POLAR_H #define OPENMC_TALLIES_FILTER_POLAR_H #include <cmath> #include <vector> #include <gsl/gsl> #include "openmc/tallies/filter.h" namespace openmc { //============================================================================== //! Bins the incident neutron polar angle (relative to the global z-axis). //============================================================================== class PolarFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors ~PolarFilter() = default; //---------------------------------------------------------------------------- // Methods std::string type() const override {return "polar";} void from_xml(pugi::xml_node node) override; void get_all_bins(const Particle* p, int estimator, FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; std::string text_label(int bin) const override; //---------------------------------------------------------------------------- // Accessors void set_bins(gsl::span<double> bins); private: //---------------------------------------------------------------------------- // Data members std::vector<double> bins_; }; } // namespace openmc #endif // OPENMC_TALLIES_FILTER_POLAR_H
{ "alphanum_fraction": 0.4734513274, "avg_line_length": 25.5849056604, "ext": "h", "hexsha": "9659504568819c1ef1240040e0adae5c191c7df2", "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": "4a4ac4c351d41fe153ca3341820cc507e484ce50", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "janmalec/openmc", "max_forks_repo_path": "include/openmc/tallies/filter_polar.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4a4ac4c351d41fe153ca3341820cc507e484ce50", "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": "janmalec/openmc", "max_issues_repo_path": "include/openmc/tallies/filter_polar.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4a4ac4c351d41fe153ca3341820cc507e484ce50", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "janmalec/openmc", "max_stars_repo_path": "include/openmc/tallies/filter_polar.h", "max_stars_repo_stars_event_max_datetime": "2021-07-05T00:08:39.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-05T00:08:39.000Z", "num_tokens": 245, "size": 1356 }
/* multifit_nlinear/nielsen.c * * Copyright (C) 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * This module contains routines for updating the Levenberg-Marquardt * damping parameter on each iteration using Nielsen's method: * * [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and * Data Fitting, Informatics and Mathematical Modeling, * Technical University of Denmark (DTU), 2010. * * 5 routines are needed to implement the update procedure: * * 1. accept - update parameter after a step has been accepted * 2. reject - update parameter after a step has been rejected * 3. free - free workspace state */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #define LM_ONE_THIRD (0.333333333333333) static int nielsen_init(const gsl_matrix * J, const gsl_vector * diag, double * mu, long * nu); static int nielsen_accept(const double rho, double * mu, long * nu); static int nielsen_reject(double * mu, long * nu); static int nielsen_init(const gsl_matrix * J, const gsl_vector * diag, double * mu, long * nu) { const double mu0 = 1.0e-3; const size_t p = J->size2; size_t j; double max = -1.0; *nu = 2; /* set mu = mu0 * max(diag(J~^T J~)), with J~ = J D^{-1} */ for (j = 0; j < p; ++j) { gsl_vector_const_view v = gsl_matrix_const_column(J, j); double dj = gsl_vector_get(diag, j); double norm = gsl_blas_dnrm2(&v.vector) / dj; max = GSL_MAX(max, norm); } *mu = mu0 * max * max; return GSL_SUCCESS; } static int nielsen_accept(const double rho, double * mu, long * nu) { double b; /* reset nu */ *nu = 2; b = 2.0 * rho - 1.0; b = 1.0 - b*b*b; *mu *= GSL_MAX(LM_ONE_THIRD, b); return GSL_SUCCESS; } static int nielsen_reject(double * mu, long * nu) { *mu *= (double) *nu; /* nu := 2*nu */ *nu <<= 1; return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6696750903, "avg_line_length": 27.1568627451, "ext": "c", "hexsha": "73c0f15031f5f1aeb4944ee69c12a2109a56a361", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/nielsen.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/nielsen.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/nielsen.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": 792, "size": 2770 }
#ifndef MAT_H #define MAT_H #include <cstdio> #include <sstream> #include <string> #include <cstring> #include <cmath> extern "C" { #include <cblas.h> }; namespace mat { struct Mat { size_t n_row; size_t n_col; float *dptr; Mat() { dptr = NULL; } Mat(float *dptr, size_t n_row, size_t n_col) : n_row(n_row), n_col(n_col), dptr(dptr) {} inline void deepcopy(const Mat &mat) { memcpy(dptr, mat.dptr, sizeof(float) * mat.n_row * mat.n_col); n_row = mat.n_row; n_col = mat.n_col; } Mat& operator+=(const Mat &rhs) { size_t n_total = n_row * n_col; for(size_t i = 0; i < n_total; ++ i) { this->dptr[i] += rhs.dptr[i]; } return *this; } float* operator[](size_t i) { return dptr + i*n_col; } inline void Set(float *_dptr, size_t _n_row, size_t _n_col) { dptr = _dptr; n_row = _n_row; n_col = _n_col; } inline void SetRowNum(size_t _n_row) { n_row = _n_row; } inline void Reset() { memset(dptr, 0, sizeof(float) * n_row * n_col); } inline float* GetRow(size_t i) const { return dptr + i*n_col; } inline Mat SubMat(size_t start_row, size_t end_row) { Mat mat(GetRow(start_row), end_row - start_row, n_col); return mat; } inline Mat Reshape(size_t n_row_new, size_t n_col_new) { this->n_row = n_row_new; this->n_col = n_col_new; return *this; } inline void Save(const char *filename) { FILE *fp = fopen(filename, "wb"); if(fp) { fwrite(dptr, sizeof(float), n_row * n_col, fp); } fclose(fp); } inline std::string Shape() const { std::stringstream ss; ss << "(" << n_row << ", " << n_col << ")"; return ss.str(); } inline std::string ToString() const { std::stringstream ss; for(size_t i = 0; i < n_row*n_col; ++ i) { ss << dptr[i] << " "; if((i + 1) % n_col == 0) ss << "|\n"; } return ss.str(); } }; // c = dot(a, b) + c static inline void sgemm(const Mat &a, const Mat &b, const Mat &c) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, a.n_row, b.n_col, a.n_col, 1, a.dptr, a.n_col, b.dptr, b.n_col, 1, c.dptr, c.n_col); } } #endif /*MAT_H*/
{ "alphanum_fraction": 0.5454159593, "avg_line_length": 27.0804597701, "ext": "h", "hexsha": "28ec1f8a2705bb5d97b099067e6580f3db23b2cc", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-06-15T09:36:43.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-17T14:14:35.000Z", "max_forks_repo_head_hexsha": "20891774e725aa807a3a3615b3442d3ae3bf58e7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dongguosheng/learn_dssm", "max_forks_repo_path": "cpp/mat.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "20891774e725aa807a3a3615b3442d3ae3bf58e7", "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": "dongguosheng/learn_dssm", "max_issues_repo_path": "cpp/mat.h", "max_line_length": 144, "max_stars_count": 4, "max_stars_repo_head_hexsha": "20891774e725aa807a3a3615b3442d3ae3bf58e7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dongguosheng/learn_dssm", "max_stars_repo_path": "cpp/mat.h", "max_stars_repo_stars_event_max_datetime": "2017-05-02T14:37:36.000Z", "max_stars_repo_stars_event_min_datetime": "2016-05-27T09:14:05.000Z", "num_tokens": 712, "size": 2356 }
// Copyright (C) 2015 Vincent Lejeune // For conditions of distribution and use, see copyright notice in License.txt #pragma once #include <vector> #include <tuple> #include <array> #include <memory> #include <gsl/gsl> #include <variant> #include <optional> #include "..\Core\SColor.h" namespace irr { namespace video { enum class E_INDEX_TYPE { EIT_16BIT, EIT_32BIT }; enum class E_POLYGON_MODE { EPM_FILL, EPM_LINE, EPM_POINT }; enum class E_CULL_MODE { ECM_NONE, ECM_FRONT, ECM_BACK, ECM_FRONT_AND_BACK }; enum class E_FRONT_FACE { EFF_CCW, EFF_CW }; enum class E_SAMPLE_COUNT { ESC_1, ESC_2, ESC_4, ESC_8 }; enum class E_PRIMITIVE_TYPE { EPT_POINTS, EPT_LINE_STRIP, EPT_LINES, EPT_TRIANGLE_STRIP, EPT_TRIANGLES, }; enum class E_COMPARE_FUNCTION { ECF_LESS, ECF_LEQUAL, ECF_NEVER, }; enum class E_STENCIL_OP { ESO_KEEP, }; enum class E_ASPECT { EA_COLOR, EA_DEPTH, EA_STENCIL, EA_DEPTH_STENCIL }; enum class E_MEMORY_POOL { EMP_CPU_WRITEABLE, EMP_GPU_LOCAL, EMP_CPU_READABLE, }; enum class E_TEXTURE_TYPE { ETT_2D, ETT_CUBE, }; } } enum class RESOURCE_USAGE { PRESENT, COPY_DEST, COPY_SRC, RENDER_TARGET, READ_GENERIC, DEPTH_WRITE, undefined, uav, }; enum image_flags { usage_transfer_src = 0x1, usage_transfer_dst = 0x2, usage_sampled = 0x4, usage_render_target = 0x8, usage_depth_stencil = 0x10, usage_input_attachment = 0x20, usage_cube = 0x40, }; enum buffer_flags { none = 0, usage_uav = 0x1, usage_texel_buffer = 0x2, usage_buffer_transfer_src = 0x4, usage_uniform = 0x8, usage_index = 0x10, usage_vertex = 0x20, }; enum class SAMPLER_TYPE { NEAREST, BILINEAR_CLAMPED, TRILINEAR, ANISOTROPIC, }; struct MipLevelData { uint64_t Offset; uint32_t Width; uint32_t Height; uint32_t RowPitch; }; enum class RESOURCE_VIEW { CONSTANTS_BUFFER, INPUT_ATTACHMENT, SHADER_RESOURCE, TEXEL_BUFFER, SAMPLER, UAV_BUFFER, UAV_IMAGE, }; enum class shader_stage { vertex_shader, fragment_shader, all, }; struct range_of_descriptors { const RESOURCE_VIEW range_type; const uint32_t bind_point; const uint32_t count; constexpr range_of_descriptors(const RESOURCE_VIEW rt, const uint32_t bindpoint, const uint32_t range_size) : range_type(rt), bind_point(bindpoint), count(range_size) {} }; struct descriptor_set { const std::vector<range_of_descriptors> descriptors_ranges; const shader_stage stage; descriptor_set(const std::initializer_list<range_of_descriptors>& ranges, const shader_stage& st) : descriptors_ranges(ranges), stage(st) { } }; struct pipeline_vertex_attributes { uint32_t location; irr::video::ECOLOR_FORMAT format; uint32_t binding; uint32_t stride; uint32_t offset; }; /* VkPipelineColorBlendAttachmentState blend_attachment_state{ true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE , VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE , VK_BLEND_FACTOR_ONE , VK_BLEND_OP_ADD, -1 }; VkPipelineColorBlendStateCreateInfo blend_state{ VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, nullptr, 0, false, VK_LOGIC_OP_NO_OP, 1, &blend_attachment_state };*/ enum class blend_factor { zero, one, }; enum class blend_op { add }; struct color_output { bool blend; blend_op op; blend_factor src_color; blend_factor src_alpha; blend_factor dst_color; blend_factor dst_alpha; }; struct compute_pipeline_state_description { std::vector<uint32_t> compute_binary; compute_pipeline_state_description set_compute_shader(gsl::span<const uint32_t> code) { std::copy(code.begin(), code.end(), std::back_inserter(compute_binary)); return *this; } }; struct graphic_pipeline_state_description { std::vector<uint32_t> vertex_binary; std::vector<uint32_t> fragment_binary; std::vector<pipeline_vertex_attributes> attributes; std::vector<color_output> color_outputs; bool rasterization_depth_clamp_enable; bool rasterization_discard_enable; irr::video::E_POLYGON_MODE rasterization_polygon_mode; irr::video::E_CULL_MODE rasterization_cull_mode; irr::video::E_FRONT_FACE rasterization_front_face; bool rasterization_depth_bias_enable; float rasterization_depth_bias_constant_factor; float rasterization_depth_bias_clamp; float rasterization_depth_bias_slope_factor; float rasterization_line_width; bool rasterization_conservative_enable; bool multisample_multisample_enable; irr::video::E_SAMPLE_COUNT multisample_sample_count; float multisample_min_sample_shading; // sample mask ? bool multisample_alpha_to_coverage; bool multisample_alpha_to_one; irr::video::E_PRIMITIVE_TYPE input_assembly_topology; bool input_assembly_primitive_restart; bool depth_stencil_depth_test; bool depth_stencil_depth_write; irr::video::E_COMPARE_FUNCTION depth_stencil_depth_compare_op; bool depth_stencil_depth_clip_enable; bool depth_stencil_stencil_test; irr::video::E_STENCIL_OP depth_stencil_front_stencil_fail_op; irr::video::E_STENCIL_OP depth_stencil_front_stencil_depth_fail_op; irr::video::E_STENCIL_OP depth_stencil_front_stencil_pass_op; irr::video::E_COMPARE_FUNCTION depth_stencil_front_stencil_compare_op; irr::video::E_STENCIL_OP depth_stencil_back_stencil_fail_op; irr::video::E_STENCIL_OP depth_stencil_back_stencil_depth_fail_op; irr::video::E_STENCIL_OP depth_stencil_back_stencil_pass_op; irr::video::E_COMPARE_FUNCTION depth_stencil_back_stencil_compare_op; float depth_stencil_min_depth_clip; float depth_stencil_max_depth_clip; static graphic_pipeline_state_description get() { return graphic_pipeline_state_description(false, false, irr::video::E_POLYGON_MODE::EPM_FILL, irr::video::E_CULL_MODE::ECM_BACK, irr::video::E_FRONT_FACE::EFF_CW, false, 0.f, 0.f, 0.f, 1.f, false, false, irr::video::E_SAMPLE_COUNT::ESC_1, 0.f, false, false, irr::video::E_PRIMITIVE_TYPE::EPT_TRIANGLES, false, true, true, irr::video::E_COMPARE_FUNCTION::ECF_LESS, false, false, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_COMPARE_FUNCTION::ECF_NEVER, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_STENCIL_OP::ESO_KEEP, irr::video::E_COMPARE_FUNCTION::ECF_NEVER, 0.f, 1.f); } graphic_pipeline_state_description set_depth_compare_function(irr::video::E_COMPARE_FUNCTION depth_compare) const { return graphic_pipeline_state_description(rasterization_depth_clamp_enable, rasterization_discard_enable, rasterization_polygon_mode, rasterization_cull_mode, rasterization_front_face, rasterization_depth_bias_enable, rasterization_depth_bias_constant_factor, rasterization_depth_bias_clamp, rasterization_depth_bias_slope_factor, rasterization_line_width, rasterization_conservative_enable, multisample_multisample_enable, multisample_sample_count, multisample_min_sample_shading, multisample_alpha_to_coverage, multisample_alpha_to_one, input_assembly_topology, input_assembly_primitive_restart, depth_stencil_depth_test, depth_stencil_depth_write, depth_compare, depth_stencil_depth_clip_enable, depth_stencil_stencil_test, depth_stencil_front_stencil_fail_op, depth_stencil_front_stencil_depth_fail_op, depth_stencil_front_stencil_pass_op, depth_stencil_front_stencil_compare_op, depth_stencil_back_stencil_fail_op, depth_stencil_back_stencil_depth_fail_op, depth_stencil_back_stencil_pass_op, depth_stencil_back_stencil_compare_op, depth_stencil_min_depth_clip, depth_stencil_max_depth_clip); } graphic_pipeline_state_description set_depth_write(bool depthwrite) const { return graphic_pipeline_state_description(rasterization_depth_clamp_enable, rasterization_discard_enable, rasterization_polygon_mode, rasterization_cull_mode, rasterization_front_face, rasterization_depth_bias_enable, rasterization_depth_bias_constant_factor, rasterization_depth_bias_clamp, rasterization_depth_bias_slope_factor, rasterization_line_width, rasterization_conservative_enable, multisample_multisample_enable, multisample_sample_count, multisample_min_sample_shading, multisample_alpha_to_coverage, multisample_alpha_to_one, input_assembly_topology, input_assembly_primitive_restart, depth_stencil_depth_test, depthwrite, depth_stencil_depth_compare_op, depth_stencil_depth_clip_enable, depth_stencil_stencil_test, depth_stencil_front_stencil_fail_op, depth_stencil_front_stencil_depth_fail_op, depth_stencil_front_stencil_pass_op, depth_stencil_front_stencil_compare_op, depth_stencil_back_stencil_fail_op, depth_stencil_back_stencil_depth_fail_op, depth_stencil_back_stencil_pass_op, depth_stencil_back_stencil_compare_op, depth_stencil_min_depth_clip, depth_stencil_max_depth_clip); } graphic_pipeline_state_description set_depth_test(bool depth_test) const { return graphic_pipeline_state_description(rasterization_depth_clamp_enable, rasterization_discard_enable, rasterization_polygon_mode, rasterization_cull_mode, rasterization_front_face, rasterization_depth_bias_enable, rasterization_depth_bias_constant_factor, rasterization_depth_bias_clamp, rasterization_depth_bias_slope_factor, rasterization_line_width, rasterization_conservative_enable, multisample_multisample_enable, multisample_sample_count, multisample_min_sample_shading, multisample_alpha_to_coverage, multisample_alpha_to_one, input_assembly_topology, input_assembly_primitive_restart, depth_test, depth_stencil_depth_write, depth_stencil_depth_compare_op, depth_stencil_depth_clip_enable, depth_stencil_stencil_test, depth_stencil_front_stencil_fail_op, depth_stencil_front_stencil_depth_fail_op, depth_stencil_front_stencil_pass_op, depth_stencil_front_stencil_compare_op, depth_stencil_back_stencil_fail_op, depth_stencil_back_stencil_depth_fail_op, depth_stencil_back_stencil_pass_op, depth_stencil_back_stencil_compare_op, depth_stencil_min_depth_clip, depth_stencil_max_depth_clip); } graphic_pipeline_state_description set_vertex_shader(gsl::span<const uint32_t> binary) { std::copy(binary.begin(), binary.end(), std::back_inserter(vertex_binary)); return *this; } graphic_pipeline_state_description set_fragment_shader(gsl::span<const uint32_t> binary) { std::copy(binary.begin(), binary.end(), std::back_inserter(fragment_binary)); return *this; } graphic_pipeline_state_description set_vertex_attributes(const gsl::span<pipeline_vertex_attributes> &attributes_) { attributes = std::vector<pipeline_vertex_attributes>(attributes_.begin(), attributes_.end()); return *this; } graphic_pipeline_state_description set_color_outputs(const gsl::span<color_output> &color_outputs_) { color_outputs = std::vector<color_output>(color_outputs_.begin(), color_outputs_.end()); return *this; } graphic_pipeline_state_description() { } private: graphic_pipeline_state_description( bool depth_clamp_enable, bool rasterizer_discard_enable, irr::video::E_POLYGON_MODE polygon_mode, irr::video::E_CULL_MODE cull_mode, irr::video::E_FRONT_FACE front_face, bool depth_bias_enable, float depth_bias_constant_factor, float depth_bias_clamp, float depth_bias_slope_factor, float line_width, bool conservative_enable, bool multisample_enable, irr::video::E_SAMPLE_COUNT sample_count, float min_sample_shading, bool alpha_to_coverage, bool alpha_to_one, irr::video::E_PRIMITIVE_TYPE topology, bool primitive_restart, bool depth_test, bool depth_write, irr::video::E_COMPARE_FUNCTION depth_compare_op, bool depth_clip_enable, bool stencil_test, irr::video::E_STENCIL_OP front_stencil_fail_op, irr::video::E_STENCIL_OP front_stencil_depth_fail_op, irr::video::E_STENCIL_OP front_stencil_pass_op, irr::video::E_COMPARE_FUNCTION front_stencil_compare_op, irr::video::E_STENCIL_OP back_stencil_fail_op, irr::video::E_STENCIL_OP back_stencil_depth_fail_op, irr::video::E_STENCIL_OP back_stencil_pass_op, irr::video::E_COMPARE_FUNCTION back_stencil_compare_op, float min_depth_clip, float max_depth_clip ) : rasterization_depth_clamp_enable(depth_clamp_enable), rasterization_discard_enable(rasterizer_discard_enable), rasterization_polygon_mode(polygon_mode), rasterization_cull_mode(cull_mode), rasterization_front_face(front_face), rasterization_depth_bias_enable(depth_bias_enable), rasterization_depth_bias_constant_factor(depth_bias_constant_factor), rasterization_depth_bias_clamp(depth_bias_clamp), rasterization_depth_bias_slope_factor(depth_bias_slope_factor), rasterization_line_width(line_width), rasterization_conservative_enable(conservative_enable), multisample_multisample_enable(multisample_enable), multisample_sample_count(sample_count), multisample_min_sample_shading(min_sample_shading), multisample_alpha_to_coverage(alpha_to_coverage), multisample_alpha_to_one(alpha_to_one), input_assembly_topology(topology), input_assembly_primitive_restart(primitive_restart), depth_stencil_depth_test(depth_test), depth_stencil_depth_write(depth_write), depth_stencil_depth_compare_op(depth_compare_op), depth_stencil_depth_clip_enable(depth_clip_enable), depth_stencil_stencil_test(stencil_test), depth_stencil_front_stencil_fail_op(front_stencil_fail_op), depth_stencil_front_stencil_depth_fail_op(front_stencil_depth_fail_op), depth_stencil_front_stencil_pass_op(front_stencil_pass_op), depth_stencil_front_stencil_compare_op(front_stencil_compare_op), depth_stencil_back_stencil_fail_op(back_stencil_fail_op), depth_stencil_back_stencil_depth_fail_op(back_stencil_depth_fail_op), depth_stencil_back_stencil_pass_op(back_stencil_pass_op), depth_stencil_back_stencil_compare_op(back_stencil_compare_op), depth_stencil_min_depth_clip(min_depth_clip), depth_stencil_max_depth_clip(max_depth_clip) { } }; struct framebuffer_t { virtual ~framebuffer_t() {} }; struct pipeline_state_t { virtual ~pipeline_state_t() {} }; struct compute_pipeline_state_t { virtual ~compute_pipeline_state_t() {} }; struct pipeline_layout_t { virtual ~pipeline_layout_t() {} }; struct render_pass_t { virtual ~render_pass_t() {} }; using clear_value_t = std::variant<std::array<float, 4>, std::tuple<float, uint8_t> >; struct image_view_t { virtual ~image_view_t() {} }; struct sampler_t { virtual ~sampler_t() {} }; struct buffer_view_t { virtual ~buffer_view_t() {} }; struct allocated_descriptor_set { }; struct descriptor_set_layout { virtual ~descriptor_set_layout() {} }; struct buffer_t { virtual void* map_buffer() = 0; virtual void unmap_buffer() = 0; virtual ~buffer_t() {} }; struct image_t { virtual ~image_t() {} }; struct descriptor_storage_t { virtual std::unique_ptr<allocated_descriptor_set> allocate_descriptor_set_from_cbv_srv_uav_heap(uint32_t starting_index, const std::vector<descriptor_set_layout*> layouts, uint32_t descriptors_count) = 0; virtual std::unique_ptr<allocated_descriptor_set> allocate_descriptor_set_from_sampler_heap(uint32_t starting_index, const std::vector<descriptor_set_layout*> layouts, uint32_t descriptors_count) = 0; virtual ~descriptor_storage_t() {}; }; struct command_list_t { virtual void bind_graphic_descriptor(uint32_t bindpoint, const allocated_descriptor_set& descriptor_set, pipeline_layout_t& sig) = 0; virtual void bind_compute_descriptor(uint32_t bindpoint, const allocated_descriptor_set& descriptor_set, pipeline_layout_t& sig) = 0; virtual void copy_buffer_to_image_subresource(image_t& destination_image, uint32_t destination_subresource, buffer_t& source, uint64_t offset_in_buffer, uint32_t width, uint32_t height, uint32_t row_pitch, irr::video::ECOLOR_FORMAT format) = 0; virtual void set_pipeline_barrier(image_t& resource, RESOURCE_USAGE before, RESOURCE_USAGE after, uint32_t subresource, irr::video::E_ASPECT) = 0; virtual void set_uav_flush(image_t& resource) = 0; virtual void set_viewport(float x, float width, float y, float height, float min_depth, float max_depth) = 0; virtual void set_scissor(uint32_t left, uint32_t right, uint32_t top, uint32_t bottom) = 0; virtual void set_graphic_pipeline(pipeline_state_t& pipeline) = 0; virtual void set_graphic_pipeline_layout(pipeline_layout_t& sig) = 0; virtual void set_compute_pipeline(compute_pipeline_state_t& pipeline) = 0; virtual void set_compute_pipeline_layout(pipeline_layout_t& sig) = 0; virtual void set_descriptor_storage_referenced(descriptor_storage_t& main_heap, descriptor_storage_t* sampler_heap = nullptr) = 0; virtual void bind_index_buffer(buffer_t& buffer, uint64_t offset, uint32_t size, irr::video::E_INDEX_TYPE type) = 0; virtual void bind_vertex_buffers(uint32_t first_bind, const std::vector<std::tuple<buffer_t&, uint64_t, uint32_t, uint32_t> > &buffer_offset_stride_size) = 0; virtual void draw_indexed(uint32_t index_count, uint32_t instance_count, uint32_t base_index, int32_t base_vertex, uint32_t base_instance) = 0; virtual void draw_non_indexed(uint32_t vertex_count, uint32_t instance_count, int32_t base_vertex, uint32_t base_instance) = 0; virtual void dispatch(uint32_t x, uint32_t y, uint32_t z) = 0; virtual void copy_buffer(buffer_t& src, uint64_t src_offset, buffer_t& dst, uint64_t dst_offset, uint64_t size) = 0; virtual void clear_depth_stencil(image_t &img, float depth) = 0; virtual void clear_depth_stencil(image_t &img, uint8_t stencil) = 0; virtual void clear_depth_stencil(image_t &img, float depth, uint8_t stencil) = 0; virtual void clear_color(image_t &img, const std::array<float, 4> &clear_colors) = 0; virtual void begin_renderpass(render_pass_t& rp, framebuffer_t& fbo, gsl::span<clear_value_t> clear_values, uint32_t width, uint32_t height) = 0; virtual void next_subpass() = 0; virtual void end_renderpass() = 0; virtual void make_command_list_executable() = 0; virtual void start_command_list_recording(struct command_list_storage_t& storage) = 0; }; struct semaphore_t { virtual ~semaphore_t() {}; }; struct fence_t { virtual ~fence_t() {}; }; struct command_list_storage_t { virtual std::unique_ptr<command_list_t> create_command_list() = 0; virtual void reset_command_list_storage() = 0; virtual ~command_list_storage_t() {} }; struct command_queue_t { virtual void submit_executable_command_list(command_list_t& command_list, semaphore_t* wait_sem) = 0; virtual void wait_for_command_queue_idle() = 0; }; struct swap_chain_t { virtual ~swap_chain_t() {} virtual uint32_t get_next_backbuffer_id(semaphore_t& semaphore) = 0; virtual std::vector<std::unique_ptr<image_t>> get_image_view_from_swap_chain() = 0; virtual void present(command_queue_t& cmdqueue, uint32_t backbuffer_index) = 0; }; struct device_t { virtual std::unique_ptr<command_list_storage_t> create_command_storage() = 0; virtual std::unique_ptr<buffer_t> create_buffer(size_t size, irr::video::E_MEMORY_POOL memory_pool, uint32_t flags) = 0; virtual std::unique_ptr<buffer_view_t> create_buffer_view(buffer_t&, irr::video::ECOLOR_FORMAT, uint64_t offset, uint32_t size) = 0; virtual void set_constant_buffer_view(const allocated_descriptor_set& descriptor_set, uint32_t offset_in_set, uint32_t binding_location, buffer_t& buffer, uint32_t buffer_size, uint64_t offset_in_buffer = 0) = 0; virtual void set_uniform_texel_buffer_view(const allocated_descriptor_set& descriptor_set, uint32_t offset_in_set, uint32_t binding_location, buffer_view_t& buffer_view) = 0; virtual void set_uav_buffer_view(const allocated_descriptor_set& descriptor_set, uint32_t offset_in_set, uint32_t binding_location, buffer_t& buffer, uint64_t offset, uint32_t size) = 0; virtual std::unique_ptr<image_t> create_image(irr::video::ECOLOR_FORMAT format, uint32_t width, uint32_t height, uint16_t mipmap, uint32_t layers, uint32_t flags, clear_value_t *clear_value) = 0; virtual std::unique_ptr<image_view_t> create_image_view(image_t& img, irr::video::ECOLOR_FORMAT fmt, uint16_t base_mipmap, uint16_t mipmap_count, uint16_t base_layer, uint16_t layer_count, irr::video::E_TEXTURE_TYPE texture_type, irr::video::E_ASPECT aspect = irr::video::E_ASPECT::EA_COLOR) = 0; virtual void set_image_view(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, image_view_t& img_view) = 0; virtual void set_input_attachment(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, image_view_t& img_view) = 0; virtual void set_uav_image_view(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, image_view_t& img_view) = 0; virtual void set_sampler(const allocated_descriptor_set& descriptor_set, uint32_t offset, uint32_t binding_location, sampler_t& sampler) = 0; virtual std::unique_ptr<sampler_t> create_sampler(SAMPLER_TYPE sampler_type) = 0; virtual std::unique_ptr<descriptor_storage_t> create_descriptor_storage(uint32_t num_sets, const std::vector<std::tuple<RESOURCE_VIEW, uint32_t> > &num_descriptors) = 0; virtual std::unique_ptr<framebuffer_t> create_frame_buffer(gsl::span<const image_view_t*> render_targets, uint32_t width, uint32_t height, render_pass_t* render_pass) = 0; virtual std::unique_ptr<framebuffer_t> create_frame_buffer(gsl::span<const image_view_t*> render_targets, const image_view_t& depth_stencil_texture, uint32_t width, uint32_t height, render_pass_t* render_pass) = 0; virtual std::unique_ptr<descriptor_set_layout> get_object_descriptor_set(const descriptor_set &ds) = 0; virtual std::unique_ptr<pipeline_state_t> create_graphic_pso(const graphic_pipeline_state_description&, const render_pass_t&, const pipeline_layout_t&, const uint32_t& subpass) = 0; virtual std::unique_ptr<compute_pipeline_state_t> create_compute_pso(const compute_pipeline_state_description&, const pipeline_layout_t&) = 0; virtual std::unique_ptr<pipeline_layout_t> create_pipeline_layout(gsl::span<const descriptor_set_layout *>) = 0; virtual std::unique_ptr<fence_t> create_fence() = 0; virtual std::unique_ptr<semaphore_t> create_semaphore() = 0; virtual std::unique_ptr<render_pass_t> create_ibl_sky_pass(const irr::video::ECOLOR_FORMAT&) = 0; virtual std::unique_ptr<render_pass_t> create_object_sunlight_pass(const irr::video::ECOLOR_FORMAT&) = 0; virtual std::unique_ptr<render_pass_t> create_ssao_pass() = 0; virtual std::unique_ptr<render_pass_t> create_blit_pass(const irr::video::ECOLOR_FORMAT& color_format) = 0; virtual ~device_t() {}; }; clear_value_t get_clear_value(irr::video::ECOLOR_FORMAT format, float depth, uint8_t stencil); clear_value_t get_clear_value(irr::video::ECOLOR_FORMAT format, const std::array<float,4> &color);
{ "alphanum_fraction": 0.8121549382, "avg_line_length": 34.7896341463, "ext": "h", "hexsha": "ce6fe09ef845b3925e6325e6d8d5b1192f010e4e", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-10-31T04:40:05.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-18T16:23:33.000Z", "max_forks_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vlj/YAGF", "max_forks_repo_path": "include/API/GfxApi.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_issues_repo_issues_event_max_datetime": "2017-11-16T03:06:58.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-16T19:46:53.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "vlj/YAGF", "max_issues_repo_path": "include/API/GfxApi.h", "max_line_length": 297, "max_stars_count": 15, "max_stars_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vlj/YAGF", "max_stars_repo_path": "include/API/GfxApi.h", "max_stars_repo_stars_event_max_datetime": "2019-10-23T23:30:18.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-16T19:41:41.000Z", "num_tokens": 5917, "size": 22822 }
/* spprop.c * * Copyright (C) 2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_errno.h> /* gsl_spmatrix_equal() Return 1 if a = b, 0 otherwise */ int gsl_spmatrix_equal(const gsl_spmatrix *a, const gsl_spmatrix *b) { const size_t M = a->size1; const size_t N = a->size2; if (b->size1 != M || b->size2 != N) { GSL_ERROR_VAL("matrices must have same dimensions", GSL_EBADLEN, 0); } else if (a->sptype != b->sptype) { GSL_ERROR_VAL("trying to compare different sparse matrix types", GSL_EINVAL, 0); } else { const size_t nz = a->nz; size_t n; if (nz != b->nz) return 0; /* different number of non-zero elements */ if (GSL_SPMATRIX_ISTRIPLET(a)) { /* * triplet formats could be out of order but identical, so use * gsl_spmatrix_get() on b for each aij */ for (n = 0; n < nz; ++n) { double bij = gsl_spmatrix_get(b, a->i[n], a->p[n]); if (a->data[n] != bij) return 0; } } else if (GSL_SPMATRIX_ISCCS(a)) { /* * for CCS, both matrices should have everything * in the same order */ /* check row indices and data */ for (n = 0; n < nz; ++n) { if ((a->i[n] != b->i[n]) || (a->data[n] != b->data[n])) return 0; } /* check column pointers */ for (n = 0; n < a->size2 + 1; ++n) { if (a->p[n] != b->p[n]) return 0; } } else if (GSL_SPMATRIX_ISCRS(a)) { /* * for CRS, both matrices should have everything * in the same order */ /* check column indices and data */ for (n = 0; n < nz; ++n) { if ((a->i[n] != b->i[n]) || (a->data[n] != b->data[n])) return 0; } /* check row pointers */ for (n = 0; n < a->size1 + 1; ++n) { if (a->p[n] != b->p[n]) return 0; } } else { GSL_ERROR_VAL("unknown sparse matrix type", GSL_EINVAL, 0); } return 1; } } /* gsl_spmatrix_equal() */
{ "alphanum_fraction": 0.5133843212, "avg_line_length": 26.8205128205, "ext": "c", "hexsha": "50419a38121d6d0cf308d21db766714c7a2d77d8", "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": "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/spmatrix/spprop.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "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": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spprop.c", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/spmatrix/spprop.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 852, "size": 3138 }
/** * Copyright 2016 BitTorrent Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <scraps/config.h> #include <scraps/Temp.h> #include <scraps/type-traits.h> #include <scraps/utility.h> SCRAPS_IGNORE_WARNINGS_PUSH #include <gsl.h> SCRAPS_IGNORE_WARNINGS_POP #include <array> namespace scraps { /** * Convenience functions to create an std::array from a gsl::span */ template <typename T, std::ptrdiff_t ArraySize, template <typename, std::ptrdiff_t...> class Span> constexpr std::array<std::remove_cv_t<T>, ArraySize> ToArray(Span<T, ArraySize> span) { static_assert(ArraySize != gsl::dynamic_range, "Dynamic range spans are not allowed."); static_assert(ArraySize > 0, "ArraySize must be greater than 0"); std::array<std::remove_cv_t<T>, ArraySize> ret{}; std::copy(span.begin(), span.end(), ret.begin()); return ret; } template <typename T, std::ptrdiff_t ArraySize, template <typename, std::ptrdiff_t...> class Span> constexpr std::array<std::remove_cv_t<T>, ArraySize> ToArray(Temp<Span<T, ArraySize>> span) { return ToArray(static_cast<Span<T, ArraySize>>(span)); } template <typename T, size_t N> constexpr std::array<std::remove_cv_t<T>, N> ToArray(T (&arr)[N]) { std::array<std::remove_cv_t<T>, N> ret{}; std::copy(arr, arr + N, ret.begin()); return ret; } /** * Convenience type for defining a c-style array using the template parameters * of a std::array. */ template <typename ArrayT> using CArray = typename RemoveCVRType<ArrayT>::value_type[std::tuple_size<RemoveCVRType<ArrayT>>::value]; /** * Hashing struct suitable for using an std::array as the key in stl * associative containers such as unordered_map. */ struct ArrayHasher { template <typename T, size_t N> size_t operator()(const std::array<T, N>& arr) const { return HashRange(arr.begin(), arr.end()); } }; } // namespace scraps namespace std { template<typename T, size_t N> struct hash<std::array<T, N>> { size_t operator()(const std::array<T, N>& array) const { return scraps::ArrayHasher{}(array); } }; } // namespace std
{ "alphanum_fraction": 0.7026515152, "avg_line_length": 31.0588235294, "ext": "h", "hexsha": "05fe754da28c4e4291c910bfd3fbf32a4ef3c1c3", "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/array.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/array.h", "max_line_length": 105, "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/array.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 658, "size": 2640 }
/* multimin/fdfminimizer.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multimin.h> gsl_multimin_fdfminimizer * gsl_multimin_fdfminimizer_alloc (const gsl_multimin_fdfminimizer_type * T, size_t n) { int status; gsl_multimin_fdfminimizer *s = (gsl_multimin_fdfminimizer *) malloc (sizeof (gsl_multimin_fdfminimizer)); 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->gradient = gsl_vector_calloc (n); if (s->gradient == 0) { gsl_vector_free (s->x); free (s); GSL_ERROR_VAL ("failed to allocate space for gradient", GSL_ENOMEM, 0); } s->dx = gsl_vector_calloc (n); if (s->dx == 0) { gsl_vector_free (s->x); gsl_vector_free (s->gradient); free (s); GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0); } s->state = malloc (T->size); if (s->state == 0) { gsl_vector_free (s->x); gsl_vector_free (s->gradient); gsl_vector_free (s->dx); 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); gsl_vector_free (s->gradient); gsl_vector_free (s->dx); free (s); GSL_ERROR_VAL ("failed to initialize minimizer state", GSL_ENOMEM, 0); } return s; } int gsl_multimin_fdfminimizer_set (gsl_multimin_fdfminimizer * s, gsl_multimin_function_fdf * fdf, const gsl_vector * x, double step_size, double tol) { if (s->x->size != fdf->n) { GSL_ERROR ("function incompatible with solver size", GSL_EBADLEN); } if (x->size != fdf->n) { GSL_ERROR ("vector length not compatible with function", GSL_EBADLEN); } s->fdf = fdf; gsl_vector_memcpy (s->x,x); gsl_vector_set_zero (s->dx); return (s->type->set) (s->state, s->fdf, s->x, &(s->f), s->gradient, step_size, tol); } void gsl_multimin_fdfminimizer_free (gsl_multimin_fdfminimizer * s) { (s->type->free) (s->state); free (s->state); gsl_vector_free (s->dx); gsl_vector_free (s->gradient); gsl_vector_free (s->x); free (s); } int gsl_multimin_fdfminimizer_iterate (gsl_multimin_fdfminimizer * s) { return (s->type->iterate) (s->state, s->fdf, s->x, &(s->f), s->gradient, s->dx); } int gsl_multimin_fdfminimizer_restart (gsl_multimin_fdfminimizer * s) { return (s->type->restart) (s->state); } const char * gsl_multimin_fdfminimizer_name (const gsl_multimin_fdfminimizer * s) { return s->type->name; } gsl_vector * gsl_multimin_fdfminimizer_x (gsl_multimin_fdfminimizer * s) { return s->x; } gsl_vector * gsl_multimin_fdfminimizer_dx (gsl_multimin_fdfminimizer * s) { return s->dx; } gsl_vector * gsl_multimin_fdfminimizer_gradient (gsl_multimin_fdfminimizer * s) { return s->gradient; } double gsl_multimin_fdfminimizer_minimum (gsl_multimin_fdfminimizer * s) { return s->f; }
{ "alphanum_fraction": 0.6502087939, "avg_line_length": 23.3965517241, "ext": "c", "hexsha": "4029c375e9caa3353d8f3304163ed6b707161b24", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/multimin/fdfminimizer.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/multimin/fdfminimizer.c", "max_line_length": 87, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/multimin/fdfminimizer.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": 1219, "size": 4071 }
#ifndef __EXECUTE_PLUGIN_H__ #define __EXECUTE_PLUGIN_H__ #include <memory> #include <optional> #include <stdexcept> #include <string> #include <vector> #include <gsl/gsl> #include "config/commandLineOptions.h" #include "config/fleetingOptionsInterface.h" #include "config/pattern.h" #include "config/patternsHandler.h" #include "config/settingsNode.h" #include "plugin.h" namespace execHelper::plugins { using Plugins = std::map<std::string, std::shared_ptr<const Plugin>>; /** * \brief Exception thrown when the requested plugin is invalid * * Exception thrown when the requested plugin is invalid e.g. due to the fact that it can not be found */ struct InvalidPlugin : public std::runtime_error { public: /** * Create an invalid plugin * * \param[in] msg A message detailing the specifics of the exception */ inline explicit InvalidPlugin(const std::string& msg) : std::runtime_error(msg) {} /*! @copydoc InvalidPlugin(const std::string&) */ inline explicit InvalidPlugin(const char* msg) : std::runtime_error(msg) {} }; /** * \brief Plugin for executing arbitrary configured commands and/or plugins * * The ExecutePlugin handles the context of and calls all plugins. It uses the prototype pattern for retrieving a map of plugins it can call. */ class ExecutePlugin : public Plugin { public: /** * Create an executePlugin instance * * \param[in] commandsToExecute The commands to execute with this plugin * instance */ explicit ExecutePlugin( const config::CommandCollection& commandsToExecute) noexcept; /** * \param[in] commandsToExecute The commands to execute * \param[in] initialCommand The initial command that is being executed */ ExecutePlugin(const config::CommandCollection& commandsToExecute, const config::Command& initialCommand) noexcept; config::VariablesMap getVariablesMap(const config::FleetingOptionsInterface& fleetingOptions) const noexcept override; bool apply(core::Task task, const config::VariablesMap& variables, const config::Patterns& patterns) const noexcept override; std::string summary() const noexcept override; /** * Returns a list with the names of all known plugins * * @returns A list of plugin names */ static auto getPluginNames() noexcept -> std::vector<std::string>; /** * Returns an instance of the plugin associated with the given name * * \param[in] pluginName The plugin to get the associated instance from * \returns A pointer to the new instance * \throws InvalidPlugin When no plugin associated with the given pluginName is found */ static std::shared_ptr<const Plugin> getPlugin(const std::string& pluginName); /** * Push the given fleeting options on the stack * * \param[in] fleetingOptions The fleeting options to use. The last option * on the stack will be used for calling the commands. \returns True if * the options were successfully pushed False otherwise */ static bool push(gsl::not_null<const config::FleetingOptionsInterface*> fleetingOptions) noexcept; /** * Push the given settings node on the stack * * \param[in] settings The settings node to use. The last settings node on * the stack will be used for calling the commands. \returns True if the * settings node was successfully pushed False otherwise */ static bool push(config::SettingsNode&& settings) noexcept; /** * Push the given patterns on the stack * * \param[in] patterns The patterns to use. The last patterns on the stack * will be used for calling the commands. * \returns True if the patterns were successfully pushed * False otherwise */ static bool push(config::Patterns&& patterns) noexcept; /** * Push the plugin prototypes to the stack * * \param[in] plugins Mapping of discovered plugin prototypes */ static void push(Plugins&& plugins) noexcept; /** * Pop the last fleeting options from the stack * */ static void popFleetingOptions() noexcept; /** * Pop the last settings node from the stack */ static void popSettingsNode() noexcept; /** * Pop the last patterns from the stack */ static void popPatterns() noexcept; /** * Pop the last plugin prototypes from the stack */ static void popPlugins() noexcept; private: static auto getNextStep(const config::Command& command, const config::Command& originalCommand) noexcept -> std::shared_ptr<const Plugin>; static bool getVariablesMap(config::VariablesMap* variables, const std::vector<config::SettingsKeys>& keys, const config::SettingsNode& rootSettings) noexcept; static void index(config::VariablesMap* variables, const config::SettingsNode& settings, const config::SettingsKeys& key) noexcept; const config::CommandCollection m_commands; const config::CommandCollection m_initialCommands; static std::vector<gsl::not_null<const config::FleetingOptionsInterface*>> m_fleeting; static std::vector<config::SettingsNode> m_settings; static std::vector<config::PatternsHandler> m_patterns; static std::vector<Plugins> m_plugins; }; } // namespace execHelper::plugins #endif /* __EXECUTE_PLUGIN_H__ */
{ "alphanum_fraction": 0.6736542903, "avg_line_length": 32.726744186, "ext": "h", "hexsha": "b3f1ce5dcdb075c1b381919a06ac2d9a35d15a89", "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/executePlugin.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/executePlugin.h", "max_line_length": 141, "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/executePlugin.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": 1207, "size": 5629 }
/* roots/fdfsolver.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> gsl_root_fdfsolver * gsl_root_fdfsolver_alloc (const gsl_root_fdfsolver_type * T) { gsl_root_fdfsolver * s = (gsl_root_fdfsolver *) malloc (sizeof (gsl_root_fdfsolver)); if (s == 0) { GSL_ERROR_VAL ("failed to allocate space for root solver struct", GSL_ENOMEM, 0); }; s->state = malloc (T->size); if (s->state == 0) { free (s); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for root solver state", GSL_ENOMEM, 0); }; s->type = T ; s->fdf = NULL; return s; } int gsl_root_fdfsolver_set (gsl_root_fdfsolver * s, gsl_function_fdf * f, double root) { s->fdf = f; s->root = root; return (s->type->set) (s->state, s->fdf, &(s->root)); } int gsl_root_fdfsolver_iterate (gsl_root_fdfsolver * s) { return (s->type->iterate) (s->state, s->fdf, &(s->root)); } void gsl_root_fdfsolver_free (gsl_root_fdfsolver * s) { free (s->state); free (s); } const char * gsl_root_fdfsolver_name (const gsl_root_fdfsolver * s) { return s->type->name; } double gsl_root_fdfsolver_root (const gsl_root_fdfsolver * s) { return s->root; }
{ "alphanum_fraction": 0.6907066796, "avg_line_length": 23.2134831461, "ext": "c", "hexsha": "7f4146e48bc41b7f04e68da85c4fd95c24ee1df9", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/roots/fdfsolver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/roots/fdfsolver.c", "max_line_length": 87, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/roots/fdfsolver.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": 614, "size": 2066 }
/* * ----------------------------------------------------------------- * Pairwise Mixing Stirred Reaction Library --- pmsr_lib.h * Version: 1.6180 * Date: Nov 16, 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 the PMSR model. * ----------------------------------------------------------------- */ #ifndef __PMSR_LIB_H__ #define __PMSR_LIB_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> /* * ------------------------------------------------------------ * Types: struct pmsr, pmsr_wrk * ------------------------------------------------------------ * This structure contains fields of PMSR model. * * last update: Nov 5, 2009 * ------------------------------------------------------------ */ typedef struct pmsr { int *pmsr_idx; /* particles index vector */ gsl_vector **pmsr_ps; /* particle system */ } pmsr_wrk; /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * function prototypes *------------------------------------------------------------ */ void pmsr_title(); int pmsr_input(unsigned long int *seed, unsigned int *Np, unsigned int *K, double *t0, double *delta_t, double *tau_res, double *tau_mix, double *tau_pair, double *Tmax, double *Tmin); pmsr_wrk *pmsr_alloc(); int pmsr_init(int Np, int Neq, pmsr_wrk *pmsr); void pmsr_free(int Np, void **pmsr_bl); void pmsr_set_all(int Np, gsl_vector *phi, pmsr_wrk *pmsr); int pmsr_Nexc(int Np, double delta_t, double tau_res); int pmsr_Npair(int Np, double delta_t, double tau_pair); void pmsr_meanvar(int Np, int k, gsl_vector **ps, double *mean, double *var); void pmsr_mixture(int Np, int Neq, double delta_t, double tau_mix, int *idx, gsl_vector **ps); void pmsr_iops(int Np, int Nexc, int Npair, gsl_rng *r, gsl_vector *phi, pmsr_wrk *pmsr); #endif /* __PMSR_LIB_H__ */
{ "alphanum_fraction": 0.4534813926, "avg_line_length": 26.656, "ext": "h", "hexsha": "a6f4ccaba20e70bc4c39037b6cc344ffbc97bf35", "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/pmsr_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/pmsr_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/pmsr_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": 716, "size": 3332 }
/** * * @file example_dpotrf.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @brief Example of Cholesky factorization * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @generated d Tue Jan 7 11:45:20 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <time.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_dmain.h" static void GENMAT_SYM_FULL(int m, double *A) { srand48(time(NULL)); int j; for (j = 0; j < m; ++j ) { int i; for( i = j; i < m; ++i ) { double dran = drand48(); A[j*m+i] = A[i*m+j] = dran; } } for(j = 0; j < m; ++j) A[j*m+j] += 10 * m; } int testing_dspdsolv(int argc, char **argv) { int N = 4000; int LDA = 4000; int info_factorization; double *A = (double *)malloc(LDA*N*sizeof(double)); double *X = (double *)malloc(LDA*N*sizeof(double)); double *B = (double *)malloc(LDA*N*sizeof(double)); /* Check if unable to allocate memory */ if ((!A)||(!X)||(!B)){ fprintf(stderr, "Out of Memory \n "); return 0; } PLASMA_Set( PLASMA_RUNTIME_MODE, PLASMA_OMPSS); //Toggle runtime mdoe to OmpSs PLASMA_Set( PLASMA_TILE_SIZE, 384); //Set up tile size GENMAT_SYM_FULL(N, A); //Initialize A with a SPD matrix LAPACKE_dlarnv(IONE, ISEED, LDA*N, X); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, N, N, 1.0, A, LDA, X, LDA, 0.0, B, LDA); PLASMA_dpotrf(PlasmaLower, N, A, LDA); PLASMA_dtrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaNonUnit, N, N, 1.0, A, LDA, B, LDA); PLASMA_dtrsm(PlasmaLeft, PlasmaLower, PlasmaTrans, PlasmaNonUnit, N, N, 1.0, A, LDA, B, LDA); char infnorm = 'F'; double Normb = LAPACKE_dlange(LAPACK_COL_MAJOR, infnorm, N, N, B, LDA); double Normx = LAPACKE_dlange(LAPACK_COL_MAJOR, infnorm, N, N, X, LDA); printf("Residual= %e, norm(b): %e, norm(x): %e\n", fabs(Normb-Normx)/Normx, Normb, Normx); free(A); free(X); free(B); return 0; }
{ "alphanum_fraction": 0.6357243319, "avg_line_length": 25.0941176471, "ext": "c", "hexsha": "a618461c741ee887bb97fc3cf0c0978f18f488c6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_dspdsolv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_dspdsolv.c", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_dspdsolv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 769, "size": 2133 }
#pragma once #include <cstddef> #include <iostream> #include <limits> #include <cuda/define_specifiers.hpp> #include <cuda/runtime_api.hpp> #include <gsl-lite/gsl-lite.hpp> #include <cub/cub.cuh> #include <thrustshift/fill.h> #include <thrustshift/math.h> #include <thrustshift/not-a-vector.h> namespace thrustshift { namespace kernel { template <typename IndexT> __global__ void wrap_subgroups(gsl_lite::span<const IndexT> subgroup_ptrs, gsl_lite::span<IndexT> group_ptrs, IndexT mean_group_size) { const IndexT gtid = threadIdx.x + blockIdx.x * blockDim.x; const IndexT num_rows = subgroup_ptrs.size() - 1; const IndexT N = group_ptrs.size() - 1; if (gtid < num_rows) { const IndexT row_id = gtid; const IndexT curr_work = subgroup_ptrs[row_id + 1]; const IndexT prev_work = subgroup_ptrs[row_id]; const IndexT l = curr_work / mean_group_size; const IndexT m = prev_work / mean_group_size; if (prev_work != curr_work && l != 0 && (l != m) && l != N) { // only first thread is allowed to write to last element group_ptrs[l] = row_id + 1; } } if (gtid == 0) { group_ptrs[N] = num_rows; group_ptrs[0] = 0; } } } // namespace kernel namespace { template <typename StorageIndex> struct unequal_to_functor { StorageIndex x; CUDA_FD bool operator()(StorageIndex y) const { return y != x; } }; } // namespace namespace async { /*! \brief Wrap subsequent subgroups of varying size into groups. * * No subgroup can be part of two groups. Each subgroup can * contain a certain amount of elements (also no elements at all). This * function tries to wrap the subgroups into bigger groups of size `mean_group_size`. * This function is especially useful to distribute the work amongst CUDA thread blocks, * which operate on rows of a sparse matrix. If a single subgroup is larger than `mean_group_size` * the subgroup will form a group on its own, which is larger than `mean_group_size`. * The last group is rather larger than `mean_group_size` instead of creating one * group which is smaller than `mean_group_size`. * * \param stream CUDA stream. * \param subgroup_ptrs Array of length `num_subgroups + 1`. `subgroup_ptrs[i]` denotes * the index of the first element of subgroup `i`. `subgroup_ptrs[num_subgroups]` must * be equal to `num_elements`. * \param num_elements The sum of the sizes of all subgroups. * \param group_ptrs The result. `group_ptrs[k]` is the start subgroup ID of group `i`, whereas * `group_ptrs[k+1]` is the end subgroup ID of group `i`. Thus group `i` contains all subgroups * in range `[group_ptrs[k], group_ptrs[k+1])`. The last valid output * is `group_ptrs[*group_ptrs_size - 1] = subgroup_ptrs.size() - 1`. The maximum number of groups * is `num_elements / mean_group_size + 1`. The minimum number of groups is 2. Thus the buffer * of `group_ptrs` must be of size `max(num_elements / mean_group_size + 1, 2)`. * \param mean_group_size Intended group size, which is not always possible. E.g. if there * is only one subgroup, there can also be only one group. * \param group_ptrs_size Pointer to an element in GPU memory. After successful execution the * total number of groups is written to this variable. */ template <typename IndexT, class MemoryResource> void wrap_subgroups(cuda::stream_t& stream, gsl_lite::span<const IndexT> subgroup_ptrs, IndexT num_elements, gsl_lite::span<IndexT> group_ptrs, IndexT mean_group_size, gsl_lite::not_null<IndexT*> group_ptrs_size, MemoryResource& delayed_memory_resource) { constexpr cuda::grid::block_dimension_t block_dim = 128; if (subgroup_ptrs.size() < 2) { // There is not a single subgroup return; } if (gsl_lite::narrow<IndexT>(group_ptrs.size()) != std::max(num_elements / mean_group_size + 1, (IndexT) 2)) { std::cerr << "ERROR: group_ptrs buffer has wrong size! actual " "size = " << group_ptrs.size() << ", required size = max(num_elements / " "mean_group_size + 1, 2) = " << std::max(num_elements / mean_group_size + 1, 2) << std::endl; std::terminate(); } unequal_to_functor<IndexT> f({std::numeric_limits<IndexT>::max()}); gsl_lite::span<std::byte> tmp_storage; size_t tmp_storage_size = 0; auto enqueue_select_if = [&]() { cuda::throw_if_error(cub::DeviceSelect::If(tmp_storage.data(), tmp_storage_size, group_ptrs.data(), group_ptrs.data(), group_ptrs_size, group_ptrs.size(), f, stream.handle())); }; // set temporary memory size only enqueue_select_if(); auto tmp = make_not_a_vector<std::byte>(tmp_storage_size, delayed_memory_resource); tmp_storage = tmp.to_span(); fill(stream, group_ptrs, std::numeric_limits<IndexT>::max()); gsl_Expects(subgroup_ptrs.size() > 0); const IndexT num_rows = subgroup_ptrs.size() - 1; const IndexT grid_dim = ceil_divide(num_rows, gsl_lite::narrow<IndexT>(block_dim)); cuda::enqueue_launch(kernel::wrap_subgroups<IndexT>, stream, cuda::make_launch_config(grid_dim, block_dim), subgroup_ptrs, group_ptrs, mean_group_size); enqueue_select_if(); } } // namespace async } // namespace thrustshift
{ "alphanum_fraction": 0.6381134038, "avg_line_length": 36.5, "ext": "h", "hexsha": "ec4c9e7c89a72f1b57c59febd0b267700a2ea098", "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/wrap-subgroups.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_path": "include/thrustshift/wrap-subgroups.h", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_path": "include/thrustshift/wrap-subgroups.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1381, "size": 5767 }
#pragma once #include "utility/types.h" #include "utility/c++std/optional.h" #include <gsl/gsl> #include <vector> #include <string> namespace cws80 { enum class FileChooserMode { Open, Save, }; struct FileChooserFilter { const char *name; std::vector<const char *> patterns; }; class NativeUI { public: virtual ~NativeUI() {} static NativeUI *create(); virtual std::string choose_file(gsl::span<const FileChooserFilter> filters, const std::string &directory, const std::string &title, FileChooserMode mode) = 0; virtual cxx::optional<std::string> edit_line(const std::string &title, const std::string &initial_value) = 0; virtual uint select_by_menu(gsl::span<const std::string> choices, uint initial_selection) = 0; }; } // namespace cws80
{ "alphanum_fraction": 0.7070063694, "avg_line_length": 24.53125, "ext": "h", "hexsha": "2b714afcea3553b4eb8b877e7c849e7efc375bf8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_path": "sources/ui/detail/ui_helpers_native.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_path": "sources/ui/detail/ui_helpers_native.h", "max_line_length": 162, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_path": "sources/ui/detail/ui_helpers_native.h", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "num_tokens": 199, "size": 785 }
//====---- Sudoku/Location.h ----====// // // class Location: represent locations within a board, // and calculate location related properties. //====--------------------------------------------------------------------====// // // Everything is `constexpr` and `noexcept`. // All values are `const`. // // A separate Location_Block class offers block properties. // There is no implicit conversion between these. // //====--------------------------------------------------------------------====// #pragma once #include "Size.h" #include <gsl/gsl> // index #include <type_traits> // is_signed namespace Sudoku { template<int N> class Location { using Size = ::Sudoku::Size<N>; using index = gsl::index; // prefer signed integers for calculations static_assert(std::is_signed_v<decltype(Size::base)>); static_assert(std::is_signed_v<decltype(Size::elem)>); static constexpr gsl::index location(index row, index col) noexcept { return row * Size::elem + col; // [0,full) } public: // constructors constexpr Location() = default; explicit constexpr Location(index element) noexcept : id_(element) {} constexpr Location(index row, index col) noexcept : id_(location(row, col)) { } // information [[nodiscard]] constexpr index element() const noexcept { return id_; // default [0,full) } [[nodiscard]] constexpr index row() const noexcept { return id_ / Size::elem; //[0,elem) } [[nodiscard]] constexpr index col() const noexcept { return id_ % Size::elem; //[0,elem) } [[nodiscard]] constexpr index block() const noexcept { return row() / Size::base * Size::base + col() / Size::base; // [0,elem) } [[nodiscard]] constexpr index block_row() const noexcept { return row() % Size::base; // [0,base) } [[nodiscard]] constexpr index block_col() const noexcept { return col() % Size::base; // [0,base) } [[nodiscard]] constexpr index block_elem() const noexcept { return block_row() * Size::base + block_col(); // [0,elem) } // comparison friend constexpr bool operator==(const Location& a, const Location& b) noexcept { // Friend definitions: abseil.io/tips/99 return a.id_ == b.id_; } private: const index id_{}; }; //====--------------------------------------------------------------------====// template<int N> class Location_Block { using Size = ::Sudoku::Size<N>; using Location = ::Sudoku::Location<N>; // prefer signed integers for calculations static_assert(std::is_signed_v<decltype(Size::base)>); static constexpr gsl::index block_element(gsl::index row, gsl::index col) noexcept { return row * Size::base + col; // [0,elem) } static constexpr Location block_loc(gsl::index id, gsl::index element) noexcept { const gsl::index row{ (id / Size::base) * Size::base + element / Size::base}; const gsl::index col{ (id % Size::base) * Size::base + element % Size::base}; return Location(row, col); } static constexpr Location block_loc(gsl::index id, gsl::index row, gsl::index col) noexcept { return block_loc(id, block_element(row, col)); } public: constexpr Location_Block() = default; explicit constexpr Location_Block(Location loc) noexcept : loc_(loc) { // empty constructor } constexpr Location_Block(gsl::index id, gsl::index element) noexcept : loc_(block_loc(id, element)) { // empty constructor } constexpr Location_Block( gsl::index id, gsl::index row, gsl::index col) noexcept : loc_(block_loc(id, row, col)) { // empty constructor } [[nodiscard]] constexpr gsl::index id() const noexcept { return loc_.block(); // [0,elem) } [[nodiscard]] constexpr gsl::index element() const noexcept { return loc_.block_elem(); // [0,elem) } [[nodiscard]] constexpr gsl::index row() const noexcept { return loc_.block_row(); // [0,base) } [[nodiscard]] constexpr gsl::index col() const noexcept { return loc_.block_col(); // [0,base) } // [[implicit]] // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) constexpr operator Location() const noexcept { return loc_; } private: const Location loc_{}; }; //====--------------------------------------------------------------------====// // free-function declarations template<int N> constexpr bool operator==(const Location_Block<N>&, const Location_Block<N>&) noexcept; template<int N> constexpr bool operator==(const Location<N>&, const Location_Block<N>&) noexcept; template<int N> constexpr bool operator==(const Location_Block<N>&, const Location<N>&) noexcept; template<int N, typename typeB> constexpr bool operator!=(const Location<N>&, const typeB&) noexcept; template<int N, typename typeB> constexpr bool operator!=(const Location_Block<N>&, const typeB&) noexcept; template<int N> constexpr bool operator<(const Location<N>&, const Location<N>&) noexcept; template<int N> constexpr bool operator<(const Location_Block<N>&, const Location_Block<N>&) noexcept; template<int N> constexpr bool operator<=(const Location<N>&, const Location<N>&) noexcept; template<int N> constexpr bool operator<=(const Location_Block<N>&, const Location_Block<N>&) noexcept; template<int N> constexpr bool operator>=(const Location<N>&, const Location<N>&) noexcept; template<int N> constexpr bool operator>=(const Location_Block<N>&, const Location_Block<N>&) noexcept; template<int N> constexpr bool operator>(const Location<N>&, const Location<N>&) noexcept; template<int N> constexpr bool operator>(const Location_Block<N>&, const Location_Block<N>&) noexcept; //====--------------------------------------------------------------------====// // definitions template<int N> constexpr bool operator==( const Location_Block<N>& left, const Location_Block<N>& right) noexcept { return Location<N>{left} == Location<N>{right}; } template<int N> constexpr bool operator==(const Location_Block<N>& block, const Location<N>& loc) noexcept { return Location<N>{block} == loc; } template<int N> inline constexpr bool operator==(const Location<N>& loc, const Location_Block<N>& block) noexcept { return block == loc; } template<int N, typename typeB> inline constexpr bool operator!=(const Location<N>& left, const typeB& right) noexcept { static_assert( std::is_same_v<Location<N>, typeB> || std::is_same_v<Location_Block<N>, typeB>); return !(left == right); } template<int N, typename typeB> inline constexpr bool operator!=(const Location_Block<N>& left, const typeB& right) noexcept { static_assert( std::is_same_v<Location<N>, typeB> || std::is_same_v<Location_Block<N>, typeB>); return !(left == right); } template<int N> constexpr bool operator<(const Location<N>& left, const Location<N>& right) noexcept { return left.element() < right.element(); } template<int N> constexpr bool operator<=(const Location<N>& left, const Location<N>& right) noexcept { return left.element() <= right.element(); } template<int N> constexpr bool operator>=(const Location<N>& left, const Location<N>& right) noexcept { return left.element() >= right.element(); } template<int N> constexpr bool operator>(const Location<N>& left, const Location<N>& right) noexcept { return left.element() > right.element(); } // Sorted by block first. template<int N> constexpr bool operator<( const Location_Block<N>& left, const Location_Block<N>& right) noexcept { return (left.id() == right.id()) ? (left.element() < right.element()) : left.id() < right.id(); } template<int N> constexpr bool operator<=( const Location_Block<N>& left, const Location_Block<N>& right) noexcept { return (left.id() == right.id()) ? (left.element() <= right.element()) : left.id() < right.id(); } template<int N> constexpr bool operator>=( const Location_Block<N>& left, const Location_Block<N>& right) noexcept { return (left.id() == right.id()) ? (left.element() >= right.element()) : left.id() > right.id(); } template<int N> constexpr bool operator>( const Location_Block<N>& left, const Location_Block<N>& right) noexcept { return (left.id() == right.id()) ? (left.element() > right.element()) : left.id() > right.id(); } } // namespace Sudoku
{ "alphanum_fraction": 0.6595170977, "avg_line_length": 26.7508196721, "ext": "h", "hexsha": "36c838817a2c7ffda833a5667b237c452ea37a9d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z", "max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_path": "Sudoku/Sudoku/Location.h", "max_issues_count": 38, "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "FeodorFitsner/fwkSudoku", "max_issues_repo_path": "Sudoku/Sudoku/Location.h", "max_line_length": 80, "max_stars_count": 2, "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_path": "Sudoku/Sudoku/Location.h", "max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z", "num_tokens": 1935, "size": 8159 }
/* permutation/gsl_permutation.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_PERMUTATION_H__ #define __GSL_PERMUTATION_H__ #include <stdlib.h> #include <gsl/gsl_errno.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 struct gsl_permutation_struct { size_t size; size_t *data; }; typedef struct gsl_permutation_struct gsl_permutation; gsl_permutation *gsl_permutation_alloc (const size_t n); gsl_permutation *gsl_permutation_calloc (const size_t n); void gsl_permutation_init (gsl_permutation * p); void gsl_permutation_free (gsl_permutation * p); int gsl_permutation_fread (FILE * stream, gsl_permutation * p); int gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p); int gsl_permutation_fscanf (FILE * stream, gsl_permutation * p); int gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format); size_t gsl_permutation_size (const gsl_permutation * p); size_t * gsl_permutation_data (const gsl_permutation * p); size_t gsl_permutation_get (const gsl_permutation * p, const size_t i); int gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j); int gsl_permutation_valid (gsl_permutation * p); void gsl_permutation_reverse (gsl_permutation * p); int gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p); int gsl_permutation_next (gsl_permutation * p); int gsl_permutation_prev (gsl_permutation * p); extern int gsl_check_range; #ifdef HAVE_INLINE extern inline size_t gsl_permutation_get (const gsl_permutation * p, const size_t i) { #ifndef GSL_RANGE_CHECK_OFF if (i >= p->size) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return p->data[i]; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_PERMUTATION_H__ */
{ "alphanum_fraction": 0.7651031895, "avg_line_length": 29.6111111111, "ext": "h", "hexsha": "6f3a413c157afc869156b6b0a86980bbd34eee61", "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/permutation/gsl_permutation.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/permutation/gsl_permutation.h", "max_line_length": 91, "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/permutation/gsl_permutation.h", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 695, "size": 2665 }
/*This program evaluates the differential equations for a photon's geodesic in a FRW perturbed spacetime in SPHERICAL coordinates and restricted to photon RADIAL MOTION only.*/ /*This program solves the particular case for flat FRW perturbed spacetime with metric: $g_{ab} = {[g]}_{ab} + h_{ab}$. Where ${[g]}_{ab}$ corresponds to the flat FRW metric and $h_{ab}$ corresponds to the perturbation in the conformal Newtonian gauge. A Plummer potential or a Hernquist potential with adequate parameters can be used to simulate the perturbation. The equations are written in the form $\frac{d(x or p)^{\alpha}}{d\lambda}=f(x^{\alpha},p^{\alpha})$ and the indice $\alpha$ runs from 0 to 1 since the motion is only radial. Where $p^{\alpha}={\dot{x}}^{\alpha}$. The coordinates for the photon's geodesics are then: (ct,r) = (x0,x1).*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> //GSL error management module #include <gsl/gsl_spline.h> //GSL interpolation module /* PHYSICAL CONSTANTS AND PARAMETERS */ #define A 10.0 //Distance parameter of the perturbations #define G 43007.01 //Gravitational constant #define M 15000.0 //Mass of the perturbation #define C 299792.458 //Speed of light #define GAMMA 0.8 //Parameter for halo mass evolution /* PROGRAM PARAMETERS */ #define NLINES 100000 //Number of lines in geodesic_solution.dat file #define NSTEPS 600000000 //Number of steps for solving geodesics #define NLINESFRW 10000 //Number of lines in frw.dat file #define DLAMBDA 0.01 //Geodesics parameter step typedef long double mydbl; /*Interpolation of function inside *spline object evaluated at an abscisa 'x'. Argument *spline is a pointer to a spline object which stores the type of interpolation to be made. x is the independent variable where the function is evaluated. *acc is a pointer to a lookup object for interpolations.*/ double interpolator(gsl_spline *spline, double x, gsl_interp_accel *acc) { double a = gsl_spline_eval(spline, x, acc); //Interpolates data to abcisa x using method in spline and acceleration object acc return a; //Return value of interpolated function at x } /*Mass evolution. Function providing the mass at a given z. Mass at present time is obtained at z=0.*/ mydbl mass(mydbl a) { mydbl z = 1.0/a - 1.0; return M*expl(-GAMMA*z); } /*Plummer model. Provided two variables pointers, this function stores the potential and the derivative of the potential for the Plummer model in these variables at a given radius.*/ void plummer_model(mydbl a, mydbl adot, mydbl r, mydbl *potential, mydbl *der_potential_radial, mydbl *der_potential_temporal) { *potential = -G*mass(a)/(sqrtl(A*A + r*r)); *der_potential_radial = G*mass(a)*r/(powl(A*A+r*r, 1.5)); *der_potential_temporal = *potential*GAMMA*adot/(a*a); } /*Hernquist model. Provided two variables pointers, this function stores the potential and the derivative of the potential for the Hernquist model in these variables at a given radius.*/ void hernquist_model(mydbl a, mydbl adot, mydbl r, mydbl *potential, mydbl *der_potential_radial, mydbl *der_potential_temporal) { double rsign = copysign(1.0,(double)(1.0*r)); mydbl absr = fabsl(r); if(absr > 2000.0) { *potential = 0.0; *der_potential_radial = 0.0; *der_potential_temporal = 0.0; } else if(rsign == -1.0) { *potential = -G*mass(a)/(A + absr); *der_potential_radial = -G*mass(a)/powl(absr+A,2.0); *der_potential_temporal = *potential*GAMMA*adot/(a*a); } else if(rsign == 1.0) { *potential = -G*mass(a)/(A + absr); *der_potential_radial = G*mass(a)/powl(absr+A,2.0); *der_potential_temporal = *potential*GAMMA*adot/(a*a); } } /*Function of the 0th momentum component differential equation for the geodesics. ${p0}^{dot} = f0(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_0(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *)) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl potential, der_potential_radial, der_potential_temporal; (*model)(a, adot, r, &potential, &der_potential_radial, &der_potential_temporal); mydbl f = -2.0*p0*(der_potential_temporal*p0/C + der_potential_radial*pr)/(C*C + 2.0*potential) + der_potential_temporal*(p0*p0 + a*a*pr*pr)/(C*C*C) - (1.0 - 2.0*potential/(C*C))*(a*adot)*(pr*pr)/(C + 2.0*potential/C); return f; } /*Function of the 1th (radial) momentum component differential equation for the geodesics. ${p1}^{dot} = f1(x^{\alpha},p^{\alpha})$.*/ mydbl geodesic_equation_r(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *)) { double t = (double)(1.0*x0/C); mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1); mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2); mydbl potential, der_potential_radial, der_potential_temporal; (*model)(a, adot, r, &potential, &der_potential_radial, &der_potential_temporal); mydbl f = - (der_potential_radial*p0*p0)/(a*a*(C*C - 2.0*potential)) - (2.0*adot*p0*pr)/(C*a) + der_potential_radial*(pr*pr)/(C*C - 2.0*potential) + 2.0*der_potential_temporal*p0*pr/(a*a*C*(C*C - 2.0*potential)); return f; } /*Function for solving the geodesics differential equations using 4th order Runge-Kutta method. Arguments are pointer so variables in that memory addresses are changed every time this function is called.*/ void runge_kutta_4(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl *x0, mydbl *x1, mydbl *p0, mydbl *p1, mydbl *lambda, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *)) { /*Increment in the variables of the differential equation we want to solve*/ mydbl dx0, dx1, dp0, dp1; /*dxi = (k1,j + 2*k2,j + 2*k3,j + k4,j)/6. In this sections the ki,j are declared with i=1,2,3,4.*/ mydbl k1x0, k1x1, k1p0, k1p1; mydbl k2x0, k2x1, k2p0, k2p1; mydbl k3x0, k3x1, k3p0, k3p1; mydbl k4x0, k4x1, k4p0, k4p1; /*This section calculates the k1 quantities*/ k1x0 = *p0*DLAMBDA; k1x1 = *p1*DLAMBDA; k1p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1, (*model)); k1p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1, (*model)); /*This section calculates the k2 quantities*/ k2x0 = DLAMBDA*(*p0 + 0.5*k1p0); k2x1 = DLAMBDA*(*p1 + 0.5*k1p1); k2p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, (*model)); k2p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, (*model)); /*This section calculates the k3 quantities*/ k3x0 = DLAMBDA*(*p0 + 0.5*k2p0); k3x1 = DLAMBDA*(*p1 + 0.5*k2p1); k3p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, (*model)); k3p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, (*model)); /*This section calculates the k4 quantities*/ k4x0 = DLAMBDA*(*p0 + k3p0); k4x1 = DLAMBDA*(*p1 + k3p1); k4p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *x0 + k3x0, *x1 + k3x1, (*model)); k4p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *x0 + k3x0, *x1 + k3x1, (*model)); /*Calculation of the increments*/ dx0 = (k1x0 + 2.0*k2x0 + 2.0*k3x0 + k4x0)/6.0; dx1 = (k1x1 + 2.0*k2x1 + 2.0*k3x1 + k4x1)/6.0; dp0 = (k1p0 + 2.0*k2p0 + 2.0*k3p0 + k4p0)/6.0; dp1 = (k1p1 + 2.0*k2p1 + 2.0*k3p1 + k4p1)/6.0; /*New values of the variables of the differential equation. Since we are using pointers, when called the routine the value of variable change.*/ *x0 = *x0 + dx0; *x1 = *x1 + dx1; *p0 = *p0 + dp0; *p1 = *p1 + dp1; /*Increment of parameter of geodesics*/ *lambda = *lambda + DLAMBDA; } /*To set the initial value of pr, it must hold $g_{\mu\nu}p^{\mu}p^{\nu} = 0$. This factor multiplies p0 to guarantee that p1 fulfill the null geodesic condition.*/ mydbl condition_factor(mydbl r, double a, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *)) { mydbl potential, der_potential_radial, der_potential_temporal; (*model)((mydbl)(1.0*a), 0.0, r, &potential, &der_potential_radial, &der_potential_temporal); return (mydbl)(1.0/a)*sqrtl((C*C + 2.0*potential)/(C*C - 2.0*potential)); } /*$cp^{0}$ multiplied by this factor allows to obtain the energy for a local inertial observer in this spacetime.*/ mydbl energy_factor(mydbl r, double a, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *)) { mydbl potential, der_potential_radial, der_potential_temporal; (*model)((mydbl)(1.0*a), 0.0, r, &potential, &der_potential_radial, &der_potential_temporal); mydbl g = sqrtl(1.0 + 2.0*potential/(C*C)); return g; } /*Violation of null geodesics condition $g_{\mu\nu}p^{\mu}p^{\nu} = 0$.*/ mydbl violation(mydbl r, mydbl p0, mydbl pr, double a, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *)) { mydbl potential, der_potential_radial, der_potential_temporal; (*model)((mydbl)(1.0*a), 0.0, r, &potential, &der_potential_radial, &der_potential_temporal); mydbl f = -(1.0+2.0*potential/(C*C))*p0*p0 + (mydbl)(1.0*a*a)*(1.0-2.0*potential/(C*C))*pr*pr; return f; } int main(void) { /***READ SCALE FACTOR DATA AND PREPARE OBJECTS FOR INTERPOLATION ***/ int i; //For array manipulation /*Pointer to scale_factor.data file*/ FILE *frw; frw = fopen("../scale_factor.dat","r"); /*Variables and arrays to read the data*/ double cosmictime[NLINESFRW], conftime, scale_factor[NLINESFRW], der_scale_factor[NLINESFRW]; /*Reading the data*/ for(i=0; i<NLINESFRW; i++) { fscanf(frw,"%lf %lf %lf %lf", &cosmictime[i], &conftime, &scale_factor[i], &der_scale_factor[i]); } /*Free space in memory*/ fclose(frw); /*** Initializes objects for interpolation. 1 is for interpolation of scale factor, 2 is for interpolation of derivative of scale factor ***/ /*Allocate space in memory*/ gsl_interp_accel *acc1 = gsl_interp_accel_alloc(); //Acceleration type object (for index lookup) gsl_interp_accel *acc2 = gsl_interp_accel_alloc(); gsl_spline *spline1 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW); //Spline type object (define interpolation type and space in memory, works for both) gsl_spline *spline2 = gsl_spline_alloc(gsl_interp_cspline, NLINESFRW); /*Initializes objects for interpolation*/ gsl_spline_init(spline1, cosmictime, scale_factor, NLINESFRW); //Initializes spline object for data cosmictime, scale_factor of size NLINES gsl_spline_init(spline2, cosmictime, der_scale_factor, NLINESFRW); //Initializes spline object for data cosmictime, der_scale_factor of size NLINES /************************************************************************************/ /***SOLVES GEODESIC EQUATIONS FOR PERTURBED FRW UNIVERSE WITH A GIVEN POTENTIAL MODEL ***/ /*Choose model to use for solving geodesics*/ void (*model_in_use)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *); model_in_use = hernquist_model; /*Initial conditions*/ mydbl ti = 9.0 ,x0, r = -3000.0, p0 = 1.0e-3, pr, lambda = 0.0, energy1, energy, v, difft, difference, pfrw, isw; double difftfrw, aem, aobs; x0 = C*ti; aem = interpolator(spline1, (double)(1.0*ti), acc1); pr = condition_factor(r, aem, model_in_use)*p0; energy1 = C*energy_factor(r, aem, model_in_use)*p0; v = violation(r, p0, pr, aem, model_in_use); difft = (energy1 - energy1)/energy1; difftfrw = (aem/aem) - 1.0; difference = difft - (mydbl)(1.0*difftfrw); pfrw = ((mydbl)(1.0*aem)*1.0e-03/((mydbl)(1.0*aem))); isw = p0/pfrw - 1.0; /*Pointer to file where solution of differential equation will be saved.*/ FILE *geodesic; geodesic = fopen("geodesic_solution.dat","w"); /*Write line of initial values in file*/ fprintf(geodesic, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le %16.8Le\n", lambda, x0, r, p0, pr, energy1, v, difft, difftfrw, difference, isw); long long int ii; /*Solution of the differential equation*/ for(ii=0; ii< NSTEPS; ii++) { runge_kutta_4(spline1, acc1, spline2, acc2, &x0, &r, &p0, &pr, &lambda, model_in_use); if((ii%(NSTEPS/NLINES)) == 0) { ti = x0/C; aobs = interpolator(spline1, (double)(1.0*ti), acc1); energy = C*energy_factor(r, aobs, model_in_use)*p0; v = violation(r, p0, pr, aobs, model_in_use); difft = (energy - energy1)/energy1; difftfrw = (aem/aobs) - 1.0; difference = difft - (mydbl)(1.0*difftfrw); pfrw = (mydbl)(1.0*aem)*1.0e-03/((mydbl)(1.0*aobs)); isw = p0/pfrw - 1.0; fprintf(geodesic, "%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le %16.8Le\n", lambda, x0, r, p0, pr, energy, v, difft, difftfrw, difference, isw); } } /************************************************************************************/ /*** Releasing all used space in memory ***/ fclose(geodesic); //Close file storing the results gsl_spline_free(spline1); //Free memory of spline object gsl_spline_free(spline2); gsl_interp_accel_free(acc1); //Free memory of accel object gsl_interp_accel_free(acc2); }
{ "alphanum_fraction": 0.6802342606, "avg_line_length": 50.780669145, "ext": "c", "hexsha": "deda15df223363a42ec8b763a77d0d472aa64382", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_forks_repo_path": "frw/frw_perturbed_spherical_radial_motion.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_issues_repo_issues_event_max_datetime": "2016-09-19T20:33:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-26T05:36:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_issues_repo_path": "frw/frw_perturbed_spherical_radial_motion.c", "max_line_length": 364, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_stars_repo_path": "frw/frw_perturbed_spherical_radial_motion.c", "max_stars_repo_stars_event_max_datetime": "2015-10-21T03:59:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-21T03:59:02.000Z", "num_tokens": 4879, "size": 13660 }
#ifndef __REGIONAL_H_ #define __REGIONAL_H_ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "defs.h" typedef struct stochasticity_grid { t_float *arr; int height, width; double weight_factor; double stddev; double mean; int depth; gsl_rng *rng; double *weights; } t_stochasticity_grid; t_stochasticity_grid *create_stochasticity_grid(t_float *arr, int height, int width, double weight_factor, double mean, double stddev, long int seed); void free_stochasticity_grid(t_stochasticity_grid *g); void generate_stochasticity(t_stochasticity_grid *g); #endif /* __REGIONAL_H_ */
{ "alphanum_fraction": 0.7596153846, "avg_line_length": 26, "ext": "h", "hexsha": "5d624260e45ec9e21a8ce6b3df59235225467886", "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": "77b6e1abf72421d6268f5aa865559b134965d070", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rybicki/corridor-spom", "max_forks_repo_path": "active/spom/model/src/regional.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "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": "rybicki/corridor-spom", "max_issues_repo_path": "active/spom/model/src/regional.h", "max_line_length": 150, "max_stars_count": null, "max_stars_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rybicki/corridor-spom", "max_stars_repo_path": "active/spom/model/src/regional.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 160, "size": 624 }
#pragma once #include <vector> #include <algorithm> #include <gsl/gsl.h> #include "utils/linear_algebra.h" namespace util{ namespace math{ template<typename T, int64_t dim_1> struct VecLoop_void{ template<typename OP, typename... Args> void operator()(OP const&fun, Args&&... args) const { #pragma clang loop vectorize(enable) for(int64_t i=0; i<dim_1; ++i){ fun(i, std::forward<Args>(args)...); } } }; template<typename T, int64_t dim_1> struct VecLoop_vec{ template<typename OP, typename... Args> auto operator()(OP const&fun, Args&&... args) const { util::math::Vector<T,dim_1> result{}; #pragma clang loop vectorize(enable) for(int64_t i=0; i<dim_1; ++i){ result.span[i]=fun(i, std::forward<Args>(args)...); } return result; } }; template<typename T, int64_t dim_1, int64_t dim_2> struct MatLoop_mat{ template<typename OP, typename... Args> void operator()(OP const&fun, Args&&... args) const { util::math::Matrix<T,dim_1,dim_2> result{}; for(int64_t i=0; i<dim_1; ++i){ for(int64_t j=0; j<dim_2; ++j){ result.span[i][j]=fun(i,j, std::forward<Args>(args)...); } } } }; template<typename T, int64_t dim_1, int64_t dim_2> struct MatLoop_void{ template<typename OP, typename... Args> void operator()(OP const&fun, Args&&... args) const { for(int64_t i=0; i<dim_1; ++i){ for(int64_t j=0; j<dim_2; ++j){ fun(i,j, std::forward<Args>(args)...); } } } }; }//namespace util::math }//namespace util namespace gsl{ auto add_assign_vec=[](int64_t i, auto &out, auto const & x) { out[i]+=x[i]; }; auto sub_assign_vec=[](int64_t i, auto &out, auto const & x) { out[i]-=x[i]; }; auto mul_assign_vec=[](int64_t i, auto &out, auto x) { out[i]*=x; }; auto add_assign_mat=[](int64_t i,int64_t j, auto &out, auto const & x) { out[i][j]+=x[i][j]; }; auto sub_assign_mat=[](int64_t i,int64_t j, auto &out, auto const & x) { out[i][j]-=x[i][j]; }; auto mul_assign_mat=[](int64_t i,int64_t j, auto &out, auto x) { out[i][j]*=x; }; template<typename T, int64_t M> span<T,M>& operator +=(span<T,M>& out, const span<T,M>& x){ auto vecloop_void=util::math::VecLoop_void<T,M>{}; vecloop_void(add_assign_vec, out, x); return out; } template<typename T, int64_t M> span<T,M>& operator -=(span<T,M>& out, const span<T,M>& x){ auto vecloop_void=util::math::VecLoop_void<T,M>{}; vecloop_void(sub_assign_vec, out, x); return out; } template<typename T, int64_t M> span<T,M>& operator *=(span<T,M>& out, T x){ auto vecloop_void=util::math::VecLoop_void<T,M>{}; vecloop_void(mul_assign_vec, out, x); return out; } template<typename T, int64_t M, int64_t N> span<T,M,N>& operator +=(span<T,M,N>& out, const span<T,M,N>& x){ auto matloop_void=util::math::MatLoop_void<T,M,N>{}; matloop_void(add_assign_mat, out, x); return out; } template<typename T, int64_t M, int64_t N> span<T,M,N>& operator -=(span<T,M,N>& out, const span<T,M,N>& x){ auto matloop_void=util::math::MatLoop_void<T,M,N>{}; matloop_void(sub_assign_mat, out, x); return out; } template<typename T, int64_t M, int64_t N> span<T,M,N>& operator *=(span<T,M,N>& out, T x){ auto matloop_void=util::math::MatLoop_void<T,M,N>{}; matloop_void(mul_assign_mat, out, x); return out; } auto grad_update_mat=[](int64_t i,int64_t j, auto &param, auto const &grad, auto scale) { param[i][j] += scale*grad[i][j]; }; auto grad_update_vec=[](int64_t i, auto &param, auto const &grad, auto scale) { param[i] += scale*grad[i]; }; template<typename T, int64_t M, int64_t N> void grad_update(span<T,M,N>& param, span<T,M,N> const &grad, T scale){ auto matloop_void=util::math::MatLoop_void<T,M,N>{}; matloop_void(grad_update_mat, param, grad, scale); } template<typename T, int64_t M> void grad_update(span<T,M>& param, span<T,M> const &grad, T scale){ auto vecloop_void=util::math::VecLoop_void<T,M>{}; vecloop_void(grad_update_vec, param, grad, scale); } }//namespace gsl
{ "alphanum_fraction": 0.61496695, "avg_line_length": 29.2137931034, "ext": "h", "hexsha": "d4c5165fe6670e4bf8ae949b2afc39ce8ea11666", "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": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "uphere-co/nlp-prototype", "max_forks_repo_path": "rnn++/utils/loop_gen.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "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": "uphere-co/nlp-prototype", "max_issues_repo_path": "rnn++/utils/loop_gen.h", "max_line_length": 72, "max_stars_count": null, "max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "uphere-co/nlp-prototype", "max_stars_repo_path": "rnn++/utils/loop_gen.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1275, "size": 4236 }
// // Created by daeyun on 4/11/17. // #pragma once #ifndef NDEBUG #define USE_OMP false #else #define USE_OMP true #endif #include <iostream> #include <limits> #include <cstdlib> #include <vector> #include <array> #include <string> #include <map> #include <set> #include <memory> #include <gsl/gsl_assert> #include <Eigen/Dense> #include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_color_sinks.h" using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::Dynamic; using Vec = Eigen::VectorXd; using Vec2 = Eigen::Vector2d; using Vec2i = Eigen::Matrix<int, 2, 1>; using Vec3 = Eigen::Vector3d; using Vec4 = Eigen::Vector4d; using Mat44 = Eigen::Matrix<double, 4, 4>; using Mat34 = Eigen::Matrix<double, 3, 4>; using Mat33 = Eigen::Matrix<double, 3, 3>; using MatrixX = Eigen::MatrixXd; using Points4d = Eigen::Matrix<double, 4, Eigen::Dynamic>; using Points3d = Eigen::Matrix<double, 3, Eigen::Dynamic>; using Points2d = Eigen::Matrix<double, 2, Eigen::Dynamic>; using Points2i = Eigen::Matrix<int, 2, Eigen::Dynamic>; using Points1d = Eigen::Matrix<double, 1, Eigen::Dynamic>; using std::vector; using std::array; using std::string; using std::unique_ptr; using std::shared_ptr; using std::make_unique; using std::make_shared; using std::move; using std::tuple; using std::pair; using std::map; using std::set; using std::get; constexpr double kInfinity = std::numeric_limits<double>::infinity(); constexpr double kOneOverTwoPi = M_1_PI * 0.5; constexpr double kEpsilon = 1e-9; constexpr double kDeg2Rad = M_PI / 180.0; // Make sure to have the following in the executable: spdlog::stdout_color_mt("console"); #define LOGGER spdlog::get("console")
{ "alphanum_fraction": 0.729843562, "avg_line_length": 24.0869565217, "ext": "h", "hexsha": "dd2a83f400570c0e664675511dac45c47a07d27c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-26T13:53:00.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-26T13:53:00.000Z", "max_forks_repo_head_hexsha": "a26a92923f1371914b8e73635c9e9da45839dd73", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "daeyun/mesh_to_depth", "max_forks_repo_path": "cpp/lib/common.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "a26a92923f1371914b8e73635c9e9da45839dd73", "max_issues_repo_issues_event_max_datetime": "2021-04-26T16:16:40.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-26T13:52:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "daeyun/mesh_to_depth", "max_issues_repo_path": "cpp/lib/common.h", "max_line_length": 89, "max_stars_count": 12, "max_stars_repo_head_hexsha": "a26a92923f1371914b8e73635c9e9da45839dd73", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "daeyun/mesh_to_depth", "max_stars_repo_path": "cpp/lib/common.h", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:11:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-21T05:32:29.000Z", "num_tokens": 472, "size": 1662 }
/* CUDA speed test without the memory overhead gcc-mp-4.8 -O3 cudadgemmtest.c common.c -o cudadgemmtest -I../../../../netlib/CBLAS -I/usr/local/cuda/include/ -L/usr/local/cuda/lib -lcublas export DYLD_LIBRARY_PATH=/usr/local/cuda/lib ./cudadgemmtest > ../../../results/mac_os_x-x86_64-dgemm-cuda_nooh.csv */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <cblas.h> #include "common.h" #include <cublas.h> // does AB == C ? If not, complain on stderr void test(int m, double* a, double *b, double *c) { int i, j, k, exact = 0, wrong = 0; double diff; double* d = calloc(m * m, sizeof(double)); for (i = 0 ; i < m ; i++) { for (j = 0 ; j < m ; j++) { for (k = 0 ; k < m ; k++) { d[i + j * m] += a[i + k * m] * b[j * m + k]; } } } for (i = 0 ; i < m ; i++) { for (j = 0 ; j < m ; j++) { diff = c[i * m + j] - d[i * m + j]; if (diff != 0.0) { exact++; } if (abs(diff) > 0.000001) { wrong++; } } } free(d); if (wrong > 0) { fprintf(stderr, "not exact = %d, wrong = %d\n", exact, wrong); } } void checkStatus(char* message, cublasStatus status) { if (status != CUBLAS_STATUS_SUCCESS) { fprintf (stderr, "!!!! %s fail %d\n", message, status); exit(EXIT_FAILURE); } } long benchmark(int size) { int m = sqrt(size); long requestStart, requestEnd; double* a = random_array(m * m); double* b = random_array(m * m); double* c = calloc(m * m, sizeof(double)); double *cuA, *cuB, *cuC; cublasStatus status; status = cublasAlloc(m * m, sizeof(double),(void**)&cuA); checkStatus("A", status); status = cublasAlloc(m * m, sizeof(double),(void**)&cuB); checkStatus("B", status); status = cublasAlloc(m * m, sizeof(double),(void**)&cuC); checkStatus("C", status); status = cublasSetMatrix(m, m, sizeof(double), a, m, cuA, m); checkStatus("setA", status); status = cublasSetMatrix(m, m, sizeof(double), b, m, cuB, m); checkStatus("setB", status); requestStart = currentTimeNanos(); cublasDgemm('N', 'N', m, m, m, 1, cuA, m, cuB, m, 0, cuC, m); requestEnd = currentTimeNanos(); status = cublasGetMatrix(m, m, sizeof(double), cuC, m, c, m); checkStatus("setB", status); status = cublasFree(cuA); checkStatus("freeA", status); status = cublasFree(cuB); checkStatus("freeB", status); status = cublasFree(cuC); checkStatus("freeC", status); #ifdef __TEST__ test(m, a, b, c); #endif free(a); free(b); free(c); return (requestEnd - requestStart); } main() { cublasStatus status; srand(time(NULL)); status = cublasInit(); checkStatus("init", status); double factor = 6.0 / 100.0; int i, j; for (i = 0 ; i < 10 ; i++) { for (j = 1 ; j <= 100 ; j++) { int size = (int) pow(10.0, factor * j); if (size < 10) continue; long took = benchmark(size); printf("\"%d\",\"%lu\"\n", size, took); fflush(stdout); } } }
{ "alphanum_fraction": 0.5724465558, "avg_line_length": 23.2047244094, "ext": "c", "hexsha": "b100e772bd602325aa0eaadbcbbc9044c86014bc", "lang": "C", "max_forks_count": 154, "max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z", "max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "debasish83/netlib-java", "max_forks_repo_path": "perf/src/main/c/cudadgemmtest.c", "max_issues_count": 59, "max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "debasish83/netlib-java", "max_issues_repo_path": "perf/src/main/c/cudadgemmtest.c", "max_line_length": 141, "max_stars_count": 624, "max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "debasish83/netlib-java", "max_stars_repo_path": "perf/src/main/c/cudadgemmtest.c", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z", "num_tokens": 970, "size": 2947 }
static char help[] = "Solves the Liouville-Bratu reaction-diffusion problem in 1D. Option prefix lb_. Solves\n" " - u'' - lambda e^u = 0\n" "on [0,1] subject to homogeneous Dirichlet boundary conditions. Optionally uses manufactured solution to problem with f(x) on right-hand-side.\n\n"; #include <petsc.h> typedef struct { PetscBool manufactured; PetscReal lambda; } AppCtx; extern PetscErrorCode Exact(DM, DMDALocalInfo*, Vec, AppCtx*); extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal*, PetscReal*, AppCtx*); extern PetscErrorCode FormJacobianLocal(DMDALocalInfo*, PetscReal*, Mat, Mat, AppCtx*); int main(int argc,char **args) { PetscErrorCode ierr; DM da; SNES snes; AppCtx user; Vec u, uexact; PetscReal unorm, errnorm; DMDALocalInfo info; PetscInitialize(&argc,&args,(char*)0,help); user.lambda = 1.0; user.manufactured = PETSC_FALSE; ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "lb_","options for bratu1D",""); CHKERRQ(ierr); ierr = PetscOptionsReal("-lambda","coefficient of nonlinear zeroth-order term", "bratu1D.c",user.lambda,&(user.lambda),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-manu","if set, use a manufactured solution", "bratu1D.c",user.manufactured,&(user.manufactured),NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); ierr = DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,9,1,1,NULL,&da); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); ierr = DMDASetUniformCoordinates(da,0.0,1.0,-1.0,-1.0,-1.0,-1.0); CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetDM(snes,da); CHKERRQ(ierr); ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES, (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr); ierr = DMDASNESSetJacobianLocal(da, (DMDASNESJacobian)FormJacobianLocal,&user); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); ierr = DMCreateGlobalVector(da,&u); CHKERRQ(ierr); ierr = VecSet(u,0.0); CHKERRQ(ierr); ierr = SNESSolve(snes,NULL,u); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); if (user.manufactured) { ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr); ierr = Exact(da,&info,uexact,&user); CHKERRQ(ierr); ierr = VecNorm(u,NORM_INFINITY,&unorm); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uxact ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "on %d point grid: |u-u_exact|_inf/|u|_inf = %g\n", info.mx,errnorm/unorm); CHKERRQ(ierr); VecDestroy(&uexact); } else { ierr = PetscPrintf(PETSC_COMM_WORLD,"done on %d point grid\n",info.mx); CHKERRQ(ierr); } VecDestroy(&u); SNESDestroy(&snes); DMDestroy(&da); return PetscFinalize(); } PetscErrorCode Exact(DM da, DMDALocalInfo *info, Vec uex, AppCtx *user) { PetscErrorCode ierr; PetscInt i; PetscReal h = 1.0 / (info->mx-1), x, *auex; ierr = DMDAVecGetArray(da,uex,&auex); CHKERRQ(ierr); for (i=info->xs; i<info->xs+info->xm; i++) { x = i * h; auex[i] = sin(PETSC_PI * x); } ierr = DMDAVecRestoreArray(da,uex,&auex); CHKERRQ(ierr); return 0; } PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal *u, PetscReal *f, AppCtx *user) { PetscInt i; PetscReal h = 1.0 / (info->mx-1), x, R, compf, uex; for (i=info->xs; i<info->xs+info->xm; i++) { if ((i == 0) || (i == info->mx-1)) { f[i] = u[i]; } else { // interior location R = user->lambda * PetscExpReal(u[i]); f[i] = - u[i+1] + 2.0 * u[i] - u[i-1] - h*h * R; if (user->manufactured) { x = i * h; uex = sin(PETSC_PI * x); compf = PETSC_PI * PETSC_PI * uex - user->lambda * PetscExpReal(uex); f[i] -= h * h * compf; } } } return 0; } PetscErrorCode FormJacobianLocal(DMDALocalInfo *info, PetscReal *u, Mat J, Mat P, AppCtx *user) { PetscErrorCode ierr; PetscInt i, col[3]; PetscReal h = 1.0 / (info->mx-1), dRdu, v[3]; for (i=info->xs; i<info->xs+info->xm; i++) { if ((i == 0) | (i == info->mx-1)) { v[0] = 1.0; ierr = MatSetValues(P,1,&i,1,&i,v,INSERT_VALUES); CHKERRQ(ierr); } else { dRdu = user->lambda * PetscExpReal(u[i]); col[0] = i-1; v[0] = - 1.0; col[1] = i; v[1] = 2.0 - h*h * dRdu; col[2] = i+1; v[2] = - 1.0; ierr = MatSetValues(P,1,&i,3,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; }
{ "alphanum_fraction": 0.5860335196, "avg_line_length": 39.7777777778, "ext": "c", "hexsha": "9ef6257f3267b670cc98e7dd54e81bafb0c5ccc4", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch4/solns/bratu1D.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch4/solns/bratu1D.c", "max_line_length": 149, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch4/solns/bratu1D.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 1649, "size": 5370 }
/// @file mlr.h /// @brief multiple linear regression support /// @author Jeff Perry <jeffsp@gmail.com> /// @version 1.0 /// @date 2013-06-13 #ifndef MLR_H #define MLR_H #include "raster_utils.h" //#include <lapacke.h> namespace horny_toad { /// @brief helper function template<typename T> T matrix_multiply (const T &a, const T &b) { assert (a.cols () == b.rows ()); const size_t N = a.rows (); const size_t M = a.cols (); const size_t P = b.cols (); T y (a.rows (), b.cols ()); for (size_t i = 0; i < N; ++i) for (size_t j = 0; j < P; ++j) for (size_t k = 0; k < M; ++k) y (i, j) += a (i, k) * b (k, j); return y; } /// @brief multiple linear regression /// /// @tparam T matrix types /// @param y responses /// @param x predictors /// /// @return linear estimates of y=b*x template<typename T> T mlr_inverse (const T &y, const T &x) { // add a column of 1's to x on the left T xx (x.rows (), x.cols () + 1); for (size_t i = 0; i < x.rows (); ++i) { xx (i, 0) = 1; for (size_t j = 0; j < x.cols (); ++j) { xx (i, j + 1) = x (i, j); } } // b = (x^T * x)^-1 * x^T * y T xt = transpose (xx); T tmp = matrix_multiply (xt, xx); tmp = invert (tmp); tmp = matrix_multiply (tmp, xt); tmp = matrix_multiply (tmp, y); return tmp; } /// @brief multiple linear regression /// /// @tparam T matrix types /// @param y responses /// @param x predictors /// /// @return linear estimates of y=b*x /* template<typename T> T mlr_lapack (const T &y, const T &x) { assert (x.cols () <= x.rows ()); assert (y.rows () == x.rows ()); // result gets stored in b T b (y); // add a column of 1's to x on the left T xx (x.rows (), x.cols () + 1); for (size_t i = 0; i < x.rows (); ++i) { xx (i, 0) = 1; for (size_t j = 0; j < x.cols (); ++j) { xx (i, j + 1) = x (i, j); } } const size_t M = xx.rows (); const size_t N = xx.cols (); // solve it if (LAPACKE_dgels (LAPACK_ROW_MAJOR, 'N', M, N, 1, &xx[0], N, &b[0], 1) != 0) throw std::runtime_error ("LAPACK error: can't solve mlr"); // copy result into matrix with correct dimensions T z (xx.cols (), 1); for (size_t i = 0; i < z.rows (); ++i) z[i] = b[i]; return z; } */ /// @brief multiple linear regression /// /// @tparam T matrix types /// @param y responses /// @param x predictors /// /// @return linear estimates of y=b*x template<typename T> T mlr (const T &y, const T &x) { return mlr_inverse (y, x); //return mlr_lapack (y, x); } } // namespace horny_toad #endif // MLR_H
{ "alphanum_fraction": 0.4623131904, "avg_line_length": 26.7652173913, "ext": "h", "hexsha": "0d2e937d74aa91ff78d2aec8edf9d03677cdf442", "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": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jeffsp/kaggle_denoising", "max_forks_repo_path": "jsp/rcm_denoising/horny_toad/mlr.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "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": "jeffsp/kaggle_denoising", "max_issues_repo_path": "jsp/rcm_denoising/horny_toad/mlr.h", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jeffsp/kaggle_denoising", "max_stars_repo_path": "jsp/rcm_denoising/horny_toad/mlr.h", "max_stars_repo_stars_event_max_datetime": "2015-06-04T14:34:01.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-04T14:34:01.000Z", "num_tokens": 927, "size": 3078 }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #pragma once /** * This file is for maintaining compatibility with systems where C++ standard library is * not available i.e. for Arduino. I was totally unaware, that there is no C++ standard * library implemented for this toy platform. */ #if defined(__GNUC__) && (defined(AVR) || defined(ARDUINO) || defined (ARDUINO_ARCH_AVR)) #include <assert.h> #include <stddef.h> #include <stdint.h> #include <etl/array.h> #include <etl/map.h> #include <etl/optional.h> #if !defined Expects #define Expects(x) assert (x) #endif namespace gsl { template <class T, std::size_t N> constexpr T &at (T (&arr)[N], const int i) { Expects (i >= 0 && i < static_cast<int> (N)); return arr[static_cast<size_t> (i)]; } template <class Cont> constexpr auto at (Cont &cont, const int i) -> decltype (cont[cont.size ()]) { Expects (i >= 0 && i < static_cast<int> (cont.size ())); using size_type = decltype (cont.size ()); return cont[static_cast<size_type> (i)]; } } // namespace gsl namespace std { template <typename _Tp, typename _Up = _Tp &&> _Up __declval (int); template <typename _Tp> _Tp __declval (long); template <typename _Tp> auto declval () noexcept -> decltype (__declval<_Tp> (0)); template <typename _Tp> struct __declval_protector { static const bool __stop = false; }; template <typename _Tp> auto declval () noexcept -> decltype (__declval<_Tp> (0)) { static_assert (__declval_protector<_Tp>::__stop, "declval() must not be used!"); return __declval<_Tp> (0); } } // namespace std #else #include <cstdint> #include <gsl/gsl> #endif #include <etl/map.h> #include <etl/optional.h>
{ "alphanum_fraction": 0.5322141561, "avg_line_length": 31.4857142857, "ext": "h", "hexsha": "a28faf8aec0e65f5599060e20614d723319b3e52", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-05-31T07:40:34.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-15T06:14:27.000Z", "max_forks_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "semasquare/cpp-can-isotp", "max_forks_repo_path": "src/CppCompat.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:32:11.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-02T19:05:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "semasquare/cpp-can-isotp", "max_issues_repo_path": "src/CppCompat.h", "max_line_length": 98, "max_stars_count": 14, "max_stars_repo_head_hexsha": "8f6b487de162e4c7e871d33ce9cdb4329eff9d5d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "semasquare/cpp-can-isotp", "max_stars_repo_path": "src/CppCompat.h", "max_stars_repo_stars_event_max_datetime": "2021-10-09T20:32:58.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-17T15:01:36.000Z", "num_tokens": 493, "size": 2204 }