Search is not available for this dataset
text
string
meta
dict
/* * test_shaw.c * * Test L-curve (Tikhonov) regression routines using Shaw * problem. See example 1.10 of * * [1] R.C. Aster, B. Borchers and C. H. Thurber, * Parameter Estimation and Inverse Problems (2nd ed), 2012. */ #include <gsl/gsl_sf_trig.h> /* alternate (and inefficient) method of computing G(lambda) */ static double shaw_gcv_G(const double lambda, const gsl_matrix * X, const gsl_vector * y, gsl_multifit_linear_workspace * work) { const size_t n = X->size1; const size_t p = X->size2; gsl_matrix * XTX = gsl_matrix_alloc(p, p); gsl_matrix * XI = gsl_matrix_alloc(p, n); gsl_matrix * XXI = gsl_matrix_alloc(n, n); gsl_vector * c = gsl_vector_alloc(p); gsl_vector_view d; double rnorm, snorm; double term1, term2, G; size_t i; /* compute regularized solution with this lambda */ gsl_multifit_linear_solve(lambda, X, y, c, &rnorm, &snorm, work); /* compute X^T X */ gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, X, 0.0, XTX); /* add lambda*I */ d = gsl_matrix_diagonal(XTX); gsl_vector_add_constant(&d.vector, lambda * lambda); /* invert (X^T X + lambda*I) */ gsl_linalg_cholesky_decomp1(XTX); gsl_linalg_cholesky_invert(XTX); gsl_matrix_transpose_tricpy('L', 0, XTX, XTX); /* XI = (X^T X + lambda*I)^{-1} X^T */ gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, XTX, X, 0.0, XI); /* XXI = X (X^T X + lambda*I)^{-1} X^T */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, X, XI, 0.0, XXI); /* compute: term1 = Tr(I - X XI) */ term1 = 0.0; for (i = 0; i < n; ++i) { double *Ai = gsl_matrix_ptr(XXI, i, i); term1 += 1.0 - (*Ai); } gsl_matrix_free(XTX); gsl_matrix_free(XI); gsl_matrix_free(XXI); gsl_vector_free(c); term2 = rnorm / term1; return term2 * term2;; } /* construct design matrix and rhs vector for Shaw problem */ static int shaw_system(gsl_matrix * X, gsl_vector * y) { int s = GSL_SUCCESS; const size_t n = X->size1; const size_t p = X->size2; const double dtheta = M_PI / (double) p; size_t i, j; gsl_vector *m = gsl_vector_alloc(p); /* build the design matrix */ for (i = 0; i < n; ++i) { double si = (i + 0.5) * M_PI / n - M_PI / 2.0; double csi = cos(si); double sni = sin(si); for (j = 0; j < p; ++j) { double thetaj = (j + 0.5) * M_PI / p - M_PI / 2.0; double term1 = csi + cos(thetaj); double term2 = gsl_sf_sinc(sni + sin(thetaj)); double Xij = term1 * term1 * term2 * term2 * dtheta; gsl_matrix_set(X, i, j, Xij); } } /* construct coefficient vector */ { const double a1 = 2.0; const double a2 = 1.0; const double c1 = 6.0; const double c2 = 2.0; const double t1 = 0.8; const double t2 = -0.5; for (j = 0; j < p; ++j) { double tj = -M_PI / 2.0 + (j + 0.5) * dtheta; double mj = a1 * exp(-c1 * (tj - t1) * (tj - t1)) + a2 * exp(-c2 * (tj - t2) * (tj - t2)); gsl_vector_set(m, j, mj); } } /* construct rhs vector */ gsl_blas_dgemv(CblasNoTrans, 1.0, X, m, 0.0, y); gsl_vector_free(m); return s; } static int test_shaw_system_l(gsl_rng *rng_p, const size_t n, const size_t p, const double lambda_expected, gsl_vector *rhs) { const size_t npoints = 1000; /* number of points on L-curve */ const double tol1 = 1.0e-12; const double tol2 = 1.0e-9; const double tol3 = 1.0e-5; gsl_vector * reg_param = gsl_vector_alloc(npoints); gsl_vector * rho = gsl_vector_alloc(npoints); gsl_vector * eta = gsl_vector_alloc(npoints); gsl_matrix * X = gsl_matrix_alloc(n, p); gsl_matrix * cov = gsl_matrix_alloc(p, p); gsl_vector * c = gsl_vector_alloc(p); gsl_vector * ytmp = gsl_vector_alloc(n); gsl_vector * y; gsl_vector * r = gsl_vector_alloc(n); gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n, p); size_t reg_idx, i; double lambda, rnorm, snorm; /* build design matrix */ shaw_system(X, ytmp); if (rhs) y = rhs; else { y = ytmp; /* add random noise to exact rhs vector */ test_random_vector_noise(rng_p, y); } /* SVD decomposition */ gsl_multifit_linear_svd(X, work); /* calculate L-curve */ gsl_multifit_linear_lcurve(y, reg_param, rho, eta, work); /* test rho and eta vectors */ for (i = 0; i < npoints; ++i) { double rhoi = gsl_vector_get(rho, i); double etai = gsl_vector_get(eta, i); double lami = gsl_vector_get(reg_param, i); /* solve regularized system and check for consistent rho/eta values */ gsl_multifit_linear_solve(lami, X, y, c, &rnorm, &snorm, work); gsl_test_rel(rhoi, rnorm, tol3, "shaw rho n=%zu p=%zu lambda=%e", n, p, lami); gsl_test_rel(etai, snorm, tol1, "shaw eta n=%zu p=%zu lambda=%e", n, p, lami); } /* calculate corner of L-curve */ gsl_multifit_linear_lcorner(rho, eta, &reg_idx); lambda = gsl_vector_get(reg_param, reg_idx); /* test against known lambda value if given */ if (lambda_expected > 0.0) { gsl_test_rel(lambda, lambda_expected, tol1, "shaw: n=%zu p=%zu L-curve corner lambda", n, p); } /* compute regularized solution with optimal lambda */ gsl_multifit_linear_solve(lambda, X, y, c, &rnorm, &snorm, work); /* compute residual norm ||y - X c|| */ gsl_vector_memcpy(r, y); gsl_blas_dgemv(CblasNoTrans, 1.0, X, c, -1.0, r); /* test rnorm value */ gsl_test_rel(rnorm, gsl_blas_dnrm2(r), tol2, "shaw: n=%zu p=%zu rnorm", n, p); /* test snorm value */ gsl_test_rel(snorm, gsl_blas_dnrm2(c), tol2, "shaw: n=%zu p=%zu snorm", n, p); gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(reg_param); gsl_vector_free(rho); gsl_vector_free(eta); gsl_vector_free(r); gsl_vector_free(c); gsl_vector_free(ytmp); gsl_multifit_linear_free(work); return 0; } /* test_shaw_system_l() */ static int test_shaw_system_gcv(gsl_rng *rng_p, const size_t n, const size_t p, const double lambda_expected, gsl_vector *rhs) { const size_t npoints = 200; /* number of points on L-curve */ const double tol1 = 1.0e-12; const double tol2 = 1.4e-10; const double tol3 = 1.0e-5; gsl_vector * reg_param = gsl_vector_alloc(npoints); gsl_vector * G = gsl_vector_alloc(npoints); gsl_matrix * X = gsl_matrix_alloc(n, p); gsl_matrix * cov = gsl_matrix_alloc(p, p); gsl_vector * c = gsl_vector_alloc(p); gsl_vector * ytmp = gsl_vector_alloc(n); gsl_vector * y; gsl_vector * r = gsl_vector_alloc(n); gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n, p); size_t reg_idx, i; double lambda, rnorm, snorm, G_lambda; /* build design matrix */ shaw_system(X, ytmp); if (rhs) y = rhs; else { y = ytmp; /* add random noise to exact rhs vector */ test_random_vector_noise(rng_p, y); } /* SVD decomposition */ gsl_multifit_linear_svd(X, work); /* calculate GCV curve */ gsl_multifit_linear_gcv(y, reg_param, G, &lambda, &G_lambda, work); /* test G vector */ for (i = 0; i < npoints; ++i) { double lami = gsl_vector_get(reg_param, i); if (lami > 1.0e-5) { /* test unreliable for small lambda */ double Gi = gsl_vector_get(G, i); double Gi_expected = shaw_gcv_G(lami, X, y, work); gsl_test_rel(Gi, Gi_expected, tol3, "shaw[%zu,%zu] gcv G i=%zu lambda=%e", n, p, i, lami); } } /* test against known lambda value if given */ if (lambda_expected > 0.0) { gsl_test_rel(lambda, lambda_expected, tol2, "shaw gcv: n=%zu p=%zu lambda", n, p); } /* compute regularized solution with optimal lambda */ gsl_multifit_linear_solve(lambda, X, y, c, &rnorm, &snorm, work); /* compute residual norm ||y - X c|| */ gsl_vector_memcpy(r, y); gsl_blas_dgemv(CblasNoTrans, 1.0, X, c, -1.0, r); /* test rnorm value */ gsl_test_rel(rnorm, gsl_blas_dnrm2(r), tol2, "shaw gcv: n=%zu p=%zu rnorm", n, p); /* test snorm value */ gsl_test_rel(snorm, gsl_blas_dnrm2(c), tol2, "shaw gcv: n=%zu p=%zu snorm", n, p); gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(reg_param); gsl_vector_free(G); gsl_vector_free(r); gsl_vector_free(c); gsl_vector_free(ytmp); gsl_multifit_linear_free(work); return 0; } /* test_shaw_system_gcv() */ void test_shaw(void) { gsl_rng * r = gsl_rng_alloc(gsl_rng_default); { double shaw20_y[] = { 8.7547455124379323e-04, 5.4996835885761936e-04, 1.7527999407005367e-06, 1.9552372913117047e-03, 1.4411645433785081e-02, 5.2800013336393704e-02, 1.3609152023257112e-01, 2.7203484587635818e-01, 4.3752225136193390e-01, 5.7547667319875240e-01, 6.2445052213539942e-01, 5.6252658286441348e-01, 4.2322239923561566e-01, 2.6768469219560631e-01, 1.4337901162734543e-01, 6.5614569346074361e-02, 2.6013851831752945e-02, 9.2336933089481269e-03, 3.2269066658993694e-03, 1.3999201459261811e-03 }; gsl_vector_view rhs = gsl_vector_view_array(shaw20_y, 20); /* lambda and rhs values from [1] */ test_shaw_system_l(r, 20, 20, 5.793190958069266e-06, &rhs.vector); test_shaw_system_gcv(r, 20, 20, 1.24921780949051038e-05, &rhs.vector); } { size_t n, p; for (n = 10; n <= 50; n += 2) { for (p = n - 6; p <= n; p += 2) test_shaw_system_l(r, n, p, -1.0, NULL); } } gsl_rng_free(r); } /* test_shaw() */
{ "alphanum_fraction": 0.6159219312, "avg_line_length": 27.5, "ext": "c", "hexsha": "33c99188a8d573c1a06f1542fd5854c50bff78fe", "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/multifit/test_shaw.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/multifit/test_shaw.c", "max_line_length": 84, "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/multifit/test_shaw.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": 3236, "size": 9735 }
// lu2t.c // // test program for blocked LU decomposition // // Time-stamp: <09/08/31 00:41:24 makino> #include <stdio.h> #include <stdlib.h> #include <math.h> #ifndef NOBLAS #include <cblas.h> #endif #include <lu2tlib.h> void timer_init(); double cpusec(); double wsec(); #define FTYPE double void copymats( int n, double a[n+1][n], double a2[n+1][n]) { int i, j; for(j=0;j<n+1;j++) for(i=0;i<n;i++) a2[j][i] = a[j][i]; } void showresult(int n, double a[n+1][n], double x[]) { int i, j; double emax = 0; for(i=0;i<n;i++){ int k; double b2=0; printf("%3d: ", i); // for(j=0;j<n;j++) printf(" %10.3e", a[j][i]); for(j=0;j<n;j++) b2 += a[j][i] * x[j]; double err = b2-a[n][i]; emax = (fabs(err) > emax) ? fabs(err):emax; printf(" %10.3e %10.3e %10.3e %10.3e \n", x[i], a[n][i], b2, err); } printf("Emax= %10.3e\n", emax); } void readmat( int n, double a[n+1][n]) { int i, j; for(i=0;i<n;i++){ for(j=0;j<n+1;j++) scanf("%le", &(a[j][i])); } } void printmat( int n, double a[n+1][n]) { int i, j; for(i=0;i<n;i++){ printf("%3d: ", i); for(j=0;j<n+1;j++) printf(" %10.3e", a[j][i]); printf("\n"); } printf("\n"); } void backward_sub(int n,double a[n+1][n], double b[]) { int i,j,k; for (i=0;i<n;i++)b[i] = a[n][i]; for(j=n-2;j>=0;j--) for(k=j+1;k<n;k++) b[j] -= b[k]*a[k][j]; } void lu( int n, double a[n+1][n], double b[]) { int i, j, k; for(i=0;i<n-1;i++){ // select pivot double amax = fabs(a[i][i]); int p=i; for(j=i+1;j<n;j++){ if (fabs(a[i][j]) > amax){ amax = fabs(a[i][j]); p = j; } } // exchange rows if (p != i){ for(j=i;j<n+1;j++){ double tmp = a[j][p]; a[j][p] = a[j][i]; a[j][i]=tmp; } } // normalize row i double ainv = 1.0/a[i][i]; // fprintf(stderr,"%d %e\n", i, ainv); for(k=i+1;k<n+1;k++) a[k][i]*= ainv; // subtract row i from all lower rows for(j=i+1;j<n;j++){ // fprintf(stderr,"j=%d \n",j); for(k=i+1;k<n+1;k++) a[k][j] -= a[i][j] * a[k][i]; } } printmat(n,a); a[n][n-1] /= a[n-1][n-1]; backward_sub(n,a,b); } void lumcolumn( int n, double a[n+1][n], double b[], int m, int pv[], int recursive) { int i; for(i=0;i<n;i+=m){ if (recursive){ cm_column_decomposition_recursive(n, a+i, m, pv,i); }else{ cm_column_decomposition(n, a+i, m, pv,i); } cm_process_right_part(n,a+i,m,pv,i,n+1); } backward_sub(n,a,b); } main() { int n; fprintf(stderr, "Enter n:"); scanf("%d", &n); printf("N=%d\n", n); #if 0 double a[n+1][n]; double b[n]; double acopy[n+1][n]; double bcopy[n]; int pv[n]; #endif double (*a)[]; double (*acopy)[]; int * pv; double *b, *bcopy; a = (double(*)[]) malloc(sizeof(double)*n*(n+1)); acopy = (double(*)[]) malloc(sizeof(double)*n*(n+1)); b = (double*)malloc(sizeof(double)*n); bcopy = (double*)malloc(sizeof(double)*n); pv = (int*)malloc(sizeof(int)*n); readmat(n,a); copymats(n,a,acopy); // printmat(n,a,b); // lu2columnv2(n,a,b); // lu2columnv2(n,a,b); // lub(n,a,b,NBK); // printmat(n,a,b); // showresult(n,acopy, b, bcopy); // copymats(n,acopy,bcopy,a, b); // lu(n,a,b); timer_init(); lumcolumn(n,a,b,16,pv,1); double ctime=cpusec(); double wtime=wsec(); showresult(n,acopy, b); printf("cpsec = %g wsec=%g\n", ctime, wtime); return 0; }
{ "alphanum_fraction": 0.5002862049, "avg_line_length": 20.674556213, "ext": "c", "hexsha": "bca1de28e72608a14bb7767551011047709a036e", "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": "lu2t.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": "lu2t.c", "max_line_length": 69, "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": "lu2t.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": 1315, "size": 3494 }
#pragma once #include "iflag.h" #include "optioninfo.h" #include "configaccess.h" #include "format.h" #include <gsl/gsl> #include <cmdlime/customnames.h> #include <memory> #include <functional> #include <utility> namespace cmdlime::detail{ class Flag : public IFlag{ public: enum class Type{ Normal, Exit }; Flag(std::string name, std::string shortName, std::function<bool&()> flagGetter, Type type) : info_(std::move(name), std::move(shortName), {}) , flagGetter_(std::move(flagGetter)) , type_(type) { } OptionInfo& info() override { return info_; } const OptionInfo& info() const override { return info_; } private: void set() override { flagGetter_() = true; } bool isSet() const override { return flagGetter_(); } bool isExitFlag() const override { return type_ == Type::Exit; } private: OptionInfo info_; std::function<bool&()> flagGetter_; Type type_; }; template <typename TConfig> class FlagCreator{ using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider; public: FlagCreator(TConfig& cfg, const std::string& varName, std::function<bool&()> flagGetter, Flag::Type flagType = Flag::Type::Normal) : cfg_(cfg) { Expects(!varName.empty()); flag_ = std::make_unique<Flag>(NameProvider::name(varName), NameProvider::shortName(varName), std::move(flagGetter), flagType); } FlagCreator& operator<<(const std::string& info) { flag_->info().addDescription(info); return *this; } FlagCreator& operator<<(const Name& customName) { flag_->info().resetName(customName.value()); return *this; } FlagCreator& operator<<(const ShortName& customName) { static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled, "Current command line format doesn't support short names"); flag_->info().resetShortName(customName.value()); return *this; } FlagCreator& operator<<(const WithoutShortName&) { static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled, "Current command line format doesn't support short names"); flag_->info().resetShortName({}); return *this; } operator bool() { ConfigAccess<TConfig>{cfg_}.addFlag(std::move(flag_)); return false; } private: std::unique_ptr<Flag> flag_; TConfig& cfg_; }; }
{ "alphanum_fraction": 0.5728643216, "avg_line_length": 22.8360655738, "ext": "h", "hexsha": "5195d22f7ce9cd1d252062500b881cae9aa8e6cf", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": [ "MS-PL" ], "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/flag.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_licenses": [ "MS-PL" ], "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/flag.h", "max_line_length": 88, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": [ "MS-PL" ], "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/flag.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "num_tokens": 622, "size": 2786 }
/* * 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 clip_c55b09bc_5fbd_463f_8d45_b12013b57f42_h #define clip_c55b09bc_5fbd_463f_8d45_b12013b57f42_h #include <gslib/tree.h> #include <ariel/painterpath.h> __ariel_begin__ enum clip_point_tag { cpt_corner = 0x01, cpt_interpolate = 0x02, }; enum clip_fill_type { cft_even_odd = 0, cft_non_zero, cft_positive, cft_negative, }; struct clip_vec2_hash { size_t operator()(const vec2& pt) const { return hash_bytes((const byte*)&pt, sizeof(pt)); } }; typedef _treenode_wrapper<painter_path> clip_result_wrapper; typedef tree<painter_path, clip_result_wrapper> clip_result; typedef typename clip_result::iterator clip_result_iter; typedef typename clip_result::const_iterator clip_result_const_iter; typedef unordered_map<vec2, uint, clip_vec2_hash> clip_point_attr; ariel_export extern void clip_remap_points(painter_linestrips& output, clip_point_attr& attrmap, const painter_path& input, uint attr_selector, float step_len = -1.f); ariel_export extern void clip_offset(painter_linestrips& lss, const painter_linestrips& input, float offset); ariel_export extern void clip_stroker(painter_linestrips& lss, const painter_linestrips& input, float offset); ariel_export extern void clip_simplify(painter_linestrips& lss, const painter_linestrip& input, clip_fill_type ft = cft_even_odd); ariel_export extern void clip_simplify(painter_linestrips& lss, const painter_linestrips& input, clip_fill_type ft = cft_even_odd); ariel_export extern void clip_simplify(clip_result& output, const painter_path& input); ariel_export extern void clip_union(clip_result& output, const painter_path& subjects, const painter_path& clips); ariel_export extern void clip_intersect(clip_result& output, const painter_path& subjects, const painter_path& clips); ariel_export extern void clip_substract(clip_result& output, const painter_path& subjects, const painter_path& clips); ariel_export extern void clip_exclude(clip_result& output, const painter_path& subjects, const painter_path& clips); ariel_export extern void clip_convert(painter_path& path, const clip_result& result); __ariel_end__ #endif
{ "alphanum_fraction": 0.7813138686, "avg_line_length": 45.0657894737, "ext": "h", "hexsha": "d26a62209c04ca1b5b5fd9d26d5a752bfbd1d99c", "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/clip.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/clip.h", "max_line_length": 168, "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/clip.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": 817, "size": 3425 }
/* FILE DETAILS description: header file needed for matrix operations in LCP solver, and some macros for the main LCP function project: MPT 3.0 filename: lcp_matrix.h author: Colin N. Jones, Automatic Control Laboratory, ETH Zurich, 2006 LICENSE: 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. REVISION HISTORY: date: Nov, 2010 revised by: Martin Herceg, Automatic Control Laboratory, ETH Zurich, 2010 details: Included BLAS and LAPACK libraries which are standard in MATLAB. Replaced int declarations with ptrdiff_t to be 32/64 compatible. Added declaration of LCP_options structure. */ #ifndef LCP_MATRIX__H #define LCP_MATRIX__H /**** MODULES ****/ /* Standard headers */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stddef.h> /* to have ptrdiff_t */ #include <math.h> #include <time.h> /* BLAS and LAPACK headers are in $MATLABROOT/extern/include and are on the default search path when compiling with standard options */ #include <blas.h> #include <lapack.h> /**** MACROS ****/ /* Select an element from a column-major matrix */ #define C_SEL(mat,r,c) ((mat)->A[(r)+(c)*((mat)->rows_alloc)]) /* Select an element from a row-major matrix */ #define R_SEL(mat,r,c) ((mat)->A[(c)+(r)*((mat)->cols_alloc)]) /* Get a matrix */ #define MAT(mat) ((mat).A) /* Get a matrix pointer */ #define pMAT(mat) ((mat)->A) /* Get a pointer to a given column in a matrix */ #define COL(mat,n) &([C_SEL(mat,0,n)]) /* Get number of rows of a given matrix */ #define Matrix_Rows(pA) ((pA)->rows) /* Get number of columns of a given matrix */ #define Matrix_Cols(pA) ((pA)->cols) /* Dimension of an index set */ #define Index_Length(pI) ((pI)->len) /* Assign value "x" to position "i" in the index set "I" */ #define Index_Set(pI,i,x) (((pI)->I[(i)]) = (x)) /* Obtain value of the index set "I" at the position "i" */ #define Index_Get(pI,i) ((pI)->I[(i)]) /**** TYPEDEFS AND STRUCTURES ****/ /* Matrices */ /* If a matrix is column-major, then the form is: */ /* [M(0) M(rows_alloc) M(2rows_alloc) ... ] */ /* [M(1) M(rows_alloc+1) M(2rows_alloc+1) ... ] */ /* [... ... .... ... ] */ typedef struct LCP_Matrix { double *A; ptrdiff_t rows,cols; ptrdiff_t rows_alloc, cols_alloc; char *name; } T_Matrix, *PT_Matrix; /* Index sets for basis defintion */ typedef struct LCP_IndexSet { /* C-based indexing used throughout. i.e. 0 is the first element */ ptrdiff_t *I; ptrdiff_t len, len_alloc; char *name; } T_Index, *PT_Index; /* The basis */ typedef struct LCP_Basis { PT_Index pW; /* Slacks in the basis */ PT_Index pZ; /* Variables in the basis */ PT_Index pWc; /* Complement of W */ PT_Index pP; /* Work index (used to list positive variables) */ /* B = [I G;0 X]; */ /* inv(B) = [I -G*iX; 0 iX] */ /* G = M_W,Z */ /* X = M_Wc,X */ PT_Matrix pG, pX, pF, pLX, pUX, pUt; /* F is used as factorization of X on exit from dgesv routine, Ut is full, column major upper triangular matrix */ double *y,*z,*w, *v, *r; /* work vectors */ ptrdiff_t *p; /* work vector for dgesv, dgetrs */ double *s; /* work vector for dgels */ } T_Basis, *PT_Basis; /* options structure */ typedef struct LCP_options { double zerotol; /* zero tolerance*/ double lextol; /* lexicographic tolerance - a small treshold to determine if values are equal */ ptrdiff_t maxpiv; /* maximum number of pivots */ ptrdiff_t nstepf; /* after n steps refactorize the basis */ int clock; /* print computation time */ int verbose; /* verbose mode */ int routine; /* routine from LAPACK library to solve linear equations in Basis_solve*/ double timelimit; /* time limit for iterations in seconds */ int normalize; /* normalize matrices M, q */ double normalizethres; /* normalization threshold */ } T_Options; /**** FUNCTIONS ****/ /* Basis functions */ PT_Basis Basis_Init(ptrdiff_t m); void Basis_Free(PT_Basis pB); void Basis_Print(PT_Basis pB); ptrdiff_t Basis_Pivot(PT_Basis pB, PT_Matrix pA, ptrdiff_t enter, ptrdiff_t leave); ptrdiff_t Basis_Solve(PT_Basis pB, double *q, double *x, T_Options options); void Reinitialize_Basis(ptrdiff_t m, PT_Basis pB); void LU_Expand(PT_Matrix L, PT_Matrix U, double *y, double *z, double *w); void LU_Replace_Col(PT_Matrix L, PT_Matrix U, ptrdiff_t kcol, double *y, double *z, double *w); void LU_Replace_Row(PT_Matrix L, PT_Matrix U, ptrdiff_t krow, double *y, double *z, double *w); void LU_Shrink(PT_Matrix L, PT_Matrix U, ptrdiff_t krow, ptrdiff_t kcol, double *y, double *z, double *w); void LU_Solve0(PT_Matrix pL, PT_Matrix pU, double *vec, double *x); void LU_Solve1(PT_Matrix pL, PT_Matrix pU, double *vec, double *x, ptrdiff_t *info); void LU_Refactorize(PT_Basis pB); /* Matrix functions */ PT_Matrix Matrix_Init(ptrdiff_t m, ptrdiff_t n, const char *name); PT_Matrix Matrix_Init_NoAlloc(ptrdiff_t m, ptrdiff_t n, const char *name); void Matrix_Free(PT_Matrix pMat); void Matrix_Free_NoAlloc(PT_Matrix pMat); void Matrix_Print_col(PT_Matrix pMat); void Matrix_Print_row(PT_Matrix pMat); void Matrix_Print_utril_row(PT_Matrix pMat); void Matrix_Print_size(PT_Matrix pMat); void Matrix_AddRow(PT_Matrix pA, double *row); void Matrix_AddCol(PT_Matrix pA, double *col); void Matrix_RemoveRow(PT_Matrix pA, ptrdiff_t row); void Matrix_RemoveCol(PT_Matrix pA, ptrdiff_t col); void Matrix_GetRow(PT_Matrix pA, double *row, ptrdiff_t row_index, PT_Index col_index); void Matrix_GetCol(PT_Matrix pA, double *col, PT_Index row_index, ptrdiff_t col_index); void Matrix_ReplaceCol(PT_Matrix pA, ptrdiff_t kcol, double *vec); void Matrix_ReplaceRow(PT_Matrix pA, ptrdiff_t krow, double *vec); void Matrix_Copy(PT_Matrix pA, PT_Matrix pB, double *w); void Matrix_Triu(PT_Matrix pF, PT_Matrix pU, double *w); void Matrix_Uzeros(PT_Matrix pF); void Matrix_Full2RowTriangular(PT_Matrix pF, PT_Matrix pU, double *w); void Matrix_Transpose(PT_Matrix pA, PT_Matrix pB, double *w); void Vector_Print_raw(double *vec, ptrdiff_t m); /* Index set functions */ PT_Index Index_Init(ptrdiff_t len, const char *name); void Index_Free(PT_Index pIndex); void Index_Print(PT_Index pI); void Index_Remove(PT_Index pI, ptrdiff_t leave); void Index_Add(PT_Index pI, ptrdiff_t num); void Index_Replace(PT_Index pI, ptrdiff_t index, ptrdiff_t newval); ptrdiff_t Index_FindElement(PT_Index pI, ptrdiff_t element); #endif
{ "alphanum_fraction": 0.6996942746, "avg_line_length": 37.0927835052, "ext": "h", "hexsha": "32ae7c03eb54be12e141e8a80a378871055d973a", "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": "b0e8a04ed1ccd9e0b363e9d87c475712f89a17b9", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "adrilow/bary-polytopes", "max_forks_repo_path": "tbxmanager/toolboxes/lcp/1.0.3/glnxa64/source/lcp_matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b0e8a04ed1ccd9e0b363e9d87c475712f89a17b9", "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": "adrilow/bary-polytopes", "max_issues_repo_path": "tbxmanager/toolboxes/lcp/1.0.3/glnxa64/source/lcp_matrix.h", "max_line_length": 107, "max_stars_count": null, "max_stars_repo_head_hexsha": "b0e8a04ed1ccd9e0b363e9d87c475712f89a17b9", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "adrilow/bary-polytopes", "max_stars_repo_path": "tbxmanager/toolboxes/lcp/1.0.3/glnxa64/source/lcp_matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1979, "size": 7196 }
/** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_spline.h> #include "aXe_grism.h" #include "aXe_utils.h" #include "spce_PET.h" #include "inout_aper.h" //#include "trace_conf.h" //#include "aper_conf.h" //#include "spc_sex.h" //#include "disp_conf.h" //#include "spc_wl_calib.h" //#include "spce_binning.h" //#include "spc_spc.h" //#include "spce_pgp.h" //#include "spce_output.h" //#include "spc_FITScards.h" //#include "spc_flatfield.h" #include "fringe_conf.h" #include "fringe_utils.h" #define AXE_IMAGE_PATH "AXE_IMAGE_PATH" #define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH" #define AXE_CONFIG_PATH "AXE_CONFIG_PATH" int main (int argc, char *argv[]) { char *opt; char aper_file[MAXCHAR]; char aper_file_path[MAXCHAR]; char conf_file[MAXCHAR]; char conf_file_path[MAXCHAR]; char fconf_file[MAXCHAR]; char fconf_file_path[MAXCHAR]; char grism_file[MAXCHAR]; char grism_file_path[MAXCHAR]; char FF_file[MAXCHAR]; //char FF_file_path[MAXCHAR]; char OPET_file[MAXCHAR]; char OPET_file_path[MAXCHAR]; char BPET_file[MAXCHAR]; char BPET_file_path[MAXCHAR]; aperture_conf *conf=NULL; fringe_conf *fconf=NULL; object **oblist; observation *obs=NULL; ap_pixel *OPET=NULL; ap_pixel *BPET=NULL; fitsfile *OPET_ptr=NULL; fitsfile *BPET_ptr=NULL; beam act_beam; int index; int i; int f_status = 0; int bckmode = 0; int oaperID, obeamID; int baperID, bbeamID; if ((argc < 4) || (opt = get_online_option ("help", argc, argv))) { fprintf (stdout, "aXe_FRINGECORR Version %s:\n",RELEASE); exit (1); } fprintf (stdout, "aXe_FRINGECORR: Starting...\n\n"); // copy the first parameter to the grism filename index = 0; strcpy (grism_file, argv[++index]); build_path (AXE_IMAGE_PATH, grism_file, grism_file_path); // copy the next parameter to the aXe configuration file strcpy (conf_file, argv[++index]); build_path (AXE_CONFIG_PATH, conf_file, conf_file_path); // copy the next parameter to the fringe configuration file strcpy (fconf_file, argv[++index]); build_path (AXE_CONFIG_PATH, fconf_file, fconf_file_path); // Determine if we are using the special bck mode // In this mode, file names are handled diferently if ((opt = get_online_option("bck", argc, argv))) bckmode = 1; // load the aXe configuration file conf = get_aperture_descriptor (conf_file_path); // load the fringe configuration file fconf = load_fringe_conf(fconf_file_path); // Determine where the various extensions are in the FITS file get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1); // Build aperture file name replace_file_extension (grism_file, aper_file, ".fits", ".OAF", conf->science_numext); build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path); // Build object PET file name replace_file_extension (grism_file, OPET_file, ".fits", ".PET.fits", conf->science_numext); build_path (AXE_OUTPUT_PATH, OPET_file, OPET_file_path); // build the background PET file name // if necessary if (bckmode) { replace_file_extension (grism_file, BPET_file, ".fits", ".BCK.PET.fits", conf->science_numext); build_path (AXE_OUTPUT_PATH, BPET_file, BPET_file_path); } // Give a short feedback on the filenames // of the various input fprintf (stdout, "aXe_FRINGECORR: Grism image file name: %s\n", grism_file_path); fprintf (stdout, "aXe_FRINGECORR: Aperture file name: %s\n", aper_file_path); fprintf (stdout, "aXe_FRINGECORR: aXe configuration file name: %s\n", conf_file_path); fprintf (stdout, "aXe_FRINGECORR: Fringe configuration file name: %s\n", fconf_file_path); fprintf (stdout, "aXe_FRINGECORR: Object PET file name: %s\n", OPET_file_path); if (bckmode) fprintf (stdout, "aXe_FRINGECORR: Background PET file name: %s\n", BPET_file_path); // check whether all necessary information // is in place, provide defaults check_fringe_conf(fconf); fprintf (stdout, "aXe_FRINGECORR: Loading object aperture list..."); fflush(stdout); oblist = file_to_object_list_seq (aper_file_path, obs); fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist)); // Open the OPET file for reading/writing fits_open_file (&OPET_ptr, OPET_file_path, READWRITE, &f_status); if (f_status) { ffrprt (stdout, f_status); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_FRINGECORR: Could not open file: %s\n", OPET_file_path); } // if necessary, open the background PET if (bckmode) { fits_open_file (&BPET_ptr, BPET_file_path, READWRITE, &f_status); if (f_status) { ffrprt (stdout, f_status); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_FRINGECORR: Could not open file: %s\n", BPET_file_path); } } i = 0; if ((oblist!=NULL) && (strcmp(FF_file,"None"))) { while (1) { // Get the PET for this object OPET = get_ALL_from_next_in_PET(OPET_ptr, &oaperID, &obeamID); if ((oaperID==-1) && (obeamID==-1)) break; // Get the PET for this object if (bckmode) { BPET = get_ALL_from_next_in_PET(BPET_ptr, &baperID, &bbeamID); if ((baperID != oaperID) || (bbeamID != obeamID)) { fprintf(stderr, "%i, %i, %i, %i\n", oaperID, baperID, obeamID, bbeamID); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_FRINGECORR: The beam order in the\n" "object PET %s and the background PET\n" "%s does not coincide!\n", OPET_file_path, BPET_file_path); } } // check whether there is content in the PET; // skip it if empty if (OPET==NULL) continue; // refer about the actual beam in process fprintf (stdout, "aXe_FRINGECORR: BEAM %d%c",oaperID, BEAM(obeamID)); // get the beam information from the OAF act_beam = find_beam_in_object_list(oblist, oaperID, obeamID); fprintf (stdout, " Done. \n"); fringe_correct_PET(fconf, act_beam, OPET, BPET); // update PET table with the new FF info { char ID[60]; sprintf (ID, "%d%c", oaperID, BEAM (act_beam.ID)); add_ALL_to_PET (OPET, ID, OPET_ptr,1); if (bckmode) add_ALL_to_PET (BPET, ID, BPET_ptr,1); } // free the memory of the object pixels if (OPET!=NULL) { free(OPET); OPET=NULL; } // free the memory of the background pixels if (BPET!=NULL) { free(BPET); BPET=NULL; } } } // free the object list if (oblist!=NULL) free_oblist (oblist); // close the object PET fits-file fits_close_file (OPET_ptr, &f_status); if (f_status) { ffrprt (stderr, f_status); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETFF: " "Error closing PET: %s\n", OPET_file_path); } // if necessary, close the object PET fits-file if (bckmode) { fits_close_file (BPET_ptr, &f_status); if (f_status) { ffrprt (stderr, f_status); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETFF: " "Error closing PET: %s\n", BPET_file_path); } } fprintf (stdout, "aXe_FRINGECORR: Done...\n\n"); exit (0); }
{ "alphanum_fraction": 0.664333745, "avg_line_length": 26.3068592058, "ext": "c", "hexsha": "14dc9dde0be6e086fbb474f09890b06311254308", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/aXe_FRINGECORR.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/aXe_FRINGECORR.c", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/aXe_FRINGECORR.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2233, "size": 7287 }
#ifndef __SOLVERS_H_ #define __SOLVERS_H_ #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> #include <gsl/gsl_multifit_nlin.h> const gsl_multiroot_fdfsolver_type * get_multiroot_fdfsolver_type(int index); int solve_multiroot(size_t dim, double * x, void * params, double atol, int multiroot_fdfsolver_type_idx, int itermax, int print_, int store_intermediate, double * intermediate, int * iter, int * nfev_, int * njev_, int * nfjev_); void print_multiroot_state (int iter, gsl_multiroot_fdfsolver * s, size_t dim); int solve_multifit(size_t ne, size_t nx, double * x, void * params, double atol, double rtol, int multifit_fdfsolver_type_idx, int itermax, int criterion, int print_, int store_intermediate, double * intermediate, int * iter, int * nfev_, int * njev_, int * nfjev_); void print_multifit_state (int iter, gsl_multifit_fdfsolver * s, size_t nx, size_t ne); void c_func(size_t nx, double * x, double * params, double * out); void c_jac(size_t nx, double * x, double * params, double * out); #endif
{ "alphanum_fraction": 0.739010989, "avg_line_length": 28, "ext": "h", "hexsha": "edbfb1b75e80333c32ebfd568b4356e19679ade4", "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": "677307d6b94e452262f7ffe944ec2bed6314d34b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "bjodah/symneqsys", "max_forks_repo_path": "symneqsys/gsl/solvers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "677307d6b94e452262f7ffe944ec2bed6314d34b", "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": "bjodah/symneqsys", "max_issues_repo_path": "symneqsys/gsl/solvers.h", "max_line_length": 83, "max_stars_count": 1, "max_stars_repo_head_hexsha": "677307d6b94e452262f7ffe944ec2bed6314d34b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "bjodah/symneqsys", "max_stars_repo_path": "symneqsys/gsl/solvers.h", "max_stars_repo_stars_event_max_datetime": "2015-01-10T09:00:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:00:04.000Z", "num_tokens": 324, "size": 1092 }
#include "gs2crmod_ext.h" #include <math.h> #include <string.h> #include <gsl/gsl_spline.h> VALUE gs2crmod_tensor_complexes_field_gsl_tensor_complex_2(VALUE self, VALUE options) { VALUE field, field_complex, field_narray; VALUE field_complex_narray; VALUE cgsl_tensor_complex; VALUE ccomplex; VALUE shape; int *c_shape; int i, j, k; ccomplex = RGET_CLASS_TOP("Complex"); field = RFCALL_11("field_gsl_tensor", options); cgsl_tensor_complex = RGET_CLASS(cgsl, "TensorComplex"); shape = rb_funcall(field, rb_intern("shape"), 0); /*rb_p(shape);*/ CR_INT_ARY_R2C_STACK(shape, c_shape); field_complex = rb_funcall3(cgsl_tensor_complex, rb_intern("alloc"), 3, RARRAY_PTR(shape)); field_narray = RFCALL_10_ON(field, "narray"); field_complex_narray = RFCALL_10_ON(field_complex, "narray"); /*rb_p(field_complex);*/ for (i=0;i<c_shape[0];i++) for (j=0;j<c_shape[1];j++) for (k=0;k<c_shape[2];k++) { /*printf("%d %d %d\n", i, j, k);*/ VALUE cmplex, re, im; re = rb_funcall( field_narray, rb_intern("[]"), 4, INT2FIX(0), INT2FIX(k), INT2FIX(j), INT2FIX(i) ); /*printf("%d %d %d re\n", i, j, k);*/ im = rb_funcall( field_narray, rb_intern("[]"), 4, INT2FIX(1), INT2FIX(k), INT2FIX(j), INT2FIX(i) ); /*printf("%d %d %d im\n", i, j, k);*/ cmplex = rb_funcall( ccomplex, rb_intern("rectangular"), 2, re, im ); /*printf("%d %d %d again\n", i, j, k);*/ rb_funcall( field_complex_narray, rb_intern("[]="), 4, INT2FIX(k), INT2FIX(j), INT2FIX(i), cmplex ); } /*rb_p(field);*/ /*field_complex = */ return field_complex; } VALUE gs2crmod_tensor_field_gsl_tensor(VALUE self, VALUE options) { VALUE cgsl_tensor; VALUE field, field_narray; VALUE field_real_space, field_real_space_narray; VALUE field_real_space_new, field_real_space_new_narray; VALUE shape, shape_real_space, shape_real_space_new; VALUE workspacex, workspacey; VALUE ccomplex, cgsl_complex; VALUE re, im, cmplex; VALUE *ary_ptr; VALUE range_x, range_y; int shape0; double* c_field, *c_field_real_space; int* c_shape, *c_shape_real_space; int * c_shape_real_space_new; int i,j,k,m; int kint,km,kold; double frac, interp_value; ccomplex = RGET_CLASS_TOP("Complex"); cgsl_complex = RGET_CLASS(cgsl, "Complex"); cgsl_tensor = RGET_CLASS(cgsl, "Tensor"); /*cgsl_vector = RGET_CLASS(cgsl, "Vector");*/ Check_Type(options, T_HASH); if(RTEST(CR_HKS(options, "field_netcdf"))){ field = CR_HKS(options, "field_netcdf"); CR_CHECK_CLASS(field, cgsl_tensor); } else { field = RFCALL_11("field_gsl_tensor", options); } field_narray = RFCALL_10_ON(field, "narray"); shape = RFCALL_10_ON(field, "shape"); workspacex = RFCALL_11_ON(cgsl_vector_complex, "alloc", RARRAY_PTR(shape)[1]); shape0 = NUM2INT(RARRAY_PTR(shape)[0]); workspacey = RFCALL_11_ON(cgsl_vector, "alloc", INT2NUM(shape0 * 2 - 2 + shape0%2)); field_real_space = rb_funcall( cgsl_tensor, rb_intern("alloc"), 3, RFCALL_10_ON(workspacey, "size"), RARRAY_PTR(shape)[1], RARRAY_PTR(shape)[2] ); field_real_space_narray = RFCALL_10_ON(field_real_space, "narray"); shape_real_space = RFCALL_10_ON(field_real_space, "shape"); CR_INT_ARY_R2C_STACK(shape, c_shape); CR_INT_ARY_R2C_STACK(RFCALL_10_ON(field_real_space, "shape"), c_shape_real_space); c_field = ALLOC_N(double, c_shape[0] * c_shape[1] * c_shape[2] * c_shape[3]); /*printf("Allocated stuff\n");*/ for (j=0; j<c_shape[2]; j++) /*theta loop*/ { for (i=0; i<c_shape[0]; i++) /*ky loop*/ { for (k=0; k<c_shape[1]; k++) /*kx loop*/ { /*First copy the field onto the * x workspace, Fourier transform * the workspace and copy it onto * the c array*/ re = rb_funcall( field_narray, rb_intern("[]"), 4, INT2FIX(0), INT2FIX(j), INT2FIX(k), INT2FIX(i) ); /*printf("%d %d %d re\n", i, j, k);*/ im = rb_funcall( field_narray, rb_intern("[]"), 4, INT2FIX(1), INT2FIX(j), INT2FIX(k), INT2FIX(i) ); /*printf("%d %d %d im\n", i, j, k);*/ cmplex = rb_funcall( cgsl_complex, rb_intern("alloc"), 2, re, im ); /*printf("%d %d %d again\n", i, j, k);*/ /*printf("Made complex\n");*/ rb_funcall( workspacex, rb_intern("[]="), 2, INT2FIX(k), cmplex); /*printf("Added complex\n");*/ } /*printf("Made complex vector\n");*/ workspacex = RFCALL_10_ON(workspacex, "backward"); /*printf("Done x transform\n");*/ for (k=0;k<c_shape[1];k++){ cmplex = RFCALL_11_ON(workspacex,"[]",INT2FIX(k)); c_field[ j*c_shape[0]*c_shape[1]*2 + i*c_shape[1]*2 + k*2 ] = NUM2DBL(RFCALL_10_ON(cmplex,"real")); c_field[ j*c_shape[0]*c_shape[1]*2 + i*c_shape[1]*2 + k*2 + 1 ] = NUM2DBL(RFCALL_10_ON(cmplex,"imag")); } } /*printf("Done x\n");*/ /* Now copy onto the y workspace, * Fourier transform and copy onto * the second c array*/ for (k=0;k<c_shape[1];k++) { m=0; for (i=0;i<c_shape[0];i++) { rb_funcall( workspacey, rb_intern("[]="), 2, INT2FIX(m), rb_float_new(c_field[ j*c_shape[0]*c_shape[1]*2 + i*c_shape[1]*2 + k*2 ]) ); m++; /* We are converting a complex array * to a half complex array in * preparation for transforming * it to real space, and so there * are one or two elements we leave * unfilled.*/ if (i==0 || (c_shape[0]%2==0 && i == c_shape[0]/2 + 1)) continue; rb_funcall( workspacey, rb_intern("[]="), 2, INT2FIX(m), rb_float_new(c_field[ j*c_shape[0]*c_shape[1]*2 + i*c_shape[1]*2 + k*2 + 1 ]) ); m++; } /*printf("Made y vector\n");*/ /*rb_p(workspacey);*/ /*rb_p(RFCALL_10_ON(workspacey, "class"));*/ workspacey = RFCALL_10_ON(workspacey, "backward"); /*printf("Done y transform\n");*/ for (i=0;i<FIX2INT(RFCALL_10_ON(workspacey, "size"));i++) { rb_funcall( field_real_space_narray, rb_intern("[]="), 4, INT2FIX(j), INT2FIX(k), INT2FIX(i), RFCALL_11_ON(workspacey, "[]", INT2FIX(i)) ); } } } /*printf("HERE!\n");*/ range_x = CR_RANGE_INC( (RTEST(CR_HKS(options, "ymin")) ? FIX2INT(CR_HKS(options, "ymin")) : 0), (RTEST(CR_HKS(options, "ymax")) ? FIX2INT(CR_HKS(options, "ymax")) : c_shape_real_space[0]-1) ); /*rb_p(range_x);*/ range_y = CR_RANGE_INC( (RTEST(CR_HKS(options, "xmin")) ? FIX2INT(CR_HKS(options, "xmin")) : 0), (RTEST(CR_HKS(options, "xmax")) ? FIX2INT(CR_HKS(options, "xmax")) : c_shape_real_space[1]-1) ); /*printf("Made ranges\n");*/ /*rb_p(rb_funcall(field_real_space, rb_intern("[]"), 3, INT2FIX(0), INT2FIX(2), INT2FIX(3)));*/ field_real_space = rb_funcall( field_real_space, rb_intern("[]"), 3, range_x, range_y, Qtrue); /*rb_p(rb_funcall(field_real_space, rb_intern("[]"), 3, INT2FIX(0), INT2FIX(2), INT2FIX(3)));*/ /*printf("SHORTENED!\n");*/ if (RTEST(CR_HKS(options, "interpolate_theta"))) { shape_real_space_new = RFCALL_10_ON(shape_real_space, "dup"); kint = NUM2INT(CR_HKS(options, "interpolate_theta")); rb_funcall( shape_real_space_new, rb_intern("[]="), 2, INT2FIX(-1), INT2FIX((c_shape_real_space[2] - 1)*kint+1) ); CR_INT_ARY_R2C_STACK(shape_real_space_new, c_shape_real_space_new); ary_ptr = RARRAY_PTR(shape_real_space_new); field_real_space_new = rb_funcall( cgsl_tensor, rb_intern("float"), 3, ary_ptr[0], ary_ptr[1], ary_ptr[2]); field_real_space_new_narray = RFCALL_10_ON(field_real_space_new, "narray"); /*printf("Allocated");*/ /*rb_p(shape_real_space_new);*/ for (i=0;i<c_shape_real_space_new[0];i++) for (j=0;j<c_shape_real_space_new[1];j++) { /*printf("i %d j %d k %d\n", i, j, c_shape_real_space_new[2]-1); */ rb_funcall( field_real_space_new_narray, rb_intern("[]="), 4,INT2FIX(c_shape_real_space_new[2]-1), INT2FIX(j),INT2FIX(i), rb_funcall( field_real_space_narray, rb_intern("[]"), 3, INT2FIX(c_shape_real_space[2]-1), INT2FIX(j),INT2FIX(i) ) ); for (k=0;k<c_shape_real_space_new[2]-1;k++) { /*printf("i %d j %d k %d\n", i, j, k); */ km = k%kint; frac = (double)km/(double)kint; kold = (k-km)/kint; interp_value = NUM2DBL( rb_funcall( field_real_space_narray, rb_intern("[]"),3, INT2FIX(kold),INT2FIX(j),INT2FIX(i) ) )*(1.0-frac) + NUM2DBL( rb_funcall( field_real_space_narray, rb_intern("[]"),3, INT2FIX(kold+1),INT2FIX(j),INT2FIX(i) ) ) * frac; rb_funcall( field_real_space_new_narray, rb_intern("[]="), 4, INT2FIX(k),INT2FIX(j),INT2FIX(i), rb_float_new(interp_value) ); /*if (i==0 && j==2 && k==3){*/ /*printf("frac %f\n", frac);*/ /*}*/ } } field_real_space = field_real_space_new; } /*printf("Finished field_real_space_gsl_tensor\n");*/ /*rb_p(shape_real_space_new);*/ return field_real_space; } void Init_gs2crmod_ext() { /*printf("HERE!!!");*/ ccode_runner = RGET_CLASS_TOP("CodeRunner"); ccode_runner_gs2 = rb_define_class_under(ccode_runner, "Gs2", RGET_CLASS( RGET_CLASS(ccode_runner, "Run"), "FortranNamelist" ) ); ccode_runner_gs2_gsl_tensor_complexes = rb_define_module_under(ccode_runner_gs2, "GSLComplexTensors"); rb_include_module(ccode_runner_gs2, ccode_runner_gs2_gsl_tensor_complexes); ccode_runner_gs2_gsl_tensors = rb_define_module_under(ccode_runner_gs2, "GSLTensors"); rb_include_module(ccode_runner_gs2, ccode_runner_gs2_gsl_tensors); cgsl = RGET_CLASS_TOP("GSL"); cgsl_vector = RGET_CLASS(cgsl, "Vector"); cgsl_vector_complex = RGET_CLASS(cgsl_vector, "Complex"); rb_define_method(ccode_runner_gs2_gsl_tensor_complexes, "field_gsl_tensor_complex_2", gs2crmod_tensor_complexes_field_gsl_tensor_complex_2, 1); rb_define_method(ccode_runner_gs2_gsl_tensors, "field_real_space_gsl_tensor", gs2crmod_tensor_field_gsl_tensor, 1); /*rb_define_method(ccode_runner_ext, "hello_world", code_runner_ext_hello_world, 0);*/ }
{ "alphanum_fraction": 0.6239455521, "avg_line_length": 27.5250659631, "ext": "c", "hexsha": "7fa8119db142e6c1dcba0fcc17bd94cddb2f8cff", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-09-01T03:57:21.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-01T03:57:21.000Z", "max_forks_repo_head_hexsha": "c81d228cb677fd0e7ec568f7dde57aa4d041e16c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "coderunner-framework/gs2crmod", "max_forks_repo_path": "ext/gs2crmod_ext.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c81d228cb677fd0e7ec568f7dde57aa4d041e16c", "max_issues_repo_issues_event_max_datetime": "2016-04-05T15:11:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-04-05T15:11:09.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "coderunner-framework/gs2crmod", "max_issues_repo_path": "ext/gs2crmod_ext.c", "max_line_length": 144, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c81d228cb677fd0e7ec568f7dde57aa4d041e16c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "coderunner-framework/gs2crmod", "max_stars_repo_path": "ext/gs2crmod_ext.c", "max_stars_repo_stars_event_max_datetime": "2019-04-15T04:31:35.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-15T04:31:35.000Z", "num_tokens": 3499, "size": 10432 }
#include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include <math.h> #include <options/options.h> #include "../csm/csm_all.h" struct { double interval; int seed; }p ; LDP ld_resample(LDP ld); gsl_rng * rng; int main(int argc, const char ** argv) { sm_set_program_name(argv[0]); struct option* ops = options_allocate(3); options_double(ops, "interval", &p.interval, sqrt(2.0), " 1 = no resampling"); if(!options_parse_args(ops, argc, argv)) { options_print_help(ops, stderr); return -1; } int count = -1; LDP ld; while( (ld = ld_read_smart(stdin))) { count++; if(!ld_valid_fields(ld)) { sm_error("Invalid laser data (#%d in file)\n", count); continue; } /* if(count & 1) {*/ LDP ld2 = ld_resample(ld); ld_write_as_json(ld2, stdout); ld_free(ld2); ld_free(ld); /* } else { ld_write_as_json(ld, stdout); ld_free(ld); }*/ count++; } return 0; } LDP ld_resample(LDP ld) { /* FIXME magic number */ int n = (int) (floor(ld->nrays / p.interval)); LDP ld2 = ld_alloc_new(n); int k; for(k=0;k<n;k++) { double index = k * p.interval; int i = (int) floor(index); int j = i + 1; double a = 1 - (index - i); if( (j>= ld->nrays) || !ld->valid[i] || !ld->valid[j]) { ld2->valid[k] = 0; ld2->readings[k] = NAN; ld2->alpha_valid[k] = 0; ld2->alpha[k] = NAN; ld2->theta[k] = ld->theta[i]; } else { ld2->theta[k] = a * ld->theta[i] + (1-a) * ld->theta[j]; if(is_nan(ld2->theta[k])) { sm_debug("Hey, k=%d theta[%d]=%f theta[%d]=%f\n", k,i,ld->theta[i],j,ld->theta[j]); } ld2->readings[k] = a * ld->readings[i] + (1-a) * ld->readings[j]; ld2->valid[k] = 1; } /* sm_debug("k=%d index=%f i=%d a=%f valid %d reading %f\n", k,index,i,a,ld2->valid[k],ld2->readings[k]);*/ } ld2->min_theta = ld2->theta[0]; ld2->max_theta = ld2->theta[n-1]; ld2->tv = ld->tv; copy_d(ld->odometry, 3, ld2->odometry); copy_d(ld->estimate, 3, ld2->estimate); return ld2; }
{ "alphanum_fraction": 0.5772839506, "avg_line_length": 19.4711538462, "ext": "c", "hexsha": "95b86206ca7df7d00c266fc3c26aacd327297237", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ozaslan/basics", "max_forks_repo_path": "csm/sm/apps/ld_resample.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ozaslan/basics", "max_issues_repo_path": "csm/sm/apps/ld_resample.c", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ozaslan/basics", "max_stars_repo_path": "csm/sm/apps/ld_resample.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 741, "size": 2025 }
/* SO3blas.c */ // SO(3) Lie group implemented with GNU GSL // cf. wikipedia, "Rotation_group_SO(3)#Infinitesimal_rotations" // EY note : 20160519 Bizarrely, matrix multiplication isn't implemented // in a straightforward manner with the gsl_matrix class; // see blas (which I don't know what it is yet) and dgemm for the libraries /* Compiling advice: gcc matrixio.c -lgsl -lgslcblas */ #include <stdio.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> // Function prototype /* int commute(gsl_matrix_view, gsl_matrix_view); */ void commute1(void); // global variables double l_x[] = { 0, 0, 0, 0, 0, -1, 0, 1, 0}; double l_y[] = { 0, 0, 1, 0, 0, 0, -1, 0, 0}; double l_z[] = { 0, -1, 0, 1, 0, 0, 0, 0, 0}; // cannot put gsl_matrix view commands in global; I need to check why: // error: initializer element is not constant int main(void) { gsl_matrix_view L_x = gsl_matrix_view_array(l_x,3,3); gsl_matrix_view L_y = gsl_matrix_view_array(l_y,3,3); gsl_matrix_view L_z = gsl_matrix_view_array(l_z,3,3); printf("[ %g, %g, %g]\n", l_x[0], l_x[1], l_x[2] ); printf("[ %g, %g, %g]\n", l_x[3], l_x[4], l_x[5] ); printf("[ %g, %g, %g]\n\n", l_x[6], l_x[7], l_x[8] ); printf("[ %g, %g, %g]\n", l_y[0], l_y[1], l_y[2] ); printf("[ %g, %g, %g]\n", l_y[3], l_y[4], l_y[5] ); printf("[ %g, %g, %g]\n\n", l_y[6], l_y[7], l_y[8] ); printf("[ %g, %g, %g]\n", l_z[0], l_z[1], l_z[2] ); printf("[ %g, %g, %g]\n", l_z[3], l_z[4], l_z[5] ); printf("[ %g, %g, %g]\n\n", l_z[6], l_z[7], l_z[8] ); double xy[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 }; gsl_matrix_view XY = gsl_matrix_view_array(xy,3,3); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0, &L_x.matrix,&L_z.matrix, 0.0, &XY.matrix); printf("[ %g, %g, %g ]\n", xy[0], xy[1], xy[2]); printf("[ %g, %g, %g ]\n", xy[3], xy[4], xy[5]); printf("[ %g, %g, %g ]\n\n", xy[6], xy[7], xy[8]); commute1(); return 0; } void commute1(void) { gsl_matrix_view L_x = gsl_matrix_view_array(l_x,3,3); gsl_matrix_view L_y = gsl_matrix_view_array(l_y,3,3); gsl_matrix_view L_z = gsl_matrix_view_array(l_z,3,3); double xy[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 }; gsl_matrix_view XY = gsl_matrix_view_array(xy,3,3); double yx[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 }; gsl_matrix_view YX = gsl_matrix_view_array(yx,3,3); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0, &L_x.matrix,&L_y.matrix, 0.0, &XY.matrix); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0, &L_y.matrix,&L_x.matrix, 0.0, &YX.matrix); printf("[ %g, %g, %g ]\n", yx[0], yx[1], yx[2]); printf("[ %g, %g, %g ]\n", yx[3], yx[4], yx[5]); printf("[ %g, %g, %g ]\n", yx[6], yx[7], yx[8]); } /* int commute(gsl_matrix_view X, gsl_matrix_view Y) { double xy[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 }; double yx[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 }; double bracket[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 }; gsl_matrix_view XY = gsl_matrix_view_array(xy,3,3); gsl_matrix_view YX = gsl_matrix_view_array(yx,3,3); gsl_matrix_view Bracket = gsl_matrix_view_array(bracket,3,3); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0, &X.matrix,&Y.matrix, 0.0, &XY.matrix); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0, &X.matrix,&Y.matrix, 0.0, &XY.matrix); gls_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0, &XY.matrix, &YX.matrix, 0.0, &Bracket.matrix); return 1; } */
{ "alphanum_fraction": 0.5796074155, "avg_line_length": 23.5128205128, "ext": "c", "hexsha": "3ef1406edfc6f216f12e9ca51c339cae6fe53e3b", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z", "max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z", "max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ernestyalumni/CompPhys", "max_forks_repo_path": "gslExamples/SO3blas.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ernestyalumni/CompPhys", "max_issues_repo_path": "gslExamples/SO3blas.c", "max_line_length": 75, "max_stars_count": 70, "max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ernestyalumni/CompPhys", "max_stars_repo_path": "gslExamples/SO3blas.c", "max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z", "num_tokens": 1583, "size": 3668 }
#include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "cconfigspace_internal.h" #include "distribution_internal.h" struct _ccs_distribution_uniform_data_s { _ccs_distribution_common_data_t common_data; ccs_numeric_t lower; ccs_numeric_t upper; ccs_scale_type_t scale_type; ccs_numeric_t quantization; ccs_numeric_type_t internal_type; ccs_numeric_t internal_lower; ccs_numeric_t internal_upper; int quantize; }; typedef struct _ccs_distribution_uniform_data_s _ccs_distribution_uniform_data_t; static ccs_result_t _ccs_distribution_del(ccs_object_t o) { (void)o; return CCS_SUCCESS; } static ccs_result_t _ccs_distribution_uniform_get_bounds(_ccs_distribution_data_t *data, ccs_interval_t *interval_ret); static ccs_result_t _ccs_distribution_uniform_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t *values); static ccs_result_t _ccs_distribution_uniform_strided_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, size_t stride, ccs_numeric_t *values); static ccs_result_t _ccs_distribution_uniform_soa_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t **values); static _ccs_distribution_ops_t _ccs_distribution_uniform_ops = { { &_ccs_distribution_del }, &_ccs_distribution_uniform_samples, &_ccs_distribution_uniform_get_bounds, &_ccs_distribution_uniform_strided_samples, &_ccs_distribution_uniform_soa_samples }; static ccs_result_t _ccs_distribution_uniform_get_bounds(_ccs_distribution_data_t *data, ccs_interval_t *interval_ret) { _ccs_distribution_uniform_data_t *d = (_ccs_distribution_uniform_data_t *)data; ccs_numeric_t l; ccs_bool_t li; ccs_numeric_t u; ccs_bool_t ui; l = d->lower; li = CCS_TRUE; u = d->upper; ui = CCS_FALSE; interval_ret->type = d->common_data.data_types[0]; interval_ret->lower = l; interval_ret->upper = u; interval_ret->lower_included = li; interval_ret->upper_included = ui; return CCS_SUCCESS; } static ccs_result_t _ccs_distribution_uniform_strided_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, size_t stride, ccs_numeric_t *values) { _ccs_distribution_uniform_data_t *d = (_ccs_distribution_uniform_data_t *)data; size_t i; const ccs_numeric_type_t data_type = d->common_data.data_types[0]; const ccs_scale_type_t scale_type = d->scale_type; const ccs_numeric_t quantization = d->quantization; const ccs_numeric_t lower = d->lower; const ccs_numeric_t internal_lower = d->internal_lower; const ccs_numeric_t internal_upper = d->internal_upper; const int quantize = d->quantize; gsl_rng *grng; CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng)); if (data_type == CCS_NUM_FLOAT) { for (i = 0; i < num_values; i++) { values[i*stride].f = gsl_ran_flat(grng, internal_lower.f, internal_upper.f); } if (scale_type == CCS_LOGARITHMIC) { for (i = 0; i < num_values; i++) values[i*stride].f = exp(values[i*stride].f); if (quantize) for (i = 0; i < num_values; i++) values[i*stride].f = floor((values[i*stride].f - lower.f)/quantization.f) * quantization.f + lower.f; } else if (quantize) for (i = 0; i < num_values; i++) values[i*stride].f = floor(values[i*stride].f) * quantization.f + lower.f; else for (i = 0; i < num_values; i++) values[i*stride].f += lower.f; } else { if (scale_type == CCS_LOGARITHMIC) { for (i = 0; i < num_values; i++) { values[i*stride].i = floor(exp(gsl_ran_flat(grng, internal_lower.f, internal_upper.f))); } if (quantize) for (i = 0; i < num_values; i++) values[i*stride].i = ((values[i*stride].i - lower.i)/quantization.i) * quantization.i + lower.i; } else { for (i = 0; i < num_values; i++) { values[i*stride].i = gsl_rng_uniform_int(grng, internal_upper.i); } if (quantize) for (i = 0; i < num_values; i++) values[i*stride].i = values[i*stride].i * quantization.i + lower.i; else for (i = 0; i < num_values; i++) values[i*stride].i += lower.i; } } return CCS_SUCCESS; } static ccs_result_t _ccs_distribution_uniform_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t *values) { _ccs_distribution_uniform_data_t *d = (_ccs_distribution_uniform_data_t *)data; size_t i; const ccs_numeric_type_t data_type = d->common_data.data_types[0]; const ccs_scale_type_t scale_type = d->scale_type; const ccs_numeric_t quantization = d->quantization; const ccs_numeric_t lower = d->lower; const ccs_numeric_t internal_lower = d->internal_lower; const ccs_numeric_t internal_upper = d->internal_upper; const int quantize = d->quantize; gsl_rng *grng; CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng)); if (data_type == CCS_NUM_FLOAT) { for (i = 0; i < num_values; i++) { values[i].f = gsl_ran_flat(grng, internal_lower.f, internal_upper.f); } if (scale_type == CCS_LOGARITHMIC) { for (i = 0; i < num_values; i++) values[i].f = exp(values[i].f); if (quantize) for (i = 0; i < num_values; i++) values[i].f = floor((values[i].f - lower.f)/quantization.f) * quantization.f + lower.f; } else if (quantize) for (i = 0; i < num_values; i++) values[i].f = floor(values[i].f) * quantization.f + lower.f; else for (i = 0; i < num_values; i++) values[i].f += lower.f; } else { if (scale_type == CCS_LOGARITHMIC) { for (i = 0; i < num_values; i++) { values[i].i = floor(exp(gsl_ran_flat(grng, internal_lower.f, internal_upper.f))); } if (quantize) for (i = 0; i < num_values; i++) values[i].i = ((values[i].i - lower.i)/quantization.i) * quantization.i + lower.i; } else { for (i = 0; i < num_values; i++) { values[i].i = gsl_rng_uniform_int(grng, internal_upper.i); } if (quantize) for (i = 0; i < num_values; i++) values[i].i = values[i].i * quantization.i + lower.i; else for (i = 0; i < num_values; i++) values[i].i += lower.i; } } return CCS_SUCCESS; } static ccs_result_t _ccs_distribution_uniform_soa_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t **values) { if (*values) return _ccs_distribution_uniform_samples(data, rng, num_values, *values); return CCS_SUCCESS; } ccs_result_t ccs_create_uniform_distribution(ccs_numeric_type_t data_type, ccs_numeric_t lower, ccs_numeric_t upper, ccs_scale_type_t scale_type, ccs_numeric_t quantization, ccs_distribution_t *distribution_ret) { CCS_CHECK_PTR(distribution_ret); if (data_type != CCS_NUM_FLOAT && data_type != CCS_NUM_INTEGER) return -CCS_INVALID_TYPE; if (scale_type != CCS_LINEAR && scale_type != CCS_LOGARITHMIC) return -CCS_INVALID_SCALE; if (data_type == CCS_NUM_INTEGER && ( lower.i >= upper.i || (scale_type == CCS_LOGARITHMIC && lower.i <= 0) || quantization.i < 0 || quantization.i > upper.i - lower.i ) ) return -CCS_INVALID_VALUE; if (data_type == CCS_NUM_FLOAT && ( lower.f >= upper.f || (scale_type == CCS_LOGARITHMIC && lower.f <= 0.0) || quantization.f < 0.0 || quantization.f > upper.f - lower.f ) ) return -CCS_INVALID_VALUE; uintptr_t mem = (uintptr_t)calloc(1, sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_uniform_data_t) + sizeof(ccs_numeric_type_t)); if (!mem) return -CCS_OUT_OF_MEMORY; ccs_distribution_t distrib = (ccs_distribution_t)mem; _ccs_object_init(&(distrib->obj), CCS_DISTRIBUTION, (_ccs_object_ops_t *)&_ccs_distribution_uniform_ops); _ccs_distribution_uniform_data_t * distrib_data = (_ccs_distribution_uniform_data_t *)(mem + sizeof(struct _ccs_distribution_s)); distrib_data->common_data.data_types = (ccs_numeric_type_t *)(mem + sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_uniform_data_t)); distrib_data->common_data.type = CCS_UNIFORM; distrib_data->common_data.dimension = 1; distrib_data->common_data.data_types[0] = data_type; distrib_data->scale_type = scale_type; distrib_data->quantization = quantization; distrib_data->lower = lower; distrib_data->upper = upper; if (data_type == CCS_NUM_FLOAT) { if (quantization.f != 0.0) distrib_data->quantize = 1; if (scale_type == CCS_LOGARITHMIC) { distrib_data->internal_lower.f = log(lower.f); distrib_data->internal_upper.f = log(upper.f); } else { distrib_data->internal_lower.f = 0.0; distrib_data->internal_upper.f = upper.f - lower.f; if (distrib_data->quantize) distrib_data->internal_upper.f /= quantization.f; } } else { if (quantization.i != 0) distrib_data->quantize = 1; if (scale_type == CCS_LOGARITHMIC) { distrib_data->internal_lower.f = log(lower.i); distrib_data->internal_upper.f = log(upper.i); } else { distrib_data->internal_lower.i = 0; distrib_data->internal_upper.i = upper.i - lower.i; if (quantization.i != 0) distrib_data->internal_upper.i /= quantization.i; } } distrib->data = (_ccs_distribution_data_t *)distrib_data; *distribution_ret = distrib; return CCS_SUCCESS; } ccs_result_t ccs_uniform_distribution_get_parameters(ccs_distribution_t distribution, ccs_numeric_t *lower_ret, ccs_numeric_t *upper_ret, ccs_scale_type_t *scale_type_ret, ccs_numeric_t *quantization_ret) { CCS_CHECK_DISTRIBUTION(distribution, CCS_UNIFORM); if (!lower_ret && !upper_ret && !scale_type_ret && !quantization_ret) return -CCS_INVALID_VALUE; _ccs_distribution_uniform_data_t * data = (_ccs_distribution_uniform_data_t *)distribution->data; if (lower_ret) *lower_ret = data->lower; if (upper_ret) *upper_ret = data->upper; if (scale_type_ret) *scale_type_ret = data->scale_type; if (quantization_ret) *quantization_ret = data->quantization; return CCS_SUCCESS; }
{ "alphanum_fraction": 0.6086695279, "avg_line_length": 39.2255892256, "ext": "c", "hexsha": "7614572d500ec486489589efc9baecb3f6e57a4d", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z", "max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z", "max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "deephyper/CCS", "max_forks_repo_path": "src/distribution_uniform.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "deephyper/CCS", "max_issues_repo_path": "src/distribution_uniform.c", "max_line_length": 151, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "deephyper/CCS", "max_stars_repo_path": "src/distribution_uniform.c", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z", "num_tokens": 2916, "size": 11650 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" #ifdef PEDANTIC_MEMORY_HANDLER #define MAXBLOCKS 5000 #ifdef PEDANTIC_MEMORY_CEILING static size_t TotBytes; static void *Base; #endif static unsigned long Nblocks; static double Highmark; static void **Table; static size_t *BlockSize; void mymalloc_init(void) { #ifdef PEDANTIC_MEMORY_CEILING size_t n; #endif BlockSize = (size_t *) malloc(MAXBLOCKS * sizeof(size_t)); Table = (void **) malloc(MAXBLOCKS * sizeof(void *)); #ifdef PEDANTIC_MEMORY_CEILING n = PEDANTIC_MEMORY_CEILING * 1024.0 * 1024.0; if(!(Base = malloc(n))) { printf("Failed to allocate memory for `Base' (%d Mbytes).\n", (int) PEDANTIC_MEMORY_CEILING); endrun(122); } TotBytes = FreeBytes = n; #endif AllocatedBytes = 0; Nblocks = 0; Highmark = 0; } void *mymalloc(size_t n) { if((n % 8) > 0) n = (n / 8 + 1) * 8; if(n < 8) n = 8; if(Nblocks >= MAXBLOCKS) { printf("Task=%d: No blocks left in mymalloc().\n", ThisTask); endrun(813); } #ifdef PEDANTIC_MEMORY_CEILING if(n > FreeBytes) { printf("Task=%d: Not enough memory in mymalloc(n=%g MB). FreeBytes=%g MB\n", ThisTask, n / (1024.0 * 1024.0), FreeBytes / (1024.0 * 1024.0)); endrun(812); } Table[Nblocks] = Base + (TotBytes - FreeBytes); FreeBytes -= n; #else Table[Nblocks] = malloc(n); if(!(Table[Nblocks])) { printf("failed to allocate %g MB of memory. (presently allocated=%g MB)\n", n / (1024.0 * 1024.0), AllocatedBytes / (1024.0 * 1024.0)); endrun(18); } #endif AllocatedBytes += n; BlockSize[Nblocks] = n; Nblocks += 1; /* if(AllocatedBytes / (1024.0 * 1024.0) > Highmark) { Highmark = AllocatedBytes / (1024.0 * 1024.0); printf("Task=%d: new highmark=%g MB\n", ThisTask, Highmark); fflush(stdout); } */ return Table[Nblocks - 1]; } void *mymalloc_msg(size_t n, char *message) { if((n % 8) > 0) n = (n / 8 + 1) * 8; if(n < 8) n = 8; if(Nblocks >= MAXBLOCKS) { printf("Task=%d: No blocks left in mymalloc().\n", ThisTask); endrun(813); } #ifdef PEDANTIC_MEMORY_CEILING if(n > FreeBytes) { printf ("Task=%d: Not enough memory in for allocating (n=%g MB) for block='%s'. FreeBytes=%g MB AllocatedBytes=%g MB.\n", ThisTask, n / (1024.0 * 1024.0), message, FreeBytes / (1024.0 * 1024.0), AllocatedBytes / (1024.0 * 1024.0)); endrun(812); } Table[Nblocks] = Base + (TotBytes - FreeBytes); FreeBytes -= n; #else Table[Nblocks] = malloc(n); if(!(Table[Nblocks])) { printf("failed to allocate %g MB of memory for block='%s'. (presently allocated=%g MB)\n", n / (1024.0 * 1024.0), message, AllocatedBytes / (1024.0 * 1024.0)); endrun(18); } #endif AllocatedBytes += n; BlockSize[Nblocks] = n; Nblocks += 1; return Table[Nblocks - 1]; } void myfree(void *p) { if(Nblocks == 0) endrun(76878); if(p != Table[Nblocks - 1]) { printf("Task=%d: Wrong call of myfree() - not the last allocated block!\n", ThisTask); fflush(stdout); endrun(814); } Nblocks -= 1; AllocatedBytes -= BlockSize[Nblocks]; #ifdef PEDANTIC_MEMORY_CEILING FreeBytes += BlockSize[Nblocks]; #else free(p); #endif } void myfree_msg(void *p, char *msg) { if(Nblocks == 0) endrun(76878); if(p != Table[Nblocks - 1]) { printf("Task=%d: Wrong call of myfree() - '%s' not the last allocated block!\n", ThisTask, msg); fflush(stdout); endrun(8141); } Nblocks -= 1; AllocatedBytes -= BlockSize[Nblocks]; #ifdef PEDANTIC_MEMORY_CEILING FreeBytes += BlockSize[Nblocks]; #else free(p); #endif } void *myrealloc(void *p, size_t n) { if((n % 8) > 0) n = (n / 8 + 1) * 8; if(n < 8) n = 8; if(Nblocks == 0) endrun(76879); if(p != Table[Nblocks - 1]) { printf("Task=%d: Wrong call of myrealloc() - not the last allocated block!\n", ThisTask); fflush(stdout); endrun(815); } AllocatedBytes -= BlockSize[Nblocks - 1]; #ifdef PEDANTIC_MEMORY_CEILING FreeBytes += BlockSize[Nblocks - 1]; #endif #ifdef PEDANTIC_MEMORY_CEILING if(n > FreeBytes) { printf("Task=%d: Not enough memory in myremalloc(n=%g MB). previous=%g FreeBytes=%g MB\n", ThisTask, n / (1024.0 * 1024.0), BlockSize[Nblocks - 1] / (1024.0 * 1024.0), FreeBytes / (1024.0 * 1024.0)); endrun(812); } Table[Nblocks - 1] = Base + (TotBytes - FreeBytes); FreeBytes -= n; #else Table[Nblocks - 1] = realloc(Table[Nblocks - 1], n); if(!(Table[Nblocks - 1])) { printf("failed to reallocate %g MB of memory. previous=%g FreeBytes=%g MB\n", n / (1024.0 * 1024.0), BlockSize[Nblocks - 1] / (1024.0 * 1024.0), FreeBytes / (1024.0 * 1024.0)); endrun(18123); } #endif AllocatedBytes += n; BlockSize[Nblocks - 1] = n; return Table[Nblocks - 1]; } #else void mymalloc_init(void) { AllocatedBytes = 0; } void *mymalloc(size_t n) { void *ptr; if(n < 8) n = 8; ptr = malloc(n); if(!(ptr)) { printf("failed to allocate %g MB of memory.\n", n / (1024.0 * 1024.0)); endrun(14); } return ptr; } void *mymalloc_msg(size_t n, char *message) { void *ptr; if(n < 8) n = 8; ptr = malloc(n); if(!(ptr)) { printf("failed to allocate %g MB of memory when trying to allocate '%s'.\n", n / (1024.0 * 1024.0), message); endrun(14); } return ptr; } void *myrealloc(void *p, size_t n) { void *ptr; ptr = realloc(p, n); if(!(ptr)) { printf("failed to re-allocate %g MB of memory.\n", n / (1024.0 * 1024.0)); endrun(15); } return ptr; } void myfree(void *p) { free(p); } void myfree_msg(void *p, char *msg) { free(p); } #endif
{ "alphanum_fraction": 0.5883338921, "avg_line_length": 18.3006134969, "ext": "c", "hexsha": "ece3f4f38ac49cf7e2deb79d2467b40b99003983", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/mymalloc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/mymalloc.c", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/mymalloc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1997, "size": 5966 }
/* fft/errs.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_dft_complex.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_test.h> #include "compare.h" #include "complex_internal.h" #include "urand.c" int verbose = 0; size_t tests = 0; size_t passed = 0; size_t failed = 0; int main (int argc, char *argv[]) { int status, factor_sum; size_t i, start, end, n; double *complex_data, *complex_tmp; double rms, total; gsl_fft_complex_wavetable * cw; if (argc == 2) { start = strtol (argv[1], NULL, 0); end = start + 1; } else { start = 1 ; end = 1000 ; } for (n = start; n < end; n++) { complex_data = (double *) malloc (n * 2 * sizeof (double)); complex_tmp = (double *) malloc (n * 2 * sizeof (double)); cw = gsl_fft_complex_wavetable_alloc (n); status = gsl_fft_complex_init (n, cw); status = gsl_fft_complex_generate (n, cw); for (i = 0; i < n; i++) { REAL(complex_data,1,i) = urand(); IMAG(complex_data,1,i) = urand(); } memcpy (complex_tmp, complex_data, n * 2 * sizeof (double)); gsl_fft_complex_forward (complex_data, 1, n, cw); gsl_fft_complex_inverse (complex_data, 1, n, cw); total = 0.0; for (i = 0; i < n; i++) { double dr = REAL(complex_data,1,i) - REAL(complex_tmp,1,i); double di = IMAG(complex_data,1,i) - IMAG(complex_tmp,1,i); total += dr * dr + di * di; } rms = sqrt (total / n); factor_sum = 0; for (i = 0; i < cw->nf; i++) { int j = cw->factor[i]; factor_sum += j; } printf ("n = %d factor_sum = %d rms = %e\n", n, factor_sum, rms); free (complex_data); free (complex_tmp); } return 0; }
{ "alphanum_fraction": 0.6124777184, "avg_line_length": 24.6052631579, "ext": "c", "hexsha": "18edcfeded44e8e574ce65d5def8b3554defd7b8", "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/errs.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/errs.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/fft/errs.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": 815, "size": 2805 }
/* deriv/test.c * * Copyright (C) 2000 David Morrison * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> double f1 (double x, void *params) { return exp (x); } double df1 (double x, void *params) { return exp (x); } double f2 (double x, void *params) { if (x >= 0.0) { return x * sqrt (x); } else { return 0.0; } } double df2 (double x, void *params) { if (x >= 0.0) { return 1.5 * sqrt (x); } else { return 0.0; } } double f3 (double x, void *params) { if (x != 0.0) { return sin (1 / x); } else { return 0.0; } } double df3 (double x, void *params) { if (x != 0.0) { return -cos (1 / x) / (x * x); } else { return 0.0; } } double f4 (double x, void *params) { return exp (-x * x); } double df4 (double x, void *params) { return -2.0 * x * exp (-x * x); } double f5 (double x, void *params) { return x * x; } double df5 (double x, void *params) { return 2.0 * x; } double f6 (double x, void *params) { return 1.0 / x; } double df6 (double x, void *params) { return -1.0 / (x * x); } typedef int (deriv_fn) (const gsl_function * f, double x, double h, double * res, double *abserr); void test (deriv_fn * deriv, gsl_function * f, gsl_function * df, double x, const char * desc) { double result, abserr; double expected = GSL_FN_EVAL (df, x); (*deriv) (f, x, 1e-4, &result, &abserr); gsl_test_abs (result, expected, GSL_MIN(1e-4,fabs(expected)) + GSL_DBL_EPSILON, desc); if (abserr < fabs(result-expected)) { gsl_test_factor (abserr, fabs(result-expected), 2, "%s error estimate", desc); } else if (result == expected || expected == 0.0) { gsl_test_abs (abserr, 0.0, 1e-6, "%s abserr", desc); } else { double d = fabs(result - expected); gsl_test_abs (abserr, fabs(result-expected), 1e6*d, "%s abserr", desc); } } int main () { gsl_function F1, DF1, F2, DF2, F3, DF3, F4, DF4, F5, DF5, F6, DF6; gsl_ieee_env_setup (); F1.function = &f1; DF1.function = &df1; F2.function = &f2; DF2.function = &df2; F3.function = &f3; DF3.function = &df3; F4.function = &f4; DF4.function = &df4; F5.function = &f5; DF5.function = &df5; F6.function = &f6; DF6.function = &df6; test (&gsl_deriv_central, &F1, &DF1, 1.0, "exp(x), x=1, central deriv"); test (&gsl_deriv_forward, &F1, &DF1, 1.0, "exp(x), x=1, forward deriv"); test (&gsl_deriv_backward, &F1, &DF1, 1.0, "exp(x), x=1, backward deriv"); test (&gsl_deriv_central, &F2, &DF2, 0.1, "x^(3/2), x=0.1, central deriv"); test (&gsl_deriv_forward, &F2, &DF2, 0.1, "x^(3/2), x=0.1, forward deriv"); test (&gsl_deriv_backward, &F2, &DF2, 0.1, "x^(3/2), x=0.1, backward deriv"); test (&gsl_deriv_central, &F3, &DF3, 0.45, "sin(1/x), x=0.45, central deriv"); test (&gsl_deriv_forward, &F3, &DF3, 0.45, "sin(1/x), x=0.45, forward deriv"); test (&gsl_deriv_backward, &F3, &DF3, 0.45, "sin(1/x), x=0.45, backward deriv"); test (&gsl_deriv_central, &F4, &DF4, 0.5, "exp(-x^2), x=0.5, central deriv"); test (&gsl_deriv_forward, &F4, &DF4, 0.5, "exp(-x^2), x=0.5, forward deriv"); test (&gsl_deriv_backward, &F4, &DF4, 0.5, "exp(-x^2), x=0.5, backward deriv"); test (&gsl_deriv_central, &F5, &DF5, 0.0, "x^2, x=0, central deriv"); test (&gsl_deriv_forward, &F5, &DF5, 0.0, "x^2, x=0, forward deriv"); test (&gsl_deriv_backward, &F5, &DF5, 0.0, "x^2, x=0, backward deriv"); test (&gsl_deriv_central, &F6, &DF6, 10.0, "1/x, x=10, central deriv"); test (&gsl_deriv_forward, &F6, &DF6, 10.0, "1/x, x=10, forward deriv"); test (&gsl_deriv_backward, &F6, &DF6, 10.0, "1/x, x=10, backward deriv"); exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.6095831543, "avg_line_length": 22.1619047619, "ext": "c", "hexsha": "42463d38ef2b809af981234b7f5db9fe45916324", "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/deriv/test.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/deriv/test.c", "max_line_length": 98, "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/deriv/test.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": 1696, "size": 4654 }
/*! \file Compute 3D shape features and moments. The following functions compute several shape features, including central moments, center of gravity, and volume size. \par Author: Gabriele Lohmann, MPI-CBS */ /* From the Vista library: */ #include <viaio/Vlib.h> #include <viaio/mu.h> #include <via/via.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_eigen.h> /* From the standard C libaray: */ #include <stdio.h> #include <stdlib.h> #include <math.h> #define SQR(x) ((x)*(x)) #define ABS(x) ((x) > 0 ? (x) : -(x)) static double power(double a, int k) { register double res; register int i; res = 1.0; for (i=0; i<k; i++) res *= a; return res; } /*! \fn void VolumeCentroid(Volume v,double mean[3]) \brief Compute center of gravity of a volume. \param v input volume. \param *mean output array. The center of gravity is returned in mean[0],mean[1],mean[2]. Sufficient memory must have been allocated for <mean> prior to the call. */ void VolumeCentroid(Volume v, double mean[3]) { double npixels; long c,i,ce; VTrack t; mean[0] = 0; mean[1] = 0; mean[2] = 0; npixels = 0; for (i=0; i<v->nbuckets; i++) { for (t = v->bucket[i].first; t != NULL; t = t->next) { mean[0] += (double) (t->band * t->length); mean[1] += (double) (t->row * t->length); ce = t->col + t->length; for (c = t->col; c<ce; c++) mean[2] += (double) c; npixels += t->length; } } if (npixels > 0) { mean[0] /= npixels; mean[1] /= npixels; mean[2] /= npixels; } } /*! \fn double VolumeMoment(Volume v,double mean[3],int m0,int m1,int m2) \brief Compute central moments of a volume. \param v input volume \param *mean input array containing the center of gravity as mean[0],mean[1],mean[2] (slice,row,column). If mean is NULL, the center of gravity is taken to be (0,0,0). \param m0 first index of moment \param m1 second index of moment \param m2 third index of moment */ double VolumeMoment(Volume v,double mean[3],long m0,long m1,long m2) { double res=0; double a = 1.0,sum = 0; long i,ca,ce,ci; double b,r,c; VTrack t; double g0,g1,g2; g0 = mean[0]; g1 = mean[1]; g2 = mean[2]; res = 0; for (i=0; i<v->nbuckets; i++) { for (t = v->bucket[i].first; t != NULL; t = t->next) { b = (double) t->band - g0; r = (double) t->row - g1; a = power(b,m0) * power(r,m1); ca = t->col; ce = ca + t->length; sum = 0; for (ci=ca; ci<ce; ci++) { c = (double)(ci - g2); sum += power(c,m2); } res += sum * a; } } return res; } /*! \fn void VBinCentroid(VImage src,double mean[3]) \brief Compute central moments of a binary raster image. \param src input image (bit repn) \param *mean output array. The center of gravity is returned in mean[0],mean[1],mean[2]. Sufficient memory must have been allocated for <mean> prior to the call. */ void VBinCentroid(VImage src,double mean[3]) { double npixels; long b,r,c; mean[0] = 0; mean[1] = 0; mean[2] = 0; npixels = 0; for (b=0; b<VImageNBands(src); b++) { for (r=0; r<VImageNRows(src); r++) { for (c=0; c<VImageNColumns(src); c++) { if (VPixel(src,b,r,c,VBit) > 0) { mean[0] += b; mean[1] += r; mean[2] += c; npixels++; } } } } if (npixels > 0) { mean[0] /= npixels; mean[1] /= npixels; mean[2] /= npixels; } } /*! \fn double VBinMoment(VImage src,double mean[3],int m0, int m1, int m2) \brief Compute central moments of a binary raster image. \param src input image (bit repn) \param *mean input array containing the center of gravity as mean[0],mean[1],mean[2] (slice,row,column). If mean is NULL, the center of gravity is taken to be (0,0,0); \param m0 first index of moment \param m1 second index of moment \param m2 third index of moment */ double VBinMoment(VImage src, double mean[3], long m0, long m1, long m2) { double res; long b,r,c; double g0,g1,g2; g0 = mean[0]; g1 = mean[1]; g2 = mean[2]; res = 0; for (b=0; b<VImageNBands(src); b++) { for (r=0; r<VImageNRows(src); r++) { for (c=0; c<VImageNColumns(src); c++) { if (VPixel(src,b,r,c,VBit) > 0) res += power((double)(b - g0),m0) * power((double)(r - g1),m1) * power((double)(c - g2),m2); } } } return res; } /*! \fn long VolumeSize(Volume v) \brief compute volume size, output the number of voxels of a single volume \param v a single volume */ long VolumeSize(Volume v) { long i,isize; VTrack t; isize = 0; for (i=0; i<VolumeNBuckets(v); i++) { for (t = VFirstTrack(v,i); VTrackExists(t); t = VNextTrack(t)) isize += VTrackLength(t); } return isize; } /*! \fn long VBinSize(VImage src) \brief count number of foreground voxels. \param src input image (bit repn) */ long VBinSize(VImage src) { long n; long i; VBit *bin_pp; if (VPixelRepn(src) != VBitRepn) VError(" input image must be bit repn"); n = 0; bin_pp = (VBit *) VPixelPtr(src,0,0,0); for (i=0; i<VImageNPixels(src); i++) { if (*bin_pp > 0) n++; bin_pp++; } return n; } /*! \fn float VolumeDir(Volume vol,float *e,float x[3]) \brief computer principal direction of a volume from its interia matrix \param vol input volume \param e output largest eigenvalue \param x output first eigenvector */ float VolumeDir(Volume vol,float *e,float x[3]) { gsl_matrix *a=NULL; static gsl_matrix *evec=NULL; static gsl_vector *eval=NULL; static gsl_eigen_symmv_workspace *workspace=NULL; double m020,m002,m200,m110,m101,m011; double norm,angle; double mean[3]; float tiny=1.0e-5; mean[0] = mean[1] = mean[2] = 0; VolumeCentroid(vol,mean); m020 = VolumeMoment(vol,mean,0,2,0); m002 = VolumeMoment(vol,mean,0,0,2); m200 = VolumeMoment(vol,mean,2,0,0); m110 = VolumeMoment(vol,mean,1,1,0); m101 = VolumeMoment(vol,mean,1,0,1); m011 = VolumeMoment(vol,mean,0,1,1); /* inertia matrix */ if (a == NULL) { a = gsl_matrix_calloc(3,3); workspace = gsl_eigen_symmv_alloc(3); } gsl_matrix_set(a,0,0,m020 + m002); gsl_matrix_set(a,1,1,m200 + m002); gsl_matrix_set(a,2,2,m200 + m020); gsl_matrix_set(a,0,1,-m110); gsl_matrix_set(a,1,0,-m110); gsl_matrix_set(a,0,2,-m101); gsl_matrix_set(a,2,0,-m101); gsl_matrix_set(a,1,2,-m011); gsl_matrix_set(a,2,1,-m011); gsl_eigen_symmv(a,eval,evec,workspace); gsl_eigen_symmv_sort(eval,evec,GSL_EIGEN_SORT_VAL_DESC); x[0] = gsl_matrix_get(evec,0,0); x[1] = gsl_matrix_get(evec,1,0); x[2] = gsl_matrix_get(evec,2,0); *e = gsl_vector_get(eval,0); angle = 0; norm = sqrt((double)(SQR(x[0]) + SQR(x[1]) + SQR(x[2]))); if (norm > tiny) { angle = ABS(x[1])/ norm; } return angle; } /*! \fn void VolumeEigen(Volume vol,gsl_vector *eval,gsl_matrix *evec) \brief computer principal directions of a volume from its interia matrix \param vol input volume \param eval output eigenvalues \param evec output matrix of eigenvectors (columns) */ void VolumeEigen(Volume vol,gsl_vector *eval,gsl_matrix *evec) { static gsl_matrix *a=NULL; static gsl_eigen_symmv_workspace *workspace=NULL; double m020,m002,m200,m110,m101,m011; double mean[3]; mean[0] = mean[1] = mean[2] = 0; VolumeCentroid(vol,mean); m020 = VolumeMoment(vol,mean,0,2,0); m002 = VolumeMoment(vol,mean,0,0,2); m200 = VolumeMoment(vol,mean,2,0,0); m110 = VolumeMoment(vol,mean,1,1,0); m101 = VolumeMoment(vol,mean,1,0,1); m011 = VolumeMoment(vol,mean,0,1,1); /* inertia matrix */ if (a == NULL) { a = gsl_matrix_calloc(3,3); workspace = gsl_eigen_symmv_alloc(3); } gsl_matrix_set(a,0,0,m020 + m002); gsl_matrix_set(a,1,1,m200 + m002); gsl_matrix_set(a,2,2,m200 + m020); gsl_matrix_set(a,0,1,-m110); gsl_matrix_set(a,1,0,-m110); gsl_matrix_set(a,0,2,-m101); gsl_matrix_set(a,2,0,-m101); gsl_matrix_set(a,1,2,-m011); gsl_matrix_set(a,2,1,-m011); gsl_eigen_symmv(a,eval,evec,workspace); gsl_eigen_symmv_sort(eval,evec,GSL_EIGEN_SORT_VAL_DESC); return; }
{ "alphanum_fraction": 0.6272682688, "avg_line_length": 21.807486631, "ext": "c", "hexsha": "41116d0df07f0e61aa17a60a4e1244af05694f51", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/lib_via/ShapeMoments.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/lib_via/ShapeMoments.c", "max_line_length": 76, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/lib_via/ShapeMoments.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 2819, "size": 8156 }
#pragma once // v1.2 By Ook // #include <concepts> #include <gsl/gsl> namespace EnumConcepts { template <class T> concept IsEnum = std::is_enum_v<T>; template<class _Ty> struct is_Numeric : std::integral_constant<bool, (std::is_arithmetic_v<_Ty> || std::is_same_v<_Ty, std::byte> || std::is_enum_v<_Ty>) && !std::is_same_v<_Ty, wchar_t> && !std::is_same_v<_Ty, char> && !std::is_pointer_v<_Ty> //&& !std::is_enum_v<_Ty> > { }; // determine whether T is a Number type (excluding char / wchar), same as is_Numeric<T>::value template <typename T> constexpr bool is_Numeric_v = is_Numeric<T>::value; template <class T> concept IsNumeric = is_Numeric_v<T>; } //template <EnumConcepts::IsEnum E> //constexpr E& operator |=(E& eStyle, const E& dStyle) noexcept //{ // if constexpr (sizeof(E) <= sizeof(size_t)) // eStyle = static_cast<E>(static_cast<size_t>(eStyle) | static_cast<size_t>(dStyle)); // else // eStyle = static_cast<E>(static_cast<uint64_t>(eStyle) | static_cast<uint64_t>(dStyle)); // return eStyle; //} template <EnumConcepts::IsNumeric T, EnumConcepts::IsEnum E> constexpr E& operator |=(E& eStyle, const T& dStyle) noexcept { if constexpr(sizeof(E) <= sizeof(size_t) && sizeof(T) <= sizeof(size_t)) eStyle = static_cast<E>(static_cast<size_t>(eStyle) | static_cast<size_t>(dStyle)); else eStyle = static_cast<E>(static_cast<uint64_t>(eStyle) | static_cast<uint64_t>(dStyle)); return eStyle; } //template <EnumConcepts::IsNumeric T, EnumConcepts::IsEnum E> //constexpr T& operator |=(T& dStyle, const E& eStyle) noexcept //{ // //if constexpr (sizeof(E) <= sizeof(size_t) && sizeof(T) <= sizeof(size_t)) // // dStyle = static_cast<T>(static_cast<size_t>(eStyle) | static_cast<size_t>(dStyle)); // //else // // dStyle = static_cast<T>(static_cast<uint64_t>(eStyle) | static_cast<uint64_t>(dStyle)); // //return dStyle; // // dStyle |= static_cast<T>(eStyle); // // return dStyle; //} template <EnumConcepts::IsNumeric T, EnumConcepts::IsEnum E> constexpr E operator |(const E& eStyle, const T& dStyle) noexcept { if constexpr (sizeof(E) <= sizeof(size_t) && sizeof(T) <= sizeof(size_t)) return static_cast<E>(static_cast<size_t>(eStyle) | static_cast<size_t>(dStyle)); else return static_cast<E>(static_cast<uint64_t>(eStyle) | static_cast<uint64_t>(dStyle)); } template <EnumConcepts::IsNumeric T, EnumConcepts::IsEnum E> constexpr E& operator &=(E& eStyle, const T& dStyle) noexcept { if constexpr (sizeof(E) <= sizeof(size_t) && sizeof(T) <= sizeof(size_t)) eStyle = static_cast<E>(static_cast<size_t>(eStyle) & static_cast<size_t>(dStyle)); else eStyle = static_cast<E>(static_cast<uint64_t>(eStyle) & static_cast<uint64_t>(dStyle)); return eStyle; } template <EnumConcepts::IsNumeric T, EnumConcepts::IsEnum E> constexpr E operator &(const E& eStyle, const T& dStyle) noexcept { if constexpr (sizeof(E) <= sizeof(size_t) && sizeof(T) <= sizeof(size_t)) return static_cast<E>(static_cast<size_t>(eStyle) & static_cast<size_t>(dStyle)); else return static_cast<E>(static_cast<uint64_t>(eStyle) & static_cast<uint64_t>(dStyle)); } template <EnumConcepts::IsNumeric T, EnumConcepts::IsEnum E> constexpr E operator ^(const E& eStyle, const T& dStyle) noexcept { if constexpr (sizeof(E) <= sizeof(size_t) && sizeof(T) <= sizeof(size_t)) return static_cast<E>(static_cast<size_t>(eStyle) ^ static_cast<size_t>(dStyle)); else return static_cast<E>(static_cast<uint64_t>(eStyle) ^ static_cast<uint64_t>(dStyle)); } template <EnumConcepts::IsEnum E> constexpr E operator ~(const E& eStyle) noexcept { if constexpr (sizeof(E) <= sizeof(size_t)) return static_cast<E>(~static_cast<size_t>(eStyle)); else return static_cast<E>(~static_cast<uint64_t>(eStyle)); } template <EnumConcepts::IsNumeric T, EnumConcepts::IsEnum E> constexpr E to_Enum(T t) noexcept { return static_cast<E>(t); }
{ "alphanum_fraction": 0.6909957361, "avg_line_length": 33.5042016807, "ext": "h", "hexsha": "cacc4ed062449d275475bf46378b24292018fd7e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2018-08-04T23:53:29.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-01T09:39:33.000Z", "max_forks_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "twig/dcxdll", "max_forks_repo_path": "EnumConcepts.h", "max_issues_count": 68, "max_issues_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_issues_repo_issues_event_max_datetime": "2022-03-09T17:33:50.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-06T16:23:35.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "twig/dcxdll", "max_issues_repo_path": "EnumConcepts.h", "max_line_length": 96, "max_stars_count": 18, "max_stars_repo_head_hexsha": "cd0cb308b76daf0be614025d71670580007a0d78", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "twig/dcxdll", "max_stars_repo_path": "EnumConcepts.h", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:48:31.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-21T05:41:19.000Z", "num_tokens": 1146, "size": 3987 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <sys/time.h> #include <inttypes.h> #include <omp.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_heapsort.h> #include "sph_data_types.h" #include "sph_linked_list.h" #include "sph_compute.h" extern const double fk_bspline_32[32]; extern const double fk_bspline_128[128]; extern const double fk_bspline_1024[1024]; #pragma omp declare simd double w_bspline_3d(double r,double h){ const double A_d = 3./(2.*M_PI*h*h*h); double q=0.; if(r<0||h<=0.) exit(10); q = r/h; if(q<=1) return A_d*(2./3.-q*q + q*q*q/2.0); else if((1.<=q)&&(q<2.)) return A_d*(1./6.)*(2.-q)*(2.-q)*(2.-q); else return 0.; } double w_bspline_3d_constant(double h){ return 3./(2.*M_PI*h*h*h); } #pragma omp declare simd double w_bspline_3d_simd(double q){ double wq = 0.0; double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); if(q<2.) wq = wq2; if(q<1.) wq = wq1; return wq; } #pragma omp declare simd double dwdq_bspline_3d_simd(double q){ double wq = 0.0; double wq1 = (1.5*q*q - 2.*q); double wq2 = -0.5*(2.-q)*(2.-q); if(q<2.) wq = wq2; if(q<1.) wq = wq1; return wq; } // https://stackoverflow.com/questions/56417115/efficient-integer-floor-function-in-c // 341.333333333 = 1024./3. #pragma omp declare simd double w_bspline_3d_LUT_1024(double q){ int kq = (int)(341.333333333*q); double phi = q-kq*0.002929688; double wq = phi*fk_bspline_1024[kq] + (1.-phi)*fk_bspline_1024[kq+1]; return wq; } #pragma omp declare simd double w_bspline_3d_LUT_128(double q){ int kq = (int)(42.666666667*q); double phi = q-kq*0.0234375; double wq = phi*fk_bspline_128[kq] + (1.-phi)*fk_bspline_128[kq+1]; return wq; } #pragma omp declare simd double w_bspline_3d_LUT_32(double q){ int kq = (int)(10.666666667*q); double phi = q-kq*0.09375; double wq = (1.-phi)*fk_bspline_32[kq] + phi*fk_bspline_32[kq+1]; return wq; } double dwdq_bspline_3d(double r,double h){ const double A_d = 3./(2.*M_PI*h*h*h*h); double q=0.; if(r<0||h<=0.) exit(10); q = r/h; if(q<=1) return A_d*q*(-2.+1.5*q); else if((1.<=q)&&(q<2.)) return -A_d*0.5*(2.-q)*(2.-q); else return 0.; } double distance_2d(double xi,double yi, double xj,double yj){ double dist = 0.0; dist += (xi-xj)*(xi-xj); dist += (yi-yj)*(yi-yj); return sqrt(dist); } #pragma omp declare simd double distance_3d(double xi,double yi,double zi, double xj,double yj,double zj){ double dist = 0.0; dist += (xi-xj)*(xi-xj); dist += (yi-yj)*(yi-yj); dist += (zi-zj)*(zi-zj); return sqrt(dist); } /**********************************************************************/ int compute_density_3d_chunk(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); #pragma omp parallel for for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) nontemporal(rhoii) for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); //rhoii += nu[jj]*w_bspline_3d_LUT(q); } rho[ii] += rhoii*kernel_constant; } return 0; } int compute_density_3d_innerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box){ int res; double dist = 0.0; khiter_t kbegin,kend; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ if (kh_exist(box->hbegin, kbegin)){ kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1)// this loop inside was the problem lsph->rho[ii] = 0.0; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); compute_density_3d_chunk(node_begin,node_end,nb_begin,nb_end,h, lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); } } } } return 0; } /**********************************************************************/ int compute_density_3d_chunk_noomp(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); //rhoii += nu[jj]*w_bspline_3d_LUT(q); } rho[ii] += rhoii*kernel_constant; } return 0; } int compute_density_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t pair_count = 0; const khint32_t num_boxes = kh_size(box->hbegin); const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin); //for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++) #pragma omp parallel for num_threads(24) for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1) lsph->rho[ii] = 0.0; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += (node_end-node_begin)*(nb_end-nb_begin); compute_density_3d_chunk_noomp(node_begin,node_end,nb_begin,nb_end,h, lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); } } } //printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]); } printf("pair_count = %ld\n",pair_count); //for(int64_t i=0;i<N;i+=1000) // printf("%ld - %lf\n",i,lsph->rho[i]); return 0; } /**********************************************************************/ int compute_density_3d_chunk_loopswapped(int64_t node_begin, int64_t node_end, int64_t node_hash,linkedListBox *box, double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho) { int64_t pair_count; int res=0,nb_count=0,fused_count=0; //int64_t nb_begin= 0, nb_end = 0; const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; int64_t nb_begin[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; int64_t nb_end[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ nb_begin[nb_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end[nb_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); nb_count+=1; } else{ nb_begin[nb_count] = -1; nb_end[nb_count] = -1; } } qsort(nb_begin,nb_count,sizeof(int64_t),compare_int64_t); qsort(nb_end ,nb_count,sizeof(int64_t),compare_int64_t); fused_count = nb_count; { int64_t tmp; unsigned int j=0; while(j<nb_count-1){ if(nb_begin[j] < 0){ nb_begin[j] = nb_begin[nb_count-1]+1; nb_end[j] = nb_end[nb_count-1]+1; } else if(nb_end[j]==nb_begin[j+1]){ //printf("%ld:%ld , %ld:%d",nb_begin[j],nb_begin[j+1]); nb_end[j] = nb_end[j+1]; tmp = nb_begin[j]; nb_begin[j] = nb_begin[j+1]; nb_begin[j+1] = tmp; tmp = nb_end[j]; nb_end[j] = nb_end[j+1]; nb_end[j+1] = tmp; nb_begin[j] = nb_begin[nb_count-1]+1; nb_end[j] = nb_end[nb_count-1]+1; fused_count -= 1; } j+=1; } } qsort(nb_begin,nb_count,sizeof(int64_t),compare_int64_t); qsort(nb_end ,nb_count,sizeof(int64_t),compare_int64_t); for(unsigned int j=0;j<fused_count;j+=1){ pair_count += (node_end-node_begin)*(nb_end[j]-nb_begin[j]); for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; #pragma omp simd for(int64_t jj=nb_begin[j];jj<nb_end[j];jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rho[ii] += nu[jj]*w_bspline_3d_simd(q); } } } for(int64_t ii=node_begin;ii<node_end;ii+=1) rho[ii] *= kernel_constant; return pair_count; } int compute_density_3d_loopswapped(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t pair_count = 0, ppc; const khint32_t num_boxes = kh_size(box->hbegin); const khiter_t hbegin_start = kh_begin(box->hbegin), hbegin_finish = kh_end(box->hbegin); //for (khint32_t kbegin = hbegin_start; kbegin != hbegin_finish; kbegin++) #pragma omp parallel for num_threads(24) for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1,node_begin=0, node_end=0; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1) lsph->rho[ii] = 0.0; ppc = compute_density_3d_chunk_loopswapped(node_begin,node_end,node_hash,box,h, lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); pair_count += ppc; } } printf("pair_count = %ld\n",pair_count); return 0; } /*******************************************************************/ int count_box_pairs(linkedListBox *box){ int64_t pair_count = 0, particle_pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += 1; particle_pair_count += (node_end-node_begin)*(nb_end-nb_begin); } } } } printf("unique ordered particle_pair_count = %ld\n",particle_pair_count); return pair_count; } int setup_box_pairs(linkedListBox *box, int64_t *node_begin,int64_t *node_end, int64_t *nb_begin,int64_t *nb_end) { int64_t pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; node_begin[pair_count] = kh_value(box->hbegin, kbegin); node_end[pair_count] = kh_value(box->hend, kend); nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin); } } } //printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]); } return pair_count; } int compute_density_3d_chunk_noomp_shift(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho){ const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double rhoii = 0.0; #pragma omp simd reduction(+:rhoii) for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; rhoii += nu[jj]*w_bspline_3d_simd(q); } rho[ii-node_begin] += rhoii*kernel_constant; } return 0; } int compute_density_3d_load_ballanced(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0; max_box_pair_count = count_box_pairs(box); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for num_threads(24) for(size_t i=0;i<max_box_pair_count;i+=1){ double local_rho[node_end[i]-node_begin[i]]; for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1) local_rho[ii] = 0.; compute_density_3d_chunk_noomp_shift(node_begin[i],node_end[i],nb_begin[i],nb_end[i], h,lsph->x,lsph->y,lsph->z,lsph->nu,local_rho); #pragma omp critical { for(size_t ii=node_begin[i];ii<node_end[i];ii+=1) lsph->rho[ii] += local_rho[ii - node_begin[i]]; } } free(node_begin); free(node_end); free(nb_begin); free(nb_end); //for(int64_t i=0;i<N;i+=1000) // printf("%ld - %lf\n",i,lsph->rho[i]); return 0; } /*******************************************************************/ /*******************************************************************/ /* Pit from hell */ int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj){ const double inv_h = 1./h; for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; #pragma omp simd for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } } return 0; } #define min(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) int compute_density_3d_chunk_symm_nlo(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj){ const int64_t STRIP=512; const double inv_h = 1./h; /* for(int64_t ii=node_begin;ii<node_end;ii+=1){ #pragma omp simd for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } }*/ for(int64_t i=0;i<(node_end-node_begin);i+=STRIP) for(int64_t j=0;j<( nb_end - nb_begin );j+=STRIP) for(int64_t ii=i;ii<min(node_end-node_begin,i+STRIP);ii+=1) #pragma omp simd for(int64_t jj=j;jj<min( nb_end - nb_begin ,j+STRIP);jj+=1){ double q = 0.; double xij = x[ii+node_begin]-x[jj+nb_begin]; double yij = y[ii+node_begin]-y[jj+nb_begin]; double zij = z[ii+node_begin]-z[jj+nb_begin]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii] += nu[jj + nb_begin]*wij; rhoj[jj] += nu[ii+node_begin]*wij; } return 0; } int compute_density_3d_chunk_symm_colapse(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rhoi, double* restrict rhoj){ const double inv_h = 1./h; #pragma omp simd for(int64_t ii=node_begin;ii<node_end;ii+=1){ for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = x[ii]-x[jj]; double yij = y[ii]-y[jj]; double zij = z[ii]-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } } return 0; } int cpr_int64_t(const void *a, const void *b){ return ( *(int64_t*)a - *(int64_t*)b ); } int unique_box_bounds(int64_t max_box_pair_count, int64_t *node_begin, int64_t *node_end, int64_t *nb_begin, int64_t *nb_end) { int64_t box_skip=0; if(node_begin==NULL || node_end==NULL || nb_begin==NULL || nb_end==NULL) return -1; for(int64_t i=0;i<max_box_pair_count;i+=1){ if(node_begin[i]>=0){ for(int64_t j=i+1;j<max_box_pair_count;j+=1){ if((node_begin[j]==nb_begin[i]) && (nb_begin[j]==node_begin[i]) ){ node_begin[j] = -1; node_end[j] = -1; nb_begin[j] = -1; nb_end[j] = -1; //node_begin[j] -= -1; node_end[j] -= -1; //nb_begin[j] -= -1; nb_end[j] -= -1; box_skip += 1; } } } } //qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); //qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); //qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); //qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); /* if(node_begin[i]<=nb_begin[i]){ box_keep +=1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); max_box_pair_count = box_keep; //max_box_pair_count - box_subtract; for(int64_t i=0;i<max_box_pair_count;i+=1){ node_begin[i] *= -1; node_end[i] *= -1; nb_begin[i] *= -1; nb_end[i] *= -1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t);*/ return box_skip; } int setup_unique_box_pairs(linkedListBox *box, int64_t *node_begin,int64_t *node_end, int64_t *nb_begin,int64_t *nb_end) { int64_t pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ int res; int64_t node_hash=-1; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // I have to call this! khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ //nb_hash = nblist[j]; if(kh_value(box->hbegin, kbegin) <= kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) )) { node_begin[pair_count] = kh_value(box->hbegin, kbegin); node_end[pair_count] = kh_value(box->hend, kend); nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); pair_count += 1;//(node_end-node_begin)*(nb_end-nb_begin); } } } } //printf("thread %d - %lf %lf\n",i,lsph->rho[node_begin],lsph->rho[node_end-1]); } return pair_count; } int compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0, particle_pair_count = 0; int64_t box_skip = 0; const double kernel_constant = w_bspline_3d_constant(h); max_box_pair_count = count_box_pairs(box); printf("max_box_pair_count = %ld\n",max_box_pair_count); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); max_box_pair_count = setup_unique_box_pairs(box,node_begin,node_end,nb_begin,nb_end);//setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); printf("unique max_box_pair_count = %ld\n",max_box_pair_count); double avg_nb_len = 0.0; for(int64_t i=0;i<max_box_pair_count;i+=1) avg_nb_len += (nb_end[i]-nb_begin[i]); avg_nb_len /= max_box_pair_count; printf("avg_nb_len = %lf\n",avg_nb_len); for(int64_t i=0;i<max_box_pair_count;i+=1) particle_pair_count += (node_end[i]-node_begin[i])*(nb_end[i]-nb_begin[i]); printf("unique unordered particle_pair_count = %ld\n",particle_pair_count); //box_skip = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for schedule(dynamic,5) proc_bind(master) for(size_t i=0;i<max_box_pair_count;i+=1){ double local_rhoi[node_end[i] - node_begin[i]]; double local_rhoj[ nb_end[i] - nb_begin[i]]; for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1) local_rhoi[ii] = 0.; for(size_t ii=0;ii<nb_end[i]-nb_begin[i];ii+=1) local_rhoj[ii] = 0.; compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); //compute_density_3d_chunk_symm_nlo(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, // lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); //compute_density_3d_chunk_symm_colapse(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, // lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); #pragma omp critical { for(size_t ii=node_begin[i];ii<node_end[i];ii+=1){ lsph->rho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]]; } if(node_begin[i] != nb_begin[i]) for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1){ lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]]; } } } free(node_begin); free(node_end); free(nb_begin); free(nb_end); return 0; } int compute_density_3d_symmetrical_lb_branching(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0, particle_pair_count = 0; int64_t box_skip = 0; const double kernel_constant = w_bspline_3d_constant(h); max_box_pair_count = count_box_pairs(box); printf("max_box_pair_count = %ld\n",max_box_pair_count); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); max_box_pair_count = setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); box_skip = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end); for(int64_t i=0;i<max_box_pair_count;i+=1) if(node_end[i] >= 0) particle_pair_count += (node_end[i]-node_begin[i])*(nb_end[i]-nb_begin[i]); printf("unique unordered particle_pair_count = %ld\n",particle_pair_count); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for for(size_t i=0;i<max_box_pair_count;i+=1){ if(node_end[i]<0) continue; double local_rhoi[node_end[i] - node_begin[i]]; double local_rhoj[ nb_end[i] - nb_begin[i]]; for(size_t ii=0;ii<node_end[i]-node_begin[i];ii+=1) local_rhoi[ii] = 0.; for(size_t ii=0;ii<nb_end[i]-nb_begin[i];ii+=1) local_rhoj[ii] = 0.; compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i],h, lsph->x,lsph->y,lsph->z,lsph->nu,local_rhoi,local_rhoj); #pragma omp critical { for(size_t ii=node_begin[i];ii<node_end[i];ii+=1) lsph->rho[ii] += kernel_constant*local_rhoi[ii - node_begin[i]]; if(node_begin[i] != nb_begin[i]) for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1) lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]]; /* if(node_begin[i]!=nb_begin[i]) for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1) lsph->rho[ii] += kernel_constant*local_rhoj[ii - nb_begin[i]];*/ } } free(node_begin); free(node_end); free(nb_begin); free(nb_end); return 0; } /*******************************************************************/ /*******************************************************************/ /* int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, double* restrict x, double* restrict y, double* restrict z, double* restrict nu, double* restrict rho) { const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); double rhoi[node_end-node_begin]; double rhoj[nb_end-nb_begin]; for(int64_t ii=0;ii<node_end-node_begin;ii+=1) rhoi[ii] = 0.; for(int64_t jj=0;jj<nb_end-nb_begin;jj+=1) rhoj[jj] = 0.; for(int64_t ii=node_begin;ii<node_end;ii+=1){ double xii = x[ii]; double yii = y[ii]; double zii = z[ii]; #pragma omp simd for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ double q = 0.; double xij = xii-x[jj]; double yij = yii-y[jj]; double zij = zii-z[jj]; q += xij*xij; q += yij*yij; q += zij*zij; q = sqrt(q)*inv_h; double wij = w_bspline_3d_simd(q); rhoi[ii-node_begin] += nu[jj]*wij; rhoj[jj-nb_begin] += nu[ii]*wij; } } for(int64_t ii=node_begin;ii<node_end;ii+=1) rho[ii] += rhoi[ii-node_begin]*kernel_constant; if(nb_begin == node_begin) return 0; for(int64_t jj=nb_begin;jj<nb_end;jj+=1) rho[jj] += rhoj[jj-nb_begin]*kernel_constant; return 0; }*/ /* int cpr_int64_t(const void *a, const void *b){ return ( *(int64_t*)a - *(int64_t*)b ); } */ /* int unique_box_bounds(int64_t max_box_pair_count, int64_t *node_begin, int64_t *node_end, int64_t *nb_begin, int64_t *nb_end) { int64_t box_keep=0; if(node_begin==NULL || node_end==NULL || nb_begin==NULL || nb_end==NULL) return -1; for(int64_t i=0;i<max_box_pair_count;i+=1) if(node_begin[i]<=nb_begin[i]){ node_begin[i] *= -1; node_end[i] *= -1; nb_begin[i] *= -1; nb_end[i] *= -1; box_keep +=1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); max_box_pair_count = box_keep; //max_box_pair_count - box_subtract; for(int64_t i=0;i<max_box_pair_count;i+=1){ node_begin[i] *= -1; node_end[i] *= -1; nb_begin[i] *= -1; nb_end[i] *= -1; } qsort(node_begin,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(node_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_begin ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); qsort(nb_end ,max_box_pair_count, sizeof(int64_t),cpr_int64_t); return max_box_pair_count; } int compute_density_3d_symmetrical_lb(int N, double h, SPHparticle *lsph, linkedListBox *box){ int64_t *node_begin,*node_end,*nb_begin,*nb_end; int64_t max_box_pair_count = 0; max_box_pair_count = count_box_pairs(box); node_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); node_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_begin = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); nb_end = (int64_t*)malloc(max_box_pair_count*sizeof(int64_t)); setup_box_pairs(box,node_begin,node_end,nb_begin,nb_end); max_box_pair_count = unique_box_bounds(max_box_pair_count,node_begin,node_end,nb_begin,nb_end); for(int64_t ii=0;ii<N;ii+=1) lsph->rho[ii] = 0.0; #pragma omp parallel for num_threads(24) for(size_t i=0;i<max_box_pair_count;i+=1){ if(node_begin[i] > nb_begin[i]) continue; compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i],nb_begin[i],nb_end[i], h,lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); } free(node_begin); free(node_end); free(nb_begin); free(nb_end); //for(int64_t i=0;i<N;i+=1000) // printf("%ld - %lf\n",i,lsph->rho[i]); return 0; }*/ /*******************************************************************/ /*******************************************************************/ /*******************************************************************/ #pragma omp declare simd double pressure_from_density(double rho){ double p = cbrt(rho); p = 0.5*p*rho; return p; } #pragma omp declare simd double gamma_from_u(double ux,double uy,double uz){ double gamma = 1.0; gamma += ux*ux; gamma += uy*uy; gamma += uz*uz; gamma = sqrt(gamma); return gamma; } /* int compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){ int err, res; double dist = 0.0; khiter_t kbegin,kend; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ if (kh_exist(box->hbegin, kbegin)){ kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1)// this loop inside was the problem lsph->rho[ii] = 0.0; res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); for(int64_t ii=node_begin;ii<node_end;ii+=1){ // this loop inside was the problem for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ dist = distance_3d(lsph->x[i],lsph->y[i],lsph->z[i], lsph->x[j],lsph->y[j],lsph->z[j]); lsph->rho[ii] += (lsph->nu[jj])*(box->w(dist,h)); } } } } } } return 0; } */ /* int compute_force_3d(int N, double h, SPHparticle *lsph, linkedListBox *box){ int err, res; double dist = 0.0; khiter_t kbegin,kend; int64_t node_hash=-1,node_begin=0, node_end=0; int64_t nb_hash=-1 , nb_begin= 0, nb_end = 0; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ if (kh_exist(box->hbegin, kbegin)){ kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); node_hash = kh_key(box->hbegin, kbegin); node_begin = kh_value(box->hbegin, kbegin); node_end = kh_value(box->hend, kend); for(int64_t ii=node_begin;ii<node_end;ii+=1){ lsph[ii].F.x = 0.0; lsph[ii].F.y = 0.0; lsph[ii].F.z = 0.0; } res = neighbour_hash_3d(node_hash,nblist,box->width,box); for(unsigned int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ if(nblist[j]>=0){ nb_hash = nblist[j]; nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); for(int64_t ii=node_begin;ii<node_end;ii+=1){ // this loop inside was the problem for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ dist = double4_distance_3d(&(lsph[ii].r),&(lsph[jj].r)); = (); lsph[ii].F.x += ((lsph[ii].r.x-lsph[jj].r.x)/dist); lsph[ii].F.y += ; lsph[ii].F.z += ; } } } } } } return 0; } */ const double fk_bspline_32[32] = { 6.66666667e-01, 6.57754579e-01, 6.32830944e-01, 5.94614705e-01, 5.45824802e-01, 4.89180177e-01, 4.27399774e-01, 3.63202533e-01, 2.99307397e-01, 2.38433308e-01, 1.83299207e-01, 1.36445011e-01, 9.83294731e-02, 6.80686561e-02, 4.47562463e-02, 2.74859298e-02, 1.53513925e-02, 7.44632048e-03, 2.86439976e-03, 6.99316348e-04, 4.47562463e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00}; const double fk_bspline_128[128] = { 6.66666667e-01, 6.66115256e-01, 6.64487387e-01, 6.61822602e-01, 6.58160445e-01, 6.53540459e-01, 6.48002188e-01, 6.41585176e-01, 6.34328964e-01, 6.26273098e-01, 6.17457119e-01, 6.07920573e-01, 5.97703001e-01, 5.86843948e-01, 5.75382957e-01, 5.63359570e-01, 5.50813333e-01, 5.37783787e-01, 5.24310476e-01, 5.10432945e-01, 4.96190735e-01, 4.81623391e-01, 4.66770456e-01, 4.51671473e-01, 4.36365986e-01, 4.20893537e-01, 4.05293671e-01, 3.89605931e-01, 3.73869861e-01, 3.58125002e-01, 3.42410900e-01, 3.26767097e-01, 3.11233137e-01, 2.95848563e-01, 2.80652918e-01, 2.65685747e-01, 2.50986591e-01, 2.36594995e-01, 2.22550503e-01, 2.08892657e-01, 1.95661000e-01, 1.82895077e-01, 1.70634431e-01, 1.58916000e-01, 1.47746458e-01, 1.37112949e-01, 1.27002291e-01, 1.17401303e-01, 1.08296805e-01, 9.96756140e-02, 9.15245505e-02, 8.38304328e-02, 7.65800797e-02, 6.97603101e-02, 6.33579430e-02, 5.73597971e-02, 5.17526914e-02, 4.65234448e-02, 4.16588760e-02, 3.71458040e-02, 3.29710476e-02, 2.91214257e-02, 2.55837572e-02, 2.23448610e-02, 1.93915558e-02, 1.67106607e-02, 1.42889945e-02, 1.21133759e-02, 1.01706240e-02, 8.44755758e-03, 6.93099549e-03, 5.60775662e-03, 4.46465985e-03, 3.48852404e-03, 2.66616806e-03, 1.98441079e-03, 1.43007110e-03, 9.89967859e-04, 6.50919937e-04, 3.99746206e-04, 2.23265538e-04, 1.08296805e-04, 4.16588760e-05, 1.01706240e-05, 6.50919937e-07, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00}; const double fk_bspline_1024[1024] = { 6.66666667e-01, 6.66658079e-01, 6.66632368e-01, 6.66589608e-01, 6.66529876e-01, 6.66453246e-01, 6.66359796e-01, 6.66249599e-01, 6.66122732e-01, 6.65979271e-01, 6.65819291e-01, 6.65642868e-01, 6.65450077e-01, 6.65240994e-01, 6.65015696e-01, 6.64774257e-01, 6.64516753e-01, 6.64243260e-01, 6.63953853e-01, 6.63648609e-01, 6.63327602e-01, 6.62990909e-01, 6.62638605e-01, 6.62270765e-01, 6.61887466e-01, 6.61488783e-01, 6.61074792e-01, 6.60645569e-01, 6.60201188e-01, 6.59741726e-01, 6.59267259e-01, 6.58777861e-01, 6.58273610e-01, 6.57754579e-01, 6.57220846e-01, 6.56672485e-01, 6.56109573e-01, 6.55532184e-01, 6.54940396e-01, 6.54334282e-01, 6.53713920e-01, 6.53079384e-01, 6.52430750e-01, 6.51768095e-01, 6.51091493e-01, 6.50401020e-01, 6.49696752e-01, 6.48978765e-01, 6.48247134e-01, 6.47501935e-01, 6.46743244e-01, 6.45971135e-01, 6.45185686e-01, 6.44386971e-01, 6.43575066e-01, 6.42750048e-01, 6.41911990e-01, 6.41060970e-01, 6.40197063e-01, 6.39320344e-01, 6.38430889e-01, 6.37528774e-01, 6.36614075e-01, 6.35686866e-01, 6.34747225e-01, 6.33795226e-01, 6.32830944e-01, 6.31854457e-01, 6.30865839e-01, 6.29865166e-01, 6.28852514e-01, 6.27827959e-01, 6.26791575e-01, 6.25743439e-01, 6.24683626e-01, 6.23612213e-01, 6.22529274e-01, 6.21434885e-01, 6.20329123e-01, 6.19212062e-01, 6.18083778e-01, 6.16944347e-01, 6.15793845e-01, 6.14632348e-01, 6.13459930e-01, 6.12276668e-01, 6.11082637e-01, 6.09877913e-01, 6.08662571e-01, 6.07436688e-01, 6.06200339e-01, 6.04953599e-01, 6.03696545e-01, 6.02429251e-01, 6.01151794e-01, 5.99864249e-01, 5.98566692e-01, 5.97259199e-01, 5.95941844e-01, 5.94614705e-01, 5.93277856e-01, 5.91931373e-01, 5.90575332e-01, 5.89209808e-01, 5.87834877e-01, 5.86450616e-01, 5.85057098e-01, 5.83654401e-01, 5.82242599e-01, 5.80821769e-01, 5.79391986e-01, 5.77953326e-01, 5.76505864e-01, 5.75049676e-01, 5.73584838e-01, 5.72111425e-01, 5.70629514e-01, 5.69139179e-01, 5.67640496e-01, 5.66133541e-01, 5.64618390e-01, 5.63095118e-01, 5.61563801e-01, 5.60024515e-01, 5.58477335e-01, 5.56922337e-01, 5.55359597e-01, 5.53789190e-01, 5.52211192e-01, 5.50625678e-01, 5.49032725e-01, 5.47432408e-01, 5.45824802e-01, 5.44209983e-01, 5.42588027e-01, 5.40959010e-01, 5.39323007e-01, 5.37680094e-01, 5.36030346e-01, 5.34373840e-01, 5.32710650e-01, 5.31040853e-01, 5.29364524e-01, 5.27681738e-01, 5.25992573e-01, 5.24297102e-01, 5.22595402e-01, 5.20887548e-01, 5.19173617e-01, 5.17453683e-01, 5.15727823e-01, 5.13996112e-01, 5.12258626e-01, 5.10515440e-01, 5.08766630e-01, 5.07012271e-01, 5.05252441e-01, 5.03487213e-01, 5.01716663e-01, 4.99940869e-01, 4.98159904e-01, 4.96373845e-01, 4.94582767e-01, 4.92786746e-01, 4.90985857e-01, 4.89180177e-01, 4.87369781e-01, 4.85554745e-01, 4.83735144e-01, 4.81911054e-01, 4.80082550e-01, 4.78249708e-01, 4.76412605e-01, 4.74571315e-01, 4.72725914e-01, 4.70876478e-01, 4.69023083e-01, 4.67165804e-01, 4.65304717e-01, 4.63439897e-01, 4.61571420e-01, 4.59699362e-01, 4.57823799e-01, 4.55944806e-01, 4.54062459e-01, 4.52176833e-01, 4.50288004e-01, 4.48396048e-01, 4.46501040e-01, 4.44603057e-01, 4.42702173e-01, 4.40798465e-01, 4.38892008e-01, 4.36982877e-01, 4.35071149e-01, 4.33156899e-01, 4.31240203e-01, 4.29321136e-01, 4.27399774e-01, 4.25476193e-01, 4.23550468e-01, 4.21622675e-01, 4.19692890e-01, 4.17761188e-01, 4.15827645e-01, 4.13892336e-01, 4.11955338e-01, 4.10016726e-01, 4.08076576e-01, 4.06134962e-01, 4.04191962e-01, 4.02247650e-01, 4.00302103e-01, 3.98355395e-01, 3.96407603e-01, 3.94458803e-01, 3.92509069e-01, 3.90558477e-01, 3.88607104e-01, 3.86655025e-01, 3.84702315e-01, 3.82749050e-01, 3.80795307e-01, 3.78841159e-01, 3.76886684e-01, 3.74931957e-01, 3.72977053e-01, 3.71022048e-01, 3.69067018e-01, 3.67112038e-01, 3.65157185e-01, 3.63202533e-01, 3.61248159e-01, 3.59294138e-01, 3.57340545e-01, 3.55387457e-01, 3.53434949e-01, 3.51483097e-01, 3.49531976e-01, 3.47581662e-01, 3.45632230e-01, 3.43683758e-01, 3.41736319e-01, 3.39789989e-01, 3.37844845e-01, 3.35900962e-01, 3.33958416e-01, 3.32017282e-01, 3.30077636e-01, 3.28139553e-01, 3.26203110e-01, 3.24268382e-01, 3.22335444e-01, 3.20404373e-01, 3.18475243e-01, 3.16548131e-01, 3.14623112e-01, 3.12700262e-01, 3.10779657e-01, 3.08861372e-01, 3.06945483e-01, 3.05032065e-01, 3.03121194e-01, 3.01212946e-01, 2.99307397e-01, 2.97404622e-01, 2.95504697e-01, 2.93607697e-01, 2.91713698e-01, 2.89822776e-01, 2.87935006e-01, 2.86050465e-01, 2.84169227e-01, 2.82291369e-01, 2.80416966e-01, 2.78546093e-01, 2.76678827e-01, 2.74815243e-01, 2.72955417e-01, 2.71099424e-01, 2.69247340e-01, 2.67399241e-01, 2.65555202e-01, 2.63715299e-01, 2.61879608e-01, 2.60048204e-01, 2.58221163e-01, 2.56398561e-01, 2.54580473e-01, 2.52766975e-01, 2.50958142e-01, 2.49154051e-01, 2.47354777e-01, 2.45560395e-01, 2.43770982e-01, 2.41986612e-01, 2.40207362e-01, 2.38433308e-01, 2.36664524e-01, 2.34901086e-01, 2.33143071e-01, 2.31390554e-01, 2.29643610e-01, 2.27902316e-01, 2.26166746e-01, 2.24436977e-01, 2.22713084e-01, 2.20995143e-01, 2.19283229e-01, 2.17577418e-01, 2.15877786e-01, 2.14184409e-01, 2.12497361e-01, 2.10816720e-01, 2.09142560e-01, 2.07474956e-01, 2.05813986e-01, 2.04159724e-01, 2.02512246e-01, 2.00871628e-01, 1.99237945e-01, 1.97611273e-01, 1.95991688e-01, 1.94379265e-01, 1.92774080e-01, 1.91176209e-01, 1.89585728e-01, 1.88002711e-01, 1.86427235e-01, 1.84859375e-01, 1.83299207e-01, 1.81746806e-01, 1.80202249e-01, 1.78665611e-01, 1.77136968e-01, 1.75616394e-01, 1.74103967e-01, 1.72599761e-01, 1.71103853e-01, 1.69616317e-01, 1.68137230e-01, 1.66666667e-01, 1.65204687e-01, 1.63751281e-01, 1.62306426e-01, 1.60870094e-01, 1.59442261e-01, 1.58022902e-01, 1.56611992e-01, 1.55209505e-01, 1.53815416e-01, 1.52429700e-01, 1.51052331e-01, 1.49683285e-01, 1.48322536e-01, 1.46970060e-01, 1.45625830e-01, 1.44289821e-01, 1.42962009e-01, 1.41642368e-01, 1.40330873e-01, 1.39027499e-01, 1.37732220e-01, 1.36445011e-01, 1.35165848e-01, 1.33894704e-01, 1.32631555e-01, 1.31376375e-01, 1.30129139e-01, 1.28889822e-01, 1.27658399e-01, 1.26434845e-01, 1.25219133e-01, 1.24011240e-01, 1.22811140e-01, 1.21618807e-01, 1.20434217e-01, 1.19257343e-01, 1.18088162e-01, 1.16926648e-01, 1.15772775e-01, 1.14626518e-01, 1.13487852e-01, 1.12356752e-01, 1.11233193e-01, 1.10117149e-01, 1.09008596e-01, 1.07907507e-01, 1.06813859e-01, 1.05727624e-01, 1.04648779e-01, 1.03577299e-01, 1.02513157e-01, 1.01456328e-01, 1.00406788e-01, 9.93645117e-02, 9.83294731e-02, 9.73016473e-02, 9.62810090e-02, 9.52675330e-02, 9.42611942e-02, 9.32619673e-02, 9.22698271e-02, 9.12847483e-02, 9.03067058e-02, 8.93356743e-02, 8.83716286e-02, 8.74145435e-02, 8.64643938e-02, 8.55211542e-02, 8.45847996e-02, 8.36553047e-02, 8.27326442e-02, 8.18167931e-02, 8.09077259e-02, 8.00054177e-02, 7.91098430e-02, 7.82209767e-02, 7.73387936e-02, 7.64632684e-02, 7.55943760e-02, 7.47320911e-02, 7.38763885e-02, 7.30272430e-02, 7.21846293e-02, 7.13485223e-02, 7.05188966e-02, 6.96957272e-02, 6.88789888e-02, 6.80686561e-02, 6.72647039e-02, 6.64671071e-02, 6.56758404e-02, 6.48908785e-02, 6.41121963e-02, 6.33397686e-02, 6.25735701e-02, 6.18135756e-02, 6.10597598e-02, 6.03120976e-02, 5.95705638e-02, 5.88351331e-02, 5.81057803e-02, 5.73824802e-02, 5.66652075e-02, 5.59539371e-02, 5.52486438e-02, 5.45493022e-02, 5.38558872e-02, 5.31683736e-02, 5.24867361e-02, 5.18109496e-02, 5.11409888e-02, 5.04768285e-02, 4.98184434e-02, 4.91658084e-02, 4.85188982e-02, 4.78776876e-02, 4.72421515e-02, 4.66122645e-02, 4.59880014e-02, 4.53693371e-02, 4.47562463e-02, 4.41487038e-02, 4.35466844e-02, 4.29501628e-02, 4.23591138e-02, 4.17735123e-02, 4.11933330e-02, 4.06185507e-02, 4.00491401e-02, 3.94850760e-02, 3.89263333e-02, 3.83728867e-02, 3.78247109e-02, 3.72817808e-02, 3.67440712e-02, 3.62115568e-02, 3.56842123e-02, 3.51620127e-02, 3.46449326e-02, 3.41329469e-02, 3.36260303e-02, 3.31241576e-02, 3.26273035e-02, 3.21354430e-02, 3.16485507e-02, 3.11666014e-02, 3.06895699e-02, 3.02174310e-02, 2.97501595e-02, 2.92877301e-02, 2.88301177e-02, 2.83772970e-02, 2.79292427e-02, 2.74859298e-02, 2.70473328e-02, 2.66134267e-02, 2.61841863e-02, 2.57595862e-02, 2.53396013e-02, 2.49242063e-02, 2.45133761e-02, 2.41070854e-02, 2.37053089e-02, 2.33080216e-02, 2.29151981e-02, 2.25268132e-02, 2.21428418e-02, 2.17632586e-02, 2.13880383e-02, 2.10171558e-02, 2.06505858e-02, 2.02883032e-02, 1.99302826e-02, 1.95764990e-02, 1.92269270e-02, 1.88815414e-02, 1.85403171e-02, 1.82032287e-02, 1.78702512e-02, 1.75413592e-02, 1.72165275e-02, 1.68957310e-02, 1.65789443e-02, 1.62661424e-02, 1.59572999e-02, 1.56523917e-02, 1.53513925e-02, 1.50542771e-02, 1.47610203e-02, 1.44715968e-02, 1.41859815e-02, 1.39041492e-02, 1.36260745e-02, 1.33517323e-02, 1.30810974e-02, 1.28141446e-02, 1.25508485e-02, 1.22911841e-02, 1.20351261e-02, 1.17826493e-02, 1.15337284e-02, 1.12883382e-02, 1.10464536e-02, 1.08080492e-02, 1.05731000e-02, 1.03415805e-02, 1.01134657e-02, 9.88873037e-03, 9.66734920e-03, 9.44929700e-03, 9.23454856e-03, 9.02307866e-03, 8.81486208e-03, 8.60987360e-03, 8.40808799e-03, 8.20948005e-03, 8.01402454e-03, 7.82169626e-03, 7.63246998e-03, 7.44632048e-03, 7.26322254e-03, 7.08315094e-03, 6.90608047e-03, 6.73198590e-03, 6.56084202e-03, 6.39262360e-03, 6.22730542e-03, 6.06486228e-03, 5.90526893e-03, 5.74850018e-03, 5.59453079e-03, 5.44333554e-03, 5.29488923e-03, 5.14916663e-03, 5.00614251e-03, 4.86579166e-03, 4.72808886e-03, 4.59300890e-03, 4.46052654e-03, 4.33061658e-03, 4.20325378e-03, 4.07841294e-03, 3.95606884e-03, 3.83619624e-03, 3.71876994e-03, 3.60376471e-03, 3.49115534e-03, 3.38091660e-03, 3.27302328e-03, 3.16745016e-03, 3.06417201e-03, 2.96316362e-03, 2.86439976e-03, 2.76785523e-03, 2.67350479e-03, 2.58132323e-03, 2.49128533e-03, 2.40336587e-03, 2.31753963e-03, 2.23378139e-03, 2.15206594e-03, 2.07236804e-03, 1.99466249e-03, 1.91892406e-03, 1.84512753e-03, 1.77324769e-03, 1.70325931e-03, 1.63513718e-03, 1.56885607e-03, 1.50439077e-03, 1.44171605e-03, 1.38080670e-03, 1.32163749e-03, 1.26418322e-03, 1.20841865e-03, 1.15431857e-03, 1.10185776e-03, 1.05101100e-03, 1.00175307e-03, 9.54058747e-04, 9.07902817e-04, 8.63260059e-04, 8.20105252e-04, 7.78413178e-04, 7.38158617e-04, 6.99316348e-04, 6.61861154e-04, 6.25767814e-04, 5.91011108e-04, 5.57565818e-04, 5.25406723e-04, 4.94508604e-04, 4.64846242e-04, 4.36394418e-04, 4.09127910e-04, 3.83021501e-04, 3.58049970e-04, 3.34188099e-04, 3.11410666e-04, 2.89692454e-04, 2.69008242e-04, 2.49332811e-04, 2.30640942e-04, 2.12907414e-04, 1.96107009e-04, 1.80214506e-04, 1.65204687e-04, 1.51052331e-04, 1.37732220e-04, 1.25219133e-04, 1.13487852e-04, 1.02513157e-04, 9.22698271e-05, 8.27326442e-05, 7.38763885e-05, 6.56758404e-05, 5.81057803e-05, 5.11409888e-05, 4.47562463e-05, 3.89263333e-05, 3.36260303e-05, 2.88301177e-05, 2.45133761e-05, 2.06505858e-05, 1.72165275e-05, 1.41859815e-05, 1.15337284e-05, 9.23454856e-06, 7.26322254e-06, 5.59453079e-06, 4.20325378e-06, 3.06417201e-06, 2.15206594e-06, 1.44171605e-06, 9.07902817e-07, 5.25406723e-07, 2.69008242e-07, 1.13487852e-07, 3.36260303e-08, 4.20325378e-09, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00};
{ "alphanum_fraction": 0.6196987411, "avg_line_length": 38.4990215264, "ext": "c", "hexsha": "de10ce042e2babba256a1fc3ec7433a5ba50230c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "jhelsas/sphalerite", "max_forks_repo_path": "src/sph_compute.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "jhelsas/sphalerite", "max_issues_repo_path": "src/sph_compute.c", "max_line_length": 146, "max_stars_count": null, "max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "jhelsas/sphalerite", "max_stars_repo_path": "src/sph_compute.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 23995, "size": 59019 }
/** * (c) Author: Woongkyu Jee, woong.jee.16@ucl.ac.uk, wldndrb1@gmail.com * Created: 02.06.2019 ~ * * University College London, Department of Chemistry **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include"sp_cluster_type.h" #define SP_SUPPORT_TRUE 1 #define SP_SUPPORT_FALSE -1 #define DEBUG_SUPPORT /* Get the Lowest energy state */ int sp_cluster_support_get_lowest_state( gsl_vector* v ) { int Return = 0; double min; min = gsl_vector_get(v,0); for(int i=0;i<4;i++) { if( gsl_vector_get(v,i) < min ) { min = gsl_vector_get(v,i); Return = i; } } return Return; // Returns the index of element in gsl_vector* eval } void sp_cluster_support_sign_gs_eigenvector( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; int low_idx; for(int i=0;i<sp_sys->number_of_sp_ion;i++) { low_idx = sp_cluster_support_get_lowest_state(sp_sys->sp_ion[i].eigen_value); if( gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,0,low_idx) < 0. ) // eigen_vector : matrix(4,4) // eigen_vector_gs : vector(4) { gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,0,low_idx,-1.*gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,0,low_idx)); gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,1,low_idx,-1.*gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,1,low_idx)); gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,2,low_idx,-1.*gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,2,low_idx)); gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,3,low_idx,-1.*gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,3,low_idx)); } } return; } void sp_cluster_support_load_gs_eigenvector( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; int low_idx; for(int i=0;i<sp_sys->number_of_sp_ion;i++) { low_idx = sp_cluster_support_get_lowest_state(sp_sys->sp_ion[i].eigen_value); gsl_vector_set(sp_sys->sp_ion[i].eigen_vector_gs,0,gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,0,low_idx)); gsl_vector_set(sp_sys->sp_ion[i].eigen_vector_gs,1,gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,1,low_idx)); gsl_vector_set(sp_sys->sp_ion[i].eigen_vector_gs,2,gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,2,low_idx)); gsl_vector_set(sp_sys->sp_ion[i].eigen_vector_gs,3,gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,3,low_idx)); } return; } /* Matrix Viewer: Print out a N x N matrix on console */ void sp_cluster_support_matrix_view( const gsl_matrix* m ) { if( m != NULL ) { for(int i=0;i<m->size1;i++) { for(int j=0;j<m->size2;j++) { //printf("%s%12.4lf",gsl_matrix_get(m,i,j)>0.?"+":"",gsl_matrix_get(m,i,j)); printf("%12.4e",gsl_matrix_get(m,i,j)); } puts(""); } } else puts("sp_cluster_support_matrix_view input 'm' (gsl_matrix*) is a null pointer ... in SP_Support.c or SP_Support.h"); return; } /* Vector Viewer: Print out a vector on console */ void sp_cluster_support_vector_view( const gsl_vector* v ) { if( v != NULL ) { for(int i=0;i<v->size;i++) { //printf("%s%12.4f",gsl_vector_get(v,i)>0.?"+":"",gsl_vector_get(v,i)); printf("%12.4e",gsl_vector_get(v,i)); } puts(""); } else puts("sp_cluster_support_vector_view input 'v' (gsl_vector*) is a null pointer ... in SP_Support.c or SP_Support.h"); return; } /* Matrix Viewer: Print out a N x N matrix on file */ void sp_cluster_support_matrix_view_f( FILE* fp, const gsl_matrix* m ) { if( m != NULL ) { for(int i=0;i<m->size1;i++) { for(int j=0;j<m->size2;j++) fprintf(fp,"%s%.18lf\t",gsl_matrix_get(m,i,j)>0.?"+":"",gsl_matrix_get(m,i,j)); fprintf(fp,"\n"); } } else fputs("sp_cluster_support_matrix_view input 'm' (gsl_matrix*) is a null pointer ... in SP_Support.c or SP_Support.h",fp); fflush(fp); return; } /* Vector Viewer: Print out a vector on file */ void sp_cluster_support_vector_view_f( FILE* fp, const gsl_vector* v ) { if( v != NULL ) { for(int i=0;i<v->size;i++) fprintf(fp,"%s%.18f\t",gsl_vector_get(v,i)>0.?"+":"",gsl_vector_get(v,i)); fprintf(fp,"\n"); } else fputs("sp_cluster_support_vector_view input 'v' (gsl_vector*) is a null pointer ... in SP_Support.c or SP_Support.h",fp); fflush(fp); return; } /* Transformation Matrix calculator */ /* * this function takes a vector, and the vector is transformed along transformed z-axis * the final return is the transformation matrix (rank 2 tensor), and the this data type is * gsl_matrix* */ gsl_matrix* sp_cluster_support_get_transformation_matrix( const gsl_vector* v ) { // gsl_vector_get(v,0) == 'x' // gsl_vector_get(v,1) == 'y' // gsl_vector_get(v,2) == 'z' gsl_matrix* pReturn = NULL; const double rxy = sqrt(pow(gsl_vector_get(v,0),2.)+pow(gsl_vector_get(v,1),2.)); const double R = sqrt(pow(gsl_vector_get(v,0),2.)+pow(gsl_vector_get(v,1),2.)+pow(gsl_vector_get(v,2),2.)); double n1, n2, tmp; // dummy variables for workspace pReturn = gsl_matrix_calloc(4,4); // Normally a rotation matrix is 3x3 // For the 1st column or row has an element of '1' at T_11. if( pReturn != NULL ) { gsl_matrix_set(pReturn,0,0,1.); if( gsl_vector_get(v,0) == 0. && gsl_vector_get(v,1) == 0. && gsl_vector_get(v,2) > 0. ) // if vector 'v' is on z-axis { gsl_matrix_set(pReturn,1,1,1.); gsl_matrix_set(pReturn,2,2,1.); gsl_matrix_set(pReturn,3,3,1.); // set the matrix as I } else if( gsl_vector_get(v,0) == 0. && gsl_vector_get(v,1) == 0. && gsl_vector_get(v,2) < 0. ) // if vector 'v' is on negative z-axis { gsl_matrix_set(pReturn,1,1,1.); gsl_matrix_set(pReturn,2,2,1.); gsl_matrix_set(pReturn,3,3,-1.); // set the matrix has xy-plane reflection } else { gsl_matrix_set(pReturn,3,1,gsl_vector_get(v,0)/R); gsl_matrix_set(pReturn,3,2,gsl_vector_get(v,1)/R); gsl_matrix_set(pReturn,3,3,gsl_vector_get(v,2)/R); // set k' in the transformed (local) symmetry gsl_matrix_set(pReturn,2,1,gsl_vector_get(v,2)*gsl_vector_get(v,0)/rxy); gsl_matrix_set(pReturn,2,2,gsl_vector_get(v,2)*gsl_vector_get(v,1)/rxy); gsl_matrix_set(pReturn,2,3,-R*sqrt(1.-gsl_vector_get(v,2)*gsl_vector_get(v,2)/R/R)); n1 = 1./sqrt(pow(gsl_matrix_get(pReturn,2,1),2.) + pow(gsl_matrix_get(pReturn,2,2),2.) + pow(gsl_matrix_get(pReturn,2,3),2.)); for(int i=0;i<3;i++) { tmp = gsl_matrix_get(pReturn,2,i+1); tmp = tmp*n1; gsl_matrix_set(pReturn,2,i+1,tmp); // set j' in the transformed (local) symmetry } gsl_matrix_set(pReturn,1,1,n1/R*(pow(gsl_vector_get(v,2),2.)*gsl_vector_get(v,1)/rxy + R*gsl_vector_get(v,1)*sqrt(1.-pow(gsl_vector_get(v,2),2.)/R/R))); gsl_matrix_set(pReturn,1,2,n1/R*(-pow(gsl_vector_get(v,2),2.)*gsl_vector_get(v,0)/rxy - R*gsl_vector_get(v,0)*sqrt(1.-pow(gsl_vector_get(v,2),2.)/R/R))); gsl_matrix_set(pReturn,1,3,0.); n2 = 1./sqrt(pow(gsl_matrix_get(pReturn,1,1),2.) + pow(gsl_matrix_get(pReturn,1,2),2.) + pow(gsl_matrix_get(pReturn,1,3),2.)); for(int i=0;i<3;i++) { tmp = gsl_matrix_get(pReturn,1,i+1); tmp = tmp/n2; gsl_matrix_set(pReturn,1,i+1,tmp); // set i' in the transformed (local) symmetry } } } else puts("sp_cluster_get_trans_mat 'pReturn' alloc error ... in SP_support.c or SP_support.h"); return pReturn; } /* SEE THE DETAILS IN THE 'N1' RING BINDER */ double sp_cluster_support_kronecker_delta( int a, int b ) { double Return = 0.; if( a == b ) Return = 1.; return Return; } // norm of vector double sp_cluster_support_get_norm( double v1, double v2, double v3 ) { return pow(v1*v1+v2*v2+v3*v3,0.5); } // SPLINER double** sp_cluster_support_get_spline( const double** data, const int knot_stride ) { double** pReturn = (double**)malloc((knot_stride-1)*sizeof(double*)); for(int i=0;i<knot_stride-1;i++) pReturn[i] = (double*)calloc(4,sizeof(double)); // Work Space const int n = knot_stride; double f[n]; double t[n]; double a[n]; double b[n]; double c[n]; double d[n]; double z[n]; double L[n]; double h[n]; double alpha[n]; double mu[n]; // Measuring slopes const double rslope = 0.; const double lslope = (data[3][1]-data[0][1])/(data[3][0]-data[0][0]); // Memset memset(f,0,n*sizeof(double)); memset(t,0,n*sizeof(double)); memset(a,0,n*sizeof(double)); memset(b,0,n*sizeof(double)); memset(c,0,n*sizeof(double)); memset(d,0,n*sizeof(double)); memset(z,0,n*sizeof(double)); memset(L,0,n*sizeof(double)); memset(h,0,n*sizeof(double)); memset(alpha,0,n*sizeof(double)); memset(mu,0,n*sizeof(double)); // Make Spline for(int i=0;i<n;i++) { f[i] = data[i][1]; t[i] = data[i][0]; } h[0] = t[1] - t[0]; alpha[0] = 3.*(f[1]-f[0])/h[0]-3.*lslope; L[0] = 2.*h[0]; mu[0] = 0.5; z[0] = alpha[0]/L[0]; b[0] = lslope; // End Left Init for(int k=1;k<n-1;k++) { h[k] = t[k+1] - t[k]; alpha[k] = (3./(h[k]*h[k-1]))*(f[k+1]*h[k-1]-f[k]*(h[k]+h[k-1])+f[k-1]*h[k]); L[k] = 2.*(h[k]+h[k-1])-h[k-1]*mu[k-1]; mu[k] = h[k]/L[k]; z[k] = (alpha[k]-h[k-1]*z[k-1])/L[k]; } // Right End init alpha[n-1] = 3.*rslope - 3.*(f[n-1]-f[n-2])/h[n-2]; L[n-1] = h[n-2]*(2.-mu[n-2]); z[n-1] = (alpha[n-1]-h[n-2]*z[n-2])/L[n-1]; c[n-1] = z[n-1]; for(int j=n-2;j>=0;j--) { c[j] = z[j]-mu[j]*c[j+1]; b[j] = (f[j+1]-f[j])/h[j] - h[j]*(c[j+1]+2.*c[j])/3.; d[j] = (c[j+1]-c[j])/(3.*h[j]); a[j] = f[j]; } // R-E END // SAVE DATA for(int i=0;i<knot_stride-1;i++) { pReturn[i][0] = d[i]; pReturn[i][1] = c[i] - 3.*t[i]*d[i]; pReturn[i][2] = b[i] - 2.*c[i]*t[i] + 3.*t[i]*t[i]*d[i]; pReturn[i][3] = a[i] - b[i]*t[i] + c[i]*t[i]*t[i] - d[i]*t[i]*t[i]*t[i]; } return pReturn; } //int sp_cluster_support_get_atom_number( void sp_cluster_support_print_xyz( void* sp_sys_void, const double cur_energy, const int rank, const int numtasks ) { int offset; // cast the type into "sp_cluster_system*" sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; int atom_number=0; for(int i=0;i<sp_sys->number_of_classic_ion;i++) { if( sp_sys->classic_ion[i].if_shell == SP_SUPPORT_FALSE ) atom_number++; // CNT ONLY WHEN ITS CORE } if( cur_energy != 0. ) { //printf("\t%d\n",sp_sys->number_of_classic_ion+sp_sys->number_of_sp_ion); printf("\t%d\n",atom_number+sp_sys->number_of_sp_ion); printf(" SCF DONE %.6lf\n",cur_energy); } // CORE POSITION ONLY ... "xyz" Format Compatible for(int n=0;n<sp_sys->number_of_sp_ion+sp_sys->number_of_classic_ion;n++) { offset = n-sp_sys->number_of_classic_ion; if( n < sp_sys->number_of_classic_ion ) { if( sp_sys->classic_ion[n].if_shell == SP_SUPPORT_FALSE ) // if it is core { fprintf(stdout,"%3s%12.6lf%12.6lf%12.6lf\n", sp_sys->classic_ion[n].atom_name, gsl_vector_get(sp_sys->classic_ion[n].core_position,0), gsl_vector_get(sp_sys->classic_ion[n].core_position,1), gsl_vector_get(sp_sys->classic_ion[n].core_position,2)); } } else // this is for printing sp-ions { offset = n - sp_sys->number_of_classic_ion; fprintf(stdout,"%3s%12.6lf%12.6lf%12.6lf\n", sp_sys->sp_ion[offset].atom_name, gsl_vector_get(sp_sys->sp_ion[offset].core_position,0), gsl_vector_get(sp_sys->sp_ion[offset].core_position,1), gsl_vector_get(sp_sys->sp_ion[offset].core_position,2)); } } printf("\n"); printf(" CONFIGURATION_XYZ_SC_INFO\n"); printf(" %d\t%d\n",sp_sys->number_of_classic_ion,sp_sys->number_of_sp_ion); // SHOW SHELL CORE POSITION BOTH for(int n=0;n<sp_sys->number_of_sp_ion+sp_sys->number_of_classic_ion;n++) { offset = n-sp_sys->number_of_classic_ion; if( n < sp_sys->number_of_classic_ion ) { if( sp_sys->classic_ion[n].if_shell == SP_SUPPORT_FALSE ) { fprintf(stdout,"%3s%3s%12.6lf%12.6lf%12.6lf\n", sp_sys->classic_ion[n].atom_name,"c", gsl_vector_get(sp_sys->classic_ion[n].core_position,0), gsl_vector_get(sp_sys->classic_ion[n].core_position,1), gsl_vector_get(sp_sys->classic_ion[n].core_position,2)); } else if( sp_sys->classic_ion[n].if_shell == SP_SUPPORT_TRUE ) { fprintf(stdout,"%3s%3s%12.6lf%12.6lf%12.6lf\n", sp_sys->classic_ion[n].atom_name,"s", gsl_vector_get(sp_sys->classic_ion[n].core_position,0), gsl_vector_get(sp_sys->classic_ion[n].core_position,1), gsl_vector_get(sp_sys->classic_ion[n].core_position,2)); } } else // this is for printing sp-ions { offset = n - sp_sys->number_of_classic_ion; fprintf(stdout,"%3s%15.6lf%12.6lf%12.6lf\n", sp_sys->sp_ion[offset].atom_name, gsl_vector_get(sp_sys->sp_ion[offset].core_position,0), gsl_vector_get(sp_sys->sp_ion[offset].core_position,1), gsl_vector_get(sp_sys->sp_ion[offset].core_position,2)); } } return; } /// DIIS_SUPPORT TOOLS /* int if_diis; int diis_max_depth; int diis_cur_depth; gsl_vector** diis_error_vector; // SAVE AS CIRCULAR QUEUE gsl_vector* diis_coefficient_vector; gsl_permutation* diis_ws_p; gsl_matrix* diis_error_matrix; gsl_matrix* diis_error_matrix_inv; */ void sp_cluster_support_diis_error_vector_queue_init( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; sp_sys->diis_error_vector_queue_front = 0; sp_sys->diis_error_vector_queue_rear = 0; return; } int sp_cluster_support_diis_error_vector_queue_isfull( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; if( (sp_sys->diis_error_vector_queue_rear+1)%sp_sys->diis_max_depth == sp_sys->diis_error_vector_queue_front ) return SP_SUPPORT_TRUE; else return SP_SUPPORT_FALSE; } int sp_cluster_support_diis_error_vector_queue_isempty( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; if( sp_sys->diis_error_vector_queue_front == sp_sys->diis_error_vector_queue_rear ) return SP_SUPPORT_TRUE; else return SP_SUPPORT_FALSE; } void sp_cluster_support_diis_error_vector_enqueue( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; double delta_evec[4]; int low_idx; double delta_evec_sum = 0.; //if( !((sp_sys->diis_error_vector_queue_rear+1)%sp_sys->diis_max_depth == sp_sys->diis_error_vector_queue_front) ) // check if queue is full if( sp_cluster_support_diis_error_vector_queue_isfull( sp_sys ) == SP_SUPPORT_FALSE ) { sp_sys->diis_error_vector_queue_rear = (sp_sys->diis_error_vector_queue_rear+1)%sp_sys->diis_max_depth; // rear index ++ sp_sys->diis_cur_depth++; for(int i=0;i<sp_sys->number_of_sp_ion;i++) { low_idx = sp_cluster_support_get_lowest_state(sp_sys->sp_ion[i].eigen_value); // current eigenvector - (loaded) previous eigenvector_gs delta_evec[0] = gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,0,low_idx) - gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,0); delta_evec[1] = gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,1,low_idx) - gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,1); delta_evec[2] = gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,2,low_idx) - gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,2); delta_evec[3] = gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,3,low_idx) - gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,3); delta_evec_sum += delta_evec[0]*delta_evec[0] + delta_evec[1]*delta_evec[1] + delta_evec[2]*delta_evec[2] + delta_evec[3]*delta_evec[3]; gsl_vector_set(sp_sys->diis_error_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+0,delta_evec[0]); gsl_vector_set(sp_sys->diis_error_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+1,delta_evec[0]); gsl_vector_set(sp_sys->diis_error_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+2,delta_evec[0]); gsl_vector_set(sp_sys->diis_error_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+3,delta_evec[0]); // loading .. previous eigen_vector_gs (note that the function 'sp_cluster_support_load_gs_eigenvector()' must be called before enqueue) gsl_vector_set(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+0, gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,0)); gsl_vector_set(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+1, gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,1)); gsl_vector_set(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+2, gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,2)); gsl_vector_set(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ],i*4+3, gsl_vector_get(sp_sys->sp_ion[i].eigen_vector_gs,3)); #ifdef DEBUG_SUPPORT printf("\ndelta evec\n"); printf("%12.6lf%12.6lf%12.6lf%12.6lf\n",delta_evec[0],delta_evec[1],delta_evec[2],delta_evec[3]); printf("%12.6lf%12.6lf%12.6lf%12.6lf\n", gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,0,low_idx), gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,1,low_idx), gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,2,low_idx), gsl_matrix_get(sp_sys->sp_ion[i].eigen_vector,3,low_idx)); #endif /* printf("%12.6lf%12.6lf%12.6lf%12.6lf\n",gsl_vector_get(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ], i*4 + 0 ), gsl_vector_get(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ], i*4 + 1 ), gsl_vector_get(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ], i*4 + 2 ), gsl_vector_get(sp_sys->diis_prev_eigen_vector[ sp_sys->diis_error_vector_queue_rear ], i*4 + 3 )); */ /* Note that the both, Error vector ( sp_sys->diis_error_vector ) Prev evecs ( sp_sys->diis_prev_eigen_vector ) Follows the form of (gsl_vector)v[i][j] v[i] ... 'i' -> index in the queue // queue is circular type, max dept is 'sp_sys->diis_max_depth' v[i][j] ... 'j' -> DATA, s_sp1, px_sp1, py_sp1, pz_sp1 // s_sp2, px_sp2, py_sp2, pz_sp2 // .... i.e., length of number_of_sp_ions * 4 (each lone pair ground-state MO saved with stride of 4) */ } printf("delta_evec_sum: %12.8lf\n",sqrt(delta_evec_sum)/sp_sys->number_of_sp_ion); } return; // if queue is full do nothing } void sp_cluster_support_diis_error_vector_dequeue( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; if( sp_cluster_support_diis_error_vector_queue_isempty( sp_sys ) == SP_SUPPORT_FALSE ) { sp_sys->diis_error_vector_queue_front = (sp_sys->diis_error_vector_queue_front+1)%sp_sys->diis_max_depth; sp_sys->diis_cur_depth--; } #ifdef DEBUG_SUPPORT const int front = sp_sys->diis_error_vector_queue_front; const int rear = sp_sys->diis_error_vector_queue_rear; printf("%d\t%d\n",front,rear); #endif return; // if queue is empty do nothing } double sp_cluster_support_diis_get_error_vector_gnorm( void* sp_sys_void ) // returns latest .. i.e., the one at rear { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; double ret; if( sp_cluster_support_diis_error_vector_queue_isempty( sp_sys ) == SP_SUPPORT_FALSE ) { ret = gsl_blas_dnrm2( sp_sys->diis_error_vector[ sp_sys->diis_error_vector_queue_rear ] ); return ret/sp_sys->number_of_sp_ion; } return 0.; } void sp_cluster_support_diis_solve_least_square_problem( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; // int count = front > rear ? (MAX - front + rear) : (rear - front); const int queue_capacity = sp_sys->diis_max_depth; const int front = sp_sys->diis_error_vector_queue_front; const int rear = sp_sys->diis_error_vector_queue_rear; const int cur_size = front > rear ? (queue_capacity - front + rear) : (rear - front); // number of elements in the queue (error_vector) /* gsl_vector* diis_coefficient_vector; gsl_permutation* diis_ws_p; gsl_matrix* diis_error_matrix; gsl_matrix* diis_error_matrix_inv; */ size_t len = cur_size + 1; printf("\n#### IN LSP SOLVER / len : %zu\n",len); printf("ws size : ErrorMat / %zu %zu\n",sp_sys->diis_error_matrix->size1,sp_sys->diis_error_matrix->size2); printf("cursize/max_depth/cur_depth : %4d%4d%4d\n", cur_size, sp_sys->diis_max_depth - 1, sp_sys->diis_cur_depth ); //if( !(cur_size == (sp_sys->diis_max_depth - 1)) ) //if( !(cur_size == (sp_sys->diis_max_depth)) ) //if( !(len == (sp_sys->diis_max_depth)) ) if( !(len == sp_sys->diis_error_matrix->size1) ) { printf("Resizing!!\n"); // if current size is not same with actual max_depth in use ... i.e., max_depth - 1, since circular queue in use // have to resize the workspaces ... diis_ws_p (gsl_permutation*) / diis_error_matrix (gsl_matrix*) / diis_error_matrix_inv (gsl_matrix*) gsl_vector_free(sp_sys->diis_coefficient_vector); gsl_vector_free(sp_sys->diis_least_square_condition); gsl_permutation_free(sp_sys->diis_ws_p); gsl_matrix_free(sp_sys->diis_error_matrix); gsl_matrix_free(sp_sys->diis_error_matrix_inv); sp_sys->diis_coefficient_vector = gsl_vector_calloc(len); sp_sys->diis_least_square_condition = gsl_vector_calloc(len); sp_sys->diis_ws_p = gsl_permutation_calloc(len); sp_sys->diis_error_matrix = gsl_matrix_calloc(len,len); sp_sys->diis_error_matrix_inv = gsl_matrix_calloc(len,len); // len = cur_size (error_vector length) + 1 // 1 is to represent least square sense of coeff } int ii=0; int jj=0; // tags to get actual matrix indices ! double elem_tmp; for(int i=(front+1)%queue_capacity; i!=(rear+1)%queue_capacity ; i=(i+1)%queue_capacity) // for loop circulate over queue elements { for(int j=(front+1)%queue_capacity; j!=(rear+1)%queue_capacity ; j=(j+1)%queue_capacity) { #ifdef DEBUG_SUPPORT printf("i,j / tag_i,tag_j : %d\t%d / %d\t%d\n",i,j,ii,jj); //printf("size1 / size2 : %d\t%d\n", sp_sys->diis_error_matrix->size1, sp_sys->diis_error_matrix->size2); #endif gsl_blas_ddot(sp_sys->diis_error_vector[j],sp_sys->diis_error_vector[i],&elem_tmp); gsl_matrix_set(sp_sys->diis_error_matrix,ii,jj,elem_tmp); jj++; } jj=0; ii++; } printf("ERROR - 0 ?\n"); ///// SET RESTS for(int i=0;i<len;i++) { gsl_matrix_set(sp_sys->diis_error_matrix,i,len-1,-1.); gsl_matrix_set(sp_sys->diis_error_matrix,len-1,i,-1.); } printf("ERROR?\n"); gsl_matrix_set(sp_sys->diis_error_matrix,len-1,len-1,0.); printf("ERROR?\n"); ///// SET least Square Condition vector gsl_vector_set(sp_sys->diis_least_square_condition,len-1,-1.); //// calculate inverse int signum; // variable for LU_decomp #ifdef DEBUG_SUPPORT printf("ErrorMatrix\n"); sp_cluster_support_matrix_view( sp_sys->diis_error_matrix ); #endif /* Say, Error matrix E Coefficient Vector C RHS Least Square Condition L Need to find 'C' vector Solve : EC = L, i.e., C = E_Inverse L */ gsl_linalg_LU_decomp(sp_sys->diis_error_matrix,sp_sys->diis_ws_p,&signum); gsl_linalg_LU_invert(sp_sys->diis_error_matrix,sp_sys->diis_ws_p,sp_sys->diis_error_matrix_inv); // invert is saved in 'sp_sys->diis_error_matrix_inv' // Inverse Found // int gsl_blas_dgemv(CBLAS_TRANSPOSE_t TransA, double alpha, const gsl_matrix *A, const gsl_vector *x, double beta, gsl_vector *y) gsl_blas_dgemv(CblasNoTrans,1.,sp_sys->diis_error_matrix_inv,sp_sys->diis_least_square_condition,0.,sp_sys->diis_coefficient_vector); // Solve LeaseSquare Problem Answer saved in 'sp_sys->diis_coefficient_vector' #ifdef DEBUG_SUPPORT //sp_cluster_support_vector_view( sp_sys->diis_least_square_condition ); printf("coefficient vector, ignore the last dummy lambda value\n"); sp_cluster_support_vector_view( sp_sys->diis_coefficient_vector ); //sp_cluster_support_matrix_view( sp_sys->diis_error_matrix ); printf("InverseMatrix\n"); sp_cluster_support_matrix_view( sp_sys->diis_error_matrix_inv ); printf("cursize/max_depth/cur_depth : %d\t%d\t%d\n", cur_size, sp_sys->diis_max_depth - 1, sp_sys->diis_cur_depth ); printf(" ---- FINALISE LEAST SQUARE SOLVER \n\n"); #endif return; } void sp_cluster_support_diis_least_square_result_update( void* sp_sys_void ) { sp_cluster_system* sp_sys = (sp_cluster_system*)sp_sys_void; int low_idx; int jj = 0; double cs, cx, cy, cz, norm_factor; const int queue_capacity = sp_sys->diis_max_depth; const int front = sp_sys->diis_error_vector_queue_front; const int rear = sp_sys->diis_error_vector_queue_rear; for(int i=0;i<sp_sys->number_of_sp_ion;i++) { low_idx = sp_cluster_support_get_lowest_state(sp_sys->sp_ion[i].eigen_value); // results are in 'sp_sys->diis_coefficient_vector' ... data structure sp_sys->diis_coefficient_vector->size or 'stride'? // size can also be obtained by 'sp_sys->diis_cur_depth' jj = 0; cs = 0.; cx = 0.; cy = 0.; cz = 0.; for(int j=(front+1)%queue_capacity; j!=(rear+1)%queue_capacity ; j=(j+1)%queue_capacity) { cs += gsl_vector_get( sp_sys->diis_coefficient_vector,jj) * gsl_vector_get(sp_sys->diis_prev_eigen_vector[j],i*4+0); cx += gsl_vector_get( sp_sys->diis_coefficient_vector,jj) * gsl_vector_get(sp_sys->diis_prev_eigen_vector[j],i*4+1); cy += gsl_vector_get( sp_sys->diis_coefficient_vector,jj) * gsl_vector_get(sp_sys->diis_prev_eigen_vector[j],i*4+2); cz += gsl_vector_get( sp_sys->diis_coefficient_vector,jj) * gsl_vector_get(sp_sys->diis_prev_eigen_vector[j],i*4+3); jj++; printf("index j / tag jj: %d\t%d\n",j,jj); } #ifdef DEBUG_SUPPORT printf("%dth\t%12.4lf%12.4lf%12.4lf%12.4lf%20.4lf\n",i+1,cs,cx,cy,cz,sqrt(cs*cs+cx*cx+cy*cy+cz*cz)); #endif norm_factor = sqrt(cs*cs+cx*cx+cy*cy+cz*cz); norm_factor = 1.; gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,0,low_idx,cs/norm_factor); gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,1,low_idx,cx/norm_factor); gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,2,low_idx,cy/norm_factor); gsl_matrix_set(sp_sys->sp_ion[i].eigen_vector,3,low_idx,cz/norm_factor); // set eigenvector ... updated!!! // finish up the rest ... } return; }
{ "alphanum_fraction": 0.6490770824, "avg_line_length": 39.2282913165, "ext": "c", "hexsha": "f860481510256732fa35f546e67ba1a996d7642b", "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": "60335c37ce75b82f6589c67f3a1c1be37decfd71", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sweetmixture/SLAM_2.2.1_snapshot", "max_forks_repo_path": "src/sp_cluster_support.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "60335c37ce75b82f6589c67f3a1c1be37decfd71", "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": "sweetmixture/SLAM_2.2.1_snapshot", "max_issues_repo_path": "src/sp_cluster_support.c", "max_line_length": 175, "max_stars_count": 1, "max_stars_repo_head_hexsha": "60335c37ce75b82f6589c67f3a1c1be37decfd71", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sweetmixture/SLAM_2.2.1_snapshot", "max_stars_repo_path": "src/sp_cluster_support.c", "max_stars_repo_stars_event_max_datetime": "2022-02-02T07:01:42.000Z", "max_stars_repo_stars_event_min_datetime": "2022-02-02T07:01:42.000Z", "num_tokens": 8568, "size": 28009 }
/** @file header.h * */ #ifndef HEADER_H #define HEADER_H #define _GNU_SOURCE #include <time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <string.h> #include <omp.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_legendre.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_vegas.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_sf_expint.h> #include <ctype.h> #include "cuba.h" #define PSC 101L #define ST 102L #define TK 103L #define GROWTH 104L #define DERGROWTH 105L #define NONLINEAR 106L #define LINEAR 107L #define GAUSSIAN 114L #define NONGAUSSIAN 115L #define INIT 116L #define LOCAL 117L #define EQUILATERAL 118L #define ORTHOGONAL 119L #define QSF 120L #define HS 121L #define NGLOOP 122L #define derNGLOOP 123L #define QUADRATIC 124L #define TIDE 125L #define GAMMA 126L #define LPOWER 127L #define NLPOWER 128L #define CDM 90L #define BA 91L #define TOT 92L #define CO10 131L #define CO21 132L #define CO32 133L #define CO43 134L #define CO54 135L #define CO65 136L #define CII 137L #define MATTER 138L #define LINEMATTER 139L #define LINE 140L #define DST 141L #define GFILTER 142L #define BSPLINE 143L #define TREE 144L #define LOOP 145L #define WIR 146L #define NOIR 147L #define HALO 148L #define MEAN 149L #define HMshot 150L #define HMclust 151L #define PS_KMIN 1.e-5 #define PS_KMAX 300.1 #define PS_ZMAX 14. #define CLEANUP 1 #define DO_NOT_EVALUATE -1.0 #define NPARS 6 #define MAXL 2000 extern struct globals gb; /** * List of limHaloPT header files */ /// \cond DO_NOT_DOCUMENT #include "../Class/include/class.h" /// \endcond #include "global_structs.h" #include "hcubature.h" #include "utilities.h" #include "setup_teardown.h" #include "cosmology.h" #include "ir_res.h" #include "line_ingredients.h" #include "ps_halo_1loop.h" #include "ps_line_hm.h" #include "ps_line_pt.h" #include "survey_specs.h" #include "wnw_split.h" /** * A structure passed to the integrators to hold the parameters fixed in the integration */ struct integrand_parameters { double p1; double p2; double p3; double p4; double p5; double p6; double p7; double p8; double p9; double p10; double p11; long p12; long p13; }; /** * Another structure passed to the integrators to hold the parameters fixed in the integration */ struct integrand_parameters2 { struct Cosmology *p1; struct Cosmology *p2; struct Cosmology *p3; double p4; double p5; double p6; double p7; double p8; double p9; double p10; double p11; double p12; long p13; long p14; long p15; long p16; long p17; long p18; int p19; double *p20; size_t p22; }; #endif
{ "alphanum_fraction": 0.7032216075, "avg_line_length": 16.0052083333, "ext": "h", "hexsha": "e9020d103b3949923a284e8bd50a33e3664cb25f", "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": "302c139809ffa95a6e154a4268e4d48e4082cdf3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "amoradinejad/limHaloPT", "max_forks_repo_path": "Include/header.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "302c139809ffa95a6e154a4268e4d48e4082cdf3", "max_issues_repo_issues_event_max_datetime": "2022-03-24T17:35:55.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-17T14:55:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "amoradinejad/limHaloPT", "max_issues_repo_path": "Include/header.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "302c139809ffa95a6e154a4268e4d48e4082cdf3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "amoradinejad/limHaloPT", "max_stars_repo_path": "Include/header.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1001, "size": 3073 }
#include "cones.h" #ifdef LAPACK_LIB_FOUND #include <cblas.h> #include <lapacke.h> #endif void projectsdc(double * X, int n, Work * w); /* in place projection (with branches) */ void projCone(double *x, Cone * k, Work * w) { int i; int count; /* project onto positive orthant */ for(i = k->f; i < k->f+k->l; ++i) { if(x[i] < 0.0) x[i] = 0.0; //x[i] = (x[i] < 0.0) ? 0.0 : x[i]; } count = k->l+k->f; /* project onto SOC */ for(i = 0; i < k->qsize; ++i) { double v1 = x[count]; double s = calcNorm(&(x[count+1]),k->q[i]-1); double alpha = (s + v1)/2.0; if(s <= v1) { /* do nothing */ } else if (s <= - v1) { memset(&(x[count]), 0, k->q[i]*sizeof(double)); } else { x[count] = alpha; scaleArray(&(x[count+1]), alpha/s, k->q[i]-1); //cblas_dscal(k->q[i]-1, alpha/s, &(x[count+1]),1); } count += k->q[i]; } #ifdef LAPACK_LIB_FOUND /* project onto PSD cone */ for (i=0; i < k->ssize; ++i){ projectsdc(&(x[count]),k->s[i],w); count += (k->s[i])*(k->s[i]); } #else if(k->ssize > 0){ coneOS_printf("WARNING: solving SDP, no lapack library specified in makefile!\n"); coneOS_printf("ConeOS will return a wrong answer!\n"); } #endif /* project onto OTHER cones */ } #ifdef LAPACK_LIB_FOUND void projectsdc(double *X, int n, Work * w) { /* project onto the positive semi-definite cone */ if (n == 1) { if(X[0] < 0.0) X[0] = 0.0; return; } int i, j, m=0; double * Xs = w->Xs; double * Z = w->Z; double * e = w->e; memcpy(Xs,X,n*n*sizeof(double)); // Xs = X + X', save div by 2 for eigen-recomp for (i = 0; i < n; ++i){ cblas_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1); //b_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1); } double EIG_TOL = 1e-8; double vupper = calcNorm(Xs,n*n); LAPACKE_dsyevr( LAPACK_COL_MAJOR, 'V', 'V', 'U', n, Xs, n, 0.0, vupper, -1, -1, EIG_TOL, &m, e, Z, n , NULL); memset(X, 0, n*n*sizeof(double)); for (i = 0; i < m; ++i) { cblas_dsyr(CblasColMajor, CblasLower, n, e[i]/2, &(Z[i*n]), 1, X, n); //b_dsyr('L', n, -e[i]/2, &(Z[i*n]), 1, Xs, n); } // fill in upper half for (i = 0; i < n; ++i){ for (j = i+1; j < n; ++j){ X[i + j*n] = X[j + i*n]; } } } #endif
{ "alphanum_fraction": 0.5165326184, "avg_line_length": 24.5934065934, "ext": "c", "hexsha": "65e2f6412f5d2d070a5f997d8005001c7d1fb5c6", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-12-20T19:38:22.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-26T23:10:34.000Z", "max_forks_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "cvxgrp/coneos", "max_forks_repo_path": "coneOSdense/cones.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "cvxgrp/coneos", "max_issues_repo_path": "coneOSdense/cones.c", "max_line_length": 111, "max_stars_count": 1, "max_stars_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "cvxgrp/coneos", "max_stars_repo_path": "coneOSdense/cones.c", "max_stars_repo_stars_event_max_datetime": "2015-08-29T07:42:29.000Z", "max_stars_repo_stars_event_min_datetime": "2015-08-29T07:42:29.000Z", "num_tokens": 902, "size": 2238 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <mpi.h> #include <petsc.h> #include <petscvec.h> #include <petscsnes.h> #include <Python.h> #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include <StgFEM/libStgFEM/src/StgFEM.h> #include "StgFEM/Discretisation/src/Discretisation.h" #include "types.h" #include "SystemLinearEquations.h" #include "SLE_Solver.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "StiffnessMatrix.h" #include "SolutionVector.h" #include "ForceVector.h" #include "FiniteElementContext.h" /* Textual name of this class */ const Type SystemLinearEquations_Type = "SystemLinearEquations"; /** Constructor */ SystemLinearEquations* SystemLinearEquations_New( Name name, FiniteElementContext* context, SLE_Solver* solver, void* nlSolver, Bool isNonLinear, double nonLinearTolerance, Iteration_Index nonLinearMinIterations, Iteration_Index nonLinearMaxIterations, Bool killNonConvergent, EntryPoint_Register* entryPoint_Register, MPI_Comm comm ) { SystemLinearEquations* self = _SystemLinearEquations_DefaultNew( name ); self->isConstructed = True; _SystemLinearEquations_Init( self, solver, nlSolver, context, False, /* TODO: A hack put in place for setting the convergence stream to 'off' if the SLE class is created from within the code, not via an xml */ isNonLinear, nonLinearTolerance, nonLinearMaxIterations, killNonConvergent, nonLinearMinIterations, "", "", entryPoint_Register, comm ); return self; } /* Creation implementation / Virtual constructor */ SystemLinearEquations* _SystemLinearEquations_New( SYSTEMLINEAREQUATIONS_DEFARGS ) { SystemLinearEquations* self; /* Allocate memory */ assert( _sizeOfSelf >= sizeof(SystemLinearEquations) ); /* The following terms are parameters that have been passed into this function but are being set before being passed onto the parent */ /* This means that any values of these parameters that are passed into this function are not passed onto the parent function and so should be set to ZERO in any children of this class. */ nameAllocationType = NON_GLOBAL; self = (SystemLinearEquations*) _Stg_Component_New( STG_COMPONENT_PASSARGS ); /* Virtual info */ self->_LM_Setup = _LM_Setup; self->_matrixSetup = _matrixSetup; self->_vectorSetup = _vectorSetup; self->_updateSolutionOntoNodes = _updateSolutionOntoNodes; self->_mgSelectStiffMats = _mgSelectStiffMats; self->_sleFormFunction = NULL; /* this guy defaults to true so that we run within the execute phase as default */ self->runatExecutePhase = True; self->solver_callback = NULL; return self; } void _SystemLinearEquations_Init( void* sle, SLE_Solver* solver, void* nlSolver, FiniteElementContext* context, Bool makeConvergenceFile, Bool isNonLinear, double nonLinearTolerance, Iteration_Index nonLinearMaxIterations, Bool killNonConvergent, Iteration_Index nonLinearMinIterations, Name nonLinearSolutionType, Name optionsPrefix, EntryPoint_Register* entryPoint_Register, MPI_Comm comm ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; char* filename; char* optionsName; self->extensionManager = ExtensionManager_New_OfExistingObject( self->name, self ); self->debug = Stream_RegisterChild( StgFEM_SLE_SystemSetup_Debug, self->type ); self->info = Journal_MyStream( Info_Type, self ); /* Note: currently we're sending self->info to the master proc only so there's not too much identical timing info printed. May want to fine-tune later so that some info does get printed on all procs. */ Stream_SetPrintingRank( self->info, 0 ); self->makeConvergenceFile = makeConvergenceFile; if ( context && self->makeConvergenceFile ) { self->convergenceStream = Journal_Register( InfoStream_Type, (Name)"Convergence Info" ); Stg_asprintf( &filename, "Convergence.dat" ); Stream_RedirectFile_WithPrependedPath( self->convergenceStream, context->outputPath, filename ); Stream_SetPrintingRank( self->convergenceStream, 0 ); Memory_Free( filename ); Journal_Printf( self->convergenceStream , "Timestep\tIteration\tResidual\tTolerance\n" ); } self->comm = comm; self->solver = solver; self->nlSolver = (SNES)nlSolver; self->stiffnessMatrices = Stg_ObjectList_New(); self->forceVectors = Stg_ObjectList_New(); self->solutionVectors = Stg_ObjectList_New(); self->context = context; /* Init NonLinear Stuff */ self->nonLinearSolutionType = nonLinearSolutionType; /* This will never got propogated through to _Initialise->SetToNonLinear if we keep it in the loop */ if ( isNonLinear ) SystemLinearEquations_SetToNonLinear( self, True ); self->nonLinearTolerance = nonLinearTolerance; self->nonLinearMaxIterations = nonLinearMaxIterations; self->killNonConvergent = killNonConvergent; self->nonLinearMinIterations = nonLinearMinIterations; self->curResidual = 0.0; self->curSolveTime = 0.0; /* _ /0 */ optionsName = Memory_Alloc_Array_Unnamed( char, strlen(optionsPrefix) + 1 + 1 ); sprintf( optionsName, "%s_", optionsPrefix ); self->optionsPrefix = optionsName; /* BEGIN LUKE'S FRICTIONAL BCS BIT */ Stg_asprintf( &self->nlSetupEPName, "%s-nlSetupEP", self->name ); self->nlSetupEP = EntryPoint_New( self->nlSetupEPName, EntryPoint_2VoidPtr_CastType ); Stg_asprintf( &self->nlEPName, "%s-nlEP", self->name ); self->nlEP = EntryPoint_New( self->nlEPName, EntryPoint_2VoidPtr_CastType ); Stg_asprintf( &self->nlEPName, "%s-postNlEP", self->name ); self->postNlEP = EntryPoint_New( self->postNlEPName, EntryPoint_2VoidPtr_CastType ); Stg_asprintf( &self->nlConvergedEPName, "%s-nlConvergedEP", self->name ); self->nlConvergedEP = EntryPoint_New( self->nlConvergedEPName, EntryPoint_2VoidPtr_CastType ); /* END LUKE'S FRICTIONAL BCS BIT */ self->nlFormJacobian = False; self->nlCurIterate = PETSC_NULL; /* Initialise MG stuff. */ self->mgEnabled = False; self->mgUpdate = True; self->nMGHandles = 0; self->mgHandles = NULL; /* Create Execute Entry Point */ Stg_asprintf( &self->executeEPName, "%s-execute", self->name ); self->executeEP = EntryPoint_New( self->executeEPName, EntryPoint_2VoidPtr_CastType ); /* Add default hooks to Execute E.P. */ EntryPoint_Append( self->executeEP, "BC_Setup", SystemLinearEquations_BC_Setup, self->type); EntryPoint_Append( self->executeEP, "LM_Setup", SystemLinearEquations_LM_Setup, self->type); EntryPoint_Append( self->executeEP, "IntegrationSetup", SystemLinearEquations_IntegrationSetup, self->type ); EntryPoint_Append( self->executeEP, "ZeroAllVectors", SystemLinearEquations_ZeroAllVectors, self->type); EntryPoint_Append( self->executeEP, "MatrixSetup", SystemLinearEquations_MatrixSetup, self->type); EntryPoint_Append( self->executeEP, "VectorSetup", SystemLinearEquations_VectorSetup, self->type); EntryPoint_Append( self->executeEP, "ExecuteSolver", SystemLinearEquations_ExecuteSolver, self->type); EntryPoint_Append( self->executeEP, "UpdateSolutionOntoNodes",SystemLinearEquations_UpdateSolutionOntoNodes,self->type); /* Create Integration Setup EP */ Stg_asprintf( &self->integrationSetupEPName, "%s-integrationSetup", self->name ); self->integrationSetupEP = EntryPoint_New( self->integrationSetupEPName, EntryPoint_Class_VoidPtr_CastType ); if ( entryPoint_Register ) EntryPoint_Register_Add( entryPoint_Register, self->executeEP ); self->entryPoint_Register = entryPoint_Register; /* Add SLE to Context */ if ( context ) FiniteElementContext_AddSLE( context, self ); } void _SystemLinearEquations_Delete( void* sle ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Journal_DPrintf( self->debug, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); Stg_Class_Delete(self->integrationSetupEP); /* delete parent */ _Stg_Component_Delete( self ); Stream_UnIndentBranch( StgFEM_Debug ); } void _SystemLinearEquations_Print( void* sle, Stream* stream ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; /* General info */ Journal_Printf( stream, "SystemLinearEquations (ptr): %p\n", self ); _Stg_Component_Print( self, stream ); /* Virtual info */ Stg_Class_Print( self->stiffnessMatrices, stream ); Stg_Class_Print( self->forceVectors, stream ); Stg_Class_Print( self->solutionVectors, stream ); /* other info */ Journal_PrintPointer( stream, self->extensionManager ); Journal_Printf( stream, "\tcomm: %u\n", self->comm ); Journal_Printf( stream, "\tsolver (ptr): %p\n", self->solver ); Stg_Class_Print( self->solver, stream ); } void* _SystemLinearEquations_Copy( void* sle, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; SystemLinearEquations* newSLE; PtrMap* map = ptrMap; Bool ownMap = False; if( !map ) { map = PtrMap_New( 10 ); ownMap = True; } newSLE = _Stg_Component_Copy( sle, dest, deep, nameExt, map ); /* Virtual methods */ newSLE->_LM_Setup = self->_LM_Setup; newSLE->_matrixSetup = self->_matrixSetup; newSLE->_vectorSetup = self->_vectorSetup; newSLE->_mgSelectStiffMats = self->_mgSelectStiffMats; newSLE->debug = Stream_RegisterChild( StgFEM_SLE_SystemSetup_Debug, newSLE->type ); newSLE->comm = self->comm; if( deep ) { newSLE->solver = (SLE_Solver*)Stg_Class_Copy( self->solver, NULL, deep, nameExt, map ); newSLE->stiffnessMatrices = (StiffnessMatrixList*)Stg_Class_Copy( self->stiffnessMatrices, NULL, deep, nameExt, map ); newSLE->forceVectors = (ForceVectorList*)Stg_Class_Copy( self->forceVectors, NULL, deep, nameExt, map ); newSLE->solutionVectors = (SolutionVectorList*)Stg_Class_Copy( self->solutionVectors, NULL, deep, nameExt, map ); if( (newSLE->extensionManager = PtrMap_Find( map, self->extensionManager )) == NULL ) { newSLE->extensionManager = Stg_Class_Copy( self->extensionManager, NULL, deep, nameExt, map ); PtrMap_Append( map, self->extensionManager, newSLE->extensionManager ); } } else { newSLE->solver = self->solver; newSLE->stiffnessMatrices = self->stiffnessMatrices; newSLE->forceVectors = self->forceVectors; newSLE->solutionVectors = self->solutionVectors; } if( ownMap ) { Stg_Class_Delete( map ); } return newSLE; } void* _SystemLinearEquations_DefaultNew( Name name ) { /* Variables set in this function */ SizeT _sizeOfSelf = sizeof(SystemLinearEquations); Type type = SystemLinearEquations_Type; Stg_Class_DeleteFunction* _delete = _SystemLinearEquations_Delete; Stg_Class_PrintFunction* _print = _SystemLinearEquations_Print; Stg_Class_CopyFunction* _copy = _SystemLinearEquations_Copy; Stg_Component_DefaultConstructorFunction* _defaultConstructor = _SystemLinearEquations_DefaultNew; Stg_Component_ConstructFunction* _construct = _SystemLinearEquations_AssignFromXML; Stg_Component_BuildFunction* _build = _SystemLinearEquations_Build; Stg_Component_InitialiseFunction* _initialise = _SystemLinearEquations_Initialise; Stg_Component_ExecuteFunction* _execute = _SystemLinearEquations_Execute; Stg_Component_DestroyFunction* _destroy = _SystemLinearEquations_Destroy; SystemLinearEquations_LM_SetupFunction* _LM_Setup = _SystemLinearEquations_LM_Setup; SystemLinearEquations_MatrixSetupFunction* _matrixSetup = _SystemLinearEquations_MatrixSetup; SystemLinearEquations_VectorSetupFunction* _vectorSetup = _SystemLinearEquations_VectorSetup; SystemLinearEquations_UpdateSolutionOntoNodesFunc* _updateSolutionOntoNodes = _SystemLinearEquations_UpdateSolutionOntoNodes; SystemLinearEquations_MG_SelectStiffMatsFunc* _mgSelectStiffMats = _SystemLinearEquations_MG_SelectStiffMats; /* Variables that are set to ZERO are variables that will be set either by the current _New function or another parent _New function further up the hierachy */ AllocationType nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */; return _SystemLinearEquations_New( SYSTEMLINEAREQUATIONS_PASSARGS ); } void _SystemLinearEquations_AssignFromXML( void* sle, Stg_ComponentFactory* cf, void* data ){ SystemLinearEquations* self = (SystemLinearEquations*)sle; SLE_Solver* solver = NULL; void* entryPointRegister = NULL; FiniteElementContext* context = NULL; double nonLinearTolerance; Iteration_Index nonLinearMaxIterations; Bool isNonLinear; Bool killNonConvergent; Bool makeConvergenceFile; Iteration_Index nonLinearMinIterations; Name nonLinearSolutionType; SNES nlSolver = NULL; Name optionsPrefix; solver = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)SLE_Solver_Type, SLE_Solver, False, data ) ; makeConvergenceFile = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)"makeConvergenceFile", False ); isNonLinear = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)"isNonLinear", False ); nonLinearTolerance = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)"nonLinearTolerance", 0.01 ); nonLinearMaxIterations = Stg_ComponentFactory_GetUnsignedInt( cf, self->name, (Dictionary_Entry_Key)"nonLinearMaxIterations", 500 ); killNonConvergent = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)"killNonConvergent", True ); nonLinearMinIterations = Stg_ComponentFactory_GetUnsignedInt( cf, self->name, (Dictionary_Entry_Key)"nonLinearMinIterations", 1 ); nonLinearSolutionType = Stg_ComponentFactory_GetString( cf, self->name, (Dictionary_Entry_Key)"nonLinearSolutionType", "default" ); optionsPrefix = Stg_ComponentFactory_GetString( cf, self->name, (Dictionary_Entry_Key)"optionsPrefix", "" ); /* Read some value for Picard */ self->picard_form_function_type = Stg_ComponentFactory_GetString( cf, self->name, (Dictionary_Entry_Key)"picard_FormFunctionType", "PicardFormFunction_KSPResidual" ); self->alpha = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)"picard_alpha", 1.0 ); self->rtol = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)"picard_rtol", 1.0e-8 ); self->abstol = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)"picard_atol", 1.0e-50 ); self->stol = Stg_ComponentFactory_GetDouble( cf, self->name, (Dictionary_Entry_Key)"picard_stol", 1.0e-8 ); self->picard_monitor = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)"picard_ActivateMonitor", False ); context = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"Context", FiniteElementContext, False, data ); if( !context ) context = Stg_ComponentFactory_ConstructByName( cf, (Name)"context", FiniteElementContext, False, data ); if( context ){ entryPointRegister = context->entryPoint_Register; assert( entryPointRegister ); } if( isNonLinear ) { SNESCreate( MPI_COMM_WORLD, &nlSolver ); self->linearSolveInitGuess = Stg_ComponentFactory_GetBool( cf, self->name, (Dictionary_Entry_Key)"linearSolveInitialGuess", False ); } _SystemLinearEquations_Init( self, solver, nlSolver, context, makeConvergenceFile, isNonLinear, nonLinearTolerance, nonLinearMaxIterations, killNonConvergent, nonLinearMinIterations, nonLinearSolutionType, optionsPrefix, entryPointRegister, MPI_COMM_WORLD ); VecCreate( self->comm, &self->X ); VecCreate( self->comm, &self->F ); MatCreate( self->comm, &self->A ); MatCreate( self->comm, &self->J ); } /* Build */ void _SystemLinearEquations_Build( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Index index; Journal_DPrintf( self->debug, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); /* build the matrices */ for ( index = 0; index < self->stiffnessMatrices->count; index++ ) { /* Update rowSize and colSize if boundary conditions have been applied */ Stg_Component_Build( self->stiffnessMatrices->data[index], _context, False ); } /* and the vectors */ for ( index = 0; index < self->forceVectors->count; index++ ) { /* Build the force vectors - includes updateing matrix size based on Dofs */ Stg_Component_Build( self->forceVectors->data[index], _context, False ); } /* and the solutions */ for ( index = 0; index < self->solutionVectors->count; index++ ) { /* Build the force vectors - includes updateing matrix size based on Dofs */ Stg_Component_Build( self->solutionVectors->data[index], _context, False ); } /* lastly, the solver - if required */ if( self->solver ) Stg_Component_Build( self->solver, self, True ); Stream_UnIndentBranch( StgFEM_Debug ); } void _SystemLinearEquations_Initialise( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Index index; Journal_DPrintf( self->debug, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); /* initialise the matrices */ for ( index = 0; index < self->stiffnessMatrices->count; index++ ) { /* Update rowSize and colSize if boundary conditions have been applied */ Stg_Component_Initialise( self->stiffnessMatrices->data[index], _context, False ); } /* and the vectors */ for ( index = 0; index < self->forceVectors->count; index++ ) { /* Initialise the force vectors - includes updateing matrix size based on Dofs */ Stg_Component_Initialise( self->forceVectors->data[index], _context, False ); } /* and the solutions */ for ( index = 0; index < self->solutionVectors->count; index++ ) { /* Initialise the force vectors - includes updateing matrix size based on Dofs */ Stg_Component_Initialise( self->solutionVectors->data[index], _context, False ); } /* Check to see if any of the components need to make the SLE non-linear */ SystemLinearEquations_CheckIfNonLinear( self ); /* Setup Location Matrix */ SystemLinearEquations_LM_Setup( self, _context ); /* lastly, the solver, if required */ if( self->solver ) Stg_Component_Initialise( self->solver, self, False ); Stream_UnIndentBranch( StgFEM_Debug ); } void _SystemLinearEquations_Execute( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Journal_DPrintf( self->debug, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); if(self->runatExecutePhase) _SystemLinearEquations_RunEP( sle, _context ); Stream_UnIndentBranch( StgFEM_Debug ); } void _SystemLinearEquations_RunEP( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; _EntryPoint_Run_2VoidPtr( self->executeEP, sle, _context ); } void SystemLinearEquations_ExecuteSolver( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; double wallTime; /* Actually run the solver to get the new values into the SolutionVectors */ Journal_Printf(self->info,"Linear solver (%s) \n",self->executeEPName); wallTime = MPI_Wtime(); if( self->solver ) Stg_Component_Execute( self->solver, self, True ); self->curSolveTime = MPI_Wtime() - wallTime; Journal_Printf(self->info,"Linear solver (%s), solution time %6.6e (secs)\n",self->executeEPName, self->curSolveTime); } void _SystemLinearEquations_Destroy( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; /* BEGIN LUKE'S FRICTIONAL BCS BIT */ Memory_Free( self->nlSetupEPName ); Memory_Free( self->nlEPName ); Memory_Free( self->postNlEPName ); Memory_Free( self->nlConvergedEPName ); /* END LUKE'S FRICTIONAL BCS BIT */ Memory_Free( self->executeEPName ); Stg_Class_Delete( self->extensionManager ); Stg_Class_Delete( self->stiffnessMatrices ); Stg_Class_Delete( self->forceVectors ); Stg_Class_Delete( self->solutionVectors ); Memory_Free( self->optionsPrefix ); Stg_VecDestroy(&self->X ); Stg_VecDestroy(&self->F ); Stg_MatDestroy(&self->A ); Stg_MatDestroy(&self->J ); /* Free the the MG handles. */ FreeArray( self->mgHandles ); } void SystemLinearEquations_BC_Setup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Index index; Journal_DPrintf( self->debug, "In %s\n", __func__ ); for ( index = 0; index < self->solutionVectors->count; index++ ) { SolutionVector_ApplyBCsToVariables( self->solutionVectors->data[index], _context ); } } void SystemLinearEquations_LM_Setup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; self->_LM_Setup( self, _context ); } void SystemLinearEquations_IntegrationSetup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; _EntryPoint_Run_Class_VoidPtr( self->integrationSetupEP, _context ); } void _SystemLinearEquations_LM_Setup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Index index; Journal_DPrintf( self->debug, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); /* For each feVariable of each stiffness matrix, build the LM */ for ( index = 0; index < self->stiffnessMatrices->count; index++ ) { StiffnessMatrix* sm = (StiffnessMatrix*)self->stiffnessMatrices->data[index]; FeEquationNumber_BuildLocationMatrix( sm->rowEqNum ); FeEquationNumber_BuildLocationMatrix( sm->colEqNum ); } Stream_UnIndentBranch( StgFEM_Debug ); } void SystemLinearEquations_MatrixSetup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; self->_matrixSetup( self, _context ); } void _SystemLinearEquations_MatrixSetup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; FiniteElementContext* context = (FiniteElementContext*)_context; Index index; Journal_DPrintf( self->debug, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); for ( index = 0; index < self->stiffnessMatrices->count; index++ ) { StiffnessMatrix_Assemble( self->stiffnessMatrices->data[index], self, context ); } Stream_UnIndentBranch( StgFEM_Debug ); } void SystemLinearEquations_VectorSetup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; self->_vectorSetup( self, _context ); } void _SystemLinearEquations_VectorSetup( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Index index; Journal_DPrintf( self->debug, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); for ( index = 0; index < self->forceVectors->count; index++ ) { ForceVector_Assemble( self->forceVectors->data[index] ); } Stream_UnIndentBranch( StgFEM_Debug ); } Index _SystemLinearEquations_AddStiffnessMatrix( void* sle, StiffnessMatrix* stiffnessMatrix ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; return SystemLinearEquations_AddStiffnessMatrix( self, stiffnessMatrix ); } StiffnessMatrix* _SystemLinearEquations_GetStiffnessMatrix( void* sle, Name stiffnessMatrixName ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; return SystemLinearEquations_GetStiffnessMatrix( self, stiffnessMatrixName ); } Index _SystemLinearEquations_AddForceVector( void* sle, ForceVector* forceVector ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; return SystemLinearEquations_AddForceVector( self, forceVector ); } ForceVector* _SystemLinearEquations_GetForceVector( void* sle, Name forceVectorName ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; return SystemLinearEquations_GetForceVector( self, forceVectorName ); } Index _SystemLinearEquations_AddSolutionVector( void* sle, SolutionVector* solutionVector ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; return SystemLinearEquations_AddSolutionVector( self, solutionVector ); } SolutionVector* _SystemLinearEquations_GetSolutionVector( void* sle, Name solutionVectorName ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; return SystemLinearEquations_GetSolutionVector( self, solutionVectorName ); } void SystemLinearEquations_SetCallback( void* sle, PyObject* func) { SystemLinearEquations *self = (SystemLinearEquations*) sle; // Assign the PyObject - 'None' or callable function to solver_callback if (func == Py_None) self->solver_callback = NULL; else { // check if it's callable if(!PyCallable_Check(func)){ PyErr_SetString( PyExc_ValueError, "The callback function can't be called, please check if it's valid"); } self->solver_callback = func; } } void SystemLinearEquations_UpdateSolutionOntoNodes( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; self->_updateSolutionOntoNodes( self, _context ); // execute the python callback if found if( self->solver_callback ) { if(!PyObject_CallObject(self->solver_callback, NULL )) { // check if callback execution failed PyErr_SetString( PyExc_RuntimeError, "Failed to execute the callback function, please check if it's valid"); } } } void _SystemLinearEquations_UpdateSolutionOntoNodes( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; SolutionVector_Index solnVec_I; SolutionVector* currentSolnVec; for ( solnVec_I=0; solnVec_I < self->solutionVectors->count; solnVec_I++ ) { currentSolnVec = (SolutionVector*)self->solutionVectors->data[solnVec_I]; SolutionVector_UpdateSolutionOntoNodes( currentSolnVec ); } } void SystemLinearEquations_ZeroAllVectors( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; Index index; for ( index = 0; index < self->forceVectors->count; index++ ) ForceVector_Zero( self->forceVectors->data[index] ); } /* need to do this before the SLE specific function to set up the pre conditioners is called (beginning of solve) */ void SystemLinearEquations_NewtonInitialise( void* _context, void* data ) { FiniteElementContext* context = (FiniteElementContext*)_context; assert(0); // the following will need to be fixed to get the sle from elsewhere SystemLinearEquations* sle = (SystemLinearEquations*)context->slEquations->data[0]; SNES snes; SNES oldSnes = sle->nlSolver; /* don't assume that a snes is being used for initial guess, check for this!!! */ if( oldSnes && context->timeStep == 1 && !sle->linearSolveInitGuess ) Stg_SNESDestroy(&oldSnes ); SNESCreate( sle->comm, &snes ); sle->nlSolver = snes; sle->_setFFunc( &sle->F, context ); SNESSetJacobian( snes, sle->J, sle->P, sle->_buildJ, sle->buildJContext ); SNESSetFunction( snes, sle->F, sle->_buildF, sle->buildFContext ); /* configure the KSP */ sle->_configureNLSolverFunc( snes, context ); } /* do this after the pre conditoiners have been set up in the problem specific SLE */ void SystemLinearEquations_NewtonExecute( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*) sle; SNES snes = self->nlSolver; SNESSetOptionsPrefix( snes, self->optionsPrefix ); SNESSetFromOptions( snes ); SNESSolve( snes, PETSC_NULL, self->X ); } /* do this at end of solve step */ void SystemLinearEquations_NewtonFinalise( void* _context, void* data ) { FiniteElementContext* context = (FiniteElementContext*)_context; assert(0); // the following will need to be fixed to get the sle from elsewhere SystemLinearEquations* sle = (SystemLinearEquations*)context->slEquations->data[0]; SNES snes = sle->nlSolver; sle->_updateOldFields( &sle->X, context ); Stg_SNESDestroy(&snes ); } void SystemLinearEquations_NewtonMFFDExecute( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*) sle; Vec F; VecDuplicate( SystemLinearEquations_GetSolutionVectorAt( self, 0 )->vector, &F ); /* creates the nonlinear solver */ if( self->nlSolver != PETSC_NULL ) Stg_SNESDestroy(&self->nlSolver ); SNESCreate( self->comm, &self->nlSolver ); SNESSetFunction( self->nlSolver, F, self->_buildF, _context ); // set J (jacobian) // set F (residual vector) // call non linear solver func (SNES wrapper) } void SystemLinearEquations_NonLinearExecute( void* sle, void* _context ) { SystemLinearEquations* self = (SystemLinearEquations*) sle; Vec previousVector; Vec currentVector; double residual; double tolerance = self->nonLinearTolerance; Iteration_Index maxIterations = self->nonLinearMaxIterations; Bool converged; Stream* errorStream = Journal_Register( Error_Type, (Name)self->type ); double wallTime; Iteration_Index minIterations = self->nonLinearMinIterations; SLE_Solver* solver; PetscScalar currVecNorm, prevVecNorm; Journal_Printf( self->info, "In %s\n", __func__ ); Stream_IndentBranch( StgFEM_Debug ); wallTime = MPI_Wtime(); /* First Solve */ /* setting the nonlinear stuff */ //START OF NONLINEAR ITERATION!!!!! /* first get current timestep */ solver = self->solver; // assert(0); // THE FOLLOWING WILL NEED TO BE FIXED.. NOT SURE WHY THE SOLVER NEEDS THE CURRENT TIMESTEP // solver->currenttimestep = self->context->timeStep; /* if current timestep is not the same as previous timestep, then reset all variables back to zero and update previous timestep */ // if(solver->currenttimestep != solver->previoustimestep){ //update prev timestep solver->previoustimestep = solver->currenttimestep; solver->nonlinearitsinitialtime = 0; solver->nonlinearitsendtime = 0; solver->totalnonlinearitstime = 0; solver->totalnumnonlinearits = 0; solver->avgtimenonlinearits = 0; solver->inneritsinitialtime = 0; solver->outeritsinitialtime = 0; solver->inneritsendtime = 0; solver->outeritsendtime = 0; solver->totalinneritstime = 0; solver->totalouteritstime = 0; solver->totalnuminnerits = 0; solver->totalnumouterits = 0; solver->avgnuminnerits = 0; solver->avgnumouterits = 0; solver->avgtimeinnerits = 0; solver->avgtimeouterits = 0; // } self->nonLinearIteration_I = 0; Journal_Printf(self->info,"\nNon linear solver - iteration %d\n", self->nonLinearIteration_I); /* More of Luke's stuff. I need an entry point for a non-linear setup operation. */ _EntryPoint_Run_2VoidPtr( self->nlSetupEP, sle, _context ); /*Don't know if we should include this but the timing of the outer and inner iterations starts here so it makes sense to count this one? */ solver->nonlinearitsinitialtime = MPI_Wtime(); self->linearExecute( self, _context ); self->hasExecuted = True; solver->nonlinearitsendtime = MPI_Wtime(); solver->totalnonlinearitstime = solver->totalnonlinearitstime + (-solver->nonlinearitsinitialtime + solver->nonlinearitsendtime); /* reset initial time and end time for inner its back to 0 - probs don't need to do this but just in case */ solver->nonlinearitsinitialtime = 0; solver->nonlinearitsendtime = 0; /* ** Include an entry point to do some kind of post-non-linear-iteration operation. */ _EntryPoint_Run_2VoidPtr( self->postNlEP, sle, _context ); /* TODO - Give option which solution vector to test */ currentVector = SystemLinearEquations_GetSolutionVectorAt( self, 0 )->vector; VecDuplicate( currentVector, &previousVector ); for ( self->nonLinearIteration_I = 1 ; self->nonLinearIteration_I < maxIterations ; self->nonLinearIteration_I++ ) { /* get initial wall time for nonlinear loop */ solver->nonlinearitsinitialtime = MPI_Wtime(); /* ** BEGIN LUKE'S FRICTIONAL BCS BIT ** ** Adding an interface for allowing other components to add some form of non-linearity to the system. ** This is with a focus on frictional BCs, where we want to examine the stress field and modify ** traction BCs to enforce friction rules. - Luke 18/07/2007 */ _EntryPoint_Run_2VoidPtr( self->nlEP, sle, _context ); /* ** END LUKE'S FRICTIONAL BCS BIT */ //Vector_CopyEntries( currentVector, previousVector ); VecCopy( currentVector, previousVector ); Journal_Printf(self->info,"Non linear solver - iteration %d\n", self->nonLinearIteration_I); self->linearExecute( self, _context ); // PetscPrintf( PETSC_COMM_WORLD, "|Xn+1| = %12.12e \n", Vector_L2Norm(SystemLinearEquations_GetSolutionVectorAt(self,1)->vector) ); /* Calculate Residual */ VecAXPY( previousVector, -1.0, currentVector ); VecNorm( previousVector, NORM_2, &prevVecNorm ); VecNorm( currentVector, NORM_2, &currVecNorm ); residual = ((double)prevVecNorm) / ((double)currVecNorm); self->curResidual = residual; /* ** Include an entry point to do some kind of post-non-linear-iteration operation. */ _EntryPoint_Run_2VoidPtr( self->postNlEP, sle, _context ); Journal_Printf( self->info, "In func %s: Iteration %u of %u - Residual %.5g - Tolerance = %.5g\n", __func__, self->nonLinearIteration_I, maxIterations, residual, tolerance ); if ( self->context && self->makeConvergenceFile ) { Journal_Printf( self->convergenceStream, "%d\t\t%d\t\t%.5g\t\t%.5g\n", self->context->timeStep, self->nonLinearIteration_I, residual, tolerance ); } /* Check if residual is below tolerance */ converged = (residual < tolerance); Journal_Printf(self->info,"Non linear solver - Residual %.8e; Tolerance %.4e%s%s - %6.6e (secs)\n\n", residual, tolerance, (converged) ? " - Converged" : " - Not converged", (self->nonLinearIteration_I < maxIterations) ? "" : " - Reached iteration limit", MPI_Wtime() - wallTime ); //END OF NONLINEAR ITERATION LOOP!!! /* add the outer loop iterations to the total outer iterations */ solver->totalnumnonlinearits += 1; /*get wall time for end of outer loop*/ solver->nonlinearitsendtime = MPI_Wtime(); /* add time to total time inner its: */ solver->totalnonlinearitstime = solver->totalnonlinearitstime + (-solver->nonlinearitsinitialtime + solver->nonlinearitsendtime); //printf("totalnumnonlinearits before converging is %d totalnonlinearitstime is %g, totalouteritstime is %g and totalinneritstime is %g\n",solver->totalnumnonlinearits,solver->totalnonlinearitstime,solver->totalouteritstime,solver->totalinneritstime); /* reset initial time and end time for inner its back to 0 - probs don't need to do this but just in case */ solver->nonlinearitsinitialtime = 0; solver->nonlinearitsendtime = 0; if ( (converged) && (self->nonLinearIteration_I>=minIterations) ) { int result, ierr; /* Adding in another entry point so we can insert out own custom convergeance checks. For example, with frictional boundary conditions we need to ensure envery node was gone from the original searching state to a fixed slipping or sticking state. */ _EntryPoint_Run_2VoidPtr( self->nlConvergedEP, _context, &converged ); ierr = MPI_Allreduce( &converged, &result, 1, MPI_INT, MPI_LOR, MPI_COMM_WORLD ); if( result ) break; } } /* Print Info */ if ( converged ) { Journal_Printf( self->info, "In func %s: Converged after %u iterations.\n", __func__, self->nonLinearIteration_I ); } else { Journal_Printf( errorStream, "In func %s: Failed to converge after %u iterations.\n", __func__, self->nonLinearIteration_I); if ( self->killNonConvergent ) { abort(); } } Stream_UnIndentBranch( StgFEM_Debug ); Stg_VecDestroy(&previousVector ); /*Set all the printout variables */ if( solver->totalnumnonlinearits ) { solver->avgtimenonlinearits = (solver->totalnonlinearitstime - solver->totalouteritstime)/solver->totalnumnonlinearits; solver->avgnumouterits = solver->totalnumouterits/solver->totalnumnonlinearits; } if( solver->totalnumouterits ) { solver->avgnuminnerits = solver->totalnuminnerits/solver->totalnumouterits; solver->avgtimeouterits = (solver->totalouteritstime - solver->totalinneritstime)/solver->totalnumouterits; } if( solver->totalnuminnerits ) solver->avgtimeinnerits = solver->totalinneritstime/solver->totalnuminnerits; //printf("totalnumnonlinearits = %d, avgnumouterits %d, avgnuminnerits %d\n",solver->totalnumnonlinearits, solver->avgnumouterits, solver->avgnuminnerits); } void SystemLinearEquations_AddNonLinearSetupEP( void* sle, const char* name, EntryPoint_2VoidPtr_Cast func ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; SystemLinearEquations_SetToNonLinear( self, True ); EntryPoint_Append( self->nlSetupEP, (char*)name, func, self->type ); } void SystemLinearEquations_AddPostNonLinearEP( void* sle, const char* name, EntryPoint_2VoidPtr_Cast func ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; EntryPoint_Append( self->postNlEP, (char*)name, func, self->type ); } void SystemLinearEquations_AddNonLinearConvergedEP( void* sle, const char* name, EntryPoint_2VoidPtr_Cast func ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; SystemLinearEquations_SetToNonLinear( self, True ); EntryPoint_Append( self->nlConvergedEP, (char*)name, func, self->type ); } /* Computes F1 := A(x) x -b = -r, where r = b - A(x) x */ //void SystemLinearEquations_SNESPicardFormalResidual( void *someSLE, Vector *stg_X, Vector *stg_F, void *_context ) void SystemLinearEquations_SNESPicardFormalResidual( void *someSLE, Vec X, Vec F, void *_context ) { SystemLinearEquations *sle = (SystemLinearEquations*)someSLE; SLE_Solver *solver = (SLE_Solver*)sle->solver; abort(); solver->_formResidual( (void*)sle, (void*)solver, F ); } /* Computes F2 := x - A(x)^{-1} b */ #if 0 void SystemLinearEquations_SNESPicardKSPResidual( void *someSLE, Vector *stg_X, Vector *stg_F, void *_context ) { SystemLinearEquations *sle = (SystemLinearEquations*)someSLE; SLE_Solver *solver = (SLE_Solver*)sle->solver; Vec F,X,Xcopy; PetscReal norm; F = StgVectorGetPetscVec( stg_F ); X = StgVectorGetPetscVec( stg_X ); VecDuplicate( X, &Xcopy ); VecCopy( X, Xcopy ); VecCopy( X, F ); /* F <- X */ // VecNorm( X, NORM_2, &norm ); // PetscPrintf(PETSC_COMM_WORLD," |X|_pre = %5.5e \n", norm ); sle->linearExecute( sle, _context ); /* X = A^{-1} b */ X = StgVectorGetPetscVec( stg_X ); // VecNorm( X, NORM_2, &norm ); // PetscPrintf(PETSC_COMM_WORLD," |X|_post = %5.5e \n", norm ); VecAXPY( F, -1.0, X ); /* F <- X - F */ // VecNorm( F, NORM_2, &norm ); // PetscPrintf(PETSC_COMM_WORLD," |F|_post = %5.5e \n", norm ); VecCopy( Xcopy, X ); Stg_VecDestroy(&Xcopy ); } #endif /* stg_X must not get modified by this function !! */ void SystemLinearEquations_SNESPicardKSPResidual( void *someSLE, Vec X, Vec F, void *_context ) { SystemLinearEquations *sle = (SystemLinearEquations*)someSLE; SLE_Solver *solver = (SLE_Solver*)sle->solver; Vec Xstar; PetscReal norm,norms; solver->_getSolution( sle, solver, &Xstar ); /* Map most current solution into stg object, vec->mesh */ VecCopy( X, Xstar ); /* X* <- X */ /* Map onto nodes */ SystemLinearEquations_UpdateSolutionOntoNodes( someSLE, _context ); VecNorm( X, NORM_2, &norm ); VecNorm( Xstar, NORM_2, &norms ); // PetscPrintf(PETSC_COMM_WORLD," |X| = %12.12e : |x*| = %12.12e <pre>\n", norm, norms ); sle->linearExecute( sle, _context ); /* X* = A^{-1} b */ VecNorm( X, NORM_2, &norm ); VecNorm( Xstar, NORM_2, &norms ); // PetscPrintf(PETSC_COMM_WORLD," |X| = %12.12e : |x*| = %12.12e <post> \n", norm, norms ); VecWAXPY( F, -1.0, Xstar, X ); /* F = -X* + X */ } PetscErrorCode SLEComputeFunction( void *someSLE, Vec X, Vec F, void *_context ) { SystemLinearEquations *sle = (SystemLinearEquations*)someSLE; if (sle->_sleFormFunction!=NULL) { sle->_sleFormFunction( sle, X, F, _context ); } else { Stg_SETERRQ( PETSC_ERR_SUP, "SLEComputeFunction in not valid" ); } } void SLE_SNESMonitor( void *sle, PetscInt iter, PetscReal fnorm ) { PetscPrintf( PETSC_COMM_WORLD, " %.4d SLE_NS Function norm %12.12e --------------------------------------------------------------------------------\n", iter, fnorm ); } void SLE_SNESMonitor2( void *sle, PetscInt iter, PetscReal fnorm0, PetscReal fnorm, PetscReal dX, PetscReal X1 ) { if(iter==0) { PetscPrintf( PETSC_COMM_WORLD, " SLE_NS it |F| |F|/|F0| |X1-X0| |X1-X0|/|X1| \n" ); } PetscPrintf( PETSC_COMM_WORLD, " SLE_NS %1.4d %2.4e %2.4e %2.4e %2.4e \n", iter, fnorm, fnorm/fnorm0, dX, dX/X1 ); } void _monitor_progress( PetscReal initial, PetscReal target, PetscReal current, PetscReal *p ) { PetscReal p0; p0 = log10(initial) - log10(target); *p = 100.0 * ( 1.0 - (log10(current)-log10(target)) / p0 ); } void SLE_SNESMonitorProgress( void *sle, PetscInt iter, PetscReal fnorm0, PetscReal fnorm, PetscReal dX, PetscReal X1, PetscReal fatol, PetscReal frtol, PetscReal stol ) { PetscReal f_abs_s, f_abs_e, v1, p1; PetscReal f_rel_s, f_rel_e, v2, p2; PetscReal x_del_s, x_del_e, v3, p3; if(iter==0) { PetscPrintf( PETSC_COMM_WORLD, " SLE_NS it |F| |F|/|F0| |X1-X0|/|X1| \n" ); } f_abs_s = fnorm0; f_abs_e = fatol; v1 = fnorm; _monitor_progress( f_abs_s, f_abs_e, v1, &p1 ); f_rel_s = fnorm0; f_rel_e = fnorm0 * frtol; v2 = fnorm; _monitor_progress( f_rel_s, f_rel_e, v2, &p2 ); x_del_s = 1.0; x_del_e = stol; v3 = dX/X1; _monitor_progress( x_del_s, x_del_e, v3, &p3 ); PetscPrintf( PETSC_COMM_WORLD, " SLE_NS %1.4d %2.4e [%2.0f%%] %2.4e [%2.0f%%] %2.4e [%2.0f%%] \n", iter, fnorm,p1, fnorm/fnorm0,p2, dX/X1,p3 ); } void SLE_SNESConverged( PetscReal snes_abstol, PetscReal snes_rtol, PetscReal snes_ttol, PetscReal snes_stol, PetscInt it,PetscReal xnorm,PetscReal pnorm,PetscReal fnorm,SNESConvergedReason *reason ) { /* PetscErrorCode ierr; */ *reason = SNES_CONVERGED_ITERATING; if (!it) { /* set parameter for default relative tolerance convergence test */ snes_ttol = fnorm*snes_rtol; } if (fnorm != fnorm) { // ierr = PetscInfo(snes,"Failed to converged, function norm is NaN\n");CHKERRQ(ierr); *reason = SNES_DIVERGED_FNORM_NAN; } else if (fnorm < snes_abstol) { // ierr = PetscInfo2(snes,"Converged due to function norm %G < %G\n",fnorm,snes_abstol);CHKERRQ(ierr); *reason = SNES_CONVERGED_FNORM_ABS; } // } else if (snes->nfuncs >= snes->max_funcs) { // ierr = PetscInfo2(snes,"Exceeded maximum number of function evaluations: %D > %D\n",snes->nfuncs,snes->max_funcs);CHKERRQ(ierr); // *reason = SNES_DIVERGED_FUNCTION_COUNT; // } if (it && !*reason) { if (fnorm <= snes_ttol) { // ierr = PetscInfo2(snes,"Converged due to function norm %G < %G (relative tolerance)\n",fnorm,snes_ttol);CHKERRQ(ierr); *reason = SNES_CONVERGED_FNORM_RELATIVE; } else if (pnorm < snes_stol*xnorm) { // ierr = PetscInfo3(snes,"Converged due to small update length: %G < %G * %G\n",pnorm,snes_stol,xnorm);CHKERRQ(ierr); #if( (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR <= 2) || PETSC_VERSION_MAJOR<3 ) *reason = SNES_CONVERGED_PNORM_RELATIVE; #else *reason = SNES_CONVERGED_SNORM_RELATIVE; #endif } } } #if defined(PETSC_HAVE_ISINF) && defined(PETSC_HAVE_ISNAN) #define PetscIsInfOrNanScalar(a) (isinf(PetscAbsScalar(a)) || isnan(PetscAbsScalar(a))) #define PetscIsInfOrNanReal(a) (isinf(a) || isnan(a)) #elif defined(PETSC_HAVE__FINITE) && defined(PETSC_HAVE__ISNAN) #if defined(PETSC_HAVE_FLOAT_H) #include "float.h" /* windows defines _finite() in float.h */ #endif #define PetscIsInfOrNanScalar(a) (!_finite(PetscAbsScalar(a)) || _isnan(PetscAbsScalar(a))) #define PetscIsInfOrNanReal(a) (!_finite(a) || _isnan(a)) #else #define PetscIsInfOrNanScalar(a) ((a - a) != 0.0) #define PetscIsInfOrNanReal(a) ((a - a) != 0.0) #endif /* This will be replaced by SNESPicard in petsc 2.4.0. */ PetscErrorCode SystemLinearEquations_PicardExecute( void *sle, void *_context ) { SystemLinearEquations *self = (SystemLinearEquations*)sle; SLE_Solver *solver = (SLE_Solver*)self->solver; Vec X, Y, F, Xstar,delta_X; PetscReal alpha = 1.0; PetscReal fnorm,norm_X,pnorm,fnorm0; PetscInt i; PetscErrorCode ierr; SNESConvergedReason snes_reason; PetscReal snes_norm; PetscInt snes_iter; PetscReal snes_ttol, snes_rtol, snes_abstol, snes_stol; PetscInt snes_maxits; PetscTruth monitor_flg; /* setup temporary some vectors */ solver->_getSolution( self, solver, &Xstar ); VecDuplicate( Xstar, &X ); VecDuplicate( X, &F ); VecDuplicate( F, &Y ); VecDuplicate( F, &delta_X ); /* Get some values from dictionary */ snes_maxits = (PetscInt)self->nonLinearMaxIterations; snes_ttol = 0.0; snes_rtol = (PetscReal)self->rtol; snes_abstol = (PetscReal)self->abstol; snes_stol = (PetscReal)self->stol; monitor_flg = PETSC_FALSE; if (self->picard_monitor==True) { monitor_flg = PETSC_TRUE; } alpha = (PetscReal)self->alpha; snes_reason = SNES_CONVERGED_ITERATING; /* Map X <- X* */ VecCopy( Xstar, X ); // Vector_CopyEntries( currentVector, previousVector ); /* Get an initial guess if |X| ~ 0, by solving the linear problem */ VecNorm( X, NORM_2, &norm_X ); if (norm_X <1.0e-20) { if (monitor_flg==PETSC_TRUE) PetscPrintf( PETSC_COMM_WORLD, "SLE_Picard: Computing an initial guess for X from the linear problem\n"); self->linearExecute( sle, _context ); /* X* = A^{-1} b */ self->hasExecuted = True; /* Map X <- X* */ VecCopy( Xstar, X ); VecNorm( X, NORM_2, &norm_X ); } snes_iter = 0; snes_norm = 0; SLEComputeFunction( sle, X, F, _context ); ierr = VecNorm(F, NORM_2, &fnorm); CHKERRQ(ierr); /* fnorm <- ||F|| */ fnorm0 = fnorm; if( PetscIsInfOrNanReal(fnorm) ) Stg_SETERRQ(PETSC_ERR_FP,"Infinite or not-a-number generated in norm"); snes_norm = fnorm; if(monitor_flg==PETSC_TRUE) { /* SLE_SNESMonitor(sle,0,fnorm); */ /* SLE_SNESMonitor2(sle,0,fnorm0,fnorm, norm_X, norm_X ); */ SLE_SNESMonitorProgress( sle, snes_iter, fnorm0, fnorm, norm_X, norm_X, snes_abstol, snes_rtol, snes_stol ); } /* set parameter for default relative tolerance convergence test */ snes_ttol = fnorm*snes_rtol; /* test convergence */ SLE_SNESConverged( snes_abstol,snes_rtol,snes_ttol,snes_stol , 0,norm_X,0.0,fnorm,&snes_reason); if (snes_reason) return NULL; for(i = 0; i < snes_maxits; i++) { /* Update guess Y = X^n - F(X^n) */ ierr = VecWAXPY(Y, -1.0, F, X); CHKERRQ(ierr); VecCopy( X, delta_X ); /* delta_X <- X */ /* X^{n+1} = (1 - \alpha) X^n + alpha Y */ ierr = VecAXPBY(X, alpha, 1 - alpha, Y); CHKERRQ(ierr); VecNorm( X, NORM_2, &norm_X ); VecAYPX( delta_X, -1.0, X ); /* delta_X <- Xn+1 - delta_X */ VecNorm( delta_X, NORM_2, &pnorm ); /* Compute F(X^{new}) */ SLEComputeFunction( sle, X, F, _context ); ierr = VecNorm(F, NORM_2, &fnorm); CHKERRQ(ierr); if( PetscIsInfOrNanReal(fnorm) ) Stg_SETERRQ(PETSC_ERR_FP,"Infinite or not-a-number generated norm"); /* Monitor convergence */ snes_iter = i+1; snes_norm = fnorm; if (monitor_flg==PETSC_TRUE) { /* SLE_SNESMonitor(sle,snes_iter,snes_norm); */ /* SLE_SNESMonitor2(sle,snes_iter,fnorm0,fnorm, pnorm, norm_X ); */ SLE_SNESMonitorProgress( sle, snes_iter, fnorm0, fnorm, pnorm, norm_X, snes_abstol, snes_rtol, snes_stol ); } /* Test for convergence */ SLE_SNESConverged( snes_abstol,snes_rtol,snes_ttol,snes_stol , snes_iter,norm_X,pnorm,fnorm,&snes_reason); if (snes_reason) break; } if (i == snes_maxits) { if (!snes_reason) snes_reason = SNES_DIVERGED_MAX_IT; } /* If monitoring, report reason converged */ if (monitor_flg==PETSC_TRUE) PetscPrintf( PETSC_COMM_WORLD, "Nonlinear solve converged due to %s \n", SNESConvergedReasons[snes_reason] ); Stg_VecDestroy(&X ); Stg_VecDestroy(&F ); Stg_VecDestroy(&Y ); Stg_VecDestroy(&delta_X ); return NULL; } /* ////////////// */ void SystemLinearEquations_AddNonLinearEP( void* sle, const char* name, EntryPoint_2VoidPtr_Cast func ) { SystemLinearEquations* self = (SystemLinearEquations*)sle; SystemLinearEquations_SetToNonLinear( self, True ); EntryPoint_Append( self->nlEP, (char*)name, func, self->type ); } void SystemLinearEquations_SetNonLinearTolerance( void* sle, double tol ){ SystemLinearEquations* self = (SystemLinearEquations*) sle; self->nonLinearTolerance = tol; // SystemLinearEquations_SetToNonLinear( self, True ); } void SystemLinearEquations_SetToNonLinear( void* sle, Bool isNonLinear ) { SystemLinearEquations* self = (SystemLinearEquations*) sle; Hook* nonLinearInitHook = NULL; Hook* nonLinearFinaliseHook = NULL; FiniteElementContext* context = NULL; if (isNonLinear) { if ( self->isNonLinear ) return; self->isNonLinear = True; self->linearExecute = self->_execute; self->_execute = SystemLinearEquations_NonLinearExecute; if( self->nonLinearSolutionType ) { if( !strcmp( self->nonLinearSolutionType, "default" ) ) { self->_execute = SystemLinearEquations_NonLinearExecute; } if( !strcmp( self->nonLinearSolutionType, "MatrixFreeNewton" ) ) self->_execute = SystemLinearEquations_NewtonMFFDExecute; if( !strcmp( self->nonLinearSolutionType, "Newton" ) ) { assert(0); // the following will need to be fixed cos no context context = self->context; nonLinearInitHook = Hook_New( "NewtonInitialise", SystemLinearEquations_NewtonInitialise, self->name ); _EntryPoint_PrependHook_AlwaysFirst( Context_GetEntryPoint( context, AbstractContext_EP_Solve ), nonLinearInitHook ); nonLinearFinaliseHook = Hook_New( "NewtonFinalise", SystemLinearEquations_NewtonFinalise, self->name ); _EntryPoint_AppendHook_AlwaysLast( Context_GetEntryPoint( context, AbstractContext_EP_Solve ), nonLinearFinaliseHook ); self->_execute = SystemLinearEquations_NewtonExecute; } if (!strcmp( self->nonLinearSolutionType, "Picard") ) { /* set function pointer for execute */ self->_execute = SystemLinearEquations_PicardExecute; /* set form function */ if (!strcmp(self->picard_form_function_type,"PicardFormFunction_KSPResidual") ) { self->_sleFormFunction = SystemLinearEquations_SNESPicardKSPResidual; } else if (!strcmp(self->picard_form_function_type,"PicardFormFunction_FormalResidual") ) { self->_sleFormFunction = SystemLinearEquations_SNESPicardFormalResidual; } else { Stream *errorStream = Journal_Register( Error_Type, (Name)self->type ); Journal_Printf( errorStream, "Unknown the Picard FormFunction type %s is unrecognised. .\n", self->picard_form_function_type ); Journal_Printf( errorStream, "Supported types include <PicardFormFunction_FormalResidual, PicardFormFunction_KSPResidual> \n" ); abort(); } } } } else { self->isNonLinear = False; self->linearExecute = _SystemLinearEquations_Execute; self->_execute = _SystemLinearEquations_Execute; } } void SystemLinearEquations_CheckIfNonLinear( void* sle ) { SystemLinearEquations* self = (SystemLinearEquations*) sle; Index index; for ( index = 0; index < self->stiffnessMatrices->count; index++ ) { StiffnessMatrix* stiffnessMatrix = SystemLinearEquations_GetStiffnessMatrixAt( self, index ); if ( stiffnessMatrix->isNonLinear ) SystemLinearEquations_SetToNonLinear( self, True ); /* TODO CHECK FOR FORCE VECTORS */ } } /* ** All the MG functions and their general implementations. */ void SystemLinearEquations_MG_Enable( void* _sle ) { SystemLinearEquations* self = (SystemLinearEquations*)_sle; if( !self->isBuilt ) { Journal_Printf(self->info, "Warning: SLE has not been built, can't enable multi-grid.\n" ); return; } self->mgEnabled = True; } void SystemLinearEquations_MG_SelectStiffMats( void* _sle, unsigned* nSMs, StiffnessMatrix*** sms ) { SystemLinearEquations* self = (SystemLinearEquations*)_sle; assert( self->_mgSelectStiffMats ); self->_mgSelectStiffMats( self, nSMs, sms ); } void _SystemLinearEquations_MG_SelectStiffMats( void* _sle, unsigned* nSMs, StiffnessMatrix*** sms ) { SystemLinearEquations* self = (SystemLinearEquations*)_sle; /* ** As we have nothing else to go on, attempt to apply MG to all stiffness matrices in the list. */ { unsigned sm_i; *nSMs = 0; for( sm_i = 0; sm_i < self->stiffnessMatrices->count; sm_i++ ) { StiffnessMatrix* sm = ((StiffnessMatrix**)self->stiffnessMatrices->data)[sm_i]; /* Add this one to the list. */ *sms = Memory_Realloc_Array( *sms, StiffnessMatrix*, (*nSMs) + 1 ); (*sms)[*nSMs] = sm; (*nSMs)++; } } } void SystemLinearEquations_SetCustomRunPoint( void* sle, void* _context, const Name entryPointName ){ SystemLinearEquations* self = (SystemLinearEquations*)sle; /** set this flag to ensure we now do not run during the execute phase */ self->runatExecutePhase = False; assert(0); // the following will need to be fixed or deprecated EP_AppendClassHook( Context_GetEntryPoint( _context, entryPointName ), _SystemLinearEquations_RunEP, sle ); } SystemLinearEquations_RunEPFunction* SystemLinearEquations_GetRunEPFunction(){ return _SystemLinearEquations_RunEP; } void SystemLinearEquations_SetRunDuringExecutePhase( void* sle, Bool setRunDuringExectutePhase ){ SystemLinearEquations* self = (SystemLinearEquations*)sle; self->runatExecutePhase = setRunDuringExectutePhase; }
{ "alphanum_fraction": 0.6690090275, "avg_line_length": 39.978127136, "ext": "c", "hexsha": "ed6b17405b23e2d7fbbc031b072d95c1916a02b9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_path": "underworld/libUnderworld/StgFEM/SLE/SystemSetup/src/SystemLinearEquations.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_path": "underworld/libUnderworld/StgFEM/SLE/SystemSetup/src/SystemLinearEquations.c", "max_line_length": 260, "max_stars_count": null, "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_path": "underworld/libUnderworld/StgFEM/SLE/SystemSetup/src/SystemLinearEquations.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 15886, "size": 58488 }
#pragma once #include "Common.h" #include "PEFile.h" #include "ImportedModule.h" #include <gsl/gsl> namespace winlogo::pe_parser { namespace details { /** * This is an input iterator for iterating over the imported modules of an import directory. */ class ImportDirectoryIterator { public: ImportDirectoryIterator(PEFile file, gsl::span<IMAGE_IMPORT_DESCRIPTOR>::iterator iterator); bool operator==(const ImportDirectoryIterator& other) const noexcept; bool operator!=(const ImportDirectoryIterator& other) const noexcept; ImportedModule operator*() const noexcept; ImportDirectoryIterator& operator++() noexcept; private: PEFile m_peFile; gsl::span<IMAGE_IMPORT_DESCRIPTOR>::iterator m_current; }; } // namespace details /** * This class represents an iterable view of a PE file's import directory. */ class ImportDirectory { public: /** * Initialize the import directory from its PE file. */ explicit ImportDirectory(PEFile peFile); /** * Get the raw import descriptors. */ gsl::span<IMAGE_IMPORT_DESCRIPTOR> rawImportDescriptors() const noexcept; // Iterators for iterating over the imported modules. details::ImportDirectoryIterator begin() const noexcept; details::ImportDirectoryIterator end() const noexcept; private: /// The owning PE file. PEFile m_peFile; gsl::span<IMAGE_IMPORT_DESCRIPTOR> m_importDescriptors; }; } // namespace winlogo::pe_parser
{ "alphanum_fraction": 0.7300613497, "avg_line_length": 24.8644067797, "ext": "h", "hexsha": "5fadf567123d447335f8475a381843bafc4770d1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-11-20T12:06:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-20T12:06:02.000Z", "max_forks_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "shsh999/WinLogo", "max_forks_repo_path": "winlogo_core/ImportDirectory.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_issues_repo_issues_event_max_datetime": "2021-12-29T12:13:05.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-23T01:01:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "shsh999/WinLogo", "max_issues_repo_path": "winlogo_core/ImportDirectory.h", "max_line_length": 96, "max_stars_count": 12, "max_stars_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "shsh999/WinLogo", "max_stars_repo_path": "winlogo_core/ImportDirectory.h", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:18:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-04T22:10:13.000Z", "num_tokens": 309, "size": 1467 }
#include <jni.h> #include <assert.h> #include <lapacke.h> JNIEXPORT jint Java_JAMAJni_SingularValueDecomposition_dgesvd (JNIEnv *env, jclass klass, jint matrix_layout, jchar jobu, jchar jobvt, jint m, jint n, jdoubleArray a, jint lda, jdoubleArray s, jdoubleArray u, jint ldu, jdoubleArray vt, jint ldvt, jdoubleArray superb){ //superb contains the unconverged superdiagonal elements of an upper bidiagonal matrix B whose diagonal is in S (not necessarily sorted). double *aElems, *sElems, *uElems, *vtElems, *superbElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); sElems = (*env)-> GetDoubleArrayElements (env, s, NULL); uElems = (*env)-> GetDoubleArrayElements (env, u, NULL); vtElems = (*env)-> GetDoubleArrayElements (env, vt, NULL); superbElems = (*env)-> GetDoubleArrayElements (env, superb, NULL); assert(aElems && sElems && uElems && vtElems && superbElems); info = LAPACKE_dgesvd((int) matrix_layout, (char) jobu, (char) jobvt, (lapack_int) m, (lapack_int) n, aElems, (lapack_int) lda, sElems, uElems, (lapack_int) ldu, vtElems, (lapack_int) ldvt, superbElems); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, s, sElems, 0); (*env)-> ReleaseDoubleArrayElements (env, u, uElems, 0); (*env)-> ReleaseDoubleArrayElements (env, vt, vtElems, 0); (*env)-> ReleaseDoubleArrayElements (env, superb, superbElems, 0); return info; } JNIEXPORT jint Java_JAMAJni_SingularValueDecomposition_dgesdd (JNIEnv *env, jclass klass, jint matrix_layout, jchar jobz, jint m, jint n, jdoubleArray a, jint lda, jdoubleArray s, jdoubleArray u, jint ldu, jdoubleArray vt, jint ldvt){ double *aElems, *sElems, *uElems, *vtElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); sElems = (*env)-> GetDoubleArrayElements (env, s, NULL); uElems = (*env)-> GetDoubleArrayElements (env, u, NULL); vtElems = (*env)-> GetDoubleArrayElements (env, vt, NULL); assert(aElems && sElems && uElems && vtElems); info = LAPACKE_dgesdd((int) matrix_layout, (char) jobz, (lapack_int) m, (lapack_int) n, aElems, (lapack_int) lda, sElems, uElems, (lapack_int) ldu, vtElems, (lapack_int) ldvt); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, s, sElems, 0); (*env)-> ReleaseDoubleArrayElements (env, u, uElems, 0); (*env)-> ReleaseDoubleArrayElements (env, vt, vtElems, 0); return info; } JNIEXPORT jint Java_JAMAJni_SingularValueDecomposition_dgeev (JNIEnv *env, jclass klass, jint matrix_layout, jchar jobvl, jchar jobvr, jint n, jdoubleArray a, jint lda, jdoubleArray wr, jdoubleArray wi, jdoubleArray vl, jint ldvl, jdoubleArray vr, jint ldvr){ double *aElems, *wrElems, *wiElems, *vlElems, *vrElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); wrElems = (*env)-> GetDoubleArrayElements (env, wr, NULL); wiElems = (*env)-> GetDoubleArrayElements (env, wi, NULL); vlElems = (*env)-> GetDoubleArrayElements (env, vl, NULL); vrElems = (*env)-> GetDoubleArrayElements (env, vr, NULL); assert(aElems && wrElems && wiElems && vlElems && vrElems); info = LAPACKE_dgeev((int) matrix_layout, (char) jobvl, (char) jobvr, (lapack_int) n, aElems, (lapack_int) lda, wrElems, wiElems, vlElems, (lapack_int) ldvl, vrElems, (lapack_int) ldvr); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, vl, vlElems, 0); (*env)-> ReleaseDoubleArrayElements (env, vr, vrElems, 0); (*env)-> ReleaseDoubleArrayElements (env, wr, wrElems, 0); (*env)-> ReleaseDoubleArrayElements (env, wi, wiElems, 0); return info; }
{ "alphanum_fraction": 0.6786919284, "avg_line_length": 46.987804878, "ext": "c", "hexsha": "3293ac0a1caf786f80b70d3803fb01dd77fdf55b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_forks_repo_licenses": [ "AAL" ], "max_forks_repo_name": "dw6ja/JAMAJni", "max_forks_repo_path": "src/jni_lapacke/c/SingularValueDecomposition.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "AAL" ], "max_issues_repo_name": "dw6ja/JAMAJni", "max_issues_repo_path": "src/jni_lapacke/c/SingularValueDecomposition.c", "max_line_length": 268, "max_stars_count": null, "max_stars_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_stars_repo_licenses": [ "AAL" ], "max_stars_repo_name": "dw6ja/JAMAJni", "max_stars_repo_path": "src/jni_lapacke/c/SingularValueDecomposition.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1241, "size": 3853 }
/* * ctm-cvb * * CollapsedBayesEngine */ #ifndef COLLAPSED_BAYES_ENGINE_H #define COLLAPSED_BAYES_ENGINE_H #include "InferenceEngine.h" #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> namespace ctm { class CollapsedBayesEngine : public InferenceEngine { /*** * Model hyperparameters learnt by maximisation */ struct Model { gsl_vector* mu; gsl_matrix* cov; gsl_matrix* inv_cov; gsl_matrix* log_beta; double gamma; double log_det_inv_cov; Model( int D, int K, int V ); ~Model(); }; /*** * Data collected in the 'expectation' step, to be used in the * maximisation step. */ struct CollectedData { // Expected counts gsl_matrix* n_ij; gsl_matrix* n_jk; double ndata; CollectedData( int D, int K, int V ); ~CollectedData(); }; /*** * Variational parameters to be optimised in the expectation step */ struct Parameters { // Stores \phi_{*kj} gsl_matrix* phi; gsl_matrix* log_phi; // Likelihood saved for optimisation purposes double lhood; Parameters( int K, int V ); ~Parameters(); }; public: CollapsedBayesEngine(InferenceOptions& options); // Load/Store in a file virtual void init( string filename ); virtual void save( string filename ); // Parse a single file virtual double infer( Corpus& data ); virtual double infer( Corpus& data, CollectedData* cd ); virtual void estimate( Corpus& data ); protected: Model* model; }; }; #endif // COLLAPSED_BAYES_ENGINE_H
{ "alphanum_fraction": 0.5317377732, "avg_line_length": 22.3488372093, "ext": "h", "hexsha": "5d20207ddec0f0de7dd03ac8d1e3ed43fa12cb16", "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": "3e0fd5afe904b3e205ebfa422b6a1f677cee75c0", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "arunchaganty/ctm-cvb", "max_forks_repo_path": "include/CollapsedBayesEngine.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3e0fd5afe904b3e205ebfa422b6a1f677cee75c0", "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": "arunchaganty/ctm-cvb", "max_issues_repo_path": "include/CollapsedBayesEngine.h", "max_line_length": 73, "max_stars_count": 2, "max_stars_repo_head_hexsha": "3e0fd5afe904b3e205ebfa422b6a1f677cee75c0", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "arunchaganty/ctm-cvb", "max_stars_repo_path": "include/CollapsedBayesEngine.h", "max_stars_repo_stars_event_max_datetime": "2020-02-29T14:31:58.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-24T02:58:21.000Z", "num_tokens": 426, "size": 1922 }
/*************************************************************************** File : MatrixModel.h Project : QtiPlot -------------------------------------------------------------------- Copyright : (C) 2007 by Ion Vasilief Email (use @ for *) : ion_vasilief*yahoo.fr Description : QtiPlot's matrix model ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #ifndef MATRIXMODEL_H #define MATRIXMODEL_H #include <QAbstractTableModel> #include <QVector> #include <QLocale> #include <QSize> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.h> class Matrix; class MatrixModel : public QAbstractTableModel { Q_OBJECT public: MatrixModel(int rows = 32, int cols = 32, QObject *parent = 0); MatrixModel(const QImage& image, QObject *parent); ~MatrixModel(){free(d_data);}; Matrix *matrix(){return d_matrix;}; Qt::ItemFlags flags( const QModelIndex & index ) const; bool canResize(int rows, int cols); void setDimensions(int rows, int cols); int rowCount(const QModelIndex &parent = QModelIndex()) const; void setRowCount(int rows); int columnCount(const QModelIndex &parent = QModelIndex()) const; void setColumnCount(int cols); bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex()); bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex()); bool removeColumns(int column, int count, const QModelIndex & parent = QModelIndex()); bool insertColumns(int column, int count, const QModelIndex & parent = QModelIndex()); double x(int col) const; double y(int row) const; double cell(int row, int col); void setCell(int row, int col, double val); QString text(int row, int col); void setText(int row, int col, const QString&); QString saveToString(); QImage renderImage(); double data(int row, int col) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; bool setData(const QModelIndex & index, const QVariant & value, int role); double* dataVector(){return d_data;}; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; void setImage(const QImage& image); bool importASCII(const QString &fname, const QString &sep, int ignoredLines, bool stripSpaces, bool simplifySpaces, const QString& commentString, int importAs, const QLocale& locale, int endLineChar = 0, int maxRows = -1); void setLocale(const QLocale& locale){d_locale = locale;}; void setNumericFormat(char f, int prec); bool initWorkspace(); void invert(); void transpose(); void flipVertically(); void flipHorizontally(); void rotate90(bool clockwise); void fft(bool inverse); void clear(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1); bool calculate(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1); bool muParserCalculate(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1); double* dataCopy(int startRow = 0, int endRow = -1, int startCol = 0, int endCol = -1); void pasteData(double *clipboardBuffer, int topRow, int leftCol, int rows, int cols); private: void init(); int d_rows, d_cols; double *d_data; Matrix *d_matrix; //! Format code for displaying numbers char d_txt_format; //! Number of significant digits int d_num_precision; //! Locale used to display data QLocale d_locale; //! Pointers to GSL matrices used during inversion operations gsl_matrix *d_direct_matrix, *d_inv_matrix; //! Pointer to a GSL permutation used during inversion operations gsl_permutation *d_inv_perm; QSize d_data_block_size; }; #endif
{ "alphanum_fraction": 0.5803846154, "avg_line_length": 39.3939393939, "ext": "h", "hexsha": "863a1c48ac2d8fb418da3bbd2cca8170287bf090", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": [ "IJG" ], "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/matrix/MatrixModel.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_licenses": [ "IJG" ], "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/matrix/MatrixModel.h", "max_line_length": 101, "max_stars_count": 6, "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": [ "IJG" ], "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/matrix/MatrixModel.h", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "num_tokens": 1054, "size": 5200 }
/* Ballistic: a software to benchmark ballistic models. AUTHORS: Javier Burguete Tolosa. Copyright 2018, AUTHORS. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file runge-kutta.c * \brief Source file to define the Runge-Kutta method data and functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2018. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_rng.h> #include <libxml/parser.h> #include <glib.h> #include "config.h" #include "utils.h" #include "equation.h" #include "method.h" #include "runge-kutta.h" #define DEBUG_RUNGE_KUTTA 0 ///< macro to debug the Runge-Kutta functions. ///> 1st array of 1st order Runge-Kutta b coefficients. static const long double rk_b1_1[1] = { 1.L }; ///> matrix of 1st order Runge-Kutta b coefficients. static const long double *rk_b1[1] = { rk_b1_1 }; ///> array of 1st order Runge-Kutta t coefficients. static const long double rk_t1[1] = { 1.L }; ///> array of 1st order Runge-Kutta error coefficients. static const long double rk_e1[1] = { -1.L }; ///> 1st array of 1st order Runge-Kutta b coefficients. static const long double rk_b2_1[1] = { 1.L }; ///> 2nd array of 2nd order Runge-Kutta b coefficients. static const long double rk_b2_2[2] = { 0.5L, 0.5L }; ///> matrix of 2nd order Runge-Kutta b coefficients. static const long double *rk_b2[2] = { rk_b2_1, rk_b2_2 }; ///> array of 2nd order Runge-Kutta t coefficients. static const long double rk_t2[2] = { 1.L, 1.L }; ///> array of 2nd order Runge-Kutta error coefficients. static const long double rk_e2[2] = { 0.5L, -0.5L }; ///> 1st array of 3rd order Runge-Kutta b coefficients. static const long double rk_b3_1[1] = { 1.L }; ///> 2nd array of 3rd order Runge-Kutta b coefficients. static const long double rk_b3_2[2] = { 0.25L, 0.25L }; ///> 3rd array of 3rd order Runge-Kutta b coefficients. static const long double rk_b3_3[3] = { 1.L / 6.L, 1.L / 6.L, 2.L / 3.L }; ///> matrix of 3rd order Runge-Kutta b coefficients. static const long double *rk_b3[3] = { rk_b3_1, rk_b3_2, rk_b3_3 }; ///> array of 3rd order Runge-Kutta t coefficients. static const long double rk_t3[3] = { 1.L, 0.5L, 1.L }; ///> array of 3rd order Runge-Kutta error coefficients. static const long double rk_e3[3] = { 1.L / 12.L, 1.L / 12.L, -1.L / 6.L }; ///> 1st array of 4th order Runge-Kutta b coefficients. static const long double rk_b4_1[1] = { 0.5L }; ///> 2nd array of 4th order Runge-Kutta b coefficients. static const long double rk_b4_2[2] = { 0.L, 0.5L }; ///> 3rd array of 4th order Runge-Kutta b coefficients. static const long double rk_b4_3[3] = { 0.L, 0.L, 1.L }; ///> 4th array of 4th order Runge-Kutta b coefficients. static const long double rk_b4_4[4] = { 1.L / 6.L, 1.L / 3.L, 1.L / 3.L, 1.L / 6.L }; ///> matrix of 4th order Runge-Kutta b coefficients. static const long double *rk_b4[4] = { rk_b4_1, rk_b4_2, rk_b4_3, rk_b4_4 }; ///> array of 4th order Runge-Kutta t coefficients. static const long double rk_t4[4] = { 0.5L, 0.5L, 1.L, 1.L }; /** * Function to init the coefficients of the 1st order Runge-Kutta method. */ static inline void runge_kutta_init_1 (RungeKutta * rk) ///< RungeKutta struct. { #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_1: start\n"); #endif method_init (RUNGE_KUTTA_METHOD (rk), 1, 1); rk->b = rk_b1; rk->t = rk_t1; rk->e = rk_e1; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_1: end\n"); #endif } /** * Function to init the coefficients of the 2nd order Runge-Kutta method. */ static inline void runge_kutta_init_2 (RungeKutta * rk) ///< RungeKutta struct. { #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_2: start\n"); #endif method_init (RUNGE_KUTTA_METHOD (rk), 2, 2); rk->b = rk_b2; rk->t = rk_t2; rk->e = rk_e2; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_2: end\n"); #endif } /** * Function to init the coefficients of the 3rd order Runge-Kutta method. */ static inline void runge_kutta_init_3 (RungeKutta * rk) ///< RungeKutta struct. { #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_3: start\n"); #endif method_init (RUNGE_KUTTA_METHOD (rk), 3, 3); rk->b = rk_b3; rk->t = rk_t3; rk->e = rk_e3; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_3: end\n"); #endif } /** * Function to init the coefficients of the 4th order Runge-Kutta method. */ static inline void runge_kutta_init_4 (RungeKutta * rk) ///< RungeKutta struct. { #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_4: start\n"); #endif method_init (RUNGE_KUTTA_METHOD (rk), 4, 4); rk->b = rk_b4; rk->t = rk_t4; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_4: end\n"); #endif } /** * Function to init the variables used by the Runge-Kutta methods. */ void runge_kutta_init_variables (RungeKutta * rk) { Method *m; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_variables: start\n"); #endif m = RUNGE_KUTTA_METHOD (rk); m->nsteps = 1; method_init_variables (m); #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_init_variables: end\n"); #endif } /** * Function to perform a step of the Runge-Kutta method. */ void runge_kutta_step (RungeKutta * rk, ///< RungeKutta struct. Equation * eq, ///< Equation struct. long double t, ///< current time. long double dt) ///< time step size. { Method *m; const long double *b; unsigned int i, j, n; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_step: start\n"); fprintf (stderr, "runge_kutta_step: t=%Lg dt=%Lg\n", t, dt); #endif m = RUNGE_KUTTA_METHOD (rk); memcpy (m->r0[0], r0, 3 * sizeof (long double)); memcpy (m->r1[0], r1, 3 * sizeof (long double)); memcpy (m->r2[0], r2, 3 * sizeof (long double)); #if DEBUG_RUNGE_KUTTA for (i = 0; i < 3; ++i) fprintf (stderr, "runge_kutta_step: r0[0][%u]=%Lg\n", i, m->r0[0][i]); for (i = 0; i < 3; ++i) fprintf (stderr, "runge_kutta_step: r1[0][%u]=%Lg\n", i, m->r1[0][i]); #endif n = m->nsteps; for (i = 1; i <= n; ++i) { b = rk->b[i - 1]; #if DEBUG_RUNGE_KUTTA for (j = 0; j < i; ++j) fprintf (stderr, "runge_kutta_step: b%u-%u=%Lg\n", i, j, b[j]); #endif memcpy (m->r0[i], r0, 3 * sizeof (long double)); memcpy (m->r1[i], r1, 3 * sizeof (long double)); for (j = 0; j < i; ++j) { m->r0[i][0] += dt * b[j] * m->r1[j][0]; m->r0[i][1] += dt * b[j] * m->r1[j][1]; m->r0[i][2] += dt * b[j] * m->r1[j][2]; m->r1[i][0] += dt * b[j] * m->r2[j][0]; m->r1[i][1] += dt * b[j] * m->r2[j][1]; m->r1[i][2] += dt * b[j] * m->r2[j][2]; } equation_acceleration (eq, m->r0[i], m->r1[i], m->r2[i], t + rk->t[i - 1] * dt); #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_step: t%u=%Lg\n", i, rk->t[i - 1]); #endif } --i; memcpy (r0, m->r0[i], 3 * sizeof (long double)); memcpy (r1, m->r1[i], 3 * sizeof (long double)); memcpy (r2, m->r2[i], 3 * sizeof (long double)); #if DEBUG_RUNGE_KUTTA for (i = 0; i < 3; ++i) fprintf (stderr, "runge_kutta_step: r0[0][%u]=%Lg\n", i, r0[i]); for (i = 0; i < 3; ++i) fprintf (stderr, "runge_kutta_step: r1[0][%u]=%Lg\n", i, r1[i]); fprintf (stderr, "runge_kutta_step: end\n"); #endif } /** * Function to estimate the error on a Runge-Kutta step. */ void runge_kutta_error (RungeKutta * rk, ///< Runge-Kutta struct. long double dt) ///< time step size. { long double e0[3], e1[3]; Method *m; unsigned int i; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_error: start\n"); #endif m = RUNGE_KUTTA_METHOD (rk); e0[0] = e0[1] = e0[2] = e1[0] = e1[1] = e1[2] = 0.L; for (i = 0; i < m->nsteps; ++i) { e0[0] += dt * rk->e[i] * m->r1[i][0]; e0[1] += dt * rk->e[i] * m->r1[i][1]; e0[2] += dt * rk->e[i] * m->r1[i][2]; e1[0] += dt * rk->e[i] * m->r2[i][0]; e1[1] += dt * rk->e[i] * m->r2[i][1]; e1[2] += dt * rk->e[i] * m->r2[i][2]; } m->e0 = sqrtl (e0[0] * e0[0] + e0[1] * e0[1] + e0[2] * e0[2]); m->e1 = sqrtl (e1[0] * e1[0] + e1[1] * e1[1] + e1[2] * e1[2]); m->et0 += m->e0; m->et1 += m->e1; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_error: e0=%Lg et0=%Lg\n", m->e0, m->et0); fprintf (stderr, "runge_kutta_error: e1=%Lg et1=%Lg\n", m->e1, m->et1); fprintf (stderr, "runge_kutta_error: end\n"); #endif } /** * Function to run the Runge-Kutta method bucle. * * \return final time. */ long double runge_kutta_run (RungeKutta * rk, ///< RungeKutta struct. Equation * eq) ///< Equation struct. { Method *m; long double t, to, dt, dto, et0o, et1o; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_run: start\n"); #endif // variables backup m = RUNGE_KUTTA_METHOD (rk); memcpy (ro0, r0, 3 * sizeof (long double)); memcpy (ro1, r1, 3 * sizeof (long double)); memcpy (ro2, r2, 3 * sizeof (long double)); // temporal bucle for (t = 0.L; 1;) { // time step size if (t > 0.L && m->error_dt) { dto = dt; dt = method_dt (m, dt); // revert the step if big error if (dt < m->beta * dto) { t = to; m->et0 = et0o; m->et1 = et1o; memcpy (r0, ro0, 3 * sizeof (long double)); memcpy (r1, ro1, 3 * sizeof (long double)); memcpy (r2, ro2, 3 * sizeof (long double)); } } else dt = equation_step_size (eq); // checking trajectory end to = t; if (equation_land (eq, to, &t, &dt)) break; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_run: t=%Lg dt=%Lg\n", t, dt); #endif // backup of variables memcpy (ro0, r0, 3 * sizeof (long double)); memcpy (ro1, r1, 3 * sizeof (long double)); memcpy (ro2, r2, 3 * sizeof (long double)); // Runge-Kutta step runge_kutta_step (rk, eq, to, dt); // error estimate if (m->error_dt) { et0o = m->et0; et1o = m->et1; runge_kutta_error (rk, dt); } } #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_run: end\n"); #endif return t; } /** * Function to free the memory used by a RungeKutta struct. */ void runge_kutta_delete (RungeKutta * rk) ///< RungeKutta struct. { #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_delete: start\n"); #endif method_delete (RUNGE_KUTTA_METHOD (rk)); #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_delete: end\n"); #endif } /** * Function to read the Runge-Kutta method data on a XML node. * * \return 1 on success, 0 on error. */ int runge_kutta_read_xml (RungeKutta * rk, ///< RungeKutta struct. xmlNode * node) ///< XML node. { const char *message[] = { "Bad type", "Bad method data", "Unknown Runge-Kutta method" }; int e, error_code; unsigned int type; #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_read_xml: start\n"); #endif type = xml_node_get_uint (node, XML_TYPE, &error_code); if (error_code) { e = 0; goto fail; } if (!method_read_xml (RUNGE_KUTTA_METHOD (rk), node)) { e = 1; goto fail; } switch (type) { case 1: runge_kutta_init_1 (rk); break; case 2: runge_kutta_init_2 (rk); break; case 3: runge_kutta_init_3 (rk); break; case 4: runge_kutta_init_4 (rk); break; default: e = 2; goto fail; } #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_read_xml: success\n"); fprintf (stderr, "runge_kutta_read_xml: end\n"); #endif return 1; fail: error_add (message[e]); #if DEBUG_RUNGE_KUTTA fprintf (stderr, "runge_kutta_read_xml: error\n"); fprintf (stderr, "runge_kutta_read_xml: end\n"); #endif return 0; }
{ "alphanum_fraction": 0.6214144787, "avg_line_length": 28.5856832972, "ext": "c", "hexsha": "2a0175012904007328a18b002967a7857efdd1a2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-06-24T07:19:47.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-24T07:19:47.000Z", "max_forks_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/ballistic", "max_forks_repo_path": "1.1.0/runge-kutta.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/ballistic", "max_issues_repo_path": "1.1.0/runge-kutta.c", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/ballistic", "max_stars_repo_path": "1.1.0/runge-kutta.c", "max_stars_repo_stars_event_max_datetime": "2020-08-02T14:03:09.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-02T14:03:09.000Z", "num_tokens": 4493, "size": 13178 }
//segSites.h #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> double my_h(double q, void * p); double my_H(gsl_vector *pVector, void * p); void siteProbMatrix(gsl_matrix *probs, gsl_vector *pVector, int maxSampleSize, gsl_vector *sampleSizeVector); double weightedLikLookSites(gsl_vector *pVector, void * p); gsl_vector *jointMLEst(double *lik, void * p); double weightedLikLookSitesNState(gsl_vector *pVector, void * p); void jointMLEstNState(gsl_vector *results, double *lik, void * p);
{ "alphanum_fraction": 0.768, "avg_line_length": 41.6666666667, "ext": "h", "hexsha": "6b78c9fb744b5c49892f30139763885a78ed92fe", "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": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_path": "segSiteHMM/segSites.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "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": "andrewkern/segSiteHMM", "max_issues_repo_path": "segSiteHMM/segSites.h", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_path": "segSiteHMM/segSites.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 148, "size": 500 }
/* * ----------------------------------------------------------------- * ode_lib.c * ODE Solver Library * Version: 2.0 * Last Update: Oct 1, 2019 * * This is the implementation of a computational library with * numerical tools for Ordinary Differential Equations (ODE). * ----------------------------------------------------------------- * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2019 by Americo Barbosa da Cunha Junior * ----------------------------------------------------------------- */ #include <stdlib.h> #include <math.h> #include <float.h> #include <cvode/cvode.h> /* prototypes for CVODE functions and const */ #include <nvector/nvector_serial.h> /* access to serial NVector */ #include <sunmatrix/sunmatrix_dense.h> /* access to dense SUNMatrix */ #include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */ #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "../include/ode_lib.h" /* *------------------------------------------------------------ * uround * * This function computes the machine unit roundoff * defined as the smallest u such that 1.0 + u > 1.0 * * Output: * uround - machine unit roundoff * * last update: May 20, 2009 *------------------------------------------------------------ */ double uround(void) { double u = 1.0; double comp = 0.0; while(comp != 1.0) { u *= 0.5; comp = 1.0 + u; } return 2.0*u; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * wnorm * * This function computes v1 and v2 vector weight norm * defined as * wnorm = sqrt( (1/n)*(sum (v1[i]*v2[i])^2) ) * * Input: * n - vectors dimension * v - vector 1 * v - vector 2 * * Output: * wnorm - weight norm * * last update: May 20, 2009 *------------------------------------------------------------ */ double wnorm(int n,double *v1,double *v2) { int i; double wnorm = 0.0; for ( i = 0; i < n; i++ ) wnorm += v1[i]*v1[i]*v2[i]*v2[i]; return sqrt( wnorm / (double)n ); } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * ewset * * This function creates a error weight vector * defined as ewv[i] = rtol*abs(v[i]) + atol * * Input: * n - vector dimension * v - vector * atol - absolute tolerance * rtol - relative tolerance * * Output: * ewv - error weight vector * * last update: May 22, 2009 *------------------------------------------------------------ */ void ewtset(int n,double *v,double atol,double rtol,double *ewt) { int i; for ( i = 0; i < n; i++ ) ewt[i] = rtol*fabs(v[i]) + atol; return; } /*------------------------------------------------------------*/ /*------------------------------------------------------------ * jacobian * * This function computes the jacobian matrix of ydot = f(y,t) * defiend as Jij = dfi/dyj * * Input: * n - vector dimension * f_data - pointer to external data * Fy - reaction mapping * y - composition vector * t - time step * atol - absolute tolerance * rtol - relative tolerance * * Output: * J - jacobian matrix * success or error * * last update: Oct 7, 2009 ------------------------------------------------------------*/ int jacobian(CVRhsFn f,void *f_data,gsl_vector *Fy,gsl_vector *y, double t,double atol,double rtol,gsl_matrix *J) { unsigned int i, j, N1, N2; double roundoff, min_inc_mult; double fnorm, minInc, inc, inc_inv, yjsaved, srur; double *yd_data = NULL; double *Fyd_data = NULL; N_Vector yd = NULL; N_Vector Fyd = NULL; gsl_vector *ewt = NULL; min_inc_mult = 1.0e3; /* vectors dimensions */ N1 = y->size; N2 = Fy->size; /* error weight vector */ ewt = gsl_vector_calloc(N1); /* computing the unit roundoff */ roundoff = uround(); /* memory allocation and startup of yd and Fyd */ yd = N_VNew_Serial(N1); Fyd = N_VNew_Serial(N2); if ( yd == NULL || Fyd == NULL ) return GSL_ENOMEM; /* obtaining yd and Fyd compoments */ yd_data = NV_DATA_S(yd); Fyd_data = NV_DATA_S(Fyd); /* setting yd equal y vector */ for ( i = 0; i < N1; i++ ) yd_data[i] = y->data[i]; /* setting Fyd equal the null vector */ for ( i = 0; i < N2; i++ ) Fyd_data[i] = 0.0; /* defing error weight vector */ ewtset(N1,y->data,atol,rtol,ewt->data); /* computing weight norm */ fnorm = wnorm(N2,Fy->data,ewt->data); /* square root of the machine roundoff */ srur = sqrt(roundoff); /* computing disturbance parameter */ minInc = (fnorm != 0.0) ? (min_inc_mult*fabs(t)*roundoff*((double)N1)*fnorm) : 1.0; for ( j = 0; j < N1; j++ ) { /* saving y[j] value */ yjsaved = yd_data[j]; /* disturbance */ inc = GSL_MAX(srur*fabs(yjsaved),minInc/ewt->data[j]); /* disturbing y */ yd_data[j] += inc; /* computing Fy disturbed */ f(t,yd,Fyd,f_data); /* restoring yd[j] original value */ yd_data[j] = yjsaved; /* computing the step */ inc_inv = 1.0/inc; /* computing jacobian matrix column j */ for ( i = 0; i < N2; i++ ) J->data[i*J->tda+j] = inc_inv*(Fyd_data[i] - Fy->data[i]); } /* releasing allocated memory */ N_VDestroy_Serial(yd); N_VDestroy_Serial(Fyd); gsl_vector_free(ewt); yd = NULL; Fyd = NULL; yd_data = NULL; Fyd_data = NULL; ewt = NULL; return GSL_SUCCESS; } /*------------------------------------------------------------*/ /*------------------------------------------------------------ * gradient * * This function computes the gradient matrix of R(phi) * defiend as: Aij = d R_i/d phi_j * * Input: * cvode_mem - ODE solver workspace * t0 - initial time * delta_t - time step * phi - composition vector * Rphi - reac tion mapping * * Output: * A - gradient matrix * success or error * * last update: Oct 1, 2019 ------------------------------------------------------------*/ int gradient(void *cvode_mem,double t0,double delta_t, gsl_vector *phi,gsl_vector *Rphi,gsl_matrix *A) { unsigned int i, j, flag; double inc, inc_inv, phijsaved, srur; gsl_vector *Rphid = NULL; /* memory allocation for Rphid */ Rphid = gsl_vector_calloc(Rphi->size); /* square root of 1.0e6 times the machine roundoff */ srur = sqrt(1.0e6*DBL_EPSILON); for ( j = 0; j < phi->size; j++ ) { /* save phi_j value */ phijsaved = phi->data[j]; /* disturbance */ inc = phijsaved*srur + srur; /* disturbe phi_j */ phi->data[j] += inc; /* compute R(phi) disturbed */ flag = odesolver_reinit(t0,phi,cvode_mem); if ( flag != GSL_SUCCESS ) return flag; flag = odesolver(cvode_mem,delta_t,Rphid); if ( flag != GSL_SUCCESS ) return flag; /* restore phi_j original value */ phi->data[j] = phijsaved; /* compute the step */ inc_inv = 1.0/inc; /* compute gradient matrix column j */ for ( i = 0; i < Rphi->size; i++ ) A->data[i*A->tda+j] = inc_inv*(Rphid->data[i] - Rphi->data[i]); } /* release allocated memory */ gsl_vector_free(Rphid); Rphid = NULL; return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * linear_approx * * This function computes the linear approximation * for a vector function F(x) near the point x0. * * F(x) = F(x0) + DF(x0)*(x-x0) * * Input: * x - vector x * x0 - vector x0 * Fx0 - function at x0 * DFx0 - jacobian matrix at x0 * * Output: * Fx - linear approximation for F(x) * * last update: Jun 9, 2009 *------------------------------------------------------------ */ void linear_approx(gsl_vector *x,gsl_vector *x0, gsl_vector *Fx0,gsl_matrix *DFx0,gsl_vector *Fx) { gsl_vector *aux = NULL; /* memory allocation */ aux = gsl_vector_alloc(x0->size); /* aux := x */ gsl_vector_memcpy(aux,x); /* aux := x - x0 */ gsl_vector_sub(aux,x0); /* Fx := F(x0) */ gsl_vector_memcpy(Fx,Fx0); /* Fx := F(x0) + DF(x0)*(x-x0) */ gsl_blas_dgemv(CblasNoTrans,1.0,DFx0,aux,1.0,Fx); /* releasing allocated memory */ gsl_vector_free(aux); aux = NULL; return; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * odesolver_init * * This function initiates the ODE solver workspace. * * Input: * f - right hand side function * f_data - right hand side function data * t0 - initial time * mxsteps - max # of solver iterations * atol - absolute tolerance * rtol - relative tolerance * x - initial condition * cvode_mem - ODE solver workspace * * Output: * success or error * * last update: Oct 1, 2019 *------------------------------------------------------------ */ int odesolver_init(CVRhsFn f,void *f_data,double t0,int mxsteps, double atol,double rtol,gsl_vector *x,void *cvode_mem) { int maxnef = 100; /* max. # of error test failures */ int flag = CV_SUCCESS; /* return value flag */ N_Vector y0 = NULL; /* initial condition vector */ SUNMatrix A = NULL; /* Matrix for linear solver use */ SUNLinearSolver LS = NULL; /* dense linear solver object */ /* memory allocation for initial condition y0 */ y0 = N_VMake_Serial(x->size,x->data); if ( y0 == NULL ) return GSL_ENOMEM; /* memory allocation for CVODE workspace */ flag = CVodeInit(cvode_mem,f,t0,y0); if( flag != CV_SUCCESS ) return GSL_ENOMEM; /* specifies scalar absolute and relative tolerances */ flag = CVodeSStolerances(cvode_mem,rtol,atol); if( flag != CV_SUCCESS ) return flag; /* set user data for right hand side function */ flag = CVodeSetUserData(cvode_mem,f_data); if( flag != CV_SUCCESS ) return flag; /* Create dense SUNMatrix for use in linear solver */ A = SUNDenseMatrix(x->size,x->size); if ( A == NULL ) return GSL_ENOMEM; /* Create dense SUNLinearSolver object for use by CVode */ LS = SUNLinSol_Dense(y0, A); if ( LS == NULL ) return GSL_ENOMEM; /* Call CVodeSetLinearSolver to attach the matrix and linear solver to CVode */ flag = CVodeSetLinearSolver(cvode_mem, LS, A); if( flag != CVLS_SUCCESS ) return flag; /* set solver max # of steps */ flag = CVodeSetMaxNumSteps(cvode_mem,mxsteps); if( flag != CV_SUCCESS ) return flag; /* set max # of error test failures permitted */ flag = CVodeSetMaxErrTestFails(cvode_mem,maxnef); if( flag != CV_SUCCESS ) return flag; /* release allocated memory for y0 */ N_VDestroy_Serial(y0); y0 = NULL; return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * odesolver_reinit * * This function reinitiates the ODE solver workspace. * * Input: * f - right hand side function * f_data - right hand side function data * t0 - initial time * x - initial condition * cvode_mem - ODE solver workspace * * Output: * success or error * * last update: Oct 1, 2019 *------------------------------------------------------------ */ int odesolver_reinit(double t0,gsl_vector *x,void *cvode_mem) { int flag = CV_SUCCESS; /* return value flag */ N_Vector y0 = NULL; /* initial condition vector */ /* memory allocation for y0 */ y0 = N_VMake_Serial(x->size,x->data); if ( y0 == NULL ) return GSL_ENOMEM; /* restart CVODE workspace */ flag = CVodeReInit(cvode_mem,t0,y0); if( flag != CV_SUCCESS ) return flag; /* release allocated memory */ N_VDestroy_Serial(y0); y0 = NULL; return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * odesolver * * This function performs the direct integration of the * governing equations. * * Input: * cvode_mem - ODE solver workspace * tf - final time * Fx - solution vector * * Output: * success or error * * last update: Oct 31, 2009 *------------------------------------------------------------ */ int odesolver(void *cvode_mem,double tf,gsl_vector *Fx) { double t; int flag = CV_SUCCESS; N_Vector y = NULL; /* memory allocation and startup of y */ y = N_VMake_Serial(Fx->size,Fx->data); if ( y == NULL ) return GSL_ENOMEM; /* calling CVode solver */ flag = CVode(cvode_mem,tf,y,&t,CV_NORMAL); if( flag != CV_SUCCESS ) return flag; /* releasing allocated memory */ N_VDestroy_Serial(y); y = NULL; return GSL_SUCCESS; } /*------------------------------------------------------------*/
{ "alphanum_fraction": 0.4945858731, "avg_line_length": 24.594356261, "ext": "c", "hexsha": "ad1602f605fadc38ebf8117cc6f612c833eab52e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_path": "CRFlowLib-2.0/src/ode_lib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_path": "CRFlowLib-2.0/src/ode_lib.c", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_path": "CRFlowLib-2.0/src/ode_lib.c", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "num_tokens": 3692, "size": 13945 }
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #else #include "CustomSolver.h" #endif #include "BooleanNodes.h" #include "BooleanDAG.h" #include "NodeVisitor.h" #include <map> #include "SymbolicEvaluator.h" #include "Util.h" #include <iostream> using namespace std; // Goes through the DAG and figures out where the gradient vanishes class GradientAnalyzer: public NodeVisitor { BooleanDAG& bdag; SymbolicEvaluator* eval; double threshold = 0.01; double upThreshold = 1000; bool printVals = true; bool printGrads = false; bool printGradLoss = false; bool printGradBlowup = false; bool printSqrt = false; public: GradientAnalyzer(BooleanDAG& bdag_p, SymbolicEvaluator* eval_p): bdag(bdag_p), eval(eval_p) {} ~GradientAnalyzer(void) {} virtual void visit( SRC_node& node ); virtual void visit( DST_node& node ); virtual void visit( CTRL_node& node ); virtual void visit( PLUS_node& node ); virtual void visit( TIMES_node& node ); virtual void visit( ARRACC_node& node ); virtual void visit( DIV_node& node ); virtual void visit( MOD_node& node ); virtual void visit( NEG_node& node ); virtual void visit( CONST_node& node ); virtual void visit( LT_node& node ); virtual void visit( EQ_node& node ); virtual void visit( AND_node& node ); virtual void visit( OR_node& node ); virtual void visit( NOT_node& node ); virtual void visit( ARRASS_node& node ); virtual void visit( UFUN_node& node ); virtual void visit( TUPLE_R_node& node ); virtual void visit( ASSERT_node& node ); virtual void run(); virtual void run(bool_node* n); };
{ "alphanum_fraction": 0.7118746233, "avg_line_length": 24.7611940299, "ext": "h", "hexsha": "0bb376e27aba537161e06ce71e130a0788626fe3", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicAnalyzers/GradientAnalyzer.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicAnalyzers/GradientAnalyzer.h", "max_line_length": 98, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicAnalyzers/GradientAnalyzer.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 413, "size": 1659 }
#include <gsl/gsl> #include <functional> #include <mutex> #include <condition_variable> #include <future> #include <thread> namespace lom { using executor_t = void (*)(std::function<void()>); auto default_executor_impl = [](std::function<void()> f) { std::thread(std::move(f)).detach(); }; extern executor_t g_default_executor; // // /** * used to make the library header only. You'll need to add the following in 1 file in an app to use the continuation feature * ``` * #define LOM_FUTURE_IMPLEMENT * #include "lom/future.h" * ``` */ #ifdef LOM_FUTURE_IMPLEMENT executor_t g_default_executor = default_executor_impl; #endif template<class TYPE> class state : public std::enable_shared_from_this<state<TYPE>> { union { TYPE value_; std::exception_ptr exception_; }; enum { NONE, HAS_VALUE, HAS_EXCEPTION, } status_{NONE}; mutable std::mutex mutex_; mutable std::condition_variable cv_; std::function<void(std::shared_ptr<state>)> continuation_; public: void reset() { switch (status_) { case NONE: break; case HAS_VALUE: value_.TYPE::~TYPE(); break; case HAS_EXCEPTION: exception_.std::exception_ptr::~exception_ptr(); break; } status_ = NONE; } // for make_ready_future template<class ...ARGS> state(ARGS &&...args) { status_ = HAS_VALUE; new(&value_) TYPE(std::forward<ARGS>(args)...); } state() {} ~state() { reset(); } template<class ...ARGS> void set_value(ARGS &&...args) { if (status_ != NONE) throw std::future_error{std::future_errc::promise_already_satisfied}; { std::lock_guard<std::mutex> lock(mutex_); status_ = HAS_VALUE; new(&value_) TYPE(std::forward<ARGS>(args)...); } cv_.notify_one(); if (continuation_) { continuation_(this->shared_from_this()); } } void set_exception(std::exception_ptr p) { if (status_ != NONE) throw std::future_error{std::future_errc::promise_already_satisfied}; { std::lock_guard<std::mutex> lock(mutex_); status_ = HAS_EXCEPTION; new(&exception_) std::exception_ptr(p); } cv_.notify_one(); if (continuation_) continuation_(this->shared_from_this()); } TYPE get() { std::unique_lock<decltype(mutex_)> lock{mutex_}; cv_.wait(lock, [this]() { return this->status_ != NONE; }); if (status_ == HAS_EXCEPTION) std::rethrow_exception(exception_); return std::move(value_); } std::future_status wait() const { std::unique_lock<decltype(mutex_)> lock{mutex_}; cv_.wait(lock, [this]() { return this->status_ != NONE; }); return std::future_status::ready; } template<class Rep, class Period> std::future_status wait_for(const std::chrono::duration<Rep, Period> &rel_time) const { std::unique_lock<decltype(mutex_)> lock{mutex_}; bool time_out = cv_.wait_for(lock, rel_time, [this]() { return this->status_ != NONE; }); if (time_out) return std::future_status::timeout; return std::future_status::ready; } template<class Clock, class Duration> std::future_status wait_until(const std::chrono::time_point<Clock, Duration> &abs_time) const { std::unique_lock<decltype(mutex_)> lock{mutex_}; bool time_out = cv_.wait_until(lock, abs_time, [this]() { return this->status_ != NONE; }); if (time_out) return std::future_status::timeout; return std::future_status::ready; } void then(std::function<void(std::shared_ptr<state>)> &&func) { { std::lock_guard<std::mutex> lock(mutex_); if (status_ == NONE) { continuation_ = std::move(func); return; } } // don't need to lock cause the value is already set and it will through an exception if you try to set it again // func(this->shared_from_this()); } }; template<class TYPE> class future; template<class TYPE, class ...ARGS> future<TYPE> create_ready_future(ARGS &&... args); template<class future_t> class future { public: using type = future_t; private: template<class ...ARGS> friend future<future_t> create_ready_future(ARGS &&... args); std::shared_ptr<state<future_t>> state_; private: template<typename> struct is_future : std::false_type {}; template<typename T> struct is_future<future<T>> : std::true_type {}; public: template<class ...ARGS> future(ARGS &&... args): state_(std::make_shared<future_t>(std::forward<ARGS>(args)...)) {} future() {} future(const future &) = delete; future &operator=(const future &) = default; future(future &&p) : state_(std::move(p.state_)) { p.state_ = nullptr; } future &operator=(future &&p) { this->state_ = std::move(p.state_); p.state_ = nullptr; } future(std::shared_ptr<state<future_t>> state) : state_(std::move(state)) {} future_t get() { if (!state_) throw std::future_error{std::future_errc::no_state}; auto rm_state = gsl::finally([this]() { this->state_->reset(); this->state_ = nullptr; }); return state_->get(); } std::future_status wait() { if (!state_) throw std::future_error{std::future_errc::no_state}; return state_->wait(); } template<class Rep, class Period> std::future_status wait_for(const std::chrono::duration<Rep, Period> &rel_time) const { if (!state_) throw std::future_error{std::future_errc::no_state}; return state_->wait_for(rel_time); } template<class Clock, class Duration> std::future_status wait_until(const std::chrono::time_point<Clock, Duration> &abs_time) const { if (!state_) throw std::future_error{std::future_errc::no_state}; return state_->wait_until(abs_time); } bool valid() { return state_ != nullptr; } //function that returns void template <class callback_t, class return_t = typename std::result_of<callback_t(future_t)>::type, typename = typename std::enable_if<std::is_void<return_t>::value >::type > void then(callback_t cb_function){ if (!state_) throw std::future_error{std::future_errc::no_state}; state_->then([cb_function = std::move(cb_function)](std::shared_ptr<state<future_t>> state) mutable { g_default_executor([cb_function = std::move(cb_function), state = std::move(state)]() mutable { cb_function(future<future_t> {state}); }); }); } //function that returns a non future value template <class callback_t, class inner_return_t = typename std::result_of<callback_t(future_t)>::type, class return_t = future<inner_return_t>, typename = typename std::enable_if<!std::is_void<inner_return_t>::value >::type, typename = typename std::enable_if<!is_future<inner_return_t>::value>::type > return_t then(callback_t cb_function) { if (!state_) throw std::future_error{std::future_errc::no_state}; auto ret_state = std::make_shared<state<inner_return_t>>(); state_->then([cb_function = std::move(cb_function), ret_state](std::shared_ptr<state<future_t>> state) mutable { g_default_executor([cb_function = std::move(cb_function), state = std::move(state), ret_state = std::move(ret_state)]() mutable { ret_state->set_value(cb_function(future<future_t> {state})); }); }); return return_t {ret_state}; } // function that returns a lom::future template <class callback_t, class return_t = typename std::result_of<callback_t(future_t)>::type, class inner_return_t = typename return_t::type, typename = typename std::enable_if<is_future<return_t>::value>::type > return_t then(callback_t cb_function) { static_assert(std::is_same<return_t, lom::future<double>>::value, "qwert"); static_assert(std::is_same<inner_return_t,double>::value, "qewr"); if (!state_) throw std::future_error{std::future_errc::no_state}; auto ret_state = std::make_shared<state<inner_return_t>>(); state_->then([cb_function = std::move(cb_function), ret_state](std::shared_ptr<state<future_t>> state) mutable { g_default_executor([cb_function = std::move(cb_function), state = std::move(state), ret_state = std::move(ret_state)]() mutable { return_t rt = cb_function(future<future_t> {state}); rt.then([ret_state = std::move(ret_state)](return_t r){ ret_state->set_value(r.get()); }); //ret_state->set_value }); }); return return_t {ret_state}; } }; template<class TYPE, class ...ARGS> future<TYPE> create_ready_future(ARGS &&... args) { return {std::forward<ARGS>(args)...}; } template<class TYPE> class promise { std::shared_ptr<state<TYPE>> state_; bool has_future = false; public: promise() : state_(std::make_shared<state<TYPE>>()) {} promise(const promise &) = delete; promise &operator=(const promise &) = delete; promise(promise &&p) : state_(std::move(p.state_)) {} promise &operator=(promise &&p) noexcept { this->state_ = std::move(p.state_); } future<TYPE> get_future() { if(has_future) throw std::future_error{std::future_errc::future_already_retrieved}; has_future = true; return {state_}; } template<class ...ARGS> void set_value(ARGS &&...args) { if (!state_) throw std::future_error{std::future_errc::no_state}; state_->set_value(std::forward<ARGS>(args)...); } void set_exception(std::exception_ptr p) { if (!state_) throw std::future_error{std::future_errc::no_state}; state_->set_exception(std::move(p)); } }; /* template<class future_t> template<class callback_t, class return_t> auto future<future_t>::then(callback_t cb_function) -> return_t { static_assert(!std::is_same<return_t, void>::value, "is null"); if (!state_) throw std::future_error{std::future_errc::no_state}; state_->then([cb_function = std::move(cb_function)](std::shared_ptr<state<future_t>> state) mutable { g_default_executor([cb_function = std::move(cb_function), state = std::move(state)]() mutable { cb_function(future<future_t> {state}); }); }); } */ }
{ "alphanum_fraction": 0.6005219582, "avg_line_length": 28.2030456853, "ext": "h", "hexsha": "e7e3da92a932213cd1fea1697940b81f917fe6e0", "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": "9d91444fd92868f70fe0eb29ffa16d519ea51974", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "liamom/future", "max_forks_repo_path": "include/lom/future.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9d91444fd92868f70fe0eb29ffa16d519ea51974", "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": "liamom/future", "max_issues_repo_path": "include/lom/future.h", "max_line_length": 141, "max_stars_count": null, "max_stars_repo_head_hexsha": "9d91444fd92868f70fe0eb29ffa16d519ea51974", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "liamom/future", "max_stars_repo_path": "include/lom/future.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2605, "size": 11112 }
#pragma once #include <gsl/gsl> #include <vector> #include <sstream> namespace multiformats { // // Raw memory byte // using byte_t = uint8_t; // // Raw memory buffer // Represents a contiguous run of byte_t elements, or a const view of it. // using buffer_t = std::vector<byte_t>; using bufferview_t = gsl::span<const byte_t>; // Appends a buffer or a byte to a buffer inline buffer_t& operator += (buffer_t& _Left, bufferview_t _Right) { _Left.insert(_Left.end(), _Right.begin(), _Right.end()); return _Left; } inline buffer_t& operator += (buffer_t& _Left, byte_t _Value) { _Left.push_back(_Value); return _Left; } // Concatenates two buffers inline buffer_t operator + (bufferview_t _Left, bufferview_t _Right) { auto result = buffer_t(_Left.size() + _Right.size()); std::copy(_Right.begin(), _Right.end(), std::copy(_Left.begin(), _Left.end(), result.begin())); return result; } // Buffer comparison inline bool operator == (bufferview_t _Left, bufferview_t _Right) { return std::equal(_Left.begin(), _Left.end(), _Right.begin(), _Right.end()); } inline bool operator != (bufferview_t _Left, bufferview_t _Right) { return !(_Left == _Right); } // // String and constant view of strings // using string_t = std::string; using stringview_t = gsl::cstring_span<>; inline std::vector<stringview_t> split(stringview_t s, char delim) { auto elems = std::vector<stringview_t>{}; auto begin = s.begin(); auto end = s.end(); auto first = begin; while (first != end) { auto last = std::find(first, end, delim); elems.push_back(s.subspan(first - begin, last - first)); if (last == end) break; first = last + 1; } return elems; } inline string_t operator+(stringview_t _Left, const string_t& _Right) { return (to_string(_Left) + _Right); } inline string_t operator+(const string_t& _Left, stringview_t _Right) { return (_Left + to_string(_Right)); } // // Conversions // to_* methods create a new container and copy the content // as_* methods return a const view of the container without copy // inline buffer_t to_buffer(stringview_t s) { return { s.begin(), s.end() }; } inline buffer_t to_buffer(const char* s) { return to_buffer(gsl::ensure_z(s)); } inline bufferview_t as_buffer(stringview_t s) { return { reinterpret_cast<const byte_t*>(s.data()), gsl::narrow<ptrdiff_t>(s.size()) }; } inline stringview_t as_string(bufferview_t b) { return { reinterpret_cast<const char*>(b.data()), b.size() }; } inline string_t to_string(bufferview_t b) { return to_string(as_string(b)); } }
{ "alphanum_fraction": 0.6063179348, "avg_line_length": 34.6352941176, "ext": "h", "hexsha": "2c4316de48bb3afac2077d28325c52c5b084465b", "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": "5516d857d4429544bd641b7fdde24c6cad9265b7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cedrou/multiformats", "max_forks_repo_path": "include/multiformats/common.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7", "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": "cedrou/multiformats", "max_issues_repo_path": "include/multiformats/common.h", "max_line_length": 142, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cedrou/cpp-multiformats", "max_stars_repo_path": "include/multiformats/common.h", "max_stars_repo_stars_event_max_datetime": "2019-07-29T20:33:02.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-29T20:33:02.000Z", "num_tokens": 727, "size": 2944 }
/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions are met: */ /* * Redistributions of source code must retain the above copyright notice, */ /* this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright notice, */ /* this list of conditions and the following disclaimer in the documentation */ /* and/or other materials provided with the distribution. */ /* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */ /* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */ /* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */ /* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */ /* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */ /* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UKF_NDIM_STATE_H #define UKF_NDIM_STATE_H #include <gsl/gsl_linalg.h> // For the Cholesky decomposition #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include "ukf_types.h" namespace ukf { /** * @short UKF for state estimation, additive noise case * The notations follow "Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models",p108, PhD, van Der Merwe */ namespace state { /** * @short Allocation of the vectors/matrices and initialization * */ void ukf_init(ukf_param &p, ukf_state &s) { // Parameters for the sigma points of the process equation p.nbSamples = 2 * p.n + 1; p.lambda = p.alpha * p.alpha * (p.n + p.kpa) - p.n; p.gamma = sqrt(p.n + p.lambda); // Parameters for the sigma points of the observation equation p.nbSamplesMeasure = 4 * p.n + 1; p.lambda_aug = p.alpha * p.alpha * (2*p.n + p.kpa) - 2*p.n; p.gamma_aug = sqrt(2*p.n + p.lambda_aug); // Init the matrices used to iterate s.xi = gsl_vector_alloc(p.n); gsl_vector_set_zero(s.xi); s.xi_prediction = gsl_matrix_alloc(p.n, p.nbSamples); gsl_matrix_set_zero(s.xi_prediction); s.xi_mean = gsl_vector_alloc(p.n); gsl_vector_set_zero(s.xi_mean); s.Pxxi = gsl_matrix_alloc(p.n,p.n); gsl_matrix_set_identity(s.Pxxi); gsl_matrix_scale(s.Pxxi, p.prior_x); s.cholPxxi = gsl_matrix_alloc(p.n,p.n); gsl_matrix_set_zero(s.cholPxxi); s.Pvvi = gsl_matrix_alloc(p.n,p.n); s.cholPvvi = gsl_matrix_alloc(p.n,p.n); p.evolution_noise->init(p,s); s.yi_prediction = gsl_matrix_alloc(p.no, p.nbSamplesMeasure); gsl_matrix_set_zero(s.yi_prediction); s.yi_mean = gsl_vector_alloc(p.no); gsl_vector_set_zero(s.yi_mean); s.ino_yi = gsl_vector_alloc(p.no); gsl_vector_set_zero(s.ino_yi); s.Pyyi = gsl_matrix_alloc(p.no, p.no); gsl_matrix_set_zero(s.Pyyi); s.Pnni = gsl_matrix_alloc(p.no,p.no); gsl_matrix_set_identity(s.Pnni); gsl_matrix_scale(s.Pnni, p.measurement_noise); s.Pxyi = gsl_matrix_alloc(p.n, p.no); gsl_matrix_set_zero(s.Pxyi); s.sigmaPoint = gsl_vector_alloc(p.n); gsl_vector_set_zero(s.sigmaPoint); s.sigmaPoints = gsl_matrix_alloc(p.n, p.nbSamples); gsl_matrix_set_zero(s.sigmaPoints); s.sigmaPointMeasure = gsl_vector_alloc(p.n); gsl_vector_set_zero(s.sigmaPoint); s.sigmaPointsMeasure = gsl_matrix_alloc(p.n, p.nbSamplesMeasure); gsl_matrix_set_zero(s.sigmaPointsMeasure); // Weights used to update the statistics s.wm_j = gsl_vector_alloc(p.nbSamples); // Weights used to compute the mean of the sigma points images s.wc_j = gsl_vector_alloc(p.nbSamples); // Weights used to update the covariance matrices // Set the weights gsl_vector_set(s.wm_j, 0, p.lambda / (p.n + p.lambda)); gsl_vector_set(s.wc_j, 0, p.lambda / (p.n + p.lambda) + (1.0 - p.alpha*p.alpha + p.beta)); for(int j = 1 ; j < p.nbSamples; j ++) { gsl_vector_set(s.wm_j, j, 1.0 / (2.0 * (p.n + p.lambda))); gsl_vector_set(s.wc_j, j, 1.0 / (2.0 * (p.n + p.lambda))); } // Set the weights s.wm_aug_j = gsl_vector_alloc(p.nbSamplesMeasure); // Weights used to compute the mean of the sigma points images s.wc_aug_j = gsl_vector_alloc(p.nbSamplesMeasure); // Weights used to update the covariance matrices gsl_vector_set(s.wm_aug_j, 0, p.lambda_aug / (2*p.n + p.lambda_aug)); gsl_vector_set(s.wc_aug_j, 0, p.lambda_aug / (2*p.n + p.lambda_aug) + (1.0 - p.alpha*p.alpha + p.beta)); for(int j = 1 ; j < p.nbSamplesMeasure; j ++) { gsl_vector_set(s.wm_aug_j, j, 1.0 / (2.0 * (2*p.n + p.lambda_aug))); gsl_vector_set(s.wc_aug_j, j, 1.0 / (2.0 * (2*p.n + p.lambda_aug))); } s.Ki = gsl_matrix_alloc(p.n, p.no); s.Ki_T = gsl_matrix_alloc(p.no, p.n); // Allocate temporary matrices s.temp_n = gsl_vector_alloc(p.n); s.temp_n_1 = gsl_matrix_alloc(p.n,1); s.temp_1_n = gsl_matrix_alloc(1,p.n); s.temp_n_n = gsl_matrix_alloc(p.n, p.n); s.temp_n_no = gsl_matrix_alloc(p.n, p.no); s.temp_no_1 = gsl_matrix_alloc(p.no,1); s.temp_1_no = gsl_matrix_alloc(1,p.no); s.temp_no_no = gsl_matrix_alloc(p.no, p.no); } /** * @short Free of memory allocation * */ void ukf_free(ukf_param &p, ukf_state &s) { gsl_vector_free(s.xi); gsl_matrix_free(s.xi_prediction); gsl_vector_free(s.xi_mean); gsl_matrix_free(s.Pxxi); gsl_matrix_free(s.cholPxxi); gsl_matrix_free(s.Pvvi); gsl_matrix_free(s.cholPvvi); gsl_matrix_free(s.yi_prediction); gsl_vector_free(s.yi_mean); gsl_vector_free(s.ino_yi); gsl_matrix_free(s.Pyyi); gsl_matrix_free(s.Pnni); gsl_matrix_free(s.Pxyi); gsl_vector_free(s.sigmaPoint); gsl_matrix_free(s.sigmaPoints); gsl_vector_free(s.sigmaPointMeasure); gsl_matrix_free(s.sigmaPointsMeasure); gsl_vector_free(s.wm_j); gsl_vector_free(s.wc_j); gsl_vector_free(s.wm_aug_j); gsl_vector_free(s.wc_aug_j); gsl_matrix_free(s.Ki); gsl_matrix_free(s.Ki_T); gsl_vector_free(s.temp_n); gsl_matrix_free(s.temp_n_1); gsl_matrix_free(s.temp_1_n); gsl_matrix_free(s.temp_n_n); gsl_matrix_free(s.temp_n_no); gsl_matrix_free(s.temp_no_1); gsl_matrix_free(s.temp_1_no); gsl_matrix_free(s.temp_no_no); } /** * @short UKF-additive (zero-mean) noise case, "Kalman Filtering and Neural Networks", p.233 * */ template<typename FFUNC, typename HFUNC> void ukf_iterate(ukf_param &p, ukf_state &s, FFUNC f, HFUNC h, gsl_vector* yi) { int i,j,k; // ************************************************** // // ************ Compute the sigma points ************ // // ************************************************** // // 0 - Compute the Cholesky decomposition of s.Pxxi gsl_matrix_memcpy(s.cholPxxi, s.Pxxi); gsl_linalg_cholesky_decomp(s.cholPxxi); // Set all the elements of cholPvvi strictly above the diagonal to zero for(j = 0 ; j < p.n ; j++) for(k = j+1 ; k < p.n ; k++) gsl_matrix_set(s.cholPxxi,j,k,0.0); // 1- Compute the sigma points, // Equation (3.170) // sigmapoint_j = x_(i-1) // sigmapoint_j = x_(i-1) + gamma * sqrt(P_i-1)_j for 1 <= j <= n // sigmapoint_j = x_(i-1) - gamma * sqrt(P_i-1)_(j-(n+1)) for n+1 <= j <= 2n gsl_matrix_set_col(s.sigmaPoints, 0, s.xi); for(j = 1 ; j < p.n+1 ; ++j) for(i = 0 ; i < p.n ; ++i) { gsl_matrix_set(s.sigmaPoints,i,j, s.xi->data[i] + p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1)); gsl_matrix_set(s.sigmaPoints,i,j+p.n, s.xi->data[i] - p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1)); } /**********************************/ /***** Time update equations *****/ /**********************************/ // Time update equations // 0 - Compute the image of the sigma points and the mean of these images gsl_vector_set_zero(s.xi_mean); gsl_vector_view vec_view; for(j = 0 ; j < p.nbSamples ; ++j) { gsl_matrix_get_col(s.sigmaPoint, s.sigmaPoints, j); vec_view = gsl_matrix_column(s.xi_prediction,j); f(s.params, s.sigmaPoint, &vec_view.vector); // Update the mean, Eq (3.172) for(i = 0 ; i < p.n ; ++i) s.xi_mean->data[i] += s.wm_j->data[j] * gsl_matrix_get(s.xi_prediction,i,j); } // 1 - Compute the covariance of the images and add the process noise, // Equation (3.173) // Warning, s.Pxxi will now hold P_xk^- gsl_matrix_set_zero(s.Pxxi); for(j = 0 ; j < p.nbSamples ; ++j) { for(i = 0 ; i < p.n ; ++i) s.temp_n_1->data[i] = gsl_matrix_get(s.xi_prediction,i,j) - s.xi_mean->data[i]; gsl_blas_dgemm(CblasNoTrans, CblasTrans, s.wc_j->data[j] , s.temp_n_1, s.temp_n_1, 0, s.temp_n_n); gsl_matrix_add(s.Pxxi, s.temp_n_n); } // Add the covariance of the evolution noise gsl_matrix_add(s.Pxxi, s.Pvvi); // Augment sigma points // Equation 3.174 // First put the images of the initial sigma points gsl_matrix_view mat_view; mat_view = gsl_matrix_submatrix(s.sigmaPointsMeasure, 0, 0, p.n, p.nbSamples); gsl_matrix_memcpy(&mat_view.matrix, s.xi_prediction); // And add the additional sigma points eq. (7.56) for(j = 0 ; j < p.n ; ++j) { for(i = 0 ; i < p.n ; ++i) { gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples, gsl_matrix_get(s.xi_prediction,i,0)+p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j)); gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples+p.n, gsl_matrix_get(s.xi_prediction,i,0)-p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j)); } } // Compute the image of the sigma points through the observation equation // eq (3.175) gsl_vector_set_zero(s.yi_mean); for(j = 0 ; j < p.nbSamplesMeasure ; ++j) { gsl_matrix_get_col(s.sigmaPointMeasure, s.sigmaPointsMeasure, j); vec_view = gsl_matrix_column(s.yi_prediction,j); h(s.sigmaPointMeasure, &vec_view.vector); // Update the mean , eq (3.176) for(i = 0 ; i < p.no ; ++i) s.yi_mean->data[i] += s.wm_aug_j->data[j] * gsl_matrix_get(s.yi_prediction,i,j); } /*****************************************/ /***** Measurement update equations *****/ /*****************************************/ // Compute the covariance of the observations // Eq. (3.177) // Initialize with the observation noise covariance gsl_matrix_memcpy(s.Pyyi, s.Pnni); for(j = 0 ; j < p.nbSamplesMeasure ; ++j) { for(i = 0 ; i < p.no ; ++i) s.temp_no_1->data[i] = gsl_matrix_get(s.yi_prediction,i,j) - s.yi_mean->data[i]; gsl_blas_dgemm(CblasNoTrans, CblasTrans, s.wc_aug_j->data[j] , s.temp_no_1, s.temp_no_1, 0, s.temp_no_no); gsl_matrix_add(s.Pyyi, s.temp_no_no); } // Compute the state/observation covariance // Eq (3.178) gsl_matrix_set_zero(s.Pxyi); for(j = 0 ; j < p.nbSamplesMeasure ; ++j) { for(i = 0 ; i < p.n ; ++i) s.temp_n_1->data[i] = gsl_matrix_get(s.sigmaPointsMeasure,i,j) - s.xi_mean->data[i]; for(i = 0 ; i < p.no ; ++i) s.temp_1_no->data[i] = gsl_matrix_get(s.yi_prediction,i,j) - s.yi_mean->data[i]; gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, s.wc_aug_j->data[j] , s.temp_n_1, s.temp_1_no, 0, s.temp_n_no); gsl_matrix_add(s.Pxyi, s.temp_n_no); } // Compute the Kalman gain, eq (3.179) // 0- Compute the inverse of Pyyi gsl_matrix_memcpy(s.temp_no_no, s.Pyyi); gsl_linalg_cholesky_decomp(s.temp_no_no); gsl_linalg_cholesky_invert(s.temp_no_no); // 1- Compute the Kalman gain gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Pxyi, s.temp_no_no, 0, s.Ki); // Correction : correct the estimation of the state // Eq. 3.180 // Compute the innovations for(i = 0 ; i < p.no ; ++i) s.ino_yi->data[i] = gsl_vector_get(yi, i) - gsl_vector_get(s.yi_mean, i); gsl_vector_memcpy(s.xi, s.xi_mean); gsl_blas_dgemv(CblasNoTrans, 1.0 , s.Ki, s.ino_yi, 1.0, s.xi); // Correction : Update the covariance matrix Pk // Eq. 3.181 gsl_matrix_transpose_memcpy(s.Ki_T, s.Ki); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Ki, s.Pyyi, 0, s.temp_n_no); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0 , s.temp_n_no, s.Ki_T, 1.0, s.Pxxi); // Update of the process noise p.evolution_noise->updateEvolutionNoise(p,s); // switch(p.process_noise_type) // { // case ukf::UKF_PROCESS_FIXED: // //nothing to do // break; // case ukf::UKF_PROCESS_RLS: // gsl_matrix_memcpy(s.Pvvi, s.Pxxi); // gsl_matrix_scale(s.Pvvi, 1.0/p.process_noise-1.0); // gsl_matrix_memcpy(s.cholPvvi, s.Pvvi); // gsl_linalg_cholesky_decomp(s.cholPvvi); // for(j = 0 ; j < p.n ; j++) // for(k = j+1 ; k < p.n ; k++) // gsl_matrix_set(s.cholPvvi,j,k,0.0); // break; // default: // printf("Warning : Unrecognized process noise type\n"); // } } /** * @short Evaluation of the output from the sigma points * */ void ukf_evaluate(ukf_param &p, ukf_state &s, void (*f)(gsl_vector*, gsl_vector *, gsl_vector *), void (*h)(gsl_vector*, gsl_vector *), gsl_vector* yi) { int i,j,k; gsl_matrix_view mat_view; gsl_vector_view vec_view; // ************************************************** // // ************ Compute the sigma points ************ // // ************************************************** // // 0 - Compute the Cholesky decomposition of s.Pxxi gsl_matrix_memcpy(s.cholPxxi, s.Pxxi); gsl_linalg_cholesky_decomp(s.cholPxxi); // Set all the elements of cholPvvi strictly above the diagonal to zero for(j = 0 ; j < p.n ; j++) for(k = j+1 ; k < p.n ; k++) gsl_matrix_set(s.cholPxxi,j,k,0.0); // 1- Compute the sigma points, // Equation (3.170) // sigmapoint_j = x_(i-1) // sigmapoint_j = x_(i-1) + gamma * sqrt(P_i-1)_j for 1 <= j <= n // sigmapoint_j = x_(i-1) - gamma * sqrt(P_i-1)_(j-(n+1)) for n+1 <= j <= 2n gsl_matrix_set_col(s.sigmaPoints, 0, s.xi); for(j = 1 ; j < p.n+1 ; ++j) for(i = 0 ; i < p.n ; ++i) { gsl_matrix_set(s.sigmaPoints,i,j, s.xi->data[i] + p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1)); gsl_matrix_set(s.sigmaPoints,i,j+p.n, s.xi->data[i] - p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1)); } /**********************************/ /***** Time update equations *****/ /**********************************/ // Time update equations // 0 - Compute the image of the sigma points and the mean of these images gsl_vector_set_zero(s.xi_mean); for(j = 0 ; j < p.nbSamples ; ++j) { gsl_matrix_get_col(s.sigmaPoint, s.sigmaPoints, j); vec_view = gsl_matrix_column(s.xi_prediction,j); f(s.params, s.sigmaPoint, &vec_view.vector); // Update the mean, Eq (3.172) for(i = 0 ; i < p.n ; ++i) s.xi_mean->data[i] += s.wm_j->data[j] * gsl_matrix_get(s.xi_prediction,i,j); } // 1 - Compute the covariance of the images and add the process noise, // Equation (3.173) // Warning, s.Pxxi will now hold P_xk^- gsl_matrix_set_zero(s.Pxxi); for(j = 0 ; j < p.nbSamples ; ++j) { for(i = 0 ; i < p.n ; ++i) s.temp_n_1->data[i] = gsl_matrix_get(s.xi_prediction,i,j) - s.xi_mean->data[i]; gsl_blas_dgemm(CblasNoTrans, CblasTrans, s.wc_j->data[j] , s.temp_n_1, s.temp_n_1, 0, s.temp_n_n); gsl_matrix_add(s.Pxxi, s.temp_n_n); } // Add the covariance of the evolution noise gsl_matrix_add(s.Pxxi, s.Pvvi); // Augment sigma points // Equation 3.174 // First put the images of the initial sigma points mat_view = gsl_matrix_submatrix(s.sigmaPointsMeasure, 0, 0, p.n, p.nbSamples); gsl_matrix_memcpy(&mat_view.matrix, s.xi_prediction); // And add the additional sigma points eq. (7.56) for(j = 0 ; j < p.n ; ++j) { for(i = 0 ; i < p.n ; ++i) { gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples, gsl_matrix_get(s.xi_prediction,i,0)+p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j)); gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples+p.n, gsl_matrix_get(s.xi_prediction,i,0)-p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j)); } } // Compute the image of the sigma points through the observation equation // eq (3.175) gsl_vector_set_zero(yi); for(j = 0 ; j < p.nbSamplesMeasure ; ++j) { gsl_matrix_get_col(s.sigmaPointMeasure, s.sigmaPointsMeasure, j); vec_view = gsl_matrix_column(s.yi_prediction,j); h(s.sigmaPointMeasure, &vec_view.vector); // Update the mean , eq (3.176) for(i = 0 ; i < p.no ; ++i) yi->data[i] += s.wm_aug_j->data[j] * gsl_matrix_get(s.yi_prediction,i,j); } } } // state } // ukf #endif // UKF_NDIM_STATE_H
{ "alphanum_fraction": 0.6097100322, "avg_line_length": 37.4261954262, "ext": "h", "hexsha": "d31b4dce61828d2e12ea5fa0fadee177c83af6aa", "lang": "C", "max_forks_count": 52, "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_path": "src/ukf_state_ndim.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_path": "src/ukf_state_ndim.h", "max_line_length": 158, "max_stars_count": 101, "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_path": "src/ukf_state_ndim.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "num_tokens": 5284, "size": 18002 }
/* histogram/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #define N 397 #define NR 10 void test1d (void) { double xr[NR + 1] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; gsl_histogram *h, *h1, *hr, *g; size_t i, j; gsl_ieee_env_setup (); h = gsl_histogram_calloc (N); h1 = gsl_histogram_calloc (N); g = gsl_histogram_calloc (N); gsl_test (h->range == 0, "gsl_histogram_alloc returns valid range pointer"); gsl_test (h->bin == 0, "gsl_histogram_alloc returns valid bin pointer"); gsl_test (h->n != N, "gsl_histogram_alloc returns valid size"); hr = gsl_histogram_calloc_range (NR, xr); gsl_test (hr->range == 0, "gsl_histogram_calloc_range returns valid range pointer"); gsl_test (hr->bin == 0, "gsl_histogram_calloc_range returns valid bin pointer"); gsl_test (hr->n != NR, "gsl_histogram_calloc_range returns valid size"); { int status = 0; for (i = 0; i <= NR; i++) { if (hr->range[i] != xr[i]) { status = 1; } }; gsl_test (status, "gsl_histogram_calloc_range creates range"); } for (i = 0; i <= NR; i++) { hr->range[i] = 0.0; } { int status = gsl_histogram_set_ranges (hr, xr, NR+1); for (i = 0; i <= NR; i++) { if (hr->range[i] != xr[i]) { status = 1; } }; gsl_test (status, "gsl_histogram_set_range sets range"); } for (i = 0; i < N; i++) { gsl_histogram_accumulate (h, (double) i, (double) i); }; { int status = 0; for (i = 0; i < N; i++) { if (h->bin[i] != (double) i) { status = 1; } }; gsl_test (status, "gsl_histogram_accumulate writes into array"); } { int status = 0; for (i = 0; i < N; i++) { if (gsl_histogram_get (h, i) != i) status = 1; }; gsl_test (status, "gsl_histogram_get reads from array"); } for (i = 0; i <= N; i++) { h1->range[i] = 100.0 + i; } gsl_histogram_memcpy (h1, h); { int status = 0; for (i = 0; i <= N; i++) { if (h1->range[i] != h->range[i]) status = 1; }; gsl_test (status, "gsl_histogram_memcpy copies bin ranges"); } { int status = 0; for (i = 0; i < N; i++) { if (gsl_histogram_get (h1, i) != gsl_histogram_get (h, i)) status = 1; }; gsl_test (status, "gsl_histogram_memcpy copies bin values"); } gsl_histogram_free (h1); h1 = gsl_histogram_clone (h); { int status = 0; for (i = 0; i <= N; i++) { if (h1->range[i] != h->range[i]) status = 1; }; gsl_test (status, "gsl_histogram_clone copies bin ranges"); } { int status = 0; for (i = 0; i < N; i++) { if (gsl_histogram_get (h1, i) != gsl_histogram_get (h, i)) status = 1; }; gsl_test (status, "gsl_histogram_clone copies bin values"); } gsl_histogram_reset (h); { int status = 0; for (i = 0; i < N; i++) { if (h->bin[i] != 0) status = 1; } gsl_test (status, "gsl_histogram_reset zeros array"); } { int status = 0; for (i = 0; i < N; i++) { gsl_histogram_increment (h, (double) i); for (j = 0; j <= i; j++) { if (h->bin[j] != 1) { status = 1; } } for (j = i + 1; j < N; j++) { if (h->bin[j] != 0) { status = 1; } } } gsl_test (status, "gsl_histogram_increment increases bin value"); } { int status = 0; for (i = 0; i < N; i++) { double x0 = 0, x1 = 0; gsl_histogram_get_range (h, i, &x0, &x1); if (x0 != i || x1 != i + 1) { status = 1; } } gsl_test (status, "gsl_histogram_getbinrange returns bin range"); } { int status = 0; if (gsl_histogram_max (h) != N) status = 1; gsl_test (status, "gsl_histogram_max returns maximum"); } { int status = 0; if (gsl_histogram_min (h) != 0) status = 1; gsl_test (status, "gsl_histogram_min returns minimum"); } { int status = 0; if (gsl_histogram_bins (h) != N) status = 1; gsl_test (status, "gsl_histogram_bins returns number of bins"); } h->bin[2] = 123456.0; h->bin[4] = -654321; { double max = gsl_histogram_max_val (h); gsl_test (max != 123456.0, "gsl_histogram_max_val finds maximum value"); } { double min = gsl_histogram_min_val (h); gsl_test (min != -654321.0, "gsl_histogram_min_val finds minimum value"); } { size_t imax = gsl_histogram_max_bin (h); gsl_test (imax != 2, "gsl_histogram_max_bin finds maximum value bin"); } { size_t imin = gsl_histogram_min_bin (h); gsl_test (imin != 4, "gsl_histogram_min_bin find minimum value bin"); } for (i = 0; i < N; i++) { h->bin[i] = i + 27; g->bin[i] = (i + 27) * (i + 1); } { double sum=gsl_histogram_sum (h); gsl_test(sum != N*27+((N-1)*N)/2, "gsl_histogram_sum sums all bin values"); } gsl_histogram_memcpy (h1, g); gsl_histogram_add (h1, h); { int status = 0; for (i = 0; i < N; i++) { if (h1->bin[i] != g->bin[i] + h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram_add histogram addition"); } gsl_histogram_memcpy (h1, g); gsl_histogram_sub (h1, h); { int status = 0; for (i = 0; i < N; i++) { if (h1->bin[i] != g->bin[i] - h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram_sub histogram subtraction"); } gsl_histogram_memcpy (h1, g); gsl_histogram_mul (h1, h); { int status = 0; for (i = 0; i < N; i++) { if (h1->bin[i] != g->bin[i] * h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram_mul histogram multiplication"); } gsl_histogram_memcpy (h1, g); gsl_histogram_div (h1, h); { int status = 0; for (i = 0; i < N; i++) { if (h1->bin[i] != g->bin[i] / h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram_div histogram division"); } gsl_histogram_memcpy (h1, g); gsl_histogram_scale (h1, 0.5); { int status = 0; for (i = 0; i < N; i++) { if (h1->bin[i] != 0.5 * g->bin[i]) status = 1; } gsl_test (status, "gsl_histogram_scale histogram scaling"); } gsl_histogram_memcpy (h1, g); gsl_histogram_shift (h1, 0.25); { int status = 0; for (i = 0; i < N; i++) { if (h1->bin[i] != 0.25 + g->bin[i]) status = 1; } gsl_test (status, "gsl_histogram_shift histogram shift"); } gsl_histogram_free (h); /* free whatever is in h */ h = gsl_histogram_calloc_uniform (N, 0.0, 1.0); gsl_test (h->range == 0, "gsl_histogram_calloc_uniform returns valid range pointer"); gsl_test (h->bin == 0, "gsl_histogram_calloc_uniform returns valid bin pointer"); gsl_test (h->n != N, "gsl_histogram_calloc_uniform returns valid size"); gsl_histogram_accumulate (h, 0.0, 1.0); gsl_histogram_accumulate (h, 0.1, 2.0); gsl_histogram_accumulate (h, 0.2, 3.0); gsl_histogram_accumulate (h, 0.3, 4.0); { size_t i1, i2, i3, i4; double expected; int status = gsl_histogram_find (h, 0.0, &i1); status = gsl_histogram_find (h, 0.1, &i2); status = gsl_histogram_find (h, 0.2, &i3); status = gsl_histogram_find (h, 0.3, &i4); for (i = 0; i < N; i++) { if (i == i1) { expected = 1.0; } else if (i == i2) { expected = 2.0; } else if (i == i3) { expected = 3.0; } else if (i == i4) { expected = 4.0; } else { expected = 0.0; } if (h->bin[i] != expected) { status = 1; } } gsl_test (status, "gsl_histogram_find returns index"); } { FILE *f = fopen ("test.txt", "w"); gsl_histogram_fprintf (f, h, "%.19e", "%.19e"); fclose (f); } { FILE *f = fopen ("test.txt", "r"); gsl_histogram *hh = gsl_histogram_calloc (N); int status = 0; gsl_histogram_fscanf (f, hh); for (i = 0; i < N; i++) { if (h->range[i] != hh->range[i]) status = 1; if (h->bin[i] != hh->bin[i]) status = 1; } if (h->range[N] != hh->range[N]) status = 1; gsl_test (status, "gsl_histogram_fprintf and fscanf"); gsl_histogram_free (hh); fclose (f); } { FILE *f = fopen ("test.dat", "wb"); gsl_histogram_fwrite (f, h); fclose (f); } { FILE *f = fopen ("test.dat", "rb"); gsl_histogram *hh = gsl_histogram_calloc (N); int status = 0; gsl_histogram_fread (f, hh); for (i = 0; i < N; i++) { if (h->range[i] != hh->range[i]) status = 1; if (h->bin[i] != hh->bin[i]) status = 1; } if (h->range[N] != hh->range[N]) status = 1; gsl_test (status, "gsl_histogram_fwrite and fread"); gsl_histogram_free (hh); fclose (f); } gsl_histogram_free (h); gsl_histogram_free (g); gsl_histogram_free (h1); gsl_histogram_free (hr); }
{ "alphanum_fraction": 0.5228513941, "avg_line_length": 21.5640495868, "ext": "c", "hexsha": "b7f3dee86169fc93b34e15b5b6e160e020b31fac", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/histogram/test1d.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/histogram/test1d.c", "max_line_length": 86, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/histogram/test1d.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 3302, "size": 10437 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "arcana/errors.h" #include "arcana/expected.h" #include "arcana/functional/inplace_function.h" #include "arcana/iterators.h" #include "arcana/type_traits.h" #include "cancellation.h" #include <gsl/gsl> #include <memory> #include <stdexcept> #include <atomic> namespace mira { template<typename ResultT> class task_completion_source; // // A scheduler that will invoke the continuation inline // right after the previous task. // namespace { struct inline_scheduler_t { template<typename CallableT> constexpr void queue(CallableT&& callable) const { callable(); } }; constexpr inline_scheduler_t inline_scheduler{}; } } #include "internal/internal_task.h" namespace mira { // // Generic task system to run work with continuations on a generic scheduler. // // The scheduler on which tasks are queued must satisfy this contract: // // struct scheduler // { // template<CallableT> // void queue(CallableT&& callable) // { // callable must be usable like this: callable(); // } // }; // template<typename ResultT> class task { using payload_t = internal::base_task_payload_with_return<ResultT>; using payload_ptr = std::shared_ptr<payload_t>; static_assert(std::is_same<typename as_expected<ResultT>::result, ResultT>::value, "task can't be of expected<T>"); public: using result_t = ResultT; task() = default; task(const task& other) = default; task(task&& other) = default; task(const task_completion_source<ResultT>& source) : m_payload{ source.m_payload } {} task(task_completion_source<ResultT>&& source) : m_payload{ std::move(source.m_payload) } {} task& operator=(task&& other) = default; task& operator=(const task& other) = default; bool operator==(const task& other) { return m_payload == other.m_payload; } // // Executes a callable on this scheduler once this task is finished and // returns a task that represents the callable. // // Calling .then() on the returned task will queue a task to run after the // callable is run. // template<typename SchedulerT, typename CallableT> auto then(SchedulerT& scheduler, cancellation& token, CallableT&& callable) { return internal::continuation_factory<ResultT>::create_continuation_task( internal::input_output_wrapper<ResultT>::wrap_callable(std::forward<CallableT>(callable), token), scheduler, m_payload); } private: explicit task(payload_ptr payload) : m_payload{ std::move(payload) } {} template<typename CallableT, typename InputT> explicit task(CallableT&& callable, type_of<InputT> input) { auto payload = std::make_shared<internal::task_payload<ResultT, sizeof(CallableT)>>( std::forward<CallableT>(callable), input); m_payload = std::move(payload); } template<typename OtherResultT, size_t WorkSize> friend struct internal::task_payload; template<typename OtherResultT> friend class task; friend class task_completion_source<ResultT>; template<typename OtherResultT, typename InputT> friend struct internal::task_factory; template<typename OtherResultT> friend struct internal::continuation_factory; template<typename SchedulerT, typename CallableT> friend auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable) -> typename internal::task_factory<typename as_expected<decltype(callable())>::result, void>::task_t; template<typename OtherResultT> friend task<typename as_expected<OtherResultT>::result> task_from_result(OtherResultT&& value); friend task<void> task_from_result(); template<typename OtherResultT, typename ErrorT> friend task<OtherResultT> task_from_error(const ErrorT& error); payload_ptr m_payload; }; } namespace mira { template<typename ResultT> class task_completion_source { using payload_t = internal::noop_task_payload<ResultT>; using payload_ptr = std::shared_ptr<payload_t>; using uninitialized = std::integral_constant<int, 0>; public: using result_t = ResultT; task_completion_source() : m_payload{ std::make_shared<payload_t>() } {} static task_completion_source<ResultT> make_uninitialized() { return task_completion_source<ResultT>{ uninitialized{} }; } // // Completes the task this source represents. // void complete() { static_assert(std::is_same<ResultT, void>::value, "complete with no arguments can only be used with a void completion source"); m_payload->complete(expected<void>::make_valid()); } // // Completes the task this source represents. // template<typename ValueT> void complete(ValueT&& value) { m_payload->complete(std::forward<ValueT>(value)); } // // Returns whether or not the current source has already been completed. // bool completed() const { return m_payload->completed(); } // // Converts this task_completion_source to a task object for consumers to use. // task<ResultT> as_task() const & { return task<ResultT>{ m_payload }; } task<ResultT> as_task() && { return task<ResultT>{ std::move(m_payload) }; } private: explicit task_completion_source(uninitialized) {} explicit task_completion_source(std::shared_ptr<payload_t> payload) : m_payload{ std::move(payload) } {} friend class task<ResultT>; friend class abstract_task_completion_source; template<typename R, typename I> friend struct internal::task_factory; payload_ptr m_payload; }; // // a type erased version of task_completion_source. // class abstract_task_completion_source { using payload_t = internal::base_task_payload; using payload_ptr = std::shared_ptr<payload_t>; public: abstract_task_completion_source() : m_payload{} {} template<typename T> explicit abstract_task_completion_source(const task_completion_source<T>& other) : m_payload{ other.m_payload } {} template<typename T> explicit abstract_task_completion_source(task_completion_source<T>&& other) : m_payload{ std::move(other.m_payload) } {} // // Returns whether or not the current source has already been completed. // bool completed() const { return m_payload->completed(); } template<typename T> bool operator==(const task_completion_source<T>& other) { return m_payload == other.m_payload; } template<typename T> task_completion_source<T> unsafe_cast() { return task_completion_source<T>{ std::static_pointer_cast<internal::noop_task_payload<T>>(m_payload) }; } private: payload_ptr m_payload; }; // // creates a task and queues it to run on the given scheduler // template<typename SchedulerT, typename CallableT> inline auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable) -> typename internal::task_factory<typename as_expected<decltype(callable())>::result, void>::task_t { using callable_return_t = typename as_expected<decltype(callable())>::result; using wrapper = internal::input_output_wrapper<void>; internal::task_factory<callable_return_t, void> factory( wrapper::wrap_callable(std::forward<CallableT>(callable), token)); scheduler.queue([to_run = std::move(factory.to_run)]{ to_run.m_payload->run(nullptr); }); return factory.to_return; } // // creates a completed task from the given result // template<typename ResultT> inline task<typename as_expected<ResultT>::result> task_from_result(ResultT&& value) { task_completion_source<typename as_expected<ResultT>::result> result; result.complete(std::forward<ResultT>(value)); return std::move(result); } inline task<void> task_from_result() { task_completion_source<void> result; result.complete(); return std::move(result); } template<typename ResultT, typename ErrorT> inline task<ResultT> task_from_error(const ErrorT& error) { task_completion_source<ResultT> result; result.complete(std::make_error_code(error)); return std::move(result); } template<typename ResultT> inline task<ResultT> task_from_error(const std::error_code& error) { task_completion_source<ResultT> result; result.complete(error); return std::move(result); } inline task<void> when_all(gsl::span<task<void>> tasks) { if (tasks.empty()) { return task_from_result(); } struct when_all_data { std::mutex mutex; size_t pendingCount; std::error_code error; }; task_completion_source<void> result; auto data = std::make_shared<when_all_data>(); data->pendingCount = tasks.size(); for (task<void>& task : tasks) { task.then(inline_scheduler, cancellation::none(), [data, result](const expected<void>& exp) mutable { bool last = false; { std::lock_guard<std::mutex> guard{ data->mutex }; data->pendingCount -= 1; last = data->pendingCount == 0; if (exp.has_error() && !data->error) { // set the first error, as it might have cascaded data->error = exp.error(); } } if (last) // we were the last task to complete { if (data->error) { result.complete(data->error); } else { result.complete(); } } }); } return std::move(result); } template<typename T> inline task<std::vector<T>> when_all(gsl::span<task<T>> tasks) { if (tasks.empty()) { return task_from_result<std::vector<T>>(std::vector<T>()); } struct when_all_data { std::mutex mutex; size_t pendingCount; std::error_code error; std::vector<T> results; }; task_completion_source<std::vector<T>> result; auto data = std::make_shared<when_all_data>(); data->pendingCount = tasks.size(); data->results.resize(tasks.size()); //using forloop with index to be able to keep proper order of results for (auto idx = 0U; idx < data->results.size(); idx++) { tasks[idx].then(mira::inline_scheduler, cancellation::none(), [data, result, idx](const expected<T>& exp) mutable { bool last = false; { std::lock_guard<std::mutex> guard{ data->mutex }; data->pendingCount -= 1; last = data->pendingCount == 0; if (exp.has_error() && !data->error) { // set the first error, as it might have cascaded data->error = exp.error(); } if (exp.has_value()) { data->results[idx] = exp.value(); } } if (last) // we were the last task to complete { if (data->error) { result.complete(data->error); } else { result.complete(data->results); } } }); } return std::move(result); } template<typename... ArgTs> inline task<std::tuple<typename mira::void_passthrough<ArgTs>::type...>> when_all(task<ArgTs>... tasks) { using void_passthrough_tuple = std::tuple<typename mira::void_passthrough<ArgTs>::type...>; struct when_all_data { std::mutex mutex; int pending; std::error_code error; void_passthrough_tuple results; }; task_completion_source<void_passthrough_tuple> result; auto data = std::make_shared<when_all_data>(); data->pending = std::tuple_size<void_passthrough_tuple>::value; std::tuple<task<ArgTs>&...> taskrefs = std::make_tuple(std::ref(tasks)...); iterate_tuple(taskrefs, [&](auto& task, auto idx) { using task_t = std::remove_reference_t<decltype(task)>; task.then(inline_scheduler, cancellation::none(), [data, result](const expected<typename task_t::result_t>& exp) mutable { bool last = false; { std::lock_guard<std::mutex> guard{ data->mutex }; data->pending -= 1; last = data->pending == 0; internal::write_expected_to_tuple<decltype(idx)::value>(data->results, exp); if (exp.has_error() && !data->error) { // set the first error, as it might have cascaded data->error = exp.error(); } } if (last) // we were the last task to complete { if (data->error) { result.complete(data->error); } else { result.complete(std::move(data->results)); } } }); }); return std::move(result); } }
{ "alphanum_fraction": 0.5541650113, "avg_line_length": 30.204, "ext": "h", "hexsha": "a6de9fc9d4158a281c4b92c24bfc2f428b75418a", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/threading/task.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/threading/task.h", "max_line_length": 197, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/threading/task.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": 2972, "size": 15102 }
/*************************************************************************** * mgl_c.h is part of Math Graphic Library * Copyright (C) 2007 Alexey Balakin <balakin@appl.sci-nnov.ru> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 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 Library 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. * ***************************************************************************/ #ifndef _MGL_C_H_ #define _MGL_C_H_ #include <mgl/config.h> #if(MGL_USE_DOUBLE==1) typedef double mreal; #else typedef float mreal; #endif //#include <mgl/mgl_define.h> #ifdef __cplusplus extern "C" { #endif /*****************************************************************************/ //#ifdef _MGL_DATA_H_ #ifdef __cplusplus struct mglDraw; typedef mglDraw* HMDR; class mglGraph; typedef mglGraph* HMGL; class mglData; typedef mglData* HMDT; class mglParse; typedef mglParse* HMPR; #else typedef void* HMDR; typedef void* HMGL; typedef void* HMDT; typedef void* HMPR; #endif #ifndef NO_GSL #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #else struct gsl_vector; struct gsl_matrix; #endif /*****************************************************************************/ HMGL mgl_create_graph_gl(); HMGL mgl_create_graph_zb(int width, int height); HMGL mgl_create_graph_ps(int width, int height); HMGL mgl_create_graph_idtf(); #ifndef MGL_NO_WIDGET int mgl_fortran_func(HMGL gr, void *); HMGL mgl_create_graph_glut(int (*draw)(HMGL gr, void *p), const char *title, void *par); HMGL mgl_create_graph_fltk(int (*draw)(HMGL gr, void *p), const char *title, void *par); HMGL mgl_create_graph_qt(int (*draw)(HMGL gr, void *p), const char *title, void *par); HMGL mgl_create_graph_glut_dr(HMDR dr, const char *title); HMGL mgl_create_graph_fltk_dr(HMDR dr, const char *title); HMGL mgl_create_graph_qt_dr(HMDR dr, const char *title); void mgl_fltk_run(); void mgl_qt_run(); void mgl_wnd_set_delay(HMGL gr, mreal dt); void mgl_wnd_set_auto_clf(HMGL gr, int val); void mgl_wnd_set_show_mouse_pos(HMGL gr, int val); void mgl_wnd_set_clf_update(HMGL gr, int val); void mgl_wnd_toggle_alpha(HMGL gr); void mgl_wnd_toggle_light(HMGL gr); void mgl_wnd_toggle_zoom(HMGL gr); void mgl_wnd_toggle_rotate(HMGL gr); void mgl_wnd_toggle_no(HMGL gr); void mgl_wnd_update(HMGL gr); void mgl_wnd_reload(HMGL gr, int o); void mgl_wnd_adjust(HMGL gr); void mgl_wnd_next_frame(HMGL gr); void mgl_wnd_prev_frame(HMGL gr); void mgl_wnd_animation(HMGL gr); #endif void mgl_set_show_mouse_pos(HMGL gr, int enable); void mgl_get_last_mouse_pos(HMGL gr, mreal *x, mreal *y, mreal *z); void mgl_calc_xyz(HMGL gr, int xs, int ys, mreal *x, mreal *y, mreal *z); void mgl_calc_scr(HMGL gr, mreal x, mreal y, mreal z, int *xs, int *ys); //void mgl_fltk_thread(); //void mgl_qt_thread(); void mgl_update(HMGL graph); void mgl_delete_graph(HMGL graph); /*****************************************************************************/ HMDT mgl_create_data(); HMDT mgl_create_data_size(int nx, int ny, int nz); HMDT mgl_create_data_file(const char *fname); void mgl_delete_data(HMDT dat); /*****************************************************************************/ HMPR mgl_create_parser(); void mgl_delete_parser(HMPR p); void mgl_scan_func(HMPR p, const wchar_t *line); void mgl_add_param(HMPR p, int id, const char *str); void mgl_add_paramw(HMPR p, int id, const wchar_t *str); /*===!!! NOTE !!! You must not delete obtained data arrays !!!===============*/ HMDT mgl_add_var(HMPR, const char *name); /*===!!! NOTE !!! You must not delete obtained data arrays !!!===============*/ HMDT mgl_find_var(HMPR, const char *name); int mgl_parse(HMGL gr, HMPR p, const char *str, int pos); int mgl_parsew(HMGL gr, HMPR p, const wchar_t *str, int pos); void mgl_parse_text(HMGL gr, HMPR p, const char *str); void mgl_parsew_text(HMGL gr, HMPR p, const wchar_t *str); void mgl_restore_once(HMPR p); void mgl_parser_allow_setsize(HMPR p, int a); /*****************************************************************************/ /* Setup mglGraph */ /*****************************************************************************/ void mgl_set_def_param(HMGL gr); void mgl_set_palette(HMGL gr, const char *colors); void mgl_set_pal_color(HMGL graph, int n, mreal r, mreal g, mreal b); void mgl_set_pal_num(HMGL graph, int num); void mgl_set_rotated_text(HMGL graph, int rotated); void mgl_set_cut(HMGL graph, int cut); void mgl_set_cut_box(HMGL gr, mreal x1,mreal y1,mreal z1,mreal x2,mreal y2,mreal z2); void mgl_set_tick_len(HMGL graph, mreal len, mreal stt); void mgl_set_tick_stl(HMGL gr, const char *stl, const char *sub); void mgl_set_bar_width(HMGL graph, mreal width); void mgl_set_base_line_width(HMGL gr, mreal size); void mgl_set_mark_size(HMGL graph, mreal size); void mgl_set_arrow_size(HMGL graph, mreal size); void mgl_set_font_size(HMGL graph, mreal size); void mgl_set_font_def(HMGL graph, const char *fnt); void mgl_set_alpha_default(HMGL graph, mreal alpha); void mgl_set_size(HMGL graph, int width, int height); void mgl_set_axial_dir(HMGL graph, char dir); void mgl_set_meshnum(HMGL graph, int num); void mgl_set_zoom(HMGL gr, mreal x1, mreal y1, mreal x2, mreal y2); void mgl_set_plotfactor(HMGL gr, mreal val); void mgl_set_draw_face(HMGL gr, int enable); void mgl_set_scheme(HMGL gr, const char *sch); void mgl_load_font(HMGL gr, const char *name, const char *path); void mgl_copy_font(HMGL gr, HMGL gr_from); void mgl_restore_font(HMGL gr); int mgl_get_warn(HMGL gr); /*****************************************************************************/ /* Export to file or to memory */ /*****************************************************************************/ void mgl_show_image(HMGL graph, const char *viewer, int keep); void mgl_write_frame(HMGL graph, const char *fname,const char *descr); void mgl_write_bmp(HMGL graph, const char *fname,const char *descr); void mgl_write_jpg(HMGL graph, const char *fname,const char *descr); void mgl_write_png(HMGL graph, const char *fname,const char *descr); void mgl_write_png_solid(HMGL graph, const char *fname,const char *descr); void mgl_write_eps(HMGL graph, const char *fname,const char *descr); void mgl_write_svg(HMGL graph, const char *fname,const char *descr); void mgl_write_idtf(HMGL graph, const char *fname,const char *descr); void mgl_write_gif(HMGL graph, const char *fname,const char *descr); void mgl_start_gif(HMGL graph, const char *fname,int ms); void mgl_close_gif(HMGL graph); const unsigned char *mgl_get_rgb(HMGL graph); const unsigned char *mgl_get_rgba(HMGL graph); int mgl_get_width(HMGL graph); int mgl_get_height(HMGL graph); /*****************************************************************************/ /* Setup frames transparency (alpha) and lightning */ /*****************************************************************************/ int mgl_new_frame(HMGL graph); void mgl_end_frame(HMGL graph); int mgl_get_num_frame(HMGL graph); void mgl_reset_frames(HMGL graph); void mgl_set_transp_type(HMGL graph, int type); void mgl_set_transp(HMGL graph, int enable); void mgl_set_alpha(HMGL graph, int enable); void mgl_set_fog(HMGL graph, mreal d, mreal dz); void mgl_set_light(HMGL graph, int enable); void mgl_set_light_n(HMGL gr, int n, int enable); void mgl_add_light(HMGL graph, int n, mreal x, mreal y, mreal z, char c); void mgl_add_light_rgb(HMGL graph, int n, mreal x, mreal y, mreal z, int infty, mreal r, mreal g, mreal b, mreal i); void mgl_set_ambbr(HMGL gr, mreal i); /*****************************************************************************/ /* Scale and rotate */ /*****************************************************************************/ void mgl_mat_pop(HMGL gr); void mgl_mat_push(HMGL gr); void mgl_identity(HMGL graph, int rel); void mgl_clf(HMGL graph); void mgl_flush(HMGL gr); void mgl_clf_rgb(HMGL graph, mreal r, mreal g, mreal b); void mgl_subplot(HMGL graph, int nx,int ny,int m); void mgl_subplot_d(HMGL graph, int nx,int ny,int m, mreal dx, mreal dy); void mgl_subplot_s(HMGL graph, int nx,int ny,int m,const char *style); void mgl_inplot(HMGL graph, mreal x1,mreal x2,mreal y1,mreal y2); void mgl_relplot(HMGL graph, mreal x1,mreal x2,mreal y1,mreal y2); void mgl_columnplot(HMGL graph, int num, int ind); void mgl_columnplot_d(HMGL graph, int num, int ind, mreal d); void mgl_stickplot(HMGL graph, int num, int ind, mreal tet, mreal phi); void mgl_aspect(HMGL graph, mreal Ax,mreal Ay,mreal Az); void mgl_rotate(HMGL graph, mreal TetX,mreal TetZ,mreal TetY); void mgl_rotate_vector(HMGL graph, mreal Tet,mreal x,mreal y,mreal z); void mgl_perspective(HMGL graph, mreal val); /*****************************************************************************/ /* Axis functions */ /*****************************************************************************/ void mgl_adjust_ticks(HMGL graph, const char *dir); void mgl_set_ticks(HMGL graph, mreal DX, mreal DY, mreal DZ); void mgl_set_subticks(HMGL graph, int NX, int NY, int NZ); void mgl_set_ticks_dir(HMGL graph, char dir, mreal d, int ns, mreal org); void mgl_set_ticks_val(HMGL graph, char dir, int n, double val, const char *lbl, ...); void mgl_set_ticks_vals(HMGL graph, char dir, int n, mreal *val, const char **lbl); void mgl_set_caxis(HMGL graph, mreal C1,mreal C2); void mgl_set_axis(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, mreal x0, mreal y0, mreal z0); void mgl_set_axis_3d(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2); void mgl_set_axis_2d(HMGL graph, mreal x1, mreal y1, mreal x2, mreal y2); inline void mgl_set_ranges(HMGL graph, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2) { mgl_set_axis_3d(graph, x1,y1,z1,x2,y2,z2); }; void mgl_set_origin(HMGL graph, mreal x0, mreal y0, mreal z0); void mgl_set_tick_origin(HMGL graph, mreal x0, mreal y0, mreal z0); void mgl_set_crange(HMGL graph, const HMDT a, int add); void mgl_set_xrange(HMGL graph, const HMDT a, int add); void mgl_set_yrange(HMGL graph, const HMDT a, int add); void mgl_set_zrange(HMGL graph, const HMDT a, int add); void mgl_set_auto(HMGL graph, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2); void mgl_set_func(HMGL graph, const char *EqX,const char *EqY,const char *EqZ); void mgl_set_func_ext(HMGL graph, const char *EqX,const char *EqY,const char *EqZ,const char *EqA); void mgl_set_coor(HMGL gr, int how); void mgl_set_ternary(HMGL gr, int enable); void mgl_set_cutoff(HMGL graph, const char *EqC); void mgl_box(HMGL graph, int ticks); void mgl_box_str(HMGL graph, const char *col, int ticks); void mgl_box_rgb(HMGL graph, mreal r, mreal g, mreal b, int ticks); void mgl_axis(HMGL graph, const char *dir); void mgl_axis_grid(HMGL graph, const char *dir,const char *pen); void mgl_label(HMGL graph, char dir, const char *text); void mgl_label_ext(HMGL graph, char dir, const char *text, mreal pos, mreal size, mreal shift); void mgl_labelw_ext(HMGL graph, char dir, const wchar_t *text, mreal pos, mreal size, mreal shift); void mgl_label_xy(HMGL graph, mreal x, mreal y, const char *text, const char *fnt, mreal size); void mgl_labelw_xy(HMGL graph, mreal x, mreal y, const wchar_t *text, const char *fnt, mreal size); void mgl_tune_ticks(HMGL graph, int tune, mreal fact_pos); void mgl_set_xttw(HMGL graph, const wchar_t *templ); void mgl_set_yttw(HMGL graph, const wchar_t *templ); void mgl_set_zttw(HMGL graph, const wchar_t *templ); void mgl_set_cttw(HMGL graph, const wchar_t *templ); void mgl_set_xtt(HMGL graph, const char *templ); void mgl_set_ytt(HMGL graph, const char *templ); void mgl_set_ztt(HMGL graph, const char *templ); void mgl_set_ctt(HMGL graph, const char *templ); /*****************************************************************************/ /* Simple drawing */ /*****************************************************************************/ void mgl_ball(HMGL graph, mreal x,mreal y,mreal z); void mgl_ball_rgb(HMGL graph, mreal x, mreal y, mreal z, mreal r, mreal g, mreal b, mreal alpha); void mgl_ball_str(HMGL graph, mreal x, mreal y, mreal z, char col); void mgl_line(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, const char *pen,int n); void mgl_facex(HMGL graph, mreal x0, mreal y0, mreal z0, mreal wy, mreal wz, const char *stl, mreal dx, mreal dy); void mgl_facey(HMGL graph, mreal x0, mreal y0, mreal z0, mreal wx, mreal wz, const char *stl, mreal dx, mreal dy); void mgl_facez(HMGL graph, mreal x0, mreal y0, mreal z0, mreal wx, mreal wy, const char *stl, mreal dx, mreal dy); void mgl_curve(HMGL graph, mreal x1, mreal y1, mreal z1, mreal dx1, mreal dy1, mreal dz1, mreal x2, mreal y2, mreal z2, mreal dx2, mreal dy2, mreal dz2, const char *pen,int n); void mgl_puts(HMGL graph, mreal x, mreal y, mreal z,const char *text); void mgl_putsw(HMGL graph, mreal x, mreal y, mreal z,const wchar_t *text); void mgl_puts_dir(HMGL graph, mreal x, mreal y, mreal z, mreal dx, mreal dy, mreal dz, const char *text, mreal size); void mgl_putsw_dir(HMGL graph, mreal x, mreal y, mreal z, mreal dx, mreal dy, mreal dz, const wchar_t *text, mreal size); void mgl_text(HMGL graph, mreal x, mreal y, mreal z,const char *text); void mgl_title(HMGL graph, const char *text, const char *fnt, mreal size); void mgl_titlew(HMGL graph, const wchar_t *text, const char *fnt, mreal size); void mgl_putsw_ext(HMGL graph, mreal x, mreal y, mreal z,const wchar_t *text,const char *font,mreal size,char dir); void mgl_puts_ext(HMGL graph, mreal x, mreal y, mreal z,const char *text,const char *font,mreal size,char dir); void mgl_text_ext(HMGL graph, mreal x, mreal y, mreal z,const char *text,const char *font,mreal size,char dir); void mgl_colorbar(HMGL graph, const char *sch,int where); void mgl_colorbar_ext(HMGL graph, const char *sch, int where, mreal x, mreal y, mreal w, mreal h); void mgl_colorbar_val(HMGL graph, const HMDT dat, const char *sch,int where); void mgl_simple_plot(HMGL graph, const HMDT a, int type, const char *stl); void mgl_add_legend(HMGL graph, const char *text,const char *style); void mgl_add_legendw(HMGL graph, const wchar_t *text,const char *style); void mgl_clear_legend(HMGL graph); void mgl_legend_xy(HMGL graph, mreal x, mreal y, const char *font, mreal size, mreal llen); void mgl_legend(HMGL graph, int where, const char *font, mreal size, mreal llen); void mgl_set_legend_box(HMGL gr, int enable); void mgl_set_legend_marks(HMGL gr, int num); /*****************************************************************************/ /* 1D plotting functions */ /*****************************************************************************/ void mgl_fplot(HMGL graph, const char *fy, const char *stl, int n); void mgl_fplot_xyz(HMGL graph, const char *fx, const char *fy, const char *fz, const char *stl, int n); void mgl_plot_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen); void mgl_plot_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen); void mgl_plot(HMGL graph, const HMDT y, const char *pen); void mgl_radar(HMGL graph, const HMDT a, const char *pen, mreal r); void mgl_boxplot_xy(HMGL graph, const HMDT x, const HMDT a, const char *pen); void mgl_boxplot(HMGL graph, const HMDT a, const char *pen); void mgl_tens_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *pen); void mgl_tens_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT c, const char *pen); void mgl_tens(HMGL graph, const HMDT y, const HMDT c, const char *pen); void mgl_area_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen); void mgl_area_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen); void mgl_area_xys(HMGL graph, const HMDT x, const HMDT y, const char *pen); void mgl_area_s(HMGL graph, const HMDT y, const char *pen); void mgl_area(HMGL graph, const HMDT y, const char *pen); void mgl_region_xy(HMGL graph, const HMDT x, const HMDT y1, const HMDT y2, const char *pen, int inside); void mgl_region(HMGL graph, const HMDT y1, const HMDT y2, const char *pen, int inside); void mgl_mark(HMGL graph, mreal x,mreal y,mreal z,char mark); void mgl_stem_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen); void mgl_stem_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen); void mgl_stem(HMGL graph, const HMDT y, const char *pen); void mgl_step_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen); void mgl_step_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen); void mgl_step(HMGL graph, const HMDT y, const char *pen); void mgl_bars_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *pen); void mgl_bars_xy(HMGL graph, const HMDT x, const HMDT y, const char *pen); void mgl_bars(HMGL graph, const HMDT y, const char *pen); void mgl_barh_yx(HMGL graph, const HMDT y, const HMDT v, const char *pen); void mgl_barh(HMGL graph, const HMDT v, const char *pen); /*****************************************************************************/ /* Advanced 1D plotting functions */ /*****************************************************************************/ void mgl_torus(HMGL graph, const HMDT r, const HMDT z, const char *pen); void mgl_text_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z,const char *text, const char *font, mreal size); void mgl_text_xy(HMGL graph, const HMDT x, const HMDT y, const char *text, const char *font, mreal size); void mgl_text_y(HMGL graph, const HMDT y, const char *text, const char *font, mreal size); void mgl_chart(HMGL graph, const HMDT a, const char *col); void mgl_error(HMGL graph, const HMDT y, const HMDT ey, const char *pen); void mgl_error_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ey, const char *pen); void mgl_error_exy(HMGL graph, const HMDT x, const HMDT y, const HMDT ex, const HMDT ey, const char *pen); void mgl_mark_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *pen); void mgl_mark_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const char *pen); void mgl_mark_y(HMGL graph, const HMDT y, const HMDT r, const char *pen); void mgl_tube_xyzr(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *pen); void mgl_tube_xyr(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const char *pen); void mgl_tube_r(HMGL graph, const HMDT y, const HMDT r, const char *pen); void mgl_tube_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, mreal r, const char *pen); void mgl_tube_xy(HMGL graph, const HMDT x, const HMDT y, mreal r, const char *penl); void mgl_tube(HMGL graph, const HMDT y, mreal r, const char *pen); void mgl_textmark_xyzr(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *text, const char *fnt); void mgl_textmark_xyr(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const char *text, const char *fnt); void mgl_textmark_yr(HMGL graph, const HMDT y, const HMDT r, const char *text, const char *fnt); void mgl_textmark(HMGL graph, const HMDT y, const char *text, const char *fnt); void mgl_textmarkw_xyzr(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const wchar_t *text, const char *fnt); void mgl_textmarkw_xyr(HMGL graph, const HMDT x, const HMDT y, const HMDT r, const wchar_t *text, const char *fnt); void mgl_textmarkw_yr(HMGL graph, const HMDT y, const HMDT r, const wchar_t *text, const char *fnt); void mgl_textmarkw(HMGL graph, const HMDT y, const wchar_t *text, const char *fnt); /*****************************************************************************/ /* 2D plotting functions */ /*****************************************************************************/ void mgl_fsurf(HMGL graph, const char *fz, const char *stl, int n); void mgl_fsurf_xyz(HMGL graph, const char *fx, const char *fy, const char *fz, const char *stl, int n); void mgl_grid_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *stl,mreal zVal); void mgl_grid(HMGL graph, const HMDT a,const char *stl,mreal zVal); void mgl_mesh_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_mesh(HMGL graph, const HMDT z, const char *sch); void mgl_fall_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_fall(HMGL graph, const HMDT z, const char *sch); void mgl_belt_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_belt(HMGL graph, const HMDT z, const char *sch); void mgl_surf_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_surf(HMGL graph, const HMDT z, const char *sch); void mgl_dens_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch,mreal zVal); void mgl_dens(HMGL graph, const HMDT z, const char *sch,mreal zVal); void mgl_boxs_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch,mreal zVal); void mgl_boxs(HMGL graph, const HMDT z, const char *sch,mreal zVal); void mgl_tile_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_tile(HMGL graph, const HMDT z, const char *sch); void mgl_tiles_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT r, const char *sch); void mgl_tiles(HMGL graph, const HMDT z, const HMDT r, const char *sch); void mgl_cont_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal); void mgl_cont_val(HMGL graph, const HMDT v, const HMDT z, const char *sch,mreal zVal); void mgl_cont_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch, int Num, mreal zVal); void mgl_cont(HMGL graph, const HMDT z, const char *sch, int Num, mreal zVal); void mgl_contf_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal); void mgl_contf_val(HMGL graph, const HMDT v, const HMDT z, const char *sch,mreal zVal); void mgl_contf_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch, int Num, mreal zVal); void mgl_contf(HMGL graph, const HMDT z, const char *sch, int Num, mreal zVal); void mgl_contd_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal); void mgl_contd_val(HMGL graph, const HMDT v, const HMDT z, const char *sch,mreal zVal); void mgl_contd_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const char *sch, int Num, mreal zVal); void mgl_contd(HMGL graph, const HMDT z, const char *sch, int Num, mreal zVal); void mgl_axial_xy_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT a, const char *sch); void mgl_axial_val(HMGL graph, const HMDT v, const HMDT a, const char *sch); void mgl_axial_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT a, const char *sch, int Num); void mgl_axial(HMGL graph, const HMDT a, const char *sch, int Num); /*****************************************************************************/ /* Dual plotting functions */ /*****************************************************************************/ void mgl_surfc_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch); void mgl_surfc(HMGL graph, const HMDT z, const HMDT c, const char *sch); void mgl_surfa_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch); void mgl_surfa(HMGL graph, const HMDT z, const HMDT c, const char *sch); void mgl_stfa_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT re, const HMDT im, int dn, const char *sch, mreal zVal); void mgl_stfa(HMGL graph, const HMDT re, const HMDT im, int dn, const char *sch, mreal zVal); void mgl_traj_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal,mreal len); void mgl_traj_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch,mreal len); void mgl_vect_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal,int flag); void mgl_vect_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch,mreal zVal,int flag); void mgl_vectl_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal); void mgl_vectl_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch,mreal zVal); void mgl_vectc_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal); void mgl_vectc_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch,mreal zVal); void mgl_vect_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch,int flag); void mgl_vect_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch,int flag); void mgl_vectl_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch); void mgl_vectl_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch); void mgl_vectc_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch); void mgl_vectc_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch); void mgl_map_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT a, const HMDT b, const char *sch, int ks, int pnts); void mgl_map(HMGL graph, const HMDT a, const HMDT b, const char *sch, int ks, int pnts); void mgl_surf3a_xyz_val(HMGL graph, mreal Val, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b, const char *stl); void mgl_surf3a_val(HMGL graph, mreal Val, const HMDT a, const HMDT b, const char *stl); void mgl_surf3a_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b, const char *stl, int num); void mgl_surf3a(HMGL graph, const HMDT a, const HMDT b, const char *stl, int num); void mgl_surf3c_xyz_val(HMGL graph, mreal Val, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b, const char *stl); void mgl_surf3c_val(HMGL graph, mreal Val, const HMDT a, const HMDT b, const char *stl); void mgl_surf3c_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT b, const char *stl, int num); void mgl_surf3c(HMGL graph, const HMDT a, const HMDT b, const char *stl, int num); void mgl_flow_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch, int num, int central, mreal zVal); void mgl_flow_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch, int num, int central, mreal zVal); void mgl_flow_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, int num, int central); void mgl_flow_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, int num, int central); void mgl_flowp_xy(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch); void mgl_flowp_2d(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT ax, const HMDT ay, const char *sch); void mgl_flowp_xyz(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch); void mgl_flowp_3d(HMGL graph, mreal x0, mreal y0, mreal z0, const HMDT ax, const HMDT ay, const HMDT az, const char *sch); void mgl_pipe_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch, mreal r0, int num, int central, mreal zVal); void mgl_pipe_2d(HMGL graph, const HMDT ax, const HMDT ay, const char *sch, mreal r0, int num, int central, mreal zVal); void mgl_pipe_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, mreal r0, int num, int central); void mgl_pipe_3d(HMGL graph, const HMDT ax, const HMDT ay, const HMDT az, const char *sch, mreal r0, int num, int central); void mgl_dew_xy(HMGL gr, const HMDT x, const HMDT y, const HMDT ax, const HMDT ay, const char *sch,mreal zVal); void mgl_dew_2d(HMGL gr, const HMDT ax, const HMDT ay, const char *sch,mreal zVal); void mgl_grad_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT ph, const char *sch, int num); void mgl_grad_xy(HMGL graph, const HMDT x, const HMDT y, const HMDT ph, const char *sch, int num, mreal zVal); void mgl_grad(HMGL graph, const HMDT ph, const char *sch, int num, mreal zVal); /*****************************************************************************/ /* 3D plotting functions */ /*****************************************************************************/ void mgl_grid3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *stl); void mgl_grid3(HMGL graph, const HMDT a, char dir, int sVal, const char *stl); void mgl_grid3_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl); void mgl_grid3_all(HMGL graph, const HMDT a, const char *stl); void mgl_dens3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *stl); void mgl_dens3(HMGL graph, const HMDT a, char dir, int sVal, const char *stl); void mgl_dens3_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl); void mgl_dens3_all(HMGL graph, const HMDT a, const char *stl); void mgl_surf3_xyz_val(HMGL graph, mreal Val, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl); void mgl_surf3_val(HMGL graph, mreal Val, const HMDT a, const char *stl); void mgl_surf3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl, int num); void mgl_surf3(HMGL graph, const HMDT a, const char *stl, int num); void mgl_cont3_xyz_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch); void mgl_cont3_val(HMGL graph, const HMDT v, const HMDT a, char dir, int sVal, const char *sch); void mgl_cont3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch, int Num); void mgl_cont3(HMGL graph, const HMDT a, char dir, int sVal, const char *sch, int Num); void mgl_cont_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *sch, int Num); void mgl_cont_all(HMGL graph, const HMDT a, const char *sch, int Num); void mgl_cloudp_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl, mreal alpha); void mgl_cloudp(HMGL graph, const HMDT a, const char *stl, mreal alpha); void mgl_cloud_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *stl, mreal alpha); void mgl_cloud(HMGL graph, const HMDT a, const char *stl, mreal alpha); void mgl_contf3_xyz_val(HMGL graph, const HMDT v, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch); void mgl_contf3_val(HMGL graph, const HMDT v, const HMDT a, char dir, int sVal, const char *sch); void mgl_contf3_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, char dir, int sVal, const char *sch, int Num); void mgl_contf3(HMGL graph, const HMDT a, char dir, int sVal, const char *sch, int Num); void mgl_contf_all_xyz(HMGL graph, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *sch, int Num); void mgl_contf_all(HMGL graph, const HMDT a, const char *sch, int Num); void mgl_beam_val(HMGL graph, mreal Val, const HMDT tr, const HMDT g1, const HMDT g2, const HMDT a, mreal r, const char *stl, int norm); void mgl_beam(HMGL graph, const HMDT tr, const HMDT g1, const HMDT g2, const HMDT a, mreal r, const char *stl, int norm, int num); /*****************************************************************************/ /* Triangular plotting functions */ /*****************************************************************************/ void mgl_triplot_xyzc(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch); void mgl_triplot_xyz(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_triplot_xy(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const char *sch, mreal zVal); void mgl_quadplot_xyzc(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch); void mgl_quadplot_xyz(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_quadplot_xy(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const char *sch, mreal zVal); void mgl_tricont_xyzcv(HMGL gr, const HMDT v, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch, mreal zVal); void mgl_tricont_xyzv(HMGL gr, const HMDT v, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal zVal); void mgl_tricont_xyzc(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const HMDT c, const char *sch, int n, mreal zVal); void mgl_tricont_xyz(HMGL gr, const HMDT nums, const HMDT x, const HMDT y, const HMDT z, const char *sch, int n, mreal zVal); void mgl_dots(HMGL gr, const HMDT x, const HMDT y, const HMDT z, const char *sch); void mgl_dots_a(HMGL gr, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *sch); void mgl_dots_tr(HMGL gr, const HMDT tr, const char *sch); void mgl_crust(HMGL gr, const HMDT x, const HMDT y, const HMDT z, const char *sch, mreal er); void mgl_crust_tr(HMGL gr, const HMDT tr, const char *sch, mreal er); /*****************************************************************************/ /* Combined plotting functions */ /*****************************************************************************/ void mgl_dens_x(HMGL graph, const HMDT a, const char *stl, mreal sVal); void mgl_dens_y(HMGL graph, const HMDT a, const char *stl, mreal sVal); void mgl_dens_z(HMGL graph, const HMDT a, const char *stl, mreal sVal); void mgl_cont_x(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num); void mgl_cont_y(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num); void mgl_cont_z(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num); void mgl_cont_x_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal); void mgl_cont_y_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal); void mgl_cont_z_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal); void mgl_contf_x(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num); void mgl_contf_y(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num); void mgl_contf_z(HMGL graph, const HMDT a, const char *stl, mreal sVal, int Num); void mgl_contf_x_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal); void mgl_contf_y_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal); void mgl_contf_z_val(HMGL graph, const HMDT v, const HMDT a, const char *stl, mreal sVal); /*****************************************************************************/ /* Data creation functions */ /*****************************************************************************/ void mgl_data_rearrange(HMDT dat, int mx, int my, int mz); void mgl_data_set_float(HMDT dat, const float *A,int NX,int NY,int NZ); void mgl_data_set_double(HMDT dat, const double *A,int NX,int NY,int NZ); void mgl_data_set_float2(HMDT d, const float **A,int N1,int N2); void mgl_data_set_double2(HMDT d, const double **A,int N1,int N2); void mgl_data_set_float3(HMDT d, const float ***A,int N1,int N2,int N3); void mgl_data_set_double3(HMDT d, const double ***A,int N1,int N2,int N3); void mgl_data_set(HMDT dat, const HMDT a); void mgl_data_set_vector(HMDT dat, gsl_vector *v); void mgl_data_set_matrix(HMDT dat, gsl_matrix *m); mreal mgl_data_get_value(const HMDT dat, int i, int j, int k); int mgl_data_get_nx(const HMDT dat); int mgl_data_get_ny(const HMDT dat); int mgl_data_get_nz(const HMDT dat); void mgl_data_set_value(HMDT dat, mreal v, int i, int j, int k); void mgl_data_set_values(HMDT dat, const char *val, int nx, int ny, int nz); int mgl_data_read(HMDT dat, const char *fname); int mgl_data_read_mat(HMDT dat, const char *fname, int dim); int mgl_data_read_dim(HMDT dat, const char *fname,int mx,int my,int mz); void mgl_data_save(HMDT dat, const char *fname,int ns); void mgl_data_export(HMDT dat, const char *fname, const char *scheme,mreal v1,mreal v2,int ns); void mgl_data_import(HMDT dat, const char *fname, const char *scheme,mreal v1,mreal v2); void mgl_data_create(HMDT dat, int nx,int ny,int nz); void mgl_data_transpose(HMDT dat, const char *dim); void mgl_data_norm(HMDT dat, mreal v1,mreal v2,int sym,int dim); void mgl_data_norm_slice(HMDT dat, mreal v1,mreal v2,char dir,int keep_en,int sym); HMDT mgl_data_subdata(const HMDT dat, int xx,int yy,int zz); HMDT mgl_data_subdata_ext(const HMDT dat, const HMDT xx, const HMDT yy, const HMDT zz); HMDT mgl_data_column(const HMDT dat, const char *eq); void mgl_data_set_id(HMDT d, const char *id); void mgl_data_fill(HMDT dat, mreal x1,mreal x2,char dir); void mgl_data_fill_eq(HMGL gr, HMDT dat, const char *eq, const HMDT vdat, const HMDT wdat); void mgl_data_put_val(HMDT dat, mreal val, int i, int j, int k); void mgl_data_put_dat(HMDT dat, const HMDT val, int i, int j, int k); void mgl_data_modify(HMDT dat, const char *eq,int dim); void mgl_data_modify_vw(HMDT dat, const char *eq,const HMDT vdat,const HMDT wdat); void mgl_data_squeeze(HMDT dat, int rx,int ry,int rz,int smooth); mreal mgl_data_max(const HMDT dat); mreal mgl_data_min(const HMDT dat); mreal *mgl_data_value(HMDT dat, int i,int j,int k); const mreal *mgl_data_data(const HMDT dat); mreal mgl_data_first(const HMDT dat, const char *cond, int *i, int *j, int *k); mreal mgl_data_last(const HMDT dat, const char *cond, int *i, int *j, int *k); int mgl_data_find(const HMDT dat, const char *cond, char dir, int i, int j, int k); int mgl_data_find_any(const HMDT dat, const char *cond); mreal mgl_data_max_int(const HMDT dat, int *i, int *j, int *k); mreal mgl_data_max_real(const HMDT dat, mreal *x, mreal *y, mreal *z); mreal mgl_data_min_int(const HMDT dat, int *i, int *j, int *k); mreal mgl_data_min_real(const HMDT dat, mreal *x, mreal *y, mreal *z); mreal mgl_data_momentum_mw(const HMDT dat, char dir, mreal *m, mreal *w); HMDT mgl_data_combine(const HMDT dat1, const HMDT dat2); void mgl_data_extend(HMDT dat, int n1, int n2); void mgl_data_insert(HMDT dat, char dir, int at, int num); void mgl_data_delete(HMDT dat, char dir, int at, int num); /*****************************************************************************/ /* Data manipulation functions */ /*****************************************************************************/ void mgl_data_smooth(HMDT dat, int Type,mreal delta,const char *dirs); HMDT mgl_data_sum(const HMDT dat, const char *dir); HMDT mgl_data_max_dir(const HMDT dat, const char *dir); HMDT mgl_data_min_dir(const HMDT dat, const char *dir); void mgl_data_cumsum(HMDT dat, const char *dir); void mgl_data_integral(HMDT dat, const char *dir); void mgl_data_diff(HMDT dat, const char *dir); void mgl_data_diff_par(HMDT dat, const HMDT v1, const HMDT v2, const HMDT v3); void mgl_data_diff2(HMDT dat, const char *dir); void mgl_data_swap(HMDT dat, const char *dir); void mgl_data_roll(HMDT dat, char dir, int num); void mgl_data_mirror(HMDT dat, const char *dir); void mgl_data_hankel(HMDT dat, const char *dir); void mgl_data_sinfft(HMDT dat, const char *dir); void mgl_data_cosfft(HMDT dat, const char *dir); void mgl_data_fill_sample(HMDT dat, int num, const char *how); mreal mgl_data_spline(const HMDT dat, mreal x,mreal y,mreal z); mreal mgl_data_spline1(const HMDT dat, mreal x,mreal y,mreal z); mreal mgl_data_linear(const HMDT dat, mreal x,mreal y,mreal z); mreal mgl_data_linear1(const HMDT dat, mreal x,mreal y,mreal z); HMDT mgl_data_resize(const HMDT dat, int mx,int my,int mz); HMDT mgl_data_resize_box(const HMDT dat, int mx,int my,int mz,mreal x1,mreal x2, mreal y1,mreal y2,mreal z1,mreal z2); HMDT mgl_data_hist(const HMDT dat, int n, mreal v1, mreal v2, int nsub); HMDT mgl_data_hist_w(const HMDT dat, const HMDT weight, int n, mreal v1, mreal v2, int nsub); HMDT mgl_data_momentum(const HMDT dat, char dir, const char *how); HMDT mgl_data_evaluate_i(const HMDT dat, const HMDT idat, int norm); HMDT mgl_data_evaluate_ij(const HMDT dat, const HMDT idat, const HMDT jdat, int norm); HMDT mgl_data_evaluate_ijk(const HMDT dat, const HMDT idat, const HMDT jdat, const HMDT kdat, int norm); void mgl_data_envelop(HMDT dat, char dir); void mgl_data_sew(HMDT dat, const char *dirs, mreal da); void mgl_data_crop(HMDT dat, int n1, int n2, char dir); /*****************************************************************************/ /* Data operations */ /*****************************************************************************/ void mgl_data_mul_dat(HMDT dat, const HMDT d); void mgl_data_div_dat(HMDT dat, const HMDT d); void mgl_data_add_dat(HMDT dat, const HMDT d); void mgl_data_sub_dat(HMDT dat, const HMDT d); void mgl_data_mul_num(HMDT dat, mreal d); void mgl_data_div_num(HMDT dat, mreal d); void mgl_data_add_num(HMDT dat, mreal d); void mgl_data_sub_num(HMDT dat, mreal d); /*****************************************************************************/ /* Nonlinear fitting */ /*****************************************************************************/ void mgl_hist_x(HMGL gr, HMDT res, const HMDT x, const HMDT a); void mgl_hist_xy(HMGL gr, HMDT res, const HMDT x, const HMDT y, const HMDT a); void mgl_hist_xyz(HMGL gr, HMDT res, const HMDT x, const HMDT y, const HMDT z, const HMDT a); /*****************************************************************************/ /* Nonlinear fitting */ /*****************************************************************************/ mreal mgl_fit_1(HMGL gr, HMDT fit, const HMDT y, const char *eq, const char *var, mreal *ini); mreal mgl_fit_2(HMGL gr, HMDT fit, const HMDT z, const char *eq, const char *var, mreal *ini); mreal mgl_fit_3(HMGL gr, HMDT fit, const HMDT a, const char *eq, const char *var, mreal *ini); mreal mgl_fit_xy(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const char *eq, const char *var, mreal *ini); mreal mgl_fit_xyz(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const char *eq, const char *var, mreal *ini); mreal mgl_fit_xyza(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *eq, const char *var, mreal *ini); mreal mgl_fit_ys(HMGL gr, HMDT fit, const HMDT y, const HMDT s, const char *eq, const char *var, mreal *ini); mreal mgl_fit_xys(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT s, const char *eq, const char *var, mreal *ini); mreal mgl_fit_xyzs(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT s, const char *eq, const char *var, mreal *ini); mreal mgl_fit_xyzas(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT s, const char *eq, const char *var, mreal *ini); mreal mgl_fit_1_d(HMGL gr, HMDT fit, const HMDT y, const char *eq, const char *var, HMDT ini); mreal mgl_fit_2_d(HMGL gr, HMDT fit, const HMDT z, const char *eq, const char *var, HMDT ini); mreal mgl_fit_3_d(HMGL gr, HMDT fit, const HMDT a, const char *eq, const char *var, HMDT ini); mreal mgl_fit_xy_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const char *eq, const char *var, HMDT ini); mreal mgl_fit_xyz_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const char *eq, const char *var, HMDT ini); mreal mgl_fit_xyza_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const char *eq, const char *var, HMDT ini); mreal mgl_fit_ys_d(HMGL gr, HMDT fit, const HMDT y, const HMDT s, const char *eq, const char *var, HMDT ini); mreal mgl_fit_xys_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT s, const char *eq, const char *var, HMDT ini); mreal mgl_fit_xyzs_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT s, const char *eq, const char *var, HMDT ini); mreal mgl_fit_xyzas_d(HMGL gr, HMDT fit, const HMDT x, const HMDT y, const HMDT z, const HMDT a, const HMDT s, const char *eq, const char *var, HMDT ini); void mgl_puts_fit(HMGL gr, mreal x, mreal y, mreal z, const char *prefix, const char *font, mreal size); const char *mgl_get_fit(HMGL gr); /*****************************************************************************/ void mgl_sphere(HMGL graph, mreal x, mreal y, mreal z, mreal r, const char *stl); void mgl_drop(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, mreal r, const char *stl, mreal shift, mreal ap); void mgl_cone(HMGL graph, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, mreal r1, mreal r2, const char *stl, int edge); HMDT mgl_pde_solve(HMGL gr, const char *ham, const HMDT ini_re, const HMDT ini_im, mreal dz, mreal k0); HMDT mgl_qo2d_solve(const char *ham, const HMDT ini_re, const HMDT ini_im, const HMDT ray, mreal r, mreal k0, HMDT xx, HMDT yy); HMDT mgl_af2d_solve(const char *ham, const HMDT ini_re, const HMDT ini_im, const HMDT ray, mreal r, mreal k0, HMDT xx, HMDT yy); HMDT mgl_ray_trace(const char *ham, mreal x0, mreal y0, mreal z0, mreal px, mreal py, mreal pz, mreal dt, mreal tmax); HMDT mgl_jacobian_2d(const HMDT x, const HMDT y); HMDT mgl_jacobian_3d(const HMDT x, const HMDT y, const HMDT z); HMDT mgl_transform_a(const HMDT am, const HMDT ph, const char *tr); HMDT mgl_transform(const HMDT re, const HMDT im, const char *tr); HMDT mgl_data_stfa(const HMDT re, const HMDT im, int dn, char dir); #ifdef __cplusplus } #endif #endif /* _mgl_c_h_ */
{ "alphanum_fraction": 0.6844536647, "avg_line_length": 69.4754829123, "ext": "h", "hexsha": "80b2f1fb8b765bb8ddbeba267c216b9360355870", "lang": "C", "max_forks_count": 17, "max_forks_repo_forks_event_max_datetime": "2022-01-20T15:00:57.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:38:03.000Z", "max_forks_repo_head_hexsha": "1146f0c683f3d3487cf5524d7d9d7dc01b20aec9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "xuminic/iup-porting", "max_forks_repo_path": "iup/srcmglplot/mgl/mgl_c.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1146f0c683f3d3487cf5524d7d9d7dc01b20aec9", "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": "xuminic/iup-porting", "max_issues_repo_path": "iup/srcmglplot/mgl/mgl_c.h", "max_line_length": 176, "max_stars_count": 68, "max_stars_repo_head_hexsha": "1146f0c683f3d3487cf5524d7d9d7dc01b20aec9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "xuminic/iup-porting", "max_stars_repo_path": "iup/srcmglplot/mgl/mgl_c.h", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:01:40.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-21T11:06:38.000Z", "num_tokens": 15427, "size": 46757 }
/** * @file DiscreteRangeDecorators.h * * @brief This file contains some decorator functions for DiscreteRange * types * * @author Stefan Reinhold * @copyright Copyright (C) 2018 Stefan Reinhold -- All Rights Reserved. * You may use, distribute and modify this code under the terms of the * AFL 3.0 license; see LICENSE for full license details. */ #include "DiscreteRange.h" #include <Eigen/Core> #include <gsl/gsl> namespace CortidQCT { namespace Internal { /** * @brief Returns all element of the given discrete range as a vector * @param range DiscreteRange object * @return An Eigen vector containing all element of `range` */ template <class T> Eigen::Matrix<T, Eigen::Dynamic, 1> discreteRangeElementVector(DiscreteRange<T> const &range) { using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>; Vector t(gsl::narrow<Eigen::Index>(range.numElements())); for (auto i = 0; i < t.rows(); ++i) { t(i) = range.min + static_cast<T>(i) * range.stride; } return t; } } // namespace Internal } // namespace CortidQCT
{ "alphanum_fraction": 0.6943396226, "avg_line_length": 25.2380952381, "ext": "h", "hexsha": "ec0393b7fbc87c4704527115aa6fc0513353f9e5", "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": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_forks_repo_licenses": [ "AFL-3.0" ], "max_forks_repo_name": "ithron/CortidQCT", "max_forks_repo_path": "lib/DiscreteRangeDecorators.h", "max_issues_count": 28, "max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z", "max_issues_repo_licenses": [ "AFL-3.0" ], "max_issues_repo_name": "ithron/CortidQCT", "max_issues_repo_path": "lib/DiscreteRangeDecorators.h", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_stars_repo_licenses": [ "AFL-3.0" ], "max_stars_repo_name": "ithron/CortidQCT", "max_stars_repo_path": "lib/DiscreteRangeDecorators.h", "max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z", "num_tokens": 280, "size": 1060 }
/* Copyright (c) 2015, Mina Kamel, ASL, ETH Zurich, Switzerland You can contact the author at <mina.kamel@mavt.ethz.ch> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of ETHZ-ASL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ETHZ-ASL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INCLUDE_MAV_NONLINEAR_MPC_NONLINEAR_MPC_H_ #define INCLUDE_MAV_NONLINEAR_MPC_NONLINEAR_MPC_H_ #include <ros/ros.h> #include <Eigen/Eigen> #include <mav_msgs/conversions.h> #include <mav_msgs/eigen_mav_msgs.h> #include <stdio.h> #include <mav_control_interface/mpc_queue.h> #include "acado_common.h" #include "acado_auxiliary_functions.h" #include <mav_disturbance_observer/KF_disturbance_observer.h> #include <std_srvs/Empty.h> #include <lapacke.h> ACADOvariables acadoVariables; ACADOworkspace acadoWorkspace; namespace mav_control { lapack_logical select_lhp(const double *real, const double *imag) { return *real < 0.0; } class NonlinearModelPredictiveControl { public: NonlinearModelPredictiveControl(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh); ~NonlinearModelPredictiveControl(); // Dynamic parameters void setPositionPenality(const Eigen::Vector3d& q_position) { q_position_ = q_position; } void setVelocityPenality(const Eigen::Vector3d& q_velocity) { q_velocity_ = q_velocity; } void setAttitudePenality(const Eigen::Vector2d& q_attitude) { q_attitude_ = q_attitude; } void setCommandPenality(const Eigen::Vector3d& r_command) { r_command_ = r_command; } void setYawGain(double K_yaw) { K_yaw_ = K_yaw; } void setAltitudeIntratorGain(double Ki_altitude) { Ki_altitude_ = Ki_altitude; } void setXYIntratorGain(double Ki_xy) { Ki_xy_ = Ki_xy; } void setEnableOffsetFree(bool enable_offset_free) { enable_offset_free_ = enable_offset_free; } void setEnableIntegrator(bool enable_integrator) { enable_integrator_ = enable_integrator; } void setControlLimits(const Eigen::VectorXd& control_limits) { //roll_max, pitch_max, yaw_rate_max, thrust_min and thrust_max roll_limit_ = control_limits(0); pitch_limit_ = control_limits(1); yaw_rate_limit_ = control_limits(2); thrust_min_ = control_limits(3); thrust_max_ = control_limits(4); } void applyParameters(); double getMass() const { return mass_; } // get reference and predicted state bool getCurrentReference(mav_msgs::EigenTrajectoryPoint* reference) const; bool getCurrentReference(mav_msgs::EigenTrajectoryPointDeque* reference) const; bool getPredictedState(mav_msgs::EigenTrajectoryPointDeque* predicted_state) const; // set odom and commands void setOdometry(const mav_msgs::EigenOdometry& odometry); void setCommandTrajectoryPoint(const mav_msgs::EigenTrajectoryPoint& command_trajectory); void setCommandTrajectory(const mav_msgs::EigenTrajectoryPointDeque& command_trajectory); // compute control input void calculateRollPitchYawrateThrustCommand(Eigen::Vector4d* ref_attitude_thrust); EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: // constants static constexpr double kGravity = 9.8066; static constexpr int kDisturbanceSize = 3; // ros node handles ros::NodeHandle nh_, private_nh_; // reset integrator service ros::ServiceServer reset_integrator_service_server_; bool resetIntegratorServiceCallback(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res); // sampling time parameters void initializeParameters(); bool initialized_parameters_; // sampling time parameters double sampling_time_; double prediction_sampling_time_; // system model parameters double mass_; double roll_time_constant_; double roll_gain_; double pitch_time_constant_; double pitch_gain_; Eigen::Vector3d drag_coefficients_; // controller parameters // state penalty Eigen::Vector3d q_position_; Eigen::Vector3d q_velocity_; Eigen::Vector2d q_attitude_; // control penalty Eigen::Vector3d r_command_; // yaw P gain double K_yaw_; // error integrator bool enable_integrator_; double Ki_altitude_; double Ki_xy_; double antiwindup_ball_; Eigen::Vector3d position_error_integration_; double position_error_integration_limit_; // control input limits double roll_limit_; double pitch_limit_; double yaw_rate_limit_; double thrust_min_; double thrust_max_; // reference queue MPCQueue mpc_queue_; Vector3dDeque position_ref_, velocity_ref_, acceleration_ref_; std::deque<double> yaw_ref_, yaw_rate_ref_; // solver matrices Eigen::Matrix<double, ACADO_NY, ACADO_NY> W_; Eigen::Matrix<double, ACADO_NYN, ACADO_NYN> WN_; Eigen::Matrix<double, ACADO_N + 1, ACADO_NX> state_; Eigen::Matrix<double, ACADO_N, ACADO_NU> input_; Eigen::Matrix<double, ACADO_N, ACADO_NY> reference_; Eigen::Matrix<double, 1, ACADO_NYN> referenceN_; Eigen::Matrix<double, ACADO_N + 1, ACADO_NOD> acado_online_data_; // disturbance observer bool enable_offset_free_; KFDisturbanceObserver disturbance_observer_; // commands Eigen::Vector4d command_roll_pitch_yaw_thrust_; // debug info bool verbose_; double solve_time_average_; // most recent odometry information mav_msgs::EigenOdometry odometry_; bool received_first_odometry_; // initilize solver void initializeAcadoSolver(Eigen::VectorXd x0); // solve continuous time Riccati equation Eigen::MatrixXd solveCARE(Eigen::MatrixXd Q, Eigen::MatrixXd R); }; } #endif /* INCLUDE_MAV_NONLINEAR_MPC_NONLINEAR_MPC_H_ */
{ "alphanum_fraction": 0.7709399211, "avg_line_length": 29.4870689655, "ext": "h", "hexsha": "39ec0b604a9edc883d8afecf07efdc02a860cc1b", "lang": "C", "max_forks_count": 142, "max_forks_repo_forks_event_max_datetime": "2022-03-14T12:23:21.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-04T03:32:39.000Z", "max_forks_repo_head_hexsha": "207058d78428b944fb8afe51cde06bf9629d8d7a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "caomuqing/mav_control_rw", "max_forks_repo_path": "mav_nonlinear_mpc/include/mav_nonlinear_mpc/nonlinear_mpc.h", "max_issues_count": 40, "max_issues_repo_head_hexsha": "207058d78428b944fb8afe51cde06bf9629d8d7a", "max_issues_repo_issues_event_max_datetime": "2022-01-28T03:41:13.000Z", "max_issues_repo_issues_event_min_datetime": "2017-01-22T16:27:40.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "caomuqing/mav_control_rw", "max_issues_repo_path": "mav_nonlinear_mpc/include/mav_nonlinear_mpc/nonlinear_mpc.h", "max_line_length": 96, "max_stars_count": 230, "max_stars_repo_head_hexsha": "207058d78428b944fb8afe51cde06bf9629d8d7a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "caomuqing/mav_control_rw", "max_stars_repo_path": "mav_nonlinear_mpc/include/mav_nonlinear_mpc/nonlinear_mpc.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:56:13.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-11T01:48:43.000Z", "num_tokens": 1674, "size": 6841 }
/* matrix/gsl_matrix_long.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_LONG_H__ #define __GSL_MATRIX_LONG_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_long.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; long * data; gsl_block_long * block; int owner; } gsl_matrix_long; typedef struct { gsl_matrix_long matrix; } _gsl_matrix_long_view; typedef _gsl_matrix_long_view gsl_matrix_long_view; typedef struct { gsl_matrix_long matrix; } _gsl_matrix_long_const_view; typedef const _gsl_matrix_long_const_view gsl_matrix_long_const_view; /* Allocation */ GSL_EXPORT gsl_matrix_long * gsl_matrix_long_alloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_long * gsl_matrix_long_calloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_long * gsl_matrix_long_alloc_from_block (gsl_block_long * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_EXPORT gsl_matrix_long * gsl_matrix_long_alloc_from_matrix (gsl_matrix_long * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_EXPORT gsl_vector_long * gsl_vector_long_alloc_row_from_matrix (gsl_matrix_long * m, const size_t i); GSL_EXPORT gsl_vector_long * gsl_vector_long_alloc_col_from_matrix (gsl_matrix_long * m, const size_t j); GSL_EXPORT void gsl_matrix_long_free (gsl_matrix_long * m); /* Views */ GSL_EXPORT _gsl_matrix_long_view gsl_matrix_long_submatrix (gsl_matrix_long * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_long_view gsl_matrix_long_row (gsl_matrix_long * m, const size_t i); GSL_EXPORT _gsl_vector_long_view gsl_matrix_long_column (gsl_matrix_long * m, const size_t j); GSL_EXPORT _gsl_vector_long_view gsl_matrix_long_diagonal (gsl_matrix_long * m); GSL_EXPORT _gsl_vector_long_view gsl_matrix_long_subdiagonal (gsl_matrix_long * m, const size_t k); GSL_EXPORT _gsl_vector_long_view gsl_matrix_long_superdiagonal (gsl_matrix_long * m, const size_t k); GSL_EXPORT _gsl_matrix_long_view gsl_matrix_long_view_array (long * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_long_view gsl_matrix_long_view_array_with_tda (long * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_long_view gsl_matrix_long_view_vector (gsl_vector_long * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_long_view gsl_matrix_long_view_vector_with_tda (gsl_vector_long * v, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_long_const_view gsl_matrix_long_const_submatrix (const gsl_matrix_long * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_long_const_view gsl_matrix_long_const_row (const gsl_matrix_long * m, const size_t i); GSL_EXPORT _gsl_vector_long_const_view gsl_matrix_long_const_column (const gsl_matrix_long * m, const size_t j); GSL_EXPORT _gsl_vector_long_const_view gsl_matrix_long_const_diagonal (const gsl_matrix_long * m); GSL_EXPORT _gsl_vector_long_const_view gsl_matrix_long_const_subdiagonal (const gsl_matrix_long * m, const size_t k); GSL_EXPORT _gsl_vector_long_const_view gsl_matrix_long_const_superdiagonal (const gsl_matrix_long * m, const size_t k); GSL_EXPORT _gsl_matrix_long_const_view gsl_matrix_long_const_view_array (const long * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_long_const_view gsl_matrix_long_const_view_array_with_tda (const long * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_long_const_view gsl_matrix_long_const_view_vector (const gsl_vector_long * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_long_const_view gsl_matrix_long_const_view_vector_with_tda (const gsl_vector_long * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_EXPORT long gsl_matrix_long_get(const gsl_matrix_long * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_long_set(gsl_matrix_long * m, const size_t i, const size_t j, const long x); GSL_EXPORT long * gsl_matrix_long_ptr(gsl_matrix_long * m, const size_t i, const size_t j); GSL_EXPORT const long * gsl_matrix_long_const_ptr(const gsl_matrix_long * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_long_set_zero (gsl_matrix_long * m); GSL_EXPORT void gsl_matrix_long_set_identity (gsl_matrix_long * m); GSL_EXPORT void gsl_matrix_long_set_all (gsl_matrix_long * m, long x); GSL_EXPORT int gsl_matrix_long_fread (FILE * stream, gsl_matrix_long * m) ; GSL_EXPORT int gsl_matrix_long_fwrite (FILE * stream, const gsl_matrix_long * m) ; GSL_EXPORT int gsl_matrix_long_fscanf (FILE * stream, gsl_matrix_long * m); GSL_EXPORT int gsl_matrix_long_fprintf (FILE * stream, const gsl_matrix_long * m, const char * format); GSL_EXPORT int gsl_matrix_long_memcpy(gsl_matrix_long * dest, const gsl_matrix_long * src); GSL_EXPORT int gsl_matrix_long_swap(gsl_matrix_long * m1, gsl_matrix_long * m2); GSL_EXPORT int gsl_matrix_long_swap_rows(gsl_matrix_long * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_long_swap_columns(gsl_matrix_long * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_long_swap_rowcol(gsl_matrix_long * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_long_transpose (gsl_matrix_long * m); GSL_EXPORT int gsl_matrix_long_transpose_memcpy (gsl_matrix_long * dest, const gsl_matrix_long * src); GSL_EXPORT long gsl_matrix_long_max (const gsl_matrix_long * m); GSL_EXPORT long gsl_matrix_long_min (const gsl_matrix_long * m); GSL_EXPORT void gsl_matrix_long_minmax (const gsl_matrix_long * m, long * min_out, long * max_out); GSL_EXPORT void gsl_matrix_long_max_index (const gsl_matrix_long * m, size_t * imax, size_t *jmax); GSL_EXPORT void gsl_matrix_long_min_index (const gsl_matrix_long * m, size_t * imin, size_t *jmin); GSL_EXPORT void gsl_matrix_long_minmax_index (const gsl_matrix_long * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_EXPORT int gsl_matrix_long_isnull (const gsl_matrix_long * m); GSL_EXPORT int gsl_matrix_long_add (gsl_matrix_long * a, const gsl_matrix_long * b); GSL_EXPORT int gsl_matrix_long_sub (gsl_matrix_long * a, const gsl_matrix_long * b); GSL_EXPORT int gsl_matrix_long_mul_elements (gsl_matrix_long * a, const gsl_matrix_long * b); GSL_EXPORT int gsl_matrix_long_div_elements (gsl_matrix_long * a, const gsl_matrix_long * b); GSL_EXPORT int gsl_matrix_long_scale (gsl_matrix_long * a, const double x); GSL_EXPORT int gsl_matrix_long_add_constant (gsl_matrix_long * a, const double x); GSL_EXPORT int gsl_matrix_long_add_diagonal (gsl_matrix_long * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_EXPORT int gsl_matrix_long_get_row(gsl_vector_long * v, const gsl_matrix_long * m, const size_t i); GSL_EXPORT int gsl_matrix_long_get_col(gsl_vector_long * v, const gsl_matrix_long * m, const size_t j); GSL_EXPORT int gsl_matrix_long_set_row(gsl_matrix_long * m, const size_t i, const gsl_vector_long * v); GSL_EXPORT int gsl_matrix_long_set_col(gsl_matrix_long * m, const size_t j, const gsl_vector_long * v); /* inline functions if you are using GCC */ #ifdef HAVE_INLINE extern inline long gsl_matrix_long_get(const gsl_matrix_long * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } #endif return m->data[i * m->tda + j] ; } extern inline void gsl_matrix_long_set(gsl_matrix_long * m, const size_t i, const size_t j, const long x) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif m->data[i * m->tda + j] = x ; } extern inline long * gsl_matrix_long_ptr(gsl_matrix_long * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (long *) (m->data + (i * m->tda + j)) ; } extern inline const long * gsl_matrix_long_const_ptr(const gsl_matrix_long * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const long *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_LONG_H__ */
{ "alphanum_fraction": 0.6735696736, "avg_line_length": 33.2244897959, "ext": "h", "hexsha": "5344f4aafce92e8f5f09d82ce1697697776d77ba", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long.h", "max_line_length": 133, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2791, "size": 11396 }
/* randist/mvgauss.c * * Copyright (C) 2016 Timothée Flutre, 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 <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_statistics.h> static int multivar_vcov (const double data[], size_t d, size_t tda, size_t n, double vcov[], size_t tda2); /* Generate a random vector from a multivariate Gaussian distribution using * the Cholesky decomposition of the variance-covariance matrix, following * "Computational Statistics" from Gentle (2009), section 7.4. * * mu mean vector (dimension d) * L matrix resulting from the Cholesky decomposition of * variance-covariance matrix Sigma = L L^T (dimension d x d) * result output vector (dimension d) */ int gsl_ran_multivariate_gaussian (const gsl_rng * r, const gsl_vector * mu, const gsl_matrix * L, gsl_vector * result) { const size_t M = L->size1; const size_t N = L->size2; if (M != N) { GSL_ERROR("requires square matrix", GSL_ENOTSQR); } else if (mu->size != M) { GSL_ERROR("incompatible dimension of mean vector with variance-covariance matrix", GSL_EBADLEN); } else if (result->size != M) { GSL_ERROR("incompatible dimension of result vector", GSL_EBADLEN); } else { size_t i; for (i = 0; i < M; ++i) gsl_vector_set(result, i, gsl_ran_ugaussian(r)); gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasNonUnit, L, result); gsl_vector_add(result, mu); return GSL_SUCCESS; } } /* Compute the log of the probability density function at a given quantile * vector for a multivariate Gaussian distribution using the Cholesky * decomposition of the variance-covariance matrix. * * x vector of quantiles (dimension d) * mu mean vector (dimension d) * L matrix resulting from the Cholesky decomposition of * variance-covariance matrix Sigma = L L^T (dimension d x d) * result output of the density (dimension 1) * work vector used for intermediate computations (dimension d) */ int gsl_ran_multivariate_gaussian_log_pdf (const gsl_vector * x, const gsl_vector * mu, const gsl_matrix * L, double * result, gsl_vector * work) { const size_t M = L->size1; const size_t N = L->size2; if (M != N) { GSL_ERROR("requires square matrix", GSL_ENOTSQR); } else if (mu->size != M) { GSL_ERROR("incompatible dimension of mean vector with variance-covariance matrix", GSL_EBADLEN); } else if (x->size != M) { GSL_ERROR("incompatible dimension of quantile vector", GSL_EBADLEN); } else if (work->size != M) { GSL_ERROR("incompatible dimension of work vector", GSL_EBADLEN); } else { size_t i; double quadForm; /* (x - mu)' Sigma^{-1} (x - mu) */ double logSqrtDetSigma; /* log [ sqrt(|Sigma|) ] */ /* compute: work = x - mu */ for (i = 0; i < M; ++i) { double xi = gsl_vector_get(x, i); double mui = gsl_vector_get(mu, i); gsl_vector_set(work, i, xi - mui); } /* compute: work = L^{-1} * (x - mu) */ gsl_blas_dtrsv(CblasLower, CblasNoTrans, CblasNonUnit, L, work); /* compute: quadForm = (x - mu)' Sigma^{-1} (x - mu) */ gsl_blas_ddot(work, work, &quadForm); /* compute: log [ sqrt(|Sigma|) ] = sum_i log L_{ii} */ logSqrtDetSigma = 0.0; for (i = 0; i < M; ++i) { double Lii = gsl_matrix_get(L, i, i); logSqrtDetSigma += log(Lii); } *result = -0.5*quadForm - logSqrtDetSigma - 0.5*M*log(2.0*M_PI); return GSL_SUCCESS; } } int gsl_ran_multivariate_gaussian_pdf (const gsl_vector * x, const gsl_vector * mu, const gsl_matrix * L, double * result, gsl_vector * work) { double logpdf; int status = gsl_ran_multivariate_gaussian_log_pdf(x, mu, L, &logpdf, work); if (status == GSL_SUCCESS) *result = exp(logpdf); return status; } /* Compute the maximum-likelihood estimate of the mean vector of samples * from a multivariate Gaussian distribution. * * Example from R (GPL): http://www.r-project.org/ * (samples <- matrix(c(4.348817, 2.995049, -3.793431, 4.711934, 1.190864, -1.357363), nrow=3, ncol=2)) * colMeans(samples) # 1.183478 1.515145 */ int gsl_ran_multivariate_gaussian_mean (const gsl_matrix * X, gsl_vector * mu_hat) { const size_t M = X->size1; const size_t N = X->size2; if (N != mu_hat->size) { GSL_ERROR("mu_hat vector has wrong size", GSL_EBADLEN); } else { size_t j; for (j = 0; j < N; ++j) { gsl_vector_const_view c = gsl_matrix_const_column(X, j); double mean = gsl_stats_mean(c.vector.data, c.vector.stride, M); gsl_vector_set(mu_hat, j, mean); } return GSL_SUCCESS; } } /* Compute the maximum-likelihood estimate of the variance-covariance matrix * of samples from a multivariate Gaussian distribution. */ int gsl_ran_multivariate_gaussian_vcov (const gsl_matrix * X, gsl_matrix * sigma_hat) { const size_t M = X->size1; const size_t N = X->size2; if (sigma_hat->size1 != sigma_hat->size2) { GSL_ERROR("sigma_hat must be a square matrix", GSL_ENOTSQR); } else if (N != sigma_hat->size1) { GSL_ERROR("sigma_hat does not match X matrix dimensions", GSL_EBADLEN); } else { return multivar_vcov (X->data, N, X->tda, M, sigma_hat->data, sigma_hat->tda); } } /* Example from R (GPL): http://www.r-project.org/ * (samples <- matrix(c(4.348817, 2.995049, -3.793431, 4.711934, 1.190864, -1.357363), nrow=3, ncol=2)) * cov(samples) # 19.03539 11.91384 \n 11.91384 9.28796 */ static int multivar_vcov (const double data[], size_t d, size_t tda, size_t n, double vcov[], size_t tda2) { size_t j1 = 0, j2 = 0; for (j1 = 0; j1 < d; ++j1) { vcov[j1 * tda2 + j1] = gsl_stats_variance(&(data[j1]), tda, n); for (j2 = j1 + 1; j2 < d; ++j2) { vcov[j1 * tda2 + j2] = gsl_stats_covariance(&(data[j1]), tda, &(data[j2]), tda, n); vcov[j2 * tda2 + j1] = vcov[j1 * tda2 + j2]; } } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6027415491, "avg_line_length": 30.9218106996, "ext": "c", "hexsha": "917429f463b516f26326de53061a454d05d466ea", "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/randist/mvgauss.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/randist/mvgauss.c", "max_line_length": 103, "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/randist/mvgauss.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": 2096, "size": 7514 }
/* ===============================================================================*/ /* Version 1.0. Cullan Howlett */ /* Copyright (c) 2017 International Centre for Radio Astronomy Research, */ /* The MIT License (MIT) University of Western Australia */ /* */ /* 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. */ /* ===============================================================================*/ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_integration.h> // Fisher matrix calculation for surveys with velocity and density field measurements. This extended version includes the extra parameters // associated with primordial non-Gaussianity, scale-dependent density and velocity bias, and zero-point offsets, as per Howlett 2017a. // ASSUMPTIONS: // - Uncorrelated shot-noise between the density and velocity fields // - I use the trapezium rule to integrate over r. There will be some error due to this, but this makes the most sense as // we are binning the number density anyway, and it makes hella difference in the speed of the code. // - The redshift dependence of the non-linear matter and velocity divergence power spectra is captured using linear interpolation. // - The PV error scales as a fixed pecentage of H0*r. // - Flat LCDM cosmology (but not necessarily GR as gammaval can be changed). // - The damping of the velocity and density fields due to non-linear RSD is redshift independent // - The scale dependence of the scale-dependent bias is redshift independent // The parameters necessary for the calculation static int nparams = 2; // The number of free parameters (we can use any of beta, fsigma8, r_g, sigma_g, sigma_u, fnl, Rv, Rd, zp_err) static int Data[2] = {0,1}; // A vector of flags for the parameters we are interested in (0=beta, 1=fsigma8, 2=r_g, 3=sigma_g, 4=sigma_u, 5=fnl, 6=Rv, 7=Rd, 8=zp_err). MAKE SURE THE LENGTH OF THIS VECTOR, NPARAMS AND THE ENTRIES AGREE/MAKE SENSE, OR YOU MIGHT GET NONSENSE RESULTS!! static int nziter = 1; // Now many bins in redshift between zmin and zmax we are considering static double zmin = 0.0; // The minimum redshift to consider (You must have power spectra that are within this range or GSL spline will error out) static double zmax = 0.4; // The maximum redshift to consider (You must have power spectra that are within this range or GSL spline will error out) static double Om = 0.3121; // The matter density at z=0 static double c = 299792.458; // The speed of light in km/s static double gammaval = 0.55; // The value of gammaval to use in the forecasts (where f(z) = Om(z)^gammaval) static double r_g = 1.0; // The cross correlation coefficient between the velocity and density fields static double beta0 = 0.493; // The value of beta (at z=0, we'll modify this by the redshift dependent value of bias and f as required) static double sigma80 = 0.8150; // The value of sigma8 at z=0 static double sigma_u = 13.00; // The value of the velocity damping parameter in Mpc/h. I use the values from Jun Koda's paper static double sigma_g = 4.24; // The value of the density damping parameter in Mpc/h. I use the values from Jun Koda's paper static double fnl = 0.0; // The value of fnl contributing to primordial non-Gaussianity static double Rd = 0.0; // Scale-dependent bias following the parameterisation in Howlett2017a static double Rv = 0.0; // Velocity bias following the parameterisation in Howlett2017a static double zp_err = 0.05; // The error in the zeropoint offset if we are interested in the systematic bias caused by such an error (sigma_m in Eq. 34 of Howlett 2017a) static double do_bias = 0; // Whether or not to calculate the systematic parameter bias due to neglecting scale-dependent biases. static double do_zp_bias = 1; // Whether or not to calculate the systematic parameter bias due to having a zero-point offset. static double kmax = 0.2; // The maximum k to evaluate for dd, dv and vv correlations (Typical values are 0.1 - 0.2, on smaller scales the models are likely to break down). static double survey_area[3] = {0.0, 0.0, 1.65}; // We need to know the survey area for each survey and the overlap area between the surveys (redshift survey only first, then PV survey only, then overlap. // For fully overlapping we would have {0, 0, size_overlap}. For redshift larger than PV, we would have {size_red-size_overlap, 0, size_overlap}). Units are pi steradians, such that full sky is 4.0, half sky is 2.0 etc. static double error_rand = 300.0; // The observational error due to random non-linear velocities (I normally use 300km/s as in Jun Koda's paper) static double error_dist = 0.20; // The percentage error on the distance indicator (Typically 0.05 - 0.10 for SNe IA, 0.2 or more for Tully-Fisher or Fundamental Plane) static double verbosity = 2; // How much output to give: 0 = only percentage errors on fsigma8, 1 = other useful info and nuisance parameters, 2 = full fisher and covariance matrices // The number of redshifts and the redshifts themselves of the input matter and velocity divergence power spectra. // These numbers are multiplied by 100, converted to ints and written in the form _z0p%02d which is then appended to the filename Pvel_file. See routine read_power. static double nzin = 11; static double zin[11] = {0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50}; char * Pvel_file = "./example_files/example_pk"; // The file containing the velocity divergence power spectrum. Don't include .dat as we'll append the redshifts on read in char * Trans_file = "./example_files/example_transfer.dat"; // The file containing the transfer function. Only used for primordial non-Gaussianity and must be normalised to 1 as k->0 // The files containing the number density of the surveys. First is the PV survey, then the redshift survey. These files MUST have the same binning and redshift range, // so that the sum over redshift bins works (would be fine if we used splines), i.e., if one survey is shallower then that file must contain rows with n(z)=0. // I also typically save nbar x 10^6 in the input file to make sure I don't lose precision when outputting small nbar values to files. This is corrected when the nbar file // is read in, so see the read_nz() routine! char * nbar_file[300] = {"./example_files/taipan_vel_nbar_final_reformat.dat", "./example_files/taipan_red_nbar_final_reformat.dat"}; // Other global parameters and arrays int NK, * NRED; double pkkmin; // The minimum kmin to integrate over, based on the input power spectrum file double pkkmax; // The maximum k in the input power spectrum. The maximum k to integrate over is the smallest of this or kmax double * zarray; double * rarray; double * ezarray; double * deltararray; double * growtharray; double ** nbararray; double * karray, * deltakarray; double ** pmmarray, ** pmtarray, ** pttarray; gsl_spline * growth_spline, * r_spline; gsl_interp_accel * growth_acc, * r_acc; gsl_spline * Trans_spline, * growth_spline, * r_spline; gsl_interp_accel * Trans_acc, * growth_acc, * r_acc; // Prototypes double zeff_integrand(double mu, void * pin); double mu_integrand(double mu, void * pin); double ezinv(double x, void *p); double rz(double red); double growthfunc(double x, void *p); double growthz(double red); void read_nz(); void read_power(); void read_transfer(); double calc_zeff(double kmin, double zmin_iter, double zmax_iter); void calc_fisher(double kmin, double zmin_iter, double zmax_iter, double z_eff, double bias_flag, gsl_matrix * Covariance, double * Sys); // Calculates the fished matrix for a velocity survey. int main(int argc, char **argv) { int i, j; // Read in the velocity divergence power spectrum output from the COPTER code (Carlson 2009) read_power(); // Read in the transfer function read_transfer(); // Read in the number densities of the surveys read_nz(); // Run some checks if (!((survey_area[0] > 0.0) || (survey_area[2] > 0.0))) { for (i=0; i<nparams; i++) { if (Data[i] == 2) { printf("ERROR: r_g is a free parameter, but there is no information in the density field (Fisher matrix will be singular)\n"); exit(0); } if (Data[i] == 3) { printf("ERROR: sigma_g is a free parameter, but there is no information in the density field (Fisher matrix will be singular)\n"); exit(0); } } } if (!((survey_area[1] > 0.0) || (survey_area[2] > 0.0))) { for (i=0; i<nparams; i++) { if (Data[i] == 4) { printf("ERROR: sigma_u is a free parameter, but there is no information in the velocity field (Fisher matrix will be singular)\n"); exit(0); } } } if ((sizeof(Data)/sizeof(*Data)) != nparams) { printf("ERROR: Size of Data vector for parameters of interest must be equal to nparams\n"); exit(0); } printf("Evaluating the Fisher Matrix for %d bins between [z_min = %lf, z_max = %lf]\n", nziter, zmin, zmax); if (verbosity == 0) { if (do_bias || do_zp_bias) { printf("# zmin zmax zeff fsigma8(z_eff) TRUE percentage error(z_eff) percentage bias(z_eff) INCORRECT percentage error(z_eff)\n"); } else { printf("# zmin zmax zeff fsigma8(z_eff) percentage error(z_eff)\n"); } } int ziter; double * Sys = (double *)malloc(nparams*sizeof(double*)); gsl_matrix * Covariance = gsl_matrix_alloc(nparams, nparams); for (ziter = 0; ziter<nziter; ziter++) { double zbinwidth = (zmax-zmin)/(nziter); double zmin_iter = ziter*zbinwidth + zmin; double zmax_iter = (ziter+1.0)*zbinwidth + zmin; double rzmax = gsl_spline_eval(r_spline, zmax_iter, r_acc); double kmin = M_PI/rzmax; if (verbosity > 0) printf("Evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\n", kmin, kmax, zmin_iter, zmax_iter); // Calculate the effective redshift (which I base on the sum of the S/N for the density and velocity fields) // ********************************************************************************************************* double z_eff = calc_zeff(kmin, zmin_iter, zmax_iter); // Fisher matrix using the TRUE covariance matrix (i.e., with scale-dependent biases). This routine changes based on whether do_zp_bias is true or false. // In the former case, this Fisher Matrix DOESN'T include a zero-point offset, as we compute the systematically biased case later. If do_zp_bias is false // we are not interested in the bias caused by an offset, and so we treat whatever value is in zp_err as real and the Fisher Matrix DOES include a potential zero-point offset // ****************************************************************************************************************** calc_fisher(kmin, zmin_iter, zmax_iter, z_eff, 0, Covariance, Sys); // Bias vector (i.e., Eq. 50 from Howlett 2017a, which uses computes the parameter offset due to neglecting scale-dependent biases or adding a zero-point offset) // ****************************************************************************************************************** if (do_bias || do_zp_bias) calc_fisher(kmin, zmin_iter, zmax_iter, z_eff, 1, Covariance, Sys); // Fisher matrix using the INCORRECT covariance matrix (i.e., without scale-dependent biases, and with zero-point offsets). This is used for comparing the // magnitude of any bias with respect to the errors (as the errors could also be biased too small!) // ****************************************************************************************************************** if (do_bias || do_zp_bias) calc_fisher(kmin, zmin_iter, zmax_iter, z_eff, 2, Covariance, Sys); } // Now the full Fisher matrix over all redshifts if we had more than 1 redshift bin. This is equivalent to assuming a single measurement from all data // and NOT the same as summing the individual matrices above (which is equivalent to making separate measurements at each redshift, then marginalising over // all redshift-dependent quantities, and so may be different for things like fnl). if (nziter > 1) { double rzmax = gsl_spline_eval(r_spline, zmax, r_acc); double kmin = M_PI/rzmax; if (verbosity > 0) printf("Finally, evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\n", kmin, kmax, zmin, zmax); // Calculate the effective redshift (which I base on the sum of the S/N for the density and velocity fields) // ********************************************************************************************************* double z_eff = calc_zeff(kmin, zmin, zmax); // Fisher matrix using the TRUE covariance matrix (i.e., with scale-dependent biases). This routine changes based on whether do_zp_bias is true or false. // In the former case, this Fisher Matrix DOESN'T include a zero-point offset, as we compute the systematically biased case later. If do_zp_bias is false // we are not interested in the bias caused by an offset, and so we treat whatever value is in zp_err as real and the Fisher Matrix DOES include a potential zero-point offset // ****************************************************************************************************************** calc_fisher(kmin, zmin, zmax, z_eff, 0, Covariance, Sys); // Bias vector (i.e., Eq. 50 from Howlett 2017a, which uses computes the parameter offset due to neglecting scale-dependent biases or adding a zero-point offset) // ****************************************************************************************************************** if (do_bias || do_zp_bias) calc_fisher(kmin, zmin, zmax, z_eff, 1, Covariance, Sys); // Fisher matrix using the INCORRECT covariance matrix (i.e., without scale-dependent biases, and with zero-point offsets). This is used for comparing the // magnitude of any bias with respect to the errors (as the errors could also be biased too small!) // ****************************************************************************************************************** if (do_bias || do_zp_bias) calc_fisher(kmin, zmin, zmax, z_eff, 2, Covariance, Sys); } free(Sys); gsl_matrix_free(Covariance); gsl_spline_free(growth_spline); gsl_interp_accel_free(growth_acc); gsl_spline_free(Trans_spline); gsl_interp_accel_free(Trans_acc); return 0; } double calc_zeff(double kmin, double zmin_iter, double zmax_iter) { int numk; double k_sum1 = 0.0, k_sum2 = 0.0; for (numk=0; numk<NK; numk++) { double k = karray[numk]+0.5*deltakarray[numk]; double deltak = deltakarray[numk]; if (k < kmin) continue; if (k > kmax) continue; double result, error; double params[4] = {numk, k, zmin_iter, zmax_iter}; size_t nevals = 1000; gsl_function F; F.function = &zeff_integrand; F.params = &params; gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000); gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error); gsl_integration_workspace_free(w); k_sum1 += k*k*deltak*result; k_sum2 += k*k*deltak; } double z_eff = k_sum1/k_sum2; if (verbosity > 0) printf("Effective redshift z_eff = %lf\n", z_eff); return z_eff; } // Calculate the fisher matrix, integrating over k, then mu, then r (r is last as it means we are effectively integrating over effective volume). // As the input spectra are tabulated we'll just use the trapezium rule to integrate over k void calc_fisher(double kmin, double zmin_iter, double zmax_iter, double z_eff, double bias_flag, gsl_matrix * Covariance, double * Sys) { int i, j, numk; double growth_eff = gsl_spline_eval(growth_spline, z_eff, growth_acc); double sigma8 = sigma80 * growth_eff; double Omz = Om*ezinv(z_eff,NULL)*ezinv(z_eff,NULL)*(1.0+z_eff)*(1.0+z_eff)*(1.0+z_eff); double f = pow(Omz, gammaval); double beta = f*beta0*growth_eff/pow(Om,0.55); if (verbosity > 0) { if (do_zp_bias) { if (bias_flag == 0) { printf("TRUE Fisher matrix without zero-point offset:\n"); } else if (bias_flag == 1) { printf("BIAS vector:\n"); } else if (bias_flag == 2) { printf("INCORRECT Fisher matrix:\n"); } } else { if (bias_flag == 0) { printf("TRUE Fisher matrix with potential zero-point offset set by zp_err:\n"); } else if (bias_flag == 1) { printf("BIAS vector:\n"); } else if (bias_flag == 2) { printf("INCORRECT Fisher matrix:\n"); } } } double * Bias = (double *)malloc(nparams*sizeof(double*)); gsl_matrix * Fisher = gsl_matrix_alloc(nparams, nparams); for (i=0; i<nparams; i++) { for (j=i; j<nparams; j++) { double k_sum = 0.0; for (numk=0; numk<NK; numk++) { double k = karray[numk]+0.5*deltakarray[numk]; double deltak = deltakarray[numk]; if (k < kmin) continue; if (k > kmax) continue; double result, error; double params[7] = {numk, k, Data[i], Data[j], zmin_iter, zmax_iter, bias_flag}; size_t nevals = 1000; gsl_function F; F.function = &mu_integrand; F.params = &params; gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000); gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error); gsl_integration_workspace_free(w); k_sum += k*k*deltak*result; } //printf("%d, %d, %lf\n", i, j, k_sum/(4.0*M_PI)); if (bias_flag == 1) { Bias[i] = k_sum/(4.0*M_PI); } else { gsl_matrix_set(Fisher, i, j, k_sum/(4.0*M_PI)); gsl_matrix_set(Fisher, j, i, k_sum/(4.0*M_PI)); } } } if (bias_flag == 1) { for (i=0; i<nparams; i++) { Sys[i] = 0.0; for (j=0; j<nparams; j++) { Sys[i] += gsl_matrix_get(Covariance, i, j)*Bias[j]; } } if (verbosity > 0) { for (i=0; i<nparams; i++) { if (Data[i] == 0) { printf("%12.6lf bias on beta = %12.6lf\n", Sys[i], beta); } if (Data[i] == 1) { printf("%12.6lf bias on fsigma8 = %12.6lf\n", Sys[i], f*sigma8); } if (Data[i] == 2) { printf("%12.6lf bias on r_g = %12.6lf\n", Sys[i], r_g); } if (Data[i] == 3) { printf("%12.6lf bias on sigma_g = %12.6lf\n", Sys[i], sigma_g); } if (Data[i] == 4) { printf("%12.6lf bias on sigma_u = %12.6lf\n", Sys[i], sigma_u); } if (Data[i] == 5) { printf("%12.6lf bias on fnl = %12.6lf\n", Sys[i], fnl); } } } } else { if (verbosity == 2) { printf("Fisher Matrix\n======================\n"); for (i=0; i<nparams; i++) { printf("["); for (j=0; j<nparams; j++) printf("%15.6lf,\t", gsl_matrix_get(Fisher, i, j)); printf("],\n"); } } // Now invert the Fisher matrix int s; gsl_permutation * p; p = gsl_permutation_alloc(nparams); gsl_linalg_LU_decomp(Fisher, p, &s); gsl_linalg_LU_invert(Fisher, p, Covariance); gsl_permutation_free(p); if (verbosity == 0) { for (i=0; i<nparams; i++) { if (Data[i] == 1) { if (do_bias || do_zp_bias) { if (bias_flag == 0) { printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf ", zmin_iter, zmax_iter, z_eff, f*sigma8, 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8)); } else if (bias_flag == 2) { printf(" %12.6lf %12.6lf\n", 100.0*Sys[i]/sqrt(gsl_matrix_get(Covariance, i, i)), 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8)); } } else { printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\n", zmin_iter, zmax_iter, z_eff, f*sigma8, 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8)); } } } } if (verbosity > 0) { printf("Parameter constraints\n======================================================\n"); for (i=0; i<nparams; i++) { if (Data[i] == 0) { printf("beta = %12.6lf +/- %12.6lf\n", beta, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on beta\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/beta); if (bias_flag == 2) printf("%4.2lf percent bias on beta\n", 100.0*Sys[i]/sqrt(gsl_matrix_get(Covariance, i, i))); } if (Data[i] == 1) { printf("fsigma8 = %12.6lf +/- %12.6lf\n", f*sigma8, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on fsigma8\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8)); if (bias_flag == 2) printf("%4.2lf percent bias on fsigma8\n", 100.0*Sys[i]/sqrt(gsl_matrix_get(Covariance, i, i))); } if (Data[i] == 2) { printf("r_g = %12.6lf +/- %12.6lf\n", r_g, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on r_g\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/r_g); if (bias_flag == 2) printf("%4.2lf percent bias on r_g\n", 100.0*Sys[i]/sqrt(gsl_matrix_get(Covariance, i, i))); } if (Data[i] == 3) { printf("sigma_g = %12.6lf +/- %12.6lf\n", sigma_g, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on sigma_g\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_g); if (bias_flag == 2) printf("%4.2lf percent bias on sigma_g\n", 100.0*Sys[i]/sqrt(gsl_matrix_get(Covariance, i, i))); } if (Data[i] == 4) { printf("sigma_u = %12.6lf +/- %12.6lf\n", sigma_u, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on sigma_u\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_u); if (bias_flag == 2) printf("%4.2lf percent bias on sigma_u\n", 100.0*Sys[i]/sqrt(gsl_matrix_get(Covariance, i, i))); } if (Data[i] == 5) { printf("fnl = %12.6lf +/- %12.6lf\n", fnl, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf absolute error on fnl\n", sqrt(gsl_matrix_get(Covariance, i, i))); if (bias_flag == 2) printf("%4.2lf percent bias on fnl\n", 100.0*Sys[i]/sqrt(gsl_matrix_get(Covariance, i, i))); } if (Data[i] == 6) { printf("Rv = %12.6lf +/- %12.6lf\n", Rv, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on Rv\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/Rv); } if (Data[i] == 7) { printf("Rd = %12.6lf +/- %12.6lf\n", Rd, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on Rd\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/Rd); } if (Data[i] == 8) { printf("zp_err = %12.6lf +/- %12.6lf\n", zp_err, sqrt(gsl_matrix_get(Covariance, i, i))); printf("%4.2lf percent error on zp_err\n", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/zp_err); } } } if (verbosity == 2) { printf("Covariance Matrix\n======================\n"); for (i=0; i<nparams; i++) { printf("["); for (j=0; j<nparams; j++) printf("%15.6lf,\t", gsl_matrix_get(Covariance, i, j)); printf("],\n"); } } } free(Bias); gsl_matrix_free(Fisher); } // The integrand to calculate the effective redshift. I'm not actually sure how this is done in the case of // density and velocity field measurements, but it seems logical to base it on the sum of the integral of the density spectra and the velocity power spectra // weighted by their effective signal to noise. In this way the effective redshift is calculated in the same way as a redshift survey, but there is some dependence // on the S/N in the velocity power spectrum too. In any case, the S/N of the density field measurement is always much higher (because there are // no errors and the number density is higher) and so this dominates the effective redshift calculation. double zeff_integrand(double mu, void * pin) { int i, j, m, q, u, surv; double * p = (double *)pin; int numk = (int)p[0]; double k = p[1]; double zminval = p[2]; double zmaxval = p[3]; gsl_interp_accel * Pmm_acc, * Pmt_acc, * Ptt_acc; gsl_spline * Pmm_spline, * Pmt_spline, * Ptt_spline; if (nzin > 1) { double * Pmm_array = (double *)malloc(nzin*sizeof(double)); double * Pmt_array = (double *)malloc(nzin*sizeof(double)); double * Ptt_array = (double *)malloc(nzin*sizeof(double)); for (j=0; j<nzin; j++) { Pmm_array[j] = pmmarray[j][numk]; Pmt_array[j] = pmtarray[j][numk]; Ptt_array[j] = pttarray[j][numk]; } Pmm_acc = gsl_interp_accel_alloc(); Pmm_spline = gsl_spline_alloc(gsl_interp_cspline, nzin); gsl_spline_init(Pmm_spline, zin, Pmm_array, nzin); free(Pmm_array); Pmt_acc = gsl_interp_accel_alloc(); Pmt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin); gsl_spline_init(Pmt_spline, zin, Pmt_array, nzin); free(Pmt_array); Ptt_acc = gsl_interp_accel_alloc(); Ptt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin); gsl_spline_init(Ptt_spline, zin, Ptt_array, nzin); free(Ptt_array); } double Tk = gsl_spline_eval(Trans_spline, k, Trans_acc); double Ak0 = 3.0*1.686*Om*1.0e4/(k*k*Tk*c*c); // The prefactor for the scale dependent bias induced by primordial non-Gaussianity double dendamp = sqrt(1.0/(1.0+0.5*(k*k*mu*mu*sigma_g*sigma_g))); // This is unitless double veldamp = sin(k*sigma_u)/(k*sigma_u); // This is unitless double dVeff = 0.0, zdVeff = 0.0; for (i=0; i<NRED[0]; i++) { double zval = zarray[i]; if (zval < zminval) continue; if (zval > zmaxval) break; double r_sum = 0.0; double r = rarray[i]; double deltar = deltararray[i]; double dd_prefac=0.0, vv_prefac=0.0; double P_gg=0.0, P_uu=0.0; double Ak = Ak0/growtharray[i]; double sigma8 = sigma80 * growtharray[i]; // First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift double Pmm, Pmt, Ptt; Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc); Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc); Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc); double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval); double f = pow(Omz, gammaval); double beta = f*beta0*growtharray[i]/pow(Om,0.55); double bv = 1.0 - Rv*Rv*k*k; double bsd = Rd*k*k; double beta_sd = 1.0/beta + bsd/f; vv_prefac = 1.0e2*bv*f*mu*veldamp/k; dd_prefac = ((1.0+fnl*Ak)*(1.0+fnl*Ak)*(beta_sd*beta_sd) + 2.0*bv*r_g*mu*mu*(1.0+fnl*Ak)*beta_sd + bv*bv*mu*mu*mu*mu - 2.0*fnl*Ak*(1.0+fnl*Ak)*beta_sd/f - 2.0*bv*r_g*mu*mu*fnl*Ak/f + fnl*fnl*Ak*Ak/(f*f))*f*f*dendamp*dendamp; P_gg = dd_prefac*Pmm; P_uu = vv_prefac*vv_prefac*Ptt; // We need to do the overlapping and non-overlapping parts of the redshifts and PV surveys separately for (surv=0; surv<3; surv++) { double surv_sum = 0.0; if (survey_area[surv] > 0.0) { double error_obs, error_noise, n_g = 0.0, n_u = 0.0; // Set the nbar for each section. if (surv == 0) { n_g = nbararray[1][i]; } else if (surv == 1) { error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter) error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2} n_u = nbararray[0][i]/error_noise; } else { error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter) error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2} n_u = nbararray[0][i]/error_noise; n_g = nbararray[1][i]; } double value1 = n_g/(1.0 + n_g*P_gg); double value2 = n_u/(1.0 + n_u*P_uu); surv_sum += value1*value1 + value2*value2; surv_sum *= survey_area[surv]; r_sum += surv_sum; } } dVeff += r*r*deltar*r_sum; zdVeff += zval*r*r*deltar*r_sum; } gsl_spline_free(Pmm_spline); gsl_spline_free(Pmt_spline); gsl_spline_free(Ptt_spline); gsl_interp_accel_free(Pmm_acc); gsl_interp_accel_free(Pmt_acc); gsl_interp_accel_free(Ptt_acc); return zdVeff/dVeff; } // The integrand for the integral over mu in the Fisher matrix calculation. // For each mu we need to create a 2x2 matrix of the relevant power spectra derivatives and the inverse of the power spectrum matrix. // Because there are some regions where the number density goes to zero we have to work directly with the inverse as it is difficult to invert numerically // but if we deal with the inverse only then we can just set the relevant parts to zero when the number density is zero. double mu_integrand(double mu, void * pin) { int i, j, m, q, u, surv; double * p = (double *)pin; double result, error; int numk = (int)p[0]; double k = p[1]; double zminval = p[4]; double zmaxval = p[5]; gsl_interp_accel * Pmm_acc, * Pmt_acc, * Ptt_acc; gsl_spline * Pmm_spline, * Pmt_spline, * Ptt_spline; double * Pmm_array = (double *)malloc(nzin*sizeof(double)); double * Pmt_array = (double *)malloc(nzin*sizeof(double)); double * Ptt_array = (double *)malloc(nzin*sizeof(double)); for (j=0; j<nzin; j++) { Pmm_array[j] = pmmarray[j][numk]; Pmt_array[j] = pmtarray[j][numk]; Ptt_array[j] = pttarray[j][numk]; } Pmm_acc = gsl_interp_accel_alloc(); Pmm_spline = gsl_spline_alloc(gsl_interp_cspline, nzin); gsl_spline_init(Pmm_spline, zin, Pmm_array, nzin); free(Pmm_array); Pmt_acc = gsl_interp_accel_alloc(); Pmt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin); gsl_spline_init(Pmt_spline, zin, Pmt_array, nzin); free(Pmt_array); Ptt_acc = gsl_interp_accel_alloc(); Ptt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin); gsl_spline_init(Ptt_spline, zin, Ptt_array, nzin); free(Ptt_array); double Tk = gsl_spline_eval(Trans_spline, k, Trans_acc); double Ak0 = 3.0*1.686*Om*1.0e4/(k*k*Tk*c*c); // The prefactor for the scale dependent bias induced by primordial non-Gaussianity double dendamp = sqrt(1.0/(1.0+0.5*(k*k*mu*mu*sigma_g*sigma_g))); // This is unitless double veldamp = sin(k*sigma_u)/(k*sigma_u); // This is unitless double result_sum = 0.0; for (i=0; i<NRED[0]; i++) { double zval = zarray[i]; double r_sum = 0.0; double r = rarray[i]; double ez = ezarray[i]; double deltar = deltararray[i]; if (zval < zminval) continue; if (zval > zmaxval) break; double dd_prefac=0.0, dv_prefac=0.0, vv_prefac=0.0; double dd_prefac_bias=0.0, dv_prefac_bias=0.0, vv_prefac_bias=0.0; double P_gg=0.0, P_ug=0.0, P_uu=0.0; double P_gg_bias=0.0, P_ug_bias=0.0, P_uu_bias=0.0; double Ak = Ak0/growtharray[i]; double sigma8 = sigma80 * growtharray[i]; // First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift double Pmm, Pmt, Ptt; Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc); Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc); Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc); double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval); double f = pow(Omz, gammaval); double beta = f*beta0*growtharray[i]/pow(Om,0.55); double bv = 1.0 - Rv*Rv*k*k; double bsd = Rd*k*k; double beta_sd = 1.0/beta + bsd/f; // If p[6] (bias_flag) == 2 this means we are computing the Fisher matrix INCLUDING systematics, and so we need the covariance matrix without scale-dependent bias if ((int)p[6] == 2) { bv = 1.0; beta_sd = 1.0/beta; } // In the presence of a zero-point offset we have to calculate the additional velocity recieved. // This is redshift dependent if we assume a fixed offset in the logarithmic distance ratio double zp_err_prefac = c*log(10.0)/(1.0 - ((c*(1.0 + zval)*(1.0 + zval))/(100.0*ez*r)))/5.0; double zp_err_v = zp_err*zp_err_prefac; vv_prefac = 1.0e2*bv*f*mu*veldamp/k; dd_prefac = ((1.0+fnl*Ak)*(1.0+fnl*Ak)*(beta_sd*beta_sd) + 2.0*bv*r_g*mu*mu*(1.0+fnl*Ak)*beta_sd + bv*bv*mu*mu*mu*mu - 2.0*fnl*Ak*(1.0+fnl*Ak)*beta_sd/f - 2.0*bv*r_g*mu*mu*fnl*Ak/f + fnl*fnl*Ak*Ak/(f*f))*f*f*dendamp*dendamp; dv_prefac = (r_g*(1.0+fnl*Ak)*beta_sd - r_g*fnl*Ak/f + bv*mu*mu)*f*dendamp; P_gg = dd_prefac*Pmm; P_ug = vv_prefac*dv_prefac*Pmt; P_uu = vv_prefac*vv_prefac*Ptt; // And now the derivatives. Need to create a matrix of derivatives for each of the two parameters of interest gsl_matrix * dPdt1 = gsl_matrix_calloc(2, 2); gsl_matrix * dPdt2 = gsl_matrix_calloc(2, 2); double value; switch((int)p[2]) { // Differential w.r.t betaA case 0: value = -2.0*((1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak)/f)*f*f*dendamp*dendamp*Pmm/(beta*beta); gsl_matrix_set(dPdt1, 0, 0, value); value = -(vv_prefac*f*r_g*(1.0+fnl*Ak)*dendamp*Pmt)/(beta*beta); gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); break; // Differential w.r.t fsigma8 case 1: value = 2.0*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd/beta + f*r_g*bv*mu*mu*(1.0+fnl*Ak)*(2.0/beta + bsd/f) + f*bv*bv*mu*mu*mu*mu - fnl*Ak*(1.0+fnl*Ak)/beta - bv*r_g*mu*mu*fnl*Ak)*dendamp*dendamp*Pmm/sigma8; gsl_matrix_set(dPdt1, 0, 0, value); value = vv_prefac*(r_g*(1.0+fnl*Ak)*(2.0/beta + bsd/f) - r_g*fnl*Ak/f + bv*mu*mu)*dendamp*Pmt/sigma8; gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); value = (2.0*P_uu)/(f*sigma8); gsl_matrix_set(dPdt1, 1, 1, value); break; // Differential w.r.t r_g case 2: value = 2.0*bv*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*f*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt1, 0, 0, value); value = vv_prefac*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*dendamp*Pmt; gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); break; // Differential w.r.t sigma_g case 3: value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg; gsl_matrix_set(dPdt1, 0, 0, value); value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug; gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); break; // Differential w.r.t sigma_u case 4: value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u); gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u); gsl_matrix_set(dPdt1, 1, 1, value); break; // Differential w.r.t fnl case 5: value = 2.0*Ak*((1.0+fnl*Ak)*beta_sd*beta_sd + bv*r_g*mu*mu*(beta_sd - 1.0/f) - (1.0+2.0*fnl*Ak)*beta_sd/f + fnl*Ak/(f*f))*f*f*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt1, 0, 0, value); value = vv_prefac*r_g*Ak*(beta_sd - 1.0/f)*f*dendamp*Pmt; gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); break; // Differential w.r.t Rv case 6: value = -4.0*Rv*k*k*(r_g*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f) + bv*mu*mu*mu*mu)*f*f*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt1, 0, 0, value); value = -2.0*Rv*k*k*vv_prefac*(r_g*(1.0+fnl*Ak)*beta_sd/bv - r_g*fnl*Ak/(f*bv) + 2.0*mu*mu)*f*dendamp*Pmt; gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); value = -4.0*Rv*k*k*P_uu/bv; gsl_matrix_set(dPdt1, 1, 1, value); break; // Differential w.r.t Rd case 7: value = 2.0*k*k*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*f*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak))*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt1, 0, 0, value); value = vv_prefac*k*k*r_g*(1.0+fnl*Ak)*dendamp*Pmt; gsl_matrix_set(dPdt1, 0, 1, value); gsl_matrix_set(dPdt1, 1, 0, value); break; // Differential w.r.t. zp_err case 8: if (nbararray[0][i] > 0.0) { value = 2.0*zp_err_v*zp_err_prefac/nbararray[0][i]; gsl_matrix_set(dPdt1, 1, 1, value); } break; default: break; } // If we want to calculate the Bias vector and look at systematics from scale-dependent bias or zero-point offsets, we simply have to replace dPdt2 with the difference between the models with and without bias. // The subscript "bias" is the systematically biased covariance matrix, which, in the most confusing way possible, is the one which doesn't have the velocity/scale-dependent bias included or does have the zero-point offset if ((int)p[6] == 1) { // Calculate the model without scale-dependent biases if (do_bias) { double bv_bias = 1.0; double beta_sd_bias = 1.0/beta; vv_prefac_bias = 1.0e2*bv_bias*f*mu*veldamp/k; dd_prefac_bias = ((1.0+fnl*Ak)*(1.0+fnl*Ak)*(beta_sd_bias*beta_sd_bias) + 2.0*bv_bias*r_g*mu*mu*(1.0+fnl*Ak)*beta_sd_bias + bv_bias*bv_bias*mu*mu*mu*mu - 2.0*fnl*Ak*(1.0+fnl*Ak)*beta_sd_bias/f - 2.0*bv_bias*r_g*mu*mu*fnl*Ak/f + fnl*fnl*Ak*Ak/(f*f))*f*f*dendamp*dendamp; dv_prefac_bias = (r_g*(1.0+fnl*Ak)*beta_sd_bias - r_g*fnl*Ak/f + bv_bias*mu*mu)*f*dendamp; P_gg_bias = dd_prefac_bias*Pmm; P_ug_bias = vv_prefac_bias*dv_prefac_bias*Pmt; P_uu_bias = vv_prefac_bias*vv_prefac_bias*Ptt; gsl_matrix_set(dPdt2, 0, 0, P_gg - P_gg_bias); gsl_matrix_set(dPdt2, 0, 1, P_ug - P_ug_bias); gsl_matrix_set(dPdt2, 1, 0, P_ug - P_ug_bias); gsl_matrix_set(dPdt2, 1, 1, P_uu - P_uu_bias); //printf("%lf, %lf, %lf, %lf\n",bvA, P_uuAA, P_uuAA_bias, gsl_matrix_get(dPdt2, 1, 1)); } if (do_zp_bias) { if (nbararray[0][i] > 0.0) { gsl_matrix_set(dPdt2, 1, 1, zp_err_v*zp_err_v/nbararray[0][i]); } } } else { switch((int)p[3]) { // Differential w.r.t betaA case 0: value = -2.0*((1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak)/f)*f*f*dendamp*dendamp*Pmm/(beta*beta); gsl_matrix_set(dPdt2, 0, 0, value); value = -(vv_prefac*f*r_g*(1.0+fnl*Ak)*dendamp*Pmt)/(beta*beta); gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); break; // Differential w.r.t fsigma8 case 1: value = 2.0*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd/beta + f*r_g*bv*mu*mu*(1.0+fnl*Ak)*(2.0/beta + bsd/f) + f*bv*bv*mu*mu*mu*mu - fnl*Ak*(1.0+fnl*Ak)/beta - bv*r_g*mu*mu*fnl*Ak)*dendamp*dendamp*Pmm/sigma8; gsl_matrix_set(dPdt2, 0, 0, value); value = vv_prefac*(r_g*(1.0+fnl*Ak)*(2.0/beta + bsd/f) - r_g*fnl*Ak/f + bv*mu*mu)*dendamp*Pmt/sigma8; gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); value = (2.0*P_uu)/(f*sigma8); gsl_matrix_set(dPdt2, 1, 1, value); break; // Differential w.r.t r_g case 2: value = 2.0*bv*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*f*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt2, 0, 0, value); value = vv_prefac*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*dendamp*Pmt; gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); break; // Differential w.r.t sigma_g case 3: value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg; gsl_matrix_set(dPdt2, 0, 0, value); value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug; gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); break; // Differential w.r.t sigma_u case 4: value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u); gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u); gsl_matrix_set(dPdt2, 1, 1, value); break; // Differential w.r.t fnl case 5: value = 2.0*Ak*((1.0+fnl*Ak)*beta_sd*beta_sd + bv*r_g*mu*mu*(beta_sd - 1.0/f) - (1.0+2.0*fnl*Ak)*beta_sd/f + fnl*Ak/(f*f))*f*f*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt2, 0, 0, value); value = vv_prefac*r_g*Ak*(beta_sd - 1.0/f)*f*dendamp*Pmt; gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); break; // Differential w.r.t Rv case 6: value = -4.0*Rv*k*k*(r_g*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f) + bv*mu*mu*mu*mu)*f*f*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt2, 0, 0, value); value = -2.0*Rv*k*k*vv_prefac*(r_g*(1.0+fnl*Ak)*beta_sd/bv - r_g*fnl*Ak/(f*bv) + 2.0*mu*mu)*f*dendamp*Pmt; gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); value = -4.0*Rv*k*k*P_uu/bv; gsl_matrix_set(dPdt2, 1, 1, value); break; // Differential w.r.t Rd case 7: value = 2.0*k*k*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*f*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak))*dendamp*dendamp*Pmm; gsl_matrix_set(dPdt2, 0, 0, value); value = vv_prefac*k*k*r_g*(1.0+fnl*Ak)*dendamp*Pmt; gsl_matrix_set(dPdt2, 0, 1, value); gsl_matrix_set(dPdt2, 1, 0, value); break; // Differential w.r.t. zp_err case 8: if (nbararray[0][i] > 0.0) { value = 2.0*zp_err_v*zp_err_prefac/nbararray[0][i]; gsl_matrix_set(dPdt2, 1, 1, value); } break; default: break; } } // If we are looking at the bias from the zero-point error, then once we have calculated dPdt2 we want the covariance matrix without // systematics and so without a zero-point offset. The same is true if we want the TRUE covariance matrix if (do_zp_bias) { if (((int)p[6] == 0) || ((int)p[6] == 1)) zp_err_v = 0.0; } // We need to do the overlapping and non-overlapping parts of the surveys separately for (surv=0; surv<3; surv++) { double surv_sum = 0.0; if (survey_area[surv] > 0.0) { double error_obs, error_noise, n_g = 0.0, n_u = 0.0; // Set the nbar for each section. if (surv == 0) { n_g = nbararray[1][i]; } else if (surv == 1) { error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter) error_noise = error_rand*error_rand + error_obs*error_obs + zp_err_v*zp_err_v; // Error_noise is in km^{2}s^{-2} n_u = nbararray[0][i]/error_noise; } else { error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter) error_noise = error_rand*error_rand + error_obs*error_obs + zp_err_v*zp_err_v; // Error_noise is in km^{2}s^{-2} n_u = nbararray[0][i]/error_noise; n_g = nbararray[1][i]; } //printf("%lf, %lf, %lf\n", r, n_g, 1.0e6*n_u); if (!((n_u > 0.0) || (n_g > 0.0))) continue; // First we need the determinant. double det = 1.0 + n_u*n_g*(P_gg*P_uu - P_ug*P_ug) + n_u*P_uu + n_g*P_gg; // Now the inverse matrix. gsl_matrix * iP = gsl_matrix_calloc(2, 2); value = n_u*n_g*P_uu + n_g; gsl_matrix_set(iP, 0, 0, value); value = n_g*n_u*P_gg + n_u; gsl_matrix_set(iP, 1, 1, value); value = - n_g*n_u*P_ug; gsl_matrix_set(iP, 0, 1, value); gsl_matrix_set(iP, 1, 0, value); // Finally we need to compute the Fisher integrand by summing over the inverse and differential matrices for (j=0; j<2; j++) { for (m=0; m<2; m++) { for (u=0; u<2; u++) { for (q=0; q<2; q++) { value = gsl_matrix_get(dPdt1, j, q)*gsl_matrix_get(iP, q, u)*gsl_matrix_get(dPdt2, u, m)*gsl_matrix_get(iP, m, j); surv_sum += value; } } } } surv_sum /= det*det; surv_sum *= survey_area[surv]; r_sum += surv_sum; gsl_matrix_free(iP); //printf("%d, %lf, %lf, %lf, %lf, %lf\n", surv, k, mu, r, r_sum, surv_sum); } } //printf("%lf, %lf, %lf, %lf\n", k, mu, r, r_sum); result_sum += r*r*deltar*r_sum; gsl_matrix_free(dPdt1); gsl_matrix_free(dPdt2); } gsl_spline_free(Pmm_spline); gsl_spline_free(Pmt_spline); gsl_spline_free(Ptt_spline); gsl_interp_accel_free(Pmm_acc); gsl_interp_accel_free(Pmt_acc); gsl_interp_accel_free(Ptt_acc); return result_sum; } // Routine to read in the number density as a function of redshift. We need a file containing the left-most edge of each redshift bin and teh number density in that bin. // From this we create arrays to store the bin centre, the bin width, the comoving distance and growth factor at the bin centre and the number density. // The last bin width and bin centre is constructed from the last row of the input and the value of zmax at the top of the code. // ITS VERY IMPORTANT THAT THE NUMBER OF ROWS AND THE REDSHIFTS OF BOTH THE DENSITY AND PV NUMBER DENSITIES MATCH AS THE INTEGRATION OVER Z IS DONE USING THE TRAPEZIUM RULE. // ALSO MAKE NOTE OF THE FACTOR OF 1.0e-6 ON LINE 827. THIS IS BECAUSE I TYPICALLY SAVE THE VALUE OF NBAR x 10^6 IN THE INPUT FILES< SO THAT I DON'T LOSE PRECISION // WHEN SMALL VALUES OF THE NUMBER DENSITY ARE WRITTEN TO A FILE! void read_nz() { FILE * fp; char buf[500]; int i, nsamp; NRED = (int *)calloc(2, sizeof(int)); nbararray = (double **)calloc(2, sizeof(double*)); double * zinarray; for (nsamp = 0; nsamp < 2; nsamp++) { if(!(fp = fopen(nbar_file[nsamp], "r"))) { printf("\nERROR: Can't open nbar file '%s'.\n\n", nbar_file[nsamp]); exit(0); } NRED[nsamp] = 0; while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tz, tnbar; if(sscanf(buf, "%lf %lf\n", &tz, &tnbar) != 2) {printf("nbar read error\n"); exit(0);}; if (tz > zmax) break; NRED[nsamp]++; } } fclose(fp); if (nsamp == 0) zinarray = (double *)calloc(NRED[nsamp], sizeof(double)); nbararray[nsamp] = (double *)calloc(NRED[nsamp], sizeof(double)); NRED[nsamp] = 0; fp = fopen(nbar_file[nsamp], "r"); while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tz, tnbar; if(sscanf(buf, "%lf %lf\n", &tz, &tnbar) != 2) {printf("nbar read error\n"); exit(0);}; if (tz > zmax) break; if (nsamp == 0) zinarray[NRED[nsamp]] = tz; nbararray[nsamp][NRED[nsamp]] = 1.0e-6*tnbar; NRED[nsamp]++; } } fclose(fp); } if (NRED[1] != NRED[0]) { printf("ERROR: The number of redshift bins for each sample must match\n"); exit(0); } zarray = (double *)calloc(NRED[0], sizeof(double)); rarray = (double *)calloc(NRED[0], sizeof(double)); ezarray = (double *)calloc(NRED[0], sizeof(double)); deltararray = (double *)calloc(NRED[0], sizeof(double)); growtharray = (double *)calloc(NRED[0], sizeof(double)); for (i=0; i<NRED[0]-1; i++) { zarray[i] = (zinarray[i+1]+zinarray[i])/2.0; rarray[i] = rz(zarray[i]); ezarray[i] = 1.0/ezinv(zarray[i], NULL); deltararray[i] = rz(zinarray[i+1]) - rz(zinarray[i]); growtharray[i] = growthz(zarray[i])/growthz(0.0); //printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\n", zarray[i], rarray[i], deltararray[i], growtharray[i], nbararray[0][i], nbararray[1][i]); } zarray[NRED[0]-1] = (zmax+zinarray[NRED[0]-1])/2.0; rarray[NRED[0]-1] = rz(zarray[NRED[0]-1]); ezarray[NRED[0]-1] = 1.0/ezinv(zarray[NRED[0]-1], NULL); deltararray[NRED[0]-1] = rz(zmax) - rz(zinarray[NRED[0]-1]); growtharray[NRED[0]-1] = growthz(zarray[NRED[0]-1])/growthz(0.0); //printf("%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\n", zarray[NRED[0]-1], rarray[NRED[0]-1], deltararray[NRED[0]-1], growtharray[NRED[0]-1], nbararray[0][NRED[0]-1], nbararray[1][NRED[0]-1]); growth_acc = gsl_interp_accel_alloc(); growth_spline = gsl_spline_alloc(gsl_interp_cspline, NRED[0]); gsl_spline_init(growth_spline, zarray, growtharray, NRED[0]); free(zinarray); // Also create a simple redshift-distance spline int nbins = 400; double REDMIN = 0.0; double REDMAX = 2.0; double redbinwidth = (REDMAX-REDMIN)/(double)(nbins-1); double RMIN = rz(REDMIN); double RMAX = rz(REDMAX); double * ztemp = (double *)malloc(nbins*sizeof(double)); double * rtemp = (double *)malloc(nbins*sizeof(double)); for (i=0;i<nbins;i++) { ztemp[i] = i*redbinwidth+REDMIN; rtemp[i] = rz(ztemp[i]); } r_acc = gsl_interp_accel_alloc(); r_spline = gsl_spline_alloc(gsl_interp_cspline, nbins); gsl_spline_init(r_spline, ztemp, rtemp, nbins); free(ztemp); free(rtemp); return; } // Routine to read in the velocity power spectrum. void read_power() { FILE * fp; char buf[500]; int i, j; pmmarray = (double**)malloc(nzin*sizeof(double*)); pmtarray = (double**)malloc(nzin*sizeof(double*)); pttarray = (double**)malloc(nzin*sizeof(double*)); for (i = 0; i<nzin; i++) { char Pvel_file_in[500]; sprintf(Pvel_file_in, "%s_z0p%02d.dat", Pvel_file, (int)(100.0*zin[i])); if(!(fp = fopen(Pvel_file_in, "r"))) { printf("\nERROR: Can't open power file '%s'.\n\n", Pvel_file_in); exit(0); } NK = 0; while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, pkdelta, pkdeltavel, pkvel; if(sscanf(buf, "%lf %lf %lf %lf\n", &tk, &pkdelta, &pkdeltavel, &pkvel) != 4) {printf("Pvel read error\n"); exit(0);}; NK++; } } fclose(fp); if (i == 0) { karray = (double *)calloc(NK, sizeof(double)); deltakarray = (double *)calloc(NK-1, sizeof(double)); } pmmarray[i] = (double *)calloc(NK, sizeof(double)); pmtarray[i] = (double *)calloc(NK, sizeof(double)); pttarray[i] = (double *)calloc(NK, sizeof(double)); NK = 0; fp = fopen(Pvel_file_in, "r"); while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, pkdelta, pkdeltavel, pkvel; if(sscanf(buf, "%lf %lf %lf %lf\n", &tk, &pkdelta, &pkdeltavel, &pkvel) != 4) {printf("Pvel read error\n"); exit(0);}; if (i == 0) karray[NK] = tk; pttarray[i][NK] = pkvel; pmmarray[i][NK] = pkdelta; pmtarray[i][NK] = pkdeltavel; NK++; } } fclose(fp); } for (i=0; i<NK-1; i++) deltakarray[i] = karray[i+1]-karray[i]; pkkmin = karray[0]; pkkmax = karray[NK-1]; if (pkkmax < kmax) { printf("ERROR: The maximum k in the input power spectra is less than k_max\n"); exit(0); } return; } // Routine to read in the transfer function. void read_transfer() { FILE * fp; char buf[500]; int i; if(!(fp = fopen(Trans_file, "r"))) { printf("\nERROR: Can't open transfer function file '%s'.\n\n", Trans_file); exit(0); } int NTK = 0; while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, ttk; if(sscanf(buf, "%lf %lf\n", &tk, &ttk) != 2) {printf("Transfer read error\n"); exit(0);}; NTK++; } } fclose(fp); double * tkarray = (double *)calloc(NTK, sizeof(double)); double * ttkarray = (double *)calloc(NTK, sizeof(double)); NTK = 0; fp = fopen(Trans_file, "r"); while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, ttk; if(sscanf(buf, "%lf %lf\n", &tk, &ttk) != 2) {printf("Transfer read error\n"); exit(0);}; tkarray[NTK] = tk; ttkarray[NTK] = ttk; NTK++; } } fclose(fp); // Spline the transfer function Trans_acc = gsl_interp_accel_alloc(); Trans_spline = gsl_spline_alloc(gsl_interp_cspline, NTK); gsl_spline_init(Trans_spline, tkarray, ttkarray, NTK); free(tkarray); free(ttkarray); return; } // Integrand for the comoving distance double ezinv(double x, void *p) { return 1.0/sqrt(Om*(1.0+x)*(1.0+x)*(1.0+x)+(1.0-Om)); } // Calculates the comoving distance from the redshift double rz(double red) { double result, error; gsl_function F; gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000); F.function = &ezinv; gsl_integration_qags(&F, 0.0, red, 0, 1e-7, 1000, w, &result, &error); gsl_integration_workspace_free(w); return c*result/100.0; } // The integrand for the normalised growth factor double growthfunc(double x, void *p) { double red = 1.0/x - 1.0; double Omz = Om*ezinv(red,NULL)*ezinv(red,NULL)/(x*x*x); double f = pow(Omz, gammaval); return f/x; } // Calculates the normalised growth factor as a function of redshift given a value of gammaval double growthz(double red) { double result, error; gsl_function F; gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000); F.function = &growthfunc; double a = 1.0/(1.0+red); gsl_integration_qags(&F, a, 1.0, 0, 1e-7, 1000, w, &result, &error); gsl_integration_workspace_free(w); return exp(-result); }
{ "alphanum_fraction": 0.5589691298, "avg_line_length": 49.2331983806, "ext": "c", "hexsha": "707baea25f9a009483bfcee33f81c9f939130b0d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-09-20T11:31:54.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-20T11:31:54.000Z", "max_forks_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LBJ-Wade/PV_fisher", "max_forks_repo_path": "PV_fisher_extended.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15", "max_issues_repo_issues_event_max_datetime": "2019-02-05T08:34:03.000Z", "max_issues_repo_issues_event_min_datetime": "2017-08-30T17:39:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LBJ-Wade/PV_fisher", "max_issues_repo_path": "PV_fisher_extended.c", "max_line_length": 286, "max_stars_count": 2, "max_stars_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LBJ-Wade/PV_fisher", "max_stars_repo_path": "PV_fisher_extended.c", "max_stars_repo_stars_event_max_datetime": "2022-03-04T11:39:16.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-01T15:07:11.000Z", "num_tokens": 17679, "size": 60803 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_core_narrow_inl_h_ #define SQ_INCLUDE_GUARD_core_narrow_inl_h_ #include "core/errors.h" #include <fmt/format.h> #include <fmt/ostream.h> #include <gsl/gsl> namespace sq { template <typename T, typename U, typename... FormatArgs> constexpr T narrow(U value, FormatArgs &&...format_args) { try { return gsl::narrow<T>(value); } catch (gsl::narrowing_error &e) { throw NarrowingError{T{}, value, SQ_FWD(format_args)...}; } } constexpr gsl::index to_index(auto value, auto &&...format_args) { return narrow<gsl::index>(SQ_FWD(value), SQ_FWD(format_args)...); } constexpr std::size_t to_size(auto value, auto &&...format_args) { return narrow<std::size_t>(SQ_FWD(value), SQ_FWD(format_args)...); } } // namespace sq #endif // SQ_INCLUDE_GUARD_core_narrow_inl_h_
{ "alphanum_fraction": 0.61003861, "avg_line_length": 28, "ext": "h", "hexsha": "78ef23acfcca8cbbedfd91b776b617b3ed89efcd", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/core/include/core/narrow.inl.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/core/include/core/narrow.inl.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/core/include/core/narrow.inl.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 237, "size": 1036 }
// SPDX-License-Identifier: MIT // The MIT License (MIT) // // Copyright (c) 2014-2018, Institute for Software & Systems Engineering // Copyright (c) 2018-2019, Johannes Leupolz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef PEMC_GENERIC_TRAVERSER_TRAVERSAL_TRANSITION_H_ #define PEMC_GENERIC_TRAVERSER_TRAVERSAL_TRANSITION_H_ #include <gsl/gsl_byte> #include <cstdint> #include "pemc/basic/tsc_index.h" #include "pemc/basic/label.h" namespace pemc { enum TraversalTransitionFlags : uint32_t { NoFlag, /// If set, the value of targetStateIndex is set and targetState is invalid. /// If unset, the value of targetState is set and targetStateIndex is invalid. IsTargetStateTransformedToIndex = 1, /// If set, the transition is invalid and should be ignored IsTransitionInvalid = 2, /// If set, the transition leads to the stuttering state and the state in targetState /// shall be ignored. IsToStutteringState = 4 }; struct TraversalTransition { // 4 bytes / 8 bytes union { gsl::byte* targetState; // is set prior to adding the state to state storage StateIndex targetStateIndex; // is set after having added the state to state storage }; // 4 bytes TraversalTransitionFlags flags; // 4 bytes Label label; TraversalTransition() : targetState(nullptr), flags(TraversalTransitionFlags::NoFlag), label(Label()){ } TraversalTransition(gsl::byte* _targetState, Label _label) : targetState(_targetState), flags(TraversalTransitionFlags::NoFlag), label(_label) { } }; inline TraversalTransitionFlags operator|(TraversalTransitionFlags a, TraversalTransitionFlags b) { return static_cast<TraversalTransitionFlags>(static_cast<uint32_t>(a) | static_cast<uint32_t>(b)); } inline TraversalTransitionFlags operator|=(TraversalTransitionFlags a, const TraversalTransitionFlags b) { a = static_cast<TraversalTransitionFlags>(static_cast<uint32_t>(a) | static_cast<uint32_t>(b)); return a; } } #endif // PEMC_GENERIC_TRAVERSER_TRAVERSAL_TRANSITION_H_
{ "alphanum_fraction": 0.7459147709, "avg_line_length": 36.2906976744, "ext": "h", "hexsha": "c69a88437875a9e8fb5e70429fe5149c836cf3a4", "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": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_path": "pemc/generic_traverser/traversal_transition.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "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": "joleuger/pemc", "max_issues_repo_path": "pemc/generic_traverser/traversal_transition.h", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_path": "pemc/generic_traverser/traversal_transition.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 739, "size": 3121 }
#ifndef Performance_h #define Performance_h 1 #include <vector> #include <gsl/gsl_errno.h> // if p0 is less than chop, then set to zero, associated with calling routine chop const double chop = 1e-3; const double p1bound = 1e-5; void debugPerformanceOn(unsigned); enum class signalType {output, controlOpen, controlClosed}; double performance(const std::vector<double>& num, const std::vector<double>& den, double gamma, double tmax, signalType s); // GSL error handling: call setGSLErrorHandle(s), s = 0 turns off error handler, 1 sets my handler; should check return status of all significant GSL calls and take appropriate action within code, for example return high performance value and thus zero fitness if cannot evaluate performance for parameter combination inline void my_gsl_handler (const char *reason, const char *file, int line, int gsl_errno __attribute__((unused))) {std::cout << fmt::format("GSL error: {}:{}, {}\n", file, line, reason);} inline void setGSLErrorHandle(int s) {(s) ? gsl_set_error_handler(&my_gsl_handler) : gsl_set_error_handler_off();} #endif
{ "alphanum_fraction": 0.7607305936, "avg_line_length": 43.8, "ext": "h", "hexsha": "bac9a3e6b48216f463cffdab6e2d4630fbb358d9", "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": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "evolbio/design2", "max_forks_repo_path": "src/Performance.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "evolbio/design2", "max_issues_repo_path": "src/Performance.h", "max_line_length": 317, "max_stars_count": null, "max_stars_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "evolbio/design2", "max_stars_repo_path": "src/Performance.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 263, "size": 1095 }
#include <config.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_dft_complex.h> #include <gsl/gsl_dft_complex_float.h> #include "complex_internal.h" #include "urand.c" #define BASE_DOUBLE #include "templates_on.h" #include "signals_source.c" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "signals_source.c" #include "templates_off.h" #undef BASE_FLOAT
{ "alphanum_fraction": 0.7613412229, "avg_line_length": 18.7777777778, "ext": "c", "hexsha": "9869abe168a6cf01f920309eeffd25706027997e", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/fft/signals.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/fft/signals.c", "max_line_length": 38, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/fft/signals.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 131, "size": 507 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <complex.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_integration.h> // Code to calculate the covariance matrix for fitting the peculiar velocities of the 2MTF simulations. // Generates a grid covering -120<x<120 Mpc/h and similar for y/z so should cover the full data. // When applied to particular simulations, you need to remove the rows/columns from the matrix // that contain no galaxies. // Run parameters static double LightSpeed = 299792.458; double omega_m; double sigma_u; struct fparams{ gsl_spline * spline_P; gsl_interp_accel * acc_P; gsl_spline * spline_grid; gsl_interp_accel * acc_grid; double dist; int ell; int pq; int damping; int gridcorr; }; gsl_interp_accel * P_mm_acc, * P_vm_acc, * P_vv_acc, * gridcorr_acc; gsl_spline * P_mm_spline, * P_vm_spline, * P_vv_spline, * gridcorr_spline; gsl_interp_accel **** xi_dd_acc, **** xi_dv_acc, *** xi_vv_acc; gsl_spline **** xi_dd_spline, **** xi_dv_spline, *** xi_vv_spline; double ffunc(double x, void *p) { double ff = (LightSpeed/100.0)/sqrt(omega_m*(1.0+x)*(1.0+x)*(1.0+x)+(1.0-omega_m)); //This calculates c/H return ff; } double rz(double red) {//This calculates the redshift to the galaxy double result, error; gsl_function F; gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000); F.function = &ffunc; gsl_integration_qags(&F, 0.0, red, 0, 1e-7, 1000, w, &result, &error); gsl_integration_workspace_free(w); return result; } double D_u(double k) {//The damping term due to redshift space distortion double result; if (k*sigma_u < 1e-10) { result = 1; } else { result = sin(k*sigma_u)/(k*sigma_u); } return result; } double conv_integrand(double k, void * p) { struct fparams params = *(struct fparams *) p; double damping = 1.0; if (params.damping == 1) damping = D_u(k); if (params.damping == 2) damping = pow(D_u(k), 2.0); double gridcorr = 1.0; if (params.gridcorr == 1) gridcorr = gsl_spline_eval(gridcorr_spline, k, gridcorr_acc); double function = pow(k, params.pq+2)*gsl_spline_eval(params.spline_P, k, params.acc_P)*gridcorr*damping*gsl_sf_bessel_jl(params.ell,k*params.dist); return function; } double conv_integral(double kmin, double kmax, double dist, int abtype, int ell, int pq, int gridcorr, int damping) { double result, error; struct fparams params; if (abtype == 0) { params.spline_P = P_mm_spline; params.acc_P = P_mm_acc; } if (abtype == 1) { params.spline_P = P_vm_spline; params.acc_P = P_vm_acc; } if (abtype == 2) { params.spline_P = P_vv_spline; params.acc_P = P_vv_acc; } params.ell = ell; params.pq = pq; params.dist = dist; params.damping = damping; params.gridcorr = gridcorr; gsl_function F; gsl_integration_cquad_workspace * w = gsl_integration_cquad_workspace_alloc(1000); F.function = &conv_integrand; F.params = &params; gsl_integration_cquad(&F, kmin, kmax, 0, 1e-5, w, &result, &error, NULL); gsl_integration_cquad_workspace_free(w); return result; } double H_vv(int ell, double theta, double phi) { if (ell == 0){ return cos(theta)/3.0; } else if (ell == 2) { return (3.0*cos(2.0*phi) + cos(theta))/6.0; } else { return 0; } } double H_dv(int ell, int p, double theta, double phi) { if (ell == 1) { if (p == 0) { return -cos(phi + theta/2.); } else if (p == 1) { return (-cos(phi - (3*theta)/2.) - 2*cos(phi + theta/2.))/5.; } else if (p == 2) { return (-3*(2*cos(phi - (3*theta)/2.) + 3*cos(phi + theta/2.)))/35.; } else if (p == 3) { return (-3*cos(phi - (3*theta)/2.) - 4*cos(phi + theta/2.))/21.; } else if (p == 4) { return (-4*cos(phi - (3*theta)/2.) - 5*cos(phi + theta/2.))/33.; } } else if (ell == 3) { if (p == 1) { return (-cos(phi - (3*theta)/2.) - 5*cos(3*phi - theta/2.) - 2*cos(phi + theta/2.))/20.; } else if (p == 2) { return (-5*cos(3*phi - (5*theta)/2.) - 6*cos(phi - (3*theta)/2.) - 20*cos(3*phi - theta/2.) - 9*cos(phi + theta/2.))/90.; } else if (p == 3) { return (-10*cos(3*phi - (5*theta)/2.) - 9*cos(phi - (3*theta)/2.) - 25*cos(3*phi - theta/2.) - 12*cos(phi + theta/2.))/132.; } else if (p == 4) { return (-7*(5*cos(3*phi - (5*theta)/2.) + 4*cos(phi - (3*theta)/2.) + 10*cos(3*phi - theta/2.) + 5*cos(phi + theta/2.)))/429.; } } else if (ell == 5) { if (p == 2) { return (-7*cos(3*phi - (5*theta)/2.) - 12*cos(phi - (3*theta)/2.) - 63*cos(5*phi - (3*theta)/2.) - 28*cos(3*phi - theta/2.) - 18*cos(phi + theta/2.))/1008.; } else if (p == 3) { return (-63*cos(5*phi - (7*theta)/2.) - 70*cos(3*phi - (5*theta)/2.) - 90*cos(phi - (3*theta)/2.) - 378*cos(5*phi - (3*theta)/2.) - 175*cos(3*phi - theta/2.) - 120*cos(phi + theta/2.))/4368.; } else if (p == 4) { return (-42*cos(5*phi - (7*theta)/2.) - 35*cos(3*phi - (5*theta)/2.) - 40*cos(phi - (3*theta)/2.) - 147*cos(5*phi - (3*theta)/2.) - 70*cos(3*phi - theta/2.) - 50*cos(phi + theta/2.))/1560.; } } else if (ell == 7) { if (p == 3) { return (-33*cos(5*phi - (7*theta)/2.) - 54*cos(3*phi - (5*theta)/2.) - 429*cos(7*phi - (5*theta)/2.) - 75*cos(phi - (3*theta)/2.) - 198*cos(5*phi - (3*theta)/2.) - 135*cos(3*phi - theta/2.) - 100*cos(phi + theta/2.))/27456.; } else if (p == 4) { return (-429*cos(7*phi - (9*theta)/2.) - 462*cos(5*phi - (7*theta)/2.) - 567*cos(3*phi - (5*theta)/2.) - 3432*cos(7*phi - (5*theta)/2.) - 700*cos(phi - (3*theta)/2.) - 1617*cos(5*phi - (3*theta)/2.) - 1134*cos(3*phi - theta/2.) - 875*cos(phi + theta/2.))/116688.; } } else if (ell == 9) { if (p == 4) { return (-715*cos(7*phi - (9*theta)/2.) - 1144*cos(5*phi - (7*theta)/2.) - 12155*cos(9*phi - (7*theta)/2.) - 1540*cos(3*phi - (5*theta)/2.) - 5720*cos(7*phi - (5*theta)/2.) - 1960*cos(phi - (3*theta)/2.) - 4004*cos(5*phi - (3*theta)/2.) - 3080*cos(3*phi - theta/2.) - 2450*cos(phi + theta/2.))/3.11168e6; } } return 0; } double H_dd_0(int p, int q, double theta, double phi) { switch(p) { case 0: switch(q) { case 0: return 1.0; case 1: return 1.0/3.0; case 2: return 1.0/5.0; case 3: return 1.0/7.0; case 4: return 1.0/9.0; default: return 0.0; } case 1: switch(q) { case 0: return 1.0/3.0; case 1: return (2 + cos(2*theta))/15.; case 2: return (3 + 2*cos(2*theta))/35.; case 3: return (4 + 3*cos(2*theta))/63.; case 4: return (5 + 4*cos(2*theta))/99.; default: return 0.0; } case 2: switch(q) { case 0: return 1.0/5.0; case 1: return (3 + 2*cos(2*theta))/35.; case 2: return (18 + 16*cos(2*theta) + cos(4*theta))/315.; case 3: return (10 + 10*cos(2*theta) + cos(4*theta))/231.; case 4: return (15 + 16*cos(2*theta) + 2*cos(4*theta))/429.; default: return 0.0; } case 3: switch(q) { case 0: return 1.0/7.0; case 1: return (4 + 3*cos(2*theta))/63.; case 2: return (10 + 10*cos(2*theta) + cos(4*theta))/231.; case 3: return (200 + 225*cos(2*theta) + 36*cos(4*theta) + cos(6*theta))/6006.; case 4: return (175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta))/6435.; default: return 0.0; } case 4: switch(q) { case 0: return 1.0/9.0; case 1: return (5 + 4*cos(2*theta))/99.; case 2: return (15 + 16*cos(2*theta) + 2*cos(4*theta))/429.; case 3: return (175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta))/6435.; case 4: return (2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + cos(8*theta))/109395.; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_2(int p, int q, double theta, double phi) { switch(p) { case 0: switch(q) { case 1: return (1 + 3*cos(2*phi + theta))/6.; case 2: return (1 + 3*cos(2*phi + theta))/7.; case 3: return (5*(1 + 3*cos(2*phi + theta)))/42.; case 4: return (10*(1 + 3*cos(2*phi + theta)))/99.; default: return 0.0; } case 1: switch(q) { case 0: return (1 + 3*cos(2*phi - theta))/6.; case 1: return (2 + 9*cos(2*phi)*cos(theta) + cos(2*theta))/21.; case 2: return (3 + 6*cos(2*phi - theta) + 2*cos(2*theta) + 8*cos(2*phi + theta) + cos(2*phi + 3*theta))/42.; case 3: return (5*(16 + 30*cos(2*phi - theta) + 12*cos(2*theta) + 45*cos(2*phi + theta) + 9*cos(2*phi + 3*theta)))/1386.; case 4: return (5*(25 + 45*cos(2*phi - theta) + 20*cos(2*theta) + 72*cos(2*phi + theta) + 18*cos(2*phi + 3*theta)))/2574.; default: return 0.0; } case 2: switch(q) { case 0: return (1 + 3*cos(2*phi - theta))/7.; case 1: return (3 + cos(2*phi - 3*theta) + 14*cos(2*phi)*cos(theta) + 2*cos(2*theta) + 2*sin(2*phi)*sin(theta))/42.; case 2: return (2*(18 + 16*cos(2*theta) + 15*cos(2*phi)*(6*cos(theta) + cos(3*theta)) + cos(4*theta)))/693.; case 3: return (5*(100 + 45*cos(2*phi - 3*theta) + 240*cos(2*phi - theta) + 100*cos(2*theta) + 10*cos(4*theta) + 270*cos(2*phi + theta) + 72*cos(2*phi + 3*theta) + 3*cos(2*phi + 5*theta)))/12012.; case 4: return (15 + 7*cos(2*phi - 3*theta) + 35*cos(2*phi - theta) + 16*cos(2*theta) + 2*cos(4*theta) + 42*cos(2*phi + theta) + 14*cos(2*phi + 3*theta) + cos(2*phi + 5*theta))/429.; default: return 0.0; } case 3: switch(q) { case 0: return (5*(1 + 3*cos(2*phi - theta)))/42.; case 1: return (5*(16 + 9*cos(2*phi - 3*theta) + 75*cos(2*phi)*cos(theta) + 12*cos(2*theta) + 15*sin(2*phi)*sin(theta)))/1386.; case 2: return (5*(3*cos(2*phi - 5*theta) + 3*cos(2*phi)*(170*cos(theta) + 39*cos(3*theta)) + 10*(10 + 10*cos(2*theta) + cos(4*theta)) + 3*sin(2*phi)*(10*sin(theta) + 9*sin(3*theta))))/12012.; case 3: return (200 + 225*cos(2*theta) + 36*cos(4*theta) + 42*cos(2*phi)*cos(theta)*(18 + 14*cos(2*theta) + cos(4*theta)) + cos(6*theta))/6006.; case 4: return (1225 + 84*cos(2*phi - 5*theta) + 1008*cos(2*phi - 3*theta) + 3150*cos(2*phi - theta) + 1470*cos(2*theta) + 294*cos(4*theta) + 14*cos(6*theta) + 3360*cos(2*phi + theta) + 1260*cos(2*phi + 3*theta) + 144*cos(2*phi + 5*theta) + 3*cos(2*phi + 7*theta))/43758.; default: return 0.0; } case 4: switch(q) { case 0: return (10*(1 + 3*cos(2*phi - theta)))/99.; case 1: return (5*(25 + 18*cos(2*phi - 3*theta) + 117*cos(2*phi)*cos(theta) + 20*cos(2*theta) + 27*sin(2*phi)*sin(theta)))/2574.; case 2: return (15 + cos(2*phi - 5*theta) + 16*cos(2*theta) + 2*cos(4*theta) + 14*cos(theta)*(cos(2*phi)*(4 + 3*cos(2*theta)) + sin(2*phi)*sin(2*theta)))/429.; case 3: return (3*cos(2*phi - 7*theta) + 6*cos(2*phi)*(1085*cos(theta) + 378*cos(3*theta) + 38*cos(5*theta)) + 7*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 6*sin(2*phi)*(35*sin(theta) + 42*sin(3*theta) + 10*sin(5*theta)))/43758.; case 4: return (4*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + 27*cos(2*phi)*(490*cos(theta) + 28*(7*cos(3*theta) + cos(5*theta)) + cos(7*theta)) + cos(8*theta)))/415701.; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_4(int p, int q, double theta, double phi) { switch(p) { case 0: switch(q) { case 2: return (9 + 20*cos(2*phi + theta) + 35*cos(2*(2*phi + theta)))/280.; case 3: return (3*(9 + 20*cos(2*phi + theta) + 35*cos(2*(2*phi + theta))))/616.; case 4: return (3*(9 + 20*cos(2*phi + theta) + 35*cos(2*(2*phi + theta))))/572.; default: return 0.0; } case 1: switch(q) { case 1: return (6 + 35*cos(4*phi) + 20*cos(2*phi)*cos(theta) + 3*cos(2*theta))/280.; case 2: return (81 + 350*cos(4*phi) + 120*cos(2*phi - theta) + 54*cos(2*theta) + 160*cos(2*phi + theta) + 175*cos(2*(2*phi + theta)) + 20*cos(2*phi + 3*theta))/3080.; case 3: return (3*(144 + 525*cos(4*phi) + 200*cos(2*phi - theta) + 108*cos(2*theta) + 35*cos(4*(phi + theta)) + 300*cos(2*phi + theta) + 420*cos(2*(2*phi + theta)) + 60*cos(2*phi + 3*theta)))/16016.; case 4: return (15 + 49*cos(4*phi) + 20*cos(2*phi - theta) + 12*cos(2*theta) + 7*cos(4*(phi + theta)) + 32*cos(2*phi + theta) + 49*cos(2*(2*phi + theta)) + 8*cos(2*phi + 3*theta))/572.; default: return 0.0; } case 2: switch(q) { case 0: return (9 + 35*cos(4*phi - 2*theta) + 20*cos(2*phi - theta))/280.; case 1: return (81 + 350*cos(4*phi) + 20*cos(2*phi - 3*theta) + 175*cos(4*phi - 2*theta) + 280*cos(2*phi)*cos(theta) + 54*cos(2*theta) + 40*sin(2*phi)*sin(theta))/3080.; case 2: return (3*(175*cos(4*phi)*(4 + 3*cos(2*theta)) + 100*cos(2*phi)*(6*cos(theta) + cos(3*theta)) + 9*(18 + 16*cos(2*theta) + cos(4*theta))))/20020.; case 3: return (180 + 735*cos(4*phi) + 60*cos(2*phi - 3*theta) + 245*cos(4*phi - 2*theta) + 320*cos(2*phi - theta) + 180*cos(2*theta) + 18*cos(4*theta) + 49*cos(4*(phi + theta)) + 360*cos(2*phi + theta) + 441*cos(2*(2*phi + theta)) + 96*cos(2*phi + 3*theta) + 4*cos(2*phi + 5*theta))/8008.; case 4: return (405 + 1568*cos(4*phi) + 140*cos(2*phi - 3*theta) + 490*cos(4*phi - 2*theta) + 700*cos(2*phi - theta) + 432*cos(2*theta) + 54*cos(4*theta) + 224*cos(4*(phi + theta)) + 840*cos(2*phi + theta) + 1176*cos(2*(2*phi + theta)) + 280*cos(2*phi + 3*theta) + 20*cos(2*phi + 5*theta) + 7*cos(4*phi + 6*theta))/19448.; default: return 0.0; } case 3: switch(q) { case 0: return (3*(9 + 35*cos(4*phi - 2*theta) + 20*cos(2*phi - theta)))/616.; case 1: return (3*(144 + 525*cos(4*phi) + 60*cos(2*phi - 3*theta) + 420*cos(4*phi - 2*theta) + 35*cos(4*(phi - theta)) + 500*cos(2*phi)*cos(theta) + 108*cos(2*theta) + 100*sin(2*phi)*sin(theta)))/16016.; case 2: return (4*cos(2*phi - 5*theta) + 4*cos(2*phi)*(170*cos(theta) + 39*cos(3*theta)) + 18*(10 + 10*cos(2*theta) + cos(4*theta)) + 49*cos(4*phi)*(15 + 14*cos(2*theta) + cos(4*theta)) + 4*sin(2*phi)*(10*sin(theta) + 9*sin(3*theta)) + 49*sin(4*phi)*(4*sin(2*theta) + sin(4*theta)))/8008.; case 3: return (3*(490*cos(4*phi)*(15 + 16*cos(2*theta) + 2*cos(4*theta)) + 140*cos(2*phi)*(50*cos(theta) + 15*cos(3*theta) + cos(5*theta)) + 9*(200 + 225*cos(2*theta) + 36*cos(4*theta) + cos(6*theta))))/272272.; case 4: return (3*(44100*cos(4*phi) + 560*cos(2*phi - 5*theta) + 6720*cos(2*phi - 3*theta) + 22050*cos(4*phi - 2*theta) + 2940*cos(4*(phi - theta)) + 21000*cos(2*phi - theta) + 13230*cos(2*theta) + 2646*cos(4*theta) + 126*cos(6*theta) + 5*(1260*cos(4*(phi + theta)) + 4480*cos(2*phi + theta) + 5880*cos(2*(2*phi + theta)) + 1680*cos(2*phi + 3*theta) + 192*cos(2*phi + 5*theta) + 63*(35 + cos(4*phi + 6*theta)) + 4*cos(2*phi + 7*theta))))/1.84756e6; default: return 0.0; } case 4: switch(q) { case 0: return (3*(9 + 35*cos(4*phi - 2*theta) + 20*cos(2*phi - theta)))/572.; case 1: return (15 + 49*cos(4*phi) + 8*cos(2*phi - 3*theta) + 49*cos(4*phi - 2*theta) + 7*cos(4*(phi - theta)) + 52*cos(2*phi)*cos(theta) + 12*cos(2*theta) + 12*sin(2*phi)*sin(theta))/572.; case 2: return (405 + 7*cos(4*phi - 6*theta) + 20*cos(2*phi - 5*theta) + 224*cos(4*(phi - theta)) + 432*cos(2*theta) + 98*cos(4*phi)*(16 + 17*cos(2*theta)) + 54*cos(4*theta) + 280*cos(theta)*(4*cos(2*phi) + 2*cos(2*(phi - theta)) + cos(2*(phi + theta))) + 686*sin(4*phi)*sin(2*theta))/19448.; case 3: return (3*(20*cos(2*phi - 7*theta) + 40*cos(2*phi)*(1085*cos(theta) + 378*cos(3*theta) + 38*cos(5*theta)) + 63*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 105*cos(4*phi)*(420 + 490*cos(2*theta) + 88*cos(4*theta) + 3*cos(6*theta)) + 40*sin(2*phi)*(35*sin(theta) + 42*sin(3*theta) + 10*sin(5*theta)) + 105*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta))))/1.84756e6; case 4: return (3*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + 175*cos(4*phi)*(56 + 70*cos(2*theta) + 16*cos(4*theta) + cos(6*theta)) + 20*cos(2*phi)*(490*cos(theta) + 28*(7*cos(3*theta) + cos(5*theta)) + cos(7*theta)) + cos(8*theta)))/461890.; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_6(int p, int q, double theta, double phi) { switch(p) { case 0: switch(q) { case 3: return (50 + 105*cos(2*phi + theta) + 126*cos(2*(2*phi + theta)) + 231*cos(3*(2*phi + theta)))/7392.; case 4: return (50 + 105*cos(2*phi + theta) + 126*cos(2*(2*phi + theta)) + 231*cos(3*(2*phi + theta)))/3960.; default: return 0.0; } case 1: switch(q) { case 2: return (30 + 84*cos(4*phi) + 42*cos(2*phi - theta) + 20*cos(2*theta) + 56*cos(2*phi + theta) + 42*cos(2*(2*phi + theta)) + 231*cos(6*phi + theta) + 7*cos(2*phi + 3*theta))/7392.; case 3: return (800 + 1890*cos(4*phi) + 1050*cos(2*phi - theta) + 600*cos(2*theta) + 126*cos(4*(phi + theta)) + 1575*cos(2*phi + theta) + 1512*cos(2*(2*phi + theta)) + 1617*cos(3*(2*phi + theta)) + 4851*cos(6*phi + theta) + 315*cos(2*phi + 3*theta))/110880.; case 4: return (1250 + 2646*cos(4*phi) + 1575*cos(2*phi - theta) + 1000*cos(2*theta) + 378*cos(4*(phi + theta)) + 2520*cos(2*phi + theta) + 2646*cos(2*(2*phi + theta)) + 3696*cos(3*(2*phi + theta)) + 6468*cos(6*phi + theta) + 630*cos(2*phi + 3*theta) + 231*cos(6*phi + 5*theta))/134640.; default: return 0.0; } case 2: switch(q) { case 1: return (30 + 84*cos(4*phi) + 7*cos(2*phi - 3*theta) + 42*cos(4*phi - 2*theta) + 56*cos(2*phi - theta) + 231*cos(6*phi - theta) + 20*cos(2*theta) + 42*cos(2*phi + theta))/7392.; case 2: return (1617*cos(6*phi)*cos(theta) + 126*cos(4*phi)*(4 + 3*cos(2*theta)) + 105*cos(2*phi)*(6*cos(theta) + cos(3*theta)) + 10*(18 + 16*cos(2*theta) + cos(4*theta)))/27720.; case 3: return (5000 + 13230*cos(4*phi) + 1575*cos(2*phi - 3*theta) + 4410*cos(4*phi - 2*theta) + 8400*cos(2*phi - theta) + 16170*cos(6*phi - theta) + 5000*cos(2*theta) + 500*cos(4*theta) + 882*cos(4*(phi + theta)) + 9450*cos(2*phi + theta) + 7938*cos(2*(2*phi + theta)) + 6468*cos(3*(2*phi + theta)) + 25872*cos(6*phi + theta) + 2520*cos(2*phi + 3*theta) + 105*cos(2*phi + 5*theta))/628320.; case 4: return (3750 + 9408*cos(4*phi) + 1225*cos(2*phi - 3*theta) + 2940*cos(4*phi - 2*theta) + 6125*cos(2*phi - theta) + 9702*cos(6*phi - theta) + 4000*cos(2*theta) + 500*cos(4*theta) + 1344*cos(4*(phi + theta)) + 7350*cos(2*phi + theta) + 7056*cos(2*(2*phi + theta)) + 8316*cos(3*(2*phi + theta)) + 19404*cos(6*phi + theta) + 2450*cos(2*phi + 3*theta) + 175*cos(2*phi + 5*theta) + 693*cos(6*phi + 5*theta) + 42*cos(4*phi + 6*theta))/426360.; default: return 0.0; } case 3: switch(q) { case 0: return (50 + 231*cos(6*phi - 3*theta) + 126*cos(4*phi - 2*theta) + 105*cos(2*phi - theta))/7392.; case 1: return (800 + 1890*cos(4*phi) + 315*cos(2*phi - 3*theta) + 1617*cos(6*phi - 3*theta) + 1512*cos(4*phi - 2*theta) + 126*cos(4*(phi - theta)) + 1575*cos(2*phi - theta) + 4851*cos(6*phi - theta) + 600*cos(2*theta) + 1050*cos(2*phi + theta))/110880.; case 2: return (105*cos(2*phi - 5*theta) + 882*cos(4*(phi - theta)) + 882*cos(4*phi)*(15 + 14*cos(2*theta)) + 3234*cos(6*phi)*(13*cos(theta) + 2*cos(3*theta)) + 105*cos(2*phi)*(170*cos(theta) + 39*cos(3*theta)) + 500*(10 + 10*cos(2*theta) + cos(4*theta)) + 3528*sin(4*phi)*sin(2*theta) + 3234*sin(6*phi)*(3*sin(theta) + 2*sin(3*theta)) + 105*sin(2*phi)*(10*sin(theta) + 9*sin(3*theta)))/628320.; case 3: return (1764*cos(4*phi)*(15 + 16*cos(2*theta) + 11*cos(2*phi)*cos(theta)*(7 + 4*cos(2*theta)) + 2*cos(4*theta)) + 147*cos(2*phi)*(-344*cos(theta) - 57*cos(3*theta) + 5*cos(5*theta)) + 50*(200 + 225*cos(2*theta) + 36*cos(4*theta) + cos(6*theta)))/1.193808e6; case 4: return (8750 + 22680*cos(4*phi) + 420*cos(2*phi - 5*theta) + 5040*cos(2*phi - 3*theta) + 6930*cos(6*phi - 3*theta) + 11340*cos(4*phi - 2*theta) + 1512*cos(4*(phi - theta)) + 15750*cos(2*phi - theta) + 33264*cos(6*phi - theta) + 10500*cos(2*theta) + 2100*cos(4*theta) + 100*cos(6*theta) + 3240*cos(4*(phi + theta)) + 16800*cos(2*phi + theta) + 15120*cos(2*(2*phi + theta)) + 15840*cos(3*(2*phi + theta)) + 41580*cos(6*phi + theta) + 6300*cos(2*phi + 3*theta) + 720*cos(2*phi + 5*theta) + 1485*cos(6*phi + 5*theta) + 162*cos(4*phi + 6*theta) + 15*cos(2*phi + 7*theta))/1.023264e6; default: return 0.0; } case 4: switch(q) { case 0: return (50 + 231*cos(6*phi - 3*theta) + 126*cos(4*phi - 2*theta) + 105*cos(2*phi - theta))/3960.; case 1: return (2646*cos(4*phi) + 231*cos(6*phi - 5*theta) + 630*cos(2*phi - 3*theta) + 3696*cos(6*phi - 3*theta) + 2646*cos(4*phi - 2*theta) + 378*cos(4*(phi - theta)) + 2520*cos(2*phi - theta) + 6468*cos(6*phi - theta) + 25*(50 + 40*cos(2*theta) + 63*cos(2*phi + theta)))/134640.; case 2: return (42*cos(4*phi - 6*theta) + 175*cos(2*phi - 5*theta) + 693*cos(6*phi - 5*theta) + 1344*cos(4*(phi - theta)) + 588*cos(4*phi)*(16 + 17*cos(2*theta)) + 250*(15 + 16*cos(2*theta) + 2*cos(4*theta)) + 4116*sin(4*phi)*sin(2*theta) + 7*(594*cos(6*phi)*(7*cos(theta) + 2*cos(3*theta)) + 175*cos(2*phi)*(11*cos(theta) + 3*cos(3*theta)) + 700*pow(cos(theta),2)*sin(2*phi)*sin(theta) + 198*sin(6*phi)*(7*sin(theta) + 6*sin(3*theta))))/426360.; case 3: return (99*cos(6*phi)*(756*cos(theta) + 230*cos(3*theta) + 15*cos(5*theta)) + 50*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 54*cos(4*phi)*(420 + 490*cos(2*theta) + 88*cos(4*theta) + 3*cos(6*theta)) + 15*cos(2*phi)*(2170*cos(theta) + 756*cos(3*theta) + 76*cos(5*theta) + cos(7*theta)) + 297*sin(6*phi)*(28*sin(theta) + 30*sin(3*theta) + 5*sin(5*theta)) + 54*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta)) + 15*sin(2*phi)*(70*sin(theta) + 84*sin(3*theta) + 20*sin(5*theta) + sin(7*theta)))/1.023264e6; case 4: return (7623*cos(6*phi)*(28*cos(theta) + 10*cos(3*theta) + cos(5*theta)) + 1134*cos(4*phi)*(56 + 70*cos(2*theta) + 16*cos(4*theta) + cos(6*theta)) + 189*cos(2*phi)*(490*cos(theta) + 28*(7*cos(3*theta) + cos(5*theta)) + cos(7*theta)) + 10*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + cos(8*theta)))/2.941884e6; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_8(int p, int q, double theta, double phi) { switch(p) { case 0: switch(q) { case 4: return (1225 + 2520*cos(2*phi + theta) + 2772*cos(2*(2*phi + theta)) + 3432*cos(3*(2*phi + theta)) + 6435*cos(4*(2*phi + theta)))/823680.; default: return 0.0; } case 1: switch(q) { case 3: return (700 + 1485*cos(4*phi) + 900*cos(2*phi - theta) + 525*cos(2*theta) + 99*cos(4*(phi + theta)) + 1350*cos(2*phi + theta) + 1188*cos(2*(2*phi + theta)) + 858*cos(3*(2*phi + theta)) + 6435*cos(2*(4*phi + theta)) + 2574*cos(6*phi + theta) + 270*cos(2*phi + 3*theta))/823680.; case 4: return (30625 + 58212*cos(4*phi) + 37800*cos(2*phi - theta) + 24500*cos(2*theta) + 8316*cos(4*(phi + theta)) + 60480*cos(2*phi + theta) + 58212*cos(2*(2*phi + theta)) + 54912*cos(3*(2*phi + theta)) + 57915*cos(4*(2*phi + theta)) + 231660*cos(2*(4*phi + theta)) + 96096*cos(6*phi + theta) + 15120*cos(2*phi + 3*theta) + 3432*cos(6*phi + 5*theta))/1.564992e7; default: return 0.0; } case 2: switch(q) { case 2: return (6435*cos(8*phi) + 3432*cos(6*phi)*cos(theta) + 396*cos(4*phi)*(4 + 3*cos(2*theta)) + 360*cos(2*phi)*(6*cos(theta) + cos(3*theta)) + 35*(18 + 16*cos(2*theta) + cos(4*theta)))/823680.; case 3: return (20790*cos(4*phi) + 57915*cos(8*phi) + 2700*cos(2*phi - 3*theta) + 6930*cos(4*phi - 2*theta) + 14400*cos(2*phi - theta) + 17160*cos(6*phi - theta) + 8750*cos(2*theta) + 875*cos(4*theta) + 2*(4375 + 693*cos(4*(phi + theta)) + 8100*cos(2*phi + theta) + 6237*cos(2*(2*phi + theta)) + 3432*cos(3*(2*phi + theta)) + 19305*cos(2*(4*phi + theta)) + 13728*cos(6*phi + theta) + 2160*cos(2*phi + 3*theta) + 90*cos(2*phi + 5*theta)))/5.21664e6; case 4: return (206976*cos(4*phi) + 450450*cos(8*phi) + 29400*cos(2*phi - 3*theta) + 64680*cos(4*phi - 2*theta) + 147000*cos(2*phi - theta) + 144144*cos(6*phi - theta) + 98000*cos(2*theta) + 12250*cos(4*theta) + 3*(30625 + 9856*cos(4*(phi + theta)) + 58800*cos(2*phi + theta) + 51744*cos(2*(2*phi + theta)) + 41184*cos(3*(2*phi + theta)) + 32175*cos(4*(2*phi + theta)) + 171600*cos(2*(4*phi + theta)) + 96096*cos(6*phi + theta) + 19600*cos(2*phi + 3*theta) + 1400*cos(2*phi + 5*theta) + 3432*cos(6*phi + 5*theta) + 308*cos(4*phi + 6*theta)))/3.651648e7; default: return 0.0; } case 3: switch(q) { case 1: return (700 + 1485*cos(4*phi) + 270*cos(2*phi - 3*theta) + 858*cos(6*phi - 3*theta) + 1188*cos(4*phi - 2*theta) + 6435*cos(8*phi - 2*theta) + 99*cos(4*(phi - theta)) + 1350*cos(2*phi - theta) + 2574*cos(6*phi - theta) + 525*cos(2*theta) + 900*cos(2*phi + theta))/823680.; case 2: return (19305*cos(8*phi)*(3 + 2*cos(2*theta)) + 875*(10 + 10*cos(2*theta) + cos(4*theta)) + 66*cos(4*phi)*(104*cos(2*phi)*(13*cos(theta) + 2*cos(3*theta)) + 21*(15 + 14*cos(2*theta) + cos(4*theta))) + 12*cos(2*phi)*(-1168*cos(theta) + 13*cos(3*theta) + 15*cos(5*theta)) + 38610*sin(8*phi)*sin(2*theta) + 3432*sin(6*phi)*(3*sin(theta) + 2*sin(3*theta)) + 1386*sin(4*phi)*(4*sin(2*theta) + sin(4*theta)) + 180*sin(2*phi)*(10*sin(theta) + 9*sin(3*theta) + sin(5*theta)))/5.21664e6; case 3: return (38610*cos(8*phi)*(6 + 5*cos(2*theta)) + 5544*cos(4*phi)*(15 + 16*cos(2*theta) + 2*cos(4*theta)) + 72*(286*cos(6*phi)*(9*cos(theta) + 2*cos(3*theta)) + 35*cos(2*phi)*(50*cos(theta) + 15*cos(3*theta) + cos(5*theta))) + 175*(200 + 225*cos(2*theta) + 36*cos(4*theta) + cos(6*theta)))/1.4606592e7; case 4: return (7783776*cos(6*phi)*cos(theta) + 212355*cos(8*phi)*(42 + 44*cos(2*theta) + 5*cos(4*theta)) + 8575*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 360*cos(2*phi)*(15190*cos(theta) - 1286*cos(3*theta) + 103*cos(5*theta) + 7*cos(7*theta)) + 396*cos(4*phi)*(8820 + 5980*cos(2*phi - 3*theta) + 10290*cos(2*theta) + 1848*cos(4*theta) + 63*cos(6*theta) + 5980*cos(2*phi + 3*theta) + 780*cos(2*phi + 5*theta)) - 61776*sin(6*phi)*(14*sin(theta) + 15*sin(3*theta)) - 212355*sin(8*phi)*(16*sin(2*theta) + 5*sin(4*theta)) - 8316*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta)) - 360*sin(2*phi)*(490*sin(theta) + 588*sin(3*theta) + 569*sin(5*theta) + 7*sin(7*theta)))/5.03927424e8; default: return 0.0; } case 4: switch(q) { case 0: return (6435*cos(8*phi - 4*theta) + 3432*cos(6*phi - 3*theta) + 7*(175 + 396*cos(4*phi - 2*theta) + 360*cos(2*phi - theta)))/823680.; case 1: return (58212*cos(4*phi) + 3432*cos(6*phi - 5*theta) + 57915*cos(8*phi - 4*theta) + 15120*cos(2*phi - 3*theta) + 54912*cos(6*phi - 3*theta) + 58212*cos(4*phi - 2*theta) + 231660*cos(8*phi - 2*theta) + 7*(1188*cos(4*(phi - theta)) + 8640*cos(2*phi - theta) + 13728*cos(6*phi - theta) + 875*(5 + 4*cos(2*theta)) + 5400*cos(2*phi + theta)))/1.564992e7; case 2: return (924*cos(4*phi - 6*theta) + 4200*cos(2*phi - 5*theta) + 10296*cos(6*phi - 5*theta) + 96525*cos(8*phi - 4*theta) + 29568*cos(4*(phi - theta)) + 64350*cos(8*phi)*(7 + 8*cos(2*theta)) + 264*cos(4*phi)*(784 + 833*cos(2*theta) + 468*cos(2*phi)*(7*cos(theta) + 2*cos(3*theta))) + 6125*(15 + 16*cos(2*theta) + 2*cos(4*theta)) + 264*(343*sin(4*phi) + 1950*sin(8*phi))*sin(2*theta) - 24*(cos(2*phi)*(4543*cos(theta) + 1473*cos(3*theta)) - 4900*pow(cos(theta),2)*sin(2*phi)*sin(theta) - 858*sin(6*phi)*(7*sin(theta) + 6*sin(3*theta))))/3.651648e7; case 3: return (7783776*cos(6*phi)*cos(theta) + 212355*cos(8*phi)*(42 + 44*cos(2*theta) + 5*cos(4*theta)) + 8575*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 360*cos(2*phi)*(15190*cos(theta) - 1286*cos(3*theta) + 103*cos(5*theta) + 7*cos(7*theta)) + 61776*sin(6*phi)*(14*sin(theta) + 15*sin(3*theta)) + 212355*sin(8*phi)*(16*sin(2*theta) + 5*sin(4*theta)) + 396*cos(4*phi)*(260*cos(2*phi)*(46*cos(3*theta) + 3*cos(5*theta)) + 21*(420 + 490*cos(2*theta) + 88*cos(4*theta) + 3*cos(6*theta)) + 780*sin(2*phi)*sin(5*theta)) + 8316*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta)) + 360*sin(2*phi)*(490*sin(theta) + 588*sin(3*theta) + 569*sin(5*theta) + 7*sin(7*theta)))/5.03927424e8; case 4: return (127413*cos(8*phi)*(28 + 32*cos(2*theta) + 5*cos(4*theta)) + 396*cos(4*phi)*(572*cos(2*phi)*(28*cos(theta) + cos(5*theta)) + 63*(56 + 70*cos(2*theta) + 16*cos(4*theta) + cos(6*theta))) + 72*(15730*cos(6*phi)*cos(3*theta) + cos(2*phi)*(-13174*cos(theta) + 12348*cos(3*theta) + 191*cos(5*theta) + 63*cos(7*theta))) + 245*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + cos(8*theta)))/1.7997408e8; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_10(int p, int q, double theta, double phi) { switch(p) { case 1: switch(q) { case 4: return (4410 + 8008*cos(4*phi) + 5390*cos(2*phi - theta) + 3528*cos(2*theta) + 1144*cos(4*(phi + theta)) + 8624*cos(2*phi + theta) + 8008*cos(2*(2*phi + theta)) + 6864*cos(3*(2*phi + theta)) + 4862*cos(4*(2*phi + theta)) + 19448*cos(2*(4*phi + theta)) + 12012*cos(6*phi + theta) + 2156*cos(2*phi + 3*theta) + 46189*cos(10*phi + 3*theta) + 429*cos(6*phi + 5*theta))/2.3648768e7; default: return 0.0; } case 2: switch(q) { case 3: return (3780 + 8580*cos(4*phi) + 14586*cos(8*phi) + 1155*cos(2*phi - 3*theta) + 2860*cos(4*phi - 2*theta) + 6160*cos(2*phi - theta) + 6435*cos(6*phi - theta) + 3780*cos(2*theta) + 378*cos(4*theta) + 572*cos(4*(phi + theta)) + 6930*cos(2*phi + theta) + 5148*cos(2*(2*phi + theta)) + 2574*cos(3*(2*phi + theta)) + 9724*cos(2*(4*phi + theta)) + 10296*cos(6*phi + theta) + 46189*cos(10*phi + theta) + 1848*cos(2*phi + 3*theta) + 77*cos(2*phi + 5*theta))/2.3648768e7; case 4: return (119070 + 256256*cos(4*phi) + 340340*cos(8*phi) + 37730*cos(2*phi - 3*theta) + 80080*cos(4*phi - 2*theta) + 188650*cos(2*phi - theta) + 162162*cos(6*phi - theta) + 127008*cos(2*theta) + 15876*cos(4*theta) + 36608*cos(4*(phi + theta)) + 226380*cos(2*phi + theta) + 192192*cos(2*(2*phi + theta)) + 138996*cos(3*(2*phi + theta)) + 72930*cos(4*(2*phi + theta)) + 388960*cos(2*(4*phi + theta)) + 324324*cos(6*phi + theta) + 1016158*cos(10*phi + theta) + 75460*cos(2*phi + 3*theta) + 508079*cos(10*phi + 3*theta) + 5390*cos(2*phi + 5*theta) + 11583*cos(6*phi + 5*theta) + 1144*cos(4*phi + 6*theta))/2.71960832e8; default: return 0.0; } case 3: switch(q) { case 2: return (3780 + 8580*cos(4*phi) + 14586*cos(8*phi) + 77*cos(2*phi - 5*theta) + 572*cos(4*(phi - theta)) + 22*cos(2*phi)*(1934 - 2678*cos(4*phi) + 4199*cos(8*phi))*cos(theta) + 4*(945 + 2002*cos(4*phi) + 2431*cos(8*phi))*cos(2*theta) + 429*(7*cos(2*phi) + 6*cos(6*phi))*cos(3*theta) + 378*cos(4*theta) + 11*(70*sin(2*phi) + 351*sin(6*phi) + 4199*sin(10*phi))*sin(theta) + 572*(4*sin(4*phi) + 17*sin(8*phi))*sin(2*theta) + 99*(7*sin(2*phi) + 26*sin(6*phi))*sin(3*theta))/2.3648768e7; case 3: return (3*(4862*cos(8*phi)*(30 + 209*cos(2*phi)*cos(theta) + 25*cos(2*theta)) - 572*cos(4*phi)*(cos(2*phi)*(1169*cos(theta) - 135*cos(3*theta)) - 10*(15 + 16*cos(2*theta) + 2*cos(4*theta))) + 11*cos(2*phi)*(42644*cos(theta) + 165*cos(3*theta) + 245*cos(5*theta)) + 189*(200 + 225*cos(2*theta) + 36*cos(4*theta) + cos(6*theta))))/2.71960832e8; case 4: return (3*(267410*cos(8*phi)*(42 + 44*cos(2*theta) + 57*cos(2*phi)*cos(3*theta) + 5*cos(4*theta)) + 18522*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 4290*cos(4*phi)*(-1483*cos(2*phi)*cos(3*theta) + 4*(420 + 490*cos(2*theta) + 88*cos(4*theta) + 3*cos(6*theta))) + 11*(3510364*cos(10*phi)*cos(theta) + 5265*cos(6*phi)*(252*cos(theta) + 5*cos(5*theta)) + 5*cos(2*phi)*(212660*cos(theta) + 131925*cos(3*theta) + 98*(76*cos(5*theta) + cos(7*theta)))) - 2540395*sin(10*phi)*(4*sin(theta) + 3*sin(3*theta)) - 267410*sin(8*phi)*(16*sin(2*theta) + 5*sin(4*theta)) - 57915*sin(6*phi)*(28*sin(theta) + 5*(6*sin(3*theta) + sin(5*theta))) - 17160*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta)) - 5390*sin(2*phi)*(70*sin(theta) + 84*sin(3*theta) + 20*sin(5*theta) + sin(7*theta))))/1.35980416e10; default: return 0.0; } case 4: switch(q) { case 1: return (8008*cos(4*phi) + 429*cos(6*phi - 5*theta) + 4862*cos(8*phi - 4*theta) + 2156*cos(2*phi - 3*theta) + 6864*cos(6*phi - 3*theta) + 46189*cos(10*phi - 3*theta) + 2*(4004*cos(4*phi - 2*theta) + 9724*cos(8*phi - 2*theta) + 572*cos(4*(phi - theta)) + 7*(315 + 616*cos(2*phi - theta) + 858*cos(6*phi - theta) + 252*cos(2*theta) + 385*cos(2*phi + theta))))/2.3648768e7; case 2: return (256256*cos(4*phi) + 340340*cos(8*phi) + 1144*cos(4*phi - 6*theta) + 5390*cos(2*phi - 5*theta) + 11583*cos(6*phi - 5*theta) + 72930*cos(8*phi - 4*theta) + 75460*cos(2*phi - 3*theta) + 138996*cos(6*phi - 3*theta) + 508079*cos(10*phi - 3*theta) + 2*(96096*cos(4*phi - 2*theta) + 194480*cos(8*phi - 2*theta) + 18304*cos(4*(phi - theta)) + 113190*cos(2*phi - theta) + 162162*cos(6*phi - theta) + 508079*cos(10*phi - theta) + 7*(8505 + 9072*cos(2*theta) + 1134*cos(4*theta) + 13475*cos(2*phi + theta) + 5720*cos(2*(2*phi + theta)) + 11583*cos(6*phi + theta) + 2695*cos(2*phi + 3*theta))))/2.71960832e8; case 3: return (3*(267410*cos(8*phi)*(42 + 44*cos(2*theta) + 57*cos(2*phi)*cos(3*theta) + 5*cos(4*theta)) + 18522*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 4290*cos(4*phi)*(-1483*cos(2*phi)*cos(3*theta) + 4*(420 + 490*cos(2*theta) + 88*cos(4*theta) + 3*cos(6*theta))) + 11*(3510364*cos(10*phi)*cos(theta) + 5265*cos(6*phi)*(252*cos(theta) + 5*cos(5*theta)) + 5*cos(2*phi)*(212660*cos(theta) + 131925*cos(3*theta) + 98*(76*cos(5*theta) + cos(7*theta)))) + 2540395*sin(10*phi)*(4*sin(theta) + 3*sin(3*theta)) + 267410*sin(8*phi)*(16*sin(2*theta) + 5*sin(4*theta)) + 57915*sin(6*phi)*(28*sin(theta) + 5*(6*sin(3*theta) + sin(5*theta))) + 17160*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta)) + 5390*sin(2*phi)*(70*sin(theta) + 84*sin(3*theta) + 20*sin(5*theta) + sin(7*theta))))/1.35980416e10; case 4: return (7*(53482*cos(8*phi)*(247*cos(2*phi)*(4*cos(theta) + cos(3*theta)) + 5*(28 + 32*cos(2*theta) + 5*cos(4*theta))) - 286*cos(4*phi)*(11*cos(2*phi)*(10496*cos(theta) + 1949*cos(3*theta) - 225*cos(5*theta)) - 300*(56 + 70*cos(2*theta) + 16*cos(4*theta) + cos(6*theta))) + 11*cos(2*phi)*(2221228*cos(theta) + 566827*cos(3*theta) + 8985*cos(5*theta) + 1470*cos(7*theta)) + 882*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + cos(8*theta))))/1.52977968e10; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_12(int p, int q, double theta, double phi) { switch(p) { case 2: switch(q) { case 4: return (48510 + 101920*cos(4*phi) + 117572*cos(8*phi) + 15288*cos(2*phi - 3*theta) + 31850*cos(4*phi - 2*theta) + 76440*cos(2*phi - theta) + 61880*cos(6*phi - theta) + 51744*cos(2*theta) + 6468*cos(4*theta) + 14560*cos(4*(phi + theta)) + 91728*cos(2*phi + theta) + 76440*cos(2*(2*phi + theta)) + 53040*cos(3*(2*phi + theta)) + 25194*cos(4*(2*phi + theta)) + 134368*cos(2*(4*phi + theta)) + 123760*cos(6*phi + theta) + 676039*cos(2*(6*phi + theta)) + 235144*cos(10*phi + theta) + 30576*cos(2*phi + 3*theta) + 117572*cos(10*phi + 3*theta) + 2184*cos(2*phi + 5*theta) + 4420*cos(6*phi + 5*theta) + 455*cos(4*phi + 6*theta))/1.384527872e9; default: return 0.0; } case 3: switch(q) { case 3: return (676039*cos(12*phi) + 25194*cos(8*phi)*(6 + 28*cos(2*phi)*cos(theta) + 5*cos(2*theta)) + 13*cos(4*phi)*(272*cos(2*phi)*(-87*cos(theta) + 25*cos(3*theta)) + 525*(15 + 16*cos(2*theta) + 2*cos(4*theta))) + 52*cos(2*phi)*(6108*cos(theta) + 95*cos(3*theta) + 63*cos(5*theta)) + 231*(200 + 225*cos(2*theta) + 36*cos(4*theta) + cos(6*theta)))/1.384527872e9; case 4: return (8599500*cos(4*phi) + 11639628*cos(8*phi) + 35154028*cos(12*phi) + 183456*cos(2*phi - 5*theta) + 2201472*cos(2*phi - 3*theta) + 1547000*cos(6*phi - 3*theta) + 4299750*cos(4*phi - 2*theta) + 3879876*cos(8*phi - 2*theta) + 573300*cos(4*(phi - theta)) + 6879600*cos(2*phi - theta) + 7425600*cos(6*phi - theta) + 9876048*cos(10*phi - theta) + 4753980*cos(2*theta) + 950796*cos(4*theta) + 45276*cos(6*theta) + 1228500*cos(4*(phi + theta)) + 7338240*cos(2*phi + theta) + 5733000*cos(2*(2*phi + theta)) + 3536000*cos(3*(2*phi + theta)) + 3*(461890*cos(4*(2*phi + theta)) + 2771340*cos(2*(4*phi + theta)) + 3094000*cos(6*phi + theta) + 8788507*cos(2*(6*phi + theta)) + 5643456*cos(10*phi + theta) + 917280*cos(2*phi + 3*theta) + 1763580*cos(10*phi + 3*theta) + 104832*cos(2*phi + 5*theta) + 25*(52822 + 4420*cos(6*phi + 5*theta) + 819*cos(4*phi + 6*theta)) + 2184*cos(2*phi + 7*theta)))/3.7382252544e10; default: return 0.0; } case 4: switch(q) { case 2: return (101920*cos(4*phi) + 117572*cos(8*phi) + 455*cos(4*phi - 6*theta) + 2184*cos(2*phi - 5*theta) + 4420*cos(6*phi - 5*theta) + 25194*cos(8*phi - 4*theta) + 30576*cos(2*phi - 3*theta) + 53040*cos(6*phi - 3*theta) + 117572*cos(10*phi - 3*theta) + 76440*cos(4*phi - 2*theta) + 134368*cos(8*phi - 2*theta) + 676039*cos(12*phi - 2*theta) + 14*(3465 + 1040*cos(4*(phi - theta)) + 6552*cos(2*phi - theta) + 8840*cos(6*phi - theta) + 16796*cos(10*phi - theta) + 3696*cos(2*theta) + 462*cos(4*theta) + 5460*cos(2*phi + theta) + 2275*cos(2*(2*phi + theta)) + 4420*cos(6*phi + theta) + 1092*cos(2*phi + 3*theta)))/1.384527872e9; case 3: return (8788507*cos(12*phi)*(4 + 3*cos(2*theta)) + 25194*cos(8*phi)*(462 + 484*cos(2*theta) + 420*cos(2*phi)*cos(3*theta) + 55*cos(4*theta)) + 65*cos(4*phi)*(136*cos(2*phi)*(-47*cos(3*theta) + 75*cos(5*theta)) + 315*(420 + 490*cos(2*theta) + 88*cos(4*theta) + 3*cos(6*theta))) + 52*(1428*(225*cos(6*phi) + 361*cos(10*phi))*cos(theta) + cos(2*phi)*(273420*cos(theta) + 99251*cos(3*theta) + 3201*cos(5*theta) + 126*cos(7*theta))) + 3*(7546*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 8788507*sin(12*phi)*sin(2*theta) + 587860*sin(10*phi)*(4*sin(theta) + 3*sin(3*theta)) + 92378*sin(8*phi)*(16*sin(2*theta) + 5*sin(4*theta)) + 22100*sin(6*phi)*(28*sin(theta) + 5*(6*sin(3*theta) + sin(5*theta))) + 6825*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta)) + 2184*sin(2*phi)*(70*sin(theta) + 84*sin(3*theta) + 20*sin(5*theta) + sin(7*theta))))/3.7382252544e10; case 4: return (8788507*cos(12*phi)*(8 + 7*cos(2*theta)) + 75582*cos(8*phi)*(4*(77 + 88*cos(2*theta) + 91*cos(2*phi)*(4*cos(theta) + cos(3*theta))) + 55*cos(4*theta)) + 104*cos(2*phi)*cos(theta)*(356750 + 245808*cos(2*theta) + 7243*cos(4*theta) + 1134*cos(6*theta)) + 13*cos(4*phi)*(136*cos(2*phi)*(-23744*cos(theta) - 1811*cos(3*theta) + 1375*cos(5*theta)) + 23625*(56 + 70*cos(2*theta) + 16*cos(4*theta) + cos(6*theta))) + 3234*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + cos(8*theta)))/3.8717332992e10; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_14(int p, int q, double theta, double phi) { switch(p) { case 3: switch(q) { case 4: return (642600*cos(4*phi) + 813960*cos(8*phi) + 1485800*cos(12*phi) + 13860*cos(2*phi - 5*theta) + 166320*cos(2*phi - 3*theta) + 113050*cos(6*phi - 3*theta) + 321300*cos(4*phi - 2*theta) + 271320*cos(8*phi - 2*theta) + 42840*cos(4*(phi - theta)) + 519750*cos(2*phi - theta) + 542640*cos(6*phi - theta) + 624036*cos(10*phi - theta) + 360360*cos(2*theta) + 72072*cos(4*theta) + 3432*cos(6*theta) + 91800*cos(4*(phi + theta)) + 554400*cos(2*phi + theta) + 428400*cos(2*(2*phi + theta)) + 258400*cos(3*(2*phi + theta)) + 3*(32300*cos(4*(2*phi + theta)) + 193800*cos(2*(4*phi + theta)) + 226100*cos(6*phi + theta) + 371450*cos(2*(6*phi + theta)) + 356592*cos(10*phi + theta) + 5*(20020 + 334305*cos(14*phi + theta) + 13860*cos(2*phi + 3*theta) + 22287*cos(10*phi + 3*theta) + 1584*cos(2*phi + 5*theta) + 1615*cos(6*phi + 5*theta) + 306*cos(4*phi + 6*theta) + 33*cos(2*phi + 7*theta))))/4.10793984e10; default: return 0.0; } case 4: switch(q) { case 3: return (3*(358050*cos(2*phi) + 323*(1260*cos(6*phi) + 1748*cos(10*phi) + 5175*cos(14*phi)))*cos(theta) + 371450*cos(12*phi)*(4 + 3*cos(2*theta)) + 337075*cos(2*phi)*cos(3*theta) + 9690*cos(8*phi)*(84 + 88*cos(2*theta) + 69*cos(2*phi)*cos(3*theta) + 10*cos(4*theta)) + 13395*cos(2*phi)*cos(5*theta) + 170*cos(4*phi)*(19*cos(2*phi)*(23*cos(3*theta) + 15*cos(5*theta)) + 9*(420 + 490*cos(2*theta) + 88*cos(4*theta) + 3*cos(6*theta))) + 495*cos(2*phi)*cos(7*theta) + 3*(572*(175 + 210*cos(2*theta) + 42*cos(4*theta) + 2*cos(6*theta)) + 1671525*sin(14*phi)*sin(theta) + 371450*sin(12*phi)*sin(2*theta) + 37145*sin(10*phi)*(4*sin(theta) + 3*sin(3*theta)) + 6460*sin(8*phi)*(16*sin(2*theta) + 5*sin(4*theta)) + 1615*sin(6*phi)*(28*sin(theta) + 30*sin(3*theta) + 5*sin(5*theta)) + 510*sin(4*phi)*(70*sin(2*theta) + 32*sin(4*theta) + 3*sin(6*theta)) + 165*sin(2*phi)*(70*sin(theta) + 84*sin(3*theta) + 20*sin(5*theta) + sin(7*theta))))/4.10793984e10; case 4: return ((15280650*cos(2*phi) + 323*(53900*cos(6*phi) + 75348*cos(10*phi) + 232875*cos(14*phi)))*cos(theta) + 2600150*cos(12*phi)*(8 + 7*cos(2*theta)) + 5978861*cos(2*phi)*cos(3*theta) + 40698*cos(8*phi)*(280 + 320*cos(2*theta) + 299*cos(2*phi)*cos(3*theta) + 50*cos(4*theta)) + 251405*cos(2*phi)*cos(5*theta) + 238*cos(4*phi)*(19*cos(2*phi)*(59*cos(3*theta) + 275*cos(5*theta)) + 675*(56 + 70*cos(2*theta) + 16*cos(4*theta) + cos(6*theta))) + 31185*cos(2*phi)*cos(7*theta) + 1716*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + cos(8*theta)))/1.591826688e11; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd_16(int p, int q, double theta, double phi) { switch(p) { case 4: switch(q) { case 4: return (300540195*cos(16*phi) + 8023320*cos(12*phi)*(8 + 7*cos(2*theta)) + 208012*cos(8*phi)*(196 + 224*cos(2*theta) + 200*cos(2*phi)*cos(3*theta) + 35*cos(4*theta)) + 18088*cos(4*phi)*(4*cos(2*phi)*(55*cos(3*theta) + 63*cos(5*theta)) + 33*(56 + 70*cos(2*theta) + 16*cos(4*theta) + cos(6*theta))) + 272*(19*(12348*cos(6*phi) + 16100*cos(10*phi) + 30015*cos(14*phi))*cos(theta) + cos(2*phi)*(210210*cos(theta) + 76769*cos(3*theta) + 3633*cos(5*theta) + 429*cos(7*theta))) + 6435*(2450 + 3136*cos(2*theta) + 784*cos(4*theta) + 64*cos(6*theta) + cos(8*theta)))/9.84810110976e12; default: return 0.0; } default: return 0.0; } return 0.0; } double H_dd(int ell, int p, int q, double theta, double phi) { switch(ell) { case 0: return H_dd_0(p, q, theta, phi); case 2: return H_dd_2(p, q, theta, phi); case 4: return H_dd_4(p, q, theta, phi); case 6: return H_dd_6(p, q, theta, phi); case 8: return H_dd_8(p, q, theta, phi); case 10: return H_dd_10(p, q, theta, phi); case 12: return H_dd_12(p, q, theta, phi); case 14: return H_dd_14(p, q, theta, phi); case 16: return H_dd_16(p, q, theta, phi); default: return 0; } return 0; } void write_cov(char * covfile, int ncov, double ** cov, int order) { FILE * fp; int i, j; if(!(fp = fopen(covfile, "w"))) { printf("\nERROR: Can't write in file '%s'.\n\n", covfile); exit(0); } fprintf(fp, "%d\n", ncov); for (i=0; i<ncov; i++) { for (j = 0; j < ncov; j++) fprintf(fp, "%12.6lf ", pow(10.0, order)*cov[i][j]); fprintf(fp, "\n"); } fclose(fp); } int main(int argc, char **argv) { FILE * fp; char buf[500]; int i, j, k, ell, veltype; char gridcorrfile[500], covfile[500]; char * pkvelfile, * covfile_base; if (argc < 6) { printf("Error: 6 command line arguments required\n"); exit(0); } double omega_m = 0.3121; // The value of omega_m used to generate the simulations double kmin = atof(argv[1]); // The minimum k-value to include information for double kmax = atof(argv[2]); // The maximum k-value to include information for int gridsize = atoi(argv[3]); // The size of each grid cell pkvelfile = argv[4]; // The file containing the input velocity power spectrum covfile_base = argv[5]; // The base for the output file name (other stuff will get added to the name) //double job_num = atof(argv[6]); // The job number of getafix sigma_u = 0.0; // Read in the tabulated correction for the gridding sprintf(gridcorrfile, "./gridcorr_%d.dat", gridsize); //*****************************************************************************************// // I've decided to centre the grid on 0,0,0 so that we don't have any cell centres that are very close to the origin //These are the grid cells for the SDSS survey. double xmin = -170.0, xmax = 210.0; double ymin = -260.0, ymax = 280.0; double zmin = -300.0, zmax = 0.0; double smin = 0.0, smax = sqrt((xmax-xmin)*(xmax-xmin) + (ymax-ymin)*(ymax-ymin) + (zmax-zmin)*(zmax-zmin))+gridsize; int nx = (int)ceil((xmax-xmin)/gridsize); int ny = (int)ceil((ymax-ymin)/gridsize); int nz = (int)ceil((zmax-zmin)/gridsize); int nelements = nx*ny*nz; printf("%lf, %lf\n", smin, smax); printf("%d, %d, %d\n", nx, ny, nz); // Compute some useful quantities on the grid. For this we need a redshift-distance lookup table int nbins = 5000; double redmax = 0.5;//maximum redshift double * redarray = (double*)malloc(nbins*sizeof(double));//redshift array double * distarray = (double*)malloc(nbins*sizeof(double));//distance array for (i=0; i<nbins; i++) { redarray[i] = i*redmax/nbins; distarray[i] = rz(redarray[i]); } gsl_interp_accel * red_acc = gsl_interp_accel_alloc(); gsl_spline * red_spline = gsl_spline_alloc(gsl_interp_cspline, nbins); gsl_spline_init(red_spline, distarray, redarray, nbins); //spline interpolation of redshift free(redarray); free(distarray); // Some arrays to hold values for each cell double * datagrid_x = (double *)malloc(nelements*sizeof(double)); double * datagrid_y = (double *)malloc(nelements*sizeof(double)); double * datagrid_z = (double *)malloc(nelements*sizeof(double)); double * datagrid_r = (double *)malloc(nelements*sizeof(double)); double * datagrid_dm = (double *)malloc(nelements*sizeof(double)); for (i=0; i<nx; i++) { for (j=0; j<ny; j++) { for (k=0; k<nz; k++) { int ind = (i*ny+j)*nz+k; double x = (i+0.5)*gridsize+xmin; double y = (j+0.5)*gridsize+ymin; double z = (k+0.5)*gridsize+zmin; double R_dis = sqrt(x*x + y*y + z*z); datagrid_x[ind] = x; datagrid_y[ind] = y; datagrid_z[ind] = z; datagrid_r[ind] = R_dis; //distance to the galaxy double red = gsl_spline_eval(red_spline, R_dis, red_acc);//calculate redshift double ez = sqrt(omega_m*(1.0+red)*(1.0+red)*(1.0+red) + (1.0 - omega_m));//Friedman first equation datagrid_dm[ind] = (1.0/log(10))*(1.0+red)/(100.0*ez*R_dis);//The prefactor for the log-distance ratio } } } //*****************************************************************************************// // Read in the velocity divergence power spectrum and multiply by (aHf)^2. We set f=1, a=1 and H=100h. if(!(fp = fopen(pkvelfile, "r"))) { printf("\nERROR: Can't open power file '%s'.\n\n", pkvelfile); exit(0); } int npk = 0; while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, pkgal, pkgal_vel, pkvel; if(sscanf(buf, "%lg %lg %lg %lg\n", &tk, &pkgal, &pkgal_vel, &pkvel) != 4) {printf("Pvel read error\n"); exit(0);}; npk++; } } fclose(fp); double * karray = (double *)malloc(npk*sizeof(double)); double * pmmarray = (double *)malloc(npk*sizeof(double)); double * pmvarray = (double *)malloc(npk*sizeof(double)); double * pvvarray = (double *)malloc(npk*sizeof(double)); npk = 0; fp = fopen(pkvelfile, "r"); while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, pmm, pmv, pvv; if(sscanf(buf, "%lg %lg %lg %lg\n", &tk, &pmm, &pmv, &pvv) != 4) {printf("Pvel read error\n"); exit(0);}; karray[npk] = tk; pmmarray[npk] = pmm; pmvarray[npk] = pmv; pvvarray[npk] = pvv; npk++; } } fclose(fp); // Read in and spline the grid corrections if(!(fp = fopen(gridcorrfile, "r"))) { printf("\nERROR: Can't open grid_corr file '%s'.\n\n", gridcorrfile); exit(0); } P_mm_acc = gsl_interp_accel_alloc(); P_mm_spline = gsl_spline_alloc(gsl_interp_cspline, npk); gsl_spline_init(P_mm_spline, karray, pmmarray, npk); P_vm_acc = gsl_interp_accel_alloc(); P_vm_spline = gsl_spline_alloc(gsl_interp_cspline, npk); gsl_spline_init(P_vm_spline, karray, pmvarray, npk); P_vv_acc = gsl_interp_accel_alloc(); P_vv_spline = gsl_spline_alloc(gsl_interp_cspline, npk); gsl_spline_init(P_vv_spline, karray, pvvarray, npk); free(karray); free(pmmarray); free(pmvarray); free(pvvarray); int ngridcorr = 0; while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, gridcorr; if(sscanf(buf, "%lf %lf\n", &tk, &gridcorr) != 2) {printf("Pvel read error\n"); exit(0);}; ngridcorr++; } } fclose(fp); double * gridkarray = (double *)malloc(ngridcorr*sizeof(double)); double * gridcorrarray = (double *)malloc(ngridcorr*sizeof(double)); ngridcorr = 0; fp = fopen(gridcorrfile, "r"); while(fgets(buf,500,fp)) { if(strncmp(buf,"#",1)!=0) { double tk, gridcorr; if(sscanf(buf, "%lf %lf\n", &tk, &gridcorr) != 2) {printf("Pvel read error\n"); exit(0);}; gridkarray[ngridcorr] = tk; gridcorrarray[ngridcorr] = gridcorr; ngridcorr++; } } fclose(fp); gridcorr_acc = gsl_interp_accel_alloc(); gridcorr_spline = gsl_spline_alloc(gsl_interp_cspline, ngridcorr); gsl_spline_init(gridcorr_spline, gridkarray, gridcorrarray, ngridcorr); free(gridkarray); free(gridcorrarray); //*****************************************************************************************// // Now compute the covariance matrix. This is symmetric so we only need to actually calculate the forward half. However to make it more easily parallelisable // The double loop is converted to a single loop and the indices of the matrix calculated from the single iterator. For this though we need to know which indices correspond to which index int niter = nelements*(nelements+1)/2; int * indexi = (int *)malloc(niter*sizeof(int)); int * indexj = (int *)malloc(niter*sizeof(int)); int counteri = 0; int sum = 0; for (i=0; i<nelements; i++) { for (j=0; j<nelements-i; j++) { indexi[j+counteri] = i; indexj[j+counteri] = i+j; sum += 1; } counteri += nelements-i; } printf("%d\n", niter); printf("Computing diagonals\n"); // Compute the diagonal correlation functions. This only needs doing once as it is just an integral over the power spectrum // and is only non-zero for l=0 double theta_diag = 0.0; double phi_diag = 0.0; //At the diagonal of the matrix, line of sight to two galaxies overlap, so theta = 0, and phi = pi/2. This is because cos(phi) = s dot d = 0; double diag_mm_0_12 = conv_integral(kmin, kmax, 0.0, 0, 0, 12, 1, 0)*H_dd(0, 3, 3, theta_diag, phi_diag); double diag_mm_0_10 = conv_integral(kmin, kmax, 0.0, 0, 0, 10, 1, 0)*(H_dd(0, 3, 2, theta_diag, phi_diag) + H_dd(0, 2, 3, theta_diag, phi_diag)); double diag_mm_0_8 = conv_integral(kmin, kmax, 0.0, 0, 0, 8, 1, 0)*(H_dd(0, 3, 1, theta_diag, phi_diag)/6.0 + H_dd(0, 2, 2, theta_diag, phi_diag)/4.0 + H_dd(0, 1, 3, theta_diag, phi_diag)/6.0); double diag_mm_0_6 = conv_integral(kmin, kmax, 0.0, 0, 0, 6, 1, 0)*(H_dd(0, 3, 0, theta_diag, phi_diag)/6.0 + H_dd(0, 2, 1, theta_diag, phi_diag)/2.0 + H_dd(0, 1, 2, theta_diag, phi_diag)/2.0 + H_dd(0, 0, 3, theta_diag, phi_diag)/6.0); double diag_mm_0_4 = conv_integral(kmin, kmax, 0.0, 0, 0, 4, 1, 0)*(H_dd(0, 2, 0, theta_diag, phi_diag)/2.0 + H_dd(0, 1, 1, theta_diag, phi_diag) + H_dd(0, 0, 2, theta_diag, phi_diag)/2.0); double diag_mm_0_2 = conv_integral(kmin, kmax, 0.0, 0, 0, 2, 1, 0)*(H_dd(0, 1, 0, theta_diag, phi_diag) + H_dd(0, 0, 1, theta_diag, phi_diag)); double diag_mm_0_0 = conv_integral(kmin, kmax, 0.0, 0, 0, 0, 1, 0)*H_dd(0, 0, 0, theta_diag, phi_diag); //*****************************************************************************************// int rbins = 10000; double * svals = (double *)malloc(rbins*sizeof(double)); double * xivals = (double *)malloc(rbins*sizeof(double)); printf("Precomputing dd correlation functions\n"); xi_dd_acc = (gsl_interp_accel ****)malloc(3*sizeof(gsl_interp_accel ***)); for (i=0; i<3; i++) { xi_dd_acc[i] = (gsl_interp_accel ***)malloc(7*sizeof(gsl_interp_accel **)); for (j=0; j<7; j++) xi_dd_acc[i][j] = (gsl_interp_accel **)malloc((j+3)*sizeof(gsl_interp_accel *)); } xi_dd_spline = (gsl_spline ****)malloc(3*sizeof(gsl_spline ***)); for (i=0; i<3; i++) { xi_dd_spline[i] = (gsl_spline ***)malloc(7*sizeof(gsl_spline **)); for (j=0; j<7; j++) xi_dd_spline[i][j] = (gsl_spline **)malloc((j+3)*sizeof(gsl_spline *)); } svals = (double *)malloc(rbins*sizeof(double)); xivals = (double *)malloc(rbins*sizeof(double)); for (i=0; i<rbins; i++) svals[i] = i*(smax-smin)/(rbins-1.0) + smin; for (veltype=0; veltype<1; veltype++) { //veltype determines which power spectrum to use. for (i=0; i<7; i++) {// 2*i determines the power of k in the integral. for (ell=0; ell<i+3; ell++) { //2*ell is the order of the spherical bessel function. for (j=0; j<rbins; j++) xivals[j] = conv_integral(kmin, kmax, svals[j], veltype, 2*ell, 2*i, 1, 0); printf("%d, %d, %d\n", veltype, 2*i, 2*ell); xi_dd_acc[veltype][i][ell] = gsl_interp_accel_alloc(); xi_dd_spline[veltype][i][ell] = gsl_spline_alloc(gsl_interp_cspline, rbins); gsl_spline_init(xi_dd_spline[veltype][i][ell], svals, xivals, rbins); } } } free(svals); free(xivals); printf("Starting dd covariance\n"); double ** conv_pk_gal_0_0 = (double **)malloc(nelements*sizeof(double*)); double ** conv_pk_gal_0_2 = (double **)malloc(nelements*sizeof(double*)); double ** conv_pk_gal_0_4 = (double **)malloc(nelements*sizeof(double*)); double ** conv_pk_gal_0_6 = (double **)malloc(nelements*sizeof(double*)); double ** conv_pk_gal_0_8 = (double **)malloc(nelements*sizeof(double*)); double ** conv_pk_gal_0_10 = (double **)malloc(nelements*sizeof(double*)); double ** conv_pk_gal_0_12 = (double **)malloc(nelements*sizeof(double*)); for (i=0; i<nelements; i++) { conv_pk_gal_0_0[i] = (double *)malloc(nelements*sizeof(double)); conv_pk_gal_0_2[i] = (double *)malloc(nelements*sizeof(double)); conv_pk_gal_0_4[i] = (double *)malloc(nelements*sizeof(double)); conv_pk_gal_0_6[i] = (double *)malloc(nelements*sizeof(double)); conv_pk_gal_0_8[i] = (double *)malloc(nelements*sizeof(double)); conv_pk_gal_0_10[i] = (double *)malloc(nelements*sizeof(double)); conv_pk_gal_0_12[i] = (double *)malloc(nelements*sizeof(double)); } for (i=0; i<niter; i++) { int indi = indexi[i]; int indj = indexj[i]; if (indi == indj) { conv_pk_gal_0_0[indi][indi] = diag_mm_0_0/(2.0*M_PI*M_PI); conv_pk_gal_0_2[indi][indi] = -diag_mm_0_2/2.0/(2.0*M_PI*M_PI); conv_pk_gal_0_4[indi][indi] = diag_mm_0_4/4.0/(2.0*M_PI*M_PI); conv_pk_gal_0_6[indi][indi] = -diag_mm_0_6/8.0/(2.0*M_PI*M_PI); conv_pk_gal_0_8[indi][indi] = diag_mm_0_8/16.0/(2.0*M_PI*M_PI); conv_pk_gal_0_10[indi][indi] = -diag_mm_0_10/384.0/(2.0*M_PI*M_PI); conv_pk_gal_0_12[indi][indi] = diag_mm_0_12/2304.0/(2.0*M_PI*M_PI); printf("%d, %lf, %lf, %lf, %lf\n", indi, datagrid_x[indi], datagrid_y[indi], datagrid_z[indi], conv_pk_gal_0_0[indi][indi]); } else { double xi = datagrid_x[indi]; double yi = datagrid_y[indi]; double zi = datagrid_z[indi]; double ri = datagrid_r[indi]; double xj = datagrid_x[indj]; double yj = datagrid_y[indj]; double zj = datagrid_z[indj]; double rj = datagrid_r[indj]; double s = sqrt((xi - xj)*(xi - xj) + (yi - yj)*(yi - yj) + (zi - zj)*(zi - zj)); double phi, dx, dy, dz, dl, phi_arg; double costheta = (xi*xj + yi*yj + zi*zj)/(ri*rj); double theta; if ((costheta >= -1.0) && (costheta <= 1.0)) { theta = acos(costheta); dx = ri*rj/(ri+rj)*(xi/ri + xj/rj); dy = ri*rj/(ri+rj)*(yi/ri + yj/rj); dz = ri*rj/(ri+rj)*(zi/ri + zj/rj); dl = sqrt(dx*dx+dy*dy+dz*dz); phi_arg = (dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s); if ((phi_arg >=-1.0) && (phi_arg <= 1.0)) { phi = acos(phi_arg); } else if (phi_arg > 1.0) { phi = 0.0; } else { phi = M_PI; } } else if (costheta > 1.0) { theta = 0.0; dx = ri*rj/(ri+rj)*(xi/ri + xj/rj); dy = ri*rj/(ri+rj)*(yi/ri + yj/rj); dz = ri*rj/(ri+rj)*(zi/ri + zj/rj); dl = sqrt(dx*dx+dy*dy+dz*dz); phi_arg = (dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s); if ((phi_arg >=-1.0) && (phi_arg <= 1.0)) { phi = acos(phi_arg); } else if (phi_arg > 1.0) { phi = 0.0; } else { phi = M_PI; } } else { theta = M_PI; dx = ri*rj/(ri+rj)*(xi/ri + xj/rj); dy = ri*rj/(ri+rj)*(yi/ri + yj/rj); dz = ri*rj/(ri+rj)*(zi/ri + zj/rj); dl = sqrt(dx*dx+dy*dy+dz*dz); phi_arg = (dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s); if ((phi_arg >=-1.0) && (phi_arg <= 1.0)) { phi = acos(phi_arg); } else if (phi_arg > 1.0) { phi = 0.0; } else { phi = M_PI; } } /*double theta = acos((xi*xj + yi*yj + zi*zj)/(ri*rj)); double phi; if (indi + indj == nelements-1) { phi = M_PI/2.0; } else { double dx = ri*rj/(ri+rj)*(xi/ri + xj/rj); double dy = ri*rj/(ri+rj)*(yi/ri + yj/rj); double dz = ri*rj/(ri+rj)*(zi/ri + zj/rj); double dl = sqrt(dx*dx+dy*dy+dz*dz); double phi = acos((dx*(xi-xj) + dy*(yi-yj) + dz*(zi-zj))/(dl*s)); }*/ double cov_0_0 = 0, cov_0_2 = 0, cov_0_4 = 0, cov_0_6 = 0, cov_0_8 = 0, cov_0_10 = 0, cov_0_12 = 0; for (ell=16; ell>=0; ell-=2) { cov_0_12 += creal(cpow(I, ell))*gsl_spline_eval(xi_dd_spline[0][6][ell/2], s, xi_dd_acc[0][6][ell/2])*H_dd(ell, 3, 3, theta, phi); if (ell < 15) { cov_0_10 += creal(cpow(I, ell))*gsl_spline_eval(xi_dd_spline[0][5][ell/2], s, xi_dd_acc[0][5][ell/2])*(H_dd(ell, 3, 2, theta, phi) + H_dd(ell, 2, 3, theta, phi)); } if (ell < 13) { cov_0_8 += creal(cpow(I, ell))*gsl_spline_eval(xi_dd_spline[0][4][ell/2], s, xi_dd_acc[0][4][ell/2])*(H_dd(ell, 3, 1, theta, phi)/6.0 + H_dd(ell, 2, 2, theta, phi)/4.0 + H_dd(ell, 1, 3, theta, phi)/6.0); } if (ell < 11) { cov_0_6 += creal(cpow(I, ell))*gsl_spline_eval(xi_dd_spline[0][3][ell/2], s, xi_dd_acc[0][3][ell/2])*(H_dd(ell, 3, 0, theta, phi)/6.0 + H_dd(ell, 2, 1, theta, phi)/2.0 + H_dd(ell, 1, 2, theta, phi)/2.0 + H_dd(ell, 0, 3, theta, phi)/6.0); } if (ell < 9) { cov_0_4 += creal(cpow(I, ell))*gsl_spline_eval(xi_dd_spline[0][2][ell/2], s, xi_dd_acc[0][2][ell/2])*(H_dd(ell, 2, 0, theta, phi)/2.0 + H_dd(ell, 1, 1, theta, phi) + H_dd(ell, 0, 2, theta, phi)/2.0); } if (ell < 7) { cov_0_2 += creal(cpow(I, ell))*gsl_spline_eval(xi_dd_spline[0][1][ell/2], s, xi_dd_acc[0][1][ell/2])*(H_dd(ell, 1, 0, theta, phi) + H_dd(ell, 0, 1, theta, phi)); } if (ell < 5) { cov_0_0 += creal(cpow(I, ell))*gsl_spline_eval(xi_dd_spline[0][0][ell/2], s, xi_dd_acc[0][0][ell/2])*H_dd(ell, 0, 0, theta, phi); } } conv_pk_gal_0_12[indi][indj] = cov_0_12/(2.0*M_PI*M_PI)/2304.0; conv_pk_gal_0_10[indi][indj] = -cov_0_10/(2.0*M_PI*M_PI)/384.0; conv_pk_gal_0_8[indi][indj] = cov_0_8/(2.0*M_PI*M_PI)/16.0; conv_pk_gal_0_6[indi][indj] = -cov_0_6/(2.0*M_PI*M_PI)/8.0; conv_pk_gal_0_4[indi][indj] = cov_0_4/(2.0*M_PI*M_PI)/4.0; conv_pk_gal_0_2[indi][indj] = -cov_0_2/(2.0*M_PI*M_PI)/2.0; conv_pk_gal_0_0[indi][indj] = cov_0_0/(2.0*M_PI*M_PI); conv_pk_gal_0_12[indj][indi] = cov_0_12/(2.0*M_PI*M_PI)/2304.0; conv_pk_gal_0_10[indj][indi] = -cov_0_10/(2.0*M_PI*M_PI)/384.0; conv_pk_gal_0_8[indj][indi] = cov_0_8/(2.0*M_PI*M_PI)/16.0; conv_pk_gal_0_6[indj][indi] = -cov_0_6/(2.0*M_PI*M_PI)/8.0; conv_pk_gal_0_4[indj][indi] = cov_0_4/(2.0*M_PI*M_PI)/4.0; conv_pk_gal_0_2[indj][indi] = -cov_0_2/(2.0*M_PI*M_PI)/2.0; conv_pk_gal_0_0[indj][indi] = cov_0_0/(2.0*M_PI*M_PI); //printf("%d, %lf, %lf, %lf, %d, %lf, %lf, %lf, %lf, %lf, %lf\n", indi, datagrid_x[indi], datagrid_y[indi], datagrid_z[indi], indj, datagrid_x[indj], datagrid_y[indj], datagrid_z[indj], conv_pk_gal_0_12[indi][indj], conv_pk_gal_1_6[indi][indj], conv_pk_gal_0_2[indi][indj]); } } sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_0.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); write_cov(covfile, nelements, conv_pk_gal_0_0, 8); sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_2.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); write_cov(covfile, nelements, conv_pk_gal_0_2, 10); sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_4.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); write_cov(covfile, nelements, conv_pk_gal_0_4, 12); sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_6.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); write_cov(covfile, nelements, conv_pk_gal_0_6, 14); sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_8.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); write_cov(covfile, nelements, conv_pk_gal_0_8, 16); sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_10.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); write_cov(covfile, nelements, conv_pk_gal_0_10, 18); sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_0_12.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); write_cov(covfile, nelements, conv_pk_gal_0_12, 20); sprintf(covfile, "%s_k0p%03d_0p%03d_gridcorr%02d_dd_1_0.dat", covfile_base, (int)(1000.0*kmin), (int)(1000.0*kmax), gridsize); printf("Done dd covariance\n"); for (i=0; i<nelements; i++) { free(conv_pk_gal_0_0[i]); free(conv_pk_gal_0_2[i]); free(conv_pk_gal_0_4[i]); free(conv_pk_gal_0_6[i]); free(conv_pk_gal_0_8[i]); free(conv_pk_gal_0_10[i]); free(conv_pk_gal_0_12[i]); } free(conv_pk_gal_0_0); free(conv_pk_gal_0_2); free(conv_pk_gal_0_4); free(conv_pk_gal_0_6); free(conv_pk_gal_0_8); free(conv_pk_gal_0_10); free(conv_pk_gal_0_12); for (veltype=0; veltype<3; veltype++) { for (i=0; i<7; i++) { for (ell=0; ell<i+3; ell++) { gsl_spline_free (xi_dd_spline[veltype][i][ell]); gsl_interp_accel_free (xi_dd_acc[veltype][i][ell]); } } } for (i=0; i<3; i++) { for (j=0; j<7; j++) { free(xi_dd_acc[i][j]); free(xi_dd_spline[i][j]); } free(xi_dd_acc[i]); free(xi_dd_spline[i]); } free(xi_dd_acc); free(xi_dd_spline); free(datagrid_x); free(datagrid_y); free(datagrid_z); free(datagrid_r); gsl_spline_free (gridcorr_spline); gsl_interp_accel_free (gridcorr_acc); gsl_spline_free (P_mm_spline); gsl_interp_accel_free (P_mm_acc); gsl_spline_free (P_vm_spline); gsl_interp_accel_free (P_vm_acc); gsl_spline_free (P_vv_spline); gsl_interp_accel_free (P_vv_acc); return 0; }
{ "alphanum_fraction": 0.5679291643, "avg_line_length": 56.999146029, "ext": "c", "hexsha": "08d1b2626dde1d643119f73c4a5b13c4fac31671", "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": "f75bd459d0b49664440187153a569de1221332a7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "YanxiangL/Peculiar_velocity_fitting", "max_forks_repo_path": "conv_pk_wideangle_galaxy_badd.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f75bd459d0b49664440187153a569de1221332a7", "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": "YanxiangL/Peculiar_velocity_fitting", "max_issues_repo_path": "conv_pk_wideangle_galaxy_badd.c", "max_line_length": 959, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f75bd459d0b49664440187153a569de1221332a7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "YanxiangL/Peculiar_velocity_fitting", "max_stars_repo_path": "conv_pk_wideangle_galaxy_badd.c", "max_stars_repo_stars_event_max_datetime": "2021-03-12T05:40:10.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-12T05:40:10.000Z", "num_tokens": 26872, "size": 66746 }
/* gsl_multifit_ndlinear.h * * Copyright (C) 2006, 2007 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 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MULTIFIT_NDLINEAR_H__ #define __GSL_MULTIFIT_NDLINEAR_H__ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> typedef struct { size_t n_dim; /* dimension of fit function */ size_t *N; /* number of terms in fit sums N[i] = N_i */ size_t n_coeffs; /* number of fit coefficients */ gsl_vector *work; /* scratch array of size n_coeffs */ gsl_vector *work2; /* scratch array */ /* * Views into the 'work' array which will be used to store * the results of calling the basis functions, so that * (v[i])_j = u^{(i)}_j(x_i) */ gsl_vector_view *v; /* pointer to basis functions and parameters */ int (**u)(double x, double y[], void *p); void *params; } gsl_multifit_ndlinear_workspace; /* * Prototypes */ gsl_multifit_ndlinear_workspace * gsl_multifit_ndlinear_alloc(size_t n, size_t N[], int (**u)(double x, double y[], void *p), void *params); void gsl_multifit_ndlinear_free(gsl_multifit_ndlinear_workspace *w); int gsl_multifit_ndlinear_design(const gsl_matrix *data, gsl_matrix *X, gsl_multifit_ndlinear_workspace *w); int gsl_multifit_ndlinear_est(const gsl_vector *x, const gsl_vector *c, const gsl_matrix *cov, double *y, double *y_err, gsl_multifit_ndlinear_workspace *w); double gsl_multifit_ndlinear_calc(const gsl_vector *x, const gsl_vector *c, gsl_multifit_ndlinear_workspace *w); size_t gsl_multifit_ndlinear_ncoeffs(gsl_multifit_ndlinear_workspace *w); #endif /* __GSL_MULTIFIT_NDLINEAR_H__ */
{ "alphanum_fraction": 0.6762589928, "avg_line_length": 37.9090909091, "ext": "h", "hexsha": "df4737921a620a9e15a7ec44a2b88fd048d556f5", "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": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rennhak/Keyposes", "max_forks_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/gsl_multifit_ndlinear.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "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": "rennhak/Keyposes", "max_issues_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/gsl_multifit_ndlinear.h", "max_line_length": 81, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rennhak/Keyposes", "max_stars_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/gsl_multifit_ndlinear.h", "max_stars_repo_stars_event_max_datetime": "2018-05-05T12:45:52.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-26T07:28:56.000Z", "num_tokens": 629, "size": 2502 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include "ccl.h" #ifdef HAVE_ANGPOW #include "Angpow/angpow_ccl.h" #endif #define CCL_FRAC_RELEVANT 5E-4 //#define CCL_FRAC_RELEVANT 1E-3 //Gets the x-interval where the values of y are relevant //(meaning, that the values of y for those x are at least above a fraction frac of its maximum) static void get_support_interval(int n,double *x,double *y,double frac, double *xmin_out,double *xmax_out) { int ix; double ythr=-1000; //Initialize as the original edges in case we don't find an interval *xmin_out=x[0]; *xmax_out=x[n-1]; //Find threshold for(ix=0;ix<n;ix++) { if(y[ix]>ythr) ythr=y[ix]; } ythr*=frac; //Find minimum for(ix=0;ix<n;ix++) { if(y[ix]>=ythr) { *xmin_out=x[ix]; break; } } //Find maximum for(ix=n-1;ix>=0;ix--) { if(y[ix]>=ythr) { *xmax_out=x[ix]; break; } } } //Wrapper around spline_eval with GSL function syntax static double speval_bis(double x,void *params) { return ccl_spline_eval(x,(SplPar *)params); } void ccl_cl_workspace_free(CCL_ClWorkspace *w) { free(w->l_arr); free(w); } CCL_ClWorkspace *ccl_cl_workspace_default(int lmax,int l_limber,int non_limber_method, double l_logstep,int l_linstep, double dchi,double dlk,double zmin,int *status) { CCL_ClWorkspace *w=(CCL_ClWorkspace *)malloc(sizeof(CCL_ClWorkspace)); if(w==NULL) { *status=CCL_ERROR_MEMORY; //Can't access cosmology object // ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_workspace_default(); memory allocation\n"); return NULL; } //Set params w->dchi=dchi; w->dlk =dlk ; if(zmin<=0) { //We should make sure that zmin is always strictly positive free(w); *status=CCL_ERROR_INCONSISTENT; return NULL; } w->zmin=zmin; w->lmax=lmax; if((non_limber_method!=CCL_NONLIMBER_METHOD_NATIVE) && (non_limber_method!=CCL_NONLIMBER_METHOD_ANGPOW)) { free(w); *status=CCL_ERROR_INCONSISTENT; //Can't access cosmology object // ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_workspace_default(); unknown non-limber method\n"); return NULL; } w->nlimb_method=non_limber_method; w->l_limber=l_limber; w->l_logstep=l_logstep; w->l_linstep=l_linstep; //Compute number of multipoles int i_l=0,l0=0; int increment=CCL_MAX(((int)(l0*(w->l_logstep-1.))),1); while((l0 < w->lmax) && (increment < w->l_linstep)) { i_l++; l0+=increment; increment=CCL_MAX(((int)(l0*(w->l_logstep-1))),1); } increment=w->l_linstep; while(l0 < w->lmax) { i_l++; l0+=increment; } //Allocate array of multipoles w->n_ls=i_l+1; w->l_arr=(int *)malloc(w->n_ls*sizeof(int)); if(w->l_arr==NULL) { free(w); *status=CCL_ERROR_MEMORY; //Can't access cosmology object // ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_workspace_default(); memory allocation\n"); return NULL; } //Redo the computation above and store values of ell i_l=0; l0=0; increment=CCL_MAX(((int)(l0*(w->l_logstep-1.))),1); while((l0 < w->lmax) && (increment < w->l_linstep)) { w->l_arr[i_l]=l0; i_l++; l0+=increment; increment=CCL_MAX(((int)(l0*(w->l_logstep-1))),1); } increment=w->l_linstep; while(l0 < w->lmax) { w->l_arr[i_l]=l0; i_l++; l0+=increment; } //Don't go further than lmaw w->l_arr[w->n_ls-1]=w->lmax; return w; } CCL_ClWorkspace *ccl_cl_workspace_default_limber(int lmax,double l_logstep,int l_linstep, double dlk,int *status) { return ccl_cl_workspace_default(lmax,-1,CCL_NONLIMBER_METHOD_NATIVE,l_logstep,l_linstep,3.,dlk,0.05,status); } //Params for lensing kernel integrand typedef struct { double chi; SplPar *spl_pz; ccl_cosmology *cosmo; int *status; } IntLensPar; //Integrand for lensing kernel static double integrand_wl(double chip,void *params) { IntLensPar *p=(IntLensPar *)params; double chi=p->chi; double a=ccl_scale_factor_of_chi(p->cosmo,chip, p->status); double z=1./a-1; double pz=ccl_spline_eval(z,p->spl_pz); double h=p->cosmo->params.h*ccl_h_over_h0(p->cosmo,a, p->status)/CLIGHT_HMPC; if(chi==0) return h*pz; else return h*pz*ccl_sinn(p->cosmo,chip-chi,p->status)/ccl_sinn(p->cosmo,chip,p->status); } //Integral to compute lensing window function //chi -> comoving distance //cosmo -> ccl_cosmology object //spl_pz -> normalized N(z) spline //chi_max -> maximum comoving distance to which the integral is computed //win -> result is stored here static int window_lensing(double chi,ccl_cosmology *cosmo,SplPar *spl_pz,double chi_max,double *win) { int gslstatus =0, status =0; double result,eresult; IntLensPar ip; gsl_function F; gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION); ip.chi=chi; ip.cosmo=cosmo; ip.spl_pz=spl_pz; ip.status = &status; F.function=&integrand_wl; F.params=&ip; gslstatus=gsl_integration_qag(&F, chi, chi_max, 0, ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION, ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS, w, &result, &eresult); *win=result; gsl_integration_workspace_free(w); if(gslstatus!=GSL_SUCCESS || *ip.status) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: window_lensing():"); return 1; } //TODO: chi_max should be changed to chi_horizon //we should precompute this quantity and store it in cosmo by default return 0; } //Params for lensing kernel integrand typedef struct { double chi; SplPar *spl_pz; SplPar *spl_sz; ccl_cosmology *cosmo; int *status; } IntMagPar; //Integrand for magnification kernel static double integrand_mag(double chip,void *params) { IntMagPar *p=(IntMagPar *)params; //EK: added local status here as the status testing is done in routines called from this function double chi=p->chi; double a=ccl_scale_factor_of_chi(p->cosmo,chip, p->status); double z=1./a-1; double pz=ccl_spline_eval(z,p->spl_pz); double sz=ccl_spline_eval(z,p->spl_sz); double h=p->cosmo->params.h*ccl_h_over_h0(p->cosmo,a, p->status)/CLIGHT_HMPC; if(chi==0) return h*pz*(1-2.5*sz); else return h*pz*(1-2.5*sz)*ccl_sinn(p->cosmo,chip-chi,p->status)/ccl_sinn(p->cosmo,chip,p->status); } //Integral to compute magnification window function //chi -> comoving distance //cosmo -> ccl_cosmology object //spl_pz -> normalized N(z) spline //spl_pz -> magnification bias s(z) //chi_max -> maximum comoving distance to which the integral is computed //win -> result is stored here static int window_magnification(double chi,ccl_cosmology *cosmo,SplPar *spl_pz,SplPar *spl_sz, double chi_max,double *win) { int gslstatus =0, status =0; double result,eresult; IntMagPar ip; gsl_function F; gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION); ip.chi=chi; ip.cosmo=cosmo; ip.spl_pz=spl_pz; ip.spl_sz=spl_sz; ip.status = &status; F.function=&integrand_mag; F.params=&ip; gslstatus=gsl_integration_qag(&F, chi, chi_max, 0, ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION, ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS, w, &result, &eresult); *win=result; gsl_integration_workspace_free(w); if(gslstatus!=GSL_SUCCESS || *ip.status) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: window_magnification():"); return 1; } //TODO: chi_max should be changed to chi_horizon //we should precompute this quantity and store it in cosmo by default return 0; } //CCL_ClTracer creator //cosmo -> ccl_cosmology object //tracer_type -> type of tracer. Supported: CL_TRACER_NC, CL_TRACER_WL //nz_n -> number of points for N(z) //z_n -> array of z-values for N(z) //n -> corresponding N(z)-values. Normalization is irrelevant // N(z) will be set to zero outside the range covered by z_n //nz_b -> number of points for b(z) //z_b -> array of z-values for b(z) //b -> corresponding b(z)-values. // b(z) will be assumed constant outside the range covered by z_n static CCL_ClTracer *cl_tracer(ccl_cosmology *cosmo,int tracer_type, int has_rsd,int has_magnification,int has_intrinsic_alignment, int nz_n,double *z_n,double *n, int nz_b,double *z_b,double *b, int nz_s,double *z_s,double *s, int nz_ba,double *z_ba,double *ba, int nz_rf,double *z_rf,double *rf, double z_source, int * status) { int clstatus=0, gslstatus; CCL_ClTracer *clt=(CCL_ClTracer *)malloc(sizeof(CCL_ClTracer)); if(clt==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): memory allocation\n"); return NULL; } if ( ((cosmo->params.N_nu_mass)>0) && tracer_type==CL_TRACER_NC && has_rsd){ free(clt); *status=CCL_ERROR_NOT_IMPLEMENTED; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer_new(): Number counts tracers with rsd not yet implemented in cosmologies with massive neutrinos."); return NULL; } clt->tracer_type=tracer_type; clt->computed_transfer=0; double hub=cosmo->params.h*ccl_h_over_h0(cosmo,1.,status)/CLIGHT_HMPC; clt->prefac_lensing=1.5*hub*hub*cosmo->params.Omega_m; if((tracer_type==CL_TRACER_NC)||(tracer_type==CL_TRACER_WL)) { get_support_interval(nz_n,z_n,n,CCL_FRAC_RELEVANT,&(clt->zmin),&(clt->zmax)); clt->chimax=ccl_comoving_radial_distance(cosmo,1./(1+clt->zmax),status); clt->chimin=ccl_comoving_radial_distance(cosmo,1./(1+clt->zmin),status); clt->spl_nz=ccl_spline_init(nz_n,z_n,n,0,0); if(clt->spl_nz==NULL) { free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing spline for N(z)\n"); return NULL; } //Normalize n(z) gsl_function F; double nz_norm,nz_enorm; double *nz_normalized=(double *)malloc(nz_n*sizeof(double)); if(nz_normalized==NULL) { ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): memory allocation\n"); return NULL; } gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION); F.function=&speval_bis; F.params=clt->spl_nz; gslstatus=gsl_integration_qag(&F, z_n[0], z_n[nz_n-1], 0, ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION, ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS, w, &nz_norm, &nz_enorm); gsl_integration_workspace_free(w); if(gslstatus!=GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: cl_tracer():"); ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_INTEG; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): integration error when normalizing N(z)\n"); return NULL; } for(int ii=0;ii<nz_n;ii++) nz_normalized[ii]=n[ii]/nz_norm; ccl_spline_free(clt->spl_nz); clt->spl_nz=ccl_spline_init(nz_n,z_n,nz_normalized,0,0); free(nz_normalized); if(clt->spl_nz==NULL) { free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing normalized spline for N(z)\n"); return NULL; } if(tracer_type==CL_TRACER_NC) { //Initialize bias spline clt->spl_bz=ccl_spline_init(nz_b,z_b,b,b[0],b[nz_b-1]); if(clt->spl_bz==NULL) { ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing spline for b(z)\n"); return NULL; } clt->has_rsd=has_rsd; clt->has_magnification=has_magnification; if(clt->has_magnification) { //Compute weak lensing kernel int nchi; double *x,*y; double dchi_here=5.; double zmax=clt->spl_nz->xf; double chimax=ccl_comoving_radial_distance(cosmo,1./(1+zmax),status); //TODO: The interval in chi (5. Mpc) should be made a macro //In this case we need to integrate all the way to z=0. Reset zmin and chimin clt->zmin=0; clt->chimin=0; clt->spl_sz=ccl_spline_init(nz_s,z_s,s,s[0],s[nz_s-1]); if(clt->spl_sz==NULL) { ccl_spline_free(clt->spl_nz); ccl_spline_free(clt->spl_bz); free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing spline for s(z)\n"); return NULL; } nchi=(int)(chimax/dchi_here)+1; x=ccl_linear_spacing(0.,chimax,nchi); dchi_here=chimax/nchi; if(x==NULL || (fabs(x[0]-0)>1E-5) || (fabs(x[nchi-1]-chimax)>1e-5)) { ccl_spline_free(clt->spl_nz); ccl_spline_free(clt->spl_bz); ccl_spline_free(clt->spl_sz); free(clt); *status=CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): Error creating linear spacing in chi\n"); return NULL; } y=(double *)malloc(nchi*sizeof(double)); if(y==NULL) { free(x); ccl_spline_free(clt->spl_nz); ccl_spline_free(clt->spl_bz); ccl_spline_free(clt->spl_sz); free(clt); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): memory allocation\n"); return NULL; } for(int j=0;j<nchi;j++) clstatus|=window_magnification(x[j],cosmo,clt->spl_nz,clt->spl_sz,chimax,&(y[j])); if(clstatus) { free(y); free(x); ccl_spline_free(clt->spl_nz); ccl_spline_free(clt->spl_bz); ccl_spline_free(clt->spl_sz); free(clt); *status=CCL_ERROR_INTEG; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error computing lensing window\n"); return NULL; } clt->spl_wM=ccl_spline_init(nchi,x,y,y[0],0); if(clt->spl_wM==NULL) { free(y); free(x); ccl_spline_free(clt->spl_nz); ccl_spline_free(clt->spl_bz); ccl_spline_free(clt->spl_sz); free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing spline for lensing window\n"); return NULL; } free(x); free(y); } } else if(tracer_type==CL_TRACER_WL) { //Compute weak lensing kernel int nchi; double *x,*y; double dchi_here=5.; double zmax=clt->spl_nz->xf; double chimax=ccl_comoving_radial_distance(cosmo,1./(1+zmax),status); //TODO: The interval in chi (5. Mpc) should be made a macro //In this case we need to integrate all the way to z=0. Reset zmin and chimin clt->zmin=0; clt->chimin=0; nchi=(int)(chimax/dchi_here)+1; x=ccl_linear_spacing(0.,chimax,nchi); dchi_here=chimax/nchi; if(x==NULL || (fabs(x[0]-0)>1E-5) || (fabs(x[nchi-1]-chimax)>1e-5)) { ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): Error creating linear spacing in chi\n"); return NULL; } y=(double *)malloc(nchi*sizeof(double)); if(y==NULL) { free(x); ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): memory allocation\n"); return NULL; } for(int j=0;j<nchi;j++) clstatus|=window_lensing(x[j],cosmo,clt->spl_nz,chimax,&(y[j])); if(clstatus) { free(y); free(x); ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_INTEG; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error computing lensing window\n"); return NULL; } clt->spl_wL=ccl_spline_init(nchi,x,y,y[0],0); if(clt->spl_wL==NULL) { free(y); free(x); ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing spline for lensing window\n"); return NULL; } free(x); free(y); clt->has_intrinsic_alignment=has_intrinsic_alignment; if(clt->has_intrinsic_alignment) { clt->spl_rf=ccl_spline_init(nz_rf,z_rf,rf,rf[0],rf[nz_rf-1]); if(clt->spl_rf==NULL) { ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing spline for rf(z)\n"); return NULL; } clt->spl_ba=ccl_spline_init(nz_ba,z_ba,ba,ba[0],ba[nz_ba-1]); if(clt->spl_ba==NULL) { ccl_spline_free(clt->spl_rf); ccl_spline_free(clt->spl_nz); free(clt); *status=CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): error initializing spline for ba(z)\n"); return NULL; } } } } else if(tracer_type==CL_TRACER_CL) { clt->chi_source=ccl_comoving_radial_distance(cosmo,1./(1+z_source),status); clt->chimax=clt->chi_source; clt->chimin=0; } else { *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): unknown tracer type\n"); return NULL; } return clt; } //CCL_ClTracer constructor with error checking //cosmo -> ccl_cosmology object //tracer_type -> type of tracer. Supported: CL_TRACER_NC, CL_TRACER_WL //nz_n -> number of points for N(z) //z_n -> array of z-values for N(z) //n -> corresponding N(z)-values. Normalization is irrelevant // N(z) will be set to zero outside the range covered by z_n //nz_b -> number of points for b(z) //z_b -> array of z-values for b(z) //b -> corresponding b(z)-values. // b(z) will be assumed constant outside the range covered by z_n CCL_ClTracer *ccl_cl_tracer(ccl_cosmology *cosmo,int tracer_type, int has_rsd,int has_magnification,int has_intrinsic_alignment, int nz_n,double *z_n,double *n, int nz_b,double *z_b,double *b, int nz_s,double *z_s,double *s, int nz_ba,double *z_ba,double *ba, int nz_rf,double *z_rf,double *rf, double z_source, int * status) { CCL_ClTracer *clt=cl_tracer(cosmo,tracer_type,has_rsd,has_magnification,has_intrinsic_alignment, nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s, nz_ba,z_ba,ba,nz_rf,z_rf,rf,z_source,status); ccl_check_status(cosmo,status); return clt; } //CCL_ClTracer destructor void ccl_cl_tracer_free(CCL_ClTracer *clt) { if((clt->tracer_type==CL_TRACER_NC) || (clt->tracer_type==CL_TRACER_WL)) ccl_spline_free(clt->spl_nz); if(clt->tracer_type==CL_TRACER_NC) { ccl_spline_free(clt->spl_bz); if(clt->has_magnification) { ccl_spline_free(clt->spl_sz); ccl_spline_free(clt->spl_wM); } } else if(clt->tracer_type==CL_TRACER_WL) { ccl_spline_free(clt->spl_wL); if(clt->has_intrinsic_alignment) { ccl_spline_free(clt->spl_ba); ccl_spline_free(clt->spl_rf); } } if(clt->computed_transfer) { int il; free(clt->n_k); for(il=0;il<clt->n_ls;il++) ccl_spline_free(clt->spl_transfer[il]); free(clt->spl_transfer); } free(clt); } CCL_ClTracer *ccl_cl_tracer_cmblens(ccl_cosmology *cosmo,double z_source,int *status) { return ccl_cl_tracer(cosmo,CL_TRACER_CL, 0,0,0, 0,NULL,NULL,0,NULL,NULL,0,NULL,NULL, 0,NULL,NULL,0,NULL,NULL,z_source,status); } CCL_ClTracer *ccl_cl_tracer_number_counts(ccl_cosmology *cosmo, int has_rsd,int has_magnification, int nz_n,double *z_n,double *n, int nz_b,double *z_b,double *b, int nz_s,double *z_s,double *s, int * status) { return ccl_cl_tracer(cosmo,CL_TRACER_NC,has_rsd,has_magnification,0, nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s, -1,NULL,NULL,-1,NULL,NULL,0, status); } CCL_ClTracer *ccl_cl_tracer_number_counts_simple(ccl_cosmology *cosmo, int nz_n,double *z_n,double *n, int nz_b,double *z_b,double *b, int * status) { return ccl_cl_tracer(cosmo,CL_TRACER_NC,0,0,0, nz_n,z_n,n,nz_b,z_b,b,-1,NULL,NULL, -1,NULL,NULL,-1,NULL,NULL,0, status); } CCL_ClTracer *ccl_cl_tracer_lensing(ccl_cosmology *cosmo, int has_alignment, int nz_n,double *z_n,double *n, int nz_ba,double *z_ba,double *ba, int nz_rf,double *z_rf,double *rf, int * status) { return ccl_cl_tracer(cosmo,CL_TRACER_WL,0,0,has_alignment, nz_n,z_n,n,-1,NULL,NULL,-1,NULL,NULL, nz_ba,z_ba,ba,nz_rf,z_rf,rf,0, status); } CCL_ClTracer *ccl_cl_tracer_lensing_simple(ccl_cosmology *cosmo, int nz_n,double *z_n,double *n, int * status) { return ccl_cl_tracer(cosmo,CL_TRACER_WL,0,0,0, nz_n,z_n,n,-1,NULL,NULL,-1,NULL,NULL, -1,NULL,NULL,-1,NULL,NULL,0, status); } static void limits_bessel(double l,double thr,double *xmin,double *xmax) { double thrb=thr*0.5635/pow(l+0.53,0.834); *xmax=1./thrb; if(l<=0) *xmin=0; else { double logxmin=((l+1.)*(log(l+1.)+M_LN2-1.)+0.5*M_LN2+log(thrb))/l; *xmin=exp(logxmin); } } static double j_bessel_limber(int l,double k) { return sqrt(M_PI/(2*l+1.))/k; } static double f_dens(double a,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status) { double z=1./a-1; double pz=ccl_spline_eval(z,clt->spl_nz); double bz=ccl_spline_eval(z,clt->spl_bz); double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC; return pz*bz*h; } static double f_rsd(double a,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status) { double z=1./a-1; double pz=ccl_spline_eval(z,clt->spl_nz); double fg=ccl_growth_rate(cosmo,a,status); double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC; return pz*fg*h; } static double f_mag(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status) { double wM=ccl_spline_eval(chi,clt->spl_wM); if(wM<=0) return 0; else return wM/(a*chi); } //Transfer function for number counts //l -> angular multipole //k -> wavenumber modulus //cosmo -> ccl_cosmology object //w -> CCL_ClWorskpace object //clt -> CCL_ClTracer object (must be of the CL_TRACER_NC type) static double transfer_nc(int l,double k, ccl_cosmology *cosmo,CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status) { double ret=0; if(l>w->l_limber) { double x0=(l+0.5); double chi0=x0/k; if(chi0<=clt->chimax) { double a0=ccl_scale_factor_of_chi(cosmo,chi0,status); double pk0=ccl_nonlin_matter_power(cosmo,k,a0,status); double jl0=j_bessel_limber(l,k); double f_all=f_dens(a0,cosmo,clt,status)*jl0; if(clt->has_rsd) { double x1=(l+1.5); double chi1=x1/k; if(chi1<=clt->chimax) { double a1=ccl_scale_factor_of_chi(cosmo,chi1,status); double pk1=ccl_nonlin_matter_power(cosmo,k,a1,status); double fg0=f_rsd(a0,cosmo,clt,status); double fg1=f_rsd(a1,cosmo,clt,status); double jl1=j_bessel_limber(l+1,k); f_all+=fg0*(1.-l*(l-1.)/(x0*x0))*jl0-fg1*2.*jl1*sqrt(pk1/pk0)/x1; } } if(clt->has_magnification) f_all+=-2*clt->prefac_lensing*l*(l+1)*f_mag(a0,chi0,cosmo,clt,status)*jl0/(k*k); ret=f_all*sqrt(pk0); } } else { int i,nchi=(int)((clt->chimax-clt->chimin)/w->dchi)+1; for(i=0;i<nchi;i++) { double chi=clt->chimin+w->dchi*(i+0.5); if(chi<=clt->chimax) { double a=ccl_scale_factor_of_chi(cosmo,chi,status); double pk=ccl_nonlin_matter_power(cosmo,k,a,status); double jl=ccl_j_bessel(l,k*chi); double f_all=f_dens(a,cosmo,clt,status)*jl; if(clt->has_rsd) { double ddjl,x=k*chi; if(x<1E-10) { if(l==0) ddjl=0.3333-0.1*x*x; else if(l==2) ddjl=-0.13333333333+0.05714285714285714*x*x; else ddjl=0; } else { double jlp1=ccl_j_bessel(l+1,x); ddjl=((x*x-l*(l-1))*jl-2*x*jlp1)/(x*x); } f_all+=f_rsd(a,cosmo,clt,status)*ddjl; } if(clt->has_magnification) f_all+=-2*clt->prefac_lensing*l*(l+1)*f_mag(a,chi,cosmo,clt,status)*jl/(k*k); ret+=f_all*sqrt(pk); //TODO: is it worth splining this sqrt? } } ret*=w->dchi; } return ret; } static double f_lensing(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status) { double wL=ccl_spline_eval(chi,clt->spl_wL); if(wL<=0) return 0; else return clt->prefac_lensing*wL/(a*chi); } static double f_IA_NLA(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status) { if(chi<=1E-10) return 0; else { double a=ccl_scale_factor_of_chi(cosmo,chi, status); double z=1./a-1; double pz=ccl_spline_eval(z,clt->spl_nz); double ba=ccl_spline_eval(z,clt->spl_ba); double rf=ccl_spline_eval(z,clt->spl_rf); double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC; return pz*ba*rf*h/(chi*chi); } } //Transfer function for shear //l -> angular multipole //k -> wavenumber modulus //cosmo -> ccl_cosmology object //w -> CCL_ClWorskpace object //clt -> CCL_ClTracer object (must be of the CL_TRACER_WL type) static double transfer_wl(int l,double k, ccl_cosmology *cosmo,CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status) { double ret=0; if(l>w->l_limber) { double chi=(l+0.5)/k; if(chi<=clt->chimax) { double a=ccl_scale_factor_of_chi(cosmo,chi,status); double pk=ccl_nonlin_matter_power(cosmo,k,a,status); double jl=j_bessel_limber(l,k); double f_all=f_lensing(a,chi,cosmo,clt,status)*jl; if(clt->has_intrinsic_alignment) f_all+=f_IA_NLA(a,chi,cosmo,clt,status)*jl; ret=f_all*sqrt(pk); } } else { int i,nchi=(int)((clt->chimax-clt->chimin)/w->dchi)+1; for(i=0;i<nchi;i++) { double chi=clt->chimin+w->dchi*(i+0.5); if(chi<=clt->chimax) { double a=ccl_scale_factor_of_chi(cosmo,chi,status); double pk=ccl_nonlin_matter_power(cosmo,k,a,status); double jl=ccl_j_bessel(l,k*chi); double f_all=f_lensing(a,chi,cosmo,clt,status)*jl; if(clt->has_intrinsic_alignment) f_all+=f_IA_NLA(a,chi,cosmo,clt,status)*jl; ret+=f_all*sqrt(pk); //TODO: is it worth splining this sqrt? } } ret*=w->dchi; } return sqrt((l+2.)*(l+1.)*l*(l-1.))*ret/(k*k); //return (l+1.)*l*ret/(k*k); } static double transfer_cmblens(int l,double k,ccl_cosmology *cosmo,CCL_ClTracer *clt,int *status) { double chi=(l+0.5)/k; if(chi>=clt->chi_source) return 0; if(chi<=clt->chimax) { double a=ccl_scale_factor_of_chi(cosmo,chi,status); double w=1-chi/clt->chi_source; double jl=j_bessel_limber(l,k); double pk=ccl_nonlin_matter_power(cosmo,k,a,status); return clt->prefac_lensing*l*(l+1.)*w*sqrt(pk)*jl/(a*chi*k*k); } return 0; } //Wrapper for transfer function //l -> angular multipole //k -> wavenumber modulus //cosmo -> ccl_cosmology object //clt -> CCL_ClTracer object static double transfer_wrap(int il,double lk,ccl_cosmology *cosmo, CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status) { double transfer_out=0; double k=pow(10.,lk); if(clt->tracer_type==CL_TRACER_NC) transfer_out=transfer_nc(w->l_arr[il],k,cosmo,w,clt,status); else if(clt->tracer_type==CL_TRACER_WL) transfer_out=transfer_wl(w->l_arr[il],k,cosmo,w,clt,status); else if(clt->tracer_type==CL_TRACER_CL) transfer_out=transfer_cmblens(w->l_arr[il],k,cosmo,clt,status); else transfer_out=-1; return transfer_out; } static double *get_lkarr(ccl_cosmology *cosmo,CCL_ClWorkspace *w, double l,double chimin,double chimax,int *nk, int *status) { int ik; //First compute relevant k-range for this ell double kmin,kmax,lkmin,lkmax; if(l>w->l_limber) { kmin=CCL_MAX(ccl_splines->K_MIN,0.8*(l+0.5)/chimax); kmax=CCL_MIN(ccl_splines->K_MAX,1.2*(l+0.5)/chimin); } else { double xmin,xmax; limits_bessel(l,CCL_FRAC_RELEVANT,&xmin,&xmax); kmin=CCL_MAX(ccl_splines->K_MIN,xmin/chimax); kmax=CCL_MIN(ccl_splines->K_MAX,xmax/chimin); //Cap by maximum meaningful argument of the Bessel function kmax=CCL_MIN(kmax,2*(w->l_arr[w->n_ls-1]+0.5)/chimin); //Cap by 2 x inverse scale corresponding to l_max } lkmin=log10(kmin); lkmax=log10(kmax); //Allocate memory for transfer function double *lkarr; double lknew=lkmin; double k_period=2*M_PI/chimax; double dklin=0.45; ik=0; while(lknew<=lkmax) { double kk=pow(10.,lknew); double dk1=k_period*dklin; double dk2=kk*(pow(10.,w->dlk)-1.); double dk=CCL_MIN(dk1,dk2); lknew=log10(kk+dk); ik++; } *nk=CCL_MAX(10,ik+1); lkarr=(double *)malloc((*nk)*sizeof(double)); if(lkarr==NULL) { return NULL; } if((*nk)==10) { for(ik=0;ik<(*nk);ik++) lkarr[ik]=lkmin+(lkmax-lkmin)*ik/((*nk)-1.); } else { ik=0; lkarr[ik]=lkmin; while(lkarr[ik]<=lkmax) { double kk=pow(10.,lkarr[ik]); double dk1=k_period*dklin; double dk2=kk*(pow(10.,w->dlk)-1.); double dk=CCL_MIN(dk1,dk2); ik++; lkarr[ik]=log10(kk+dk); } } return lkarr; } static void compute_transfer(CCL_ClTracer *clt,ccl_cosmology *cosmo,CCL_ClWorkspace *w,int *status) { int il; double zmin=CCL_MAX(w->zmin,clt->zmin); double chimin=ccl_comoving_radial_distance(cosmo,1./(1+zmin),status); double chimax=clt->chimax; //Get how many multipoles and allocate info for each of them clt->n_ls=w->n_ls; clt->n_k=(int *)malloc(clt->n_ls*sizeof(int)); if(clt->n_k==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: compute_transfer(): memory allocation\n"); return; } clt->spl_transfer=(SplPar **)malloc(clt->n_ls*sizeof(SplPar *)); if(clt->spl_transfer==NULL) { free(clt->n_k); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: compute_transfer(): memory allocation\n"); return; } //Loop over multipoles and compute transfer function for each for(il=0;il<clt->n_ls;il++) { int ik,nk; double l=(double)(w->l_arr[il]); double *lkarr=get_lkarr(cosmo,w,l,chimin,chimax,&nk,status); if(lkarr==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: compute_transfer(): memory allocation\n"); break; } double *tkarr=(double *)malloc(nk*sizeof(double)); if(tkarr==NULL) { free(lkarr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: compute_transfer(): memory allocation\n"); break; } clt->n_k[il]=nk; //Loop over k and compute transfer function for(ik=0;ik<nk;ik++) tkarr[ik]=transfer_wrap(il,lkarr[ik],cosmo,w,clt,status); if(*status) { free(clt->n_k); free(lkarr); free(tkarr); break; } //Initialize spline for this ell clt->spl_transfer[il]=ccl_spline_init(nk,lkarr,tkarr,0,0); if(clt->spl_transfer[il]==NULL) { free(lkarr); free(tkarr); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: compute_transfer(): memory allocation\n"); break; } free(lkarr); free(tkarr); } if(*status) { free(clt->n_k); int ill; for(ill=0;ill<il;ill++) ccl_spline_free(clt->spl_transfer[il]); free(clt->spl_transfer); } clt->computed_transfer=1; } static double transfer(int il,double lk,ccl_cosmology *cosmo, CCL_ClWorkspace *w,CCL_ClTracer *clt,int *status) { if(il<w->l_limber) { if(!(clt->computed_transfer)) compute_transfer(clt,cosmo,w,status); return ccl_spline_eval(lk,clt->spl_transfer[il]); } else { return transfer_wrap(il,lk,cosmo,w,clt,status); } } //Params for power spectrum integrand typedef struct { int il; ccl_cosmology *cosmo; CCL_ClWorkspace *w; CCL_ClTracer *clt1; CCL_ClTracer *clt2; int *status; } IntClPar; //Integrand for integral power spectrum static double cl_integrand(double lk,void *params) { double d1,d2; IntClPar *p=(IntClPar *)params; d1=transfer(p->il,lk,p->cosmo,p->w,p->clt1,p->status); d2=transfer(p->il,lk,p->cosmo,p->w,p->clt2,p->status); return pow(10.,3*lk)*d1*d2; } //Figure out k intervals where the Limber kernel has support //clt1 -> tracer #1 //clt2 -> tracer #2 //l -> angular multipole //lkmin, lkmax -> log10 of the range of scales where the transfer functions have support static void get_k_interval(ccl_cosmology *cosmo,CCL_ClWorkspace *w, CCL_ClTracer *clt1,CCL_ClTracer *clt2,int l, double *lkmin,double *lkmax) { double chimin,chimax; int cut_low_1=0,cut_low_2=0; //Define a minimum distance only if no lensing is needed if((clt1->tracer_type==CL_TRACER_NC) && (clt1->has_magnification==0)) cut_low_1=1; if((clt2->tracer_type==CL_TRACER_NC) && (clt2->has_magnification==0)) cut_low_2=1; if(l<w->l_limber) { chimin=2*(l+0.5)/ccl_splines->K_MAX; chimax=0.5*(l+0.5)/ccl_splines->K_MIN; } else { if(cut_low_1) { if(cut_low_2) { chimin=fmax(clt1->chimin,clt2->chimin); chimax=fmin(clt1->chimax,clt2->chimax); } else { chimin=clt1->chimin; chimax=clt1->chimax; } } else if(cut_low_2) { chimin=clt2->chimin; chimax=clt2->chimax; } else { chimin=0.5*(l+0.5)/ccl_splines->K_MAX; chimax=2*(l+0.5)/ccl_splines->K_MIN; } } if(chimin<=0) chimin=0.5*(l+0.5)/ccl_splines->K_MAX; *lkmax=fmin( 2,log10(2 *(l+0.5)/chimin)); *lkmin=fmax(-4,log10(0.5*(l+0.5)/chimax)); } //Compute angular power spectrum between two bins //cosmo -> ccl_cosmology object //il -> index in angular multipole array //clt1 -> tracer #1 //clt2 -> tracer #2 static double ccl_angular_cl_native(ccl_cosmology *cosmo,CCL_ClWorkspace *cw,int il, CCL_ClTracer *clt1,CCL_ClTracer *clt2,int * status) { int clastatus=0, gslstatus; IntClPar ipar; double result=0,eresult; double lkmin,lkmax; gsl_function F; gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION); ipar.il=il; ipar.cosmo=cosmo; ipar.w=cw; ipar.clt1=clt1; ipar.clt2=clt2; ipar.status = &clastatus; F.function=&cl_integrand; F.params=&ipar; get_k_interval(cosmo,cw,clt1,clt2,cw->l_arr[il],&lkmin,&lkmax); gslstatus=gsl_integration_qag(&F, lkmin, lkmax, 0, ccl_gsl->INTEGRATION_LIMBER_EPSREL, ccl_gsl->N_ITERATION, ccl_gsl->INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS, w, &result, &eresult); gsl_integration_workspace_free(w); // Test if a round-off error occured in the evaluation of the integral // If so, try another integration function, more robust but potentially slower if(gslstatus == GSL_EROUND) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: ccl_angular_cl_native(): Default GSL integration failure, attempting backup method."); gsl_integration_cquad_workspace *w_cquad= gsl_integration_cquad_workspace_alloc (ccl_gsl->N_ITERATION); size_t nevals=0; gslstatus=gsl_integration_cquad(&F, lkmin, lkmax, 0, ccl_gsl->INTEGRATION_LIMBER_EPSREL, w_cquad, &result, &eresult, &nevals); gsl_integration_cquad_workspace_free(w_cquad); } if(gslstatus!=GSL_SUCCESS || *ipar.status) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: ccl_angular_cl_native():"); // If an error status was already set, don't overwrite it. if(*status == 0){ *status=CCL_ERROR_INTEG; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_angular_cl_native(): error integrating over k\n"); } return -1; } ccl_check_status(cosmo,status); return result*M_LN10*2./M_PI; } void ccl_angular_cls(ccl_cosmology *cosmo,CCL_ClWorkspace *w, CCL_ClTracer *clt1,CCL_ClTracer *clt2, int nl_out,int *l_out,double *cl_out,int *status) { int ii; //First check if ell range is within workspace for(ii=0;ii<nl_out;ii++) { if(l_out[ii]>w->lmax) { *status=CCL_ERROR_SPLINE_EV; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_angular_cls(); " "requested l beyond range allowed by workspace\n"); return; } } //Allocate array for power spectrum at interpolation nodes double *l_nodes=(double *)malloc(w->n_ls*sizeof(double)); if(l_nodes==NULL) { *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_angular_cls(); memory allocation\n"); return; } double *cl_nodes=(double *)malloc(w->n_ls*sizeof(double)); if(cl_nodes==NULL) { free(l_nodes); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_angular_cls(); memory allocation\n"); return; } for(ii=0;ii<w->n_ls;ii++) l_nodes[ii]=(double)(w->l_arr[ii]); //Now check if angpow is needed at all int method_use=w->nlimb_method; if(method_use==CCL_NONLIMBER_METHOD_ANGPOW) { int do_angpow=0; for(ii=0;ii<w->n_ls;ii++) { if(w->l_arr[ii]<=w->l_limber) do_angpow=1; } //Resort to native method if we have lensing (this will hopefully only be temporary) if(clt1->tracer_type==CL_TRACER_WL || clt2->tracer_type==CL_TRACER_WL || clt1->has_magnification || clt2->has_magnification) { do_angpow=0; method_use=CCL_NONLIMBER_METHOD_NATIVE; } //Use angpow if non-limber is needed #ifdef HAVE_ANGPOW if(do_angpow) ccl_angular_cls_angpow(cosmo,w,clt1,clt2,cl_nodes,status); ccl_check_status(cosmo,status); #else do_angpow=0; method_use=CCL_NONLIMBER_METHOD_NATIVE; #endif } //Compute limber nodes for(ii=0;ii<w->n_ls;ii++) { if((method_use==CCL_NONLIMBER_METHOD_NATIVE) || (w->l_arr[ii]>w->l_limber)) cl_nodes[ii]=ccl_angular_cl_native(cosmo,w,ii,clt1,clt2,status); } //Interpolate into ells requested by user SplPar *spcl_nodes=ccl_spline_init(w->n_ls,l_nodes,cl_nodes,0,0); if(spcl_nodes==NULL) { free(cl_nodes); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_angular_cls(); memory allocation\n"); return; } for(ii=0;ii<nl_out;ii++) cl_out[ii]=ccl_spline_eval((double)(l_out[ii]),spcl_nodes); //Cleanup ccl_spline_free(spcl_nodes); free(cl_nodes); free(l_nodes); } static int check_clt_fa_inconsistency(CCL_ClTracer *clt,int func_code) { if(((func_code==CCL_CLT_NZ) && (clt->tracer_type==CL_TRACER_CL)) || //Lensing has no N(z) (((func_code==CCL_CLT_BZ) || (func_code==CCL_CLT_SZ) || (func_code==CCL_CLT_WM)) && (clt->tracer_type!=CL_TRACER_NC)) || //bias and magnification only for clustering (((func_code==CCL_CLT_RF) || (func_code==CCL_CLT_BA) || (func_code==CCL_CLT_WL)) && (clt->tracer_type!=CL_TRACER_WL))) //IAs only for weak lensing return 1; if((((func_code==CCL_CLT_SZ) || (func_code==CCL_CLT_WM)) && (clt->has_magnification==0)) || //Correct combination, but no magnification (((func_code==CCL_CLT_RF) || (func_code==CCL_CLT_BA)) && (clt->has_intrinsic_alignment==0))) //Correct combination, but no IAs return 1; return 0; } double ccl_get_tracer_fa(ccl_cosmology *cosmo,CCL_ClTracer *clt,double a,int func_code,int *status) { SplPar *spl; double x=1./a-1; //x-variable is redshift by default if(check_clt_fa_inconsistency(clt,func_code)) { *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: inconsistent combination of tracer and internal function to be evaluated"); return -1; } if(func_code==CCL_CLT_NZ) spl=clt->spl_nz; if(func_code==CCL_CLT_BZ) spl=clt->spl_bz; if(func_code==CCL_CLT_SZ) spl=clt->spl_sz; if(func_code==CCL_CLT_RF) spl=clt->spl_rf; if(func_code==CCL_CLT_BA) spl=clt->spl_ba; if((func_code==CCL_CLT_WL) || (func_code==CCL_CLT_WM)) { x=ccl_comoving_radial_distance(cosmo,a,status); if(func_code==CCL_CLT_WL) spl=clt->spl_wL; if(func_code==CCL_CLT_WM) spl=clt->spl_wM; } return ccl_spline_eval(x,spl); } int ccl_get_tracer_fas(ccl_cosmology *cosmo,CCL_ClTracer *clt,int na,double *a,double *fa, int func_code,int *status) { SplPar *spl; if(check_clt_fa_inconsistency(clt,func_code)) { *status=CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: inconsistent combination of tracer and internal function to be evaluated"); return -1; } if(func_code==CCL_CLT_NZ) spl=clt->spl_nz; if(func_code==CCL_CLT_BZ) spl=clt->spl_bz; if(func_code==CCL_CLT_SZ) spl=clt->spl_sz; if(func_code==CCL_CLT_RF) spl=clt->spl_rf; if(func_code==CCL_CLT_BA) spl=clt->spl_ba; if(func_code==CCL_CLT_WL) spl=clt->spl_wL; if(func_code==CCL_CLT_WM) spl=clt->spl_wM; int compchi=0; if((func_code==CCL_CLT_WL) || (func_code==CCL_CLT_WM)) compchi=1; int ia; for(ia=0;ia<na;ia++) { double x; if(compchi) x=ccl_comoving_radial_distance(cosmo,a[ia],status); else x=1./a[ia]-1; fa[ia]=ccl_spline_eval(x,spl); } return 0; }
{ "alphanum_fraction": 0.6800353227, "avg_line_length": 30.559970015, "ext": "c", "hexsha": "688cb856f420b79ec10b7822024ceb9ce620a021", "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": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_path": "src/ccl_cls.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "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": "Russell-Jones-OxPhys/CCL", "max_issues_repo_path": "src/ccl_cls.c", "max_line_length": 168, "max_stars_count": null, "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_path": "src/ccl_cls.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 13648, "size": 40767 }
/***************************************************************************** * * Copyright (c) 2003-2018 by The University of Queensland * http://www.uq.edu.au * * Primary Business: Queensland, Australia * Licensed under the Apache License, version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Development until 2012 by Earth Systems Science Computational Center (ESSCC) * Development 2012-2013 by School of Earth Sciences * Development from 2014 by Centre for Geoscience Computing (GeoComp) * *****************************************************************************/ #ifndef __PASO_BLOCKOPS_H__ #define __PASO_BLOCKOPS_H__ #include "Paso.h" #include "PasoException.h" #include <cstring> // memcpy #ifdef ESYS_HAVE_LAPACK #ifdef ESYS_MKL_LAPACK #include <mkl_lapack.h> #include <mkl_cblas.h> #else extern "C" { #include <clapack.h> #include <cblas.h> } #endif #endif namespace paso { inline void BlockOps_Cpy_N(dim_t N, double* R, const double* V) { memcpy((void*)R, (void*)V, N*sizeof(double)); } /// performs operation R=R-mat*V (V and R are not overlapping) - 2x2 inline void BlockOps_SMV_2(double* R, const double* mat, const double* V) { const double S1 = V[0]; const double S2 = V[1]; const double A11 = mat[0]; const double A12 = mat[2]; const double A21 = mat[1]; const double A22 = mat[3]; R[0] -= A11 * S1 + A12 * S2; R[1] -= A21 * S1 + A22 * S2; } /// performs operation R=R-mat*V (V and R are not overlapping) - 3x3 inline void BlockOps_SMV_3(double* R, const double* mat, const double* V) { const double S1 = V[0]; const double S2 = V[1]; const double S3 = V[2]; const double A11 = mat[0]; const double A21 = mat[1]; const double A31 = mat[2]; const double A12 = mat[3]; const double A22 = mat[4]; const double A32 = mat[5]; const double A13 = mat[6]; const double A23 = mat[7]; const double A33 = mat[8]; R[0] -= A11 * S1 + A12 * S2 + A13 * S3; R[1] -= A21 * S1 + A22 * S2 + A23 * S3; R[2] -= A31 * S1 + A32 * S2 + A33 * S3; } #define PASO_MISSING_CLAPACK throw PasoException("You need to install a LAPACK version to enable operations on block sizes > 3.") /// performs operation R=R-mat*V (V and R are not overlapping) - NxN inline void BlockOps_SMV_N(dim_t N, double* R, const double* mat, const double* V) { #ifdef ESYS_HAVE_LAPACK cblas_dgemv(CblasColMajor,CblasNoTrans, N, N, -1., mat, N, V, 1, 1., R, 1); #else PASO_MISSING_CLAPACK; #endif } inline void BlockOps_MV_N(dim_t N, double* R, const double* mat, const double* V) { #ifdef ESYS_HAVE_LAPACK cblas_dgemv(CblasColMajor,CblasNoTrans, N, N, 1., mat, N, V, 1, 0., R, 1); #else PASO_MISSING_CLAPACK; #endif } inline void BlockOps_invM_2(double* invA, const double* A, int* failed) { const double A11 = A[0]; const double A12 = A[2]; const double A21 = A[1]; const double A22 = A[3]; double D = A11*A22-A12*A21; if (std::abs(D) > 0) { D = 1./D; invA[0] = A22*D; invA[1] = -A21*D; invA[2] = -A12*D; invA[3] = A11*D; } else { *failed = 1; } } inline void BlockOps_invM_3(double* invA, const double* A, int* failed) { const double A11 = A[0]; const double A21 = A[1]; const double A31 = A[2]; const double A12 = A[3]; const double A22 = A[4]; const double A32 = A[5]; const double A13 = A[6]; const double A23 = A[7]; const double A33 = A[8]; double D = A11*(A22*A33-A23*A32) + A12*(A31*A23-A21*A33) + A13*(A21*A32-A31*A22); if (std::abs(D) > 0) { D = 1./D; invA[0] = (A22*A33-A23*A32)*D; invA[1] = (A31*A23-A21*A33)*D; invA[2] = (A21*A32-A31*A22)*D; invA[3] = (A13*A32-A12*A33)*D; invA[4] = (A11*A33-A31*A13)*D; invA[5] = (A12*A31-A11*A32)*D; invA[6] = (A12*A23-A13*A22)*D; invA[7] = (A13*A21-A11*A23)*D; invA[8] = (A11*A22-A12*A21)*D; } else { *failed = 1; } } /// LU factorization of NxN matrix mat with partial pivoting inline void BlockOps_invM_N(dim_t N, double* mat, index_t* pivot, int* failed) { #ifdef ESYS_HAVE_LAPACK #ifdef ESYS_MKL_LAPACK int res = 0; dgetrf(&N, &N, mat, &N, pivot, &res); if (res != 0) *failed = 1; #else int res = clapack_dgetrf(CblasColMajor, N, N, mat, N, pivot); if (res != 0) *failed = 1; #endif // ESYS_MKL_LAPACK #else PASO_MISSING_CLAPACK; #endif } /// solves system of linear equations A*X=B inline void BlockOps_solve_N(dim_t N, double* X, double* mat, index_t* pivot, int* failed) { #ifdef ESYS_HAVE_LAPACK #ifdef ESYS_MKL_LAPACK int res = 0; int ONE = 1; dgetrs("N", &N, &ONE, mat, &N, pivot, X, &N, &res); if (res != 0) *failed = 1; #else int res = clapack_dgetrs(CblasColMajor, CblasNoTrans, N, 1, mat, N, pivot, X, N); if (res != 0) *failed = 1; #endif // ESYS_MKL_LAPACK #else PASO_MISSING_CLAPACK; #endif } /// inplace matrix vector product - order 2 inline void BlockOps_MViP_2(const double* mat, double* V) { const double S1 = V[0]; const double S2 = V[1]; const double A11 = mat[0]; const double A12 = mat[2]; const double A21 = mat[1]; const double A22 = mat[3]; V[0] = A11 * S1 + A12 * S2; V[1] = A21 * S1 + A22 * S2; } /// inplace matrix vector product - order 3 inline void BlockOps_MViP_3(const double* mat, double* V) { const double S1 = V[0]; const double S2 = V[1]; const double S3 = V[2]; const double A11 = mat[0]; const double A21 = mat[1]; const double A31 = mat[2]; const double A12 = mat[3]; const double A22 = mat[4]; const double A32 = mat[5]; const double A13 = mat[6]; const double A23 = mat[7]; const double A33 = mat[8]; V[0] = A11 * S1 + A12 * S2 + A13 * S3; V[1] = A21 * S1 + A22 * S2 + A23 * S3; V[2] = A31 * S1 + A32 * S2 + A33 * S3; } inline void BlockOps_solveAll(dim_t n_block, dim_t n, double* D, index_t* pivot, double* x) { if (n_block == 1) { #pragma omp parallel for for (dim_t i=0; i<n; ++i) x[i] *= D[i]; } else if (n_block == 2) { #pragma omp parallel for for (dim_t i=0; i<n; ++i) BlockOps_MViP_2(&D[4*i], &x[2*i]); } else if (n_block == 3) { #pragma omp parallel for for (dim_t i=0; i<n; ++i) BlockOps_MViP_3(&D[9*i], &x[3*i]); } else { int failed = 0; #pragma omp parallel for for (dim_t i=0; i<n; ++i) { const dim_t block_size = n_block*n_block; BlockOps_solve_N(n_block, &x[n_block*i], &D[block_size*i], &pivot[n_block*i], &failed); } if (failed > 0) { throw PasoException("BlockOps_solveAll: solution failed."); } } } } // namespace paso #endif // __PASO_BLOCKOPS_H__
{ "alphanum_fraction": 0.5769064437, "avg_line_length": 27.748, "ext": "h", "hexsha": "15d576e9d00c880f6c272aa581899ea179dbe745", "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": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_path": "paso/src/BlockOps.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_path": "paso/src/BlockOps.h", "max_line_length": 129, "max_stars_count": null, "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_path": "paso/src/BlockOps.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2380, "size": 6937 }
#include <stdio.h> #include <math.h> #include <ascii.h> #include <cdisort.h> #include <c_tzs.h> #include "locate.h" #if HAVE_LIBGSL #include <gsl/gsl_sf_expint.h> #endif // include DISORT.MXD /* nlyr = number of atmospheric layers */ /* nlev_c = number of atmospheric levels on common z grid */ /* zd_c = atmospheric levels on common z grid */ /* nzout = number of output levels = number of black clouds */ /* zout = vertical level heights in km above surface */ int c_tzs (int nlyr, float* dtauc, int nlev_c, float* zd_c, int nzout, float* zout, float* ssalb, float* temper, float wvnmlo, float wvnmhi, int usrtau, int ntau, float* utau, int usrang, int numu, float* umu, int nphi, float* phi, float albedo, double btemp, float ttemp, float temis, int planck, int* prnt, char* header, // int prndis[7]; char header[127] float* rfldir, float* rfldn, float* flup, float* dfdt, float* uavg, float*** uu, int quiet) { /* .. Internal variables */ int lc, j, iu, lu; double* tauc = NULL; double tau1 = 0, tau2 = 0, etau1 = 0, etau2 = 0, etaumu = 0, ei1 = 0, ei2 = 0, *rad = NULL; double *radem = NULL, *pkag = NULL, *etau = NULL, rademtot = 0.0; double radrefl, radrefl1, radrefl2, radrefl11, radrefl22; double *b0 = NULL, *b1 = NULL; double *coeff1 = NULL, *coeff2 = NULL; double sqtau1 = 0.0, sqtau2 = 0.0, mu = 0.0, cutau1 = 0.0, tauetau1; int * nlayers = NULL, maxnlyr = 0; float * alb = NULL, *bplanck = NULL; /* nlyr = number of layers */ /* nlyr + 1 = number of levels */ /* initialise */ if ((rad = (double*)calloc (ntau, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((nlayers = (int*)calloc (ntau, sizeof (int))) == NULL) return ASCII_NO_MEMORY; if ((alb = (float*)calloc (ntau, sizeof (float))) == NULL) return ASCII_NO_MEMORY; if ((bplanck = (float*)calloc (ntau, sizeof (float))) == NULL) return ASCII_NO_MEMORY; if (prnt[0] && strlen (header) != 0) { fprintf (stderr, "**************\n TZS: %s\n*****************\n", header); } /* Initialise everything to 0. */ for (iu = 0; iu < numu; iu++) { for (lu = 0; lu < nzout; lu++) { for (j = 0; j < nphi; j++) { uu[j][lu][iu] = 0.; } } } for (lu = 0; lu < nzout; lu++) { dfdt[lu] = 0.; flup[lu] = 0.; rfldir[lu] = 0.; rfldn[lu] = 0.; uavg[lu] = 0.; } /* Layers: 0...NLYR-1 (# layers = NLYR) */ /* Levels: 0...NLYR (# levels = NLYR+1) */ /* LC = 0...NYR-1 */ /* LC = 0 : TOA */ /* -------------------------------------------------- Level LC, TAUC(LC), TEMPER(LC) */ /* */ /* Layer LC */ /* */ /* -------------------------------------------------- Level LC+1 , TAUC(LC+1) , TEMPER(LC+1) */ /* Planck radiation from surface with emissivity=1-ALBEDO and temperature BTEMP */ /* BPLANCK = (1-ALBEDO)*PLKAVG2( WVNMLO, WVNMHI, BTEMP ) */ /* Max number of layers counted from TOA used for all UTAU */ maxnlyr = -1; /* Loop over user defined tau = black cloud top heights: */ /* determine layer number corresponding to user tau */ /* Rem.: NTAU = NZOUT checked in CHEKIN_TZS */ if (ntau != nzout) { errmsg_tzs ("TZS--nzout != ntau", TZS_ERROR); } for (lu = 0; lu < ntau; lu++) { /* zd_c[0] = TOA */ /* zd_c[nlyr+1] = SUR */ /* locate gives back lc such that zd_c(lc) >= zout(lu) > zd_lc[lc+1] */ lc = flocate (zd_c, nlev_c, zout[lu]); // fprintf(stderr,"lc = %d zd_c[lc] = %f zd_c[lc+1] = %f zout[lu] = %f\n",lc,zd_c[lc],zd_c[lc+1],zout[lu]); if (lc == -1 || lc == nlev_c) { errmsg_tzs ("TZS--Zout outside atmospheric levels", TZS_ERROR); } /* Check real presence of this level in tauc ( max diff = 1mm ) */ /* Determine layer above given user level and store layer index w.r.t. zd_c in nlayers */ /* nlayers contains the layer index whose bottom is at zout[lu] */ if (fabs (zd_c[lc + 1] - zout[lu]) <= 1.e-6) { /* check lower boundary */ /* nlevel = nlayers[lu] = LC+1-1 */ /* nlayer = nlevel - 1 */ nlayers[lu] = lc; } else if (fabs (zd_c[lc] - zout[lu]) <= 1.e-6) { /* check upper boundary */ /* nlevel = nlayers[lu] = LC */ /* nlayer = nlevel - 1 */ nlayers[lu] = (int)fmax (lc - 1, 0); /* nlayers could be -1 when black cloud is at TOA */ } else { /* zout_interpolate */ // fprintf(stderr,"%d4 %4d %9.3f %9.3f %9.3f %9.3f %9.3f\n", // lc,nlev_c,zd_c[lc+1],zd_c[lc],zout[lu],fabs(zd_c[lc+1]-zout[lu]),fabs(zd_c[lc]-zout[lu])); errmsg_tzs ("TZS--User height is not contained in atmospheric levels: use zout_interpolate!", TZS_ERROR); } // fprintf(stderr,"nlev_c = %4d zout[lu] = %9.3f zd_c[nlayers[lu]] = %9.3f zd_c[nlayers[lu]+1] = %9.3f lu = %4d\n", // nlev_c,zout[lu],zd_c[nlayers[lu]],zd_c[nlayers[lu]+1],lu); // // fprintf(stderr,"lu = %4d maxnlyr = %4d nlayers[lu] = %4d\n",lu,maxnlyr,nlayers[lu]); maxnlyr = (int)fmax (maxnlyr, nlayers[lu]); } /* Above we defined layer indices, now we add +1 because we want the number of layers */ maxnlyr += 1; // fprintf(stderr,"%s %4d\n","Max # layers = ",maxnlyr); if (maxnlyr < 0) { errmsg_tzs ("TZS--wrong zout", TZS_ERROR); } if ((radem = (double*)calloc (maxnlyr, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((tauc = (double*)calloc (maxnlyr + 1, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((pkag = (double*)calloc (maxnlyr + 1, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((etau = (double*)calloc (maxnlyr + 1, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((b0 = (double*)calloc (maxnlyr, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((b1 = (double*)calloc (maxnlyr, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((coeff1 = (double*)calloc (maxnlyr, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((coeff2 = (double*)calloc (maxnlyr, sizeof (double))) == NULL) return ASCII_NO_MEMORY; /* calculate cumulative optical depth tauc[lc] up to level lc and */ /* Planck radiation for every level (not layer!) from 0 to MAXNLYR */ /* Remark: layer 1 is the first layer from above=TOA?? */ /* level 0 is the first level from above=TOA, level 0 = TOA */ /* lc = level count */ lc = 0; tauc[lc] = 0.0; pkag[lc] = (double)c_planck_func1 (wvnmlo, wvnmhi, temper[lc]); // fprintf(stderr,"lc = %d maxnlyr = %d pkag[lc] = %f tauc[lc] = %13.6e dtauc[lc-1] = %13.6e temper[lc] = %9.3f\n",lc,maxnlyr,pkag[lc],tauc[lc],dtauc[lc-1],temper[lc]); for (lc = 1; lc <= maxnlyr; lc++) { /* We work here with atmospheric optical thickness as it is provided by the user. */ /* If you want to use aborption optical thickness the you have to define it in */ /* the uvspec input file. */ tauc[lc] = tauc[lc - 1] + ((double)dtauc[lc - 1]); pkag[lc] = (double)c_planck_func1 (wvnmlo, wvnmhi, temper[lc]); // fprintf(stderr,"lc = %d maxnlyr = %d pkag[lc] = %f tauc[lc] = %13.6e dtauc[lc-1] = %13.6e temper[lc] = %9.3f\n",lc,maxnlyr,pkag[lc],tauc[lc],dtauc[lc-1],temper[lc]); } /* Print input information */ if (prnt[0]) { prtinp_tzs (nlyr, maxnlyr, dtauc, ssalb, temper, wvnmlo, wvnmhi, ntau, utau, numu, umu, nphi, phi, albedo, btemp, ttemp, temis, tauc, nlev_c, zd_c, nzout, zout); } /* check input dimensions and variables */ chekin_tzs (nlyr, maxnlyr, dtauc, nlev_c, zd_c, nzout, zout, ssalb, temper, wvnmlo, wvnmhi, usrtau, ntau, utau, usrang, numu, umu, nphi, phi, albedo, btemp, ttemp, temis, planck, tauc, quiet); for (lu = 0; lu < ntau; lu++) { // fprintf(stderr,"lu = %4d nlayers[lu] = %4d nlyr = %4d\n",lu,nlayers[lu],nlyr); /* check layer bottom level */ if (nlayers[lu] + 1 == nlyr) { /* real surface albedo = 1 - emissivity */ alb[lu] = albedo; /* Planck radiation from surface with emissivity=1-ALBEDO and temperature BTEMP */ bplanck[lu] = (1 - alb[lu]) * c_planck_func1 (wvnmlo, wvnmhi, btemp); // fprintf(stderr,"%4d %4d %12.10f %12.9f %12.8f\n",lu, nlayers[lu]+1,alb[lu],bplanck[lu],btemp); } else { /* Real surface albedo = 1 - emissivity ==> emissivity=1 (black cloud) */ alb[lu] = 0.0; /* Planck radiation of bottom level with emissivity=1 (black cloud) */ /* and temperature temper( nlayers[lu]+1 ) of bottom level */ bplanck[lu] = (float)pkag[nlayers[lu] + 1]; } } if (prnt[0]) { fprintf (stderr, "\n%4d %s", ntau, " User optical depths :"); for (lu = 0; lu < ntau; lu++) fprintf (stderr, "%14.8f", utau[lu]); fprintf (stderr, "\n"); fprintf (stderr, "\n%4d %s", ntau, " User level numbers :"); for (lu = 0; lu < ntau; lu++) fprintf (stderr, "%4d", nlayers[lu] + 1); fprintf (stderr, "\n"); fprintf (stderr, "\n%4d %s", ntau, " User levels / km :"); for (lu = 0; lu < ntau; lu++) fprintf (stderr, "%14.8f", zout[lu]); fprintf (stderr, "\n"); fprintf (stderr, "\n%4d %s", ntau, " User levels / km :"); for (lu = 0; lu < ntau; lu++) fprintf (stderr, "%14.8f", zd_c[nlayers[lu] + 1]); fprintf (stderr, "\n"); } /* loop from TOA to lowest layer/level needed for calculations */ for (lc = 0; lc < maxnlyr; lc++) { /* assume linear variation of Planck radiation from one level */ /* to the next one: Planck=b0+tauc*b1 */ b1[lc] = 0.; /* CE: this threshold was commented out, but it seems that it is needed because otherwise we get negative emissions in some layers */ if (dtauc[lc] > 1.e-4) b1[lc] = (pkag[lc + 1] - pkag[lc]) / dtauc[lc]; /* In case of thin atmosphere but high temperature variation from one level to the next, dtauc is very small */ /* but Planck varies sensibly, so we have to take care. The threshold 1.e10 is not crucial because thin */ /* atmospheric layers emit few radiation. */ if (fabs (b1[lc]) > 1.e10) { /* set b0 to average Planck emission, also not crucial */ b0[lc] = 0.5 * (pkag[lc + 1] + pkag[lc]); b1[lc] = 0.0; } else { b0[lc] = pkag[lc] - tauc[lc] * b1[lc]; } /* Compute coefficients like this even if coeff1[lc]=pkag[lc+1] and coeff2[lc]=pkag[lc] */ coeff1[lc] = b0[lc] + tauc[lc + 1] * b1[lc]; coeff2[lc] = b0[lc] + tauc[lc] * b1[lc]; // fprintf(stderr," LC %d Deltatau %e DIFFCOEFF1 %e COEFF1 %e pkag[lc+1] = %e\n",lc,dtauc[lc],coeff1[lc]-pkag[lc+1],coeff1[lc],pkag[lc+1]); // fprintf(stderr," LC %d Deltatau %e DIFFCOEFF2 %e COEFF2 %e pkag[lc] = %e\n",lc,dtauc[lc],coeff2[lc]-pkag[lc],coeff2[lc],pkag[lc]); } /* Loop over UMUs */ for (iu = 0; iu < numu; iu++) { /* Double precision UMU */ mu = (double)umu[iu]; // /* loop from TOA to lowest layer/level needed for calculations */ // for (lc=0;lc<=maxnlyr;lc++){ // /* Initialise ETAU = Attenuation factors from TOA to levels LC in direction MU */ // etau[lc]=exp(-tauc[lc]/mu); // } /* Emission of atmosphere: */ /* *********************** */ /* Initialise ETAU = Attenuation factors from TOA to level LC in direction MU */ lc = 0; etau[lc] = exp (-tauc[lc] / mu); /* loop from TOA to lowest layer/level needed for calculations */ for (lc = 0; lc < maxnlyr; lc++) { /* Initialise ETAU = Attenuation factors from TOA to level LC+1 in direction MU */ etau[lc + 1] = exp (-tauc[lc + 1] / mu); /* Attenuation factors from TOA to levels LC+1 resp. LC: */ /* ETAU[lc+1] */ /* ETAU[lc] */ /* Radiation emitted from layer LC (between levels LC and LC+1) towards TOA */ radem[lc] = etau[lc] * coeff2[lc] - etau[lc + 1] * coeff1[lc] + b1[lc] * mu * (etau[lc] - etau[lc + 1]); } /* Loop over user defined tau = black cloud top heights */ for (lu = 0; lu < ntau; lu++) { // fprintf(stderr,"lu = %4d %4d\n",lu,nlayers[lu]); /* Initialise RAD to 0. */ rad[lu] = 0.; /* Initialise TAU1 */ /* to optical thickness from TOA up to bottom of layer nlayers[lu] */ /* TAU1 = TAUC(NLYR) */ tau1 = tauc[nlayers[lu] + 1]; /* Initialise ETAU1 */ etau1 = exp (-tau1); tauetau1 = tau1 * etau1; /* Initialise EI1 */ #if HAVE_LIBGSL /* exponential integral does not converge for values larger about 600*/ /* the integral for this case becomes 0*/ if (tau1 > 500.0) ei1 = 0.0; else ei1 = gsl_sf_expint_Ei (-tau1); /* fprintf(stderr, "lu %d tau1 %g ei1 %g\n",lu, tau1, ei1); */ #endif #if !HAVE_LIBGSL fprintf (stderr, "libRadtran was built without the gsl-library. Thus \n"); fprintf (stderr, "tzs may not be used. Please install gsl on your system\n"); fprintf (stderr, "and rebuild libRadtran.\n"); exit (0); #endif /* Initialise SQTAU1 */ sqtau1 = tau1 * tau1; /* Initialise CUTAU1 */ cutau1 = tau1 * sqtau1; /* initialise RADREFL11 */ radrefl11 = -2.0 * etau1 + tauetau1 - tau1 * tauetau1 - cutau1 * ei1; /* Attenuation factor due to full atmospheric absorption in direction MU */ etaumu = etau[nlayers[lu] + 1]; /* total atmospheric emission i.e. intergral from TOA to bottom */ rademtot = 0.0; /* Contribution from surface + atmosphere */ for (lc = 0; lc <= nlayers[lu]; lc++) { if (alb[lu] > 0.0) { /* Reflection from surface: */ /* ************************ */ tau2 = tau1; etau2 = etau1; ei2 = ei1; sqtau2 = sqtau1; radrefl22 = radrefl11; radrefl2 = etau2 * coeff2[lc] * (1. - tau2) - coeff2[lc] * sqtau2 * ei2; if (lc == nlayers[lu]) { radrefl1 = coeff1[lc]; radrefl11 = -2.0; } else { tau1 = tauc[nlayers[lu] + 1] - tauc[lc + 1]; etau1 = exp (-tau1); tauetau1 = tau1 * etau1; #if HAVE_LIBGSL /* exponential integral does not converge for values larger about 600*/ /* the integral for this case becomes 0*/ if (tau1 > 500.0) ei1 = 0.0; else ei1 = gsl_sf_expint_Ei (-tau1); #endif sqtau1 = tau1 * tau1; cutau1 = tau1 * sqtau1; radrefl11 = -2.0 * etau1 + tauetau1 - tau1 * tauetau1 - cutau1 * ei1; radrefl1 = etau1 * coeff1[lc] * (1. - tau1) - coeff1[lc] * sqtau1 * ei1; } radrefl = radrefl1 - radrefl2; /* fprintf(stderr,"%s %4d %4d %13.6e\n","LC NLAYERS RADREFL[lc]",lc,nlayers[lu],radrefl); */ /* fprintf(stderr,"%s %4d %13.6e\n","LC RADREFL1",lc,radrefl1); */ /* fprintf(stderr,"%s %4d %13.6e\n","LC RADREFL2",lc,radrefl2); */ /* fprintf(stderr,"%s %4d %13.6e %13.6e\n","LC COEFF1 COEFF2",lc,coeff1[lc],coeff2[lc]); */ /* fprintf(stderr,"%s %4d %13.6e %13.6e %13.6e %13.6e\n","LC TAU1 TAU2 SQTAU1 SQTAU2",lc,tau1,tau2,sqtau1,sqtau2); */ /* fprintf(stderr,"%s %4d %13.6e %13.6e\n","LC EI1 EI2",lc,ei1,ei2); */ radrefl += b1[lc] / 3. * (radrefl11 - radrefl22); // fprintf(stderr,"%s %4d %13.6e\n","LC RADREFL[lc]",lc,radrefl); // fprintf(stderr,"%s %4d %13.6e\n","LC B1[lc]",lc,b1[lc]); // fprintf(stderr,"%s %4d %13.6e\n","LC RADREFL11",lc,radrefl11); // fprintf(stderr,"%s %4d %13.6e\n","LC RADREFL22",lc,radrefl22); /* RAD[lu] = RAD[lu]+RADEM[lc]+ALBEDO*ETAUMU*RADREFL */ rad[lu] += radrefl; } /* emission of atmosphere */ rademtot += radem[lc]; } /* fprintf(stderr,"lu = %4d rad[lu] refl = %13.6e\n",lu,rad[lu]); */ /* after computation of radiance reflected at the surface we multiply by the albedo and the extinction from bottom to TOA */ /* RAD[lu] = RAD[lu]+RADEM[lc]+ALBEDO*ETAUMU*RADREFL */ rad[lu] *= alb[lu] * etaumu; /* fprintf(stderr,"lu = %4d rad[lu] refl attenuated = %13.6e\n",lu,rad[lu]); */ /* Contribution from atmospheric emission of all levels */ rad[lu] += rademtot; /* fprintf(stderr,"lu = %4d rad[lu] refl attenuated + emission = %13.6e\n",lu,rad[lu]); */ /* contribution from surface emission (bottom): */ /* ******************************************** */ rad[lu] += bplanck[lu] * etaumu; /* fprintf(stderr,"lu = %4d rad[lu] refl attenuated + emission + surface = %13.6e\n",lu,rad[lu]); */ /* isotropic radiance */ for (j = 0; j < nphi; j++) { uu[j][lu][iu] = (float)rad[lu]; } uavg[lu] = (float)rad[lu]; /* End loop over user tau */ } /* End loop over user umu */ } free (radem); free (tauc); free (pkag); free (etau); free (b0); free (b1); free (coeff1); free (coeff2); return 0; } /*============================= errmsg_tzs() ===============================*/ /* * Print out a warning or error message; abort if type == TZS_ERROR */ #define MAX_WARNINGS 100 void errmsg_tzs (char* messag, int type) { static int warning_limit = FALSE, num_warnings = 0; if (type == TZS_ERROR) { fprintf (stderr, "\n ******* ERROR >>>>>> %s\n", messag); exit (1); } if (warning_limit) return; if (++num_warnings <= MAX_WARNINGS) { fprintf (stderr, "\n ******* WARNING >>>>>> %s\n", messag); } else { fprintf (stderr, "\n\n >>>>>> TOO MANY WARNING MESSAGES -- They will no longer be printed <<<<<<<\n\n"); warning_limit = TRUE; } return; } #undef MAX_WARNINGS void prtinp_tzs (int nlyr, int maxnlyr, float* dtauc, float* ssalb, float* temper, float wvnmlo, float wvnmhi, int ntau, float* utau, int numu, float* umu, int nphi, float* phi, float albedo, double btemp, float ttemp, float temis, double* tauc, int nlev_c, float* zd_c, int nzout, float* zout) { /* print values of input variables */ /* */ /* Called by- TZS */ /* --------------------------------------------------------------------*/ /* .. Local Scalars .. */ int lc, lu; fprintf (stderr, "\n%s%4d\n", " No. computational layers = ", nlyr); fprintf (stderr, "\n%s%4d\n", " No. computational layers needed = ", maxnlyr); fprintf (stderr, "\n%4d %s", ntau, " User optical depths :"); for (lu = 0; lu < ntau; lu++) fprintf (stderr, "%13.6e", utau[lu]); fprintf (stderr, "\n"); fprintf (stderr, "\n%4d %s", numu, " User polar angle cosines :"); for (lu = 0; lu < numu; lu++) fprintf (stderr, "%9.5f", umu[lu]); fprintf (stderr, "\n"); fprintf (stderr, "\n%4d %s", nphi, " User azimuthal angles :"); for (lu = 0; lu < nphi; lu++) fprintf (stderr, "%9.2f", phi[lu]); fprintf (stderr, "\n"); fprintf (stderr, "%s%14.4f%14.4f\n%s%10.2f%s%8.4f\n%s%8.4f\n", " Thermal emission in wavenumber interval :", wvnmlo, wvnmhi, " Bottom temperature = ", btemp, " Top temperature = ", ttemp, " Top emissivity = ", temis); fprintf (stderr, "%s%8.4f\n", " Bottom albedo (Lambertian) =", albedo); /* Print layer variables */ fprintf (stderr, "\n%s\n%s\n%s\n", " Layer Total Single", " Optical Optical Scattering", " Depth Depth Albedo Temperature"); for (lc = 0; lc < maxnlyr; lc++) { fprintf (stderr, "%4d%13.6e%13.6e%14.3f%14.3f\n", lc, dtauc[lc], tauc[lc], ssalb[lc], temper[lc]); } fprintf (stderr, "%4d%13.6e%13.6e%14.3f%14.3f\n", maxnlyr, 0.0, tauc[maxnlyr], 0.0, temper[maxnlyr]); fprintf (stderr, "\n%s\n%s\n%s\n", " Layer Single", " Optical Scattering", " Depth Albedo Temperature"); for (lc = 0; lc < nlyr; lc++) { fprintf (stderr, "%4d%13.6e%14.3f%14.3f\n", lc, dtauc[lc], ssalb[lc], temper[lc]); } fprintf (stderr, "%4d%13.6e%14.3f%14.3f\n", nlyr, -1.0, -1.0, temper[nlyr]); fprintf (stderr, "\n%s\n%s\n%s\n", " Atmospheric", " Level", " [km]"); for (lc = 0; lc < nlev_c; lc++) { fprintf (stderr, "%4d %8.3f\n", lc, zd_c[lc]); } fprintf (stderr, "\n%s\n%s\n%s\n", " Output", " Level", " [km]"); for (lc = 0; lc < nzout; lc++) { fprintf (stderr, "%4d %8.3f\n", lc, zout[lc]); } } void chekin_tzs (int nlyr, int maxnlyr, float* dtauc, int nlev_c, float* zd_c, int nzout, float* zout, float* ssalb, float* temper, float wvnmlo, float wvnmhi, int usrtau, int ntau, float* utau, int usrang, int numu, float* umu, int nphi, float* phi, float albedo, double btemp, float ttemp, float temis, int planck, double* tauc, int quiet) { /* Checks the input dimensions and variables */ int inperr = FALSE; int lc, j, iu, lu; if (planck == FALSE) inperr = c_write_bad_var (VERBOSE, "planck"); if (nlyr < 1) inperr = c_write_bad_var (VERBOSE, "NLYR"); if (maxnlyr < 1) inperr = c_write_bad_var (VERBOSE, "MAXNLYR"); if (nlyr + 1 != nlev_c) inperr = c_write_bad_var (VERBOSE, "NLYR/NLEV_C"); for (lc = 0; lc < nlyr; lc++) { if (dtauc[lc] < 0.) { inperr = c_write_bad_var (VERBOSE, "dtauc"); } if (zd_c[lc] < 0.) { inperr = c_write_bad_var (VERBOSE, "zd"); } if (ssalb[lc] < 0.0 || ssalb[lc] > 1.0) { inperr = c_write_bad_var (VERBOSE, "ssalb"); } if (temper[lc] < 0.) { inperr = c_write_bad_var (VERBOSE, "temper"); } } if (usrtau) { if (ntau < 1) { inperr = c_write_bad_var (VERBOSE, "ntau"); } if (nzout < ntau) inperr = c_write_bad_var (VERBOSE, "ntau/nzout"); for (lu = 0; lu < ntau; lu++) { /* Do a relative check to see if we are just beyond the bottom boundary */ /* This might happen due to numerical rounding off problems. ak20110224*/ // fprintf(stderr,"lu = %d utau = %13.6e tauc[maxnlyr] = %13.6e zout = %f\n",lu,utau[lu],tauc[maxnlyr],zout[lu]); if (fabs (utau[lu] - tauc[maxnlyr]) <= 1.e-6 * tauc[maxnlyr]) { utau[lu] = tauc[maxnlyr]; } // fprintf(stderr,"lu = %d utau = %13.6e tauc[maxnlyr] = %13.6e zout = %f\n",lu,utau[lu],tauc[maxnlyr],zout[lu]); // if(utau[lu] < 0. || utau[lu] > tauc[maxnlyr]) { if (utau[lu] < 0. || (utau[lu] - tauc[maxnlyr]) > 1.e-6 * tauc[maxnlyr]) { fprintf (stderr, "WARNING: lu = %d utau = %13.6e tauc[maxnlyr] = %13.6e zout = %f\n", lu, utau[lu], tauc[maxnlyr], zout[lu]); inperr = c_write_bad_var (VERBOSE, "utau"); } if (zout[lu] < 0.0) inperr = c_write_bad_var (VERBOSE, "zout"); } } else { ntau = 1; utau = (float*)calloc (1, sizeof (float)); utau[0] = 0.; nzout = 1; zout = (float*)calloc (1, sizeof (float)); zout[0] = zd_c[0]; } if (usrang) { if (numu < 0) { inperr = c_write_bad_var (VERBOSE, "numu"); } for (iu = 0; iu < numu; iu++) { if (umu[iu] < -1. || umu[iu] > 1. || umu[iu] == 0.) { inperr = c_write_bad_var (VERBOSE, "umu"); } if (iu >= 1) { if (umu[iu] < umu[iu - 1]) { inperr = c_write_bad_var (VERBOSE, "umu"); } } } if (nphi <= 0) inperr = c_write_bad_var (VERBOSE, "nphi"); for (j = 0; j < nphi; j++) { if (phi[j] < 0. || phi[j] > 360.) { inperr = c_write_bad_var (VERBOSE, "phi"); } } } else { numu = 1; umu = (float*)calloc (1, sizeof (float)); umu[0] = 1.; nphi = 1; phi = (float*)calloc (1, sizeof (float)); phi[0] = 0.; } if (albedo < 0. || albedo > 1.) inperr = c_write_bad_var (VERBOSE, "albedo"); if (wvnmlo < 0.0 || wvnmhi <= wvnmlo) inperr = c_write_bad_var (VERBOSE, "wvnmlo,hi"); if (temis < 0. || temis > 1.) inperr = c_write_bad_var (VERBOSE, "temis"); if (btemp < 0.0) inperr = c_write_bad_var (VERBOSE, "btemp"); if (ttemp < 0.0) inperr = c_write_bad_var (VERBOSE, "ttemp"); if (inperr) c_errmsg ("TZS--input and/or dimension errors", TZS_ERROR); if (!quiet) { for (lc = 1; lc <= nlyr; lc++) { if (fabs (temper[lc] - temper[lc - 1]) > 10.) { c_errmsg ("check_inputs--vertical temperature step may be too large for good accuracy", TZS_WARNING); } } } }
{ "alphanum_fraction": 0.4672381481, "avg_line_length": 35.354601227, "ext": "c", "hexsha": "9d75e2379bffd64903be54233468c60b25a3e01a", "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": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/c_tzs.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "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": "AmberCrafter/docker-compose_libRadtran", "max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/c_tzs.c", "max_line_length": 178, "max_stars_count": null, "max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/c_tzs.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9004, "size": 28814 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "Data\Types.h" #include "MageSettings.h" #include "Image\ORBDescriptor.h" #include "BaseFeatureMatcher.h" #include <vector> #include <gsl\gsl> #include <memory> namespace mage { class Keyframe; class AnalyzedImage; class BaseBow { public: struct QueryMatch { Id<Keyframe> Id; float Score; operator mage::Id<Keyframe>() const { return Id; } }; BaseBow(const BagOfWordsSettings& settings) :m_settings{ settings } {} virtual ~BaseBow() {} virtual void AddTrainingDescriptors(gsl::span<const ORBDescriptor>) {} virtual void AddImage(const Id<Keyframe>, const AnalyzedImage& image) = 0; virtual void RemoveImage(const Id<Keyframe>) = 0; virtual size_t QueryFeatures(const ORBDescriptor& descriptor, const Id<Keyframe>& keyframe, std::vector<ptrdiff_t>& features) const = 0; virtual std::unique_ptr<BaseFeatureMatcher> CreateFeatureMatcher(const Id<Keyframe>& id, gsl::span<const ORBDescriptor> features) const = 0; virtual std::unique_ptr<BaseBow> CreateTemporaryBow() const = 0; virtual std::vector<QueryMatch> QueryUnknownImage(gsl::span<const ORBDescriptor> descriptors, size_t maxResults) const = 0; virtual void Clear() = 0; virtual bool IsTrainingDone() const { return true;} protected: const BagOfWordsSettings& m_settings; }; }
{ "alphanum_fraction": 0.641875, "avg_line_length": 25.8064516129, "ext": "h", "hexsha": "ad69898818294baf95bb5cefba9a22a34192770e", "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/BoW/BaseBow.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/BoW/BaseBow.h", "max_line_length": 148, "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/BoW/BaseBow.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": 363, "size": 1600 }
/* eigen/francis.c * * Copyright (C) 2006, 2007 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> /* * This module computes the eigenvalues of a real upper hessenberg * matrix, using the classical double shift Francis QR algorithm. * It will also optionally compute the full Schur form and matrix of * Schur vectors. * * See Golub & Van Loan, "Matrix Computations" (3rd ed), * algorithm 7.5.2 */ /* exceptional shift coefficients - these values are from LAPACK DLAHQR */ #define GSL_FRANCIS_COEFF1 (0.75) #define GSL_FRANCIS_COEFF2 (-0.4375) static inline void francis_schur_decomp(gsl_matrix * H, gsl_vector_complex * eval, gsl_eigen_francis_workspace * w); static inline size_t francis_search_subdiag_small_elements(gsl_matrix * A); static inline int francis_qrstep(gsl_matrix * H, gsl_eigen_francis_workspace * w); static inline void francis_schur_standardize(gsl_matrix *A, gsl_complex *eval1, gsl_complex *eval2, gsl_eigen_francis_workspace *w); static inline size_t francis_get_submatrix(gsl_matrix *A, gsl_matrix *B); static void francis_standard_form(gsl_matrix *A, double *cs, double *sn); /* gsl_eigen_francis_alloc() Allocate a workspace for solving the nonsymmetric eigenvalue problem. The size of this workspace is O(1) Inputs: none Return: pointer to workspace */ gsl_eigen_francis_workspace * gsl_eigen_francis_alloc(void) { gsl_eigen_francis_workspace *w; w = (gsl_eigen_francis_workspace *) calloc (1, sizeof (gsl_eigen_francis_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } /* these are filled in later */ w->size = 0; w->max_iterations = 0; w->n_iter = 0; w->n_evals = 0; w->compute_t = 0; w->Z = NULL; w->H = NULL; return (w); } /* gsl_eigen_francis_alloc() */ /* gsl_eigen_francis_free() Free francis workspace w */ void gsl_eigen_francis_free (gsl_eigen_francis_workspace *w) { RETURN_IF_NULL (w); free(w); } /* gsl_eigen_francis_free() */ /* gsl_eigen_francis_T() Called when we want to compute the Schur form T, or no longer compute the Schur form T Inputs: compute_t - 1 to compute T, 0 to not compute T w - francis workspace */ void gsl_eigen_francis_T (const int compute_t, gsl_eigen_francis_workspace *w) { w->compute_t = compute_t; } /* gsl_eigen_francis() Solve the nonsymmetric eigenvalue problem H x = \lambda x for the eigenvalues \lambda using algorithm 7.5.2 of Golub & Van Loan, "Matrix Computations" (3rd ed) Inputs: H - upper hessenberg matrix eval - where to store eigenvalues w - workspace Return: success or error - if error code is returned, then the QR procedure did not converge in the allowed number of iterations. In the event of non- convergence, the number of eigenvalues found will still be stored in the beginning of eval, Notes: On output, the diagonal of H contains 1-by-1 or 2-by-2 blocks containing the eigenvalues. If T is desired, H will contain the full Schur form on output. */ int gsl_eigen_francis (gsl_matrix * H, gsl_vector_complex * eval, gsl_eigen_francis_workspace * w) { /* check matrix and vector sizes */ if (H->size1 != H->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR); } else if (eval->size != H->size1) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else { const size_t N = H->size1; int j; /* * Set internal parameters which depend on matrix size. * The Francis solver can be called with any size matrix * since the workspace does not depend on N. * Furthermore, multishift solvers which call the Francis * solver may need to call it with different sized matrices */ w->size = N; w->max_iterations = 30 * N; /* * save a pointer to original matrix since francis_schur_decomp * is recursive */ w->H = H; w->n_iter = 0; w->n_evals = 0; /* * zero out the first two subdiagonals (below the main subdiagonal) * needed as scratch space by the QR sweep routine */ for (j = 0; j < (int) N - 3; ++j) { gsl_matrix_set(H, (size_t) j + 2, (size_t) j, 0.0); gsl_matrix_set(H, (size_t) j + 3, (size_t) j, 0.0); } if (N > 2) gsl_matrix_set(H, N - 1, N - 3, 0.0); /* * compute Schur decomposition of H and store eigenvalues * into eval */ francis_schur_decomp(H, eval, w); if (w->n_evals != N) return GSL_EMAXITER; return GSL_SUCCESS; } } /* gsl_eigen_francis() */ /* gsl_eigen_francis_Z() Solve the nonsymmetric eigenvalue problem for a Hessenberg matrix H x = \lambda x for the eigenvalues \lambda using the Francis double-shift method. Here we compute the real Schur form T = Q^t H Q with the diagonal blocks of T giving us the eigenvalues. Q is the matrix of Schur vectors. Originally, H was obtained from a general nonsymmetric matrix A via a transformation H = U^t A U so that T = (UQ)^t A (UQ) = Z^t A Z Z is the matrix of Schur vectors computed by this algorithm Inputs: H - upper hessenberg matrix eval - where to store eigenvalues Z - where to store Schur vectors w - workspace Notes: 1) If T is computed, it is stored in H on output. Otherwise, the diagonal of H will contain 1-by-1 and 2-by-2 blocks containing the eigenvalues. 2) The matrix Z must be initialized to the Hessenberg similarity matrix U. Or if you want the eigenvalues of H, initialize Z to the identity matrix. */ int gsl_eigen_francis_Z (gsl_matrix * H, gsl_vector_complex * eval, gsl_matrix * Z, gsl_eigen_francis_workspace * w) { int s; /* set internal Z pointer so we know to accumulate transformations */ w->Z = Z; s = gsl_eigen_francis(H, eval, w); w->Z = NULL; return s; } /* gsl_eigen_francis_Z() */ /******************************************** * INTERNAL ROUTINES * ********************************************/ /* francis_schur_decomp() Compute the Schur decomposition of the matrix H Inputs: H - hessenberg matrix eval - where to store eigenvalues w - workspace Return: none */ static inline void francis_schur_decomp(gsl_matrix * H, gsl_vector_complex * eval, gsl_eigen_francis_workspace * w) { gsl_matrix_view m; /* active matrix we are working on */ size_t N; /* size of matrix */ size_t q; /* index of small subdiagonal element */ gsl_complex lambda1, /* eigenvalues */ lambda2; N = H->size1; m = gsl_matrix_submatrix(H, 0, 0, N, N); while ((N > 2) && ((w->n_iter)++ < w->max_iterations)) { q = francis_search_subdiag_small_elements(&m.matrix); if (q == 0) { /* * no small subdiagonal element found - perform a QR * sweep on the active reduced hessenberg matrix */ francis_qrstep(&m.matrix, w); continue; } /* * a small subdiagonal element was found - one or two eigenvalues * have converged or the matrix has split into two smaller matrices */ if (q == (N - 1)) { /* * the last subdiagonal element of the matrix is 0 - * m_{NN} is a real eigenvalue */ GSL_SET_COMPLEX(&lambda1, gsl_matrix_get(&m.matrix, q, q), 0.0); gsl_vector_complex_set(eval, w->n_evals, lambda1); w->n_evals += 1; w->n_iter = 0; --N; m = gsl_matrix_submatrix(&m.matrix, 0, 0, N, N); } else if (q == (N - 2)) { gsl_matrix_view v; /* * The bottom right 2-by-2 block of m is an eigenvalue * system */ v = gsl_matrix_submatrix(&m.matrix, q, q, 2, 2); francis_schur_standardize(&v.matrix, &lambda1, &lambda2, w); gsl_vector_complex_set(eval, w->n_evals, lambda1); gsl_vector_complex_set(eval, w->n_evals + 1, lambda2); w->n_evals += 2; w->n_iter = 0; N -= 2; m = gsl_matrix_submatrix(&m.matrix, 0, 0, N, N); } else if (q == 1) { /* the first matrix element is an eigenvalue */ GSL_SET_COMPLEX(&lambda1, gsl_matrix_get(&m.matrix, 0, 0), 0.0); gsl_vector_complex_set(eval, w->n_evals, lambda1); w->n_evals += 1; w->n_iter = 0; --N; m = gsl_matrix_submatrix(&m.matrix, 1, 1, N, N); } else if (q == 2) { gsl_matrix_view v; /* the upper left 2-by-2 block is an eigenvalue system */ v = gsl_matrix_submatrix(&m.matrix, 0, 0, 2, 2); francis_schur_standardize(&v.matrix, &lambda1, &lambda2, w); gsl_vector_complex_set(eval, w->n_evals, lambda1); gsl_vector_complex_set(eval, w->n_evals + 1, lambda2); w->n_evals += 2; w->n_iter = 0; N -= 2; m = gsl_matrix_submatrix(&m.matrix, 2, 2, N, N); } else { gsl_matrix_view v; /* * There is a zero element on the subdiagonal somewhere * in the middle of the matrix - we can now operate * separately on the two submatrices split by this * element. q is the row index of the zero element. */ /* operate on lower right (N - q)-by-(N - q) block first */ v = gsl_matrix_submatrix(&m.matrix, q, q, N - q, N - q); francis_schur_decomp(&v.matrix, eval, w); /* operate on upper left q-by-q block */ v = gsl_matrix_submatrix(&m.matrix, 0, 0, q, q); francis_schur_decomp(&v.matrix, eval, w); N = 0; } } /* handle special cases of N = 1 or 2 */ if (N == 1) { GSL_SET_COMPLEX(&lambda1, gsl_matrix_get(&m.matrix, 0, 0), 0.0); gsl_vector_complex_set(eval, w->n_evals, lambda1); w->n_evals += 1; w->n_iter = 0; } else if (N == 2) { francis_schur_standardize(&m.matrix, &lambda1, &lambda2, w); gsl_vector_complex_set(eval, w->n_evals, lambda1); gsl_vector_complex_set(eval, w->n_evals + 1, lambda2); w->n_evals += 2; w->n_iter = 0; } } /* francis_schur_decomp() */ /* francis_qrstep() Perform a Francis QR step. See Golub & Van Loan, "Matrix Computations" (3rd ed), algorithm 7.5.1 Inputs: H - upper Hessenberg matrix w - workspace Notes: The matrix H must be "reduced", ie: have no tiny subdiagonal elements. When computing the first householder reflection, we divide by H_{21} so it is necessary that this element is not zero. When a subdiagonal element becomes negligible, the calling function should call this routine with the submatrices split by that element, so that we don't divide by zeros. */ static inline int francis_qrstep(gsl_matrix * H, gsl_eigen_francis_workspace * w) { const size_t N = H->size1; size_t i; /* looping */ gsl_matrix_view m; double tau_i; /* householder coefficient */ double dat[3]; /* householder vector */ double scale; /* scale factor to avoid overflow */ gsl_vector_view v2, v3; size_t q, r; size_t top = 0; /* location of H in original matrix */ double s, disc; double h_nn, /* H(n,n) */ h_nm1nm1, /* H(n-1,n-1) */ h_cross, /* H(n,n-1) * H(n-1,n) */ h_tmp1, h_tmp2; v2 = gsl_vector_view_array(dat, 2); v3 = gsl_vector_view_array(dat, 3); if ((w->n_iter % 10) == 0) { /* * exceptional shifts: we have gone 10 iterations * without finding a new eigenvalue, try a new choice of shifts. * See LAPACK routine DLAHQR */ s = fabs(gsl_matrix_get(H, N - 1, N - 2)) + fabs(gsl_matrix_get(H, N - 2, N - 3)); h_nn = gsl_matrix_get(H, N - 1, N - 1) + GSL_FRANCIS_COEFF1 * s; h_nm1nm1 = h_nn; h_cross = GSL_FRANCIS_COEFF2 * s * s; } else { /* * normal shifts - compute Rayleigh quotient and use * Wilkinson shift if possible */ h_nn = gsl_matrix_get(H, N - 1, N - 1); h_nm1nm1 = gsl_matrix_get(H, N - 2, N - 2); h_cross = gsl_matrix_get(H, N - 1, N - 2) * gsl_matrix_get(H, N - 2, N - 1); disc = 0.5 * (h_nm1nm1 - h_nn); disc = disc * disc + h_cross; if (disc > 0.0) { double ave; /* real roots - use Wilkinson's shift twice */ disc = sqrt(disc); ave = 0.5 * (h_nm1nm1 + h_nn); if (fabs(h_nm1nm1) - fabs(h_nn) > 0.0) { h_nm1nm1 = h_nm1nm1 * h_nn - h_cross; h_nn = h_nm1nm1 / (disc * GSL_SIGN(ave) + ave); } else { h_nn = disc * GSL_SIGN(ave) + ave; } h_nm1nm1 = h_nn; h_cross = 0.0; } } h_tmp1 = h_nm1nm1 - gsl_matrix_get(H, 0, 0); h_tmp2 = h_nn - gsl_matrix_get(H, 0, 0); /* * These formulas are equivalent to those in Golub & Van Loan * for the normal shift case - the terms have been rearranged * to reduce possible roundoff error when subdiagonal elements * are small */ dat[0] = (h_tmp1*h_tmp2 - h_cross) / gsl_matrix_get(H, 1, 0) + gsl_matrix_get(H, 0, 1); dat[1] = gsl_matrix_get(H, 1, 1) - gsl_matrix_get(H, 0, 0) - h_tmp1 - h_tmp2; dat[2] = gsl_matrix_get(H, 2, 1); scale = fabs(dat[0]) + fabs(dat[1]) + fabs(dat[2]); if (scale != 0.0) { /* scale to prevent overflow or underflow */ dat[0] /= scale; dat[1] /= scale; dat[2] /= scale; } if (w->Z || w->compute_t) { /* * get absolute indices of this (sub)matrix relative to the * original Hessenberg matrix */ top = francis_get_submatrix(w->H, H); } for (i = 0; i < N - 2; ++i) { tau_i = gsl_linalg_householder_transform(&v3.vector); if (tau_i != 0.0) { /* q = max(1, i - 1) */ q = (1 > ((int)i - 1)) ? 0 : (i - 1); /* r = min(i + 3, N - 1) */ r = ((i + 3) < (N - 1)) ? (i + 3) : (N - 1); if (w->compute_t) { /* * We are computing the Schur form T, so we * need to transform the whole matrix H * * H -> P_k^t H P_k * * where P_k is the current Householder matrix */ /* apply left householder matrix (I - tau_i v v') to H */ m = gsl_matrix_submatrix(w->H, top + i, top + q, 3, w->size - top - q); gsl_linalg_householder_hm(tau_i, &v3.vector, &m.matrix); /* apply right householder matrix (I - tau_i v v') to H */ m = gsl_matrix_submatrix(w->H, 0, top + i, top + r + 1, 3); gsl_linalg_householder_mh(tau_i, &v3.vector, &m.matrix); } else { /* * We are not computing the Schur form T, so we * only need to transform the active block */ /* apply left householder matrix (I - tau_i v v') to H */ m = gsl_matrix_submatrix(H, i, q, 3, N - q); gsl_linalg_householder_hm(tau_i, &v3.vector, &m.matrix); /* apply right householder matrix (I - tau_i v v') to H */ m = gsl_matrix_submatrix(H, 0, i, r + 1, 3); gsl_linalg_householder_mh(tau_i, &v3.vector, &m.matrix); } if (w->Z) { /* accumulate the similarity transformation into Z */ m = gsl_matrix_submatrix(w->Z, 0, top + i, w->size, 3); gsl_linalg_householder_mh(tau_i, &v3.vector, &m.matrix); } } /* if (tau_i != 0.0) */ dat[0] = gsl_matrix_get(H, i + 1, i); dat[1] = gsl_matrix_get(H, i + 2, i); if (i < (N - 3)) { dat[2] = gsl_matrix_get(H, i + 3, i); } scale = fabs(dat[0]) + fabs(dat[1]) + fabs(dat[2]); if (scale != 0.0) { /* scale to prevent overflow or underflow */ dat[0] /= scale; dat[1] /= scale; dat[2] /= scale; } } /* for (i = 0; i < N - 2; ++i) */ scale = fabs(dat[0]) + fabs(dat[1]); if (scale != 0.0) { /* scale to prevent overflow or underflow */ dat[0] /= scale; dat[1] /= scale; } tau_i = gsl_linalg_householder_transform(&v2.vector); if (w->compute_t) { m = gsl_matrix_submatrix(w->H, top + N - 2, top + N - 3, 2, w->size - top - N + 3); gsl_linalg_householder_hm(tau_i, &v2.vector, &m.matrix); m = gsl_matrix_submatrix(w->H, 0, top + N - 2, top + N, 2); gsl_linalg_householder_mh(tau_i, &v2.vector, &m.matrix); } else { m = gsl_matrix_submatrix(H, N - 2, N - 3, 2, 3); gsl_linalg_householder_hm(tau_i, &v2.vector, &m.matrix); m = gsl_matrix_submatrix(H, 0, N - 2, N, 2); gsl_linalg_householder_mh(tau_i, &v2.vector, &m.matrix); } if (w->Z) { /* accumulate transformation into Z */ m = gsl_matrix_submatrix(w->Z, 0, top + N - 2, w->size, 2); gsl_linalg_householder_mh(tau_i, &v2.vector, &m.matrix); } return GSL_SUCCESS; } /* francis_qrstep() */ /* francis_search_subdiag_small_elements() Search for a small subdiagonal element starting from the bottom of a matrix A. A small element is one that satisfies: |A_{i,i-1}| <= eps * (|A_{i,i}| + |A_{i-1,i-1}|) Inputs: A - matrix (must be at least 3-by-3) Return: row index of small subdiagonal element or 0 if not found Notes: the first small element that is found (starting from bottom) is set to zero */ static inline size_t francis_search_subdiag_small_elements(gsl_matrix * A) { const size_t N = A->size1; size_t i; double dpel = gsl_matrix_get(A, N - 2, N - 2); for (i = N - 1; i > 0; --i) { double sel = gsl_matrix_get(A, i, i - 1); double del = gsl_matrix_get(A, i, i); if ((sel == 0.0) || (fabs(sel) < GSL_DBL_EPSILON * (fabs(del) + fabs(dpel)))) { gsl_matrix_set(A, i, i - 1, 0.0); return (i); } dpel = del; } return (0); } /* francis_search_subdiag_small_elements() */ /* francis_schur_standardize() Convert a 2-by-2 diagonal block in the Schur form to standard form and update the rest of T and Z matrices if required. Inputs: A - 2-by-2 matrix eval1 - where to store eigenvalue 1 eval2 - where to store eigenvalue 2 w - francis workspace */ static inline void francis_schur_standardize(gsl_matrix *A, gsl_complex *eval1, gsl_complex *eval2, gsl_eigen_francis_workspace *w) { const size_t N = w->size; double cs, sn; size_t top; /* * figure out where the submatrix A resides in the * original matrix H */ top = francis_get_submatrix(w->H, A); /* convert 2-by-2 block to standard form */ francis_standard_form(A, &cs, &sn); /* set eigenvalues */ GSL_SET_REAL(eval1, gsl_matrix_get(A, 0, 0)); GSL_SET_REAL(eval2, gsl_matrix_get(A, 1, 1)); if (gsl_matrix_get(A, 1, 0) == 0.0) { GSL_SET_IMAG(eval1, 0.0); GSL_SET_IMAG(eval2, 0.0); } else { double tmp = sqrt(fabs(gsl_matrix_get(A, 0, 1)) * fabs(gsl_matrix_get(A, 1, 0))); GSL_SET_IMAG(eval1, tmp); GSL_SET_IMAG(eval2, -tmp); } if (w->compute_t) { gsl_vector_view xv, yv; /* * The above call to francis_standard_form transformed a 2-by-2 block * of T into upper triangular form via the transformation * * U = [ CS -SN ] * [ SN CS ] * * The original matrix T was * * T = [ T_{11} | T_{12} | T_{13} ] * [ 0* | A | T_{23} ] * [ 0 | 0* | T_{33} ] * * where 0* indicates all zeros except for possibly * one subdiagonal element next to A. * * After francis_standard_form, T looks like this: * * T = [ T_{11} | T_{12} | T_{13} ] * [ 0* | U^t A U | T_{23} ] * [ 0 | 0* | T_{33} ] * * since only the 2-by-2 block of A was changed. However, * in order to be able to back transform T at the end, * we need to apply the U transformation to the rest * of the matrix T since there is no way to apply a * similarity transformation to T and change only the * middle 2-by-2 block. In other words, let * * M = [ I 0 0 ] * [ 0 U 0 ] * [ 0 0 I ] * * and compute * * M^t T M = [ T_{11} | T_{12} U | T_{13} ] * [ U^t 0* | U^t A U | U^t T_{23} ] * [ 0 | 0* U | T_{33} ] * * So basically we need to apply the transformation U * to the i x 2 matrix T_{12} and the 2 x (n - i + 2) * matrix T_{23}, where i is the index of the top of A * in T. * * The BLAS routine drot() is suited for this. */ if (top < (N - 2)) { /* transform the 2 rows of T_{23} */ xv = gsl_matrix_subrow(w->H, top, top + 2, N - top - 2); yv = gsl_matrix_subrow(w->H, top + 1, top + 2, N - top - 2); gsl_blas_drot(&xv.vector, &yv.vector, cs, sn); } if (top > 0) { /* transform the 2 columns of T_{12} */ xv = gsl_matrix_subcolumn(w->H, top, 0, top); yv = gsl_matrix_subcolumn(w->H, top + 1, 0, top); gsl_blas_drot(&xv.vector, &yv.vector, cs, sn); } } /* if (w->compute_t) */ if (w->Z) { gsl_vector_view xv, yv; /* * Accumulate the transformation in Z. Here, Z -> Z * M * * So: * * Z -> [ Z_{11} | Z_{12} U | Z_{13} ] * [ Z_{21} | Z_{22} U | Z_{23} ] * [ Z_{31} | Z_{32} U | Z_{33} ] * * So we just need to apply drot() to the 2 columns * starting at index 'top' */ xv = gsl_matrix_column(w->Z, top); yv = gsl_matrix_column(w->Z, top + 1); gsl_blas_drot(&xv.vector, &yv.vector, cs, sn); } /* if (w->Z) */ } /* francis_schur_standardize() */ /* francis_get_submatrix() B is a submatrix of A. The goal of this function is to compute the indices in A of where the matrix B resides */ static inline size_t francis_get_submatrix(gsl_matrix *A, gsl_matrix *B) { size_t diff; double ratio; size_t top; diff = (size_t) (B->data - A->data); ratio = (double)diff / ((double) (A->tda + 1)); top = (size_t) floor(ratio); return top; } /* francis_get_submatrix() */ /* francis_standard_form() Compute the Schur factorization of a real 2-by-2 matrix in standard form: [ A B ] = [ CS -SN ] [ T11 T12 ] [ CS SN ] [ C D ] [ SN CS ] [ T21 T22 ] [-SN CS ] where either: 1) T21 = 0 so that T11 and T22 are real eigenvalues of the matrix, or 2) T11 = T22 and T21*T12 < 0, so that T11 +/- sqrt(|T21*T12|) are complex conjugate eigenvalues Inputs: A - 2-by-2 matrix cs - where to store cosine parameter of rotation matrix sn - where to store sine parameter of rotation matrix Notes: 1) based on LAPACK routine DLANV2 2) On output, A is modified to contain the matrix in standard form */ static void francis_standard_form(gsl_matrix *A, double *cs, double *sn) { double a, b, c, d; /* input matrix values */ double tmp; double p, z; double bcmax, bcmis, scale; double tau, sigma; double cs1, sn1; double aa, bb, cc, dd; double sab, sac; a = gsl_matrix_get(A, 0, 0); b = gsl_matrix_get(A, 0, 1); c = gsl_matrix_get(A, 1, 0); d = gsl_matrix_get(A, 1, 1); if (c == 0.0) { /* * matrix is already upper triangular - set rotation matrix * to the identity */ *cs = 1.0; *sn = 0.0; } else if (b == 0.0) { /* swap rows and columns to make it upper triangular */ *cs = 0.0; *sn = 1.0; tmp = d; d = a; a = tmp; b = -c; c = 0.0; } else if (((a - d) == 0.0) && (GSL_SIGN(b) != GSL_SIGN(c))) { /* the matrix has complex eigenvalues with a == d */ *cs = 1.0; *sn = 0.0; } else { tmp = a - d; p = 0.5 * tmp; bcmax = GSL_MAX(fabs(b), fabs(c)); bcmis = GSL_MIN(fabs(b), fabs(c)) * GSL_SIGN(b) * GSL_SIGN(c); scale = GSL_MAX(fabs(p), bcmax); z = (p / scale) * p + (bcmax / scale) * bcmis; if (z >= 4.0 * GSL_DBL_EPSILON) { /* real eigenvalues, compute a and d */ z = p + GSL_SIGN(p) * fabs(sqrt(scale) * sqrt(z)); a = d + z; d -= (bcmax / z) * bcmis; /* compute b and the rotation matrix */ tau = gsl_hypot(c, z); *cs = z / tau; *sn = c / tau; b -= c; c = 0.0; } else { /* * complex eigenvalues, or real (almost) equal eigenvalues - * make diagonal elements equal */ sigma = b + c; tau = gsl_hypot(sigma, tmp); *cs = sqrt(0.5 * (1.0 + fabs(sigma) / tau)); *sn = -(p / (tau * (*cs))) * GSL_SIGN(sigma); /* * Compute [ AA BB ] = [ A B ] [ CS -SN ] * [ CC DD ] [ C D ] [ SN CS ] */ aa = a * (*cs) + b * (*sn); bb = -a * (*sn) + b * (*cs); cc = c * (*cs) + d * (*sn); dd = -c * (*sn) + d * (*cs); /* * Compute [ A B ] = [ CS SN ] [ AA BB ] * [ C D ] [-SN CS ] [ CC DD ] */ a = aa * (*cs) + cc * (*sn); b = bb * (*cs) + dd * (*sn); c = -aa * (*sn) + cc * (*cs); d = -bb * (*sn) + dd * (*cs); tmp = 0.5 * (a + d); a = d = tmp; if (c != 0.0) { if (b != 0.0) { if (GSL_SIGN(b) == GSL_SIGN(c)) { /* * real eigenvalues: reduce to upper triangular * form */ sab = sqrt(fabs(b)); sac = sqrt(fabs(c)); p = GSL_SIGN(c) * fabs(sab * sac); tau = 1.0 / sqrt(fabs(b + c)); a = tmp + p; d = tmp - p; b -= c; c = 0.0; cs1 = sab * tau; sn1 = sac * tau; tmp = (*cs) * cs1 - (*sn) * sn1; *sn = (*cs) * sn1 + (*sn) * cs1; *cs = tmp; } } else { b = -c; c = 0.0; tmp = *cs; *cs = -(*sn); *sn = tmp; } } } } /* set new matrix elements */ gsl_matrix_set(A, 0, 0, a); gsl_matrix_set(A, 0, 1, b); gsl_matrix_set(A, 1, 0, c); gsl_matrix_set(A, 1, 1, d); } /* francis_standard_form() */
{ "alphanum_fraction": 0.5264938756, "avg_line_length": 28.2003816794, "ext": "c", "hexsha": "96f9180e92ab8e86b829873b18b23a229c21ed65", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/eigen/francis.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/eigen/francis.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/eigen/francis.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": 8593, "size": 29554 }
/* specfunc/dilog.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_clausen.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_sf_dilog.h> /* Evaluate series for real dilog(x) * Sum[ x^k / k^2, {k,1,Infinity}] * * Converges rapidly for |x| < 1/2. */ static int dilog_series_1(const double x, gsl_sf_result * result) { const int kmax = 1000; double sum = x; double term = x; int k; for(k=2; k<kmax; k++) { const double rk = (k-1.0)/k; term *= x; term *= rk*rk; sum += term; if(fabs(term/sum) < GSL_DBL_EPSILON) break; } result->val = sum; result->err = 2.0 * fabs(term); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); if(k == kmax) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } /* Compute the associated series * * sum_{k=1}{infty} r^k / (k^2 (k+1)) * * This is a series which appears in the one-step accelerated * method, which splits out one elementary function from the * full definition of Li_2(x). See below. */ static int series_2(double r, gsl_sf_result * result) { static const int kmax = 100; double rk = r; double sum = 0.5 * r; int k; for(k=2; k<10; k++) { double ds; rk *= r; ds = rk/(k*k*(k+1.0)); sum += ds; } for(; k<kmax; k++) { double ds; rk *= r; ds = rk/(k*k*(k+1.0)); sum += ds; if(fabs(ds/sum) < 0.5*GSL_DBL_EPSILON) break; } result->val = sum; result->err = 2.0 * kmax * GSL_DBL_EPSILON * fabs(sum); return GSL_SUCCESS; } /* Compute Li_2(x) using the accelerated series representation. * * Li_2(x) = 1 + (1-x)ln(1-x)/x + series_2(x) * * assumes: -1 < x < 1 */ static int dilog_series_2(double x, gsl_sf_result * result) { const int stat_s3 = series_2(x, result); double t; if(x > 0.01) t = (1.0 - x) * log(1.0-x) / x; else { static const double c3 = 1.0/3.0; static const double c4 = 1.0/4.0; static const double c5 = 1.0/5.0; static const double c6 = 1.0/6.0; static const double c7 = 1.0/7.0; static const double c8 = 1.0/8.0; const double t68 = c6 + x*(c7 + x*c8); const double t38 = c3 + x *(c4 + x *(c5 + x * t68)); t = (x - 1.0) * (1.0 + x*(0.5 + x*t38)); } result->val += 1.0 + t; result->err += 2.0 * GSL_DBL_EPSILON * fabs(t); return stat_s3; } /* Calculates Li_2(x) for real x. Assumes x >= 0.0. */ static int dilog_xge0(const double x, gsl_sf_result * result) { if(x > 2.0) { gsl_sf_result ser; const int stat_ser = dilog_series_2(1.0/x, &ser); const double log_x = log(x); const double t1 = M_PI*M_PI/3.0; const double t2 = ser.val; const double t3 = 0.5*log_x*log_x; result->val = t1 - t2 - t3; result->err = GSL_DBL_EPSILON * fabs(log_x) + ser.err; result->err += GSL_DBL_EPSILON * (fabs(t1) + fabs(t2) + fabs(t3)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_ser; } else if(x > 1.01) { gsl_sf_result ser; const int stat_ser = dilog_series_2(1.0 - 1.0/x, &ser); const double log_x = log(x); const double log_term = log_x * (log(1.0-1.0/x) + 0.5*log_x); const double t1 = M_PI*M_PI/6.0; const double t2 = ser.val; const double t3 = log_term; result->val = t1 + t2 - t3; result->err = GSL_DBL_EPSILON * fabs(log_x) + ser.err; result->err += GSL_DBL_EPSILON * (fabs(t1) + fabs(t2) + fabs(t3)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_ser; } else if(x > 1.0) { /* series around x = 1.0 */ const double eps = x - 1.0; const double lne = log(eps); const double c0 = M_PI*M_PI/6.0; const double c1 = 1.0 - lne; const double c2 = -(1.0 - 2.0*lne)/4.0; const double c3 = (1.0 - 3.0*lne)/9.0; const double c4 = -(1.0 - 4.0*lne)/16.0; const double c5 = (1.0 - 5.0*lne)/25.0; const double c6 = -(1.0 - 6.0*lne)/36.0; const double c7 = (1.0 - 7.0*lne)/49.0; const double c8 = -(1.0 - 8.0*lne)/64.0; result->val = c0+eps*(c1+eps*(c2+eps*(c3+eps*(c4+eps*(c5+eps*(c6+eps*(c7+eps*c8))))))); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x == 1.0) { result->val = M_PI*M_PI/6.0; result->err = 2.0 * GSL_DBL_EPSILON * M_PI*M_PI/6.0; return GSL_SUCCESS; } else if(x > 0.5) { gsl_sf_result ser; const int stat_ser = dilog_series_2(1.0-x, &ser); const double log_x = log(x); const double t1 = M_PI*M_PI/6.0; const double t2 = ser.val; const double t3 = log_x*log(1.0-x); result->val = t1 - t2 - t3; result->err = GSL_DBL_EPSILON * fabs(log_x) + ser.err; result->err += GSL_DBL_EPSILON * (fabs(t1) + fabs(t2) + fabs(t3)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_ser; } else if(x > 0.25) { return dilog_series_2(x, result); } else if(x > 0.0) { return dilog_series_1(x, result); } else { /* x == 0.0 */ result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } } /* Evaluate the series representation for Li2(z): * * Li2(z) = Sum[ |z|^k / k^2 Exp[i k arg(z)], {k,1,Infinity}] * |z| = r * arg(z) = theta * * Assumes 0 < r < 1. * It is used only for small r. */ static int dilogc_series_1( const double r, const double x, const double y, gsl_sf_result * real_result, gsl_sf_result * imag_result ) { const double cos_theta = x/r; const double sin_theta = y/r; const double alpha = 1.0 - cos_theta; const double beta = sin_theta; double ck = cos_theta; double sk = sin_theta; double rk = r; double real_sum = r*ck; double imag_sum = r*sk; const int kmax = 50 + (int)(22.0/(-log(r))); /* tuned for double-precision */ int k; for(k=2; k<kmax; k++) { double dr, di; double ck_tmp = ck; ck = ck - (alpha*ck + beta*sk); sk = sk - (alpha*sk - beta*ck_tmp); rk *= r; dr = rk/((double)k*k) * ck; di = rk/((double)k*k) * sk; real_sum += dr; imag_sum += di; if(fabs((dr*dr + di*di)/(real_sum*real_sum + imag_sum*imag_sum)) < GSL_DBL_EPSILON*GSL_DBL_EPSILON) break; } real_result->val = real_sum; real_result->err = 2.0 * kmax * GSL_DBL_EPSILON * fabs(real_sum); imag_result->val = imag_sum; imag_result->err = 2.0 * kmax * GSL_DBL_EPSILON * fabs(imag_sum); return GSL_SUCCESS; } /* Compute * * sum_{k=1}{infty} z^k / (k^2 (k+1)) * * This is a series which appears in the one-step accelerated * method, which splits out one elementary function from the * full definition of Li_2. */ static int series_2_c( double r, double x, double y, gsl_sf_result * sum_re, gsl_sf_result * sum_im ) { const double cos_theta = x/r; const double sin_theta = y/r; const double alpha = 1.0 - cos_theta; const double beta = sin_theta; double ck = cos_theta; double sk = sin_theta; double rk = r; double real_sum = 0.5 * r*ck; double imag_sum = 0.5 * r*sk; const int kmax = 30 + (int)(18.0/(-log(r))); /* tuned for double-precision */ int k; for(k=2; k<kmax; k++) { double dr, di; const double ck_tmp = ck; ck = ck - (alpha*ck + beta*sk); sk = sk - (alpha*sk - beta*ck_tmp); rk *= r; dr = rk/((double)k*k*(k+1.0)) * ck; di = rk/((double)k*k*(k+1.0)) * sk; real_sum += dr; imag_sum += di; if(fabs((dr*dr + di*di)/(real_sum*real_sum + imag_sum*imag_sum)) < GSL_DBL_EPSILON*GSL_DBL_EPSILON) break; } sum_re->val = real_sum; sum_re->err = 2.0 * kmax * GSL_DBL_EPSILON * fabs(real_sum); sum_im->val = imag_sum; sum_im->err = 2.0 * kmax * GSL_DBL_EPSILON * fabs(imag_sum); return GSL_SUCCESS; } /* Compute Li_2(z) using the one-step accelerated series. * * Li_2(z) = 1 + (1-z)ln(1-z)/z + series_2_c(z) * * z = r exp(i theta) * assumes: r < 1 * assumes: r > epsilon, so that we take no special care with log(1-z) */ static int dilogc_series_2( const double r, const double x, const double y, gsl_sf_result * real_dl, gsl_sf_result * imag_dl ) { if(r == 0.0) { real_dl->val = 0.0; imag_dl->val = 0.0; real_dl->err = 0.0; imag_dl->err = 0.0; return GSL_SUCCESS; } else { gsl_sf_result sum_re; gsl_sf_result sum_im; const int stat_s3 = series_2_c(r, x, y, &sum_re, &sum_im); /* t = ln(1-z)/z */ gsl_sf_result ln_omz_r; gsl_sf_result ln_omz_theta; const int stat_log = gsl_sf_complex_log_e(1.0-x, -y, &ln_omz_r, &ln_omz_theta); const double t_x = ( ln_omz_r.val * x + ln_omz_theta.val * y)/(r*r); const double t_y = (-ln_omz_r.val * y + ln_omz_theta.val * x)/(r*r); /* r = (1-z) ln(1-z)/z */ const double r_x = (1.0 - x) * t_x + y * t_y; const double r_y = (1.0 - x) * t_y - y * t_x; real_dl->val = sum_re.val + r_x + 1.0; imag_dl->val = sum_im.val + r_y; real_dl->err = sum_re.err + 2.0*GSL_DBL_EPSILON*(fabs(real_dl->val) + fabs(r_x)); imag_dl->err = sum_im.err + 2.0*GSL_DBL_EPSILON*(fabs(imag_dl->val) + fabs(r_y)); return GSL_ERROR_SELECT_2(stat_s3, stat_log); } } /* Evaluate a series for Li_2(z) when |z| is near 1. * This is uniformly good away from z=1. * * Li_2(z) = Sum[ a^n/n! H_n(theta), {n, 0, Infinity}] * * where * H_n(theta) = Sum[ e^(i m theta) m^n / m^2, {m, 1, Infinity}] * a = ln(r) * * H_0(t) = Gl_2(t) + i Cl_2(t) * H_1(t) = 1/2 ln(2(1-c)) + I atan2(-s, 1-c) * H_2(t) = -1/2 + I/2 s/(1-c) * H_3(t) = -1/2 /(1-c) * H_4(t) = -I/2 s/(1-c)^2 * H_5(t) = 1/2 (2 + c)/(1-c)^2 * H_6(t) = I/2 s/(1-c)^5 (8(1-c) - s^2 (3 + c)) */ static int dilogc_series_3( const double r, const double x, const double y, gsl_sf_result * real_result, gsl_sf_result * imag_result ) { const double theta = atan2(y, x); const double cos_theta = x/r; const double sin_theta = y/r; const double a = log(r); const double omc = 1.0 - cos_theta; const double omc2 = omc*omc; double H_re[7]; double H_im[7]; double an, nfact; double sum_re, sum_im; gsl_sf_result Him0; int n; H_re[0] = M_PI*M_PI/6.0 + 0.25*(theta*theta - 2.0*M_PI*fabs(theta)); gsl_sf_clausen_e(theta, &Him0); H_im[0] = Him0.val; H_re[1] = -0.5*log(2.0*omc); H_im[1] = -atan2(-sin_theta, omc); H_re[2] = -0.5; H_im[2] = 0.5 * sin_theta/omc; H_re[3] = -0.5/omc; H_im[3] = 0.0; H_re[4] = 0.0; H_im[4] = -0.5*sin_theta/omc2; H_re[5] = 0.5 * (2.0 + cos_theta)/omc2; H_im[5] = 0.0; H_re[6] = 0.0; H_im[6] = 0.5 * sin_theta/(omc2*omc2*omc) * (8.0*omc - sin_theta*sin_theta*(3.0 + cos_theta)); sum_re = H_re[0]; sum_im = H_im[0]; an = 1.0; nfact = 1.0; for(n=1; n<=6; n++) { double t; an *= a; nfact *= n; t = an/nfact; sum_re += t * H_re[n]; sum_im += t * H_im[n]; } real_result->val = sum_re; real_result->err = 2.0 * 6.0 * GSL_DBL_EPSILON * fabs(sum_re) + fabs(an/nfact); imag_result->val = sum_im; imag_result->err = 2.0 * 6.0 * GSL_DBL_EPSILON * fabs(sum_im) + Him0.err + fabs(an/nfact); return GSL_SUCCESS; } /* Calculate complex dilogarithm Li_2(z) in the fundamental region, * which we take to be the intersection of the unit disk with the * half-space x < MAGIC_SPLIT_VALUE. It turns out that 0.732 is a * nice choice for MAGIC_SPLIT_VALUE since then points mapped out * of the x > MAGIC_SPLIT_VALUE region and into another part of the * unit disk are bounded in radius by MAGIC_SPLIT_VALUE itself. * * If |z| < 0.98 we use a direct series summation. Otherwise z is very * near the unit circle, and the series_2 expansion is used; see above. * Because the fundamental region is bounded away from z = 1, this * works well. */ static int dilogc_fundamental(double r, double x, double y, gsl_sf_result * real_dl, gsl_sf_result * imag_dl) { if(r > 0.98) return dilogc_series_3(r, x, y, real_dl, imag_dl); else if(r > 0.25) return dilogc_series_2(r, x, y, real_dl, imag_dl); else return dilogc_series_1(r, x, y, real_dl, imag_dl); } /* Compute Li_2(z) for z in the unit disk, |z| < 1. If z is outside * the fundamental region, which means that it is too close to z = 1, * then it is reflected into the fundamental region using the identity * * Li2(z) = -Li2(1-z) + zeta(2) - ln(z) ln(1-z). */ static int dilogc_unitdisk(double x, double y, gsl_sf_result * real_dl, gsl_sf_result * imag_dl) { static const double MAGIC_SPLIT_VALUE = 0.732; static const double zeta2 = M_PI*M_PI/6.0; const double r = hypot(x, y); if(x > MAGIC_SPLIT_VALUE) { /* Reflect away from z = 1 if we are too close. The magic value * insures that the reflected value of the radius satisfies the * related inequality r_tmp < MAGIC_SPLIT_VALUE. */ const double x_tmp = 1.0 - x; const double y_tmp = - y; const double r_tmp = hypot(x_tmp, y_tmp); /* const double cos_theta_tmp = x_tmp/r_tmp; */ /* const double sin_theta_tmp = y_tmp/r_tmp; */ gsl_sf_result result_re_tmp; gsl_sf_result result_im_tmp; const int stat_dilog = dilogc_fundamental(r_tmp, x_tmp, y_tmp, &result_re_tmp, &result_im_tmp); const double lnz = log(r); /* log(|z|) */ const double lnomz = log(r_tmp); /* log(|1-z|) */ const double argz = atan2(y, x); /* arg(z) assuming principal branch */ const double argomz = atan2(y_tmp, x_tmp); /* arg(1-z) */ real_dl->val = -result_re_tmp.val + zeta2 - lnz*lnomz + argz*argomz; real_dl->err = result_re_tmp.err; real_dl->err += 2.0 * GSL_DBL_EPSILON * (zeta2 + fabs(lnz*lnomz) + fabs(argz*argomz)); imag_dl->val = -result_im_tmp.val - argz*lnomz - argomz*lnz; imag_dl->err = result_im_tmp.err; imag_dl->err += 2.0 * GSL_DBL_EPSILON * (fabs(argz*lnomz) + fabs(argomz*lnz)); return stat_dilog; } else { return dilogc_fundamental(r, x, y, real_dl, imag_dl); } } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_dilog_e(const double x, gsl_sf_result * result) { if(x >= 0.0) { return dilog_xge0(x, result); } else { gsl_sf_result d1, d2; int stat_d1 = dilog_xge0( -x, &d1); int stat_d2 = dilog_xge0(x*x, &d2); result->val = -d1.val + 0.5 * d2.val; result->err = d1.err + 0.5 * d2.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_d1, stat_d2); } } int gsl_sf_complex_dilog_xy_e( const double x, const double y, gsl_sf_result * real_dl, gsl_sf_result * imag_dl ) { const double zeta2 = M_PI*M_PI/6.0; const double r2 = x*x + y*y; if(y == 0.0) { if(x >= 1.0) { imag_dl->val = -M_PI * log(x); imag_dl->err = 2.0 * GSL_DBL_EPSILON * fabs(imag_dl->val); } else { imag_dl->val = 0.0; imag_dl->err = 0.0; } return gsl_sf_dilog_e(x, real_dl); } else if(fabs(r2 - 1.0) < GSL_DBL_EPSILON) { /* Lewin A.2.4.1 and A.2.4.2 */ const double theta = atan2(y, x); const double term1 = theta*theta/4.0; const double term2 = M_PI*fabs(theta)/2.0; real_dl->val = zeta2 + term1 - term2; real_dl->err = 2.0 * GSL_DBL_EPSILON * (zeta2 + term1 + term2); return gsl_sf_clausen_e(theta, imag_dl); } else if(r2 < 1.0) { return dilogc_unitdisk(x, y, real_dl, imag_dl); } else { /* Reduce argument to unit disk. */ const double r = sqrt(r2); const double x_tmp = x/r2; const double y_tmp = -y/r2; /* const double r_tmp = 1.0/r; */ gsl_sf_result result_re_tmp, result_im_tmp; const int stat_dilog = dilogc_unitdisk(x_tmp, y_tmp, &result_re_tmp, &result_im_tmp); /* Unwind the inversion. * * Li_2(z) + Li_2(1/z) = -zeta(2) - 1/2 ln(-z)^2 */ const double theta = atan2(y, x); const double theta_abs = fabs(theta); const double theta_sgn = ( theta < 0.0 ? -1.0 : 1.0 ); const double ln_minusz_re = log(r); const double ln_minusz_im = theta_sgn * (theta_abs - M_PI); const double lmz2_re = ln_minusz_re*ln_minusz_re - ln_minusz_im*ln_minusz_im; const double lmz2_im = 2.0*ln_minusz_re*ln_minusz_im; real_dl->val = -result_re_tmp.val - 0.5 * lmz2_re - zeta2; real_dl->err = result_re_tmp.err + 2.0*GSL_DBL_EPSILON*(0.5 * fabs(lmz2_re) + zeta2); imag_dl->val = -result_im_tmp.val - 0.5 * lmz2_im; imag_dl->err = result_im_tmp.err + 2.0*GSL_DBL_EPSILON*fabs(lmz2_im); return stat_dilog; } } int gsl_sf_complex_dilog_e( const double r, const double theta, gsl_sf_result * real_dl, gsl_sf_result * imag_dl ) { const double cos_theta = cos(theta); const double sin_theta = sin(theta); const double x = r * cos_theta; const double y = r * sin_theta; return gsl_sf_complex_dilog_xy_e(x, y, real_dl, imag_dl); } int gsl_sf_complex_spence_xy_e( const double x, const double y, gsl_sf_result * real_sp, gsl_sf_result * imag_sp ) { const double oms_x = 1.0 - x; const double oms_y = - y; return gsl_sf_complex_dilog_xy_e(oms_x, oms_y, real_sp, imag_sp); } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_dilog(const double x) { EVAL_RESULT(gsl_sf_dilog_e(x, &result)); }
{ "alphanum_fraction": 0.6131176601, "avg_line_length": 27.2277526395, "ext": "c", "hexsha": "15586ef0d384ec5b3adf88dfe007c9ed5758e034", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/dilog.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/dilog.c", "max_line_length": 110, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/dilog.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": 6513, "size": 18052 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" #include "error_cblas_l2.h" void cblas_chemv (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY) { #define BASE float #include "source_hemv.h" #undef BASE }
{ "alphanum_fraction": 0.6699029126, "avg_line_length": 25.75, "ext": "c", "hexsha": "a501605a3d9242abf174ed76a42ed94957f617ae", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/cblas/chemv.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/cblas/chemv.c", "max_line_length": 74, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/cblas/chemv.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 122, "size": 412 }
#pragma once #include <cassert> #include <gsl/span> #include <iostream> #include <optixu/optixpp_namespace.h> namespace DeepestScatter { template<typename T> class BufferBind { public: explicit BufferBind(optix::Buffer buffer, unsigned int level = 0); ~BufferBind(); gsl::span<T>& getData(); const T& operator [](size_t pos) const; T& operator [](size_t pos); private: optix::Buffer buffer; unsigned int level; gsl::span<T> optixOwned; }; template<typename T> BufferBind<T>::BufferBind(optix::Buffer buffer, unsigned int level): buffer(buffer), level(level) { assert(sizeof(T) == buffer->getElementSize()); auto rawArray = static_cast<T*>(buffer->map(level)); RTsize totalSize = 1; RTsize sizes[3]; buffer->getMipLevelSize(level, sizes[0], sizes[1], sizes[2]); for (unsigned int i = 0; i < buffer->getDimensionality(); i++) { totalSize *= sizes[i]; } optixOwned = gsl::make_span(rawArray, totalSize); } template <typename T> BufferBind<T>::~BufferBind() { buffer->unmap(level); } template <typename T> gsl::span<T>& BufferBind<T>::getData() { return optixOwned; } template <typename T> inline const T& BufferBind<T>::operator[](size_t pos) const { return optixOwned[pos]; } template <typename T> inline T& BufferBind<T>::operator[](size_t pos) { return optixOwned[pos]; } }
{ "alphanum_fraction": 0.5748129676, "avg_line_length": 21.1052631579, "ext": "h", "hexsha": "0885fe821c7aabc032cfff29f4cbb698bb23bcd9", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-03-17T02:10:36.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-07T01:20:07.000Z", "max_forks_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "marsermd/DeepestScatter", "max_forks_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/BufferBind.h", "max_issues_count": 18, "max_issues_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:39:23.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "marsermd/DeepestScatter", "max_issues_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/BufferBind.h", "max_line_length": 74, "max_stars_count": 13, "max_stars_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "marsermd/DeepestScatter", "max_stars_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/BufferBind.h", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:15:14.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-02T05:39:28.000Z", "num_tokens": 394, "size": 1604 }
/* multifit_nlinear/qr.c * * Copyright (C) 2015, 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 handles the solution of the linear least squares * system: * * [ J~ ] p~ = - [ f ] * [ sqrt(mu)*D~ ] [ 0 ] * * using a QR approach. Quantities are scaled according to: * * J~ = J S * D~ = D S * p~ = S^{-1} p * * where S is a diagonal matrix and S_jj = || J_j || and J_j is column * j of the Jacobian. This balancing transformation seems to be more * numerically stable for some Jacobians. */ #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> #include "common.c" #include "qrsolv.c" typedef struct { size_t p; gsl_matrix *QR; /* QR factorization of J */ gsl_vector *tau_Q; /* Householder scalars for Q */ gsl_matrix *T; /* workspace matrix for qrsolv, p-by-p */ gsl_permutation *perm; /* permutation matrix */ size_t rank; /* rank of J */ gsl_vector *residual; /* residual of LS problem [ J; sqrt(mu) D ] p = - [ f; 0 ] */ gsl_vector *qtf; /* Q^T f */ gsl_vector *workn; /* workspace, length n */ gsl_vector *workp; /* workspace, length p */ gsl_vector *work3p; /* workspace, length 3*p */ double mu; /* LM parameter */ } qr_state_t; static int qr_init(const void * vtrust_state, void * vstate); static int qr_presolve(const double mu, const void * vtrust_state, void * vstate); static int qr_solve(const gsl_vector * f, gsl_vector *x, const void * vtrust_state, void *vstate); static int qr_rcond(double * rcond, void * vstate); static void * qr_alloc (const size_t n, const size_t p) { qr_state_t *state; (void)n; state = calloc(1, sizeof(qr_state_t)); if (state == NULL) { GSL_ERROR_NULL ("failed to allocate qr state", GSL_ENOMEM); } state->QR = gsl_matrix_alloc(n, p); if (state->QR == NULL) { GSL_ERROR_NULL ("failed to allocate space for QR", GSL_ENOMEM); } state->tau_Q = gsl_vector_alloc(p); if (state->tau_Q == NULL) { GSL_ERROR_NULL ("failed to allocate space for tau_Q", GSL_ENOMEM); } state->T = gsl_matrix_alloc(p, p); if (state->T == NULL) { GSL_ERROR_NULL ("failed to allocate space for T", GSL_ENOMEM); } state->qtf = gsl_vector_alloc(n); if (state->qtf == NULL) { GSL_ERROR_NULL ("failed to allocate space for qtf", GSL_ENOMEM); } state->residual = gsl_vector_alloc(n); if (state->residual == NULL) { GSL_ERROR_NULL ("failed to allocate space for residual", GSL_ENOMEM); } state->perm = gsl_permutation_calloc(p); if (state->perm == NULL) { GSL_ERROR_NULL ("failed to allocate space for perm", GSL_ENOMEM); } state->workn = gsl_vector_alloc(n); if (state->workn == NULL) { GSL_ERROR_NULL ("failed to allocate space for workn", GSL_ENOMEM); } state->workp = gsl_vector_alloc(p); if (state->workp == NULL) { GSL_ERROR_NULL ("failed to allocate space for workp", GSL_ENOMEM); } state->work3p = gsl_vector_alloc(3 * p); if (state->work3p == NULL) { GSL_ERROR_NULL ("failed to allocate space for work3p", GSL_ENOMEM); } state->p = p; state->mu = 0.0; state->rank = 0; return state; } static void qr_free(void *vstate) { qr_state_t *state = (qr_state_t *) vstate; if (state->QR) gsl_matrix_free(state->QR); if (state->tau_Q) gsl_vector_free(state->tau_Q); if (state->T) gsl_matrix_free(state->T); if (state->qtf) gsl_vector_free(state->qtf); if (state->residual) gsl_vector_free(state->residual); if (state->perm) gsl_permutation_free(state->perm); if (state->workn) gsl_vector_free(state->workn); if (state->workp) gsl_vector_free(state->workp); if (state->work3p) gsl_vector_free(state->work3p); free(state); } /* compute J = Q R PT */ static int qr_init(const void * vtrust_state, void * vstate) { const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; qr_state_t *state = (qr_state_t *) vstate; int signum; /* perform QR decomposition of J */ gsl_matrix_memcpy(state->QR, trust_state->J); gsl_linalg_QRPT_decomp(state->QR, state->tau_Q, state->perm, &signum, state->workp); return GSL_SUCCESS; } static int qr_presolve(const double mu, const void * vtrust_state, void * vstate) { qr_state_t *state = (qr_state_t *) vstate; state->mu = mu; (void) vtrust_state; return GSL_SUCCESS; } static int qr_solve(const gsl_vector * f, gsl_vector *x, const void * vtrust_state, void *vstate) { qr_state_t *state = (qr_state_t *) vstate; int status; if (state->mu == 0.0) { /* * compute Gauss-Newton direction by solving * J x = f * with an attempt to identify rank deficiency in J */ size_t rank = gsl_linalg_QRPT_rank(state->QR, -1.0); status = gsl_linalg_QRPT_lssolve2(state->QR, state->tau_Q, state->perm, f, rank, x, state->residual); } else { /* * solve: * * [ J ] x = [ f ] * [ sqrt(mu) D ] [ 0 ] * * using QRPT factorization of J */ const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; double sqrt_mu = sqrt(state->mu); /* compute qtf = Q^T f */ gsl_vector_memcpy(state->qtf, f); gsl_linalg_QR_QTvec(state->QR, state->tau_Q, state->qtf); status = qrsolv(state->QR, state->perm, sqrt_mu, trust_state->diag, state->qtf, state->T, x, state->workn); } /* reverse step to go downhill */ gsl_vector_scale(x, -1.0); return status; } static int qr_rcond(double * rcond, void * vstate) { int status; qr_state_t *state = (qr_state_t *) vstate; status = gsl_linalg_QRPT_rcond(state->QR, rcond, state->work3p); return status; } static const gsl_multifit_nlinear_solver qr_type = { "qr", qr_alloc, qr_init, qr_presolve, qr_solve, qr_rcond, qr_free }; const gsl_multifit_nlinear_solver *gsl_multifit_nlinear_solver_qr = &qr_type;
{ "alphanum_fraction": 0.6232003291, "avg_line_length": 25.4111498258, "ext": "c", "hexsha": "a865baf256dab1eb90949da4e7bf1d3d382b6f3e", "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/qr.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/qr.c", "max_line_length": 90, "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/qr.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": 2033, "size": 7293 }
#ifndef LASER_SCANNER_H_WSZJIY40 #define LASER_SCANNER_H_WSZJIY40 #include <cmath> #include <gsl/gsl> #include <sens_loc/camera_models/concepts.h> #include <sens_loc/math/constants.h> #include <sens_loc/math/coordinate.h> #include <sens_loc/math/scaling.h> #include <stdexcept> #include <type_traits> namespace sens_loc::camera_models { namespace detail { template <typename Real> Real get_d_phi(int width) noexcept { static_assert(std::is_floating_point_v<Real>); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) return Real(2.) * math::pi<Real> / Real(width); } } // namespace detail /// This struct contains the parameters for describing the equirectangular /// projection of a laser scan. /// /// The scan is expected to be 360° in horizontal direction and som /// varying degree in vertical direction. /// The conversions and projections are mainly conversion from a /// spherical coordinate-system to a cartesian. /// \tparam Real precision of the parameters and calculations. /// /// \note the coordinate convention for spherical coordinates is as follows: /// - \f$\varphi \in [0, 2 \pi] \mapsto u\f$ note that this wraps around /// - \f$\theta \in [0, \pi] \mapsto v\f$ - not wrapping! /// - it is possible to have a different range for \f$\theta\f$ but not for /// \f$\varphi\f$. /// /// \tparam Real floating point type that determines the precision of the /// calculations. /// \sa is_intrinsic_v template <typename Real = float> class equirectangular { public: static_assert(std::is_floating_point_v<Real>); using real_type = Real; /// Default initialize all parameters to zero. equirectangular() = default; /// Construct a equirectangular image for the full sphere. /// /// \param width width of the image, this maps to 360° field of vie /// horizontally which wraps around /// \param height height of the image, this /// maps to 180° field of view vertically which does __NOT__ wrap equirectangular(int width, int height) noexcept : _w(width) , _h(height) , d_phi(detail::get_d_phi<Real>(width)) , d_theta(math::pi<Real> / Real(height)) , theta_min(Real(0.)) { Expects(width > 0); Expects(height > 0); ensure_invariant(); } /// Construct the model with a custom \f$\theta\f$-range. This model does /// __NOT__ map to the whole sphere, but is not a cylindrical coordinate /// system as well! /// \param width,height image dimensions /// \param theta_range minimum and maximum angle on the unit-sphere in /// vertical direction. equirectangular(int width, int height, math::numeric_range<Real> theta_range) noexcept : _w(width) , _h(height) , d_phi(detail::get_d_phi<Real>(width)) , d_theta((theta_range.max - theta_range.min) / Real(height)) , theta_min(theta_range.min) { Expects(width > 0); Expects(height > 0); Expects(theta_range.min >= 0.); Expects(theta_range.max <= math::pi<Real>); ensure_invariant(); } /// Construct the model with a minimum angle \p theta_min and an angle /// increment \p d_theta. /// /// \param width,height image dimensions /// \param theta_min,d_theta vertical resolution configuration /// \throws if the \f$\theta\f$-angle would be out of the range with the /// configuration this constructor throws an exception. equirectangular(int width, int height, Real theta_min, Real d_theta) : _w(width) , _h(height) , d_phi(detail::get_d_phi<Real>(width)) , d_theta(d_theta) , theta_min(theta_min) { const Real theta_max = theta_min + height * d_theta; if (theta_max > math::pi<Real>) throw std::invalid_argument("angle increment too big"); ensure_invariant(); } /// Return the width of the image corresponding to this intrinsic. [[nodiscard]] int w() const noexcept { return _w; } /// Return the height of the image corresponding to this intrinsic. [[nodiscard]] int h() const noexcept { return _h; } /// This methods calculates the inverse projection of the equirectangular /// model to get the direction of the lightray for the pixel at \p p. /// /// \tparam _Real either integer pixels or floating point for subpixels /// \param p non-negative pixel coordinates /// \post \f$\lVert result \rVert_2 = 1.\f$ /// \returns normalized vector in camera coordinates - unit sphere /// coordinate /// \note if \p _Real is an integer-type the value is itself backprojected, /// which usually means the bottom left corner of the pixel and __NOT__ /// its center! template <typename _Real = int> [[nodiscard]] math::sphere_coord<Real> pixel_to_sphere(const math::pixel_coord<_Real>& p) const noexcept; /// Project points in camera coordinates to pixel coordinates. /// \note if the point can not be projected (coordinate not in view) the /// pixel coordinate {-1, -1} is returned. /// \sa equirectangular::project_to_sphere template <typename _Real = Real> [[nodiscard]] math::pixel_coord<_Real> camera_to_pixel(const math::camera_coord<Real>& p) const noexcept; private: void ensure_invariant() const noexcept { Ensures(d_phi > Real(0.)); Ensures(d_theta > Real(0.)); Ensures(theta_min >= Real(0.)); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) Ensures(std::abs(d_phi * _w - Real(2.) * math::pi<Real>) < 0.00001); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) Ensures(theta_min + _h * d_theta <= math::pi<Real> + 0.00001); } int _w = 0; ///< width of a laser-scan image int _h = 0; ///< height of a laser-scan image. Real d_phi = 0.; ///< Angle increment in u-direction. Real d_theta = 0.; ///< Angle increment in v-direction. Real theta_min = 0.; ///< Smallest angle in v-direction. }; template <typename Real> template <typename _Real> inline math::sphere_coord<Real> equirectangular<Real>::pixel_to_sphere(const math::pixel_coord<_Real>& p) const noexcept { static_assert(std::is_arithmetic_v<_Real>); Expects(p.u() >= Real(0.0)); Expects(p.v() < Real(w())); Expects(p.u() >= Real(0.0)); Expects(p.v() < Real(h())); const Real phi = p.u() * d_phi - math::pi<Real>; const Real theta = theta_min + (p.v() * d_theta); Ensures(phi >= -math::pi<Real>); Ensures(phi <= math::pi<Real>); Ensures(theta >= Real(0.)); Ensures(theta <= math::pi<Real>); using std::cos; using std::sin; math::sphere_coord<Real> s{sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)}; // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) Ensures(std::abs(s.norm() - Real(1.0)) < 0.000001); return s; } template <typename Real> template <typename _Real> inline math::pixel_coord<_Real> equirectangular<Real>::camera_to_pixel(const math::camera_coord<Real>& p) const noexcept { static_assert(std::is_arithmetic_v<_Real>); const Real r = std::sqrt(p.X() * p.X() + p.Y() * p.Y() + p.Z() * p.Z()); if (r == Real(0.0)) return {_Real(-1), _Real(-1)}; const Real theta = std::acos(p.Z() / r); const Real phi = std::atan2(p.Y(), p.X()); Ensures(r >= Real(0.0)); Ensures(phi >= -math::pi<Real>); Ensures(phi <= math::pi<Real>); Ensures(theta >= Real(0.)); Ensures(theta <= math::pi<Real>); const _Real u = gsl::narrow_cast<_Real>((phi + math::pi<Real>) / d_phi); const _Real v = gsl::narrow_cast<_Real>(theta / d_theta); if (u < _Real(0.0) || u > gsl::narrow_cast<Real>(w()) || v < _Real(0.0) || v > gsl::narrow_cast<Real>(h())) return {_Real(-1), _Real(-1)}; return {u, v}; } } // namespace sens_loc::camera_models #endif /* end of include guard: LASER_SCANNER_H_WSZJIY40 */
{ "alphanum_fraction": 0.6386003956, "avg_line_length": 37.6186046512, "ext": "h", "hexsha": "25254a763d0055a0024584d79f6a47ab63bfa811", "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/include/sens_loc/camera_models/equirectangular.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/include/sens_loc/camera_models/equirectangular.h", "max_line_length": 79, "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/include/sens_loc/camera_models/equirectangular.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": 2110, "size": 8088 }
#pragma once //============================================================================= // EXTERNAL DECLARATIONS //============================================================================= #include <Core/Components/IdType.h> #include "Core/Game/IManager.h" #include <gsl/span> #include <memory> namespace engine { //============================================================================= // FORWARD DECLARATIONS //============================================================================= class IGameEngine; using GameEngineRef = std::shared_ptr<IGameEngine>; using GameEngineWeakRef = std::weak_ptr<IGameEngine>; //============================================================================= // INTERFACE IManagerComponent //============================================================================= class IManagerComponent { public: virtual ~IManagerComponent() {} public: virtual gsl::span<IdType> interfaces() = 0; virtual void onAttached(const GameEngineRef &iGameEngine) = 0; virtual void onDetached(const GameEngineRef &iGameEngine) = 0; }; } // namespace engine
{ "alphanum_fraction": 0.4336363636, "avg_line_length": 32.3529411765, "ext": "h", "hexsha": "d2eb7aa0669179e2d628e04f911df89a9fe522e2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "gaspardpetit/INF740-GameEngine", "max_forks_repo_path": "Core/Game/IManagerComponent.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "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": "gaspardpetit/INF740-GameEngine", "max_issues_repo_path": "Core/Game/IManagerComponent.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "gaspardpetit/INF740-GameEngine", "max_stars_repo_path": "Core/Game/IManagerComponent.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 173, "size": 1100 }
/* * Created on: Mar 22, 2016 * Author: Steffen Rechner <steffen.rechner@informatik.uni-halle.de> * * This file is part of the marathon software. * * Copyright (c) 2016, Steffen Rechner * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef INCLUDE_MARATHON_TRANSITIONMATRIX_H_ #define INCLUDE_MARATHON_TRANSITIONMATRIX_H_ #include "state_graph.h" #ifdef USE_ARMADILLO #include <armadillo> #endif #ifdef USE_BLAS #include <cblas.h> #endif namespace marathon { /** * Virtual Base Class for Transition Matrix. */ template<class T=double> class TransitionMatrix { protected: size_t N; // number of rows and columns size_t ld; // lead dimension (upper bound on n) std::vector<T> data; // actual data array public: /** * Standard Constructor. Create uninitialized transition matrix of size N times N. * @param N number of rows or columns */ TransitionMatrix(const size_t N) : N(N), ld(((N + 255) / 256) * 256) // lead dimension is next mulitple of 256 { data.resize(N * ld, 0); } /** * Constructor. Create Transition Matrix from State Graph. * @param sg Pointer to state graph object. */ TransitionMatrix(const StateGraph &sg) : TransitionMatrix(sg.getNumStates()) { for (const Transition *t : sg.getArcs()) { this->data[t->from * ld + t->to] = t->weight.convert_to<T>(); } } /** * Return size of the matrix. */ size_t getDimension() const { return N; } /** * Return lead dimension of the matrix. */ size_t getLeadDimension() const { return ld; } /** * Return a pointer to the data. */ const std::vector<T> &getData() const { return data; } /** * Return P[i,j]. * @param i row index * @param j column index * @return P[i,j] */ T get(size_t i, size_t j) const { return data[i * ld + j]; } /** * Set P[i,j] to x. * @param i row index. * @param j column index. * @param x value of type T */ void set(size_t i, size_t j, T x) { data[i * ld + j] = x; } /** * Overwrite the current matrix with zeroes. */ virtual void clear() { data.resize(N * ld, T(0)); } /** * Compute P^k. * @param P A pointer to a Transition Matrix. * @param k Exponent. * @return P^k */ TransitionMatrix<T> pow(uint k) const { // init matrix if (k == 0) { return eye(N); } // create binary representation of k int bin[32]; memset(bin, 0, 32 * sizeof(int)); int l = 31; int kk = k; while (kk > 0) { bin[l] = kk % 2; kk >>= 1; l--; } l += 2; #ifdef DEBUG std::cout << "bin: "; for (int i = 0; i < 32; i++) { std::cout << bin[i]; } std::cout << " l=" << l << std::endl; #endif TransitionMatrix<T> A(*this); // will be returned // binary exponentation - Left to Right (see Don. Knuth: Seminumerical Alg. Vol. 2 page 461) while (l < 32) { // square A = A * A; // multiply if (bin[l] == 1) A = A * *this; l++; } return A; } /** * Matrix multiplication. * @param P Transition matrix. * @return P * this */ TransitionMatrix<T> operator*(const TransitionMatrix<T> &P) const { TransitionMatrix<T> X(N); // will be returned #pragma omp parallel for for (size_t i = 0; i < N; i++) { for (size_t j = 0; j < N; j++) { T p_ij = 0; for (size_t k = 0; k < N; k++) { p_ij += this->get(i, k) * P.get(k, j); } X.set(i, j, p_ij); } } return X; } /** * Return a string that represents the matrix. */ virtual std::string to_string() const { std::stringstream ss; ss << "\n"; for (size_t i = 0; i < this->N; i++) { ss << " "; for (size_t j = 0; j < this->N - 1; j++) { ss << std::setprecision(std::numeric_limits<T>::digits10) << std::fixed << this->data[i * this->ld + j] << " "; } ss << std::setprecision(std::numeric_limits<T>::digits10) << std::fixed << this->data[i * this->ld + this->N - 1]; ss << "\n"; } return ss.str(); } /** * To output into streams. */ friend inline std::ostream &operator<<(std::ostream &out, const TransitionMatrix<T> &s) { out << s.to_string(); return out; } /** * Return the identity matrix with N rows and columns. * @param N Number of rows and columns. * @return Identity matrix. */ static TransitionMatrix<T> eye(size_t N) { TransitionMatrix<T> P(N); for (size_t i = 0; i < N; i++) P.set(i,i,1); return P; } }; /*********************************************************************** * template specializations **********************************************************************/ #ifdef USE_BLAS template<> TransitionMatrix<float> TransitionMatrix<float>::operator*(const TransitionMatrix<float> &P) const { const float alpha = 1.0; const float beta = 0.0; TransitionMatrix<float> X(N); // use cblas cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, &P.data[0], P.ld, &data[0], ld, beta, &X.data[0], X.ld); return X; } template<> TransitionMatrix<double> TransitionMatrix<double>::operator*(const TransitionMatrix<double> &P) const { const double alpha = 1.0; const double beta = 0.0; TransitionMatrix<double> X(N); // use cblas cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, alpha, &P.data[0], P.ld, &data[0], ld, beta, &X.data[0], X.ld); return X; } #endif } #endif /* INCLUDE_MARATHON_TRANSITIONMATRIX_H_ */
{ "alphanum_fraction": 0.4884124427, "avg_line_length": 27.7285223368, "ext": "h", "hexsha": "664d69752a704bc212884c26d8e1dfa02f055bf8", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-10-13T10:54:55.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-04T07:56:45.000Z", "max_forks_repo_head_hexsha": "e167ef293c10a968cd6a3f9901d717949a5311d5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "srechner/marathonR", "max_forks_repo_path": "inst/marathon/transition_matrix.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "e167ef293c10a968cd6a3f9901d717949a5311d5", "max_issues_repo_issues_event_max_datetime": "2016-04-09T18:31:48.000Z", "max_issues_repo_issues_event_min_datetime": "2015-08-20T06:15:43.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "srechner/marathonR", "max_issues_repo_path": "inst/marathon/transition_matrix.h", "max_line_length": 107, "max_stars_count": 4, "max_stars_repo_head_hexsha": "e167ef293c10a968cd6a3f9901d717949a5311d5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "srechner/marathonR", "max_stars_repo_path": "inst/marathon/transition_matrix.h", "max_stars_repo_stars_event_max_datetime": "2019-02-22T13:14:24.000Z", "max_stars_repo_stars_event_min_datetime": "2016-02-04T21:40:01.000Z", "num_tokens": 1873, "size": 8069 }
/** * @copyright (c) 2017 King Abdullah University of Science and Technology (KAUST). * All rights reserved. **/ /** * @file auxcompute_z.h * * This file contains the declarations of computational auxiliary functions. * * HiCMA is a software package provided by King Abdullah University of Science and Technology (KAUST) * * @version 0.1.1 * @author Kadir Akbudak * @date 2018-11-08 **/ #ifndef __AUXCOMPUTE_Z__ #define __AUXCOMPUTE_Z__ #include "hicma_struct.h" #ifdef MKL #include <mkl.h> //#pragma message("MKL is used") #else #include <cblas.h> #ifdef LAPACKE_UTILS #include <lapacke_utils.h> #endif #include <lapacke.h> //#pragma message("MKL is NOT used") #endif #include <stdio.h> #include "morse.h" #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif #include "starsh.h" int HICMA_zuncompress( MORSE_enum uplo, MORSE_desc_t *AUV, MORSE_desc_t *AD, MORSE_desc_t *Ark); int HICMA_zuncompress_custom_size(MORSE_enum uplo, MORSE_desc_t *AUV, MORSE_desc_t *AD, MORSE_desc_t *Ark, int numrows_matrix, int numcolumns_matrix, int numrows_block, int numcolumns_block ); int HICMA_zdiag_vec2mat( MORSE_desc_t *vec, MORSE_desc_t *mat); void HICMA_znormest( int M, int N, double *A, double *e, double *work); void HICMA_zgenerate_problem( int probtype, //problem type defined in hicma_constants.h char sym, // symmetricity of problem: 'N' or 'S' double decay, // decay of singular values. Will be used in HICMA_STARSH_PROB_RND. Set 0 for now. int _M, // number of rows/columns of matrix int _nb, // number of rows/columns of a single tile int _mt, // number of tiles in row dimension int _nt, // number of tiles in column dimension HICMA_problem_t *hicma_problem // pointer to hicma struct (starsh format will be used to pass coordinate info to number generation and compression phase) ); #endif
{ "alphanum_fraction": 0.6724479683, "avg_line_length": 32.0317460317, "ext": "h", "hexsha": "20434e9a11c52a1da95d9fdeac0f847d6dc630ec", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-08T11:05:38.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-08T11:05:38.000Z", "max_forks_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "isabella232/hicma", "max_forks_repo_path": "aux/include/auxcompute_z.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_issues_repo_issues_event_max_datetime": "2021-04-08T11:06:39.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-08T11:06:39.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Quansight/hicma", "max_issues_repo_path": "aux/include/auxcompute_z.h", "max_line_length": 161, "max_stars_count": null, "max_stars_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Quansight/hicma", "max_stars_repo_path": "aux/include/auxcompute_z.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 567, "size": 2018 }
/* * neuro.c * * Created on: Oct 9, 2019 * Author: alexey */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_rng.h> #include <png.h> #include <malloc.h> #include "neuro.h" typedef struct _neuro_skeleton { int input_l; int output_l; int hidden_l; int number_of_hidden; double alpha; gsl_matrix *input_m; gsl_matrix *output_m; gsl_matrix **hidden_m; gsl_matrix **dropuot; gsl_matrix **layers; gsl_matrix **layers_delta; gsl_matrix *temp; gsl_matrix *train; gsl_matrix *error; int layers_numb; activation activ; activation *activ_l; } neuro_skeleton; const gsl_rng_type * T; gsl_rng * r; extern unsigned long int gsl_rng_default_seed; #define CLEAN_BLOB() bayrepo_clean_neuro((void *) blob); \ return NULL #define CLEAN_IF_NULL(x) if (!blob->x) { \ CLEAN_BLOB(); \ } #define ISDEBUGINFO_BEG() if (getenv("MATRIXD") && !strcmp(getenv("MATRIXD"),"1")) { #define ISDEBUGINFO_END() } #define DEBUGINFO(A, B, C) ISDEBUGINFO_BEG()\ bayrepo_print_matrix(A, B, C); \ ISDEBUGINFO_END() #define MAX_LAYER_NAME_LEN 1024 #define MAX_BUFFER_LEN 4096 static void bayrepo_print_matrix(gsl_matrix *a, const char *matrix_name, int index_matrix) { int index, jndex; if (index_matrix >= 0) { printf("Matrix %s[%d]:\n", matrix_name, index_matrix); } else { printf("Matrix %s:\n", matrix_name); } for (index = 0; index < a->size1; index++) { printf("=="); for (jndex = 0; jndex < a->size2; jndex++) { printf("%.3f ", gsl_matrix_get(a, index, jndex)); } printf("==\n"); } } static void bayrepo_layers_clean(void *blob) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if (data->layers) { int index = 0; for (index = 0; index < data->layers_numb; index++) { if (data->layers[index]) gsl_matrix_free(data->layers[index]); } free(data->layers); data->layers = NULL; } if (data->layers_delta) { int index = 0; for (index = 0; index < data->layers_numb; index++) { if (data->layers_delta[index]) gsl_matrix_free(data->layers_delta[index]); } data->layers_numb = 0; free(data->layers_delta); data->layers_delta = NULL; } data->layers_numb = 0; } } void bayrepo_clean_neuro(void *blob) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if (data->input_m) { gsl_matrix_free(data->input_m); data->input_m = NULL; } if (data->output_m) { gsl_matrix_free(data->output_m); data->output_m = NULL; } if (data->train) { gsl_matrix_free(data->train); data->train = NULL; } if (data->temp) { gsl_matrix_free(data->temp); data->temp = NULL; } if (data->error) { gsl_matrix_free(data->error); data->error = NULL; } if (data->activ_l) { free(data->activ_l); data->activ_l = NULL; } if (data->number_of_hidden > 0 && data->hidden_m) { int i; for (i = 0; i < data->number_of_hidden; i++) { if (data->hidden_m[i]) { gsl_matrix_free(data->hidden_m[i]); data->hidden_m[i] = NULL; } } free(data->hidden_m); } if (data->number_of_hidden > 0 && data->dropuot) { int i; for (i = 0; i < data->number_of_hidden; i++) { if (data->dropuot[i]) { gsl_matrix_free(data->dropuot[i]); data->dropuot[i] = NULL; } } free(data->dropuot); } bayrepo_layers_clean(blob); free(data); } if (r) { gsl_rng_free(r); r = NULL; } } void bayrepo_set_layer_activ(void * blob, int layer_number, activation activ) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if (data->number_of_hidden) { if (layer_number <= data->number_of_hidden) { data->activ_l[layer_number] = activ; } } else { if (!layer_number) { data->activ_l[0] = activ; } } } } static int bayrepo_random_matrix(gsl_matrix *a, int m, int n, int is_negative) { int index, jndex; if (!r) return -1; for (index = 0; index < m; index++) { for (jndex = 0; jndex < n; jndex++) { gsl_matrix_set(a, index, jndex, gsl_rng_uniform(r) - (is_negative ? 0.5 : 0.0)); } } return 0; } void *bayrepo_init_neuro(int input, int output, int hidden, int hidden_num, double alpha, activation activ) { int index; gsl_rng_default_seed = time(NULL); T = gsl_rng_knuthran2; r = gsl_rng_alloc(T); if (hidden_num < 0) { hidden_num = 0; } neuro_skeleton *blob = calloc(1, sizeof(neuro_skeleton)); if (!blob) return NULL; blob->input_m = gsl_matrix_alloc(1, input); CLEAN_IF_NULL(input_m); blob->train = gsl_matrix_alloc(1, output); CLEAN_IF_NULL(train); blob->error = gsl_matrix_alloc(1, output); CLEAN_IF_NULL(error); if (hidden_num) { blob->output_m = gsl_matrix_alloc(hidden, output); CLEAN_IF_NULL(output_m); blob->hidden_m = (gsl_matrix **) calloc(hidden_num, sizeof(gsl_matrix *)); CLEAN_IF_NULL(hidden_m); blob->dropuot = (gsl_matrix **) calloc(hidden_num, sizeof(gsl_matrix *)); CLEAN_IF_NULL(dropuot); for (index = 1; index < hidden_num; index++) { blob->hidden_m[index] = gsl_matrix_alloc(hidden, hidden); CLEAN_IF_NULL(hidden_m[index]); blob->dropuot[index] = gsl_matrix_alloc(1, hidden); CLEAN_IF_NULL(dropuot[index]); } blob->hidden_m[0] = gsl_matrix_alloc(input, hidden); CLEAN_IF_NULL(hidden_m[0]); blob->dropuot[0] = gsl_matrix_alloc(1, hidden); CLEAN_IF_NULL(dropuot[0]); blob->temp = gsl_matrix_alloc(1, hidden); CLEAN_IF_NULL(temp); } else { blob->output_m = gsl_matrix_alloc(input, output); CLEAN_IF_NULL(output_m); } blob->alpha = alpha; blob->input_l = input; blob->output_l = output; blob->hidden_l = hidden; blob->number_of_hidden = hidden_num; gsl_matrix_set_zero(blob->input_m); gsl_matrix_set_zero(blob->train); if (hidden_num) { if (bayrepo_random_matrix(blob->output_m, hidden, output, (activ == RELU ? 0 : 1)) < 0) { CLEAN_BLOB() ; } for (index = 1; index < hidden_num; index++) { if (bayrepo_random_matrix(blob->hidden_m[index], hidden, hidden, (activ==RELU?0:1))<0) { CLEAN_BLOB(); } } if (bayrepo_random_matrix(blob->hidden_m[0], input, hidden, (activ==RELU?0:1))<0) { CLEAN_BLOB(); } } else { if (bayrepo_random_matrix(blob->output_m, input, output, (activ==RELU?0:1))<0) { CLEAN_BLOB(); } } int lyr_nmb = 1 + blob->number_of_hidden ? (blob->number_of_hidden + 1) : 0; blob->layers = (gsl_matrix **) calloc(lyr_nmb, sizeof(gsl_matrix *)); CLEAN_IF_NULL(layers); if (hidden_num) { for (index = 1; index < hidden_num; index++) { blob->layers[index] = gsl_matrix_alloc(1, hidden); CLEAN_IF_NULL(layers[index]); } blob->layers[0] = gsl_matrix_alloc(1, hidden); CLEAN_IF_NULL(layers[0]); blob->layers[lyr_nmb - 1] = gsl_matrix_alloc(1, output); CLEAN_IF_NULL(layers[lyr_nmb-1]); } else { blob->layers[0] = gsl_matrix_alloc(1, output); CLEAN_IF_NULL(layers[0]); } blob->layers_numb = lyr_nmb; blob->layers_delta = (gsl_matrix **) calloc(lyr_nmb, sizeof(gsl_matrix *)); CLEAN_IF_NULL(layers_delta); if (hidden_num) { for (index = 1; index < hidden_num; index++) { blob->layers_delta[index] = gsl_matrix_alloc(1, hidden); CLEAN_IF_NULL(layers_delta[index]); } blob->layers_delta[0] = gsl_matrix_alloc(1, hidden); CLEAN_IF_NULL(layers_delta[0]); blob->layers_delta[lyr_nmb - 1] = gsl_matrix_alloc(1, output); CLEAN_IF_NULL(layers_delta[lyr_nmb-1]); } else { blob->layers_delta[0] = gsl_matrix_alloc(1, output); CLEAN_IF_NULL(layers_delta[0]); } blob->activ = activ; blob->activ_l = calloc(blob->number_of_hidden + 1, sizeof(activation)); CLEAN_IF_NULL(activ_l); for (index = 0; index < (blob->number_of_hidden + 1); index++) { if (index == blob->number_of_hidden) { blob->activ_l[index] = NOACTIV; } else { blob->activ_l[index] = DEFLT; } } return (void *) blob; } static void bayrepo_fill_dropout(gsl_matrix *a, int m, int n) { int index, jndex; if (!r) { for (index = 0; index < m; index++) { for (jndex = 0; jndex < n; jndex++) { gsl_matrix_set(a, index, jndex, 1.0); } } return; } for (index = 0; index < m; index++) { for (jndex = 0; jndex < n; jndex++) { gsl_matrix_set(a, index, jndex, gsl_rng_uniform_int(r, 2) * 1.0); } } return; } void bayrepo_fill_input(void *blob, int position, double scaled_value) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if (position < data->input_l) { gsl_matrix_set(data->input_m, 0, position, scaled_value); } } } void bayrepo_fill_train(void *blob, int position, double scaled_value) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if (position < data->output_l) { gsl_matrix_set(data->train, 0, position, scaled_value); } } } void bayrepo_fill_hidden(void *blob, int index, int position_x, int position_y, double scaled_value) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; gsl_matrix_set(data->hidden_m[index], position_x, position_y, scaled_value); } } void bayrepo_fill_outm(void *blob, int position_x, int position_y, double scaled_value) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; gsl_matrix_set(data->output_m, position_x, position_y, scaled_value); } } static void bayrepo_zero_layers(void *blob) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; int index; for (index = 0; index < data->layers_numb; index++) { gsl_matrix_set_zero(data->layers[index]); } } } static double bayrepo_activation_func(double elem, neuro_skeleton *data, int lyn) { activation act = data->activ; if ((lyn < (data->number_of_hidden + 1)) && (data->activ_l[lyn] != DEFLT)) { act = data->activ_l[lyn]; } switch (act) { case RELU: return elem > 0.0 ? elem : 0.0; case TANH: return tanh(elem); case SIGMOID: return 1.0 / (1.0 + exp(-elem)); default: return elem; } } activation bayrepo_get_layer_func(void *blob, int lyn) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if ((lyn < (data->number_of_hidden + 1)) && (data->activ_l[lyn] != DEFLT)) { return data->activ_l[lyn]; } } return NOACTIV; } activation bayrepo_get_sublayer_func(void *blob, int lyn) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if (lyn < (data->number_of_hidden + 1)) { return data->activ_l[lyn]; } } return NOACTIV; } static double bayrepo_activation_deriv(double elem, neuro_skeleton *data, int lyn) { activation act = data->activ; if ((lyn < (data->number_of_hidden + 1)) && (data->activ_l[lyn] != DEFLT)) { act = data->activ_l[lyn]; } switch (act) { case RELU: return elem > 0.0 ? 1.0 : 0.0; case TANH: return 1.0 - (elem * elem); case SIGMOID: return elem * (1.0 - elem); default: return elem; } } static void bayrepo_matix_customize(gsl_matrix *a, int size, neuro_skeleton *data, int lyn) { int index; for (index = 0; index < size; index++) { gsl_matrix_set(a, 0, index, bayrepo_activation_func(gsl_matrix_get(a, 0, index), data, lyn)); } } static void bayrepo_matix_deriv(gsl_matrix *a, int size, neuro_skeleton *data, int lyn) { int index; for (index = 0; index < size; index++) { gsl_matrix_set(a, 0, index, bayrepo_activation_deriv(gsl_matrix_get(a, 0, index), data, lyn)); } } static void bayrepo_query_internal(void *blob, int dropout) { int index; if (blob) { ISDEBUGINFO_BEG() printf("=====================Query=========================\n"); ISDEBUGINFO_END() neuro_skeleton *data = (neuro_skeleton *) blob; bayrepo_zero_layers(blob); if (data->number_of_hidden) { if (dropout == 1) { for (index = 0; index < data->number_of_hidden; index++) { bayrepo_fill_dropout(data->dropuot[index], 1, data->hidden_l); } } int cnt = 0; gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, data->input_m, data->hidden_m[0], 0.0, data->layers[0]); bayrepo_matix_customize(data->layers[0], data->hidden_l, data, 0); if (dropout == 1) { gsl_matrix_mul_elements(data->layers[0], data->dropuot[0]); gsl_matrix_scale(data->layers[0], 2.0); } cnt++; for (index = 1; index < data->number_of_hidden; index++) { gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, data->layers[index - 1], data->hidden_m[index], 0.0, data->layers[index]); bayrepo_matix_customize(data->layers[index], data->hidden_l, data, index); if (dropout == 1) { gsl_matrix_mul_elements(data->layers[index], data->dropuot[index]); gsl_matrix_scale(data->layers[index], 2.0); } cnt++; } gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, data->layers[cnt - 1], data->output_m, 0.0, data->layers[cnt]); bayrepo_matix_customize(data->layers[cnt], data->output_l, data, cnt); } else { gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, data->input_m, data->output_m, 0.0, data->layers[0]); bayrepo_matix_customize(data->layers[0], data->output_l, data, 0); } DEBUGINFO(data->input_m, "INPUTM", -1); if (data->number_of_hidden) { for (index = 0; index < data->number_of_hidden; index++) { DEBUGINFO(data->hidden_m[index], "HIDDEN", index); } } DEBUGINFO(data->output_m, "OUTPUTM", -1); for (index = 0; index < data->layers_numb; index++) { DEBUGINFO(data->layers[index], "LAYER", index); } } } void bayrepo_query(void *blob) { bayrepo_query_internal(blob, 0); } double bayrepo_get_result(void *blob, int position) { if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; if (data->layers && position < data->output_l) { return gsl_matrix_get(data->layers[data->layers_numb - 1], 0, position); } } return -10000.0; } double bayrepo_get_sum(gsl_matrix *a) { double result = 0.0; int index, jndex = 0; for (index = 0; index < a->size1; index++) { for (jndex = 0; jndex < a->size2; jndex++) { result += gsl_matrix_get(a, index, jndex); } } return result; } void bayrepo_train(void *blob, int epoch, int use_dropout) { int index; if (blob) { while (epoch--) { ISDEBUGINFO_BEG() printf( "=====================Epoch %d=========================\n", epoch); ISDEBUGINFO_END() neuro_skeleton *data = (neuro_skeleton *) blob; bayrepo_query_internal(blob, use_dropout); gsl_matrix_memcpy(data->layers_delta[data->layers_numb - 1], data->layers[data->layers_numb - 1]); ISDEBUGINFO_BEG() gsl_matrix_memcpy(data->error, data->layers[data->layers_numb - 1]); ISDEBUGINFO_END(); gsl_matrix_sub(data->layers_delta[data->layers_numb - 1], data->train); ISDEBUGINFO_BEG() gsl_matrix_sub(data->error, data->train); gsl_matrix_mul_elements(data->error, data->error); printf("=======>Error=%f\n", bayrepo_get_sum(data->error)); ISDEBUGINFO_END(); if (data->number_of_hidden) { int index; for (index = (data->layers_numb - 2); index >= 0; index--) { gsl_matrix_set_zero(data->temp); gsl_matrix_memcpy(data->temp, data->layers[index]); bayrepo_matix_deriv(data->temp, data->hidden_l, data, index); if (index == (data->layers_numb - 2)) { gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, data->layers_delta[index + 1], data->output_m, 0.0, data->layers_delta[index]); } else { gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, data->layers_delta[index + 1], data->hidden_m[index + 1], 0.0, data->layers_delta[index]); } gsl_matrix_mul_elements(data->layers_delta[index], data->temp); } if (use_dropout) { for (index = 0; index < data->number_of_hidden; index++) { gsl_matrix_mul_elements(data->layers_delta[index], data->dropuot[index]); } } for (index = (data->layers_numb - 1); index >= 0; index--) { if (index == (data->layers_numb - 1)) { gsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha, data->layers[index - 1], data->layers_delta[index], 1.0, data->output_m); } else if (index == 0) { gsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha, data->input_m, data->layers_delta[index], 1.0, data->hidden_m[0]); } else { gsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha, data->layers[index - 1], data->layers_delta[index], 1.0, data->hidden_m[index]); } } } else { gsl_blas_dgemm(CblasTrans, CblasNoTrans, -data->alpha, data->input_m, data->layers_delta[0], 1.0, data->output_m); } for (index = 0; index < data->layers_numb; index++) { DEBUGINFO(data->layers_delta[index], "LAYER_DELTA", index); } } } } static void byrepo_png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { bayrepo_mem_encode* p = (bayrepo_mem_encode*) png_get_io_ptr(png_ptr); size_t nsize = p->size + length; if (p->buffer) p->buffer = realloc(p->buffer, nsize); else p->buffer = malloc(nsize); if (!p->buffer) png_error(png_ptr, "Write Error"); memcpy(p->buffer + p->size, data, length); p->size += length; } static void bayrepo_png_flush(png_structp png_ptr) { } int bayrepo_write_matrix(void *blob, FILE *fp, int width, int height, bayrepo_mem_encode *buffer) { int code = 0; if (buffer) { buffer->buffer = NULL; buffer->size = 0; } png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_bytep row = NULL; if ((blob == NULL) || (fp == NULL)) { return -1; } png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { code = -3; goto finalise; } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { code = -4; goto finalise; } if (setjmp(png_jmpbuf(png_ptr))) { code = -5; goto finalise; } if (buffer) { png_set_write_fn(png_ptr, buffer, byrepo_png_write_data, bayrepo_png_flush); } else { png_init_io(png_ptr, fp); } neuro_skeleton *data = (neuro_skeleton *) blob; int picSize = (height + 3) + (height + 3) * data->number_of_hidden; png_set_IHDR(png_ptr, info_ptr, width, picSize, 8, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); row = (png_bytep) malloc(3 * width * sizeof(png_byte)); if (!row) { code = -5; goto finalise; } int index = 0; for (index = 0; index < data->number_of_hidden + 1; index++) { gsl_matrix * m = NULL; if (data->number_of_hidden) { m = (index == data->number_of_hidden) ? data->output_m : data->hidden_m[index]; } else { m = data->output_m; } double rangeMax = gsl_matrix_max(m); double rangeMin = gsl_matrix_min(m); if (((width / m->size1) == 0) || ((height / m->size2) == 0)) { return -2; } int sizeX = width / m->size1; int sizeY = height / m->size2; int x, y; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { int curX = x / sizeX; int curY = y / sizeY; if ((curX >= m->size1) || (curY >= m->size2)) { row[x] = (png_byte) 255; } else { png_byte res_color = (png_byte) ((gsl_matrix_get(m, curX, curY) - rangeMin) / (rangeMax - rangeMin) * 255.0); if (res_color > 255.0) res_color = 255.0; row[x] = (png_byte) (255.0 - res_color); } } png_write_row(png_ptr, row); } for (y = 0; y < 3; y++) { for (x = 0; x < width; x++) { if (y != 1) { row[x] = (png_byte) 255; } else { row[x] = (png_byte) 0; } } png_write_row(png_ptr, row); } } png_write_end(png_ptr, NULL); finalise: if (info_ptr != NULL) png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); if (png_ptr != NULL) png_destroy_write_struct(&png_ptr, (png_infopp) NULL); if (row != NULL) free(row); return code; } void bayrepo_print_matrix_custom(void *blob, bayrepo_decorator *decor) { char layer_name[MAX_LAYER_NAME_LEN]; if (blob) { neuro_skeleton *data = (neuro_skeleton *) blob; int index = 0; for (index = 0; index < (data->number_of_hidden + 1); index++) { gsl_matrix * m = NULL; if (data->number_of_hidden) { m = (index == data->number_of_hidden) ? data->output_m : data->hidden_m[index]; if (index == data->number_of_hidden) { snprintf(layer_name, MAX_LAYER_NAME_LEN, "Output layer"); } else { snprintf(layer_name, MAX_LAYER_NAME_LEN, "Hidden layer %d", index); } } else { m = data->output_m; snprintf(layer_name, MAX_LAYER_NAME_LEN, "Output layer"); } int posX, posY; if (decor->table_header) decor->table_header(decor->user_data, layer_name, m->size1); for (posX = 0; posX < m->size2; posX++) { if (decor->pre_column) decor->pre_column(decor->user_data); for (posY = 0; posY < m->size1; posY++) { if (decor->print_func) decor->print_func(decor->user_data, gsl_matrix_get(m, posY, posX)); } if (decor->post_column) decor->post_column(decor->user_data); } if (decor->table_footer) decor->table_footer(decor->user_data); } } } int input_l; int output_l; int hidden_l; int number_of_hidden; double alpha; gsl_matrix *input_m; gsl_matrix *output_m; gsl_matrix **hidden_m; gsl_matrix **dropuot; gsl_matrix **layers; gsl_matrix **layers_delta; gsl_matrix *temp; gsl_matrix *train; gsl_matrix *error; int layers_numb; activation activ; activation *activ_l; /* * Save format * * [int input_l]\n * [int output_l]\n * [int hidden_l]\n * [int number_of_hidden]\n * [double alpha]\n * [int activ]\n * [ACTBEG]\n * [int layer_number]:[int activ]\n * [ACTEND]\n * [HIDDEN_BEG]\n * [int X]:[int Y]:[double value]\n * [HIDDEN_END] * [OUTPUT_BEG]\n * [int X]:[int Y]:[double value]\n * [OUTPUT_END]\n */ static char *bayrepo_reallocate_buffer(char *buffer, char *newdata, int *len, int newlen) { buffer = (char *) realloc(buffer, *len + newlen); if (!buffer) { return NULL; } memcpy(buffer + *len, newdata, newlen); *len = *len + newlen; return buffer; } int bayrepo_save_to_buffer(void *blob, char **buffer) { char buff[MAX_LAYER_NAME_LEN]; int index; if (blob) { int len = 0; char *ptr = NULL; neuro_skeleton *data = (neuro_skeleton *) blob; snprintf(buff, MAX_LAYER_NAME_LEN, "%d\n", data->input_l); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); snprintf(buff, MAX_LAYER_NAME_LEN, "%d\n", data->output_l); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); snprintf(buff, MAX_LAYER_NAME_LEN, "%d\n", data->hidden_l); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); snprintf(buff, MAX_LAYER_NAME_LEN, "%d\n", data->number_of_hidden); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); snprintf(buff, MAX_LAYER_NAME_LEN, "%f\n", data->alpha); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); snprintf(buff, MAX_LAYER_NAME_LEN, "%d\n", (int) data->activ); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); ptr = bayrepo_reallocate_buffer(ptr, (char *) "[ACTBEG]\n", &len, strlen("[ACTBEG]\n")); for (index = 0; index < (data->number_of_hidden + 1); index++) { snprintf(buff, MAX_LAYER_NAME_LEN, "%d:%d\n", index, (int) data->activ_l[index]); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); } ptr = bayrepo_reallocate_buffer(ptr, (char *) "[ACTEND]\n", &len, strlen("[ACTEND]\n")); for (index = 0; index < data->number_of_hidden; index++) { ptr = bayrepo_reallocate_buffer(ptr, (char *) "[HIDDEN_BEG]\n", &len, strlen("[HIDDEN_BEG]\n")); int x, y; for (x = 0; x < data->hidden_m[index]->size1; x++) { for (y = 0; y < data->hidden_m[index]->size2; y++) { snprintf(buff, MAX_LAYER_NAME_LEN, "%d:%d:%f\n", x, y, gsl_matrix_get(data->hidden_m[index], x, y)); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); } } ptr = bayrepo_reallocate_buffer(ptr, (char *) "[HIDDEN_END]\n", &len, strlen("[HIDDEN_END]\n")); } ptr = bayrepo_reallocate_buffer(ptr, (char *) "[OUTPUT_BEG]\n", &len, strlen("[OUTPUT_BEG]\n")); int x, y; for (x = 0; x < data->output_m->size1; x++) { for (y = 0; y < data->output_m->size2; y++) { snprintf(buff, MAX_LAYER_NAME_LEN, "%d:%d:%f\n", x, y, gsl_matrix_get(data->output_m, x, y)); ptr = bayrepo_reallocate_buffer(ptr, (char *) buff, &len, strlen(buff)); } } ptr = bayrepo_reallocate_buffer(ptr, (char *) "[OUTPUT_END]\n", &len, strlen("[OUTPUT_END]\n")); *buffer = ptr; return len; } return 0; } void *bayrepo_restore_buffer(char *buffer, int buffer_len) { FILE *fp = fmemopen((void*) buffer, buffer_len, "r"); int input_l = 0; int output_l = 0; int hidden_l = 0; int numb_of_hidden = 0; activation act = RELU; int act_beg = 0; double alpha = 0.0; void *blob = NULL; int is_hidden = 0; int hidden_index = 0; int is_out = 0; if (fp) { char result_buf[MAX_BUFFER_LEN]; int counter = 0; while (!feof(fp)) { if (fgets(result_buf, MAX_BUFFER_LEN, fp)) { switch (counter) { case 0: { result_buf[strlen(result_buf) - 1] = 0; input_l = atoi(result_buf); } break; case 1: { result_buf[strlen(result_buf) - 1] = 0; output_l = atoi(result_buf); } break; case 2: { result_buf[strlen(result_buf) - 1] = 0; hidden_l = atoi(result_buf); } break; case 3: { result_buf[strlen(result_buf) - 1] = 0; numb_of_hidden = atoi(result_buf); } break; case 4: { char *tptr; result_buf[strlen(result_buf) - 1] = 0; alpha = strtod(result_buf, &tptr); } break; case 5: { result_buf[strlen(result_buf) - 1] = 0; act = (activation) atoi(result_buf); if (input_l > 0 && output_l > 0 && hidden_l >= 0 && numb_of_hidden >= 0 && alpha > 0.0) { blob = bayrepo_init_neuro(input_l, output_l, hidden_l, numb_of_hidden, alpha, act); } } break; default: { if (!blob) return NULL; if (strstr(result_buf, "[ACTBEG]")) { act_beg = 1; } else if (strstr(result_buf, "[ACTEND]")) { act_beg = 0; } else if (act_beg) { result_buf[strlen(result_buf) - 1] = 0; char *ptr = strchr(result_buf, ':'); if (ptr) { *ptr = 0; ptr++; int ly = atoi(result_buf); int ac = atoi(ptr); bayrepo_set_layer_activ(blob, ly, (activation) ac); } } else if (strstr(result_buf, "[HIDDEN_BEG]")) { is_hidden = 1; } else if (strstr(result_buf, "[HIDDEN_END]")) { hidden_index++; is_hidden = 0; } else if (is_hidden) { result_buf[strlen(result_buf) - 1] = 0; char *ptr1 = strchr(result_buf, ':'); if (ptr1) { *ptr1 = 0; ptr1++; char *ptr2 = strchr(ptr1, ':'); if (ptr2) { *ptr2 = 0; ptr2++; char *tptr = NULL; int x = atoi(result_buf); int y = atoi(ptr1); double vl = strtod(ptr2, &tptr); bayrepo_fill_hidden(blob, hidden_index, x, y, vl); } } } else if (strstr(result_buf, "[OUTPUT_BEG]")) { is_out = 1; } else if (strstr(result_buf, "[OUTPUT_END]")) { hidden_index++; is_out = 0; } else if (is_out) { result_buf[strlen(result_buf) - 1] = 0; char *ptr1 = strchr(result_buf, ':'); if (ptr1) { *ptr1 = 0; ptr1++; char *ptr2 = strchr(ptr1, ':'); if (ptr2) { *ptr2 = 0; ptr2++; char *tptr = NULL; int x = atoi(result_buf); int y = atoi(ptr1); double vl = strtod(ptr2, &tptr); bayrepo_fill_outm(blob, x, y, vl); } } } } } } counter++; } return blob; } return NULL; }
{ "alphanum_fraction": 0.6297403393, "avg_line_length": 26.6222435283, "ext": "c", "hexsha": "fec902798f3eae9a53f68cb90d2ed110e4dafd07", "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": "3888190198e356a3be4fb2b71175630b34d8f963", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bayrepo/bayrepo_neuro", "max_forks_repo_path": "neuro.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3888190198e356a3be4fb2b71175630b34d8f963", "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": "bayrepo/bayrepo_neuro", "max_issues_repo_path": "neuro.c", "max_line_length": 91, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3888190198e356a3be4fb2b71175630b34d8f963", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bayrepo/bayrepo_neuro", "max_stars_repo_path": "neuro.c", "max_stars_repo_stars_event_max_datetime": "2021-01-06T14:42:04.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:42:04.000Z", "num_tokens": 8984, "size": 27767 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #include <gsl/gsl-lite.hpp> #include <nlohmann/json.hpp> #include <platform/dirutils.h> #include <vector> class Event; /** * The Module class represents the configuration for a single module. * See ../README.md for more information. */ class Module { public: Module() = delete; Module(const nlohmann::json& json, const std::string& srcRoot, const std::string& objRoot); void createHeaderFile(); /** * The name of the module */ std::string name; /** * The lowest identifier for the audit events in this module. All * audit descriptor defined for this module MUST be within the range * [start, start + max_events_per_module] */ int64_t start; /** * The name of the file containing the audit descriptors for this * module. */ std::string file; /** * The JSON data describing the audit descriptors for this module */ nlohmann::json json; /** * Is this module enterprise only? */ bool enterprise = false; /** * If present this is the name of a C headerfile to generate with * #defines for all audit identifiers for the module. */ std::string header; /** * A list of all of the events defined for this module */ std::vector<std::unique_ptr<Event>> events; protected: /** * Add the event to the list of events for the module * * @param event the event to add * @throws std::invalid_argument if the event is outside the legal range * for the module */ void addEvent(std::unique_ptr<Event> event); /// Parse the event descriptor file and add all of the events into /// the list of events void parseEventDescriptorFile(); };
{ "alphanum_fraction": 0.6360052562, "avg_line_length": 27.8414634146, "ext": "h", "hexsha": "5880af3ba5dcfb112bdbd9bd2b84560edb0f7740", "lang": "C", "max_forks_count": 71, "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_path": "auditd/generator/generator_module.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_path": "auditd/generator/generator_module.h", "max_line_length": 79, "max_stars_count": 104, "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_path": "auditd/generator/generator_module.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "num_tokens": 537, "size": 2283 }
#include <iostream> #include <math.h> #include <Windows.h> #include <string> #include <vector> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/legacy/compat.hpp> #include <opencv2/opencv.hpp> #include <Eigen/Dense> #include <gsl/gsl_multifit.h> #include <stdbool.h> #include <CLEyeMulticam.h> #include "SerialClass.h" int i = 0; using namespace cv; using namespace std; using namespace Eigen; void setupScreen(); void setupCamera(int i); bool processCamera(int i, Mat imgOriginal); Vector3d rotateX(Vector3d v, double angle); Vector3d rotateY(Vector3d v, double angle); Vector3d rotateZ(Vector3d v, double angle); bool polynomialfit(int obs, int degree, double *dx, double *dy, double *store); void fpsPrint(); void triangulate(); void trajectoryCalc(); void arduinoSend(); int demo = 1; int dataCollectEnabled = 0; vector<double> xCoords; vector<double> yCoords; vector<double> zCoords; double XZcoeff[3] = { 0 }; double XYcoeff[2] = { 0 }; int estXY[2] = { 0 }; // sum of estimated values #include "CLEye.h" // This needs to be here b/c it uses the functions, namespaces, variables above char *port = "COM4"; class Camera { public: double rot[3]; double rot2[3]; Vector3d pos; double planeDist; double planeX; double planeY; double screenX; double screenY; Vector3d ballDir; }; Camera cameras[2]; CLEyeCameraCapture *cam[2]; int minHue, maxHue, minSat, maxSat, minValue, maxValue; int catcherHeight = 15; // Height of robot end-effector, in cm (at what height the ball will be caught) double minX = 8.7; // Minimum distance of center of catcher to origin, in cm double minY = 8.7; double maxX = 52.7; double maxY = 48.2; int lastTick = 0; char buffer[256] = ""; Serial* arduino; #include "Functions.h"
{ "alphanum_fraction": 0.7286036036, "avg_line_length": 22.4810126582, "ext": "h", "hexsha": "c2e743a69eba399322b45bd70b6ab80571c4d282", "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": "e61044cb764d2cba59203994124b534fea834360", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BaranCODE/BallCatcher", "max_forks_repo_path": "BallCatcher-C++/Header.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e61044cb764d2cba59203994124b534fea834360", "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": "BaranCODE/BallCatcher", "max_issues_repo_path": "BallCatcher-C++/Header.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "e61044cb764d2cba59203994124b534fea834360", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "BaranCODE/BallCatcher", "max_stars_repo_path": "BallCatcher-C++/Header.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 493, "size": 1776 }
// SPDX-License-Identifier: MIT // The MIT License (MIT) // // Copyright (c) 2014-2018, Institute for Software & Systems Engineering // Copyright (c) 2018-2019, Johannes Leupolz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef PEMC_GENERIC_TRAVERSER_PATH_TRACKER_H_ #define PEMC_GENERIC_TRAVERSER_PATH_TRACKER_H_ #include <vector> #include <gsl/span> #include <cstdint> #include <atomic> #include <stack> #include <limits> #include "pemc/basic/tsc_index.h" #include "pemc/basic/label.h" #include "pemc/basic/model_capacity.h" #include "pemc/basic/raw_memory.h" #include "pemc/formula/formula.h" namespace pemc { struct PathFrame { // the offset into the states array where the index of the frame's first state is stored. int32_t indexOfFirstStateIndexEntry; //offset // the number of states the frame consists of. int32_t count; }; /// When enumerating all states of a model in a depth-first fashion, we have to store the next states (that are computed all /// at once) somewhere while also being able to generate the counter example. When check a new state, a new frame is allocated /// on the stack and all unknown successor states are stored in that frame. We then take the topmost state, compute its /// successor states, and so on. When a formula violation is detected, the counter example consists of the last states of each /// frame on the stack. When a frame has been fully enumerated without detecting a formula violation, the stack frame is /// removed, the topmost state of the topmost frame is removed, and the new topmost state is checked. class PathTracker { private: std::vector<PathFrame> pathFrames; std::vector<StateIndex> stateIndexEntries; /// The lowest index of a splittable frame. -1 if no frame is splittable. int32_t lowestSplittableFrame = -1; // Maximal number of stateIndexEntries. int32_t capacity = 1 << 20; /// Finds the next splittable frame, if any. void updateLowestSplittableFrame(); public: PathTracker(int32_t _capacity); /// Indicates whether the pathFrames can be split. bool canSplit(); /// Gets the number of path frames. int32_t getPathFrameCount(); /// Clears all pathFrames and its stateIndexEntries. void clear(); /// Pushes a new frame onto the pathFrames stack. void pushFrame(); /// Adds the stateIndex to the current path frame. void pushStateIndex(StateIndex stateIndex); /// Tries to get the topmost stateIndex if there is one. /// Returns false to indicate that the path tracker was empty and no stateIndex was returned. bool tryGetStateIndex(StateIndex& stateIndex); bool splitWork(PathTracker& other); /// Gets the path the path tracker currently represents, i.e., /// returns the sequence of topmost states of each frame, starting with /// the oldest one. std::vector<StateIndex> getCurrentPath(); }; } #endif // PEMC_GENERIC_TRAVERSER_PATH_TRACKER_H_
{ "alphanum_fraction": 0.724407525, "avg_line_length": 40.1274509804, "ext": "h", "hexsha": "da7adefc857206612d2597532c8a22aa7cddf030", "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": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_path": "pemc/generic_traverser/path_tracker.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "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": "joleuger/pemc", "max_issues_repo_path": "pemc/generic_traverser/path_tracker.h", "max_line_length": 129, "max_stars_count": null, "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_path": "pemc/generic_traverser/path_tracker.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 944, "size": 4093 }
/***************************************************************************/ /* */ /* QR_decomp.c - LU Decomposition class for mruby */ /* Copyright (C) 2015 Paolo Bosetti */ /* paolo[dot]bosetti[at]unitn.it */ /* Department of Industrial Engineering, University of Trento */ /* */ /* This library is free software. You can redistribute it and/or */ /* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0. */ /* */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* Artistic License 2.0 for more details. */ /* */ /* See the file LICENSE */ /* */ /***************************************************************************/ #include <gsl/gsl_linalg.h> #include <stdio.h> #include "matrix.h" #include "vector.h" #include "QR_decomp.h" #ifndef MIN #define MAX(a, b) \ ({ \ __typeof__(a) _a = (a); \ __typeof__(b) _b = (b); \ _a < _b ? _a : _b; \ }) #endif #pragma mark - #pragma mark • Utilities // Garbage collector handler, for play_data struct // if play_data contains other dynamic data, free it too! // Check it with GC.start void qr_decomp_destructor(mrb_state *mrb, void *p_) { qr_decomp_data_s *lu = (qr_decomp_data_s *)p_; gsl_matrix_free(lu->mat); gsl_vector_free(lu->tau); free(lu); }; // Creating data type and reference for GC, in a const struct const struct mrb_data_type qr_decomp_data_type = {"qr_decomp_data", qr_decomp_destructor}; // Utility function for getting the struct out of the wrapping IV @data void mrb_qr_decomp_get_data(mrb_state *mrb, mrb_value self, qr_decomp_data_s **data) { mrb_value data_value; data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data")); // Loading data from data_value into p_data: Data_Get_Struct(mrb, data_value, &qr_decomp_data_type, *data); if (!*data) mrb_raise(mrb, E_RUNTIME_ERROR, "Could not access @data"); } #pragma mark - #pragma mark • Initializations // Data Initializer C function (not exposed!) static mrb_value mrb_qr_initialize(mrb_state *mrb, mrb_value self) { mrb_value data_value; // this IV holds the data qr_decomp_data_s *p_data = NULL; // pointer to the C struct mrb_value matrix; gsl_matrix *p_mat = NULL; mrb_int size1, size2; mrb_get_args(mrb, "o", &matrix); if (!mrb_obj_is_kind_of(mrb, matrix, mrb_class_get(mrb, "Matrix"))) { mrb_raise(mrb, E_ARGUMENT_ERROR, "Argument must be a Matrix"); } mrb_matrix_get_data(mrb, matrix, &p_mat); // if (p_mat->size1 < p_mat->size2) { // mrb_raise(mrb, E_ARGUMENT_ERROR, "Argument must be square or horizontal // Matrix"); // } size1 = p_mat->size1; size2 = p_mat->size2; data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data")); // if @data already exists, free its content: if (!mrb_nil_p(data_value)) { Data_Get_Struct(mrb, data_value, &qr_decomp_data_type, p_data); free(p_data); } // Allocate and zero-out the data struct: p_data = (qr_decomp_data_s *)malloc(sizeof(qr_decomp_data_s)); if (!p_data) { mrb_raise(mrb, E_RUNTIME_ERROR, "Could not allocate @data"); } p_data->size1 = size1; p_data->size2 = size2; p_data->minsize = MIN(size1, size2); p_data->mat = gsl_matrix_calloc(size1, size2); p_data->tau = gsl_vector_calloc(p_data->minsize); // copy argument matrix into local object data gsl_matrix_memcpy(p_data->mat, p_mat); // invert in-place gsl_linalg_QR_decomp(p_data->mat, p_data->tau); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@size1"), mrb_fixnum_value(size1)); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@size2"), mrb_fixnum_value(size2)); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@minsize"), mrb_fixnum_value(p_data->minsize)); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@residuals"), mrb_nil_value()); // Wrap struct into @data: mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@data"), // set @data mrb_obj_value( // with value hold in struct Data_Wrap_Struct(mrb, mrb->object_class, &qr_decomp_data_type, p_data))); return mrb_nil_value(); } #pragma mark - #pragma mark • Accessors static mrb_value mrb_qr_residuals(mrb_state *mrb, mrb_value self) { return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@residuals")); } static mrb_value mrb_qr_minsize(mrb_state *mrb, mrb_value self) { return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@minsize")); } static mrb_value mrb_qr_size1(mrb_state *mrb, mrb_value self) { return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@size1")); } static mrb_value mrb_qr_size2(mrb_state *mrb, mrb_value self) { return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@size2")); } static mrb_value mrb_qr_matrix(mrb_state *mrb, mrb_value self) { mrb_value result; qr_decomp_data_s *p_data = NULL; gsl_matrix *p_res = NULL; mrb_value args[2]; // call utility for unwrapping @data into p_data: mrb_qr_decomp_get_data(mrb, self, &p_data); args[0] = mrb_fixnum_value(p_data->size1); args[1] = mrb_fixnum_value(p_data->size2); result = mrb_obj_new(mrb, mrb_class_get(mrb, "Matrix"), 2, args); mrb_matrix_get_data(mrb, result, &p_res); gsl_matrix_memcpy(p_res, p_data->mat); return result; } static mrb_value mrb_qr_tau(mrb_state *mrb, mrb_value self) { mrb_value result; qr_decomp_data_s *p_data = NULL; gsl_vector *p_res = NULL; mrb_value args[1]; // call utility for unwrapping @data into p_data: mrb_qr_decomp_get_data(mrb, self, &p_data); args[0] = mrb_fixnum_value(p_data->minsize); result = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args); mrb_vector_get_data(mrb, result, &p_res); gsl_vector_memcpy(p_res, p_data->tau); return result; } #pragma mark - #pragma mark • Operations // int gsl_linalg_QR_solve (const gsl_matrix * QR, const gsl_vector * tau, const // gsl_vector * b, gsl_vector * x) static mrb_value mrb_qr_solve(mrb_state *mrb, mrb_value self) { mrb_value result, b_vec; qr_decomp_data_s *p_data = NULL; gsl_vector *p_result = NULL, *p_b = NULL; mrb_value args[1]; mrb_get_args(mrb, "o", &b_vec); if (!mrb_obj_is_kind_of(mrb, b_vec, mrb_class_get(mrb, "Vector"))) { mrb_raise(mrb, E_ARGUMENT_ERROR, "Argument must be a Vector"); } // call utility for unwrapping @data into p_data: mrb_qr_decomp_get_data(mrb, self, &p_data); if (p_data->size1 != p_data->size2) { mrb_raise(mrb, E_QR_DECOMP_ERROR, "Matrix must be square"); } args[0] = mrb_fixnum_value(p_data->tau->size); result = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args); mrb_vector_get_data(mrb, result, &p_result); mrb_vector_get_data(mrb, b_vec, &p_b); if (gsl_linalg_QR_solve(p_data->mat, p_data->tau, p_b, p_result)) { mrb_raise(mrb, E_QR_DECOMP_ERROR, "Singular matrix"); } mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@residuals"), mrb_nil_value()); return result; } // int gsl_linalg_QR_lssolve (const gsl_matrix * QR, const gsl_vector * tau, // const gsl_vector * b, gsl_vector * x, gsl_vector * residual) static mrb_value mrb_qr_lssolve(mrb_state *mrb, mrb_value self) { mrb_value result, b_vec, residuals; qr_decomp_data_s *p_data = NULL; gsl_vector *p_result = NULL, *p_b = NULL, *p_residuals; mrb_value args[1]; mrb_get_args(mrb, "o", &b_vec); if (!mrb_obj_is_kind_of(mrb, b_vec, mrb_class_get(mrb, "Vector"))) { mrb_raise(mrb, E_ARGUMENT_ERROR, "Argument must be a Vector"); } // call utility for unwrapping @data into p_data: mrb_qr_decomp_get_data(mrb, self, &p_data); if (p_data->size1 <= p_data->size2) { mrb_raise(mrb, E_QR_DECOMP_ERROR, "Matrix must have more rows than columns"); } args[0] = mrb_fixnum_value(p_data->size2); result = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args); mrb_vector_get_data(mrb, result, &p_result); mrb_vector_get_data(mrb, b_vec, &p_b); args[0] = mrb_fixnum_value(p_b->size); residuals = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args); mrb_vector_get_data(mrb, residuals, &p_residuals); mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@residuals"), residuals); if (gsl_linalg_QR_lssolve(p_data->mat, p_data->tau, p_b, p_result, p_residuals)) { mrb_raise(mrb, E_QR_DECOMP_ERROR, "Singular matrix"); } return result; } #pragma mark - #pragma mark • Gem setup void mrb_gsl_qr_decomp_init(mrb_state *mrb) { struct RClass *lu; mrb_load_string(mrb, "class QRDecompError < Exception; end"); lu = mrb_define_class(mrb, "QRDecomp", mrb->object_class); mrb_define_method(mrb, lu, "residuals", mrb_qr_residuals, MRB_ARGS_NONE()); mrb_define_method(mrb, lu, "matrix", mrb_qr_matrix, MRB_ARGS_NONE()); mrb_define_method(mrb, lu, "tau", mrb_qr_tau, MRB_ARGS_NONE()); mrb_define_method(mrb, lu, "size1", mrb_qr_size1, MRB_ARGS_NONE()); mrb_define_method(mrb, lu, "size2", mrb_qr_size2, MRB_ARGS_NONE()); mrb_define_method(mrb, lu, "minsize", mrb_qr_minsize, MRB_ARGS_NONE()); mrb_define_method(mrb, lu, "initialize", mrb_qr_initialize, MRB_ARGS_REQ(1)); mrb_define_method(mrb, lu, "solve", mrb_qr_solve, MRB_ARGS_REQ(1)); mrb_define_method(mrb, lu, "lssolve", mrb_qr_lssolve, MRB_ARGS_REQ(1)); }
{ "alphanum_fraction": 0.6288196817, "avg_line_length": 38.9467680608, "ext": "c", "hexsha": "3f767de5f3058bf3d5e76d817e4bad30547638a9", "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": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_forks_repo_path": "src/QR_decomp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "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": "UniTN-Mechatronics/mruby-gsl", "max_issues_repo_path": "src/QR_decomp.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_stars_repo_path": "src/QR_decomp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2794, "size": 10243 }
/* ODE: a program to get optime Runge-Kutta and multi-steps methods. Copyright 2011-2019, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file rk_3_3.c * \brief Source file to optimize Runge-Kutta 3 steps 3rd order methods. * \author Javier Burguete Tolosa. * \copyright Copyright 2011-2019. */ #define _GNU_SOURCE #include <string.h> #include <math.h> #include <libxml/parser.h> #include <glib.h> #include <libintl.h> #include <gsl/gsl_rng.h> #include "config.h" #include "utils.h" #include "optimize.h" #include "rk.h" #include "rk_3_3.h" #define DEBUG_RK_3_3 0 ///< macro to debug. /** * Function to obtain the coefficients of a 3 steps 3rd order Runge-Kutta * method. */ int rk_tb_3_3 (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t3 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (b32 (tb))) return 0; b31 (tb) = (1.L / 3.L - 0.5L * t2 (tb)) / (t1 (tb) * (t1 (tb) - t2 (tb))); if (isnan (b31 (tb))) return 0; b21 (tb) = 1 / 6.L / (b32 (tb) * t1 (tb)); if (isnan (b21 (tb))) return 0; rk_b_3 (tb); #if DEBUG_RK_3_3 rk_print_tb (optimize, "rk_tb_3_3", stderr); fprintf (stderr, "rk_tb_3_3: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 3rd order, 4th order in * equations depending only in time, Runge-Kutta method. */ int rk_tb_3_3t (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3t: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t3 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = (4.L * t1 (tb) - 3.L) / (6.L * t1 (tb) - 4.L); if (isnan (t2 (tb))) return 0; b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb))); if ((b32 (tb))) return 0; b31 (tb) = (1.L / 3.L - 0.5L * t2 (tb)) / (t1 (tb) * (t1 (tb) - t2 (tb))); if (isnan (b31 (tb))) return 0; b21 (tb) = 1 / 6.L / (b32 (tb) * t1 (tb)); if (isnan (b21 (tb))) return 0; rk_b_3 (tb); #if DEBUG_RK_3_3 rk_print_tb (optimize, "rk_tb_3_3t", stderr); fprintf (stderr, "rk_tb_3_3t: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 2nd-3rd order Runge-Kutta * pair. */ int rk_tb_3_3p (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3p: start\n"); #endif if (!rk_tb_3_3 (optimize)) return 0; tb = optimize->coefficient; e31 (tb) = 0.5L / t1 (tb); rk_e_3 (tb); #if DEBUG_RK_3_3 rk_print_e (optimize, "rk_tb_3_3p", stderr); fprintf (stderr, "rk_tb_3_3p: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 2nd-3rd order, 2nd-4th order * in equations depending only in time, Runge-Kutta pair. */ int rk_tb_3_3tp (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3tp: start\n"); #endif if (!rk_tb_3_3t (optimize)) return 0; tb = optimize->coefficient; e31 (tb) = 0.5L / t1 (tb); rk_e_3 (tb); #if DEBUG_RK_3_3 rk_print_e (optimize, "rk_tb_3_3tp", stderr); fprintf (stderr, "rk_tb_3_3tp: end\n"); #endif return 1; } /** * Function to calculate the objective function of a 3 steps 3rd order * Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_3_3 (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3: end\n"); #endif return o; } /** * Function to calculate the objective function of a 3 steps 3rd order, 4th * order in equations depending only in time, Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_3_3t (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3t: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3: optimal=%Lg\n", o); #endif if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3t: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3t: end\n"); #endif return o; } /** * Function to calculate the objective function of a 3 steps 2nd-3rd order * Runge-Kutta pair. * * \return objective function value. */ long double rk_objective_tb_3_3p (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3p: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (e30 (tb) < 0.L) o += e30 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3p: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3p: end\n"); #endif return o; } /** * Function to calculate the objective function of a 3 steps 2nd-3rd order, * 3rd-4th order in equations depending only in time, Runge-Kutta pair. * * \return objective function value. */ long double rk_objective_tb_3_3tp (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3tp: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (e30 (tb) < 0.L) o += e30 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3p: optimal=%Lg\n", o); #endif if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3tp: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3tp: end\n"); #endif return o; }
{ "alphanum_fraction": 0.6207498836, "avg_line_length": 24.9651162791, "ext": "c", "hexsha": "85be9a9d042873a2d2d600fdf1d39113cf7423c2", "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": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/ode", "max_forks_repo_path": "rk_3_3.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/ode", "max_issues_repo_path": "rk_3_3.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/ode", "max_stars_repo_path": "rk_3_3.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3147, "size": 8588 }
/* specfunc/bessel_Ynu.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_bessel.h" #include "error.h" #include "bessel.h" #include "bessel_olver.h" #include "bessel_temme.h" /* Perform forward recurrence for Y_nu(x) and Y'_nu(x) * * Y_{nu+1} = nu/x Y_nu - Y'_nu * Y'_{nu+1} = -(nu+1)/x Y_{nu+1} + Y_nu */ #if 0 static int bessel_Y_recur(const double nu_min, const double x, const int kmax, const double Y_start, const double Yp_start, double * Y_end, double * Yp_end) { double x_inv = 1.0/x; double nu = nu_min; double Y_nu = Y_start; double Yp_nu = Yp_start; int k; for(k=1; k<=kmax; k++) { double nuox = nu*x_inv; double Y_nu_save = Y_nu; Y_nu = -Yp_nu + nuox * Y_nu; Yp_nu = Y_nu_save - (nuox+x_inv) * Y_nu; nu += 1.0; } *Y_end = Y_nu; *Yp_end = Yp_nu; return GSL_SUCCESS; } #endif /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0 || nu < 0.0) { DOMAIN_ERROR(result); } else if(nu > 50.0) { return gsl_sf_bessel_Ynu_asymp_Olver_e(nu, x, result); } else { /* -1/2 <= mu <= 1/2 */ int N = (int)(nu + 0.5); double mu = nu - N; gsl_sf_result Y_mu, Y_mup1; int stat_mu; double Ynm1; double Yn; double Ynp1; int n; if(x < 2.0) { /* Determine Ymu, Ymup1 directly. This is really * an optimization since this case could as well * be handled by a call to gsl_sf_bessel_JY_mu_restricted(), * as below. */ stat_mu = gsl_sf_bessel_Y_temme(mu, x, &Y_mu, &Y_mup1); } else { /* Determine Ymu, Ymup1 and Jmu, Jmup1. */ gsl_sf_result J_mu, J_mup1; stat_mu = gsl_sf_bessel_JY_mu_restricted(mu, x, &J_mu, &J_mup1, &Y_mu, &Y_mup1); } /* Forward recursion to get Ynu, Ynup1. */ Ynm1 = Y_mu.val; Yn = Y_mup1.val; for(n=1; n<=N; n++) { Ynp1 = 2.0*(mu+n)/x * Yn - Ynm1; Ynm1 = Yn; Yn = Ynp1; } result->val = Ynm1; /* Y_nu */ result->err = (N + 1.0) * fabs(Ynm1) * (fabs(Y_mu.err/Y_mu.val) + fabs(Y_mup1.err/Y_mup1.val)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(Ynm1); return stat_mu; } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_Ynu(const double nu, const double x) { EVAL_RESULT(gsl_sf_bessel_Ynu_e(nu, x, &result)); }
{ "alphanum_fraction": 0.6109955423, "avg_line_length": 25.4924242424, "ext": "c", "hexsha": "6453ea1ca3a89f16e85f5ad355d85365a0de3003", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Ynu.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Ynu.c", "max_line_length": 100, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Ynu.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": 1146, "size": 3365 }
#pragma once #include <gsl/span> #include <cstddef> namespace imageview { // Class representing a color in RGB24 color space. class RGB24 { public: constexpr RGB24() noexcept = default; // Construct an RGB24 color from the given channel components. constexpr RGB24(unsigned char red, unsigned char green, unsigned char blue) noexcept : red(red), green(green), blue(blue) {} unsigned char red = 0; unsigned char green = 0; unsigned char blue = 0; }; // Implementation of the PixelFormat concept for RGB24 pixel format. // In this pixel format the color is represented via 3 8-bit integers, // specifying the red, green and blue channels. When serializing to / // deserializing from a byte array, the order of the channels is RGB (i.e. // not BGR). class PixelFormatRGB24 { public: using color_type = RGB24; static constexpr int kBytesPerPixel = 3; constexpr color_type read(gsl::span<const std::byte, kBytesPerPixel> data) const; constexpr void write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const; }; constexpr bool operator==(const RGB24& lhs, const RGB24& rhs) { return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue; } constexpr bool operator!=(const RGB24& lhs, const RGB24& rhs) { return !(lhs == rhs); } constexpr PixelFormatRGB24::color_type PixelFormatRGB24::read(gsl::span<const std::byte, kBytesPerPixel> data) const { return color_type(static_cast<unsigned char>(data[0]), static_cast<unsigned char>(data[1]), static_cast<unsigned char>(data[2])); } constexpr void PixelFormatRGB24::write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const { data[0] = static_cast<std::byte>(color.red); data[1] = static_cast<std::byte>(color.green); data[2] = static_cast<std::byte>(color.blue); } } // namespace imageview
{ "alphanum_fraction": 0.71712292, "avg_line_length": 33.8727272727, "ext": "h", "hexsha": "02317de13ff5be00a6ca8ad4d7c49d58b84dced6", "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": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_path": "include/imageview/pixel_formats/PixelFormatRGB24.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "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": "alexanderbelous/imageview", "max_issues_repo_path": "include/imageview/pixel_formats/PixelFormatRGB24.h", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_path": "include/imageview/pixel_formats/PixelFormatRGB24.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 468, "size": 1863 }
// Copyright Jean Pierre Cimalando 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <gsl/gsl> template <class Ch> bool string_starts_with(gsl::basic_string_span<const Ch> text, gsl::basic_string_span<const Ch> prefix); template <class Ch> bool string_ends_with(gsl::basic_string_span<const Ch> text, gsl::basic_string_span<const Ch> suffix); #include "strings.tcc"
{ "alphanum_fraction": 0.7418111753, "avg_line_length": 39.9230769231, "ext": "h", "hexsha": "a797da37f186189a37bbf2174d13dc452406892a", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_path": "sources/utility/strings.h", "max_issues_count": 19, "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_path": "sources/utility/strings.h", "max_line_length": 124, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_path": "sources/utility/strings.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "num_tokens": 128, "size": 519 }
/* $Id$ */ /* * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <inttypes.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <cairo.h> #include <cairo-pdf.h> #include <cairo-ps.h> #include <gtk/gtk.h> #include <gsl/gsl_multifit.h> #include <kplot.h> #include "extern.h" enum savetype { SAVE_PDF, SAVE_PS, SAVE_EPS }; static int savepng(const gchar *fname, const struct curwin *c) { cairo_surface_t *surf; cairo_t *cr; cairo_status_t st; g_debug("%p: Saving: %s", c, fname); surf = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 600, 400); st = cairo_surface_status(surf); if (CAIRO_STATUS_SUCCESS != st) { g_debug("%s", cairo_status_to_string(st)); cairo_surface_destroy(surf); return(0); } cr = cairo_create(surf); cairo_surface_destroy(surf); st = cairo_status(cr); if (CAIRO_STATUS_SUCCESS != st) { g_debug("%s", cairo_status_to_string(st)); cairo_destroy(cr); return(0); } cairo_set_source_rgb(cr, 1.0, 1.0, 1.0); cairo_rectangle(cr, 0.0, 0.0, 600.0, 400.0); cairo_fill(cr); kplot_draw(c->views[c->view], 600.0, 400.0, cr); st = cairo_surface_write_to_png(cairo_get_target(cr), fname); if (CAIRO_STATUS_SUCCESS != st) { g_debug("%s", cairo_status_to_string(st)); cairo_destroy(cr); return(0); } cairo_destroy(cr); return(1); } static int savepdf(const gchar *fname, struct curwin *c, enum savetype type) { cairo_surface_t *surf; cairo_t *cr; cairo_status_t st; struct kplotcfg *cfg; struct kdatacfg *datas; size_t datasz, i, j; int rc; double svtic, svaxis, svborder, svgrid, sv, svticln; const double w = 72 * 6, h = 72 * 5; g_debug("%p: Saving: %s", c, fname); switch (type) { case (SAVE_PDF): surf = cairo_pdf_surface_create(fname, w, h); break; case (SAVE_EPS): surf = cairo_ps_surface_create(fname, w, h); cairo_ps_surface_set_eps(surf, 1); break; case (SAVE_PS): surf = cairo_ps_surface_create(fname, w, h); cairo_ps_surface_set_eps(surf, 0); break; default: abort(); } st = cairo_surface_status(surf); if (CAIRO_STATUS_SUCCESS != st) { g_debug("%s", cairo_status_to_string(st)); cairo_surface_destroy(surf); return(0); } cr = cairo_create(surf); cairo_surface_destroy(surf); st = cairo_status(cr); if (CAIRO_STATUS_SUCCESS != st) { g_debug("%s", cairo_status_to_string(st)); cairo_destroy(cr); return(0); } cfg = kplot_get_plotcfg(c->views[c->view]); svtic = cfg->ticlabelfont.sz; svaxis = cfg->axislabelfont.sz; svborder = cfg->borderline.sz; svgrid = cfg->gridline.sz; svticln = cfg->ticline.sz; sv = 0.0; /* Silence compiler. */ cfg->ticlabelfont.sz = 9.0; cfg->axislabelfont.sz = 9.0; cfg->borderline.sz = 0.5; cfg->gridline.sz = 0.5; cfg->ticline.sz = 0.5; for (i = 0; ; i++) { rc = kplot_get_datacfg(c->views[c->view], i, &datas, &datasz); if (0 == rc) break; for (j = 0; j < datasz; j++) { sv = datas[j].line.sz; datas[j].line.sz = 1.0; } } cairo_set_source_rgb(cr, 1.0, 1.0, 1.0); cairo_rectangle(cr, 0.0, 0.0, w, h); cairo_fill(cr); kplot_draw(c->views[c->view], w, h, cr); cairo_destroy(cr); cfg->ticlabelfont.sz = svtic; cfg->axislabelfont.sz = svaxis; cfg->borderline.sz = svborder; cfg->gridline.sz = svgrid; cfg->ticline.sz = svticln; for (i = 0; ; i++) { rc = kplot_get_datacfg(c->views[c->view], i, &datas, &datasz); if (0 == rc) break; for (j = 0; j < datasz; j++) datas[j].line.sz = sv; } return(1); } int save(const gchar *fname, struct curwin *cur) { if (g_str_has_suffix(fname, ".pdf")) return(savepdf(fname, cur, SAVE_PDF)); else if (g_str_has_suffix(fname, ".ps")) return(savepdf(fname, cur, SAVE_PS)); else if (g_str_has_suffix(fname, ".eps")) return(savepdf(fname, cur, SAVE_EPS)); else return(savepng(fname, cur)); } int saveconfig(const gchar *fname, const struct curwin *cur) { FILE *f; struct sim *sim; GList *l; g_debug("%p: Saving configuration: %s", cur, fname); if (NULL == (f = fopen(fname, "w"))) { g_debug("%s: %s", fname, strerror(errno)); return(0); } for (l = cur->sims; NULL != l; l = g_list_next(l)) { sim = l->data; fprintf(f, "Name: %s\n", sim->name); fprintf(f, "Colour: #%.2x%.2x%.2x\n", (unsigned int)(cur->b->clrs[sim->colour].rgba[0] * 255), (unsigned int)(cur->b->clrs[sim->colour].rgba[1] * 255), (unsigned int)(cur->b->clrs[sim->colour].rgba[2] * 255)); fprintf(f, "Function: %s\n", sim->func); fprintf(f, "Threads: %zu\n", sim->nprocs); fprintf(f, "Multiplier: %g(1 + %g lambda)\n", sim->alpha, sim->delta); fprintf(f, "Max generations: %zu\n", sim->stop); fprintf(f, "Migration: %g (%suniform)\n", sim->m, NULL != sim->ms ? "non-" : ""); fprintf(f, "Incumbents: %zu, [%g,%g)\n", sim->dims, sim->xmin, sim->xmax); fprintf(f, "Rolling average window: %zu\n", sim->smoothing); switch (sim->maptop) { case (MAPTOP_RECORD): fprintf(f, "Map: record-based\n"); break; case (MAPTOP_RAND): fprintf(f, "Map: random\n"); break; case (MAPTOP_TORUS): fprintf(f, "Map: torus\n"); break; default: abort(); } switch (sim->migrant) { case (MAPMIGRANT_UNIFORM): fprintf(f, "Migration: uniform\n"); break; case (MAPMIGRANT_DISTANCE): fprintf(f, "Migration: distance\n"); break; case (MAPMIGRANT_NEAREST): fprintf(f, "Migration: nearest\n"); break; case (MAPMIGRANT_TWONEAREST): fprintf(f, "Migration: two nearest\n"); break; default: abort(); } if (MAPINDEX_STRIPED == sim->mapindex) fprintf(f, "Mutant index case: striped\n"); else fprintf(f, "Mutant index case: fixed (%zu)\n", sim->mapindexfix); if (MUTANTS_DISCRETE == sim->mutants) fprintf(f, "Mutants: %zu, [%g,%g)\n", sim->dims, sim->ymin, sim->ymax); else fprintf(f, "Mutants: N(sigma=%g), [%g,%g)\n", sim->mutantsigma, sim->ymin, sim->ymax); fprintf(f, "Islands: %zu (%zu islanders)\n", sim->islands, sim->totalpop); if (NULL != sim->pops) fprintf(f, "Island populations: non-uniform\n"); else fprintf(f, "Island populations: %zu\n", sim->pop); fprintf(f, "Fit polynomial: %zu (%sweighted)\n", sim->fitpoly, 0 == sim->weighted ? "un" : ""); fprintf(f, "\n"); } fclose(f); return(1); }
{ "alphanum_fraction": 0.6498143388, "avg_line_length": 24.9181494662, "ext": "c", "hexsha": "6b8557cbfcc153baf568f540f3e8c90d89eaa203", "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": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_path": "save.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_path": "save.c", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_path": "save.c", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "num_tokens": 2300, "size": 7002 }
/* * This code is to merge all the files among different directories once the MCRaT simulation is complete * The input should be the main CMC directory and the sub directories of each angle range with the number of MPI processes used to start the simulation in each directory * eg call: mpiexec -np X /.merge /dir/to/CMC_dir/ * where X shuould be a multiple of the number of sub directories * SHOULD BE COMPILED WITH -O2 OPTIMIZATION */ //TEST WITH PROCESSES INJECTING IN MULTIPLE FRAMES #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <math.h> #include <gsl/gsl_rng.h> #include "hdf5.h" #include "mclib.h" #include "mpi.h" int main(int argc, char **argv) { double *p0=NULL, *p1=NULL, *p2=NULL, *p3=NULL, *comv_p0=NULL, *comv_p1=NULL, *comv_p2=NULL, *comv_p3=NULL, *r0=NULL, *r1=NULL, *r2=NULL, *s0=NULL, *s1=NULL, *s2=NULL, *s3=NULL, *num_scatt=NULL, *weight=NULL; double *p0_p=NULL, *p1_p=NULL, *p2_p=NULL, *p3_p=NULL, *comv_p0_p=NULL, *comv_p1_p=NULL, *comv_p2_p=NULL, *comv_p3_p=NULL, *r0_p=NULL, *r1_p=NULL, *r2_p=NULL, *s0_p=NULL, *s1_p=NULL, *s2_p=NULL, *s3_p=NULL, *num_scatt_p=NULL, *weight_p=NULL; int num_angle_dirs=0, i=0, j=0, k=0, l=0, num_types=12; int *num_procs_per_dir=NULL, frm0_small, frm0_large, last_frm, frm2_small, frm2_large, small_frm, large_frm, frm=0, all_photons; int *frm_array=NULL, *each_subdir_number=NULL, *displPtr=NULL; int myid, numprocs, subdir_procs, subdir_id, frames_to_merge, start_count, end_count ; int count=0, index=0, isNotCorrupted=0; int file_count = 0, max_num_procs_per_dir=0; int *photon_injection_count=NULL; double garbage; char mc_file[500]="" ; char dir[500]=""; char group[500]=""; char merged_filename[500]=""; char filename_k[2000]="", mcdata_type[20]=""; char *str="mc_proc_", *ph_type=NULL, *ph_type_p=NULL; struct dirent* dent; DIR * dirp; struct dirent * entry; DIR* srcdir = opendir(argv[1]); MPI_Datatype stype; hid_t file, file_id, group_id, dspace, fspace, mspace; /* file and dataset identifiers */ hid_t plist_id_file, plist_id_data; /* property list identifier( access template) */ hsize_t dims[1]={0},dims_old[1]={0}; hsize_t maxdims[1]={H5S_UNLIMITED}; hsize_t size[1]; hsize_t offset[1]; herr_t status, status_group; hid_t dset_p0, dset_p1, dset_p2, dset_p3, dset_comv_p0, dset_comv_p1, dset_comv_p2, dset_comv_p3, dset_r0, dset_r1, dset_r2, dset_s0, dset_s1, dset_s2, dset_s3, dset_num_scatt, dset_weight, dset_ph_type; #if COMV_SWITCH == ON && STOKES_SWITCH == ON { num_types=17;//both switches on, want to save comv and stokes } #elif COMV_SWITCH == ON || STOKES_SWITCH == ON { num_types=13;//either switch acivated, just subtract 4 datasets } #else { num_types=9;//just save lab 4 momentum, position and num_scatt } #endif #if SAVE_TYPE == ON { num_types+=1; } #endif while((dent = readdir(srcdir)) != NULL) { struct stat st; //file_count=0; if(strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue; if (fstatat(dirfd(srcdir), dent->d_name, &st, 0) < 0) { perror(dent->d_name); continue; } if (S_ISDIR(st.st_mode)) { //snprintf(dir,sizeof(dir),"%s",dent->d_name ); if (strstr(dent->d_name, "ALL_DATA") == NULL) { num_angle_dirs++; //printf("found directory %s\n", dent->d_name); } } } closedir(srcdir); num_procs_per_dir=malloc(num_angle_dirs*sizeof(int)); each_subdir_number=malloc(num_angle_dirs*sizeof(int)); displPtr=malloc(num_angle_dirs*sizeof(int)); *(displPtr+0)=0; char *dirs[num_angle_dirs]; count=0; srcdir = opendir(argv[1]); while((dent = readdir(srcdir)) != NULL) { struct stat st; file_count=0; if(strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue; if (fstatat(dirfd(srcdir), dent->d_name, &st, 0) < 0) { perror(dent->d_name); continue; } if (S_ISDIR(st.st_mode)) { //printf("found directory %s\n", dent->d_name); if (strstr(dent->d_name, "ALL_DATA") == NULL) { snprintf(dir,sizeof(dir),"%s%s/",argv[1],dent->d_name ); dirs[count] = malloc((strlen(dir)+1)); strcpy(dirs[count],dir); //printf("SECOND: found directory %s\n", dirs[count]); dirp = opendir(dir); //do into the directory to get each file while ((entry = readdir(dirp)) != NULL) { if ((entry->d_type == DT_REG) && (strstr(entry->d_name, str) != NULL)) { /* If the entry is a regular file */ file_count++; //printf("%s\n", entry->d_name ); } } *(num_procs_per_dir +count)=file_count; if (max_num_procs_per_dir<file_count) { max_num_procs_per_dir=file_count; //find the max number of processes in each directory } count++; } } } closedir(srcdir); //find number of directories for each angle range //printf("%s: %d\n", argv[1], num_angle_dirs); //for (i=0;i<num_angle_dirs;i++) //{ // printf("%d\n", *(num_procs_per_dir+i)); // printf(" %s\n", dirs[i]); //} //get the last and initial hydro file in sim snprintf(mc_file,sizeof(mc_file),"%s%s",argv[1],MCPAR); readMcPar(mc_file, &garbage, &garbage, &garbage,&garbage, &garbage, &garbage, &garbage,&garbage, &frm0_small,&frm0_large, &last_frm ,&frm2_small, &frm2_large, &garbage, &garbage, &i, &i, &i,&i); //thetas that comes out is in degrees //printf("%s frm_0small: %d frm_0large: %d, last: %d\n", mc_file, frm0_small,frm0_large, last_frm); //with all the info make array of all the files that need to be created small_frm= (frm0_small < frm0_large) ? frm0_small : frm0_large; large_frm= (frm2_small > frm2_large) ? frm2_small : frm2_large; frm_array=malloc(sizeof(int)*(last_frm-small_frm+1)); count=0; for (i=small_frm;i<last_frm+1;i++) { //printf("Count: %d\n",count); *(frm_array+count)=i; count++; } //set up the ALL_DATA directory name snprintf(dir,sizeof(dir),"%sALL_DATA/",argv[1] ); //set up MPI and break up the processes into groups of the number of sub directories MPI_Init(NULL,NULL); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); //break up into groups by subdir index= myid/num_angle_dirs; MPI_Comm frames_to_merge_comm; MPI_Comm_split(MPI_COMM_WORLD, index , myid, &frames_to_merge_comm); MPI_Comm_rank(frames_to_merge_comm, &subdir_id); MPI_Comm_size(frames_to_merge_comm, &subdir_procs); frames_to_merge=(count-1)/(numprocs/num_angle_dirs); //count-1 b/c @ end of loop it added 1 start_count=*(frm_array+(index*frames_to_merge)); end_count=*(frm_array+((index+1)*frames_to_merge)); if (index==(numprocs/num_angle_dirs)-1) { //printf("in If\n"); end_count=*(frm_array+(count-1))+1; } printf("subdir_id %d, subdir_procs %d subdir %s, num of frames to merge %d, index %d\n", subdir_id, subdir_procs, dirs[subdir_id], frames_to_merge, index ); printf("Start file %d end file %d\n", start_count, end_count); //exit(0); if (myid==0) { //have 1st process see if the folder ALL_DATA exists and if not create it dirp = opendir(dir); if (ENOENT == errno) { //if it doesnt exist create it mkdir(dir, 0777); //make the directory with full permissions } else { closedir(dirp); } } //directory exists now, can create files in it with appropriate datasets, all processes in communicator participate in this //Set up file access property list with parallel I/O access MPI_Info info = MPI_INFO_NULL; photon_injection_count=malloc((*(num_procs_per_dir+subdir_id))*sizeof(int)); //to incrememnt the number of photons already injected by a process for (k=0;k<*(num_procs_per_dir+subdir_id);k++) { *(photon_injection_count+k)=0; } //create files //start_count=2474; //end_count=143; for (i= end_count-1; i>=start_count;i--) { //go through the mpi files to find the total number of photons needed for the final dataset //printf("\n\n%d\n", i); dims[0]=0; j=0; for (k=0;k<*(num_procs_per_dir+subdir_id);k++) { //for each process' file, find out how many elements and add up to find total number of elements needed in the data set for the frame number snprintf(filename_k,sizeof(filename_k),"%s%s%d%s",dirs[subdir_id],"mc_proc_", k, ".h5" ); //printf("Dir: %s\n",filename_k ); //open the file file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT); //see if the frame exists snprintf(group,sizeof(group),"%d",i ); status = H5Eset_auto(NULL, NULL, NULL); status_group = H5Gget_objinfo (file, group, 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); //if it does open it and read in the size if (status_group == 0) { //open the datatset group_id = H5Gopen2(file, group, H5P_DEFAULT); dset_p0 = H5Dopen (group_id, "P0", H5P_DEFAULT); //open dataset //get the number of points dspace = H5Dget_space (dset_p0); status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims j+=dims[0];//calculate the total number of photons to save to new hdf5 file //printf("File %s num_ph %d\n", filename_k, j); status = H5Sclose (dspace); status = H5Dclose (dset_p0); status = H5Gclose(group_id); } status = H5Fclose(file); } //find total number of photons MPI_Allreduce(&j, &all_photons, 1, MPI_INT, MPI_SUM, frames_to_merge_comm); //get the number for each subdir for later use //MPI_Allgather(&j, 1, MPI_INT, each_subdir_number, 1, MPI_INT, frames_to_merge_comm); //set up the displacement of data //for (j=1;j<num_angle_dirs;j++) //{ // *(displPtr+j)=(*(displPtr+j-1))+(*(each_subdir_number+j-1)); //} //if (subdir_id==0) //{ // printf("Frame: %d Total photons %d\n", i, all_photons); //} plist_id_file = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_mpio(plist_id_file, frames_to_merge_comm, info); snprintf(merged_filename,sizeof(merged_filename),"%smcdata_%d.h5",dir, i ); status = H5Eset_auto(NULL, NULL, NULL); //turn off automatic error printing file_id = H5Fcreate(merged_filename, H5F_ACC_EXCL, H5P_DEFAULT, plist_id_file); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); //turn on auto error printing //if the file exists we have to check it to ensure its not corrupted if (file_id<0) { //printf( "Checking File %s\n",merged_filename ); //the file exists, open it with read write file_id=H5Fopen(merged_filename, H5F_ACC_RDWR, plist_id_file); for (k=0;k<num_types;k++) { #if COMV_SWITCH == ON && STOKES_SWITCH == ON { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P1");break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P3"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 10: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 11: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S0"); break; case 12: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S1");break; case 13: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S2"); break; case 14: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S3"); break; case 15: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 16: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 17: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #elif STOKES_SWITCH == ON && COMV_SWITCH == OFF { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S0"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S1");break; case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S2"); break; case 10: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S3"); break; case 11: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 12: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 13: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #elif STOKES_SWITCH == OFF && COMV_SWITCH == ON { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P1");break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P3"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 10: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 11: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 12: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 13: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #else { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #endif //open the datatset dset_p0 = H5Dopen (file_id, mcdata_type, H5P_DEFAULT); //open dataset //get the number of points dspace = H5Dget_space (dset_p0); status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims //fprintf(fPtr, "j:%d, dim: %d\n",j, dims[0] ); //fflush(fPtr); isNotCorrupted += fmod(dims[0], all_photons); //if the dimension is the dame then the fmod ==0 (remainder of 0), if all datatsets are ==0 then you get a truth value of 0 meaning that it isnt corrupted status = H5Sclose (dspace); status = H5Dclose (dset_p0); } status = H5Fclose(file_id); file_id=-1; //do this so if the file exists it doesnt go into the rewriting portion just based on that } //printf("file %s has isNotCorrupted=%d\n", merged_filename, isNotCorrupted ); if ((file_id>=0) || (isNotCorrupted != 0 )) { if (isNotCorrupted != 0) { //if the data is corrupted overwrite the file file_id = H5Fcreate(merged_filename, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id_file); } frm=(i < large_frm) ? i : large_frm; for (k=0;k<*(num_procs_per_dir+subdir_id);k++) { *(photon_injection_count+k)=0; //reset the count to 0 } //order data based on which processes injected photons 1st #if SYNCHROTRON_SWITCH == ON l=i; #else for (l=small_frm;l<frm+1;l++) #endif { //printf("\n\n %d\n\n",l); //read the data in from each process in a given subdir, use max_num_procs_per_dir in case one directory used more processes than the others and deal with it in code for (k=0;k<max_num_procs_per_dir;k++) { dims[0]=0; j=0; //for each process' file, find out how many elements and add up to find total number of elements needed in the data set for the frame number snprintf(filename_k,sizeof(filename_k),"%s%s%d%s",dirs[subdir_id],"mc_proc_", k, ".h5" ); //printf("Dir: %s\n",filename_k ); if (k<*(num_procs_per_dir+subdir_id)) { //we know that the process exists and the file should exist //open the file status = H5Eset_auto(NULL, NULL, NULL); //turn of error printing if the file doesnt exist, if the process number doesnt exist file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); } else { //know that the process doesnt exist within that subdirectory so dont rry to open a non-existant file file=-1; } if (file>=0) { { //see if the frame exists /* snprintf(group,sizeof(group),"%d",i ); status = H5Eset_auto(NULL, NULL, NULL); status_group = H5Gget_objinfo (file, group, 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); */ snprintf(group,sizeof(group),"%d/PW",l ); status = H5Eset_auto(NULL, NULL, NULL); status_group = H5Gget_objinfo (file, group, 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); } } //if it does open it and read in the size //#if SYNCHROTRON_SWITCH == ON //if (status_group >= 0 && file>=0 && l>=i) //#else if (status_group >= 0 && file>=0) //#endif { //read in the number of injected photons first #if SYNCHROTRON_SWITCH == ON snprintf(group,sizeof(group),"%d",i ); #else snprintf(group,sizeof(group),"%d",l ); #endif group_id = H5Gopen2(file, group, H5P_DEFAULT); dset_weight = H5Dopen (group_id, "PW", H5P_DEFAULT); dspace = H5Dget_space (dset_weight); status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims j=dims[0];//calculate the total number of photons to save to new hdf5 file status = H5Sclose (dspace); status = H5Dclose (dset_weight); status = H5Gclose(group_id); //printf("Num of ph: %d\n", j); snprintf(group,sizeof(group),"%d",i ); //printf("Opening dataset\n"); //open the datatset group_id = H5Gopen2(file, group, H5P_DEFAULT); dset_p0 = H5Dopen (group_id, "P0", H5P_DEFAULT); //open dataset dset_p1 = H5Dopen (group_id, "P1", H5P_DEFAULT); dset_p2 = H5Dopen (group_id, "P2", H5P_DEFAULT); dset_p3 = H5Dopen (group_id, "P3", H5P_DEFAULT); #if COMV_SWITCH == ON { dset_comv_p0 = H5Dopen (group_id, "COMV_P0", H5P_DEFAULT); //open dataset dset_comv_p1 = H5Dopen (group_id, "COMV_P1", H5P_DEFAULT); dset_comv_p2 = H5Dopen (group_id, "COMV_P2", H5P_DEFAULT); dset_comv_p3 = H5Dopen (group_id, "COMV_P3", H5P_DEFAULT); } #endif dset_r0 = H5Dopen (group_id, "R0", H5P_DEFAULT); dset_r1 = H5Dopen (group_id, "R1", H5P_DEFAULT); dset_r2 = H5Dopen (group_id, "R2", H5P_DEFAULT); #if STOKES_SWITCH == ON { dset_s0 = H5Dopen (group_id, "S0", H5P_DEFAULT); dset_s1 = H5Dopen (group_id, "S1", H5P_DEFAULT); dset_s2 = H5Dopen (group_id, "S2", H5P_DEFAULT); dset_s3 = H5Dopen (group_id, "S3", H5P_DEFAULT); } #endif dset_num_scatt = H5Dopen (group_id, "NS", H5P_DEFAULT); #if SYNCHROTRON_SWITCH == ON { dset_weight = H5Dopen (group_id, "PW", H5P_DEFAULT); } #else { dset_weight = H5Dopen (file, "PW", H5P_DEFAULT);//for non synch runs look at the global /PW dataset } #endif #if SAVE_TYPE == ON { dset_ph_type = H5Dopen (group_id, "PT", H5P_DEFAULT); } #endif //malloc memory p0_p=malloc(j*sizeof(double)); p1_p=malloc(j*sizeof(double)); p2_p=malloc(j*sizeof(double)); p3_p=malloc(j*sizeof(double)); #if COMV_SWITCH == ON { comv_p0_p=malloc(j*sizeof(double)); comv_p1_p=malloc(j*sizeof(double)); comv_p2_p=malloc(j*sizeof(double)); comv_p3_p=malloc(j*sizeof(double)); } #endif r0_p=malloc(j*sizeof(double)); r1_p=malloc(j*sizeof(double)); r2_p=malloc(j*sizeof(double)); #if STOKES_SWITCH == ON { s0_p=malloc(j*sizeof(double)); s1_p=malloc(j*sizeof(double)); s2_p=malloc(j*sizeof(double)); s3_p=malloc(j*sizeof(double)); } #endif #if SAVE_TYPE == ON { ph_type_p=malloc((j)*sizeof(char)); } #endif num_scatt_p=malloc(j*sizeof(double)); weight_p=malloc(j*sizeof(double)); //printf("file %d frame: %d, process %d start: %d, j: %d\n", i, l, k, *(photon_injection_count+k), dims[0]); #if SYNCHROTRON_SWITCH == ON { offset[0]=0; } #else { offset[0]=*(photon_injection_count+k); } #endif //have to read in the data from *(photon_injection_count+k) to *(photon_injection_count+k)+j mspace = H5Screate_simple (1, dims, NULL); dspace = H5Dget_space(dset_p0); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); //read the data in status = H5Dread(dset_p0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p0_p)); status = H5Sclose (dspace); status = H5Dclose (dset_p0); dspace = H5Dget_space(dset_p1); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_p1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p1_p)); status = H5Sclose (dspace); status = H5Dclose (dset_p1); dspace = H5Dget_space(dset_p2); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_p2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p2_p)); status = H5Sclose (dspace); status = H5Dclose (dset_p2); dspace = H5Dget_space(dset_p3); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_p3, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (p3_p)); status = H5Sclose (dspace); status = H5Dclose (dset_p3); #if COMV_SWITCH == ON { dspace = H5Dget_space(dset_comv_p0); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_comv_p0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p0_p)); status = H5Sclose (dspace); status = H5Dclose (dset_comv_p0); dspace = H5Dget_space(dset_comv_p1); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_comv_p1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p1_p)); status = H5Sclose (dspace); status = H5Dclose (dset_comv_p1); dspace = H5Dget_space(dset_comv_p2); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_comv_p2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p2_p)); status = H5Sclose (dspace); status = H5Dclose (dset_comv_p2); dspace = H5Dget_space(dset_comv_p3); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_comv_p3, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (comv_p3_p)); status = H5Sclose (dspace); status = H5Dclose (dset_comv_p3); } #endif dspace = H5Dget_space(dset_r0); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_r0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (r0_p)); status = H5Sclose (dspace); status = H5Dclose (dset_r0); dspace = H5Dget_space(dset_r1); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_r1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (r1_p)); status = H5Sclose (dspace); status = H5Dclose (dset_r1); dspace = H5Dget_space(dset_r2); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_r2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (r2_p)); status = H5Sclose (dspace); status = H5Dclose (dset_r2); #if STOKES_SWITCH == ON { dspace = H5Dget_space(dset_s0); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_s0, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s0_p)); status = H5Sclose (dspace); status = H5Dclose (dset_s0); dspace = H5Dget_space(dset_s1); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_s1, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s1_p)); status = H5Sclose (dspace); status = H5Dclose (dset_s1); dspace = H5Dget_space(dset_s2); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_s2, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s2_p)); status = H5Sclose (dspace); status = H5Dclose (dset_s2); dspace = H5Dget_space(dset_s3); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_s3, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (s3_p)); status = H5Sclose (dspace); status = H5Dclose (dset_s3); } #endif dspace = H5Dget_space(dset_num_scatt); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_num_scatt, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (num_scatt_p)); status = H5Sclose (dspace); status = H5Dclose (dset_num_scatt); //printf("Before Weight read\n"); dspace = H5Dget_space(dset_weight); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_weight, H5T_NATIVE_DOUBLE, mspace, dspace, H5P_DEFAULT, (weight_p)); status = H5Sclose (dspace); status = H5Dclose (dset_weight); //printf("After Weight read\n"); #if SAVE_TYPE == ON { dspace = H5Dget_space(dset_ph_type); status = H5Sselect_hyperslab (dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dread(dset_ph_type, H5T_NATIVE_CHAR, mspace, dspace, H5P_DEFAULT, (ph_type_p)); status = H5Sclose (dspace); status = H5Dclose (dset_ph_type); } #endif status = H5Sclose (mspace); status = H5Gclose(group_id); //#if SYNCHROTRON_SWITCH == ON //{ // *(photon_injection_count+k)+=0; //} //#else { *(photon_injection_count+k)+=j; } //#endif } else { //allocate memory so Allgather doesn't fail with NULL pointer j=1; p0_p=malloc(j*sizeof(double)); p1_p=malloc(j*sizeof(double)); p2_p=malloc(j*sizeof(double)); p3_p=malloc(j*sizeof(double)); #if COMV_SWITCH == ON { comv_p0_p=malloc(j*sizeof(double)); comv_p1_p=malloc(j*sizeof(double)); comv_p2_p=malloc(j*sizeof(double)); comv_p3_p=malloc(j*sizeof(double)); } #endif r0_p=malloc(j*sizeof(double)); r1_p=malloc(j*sizeof(double)); r2_p=malloc(j*sizeof(double)); #if STOKES_SWITCH == ON { s0_p=malloc(j*sizeof(double)); s1_p=malloc(j*sizeof(double)); s2_p=malloc(j*sizeof(double)); s3_p=malloc(j*sizeof(double)); } #endif #if SAVE_TYPE == ON { ph_type_p=malloc((j)*sizeof(char)); } #endif num_scatt_p=malloc(j*sizeof(double)); weight_p=malloc(j*sizeof(double)); } //find total number of photons MPI_Allreduce(&dims[0], &all_photons, 1, MPI_INT, MPI_SUM, frames_to_merge_comm); //dims[0]=all_photons; //printf("ID %d j: %d\n", subdir_id, dims[0]); //get the number for each subdir for later use MPI_Allgather(&dims[0], 1, MPI_INT, each_subdir_number, 1, MPI_INT, frames_to_merge_comm); //for (j=0;j<num_angle_dirs;j++) //{ // printf("ID %d eachsubdir_num %d \n", subdir_id, *(each_subdir_number+j)); //} //set up the displacement of data for (j=1;j<num_angle_dirs;j++) { *(displPtr+j)=(*(displPtr+j-1))+(*(each_subdir_number+j-1)); //printf("Displ %d eachsubdir_num %d \n", *(displPtr+j), *(each_subdir_number+j-1)); } //if (subdir_id==0) //{ // printf("Frame: %d Total photons %d\n", i, all_photons); //} //now allocate enough ememory for all_photons in the mpi files from proc 0 initially p0=malloc(all_photons*sizeof(double)); p1=malloc(all_photons*sizeof(double)); p2=malloc(all_photons*sizeof(double)); p3=malloc(all_photons*sizeof(double)); #if COMV_SWITCH == ON { comv_p0=malloc(all_photons*sizeof(double)); comv_p1=malloc(all_photons*sizeof(double)); comv_p2=malloc(all_photons*sizeof(double)); comv_p3=malloc(all_photons*sizeof(double)); } #endif r0=malloc(all_photons*sizeof(double)); r1=malloc(all_photons*sizeof(double)); r2=malloc(all_photons*sizeof(double)); #if STOKES_SWITCH == ON { s0=malloc(all_photons*sizeof(double)); s1=malloc(all_photons*sizeof(double)); s2=malloc(all_photons*sizeof(double)); s3=malloc(all_photons*sizeof(double)); } #endif #if SAVE_TYPE == ON { ph_type=malloc(all_photons*sizeof(char)); } #endif num_scatt=malloc(all_photons*sizeof(double)); weight=malloc(all_photons*sizeof(double)); //save data in correct order to p0, s0, r0, etc. in order of angle //MPI_Type_commit( &stype ); MPI_Allgatherv(p0_p, dims[0], MPI_DOUBLE, p0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(p1_p, dims[0], MPI_DOUBLE, p1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(p2_p, dims[0], MPI_DOUBLE, p2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(p3_p, dims[0], MPI_DOUBLE, p3, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); #if COMV_SWITCH == ON { MPI_Allgatherv(comv_p0_p, dims[0], MPI_DOUBLE, comv_p0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(comv_p1_p, dims[0], MPI_DOUBLE, comv_p1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(comv_p2_p, dims[0], MPI_DOUBLE, comv_p2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(comv_p3_p, dims[0], MPI_DOUBLE, comv_p3, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); } #endif MPI_Allgatherv(r0_p, dims[0], MPI_DOUBLE, r0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(r1_p, dims[0], MPI_DOUBLE, r1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(r2_p, dims[0], MPI_DOUBLE, r2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); #if STOKES_SWITCH == ON { MPI_Allgatherv(s0_p, dims[0], MPI_DOUBLE, s0, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(s1_p, dims[0], MPI_DOUBLE, s1, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(s2_p, dims[0], MPI_DOUBLE, s2, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(s3_p, dims[0], MPI_DOUBLE, s3, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); } #endif #if SAVE_TYPE == ON { MPI_Allgatherv(ph_type_p, dims[0], MPI_CHAR, ph_type, each_subdir_number, displPtr, MPI_CHAR, frames_to_merge_comm); } #endif MPI_Allgatherv(num_scatt_p, dims[0], MPI_DOUBLE, num_scatt, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); MPI_Allgatherv(weight_p, dims[0], MPI_DOUBLE, weight, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); /* if (subdir_id==0) { for (j=0;j<all_photons;j++) { printf("Read Data: %e Gathered data: %e\n", *(s0+j), *(s0_p+j)); } } */ //exit(0); dims[0]=all_photons; //if ((k==0) && (all_photons>0)) #if SYNCHROTRON_SWITCH == ON if ((l==i) && (k==0) && (all_photons>0)) #else if ((l==small_frm) && (all_photons>0)) #endif { //printf("IN THE IF STATEMENT\n"); //set up new dataset //create the datasets with the appropriate number of elements plist_id_data = H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (plist_id_data, 1, dims); dspace = H5Screate_simple (1, dims, maxdims); dset_p0=H5Dcreate2(file_id, "P0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_p1=H5Dcreate2(file_id, "P1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_p2=H5Dcreate2(file_id, "P2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_p3=H5Dcreate2(file_id, "P3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); #if COMV_SWITCH == ON { dset_comv_p0=H5Dcreate2(file_id, "COMV_P0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_comv_p1=H5Dcreate2(file_id, "COMV_P1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_comv_p2=H5Dcreate2(file_id, "COMV_P2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_comv_p3=H5Dcreate2(file_id, "COMV_P3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); } #endif dset_r0=H5Dcreate2(file_id, "R0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_r1=H5Dcreate2(file_id, "R1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_r2=H5Dcreate2(file_id, "R2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); #if STOKES_SWITCH == ON { dset_s0=H5Dcreate2(file_id, "S0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_s1=H5Dcreate2(file_id, "S1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_s2=H5Dcreate2(file_id, "S2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_s3=H5Dcreate2(file_id, "S3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); } #endif #if SAVE_TYPE == ON { dset_ph_type=H5Dcreate2(file_id, "PT", H5T_NATIVE_CHAR, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); } #endif dset_num_scatt=H5Dcreate2(file_id, "NS", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); dset_weight=H5Dcreate2(file_id, "PW", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); H5Pclose(plist_id_data); H5Sclose(dspace); plist_id_data = H5Pcreate (H5P_DATASET_XFER); H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE); //write data offset[0]=0; dspace = H5Dget_space(dset_p0); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p0); H5Sclose(dspace); dspace = H5Dget_space(dset_p1); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p1); H5Sclose(dspace); dspace = H5Dget_space(dset_p2); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p2); H5Sclose(dspace); dspace = H5Dget_space(dset_p3); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, p3); H5Sclose(dspace); #if COMV_SWITCH == ON { dspace = H5Dget_space(dset_comv_p0); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p0); H5Sclose(dspace); dspace = H5Dget_space(dset_comv_p1); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p1); H5Sclose(dspace); dspace = H5Dget_space(dset_comv_p2); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p2); H5Sclose(dspace); dspace = H5Dget_space(dset_comv_p3); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, comv_p3); H5Sclose(dspace); } #endif dspace = H5Dget_space(dset_r0); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, r0); H5Sclose(dspace); dspace = H5Dget_space(dset_r1); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, r1); H5Sclose(dspace); dspace = H5Dget_space(dset_r2); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, r2); H5Sclose(dspace); #if STOKES_SWITCH == ON { dspace = H5Dget_space(dset_s0); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, s0); H5Sclose(dspace); dspace = H5Dget_space(dset_s1); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, s1); H5Sclose(dspace); dspace = H5Dget_space(dset_s2); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, s2); H5Sclose(dspace); dspace = H5Dget_space(dset_s3); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, s3); H5Sclose(dspace); } #endif #if SAVE_TYPE == ON { dspace = H5Dget_space(dset_ph_type); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, plist_id_data, ph_type); H5Sclose(dspace); } #endif dspace = H5Dget_space(dset_num_scatt); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, num_scatt); H5Sclose(dspace); dspace = H5Dget_space(dset_weight); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, weight); H5Sclose(dspace); status = H5Dclose (dset_p0); status = H5Dclose (dset_p1); status = H5Dclose (dset_p2); status = H5Dclose (dset_p3); #if COMV_SWITCH == ON { status = H5Dclose (dset_comv_p0); status = H5Dclose (dset_comv_p1); status = H5Dclose (dset_comv_p2); status = H5Dclose (dset_comv_p3); } #endif status = H5Dclose (dset_r0); status = H5Dclose (dset_r1); status = H5Dclose (dset_r2); #if STOKES_SWITCH == ON { status = H5Dclose (dset_s0); status = H5Dclose (dset_s1); status = H5Dclose (dset_s2); status = H5Dclose (dset_s3); } #endif #if SAVE_TYPE == ON { status = H5Dclose (dset_ph_type); } #endif status = H5Dclose (dset_num_scatt); status = H5Dclose (dset_weight); H5Pclose(plist_id_data); } #if SYNCHROTRON_SWITCH == ON else #else else if ((l>small_frm) && (all_photons>0)) #endif { //printf("IN THE ELSE IF STATEMENT\n"); if ((k>0) && (all_photons>0)) plist_id_data = H5Pcreate (H5P_DATASET_XFER); H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE); dset_p0 = H5Dopen (file_id, "P0", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_p0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p0, size); fspace = H5Dget_space (dset_p0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_p0); dset_p1 = H5Dopen (file_id, "P1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_p1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p1, size); fspace = H5Dget_space (dset_p1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_p1); dset_p2 = H5Dopen (file_id, "P2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_p2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p2, size); fspace = H5Dget_space (dset_p2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_p2); dset_p3 = H5Dopen (file_id, "P3", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_p3); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p3, size); fspace = H5Dget_space (dset_p3); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, p3); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_p3); #if COMV_SWITCH == ON { dset_comv_p0 = H5Dopen (file_id, "COMV_P0", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p0, size); fspace = H5Dget_space (dset_comv_p0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_comv_p0); dset_comv_p1 = H5Dopen (file_id, "COMV_P1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p1, size); fspace = H5Dget_space (dset_comv_p1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_comv_p1); dset_comv_p2 = H5Dopen (file_id, "COMV_P2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p2, size); fspace = H5Dget_space (dset_comv_p2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_comv_p2); dset_comv_p3 = H5Dopen (file_id, "COMV_P3", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p3); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p3, size); fspace = H5Dget_space (dset_comv_p3); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, comv_p3); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_comv_p3); } #endif dset_r0 = H5Dopen (file_id, "R0", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_r0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_r0, size); fspace = H5Dget_space (dset_r0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, r0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_r0); dset_r1 = H5Dopen (file_id, "R1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_r1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_r1, size); fspace = H5Dget_space (dset_r1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, r1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_r1); dset_r2 = H5Dopen (file_id, "R2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_r2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_r2, size); fspace = H5Dget_space (dset_r2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, r2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_r2); #if STOKES_SWITCH == ON { dset_s0 = H5Dopen (file_id, "S0", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s0, size); fspace = H5Dget_space (dset_s0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_s0); dset_s1 = H5Dopen (file_id, "S1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s1, size); fspace = H5Dget_space (dset_s1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_s1); dset_s2 = H5Dopen (file_id, "S2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s2, size); fspace = H5Dget_space (dset_s2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_s2); dset_s3 = H5Dopen (file_id, "S3", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s3); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s3, size); fspace = H5Dget_space (dset_s3); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, s3); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_s3); } #endif #if SAVE_TYPE == ON { dset_ph_type = H5Dopen (file_id, "PT", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_ph_type); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_ph_type, size); fspace = H5Dget_space (dset_ph_type); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, mspace, fspace, plist_id_data, ph_type); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_ph_type); } #endif dset_num_scatt = H5Dopen (file_id, "NS", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_num_scatt); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_num_scatt, size); fspace = H5Dget_space (dset_num_scatt); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, num_scatt); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_num_scatt); //printf("Before weight write\n"); dset_weight = H5Dopen (file_id, "PW", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_weight); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_weight, size); fspace = H5Dget_space (dset_weight); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, weight); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_weight); //printf("After weight write\n"); H5Pclose(plist_id_data); } if (file>=0) { status = H5Fclose(file); } free(p0_p);free(p1_p); free(p2_p);free(p3_p); #if COMV_SWITCH == ON { free(comv_p0_p);free(comv_p1_p); free(comv_p2_p);free(comv_p3_p); } #endif free(r0_p);free(r1_p); free(r2_p); #if STOKES_SWITCH == ON { free(s0_p);free(s1_p); free(s2_p);free(s3_p); } #endif free(num_scatt_p); free(weight_p); #if SAVE_TYPE == ON { free(ph_type_p); } #endif free(p0);free(p1); free(p2);free(p3); #if COMV_SWITCH == ON { free(comv_p0);free(comv_p1); free(comv_p2);free(comv_p3); } #endif free(r0);free(r1); free(r2); #if STOKES_SWITCH == ON { free(s0);free(s1); free(s2);free(s3); } #endif free(num_scatt); free(weight); #if SAVE_TYPE == ON { free(ph_type); } #endif //exit(0); } } H5Fclose(file_id); } H5Pclose(plist_id_file); } /* if (index==0) { plist_id_file = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_mpio(plist_id_file, frames_to_merge_comm, info); //merge the weights in the same order snprintf(merged_filename,sizeof(merged_filename),"%smcdata_PW.h5",dir ); file_id = H5Fcreate(merged_filename, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id_file); for (i= small_frm; i<large_frm+1;i++) { //last_frm for (k=0;k<max_num_procs_per_dir;k++) { dims[0]=0; j=0; snprintf(filename_k,sizeof(filename_k),"%s%s%d%s",dirs[subdir_id],"mc_proc_", k, ".h5" ); //printf("Dir: %s\n",filename_k ); //open the file and see if t exists status = H5Eset_auto(NULL, NULL, NULL); //turn of error printing if the file doesnt exist, if the process number doesnt exist file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); if (file>=0) { //if the file exists, see if the frame exists snprintf(group,sizeof(group),"%d/PW",i ); status = H5Eset_auto(NULL, NULL, NULL); status_group = H5Gget_objinfo (file, group, 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); } //printf("Proc %d has status_group %d\n", subdir_id, status_group); if ((status_group == 0) && (file>=0)) { //read dataset and then snprintf(group,sizeof(group),"%d",i ); group_id = H5Gopen2(file, group, H5P_DEFAULT); dset_weight = H5Dopen (group_id, "PW", H5P_DEFAULT); //open dataset //get the number of points dspace = H5Dget_space (dset_weight); status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims j=dims[0];//calculate the total number of photons to save to new hdf5 file weight_p=malloc(j*sizeof(double)); status = H5Dread(dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (weight_p)); status = H5Sclose (dspace); status = H5Dclose (dset_weight); status = H5Gclose(group_id); } else { //theres nothing to read j=1; weight_p=malloc(j*sizeof(double)); } //find total number of photons MPI_Allreduce(&dims[0], &all_photons, 1, MPI_INT, MPI_SUM, frames_to_merge_comm); //printf("ID %d j: %d\n", subdir_id, dims[0]); //get the number for each subdir for later use MPI_Allgather(&dims[0], 1, MPI_INT, each_subdir_number, 1, MPI_INT, frames_to_merge_comm); //for (j=0;j<num_angle_dirs;j++) //{ // printf("ID %d eachsubdir_num %d \n", subdir_id, *(each_subdir_number+j)); //} //set up the displacement of data for (j=1;j<num_angle_dirs;j++) { *(displPtr+j)=(*(displPtr+j-1))+(*(each_subdir_number+j-1)); // printf("Displ %d eachsubdir_num %d \n", *(displPtr+j), *(each_subdir_number+j-1)); } weight=malloc(all_photons*sizeof(double)); //MPI_Type_commit( &stype ); MPI_Allgatherv(weight_p, dims[0], MPI_DOUBLE, weight, each_subdir_number, displPtr, MPI_DOUBLE, frames_to_merge_comm); dims[0]=all_photons; if ((i== small_frm) && (all_photons>0)) { //create new datatset plist_id_data = H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (plist_id_data, 1, dims); dspace = H5Screate_simple (1, dims, maxdims); dset_weight=H5Dcreate(file_id, "PW", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, plist_id_data, H5P_DEFAULT); H5Pclose(plist_id_data); H5Sclose(dspace); plist_id_data = H5Pcreate (H5P_DATASET_XFER); H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE); //write data offset[0]=0; dspace = H5Dget_space(dset_weight); status = H5Sselect_hyperslab(dspace, H5S_SELECT_SET, offset, NULL, dims, NULL); status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, plist_id_data, weight); H5Sclose(dspace); status = H5Dclose (dset_weight); H5Pclose(plist_id_data); } else if ((i != small_frm) && (all_photons>0)) { //extend the datatset plist_id_data = H5Pcreate (H5P_DATASET_XFER); H5Pset_dxpl_mpio (plist_id_data, H5FD_MPIO_COLLECTIVE); dset_weight = H5Dopen (file_id, "PW", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_weight); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_weight, size); fspace = H5Dget_space (dset_weight); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (1, dims, NULL); status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, mspace, fspace, plist_id_data, weight); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); status = H5Dclose (dset_weight); } //exit(0); if (file>=0) { status = H5Fclose(file); } } } H5Pclose(plist_id_file); free(weight_p); free(weight); H5Fclose(file_id); } */ MPI_Finalize(); free(num_procs_per_dir); free(each_subdir_number); free(displPtr); free(frm_array); }
{ "alphanum_fraction": 0.4698353397, "avg_line_length": 52.8482632541, "ext": "c", "hexsha": "274b0a5c880bae855ab279fa358ce1a9ead0bb98", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:13:42.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-19T09:13:42.000Z", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_path": "Src/merge.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_path": "Src/merge.c", "max_line_length": 245, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_path": "Src/merge.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 20588, "size": 86724 }
/* specfunc/atanint.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_mode.h> #include <gsl/gsl_sf_expint.h> #include "chebyshev.h" #include "cheb_eval.c" static double atanint_data[21] = { 1.91040361296235937512, -0.4176351437656746940e-01, 0.275392550786367434e-02, -0.25051809526248881e-03, 0.2666981285121171e-04, -0.311890514107001e-05, 0.38833853132249e-06, -0.5057274584964e-07, 0.681225282949e-08, -0.94212561654e-09, 0.13307878816e-09, -0.1912678075e-10, 0.278912620e-11, -0.41174820e-12, 0.6142987e-13, -0.924929e-14, 0.140387e-14, -0.21460e-15, 0.3301e-16, -0.511e-17, 0.79e-18, }; static cheb_series atanint_cs = { atanint_data, 20, -1, 1, 10 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_atanint_e(const double x, gsl_sf_result * result) { const double ax = fabs(x); const double sgn = GSL_SIGN(x); /* CHECK_POINTER(result) */ if(ax == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(ax < 0.5*GSL_SQRT_DBL_EPSILON) { result->val = x; result->err = 0.0; return GSL_SUCCESS; } else if(ax <= 1.0) { const double t = 2.0 * (x*x - 0.5); gsl_sf_result result_c; cheb_eval_e(&atanint_cs, t, &result_c); result->val = x * result_c.val; result->err = x * result_c.err; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(ax < 1.0/GSL_SQRT_DBL_EPSILON) { const double t = 2.0 * (1.0/(x*x) - 0.5); gsl_sf_result result_c; cheb_eval_e(&atanint_cs, t, &result_c); result->val = sgn * (0.5*M_PI*log(ax) + result_c.val/ax); result->err = result_c.err/ax + fabs(result->val*GSL_DBL_EPSILON); result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { result->val = sgn * (0.5*M_PI*log(ax) + 1.0 / ax); result->err = 2.0 * fabs(result->val * GSL_DBL_EPSILON); return GSL_SUCCESS; } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_atanint(const double x) { EVAL_RESULT(gsl_sf_atanint_e(x, &result)); }
{ "alphanum_fraction": 0.6547500828, "avg_line_length": 26.0431034483, "ext": "c", "hexsha": "166c4f8dea02052ef4eb2b67e1100d778327baaa", "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/specfunc/atanint.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/atanint.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/atanint.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": 1060, "size": 3021 }
/* monte/plain.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth * * 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. */ /* Plain Monte-Carlo. */ /* Author: MJB */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_monte_plain.h> int gsl_monte_plain_integrate (const gsl_monte_function * f, const double xl[], const double xu[], const size_t dim, const size_t calls, gsl_rng * r, gsl_monte_plain_state * state, double *result, double *abserr) { double vol, m = 0, q = 0; double *x = state->x; size_t n, i; if (dim != state->dim) { GSL_ERROR ("number of dimensions must match allocated size", GSL_EINVAL); } for (i = 0; i < dim; i++) { if (xu[i] <= xl[i]) { GSL_ERROR ("xu must be greater than xl", GSL_EINVAL); } if (xu[i] - xl[i] > GSL_DBL_MAX) { GSL_ERROR ("Range of integration is too large, please rescale", GSL_EINVAL); } } /* Compute the volume of the region */ vol = 1; for (i = 0; i < dim; i++) { vol *= xu[i] - xl[i]; } for (n = 0; n < calls; n++) { /* Choose a random point in the integration region */ for (i = 0; i < dim; i++) { x[i] = xl[i] + gsl_rng_uniform_pos (r) * (xu[i] - xl[i]); } { double fval = GSL_MONTE_FN_EVAL (f, x); /* recurrence for mean and variance */ double d = fval - m; m += d / (n + 1.0); q += d * d * (n / (n + 1.0)); } } *result = vol * m; if (calls < 2) { *abserr = GSL_POSINF; } else { *abserr = vol * sqrt (q / (calls * (calls - 1.0))); } return GSL_SUCCESS; } gsl_monte_plain_state * gsl_monte_plain_alloc (size_t dim) { gsl_monte_plain_state *s = (gsl_monte_plain_state *) malloc (sizeof (gsl_monte_plain_state)); if (s == 0) { GSL_ERROR_VAL ("failed to allocate space for state struct", GSL_ENOMEM, 0); } s->x = (double *) malloc (dim * sizeof (double)); if (s->x == 0) { free (s); GSL_ERROR_VAL ("failed to allocate space for working vector", GSL_ENOMEM, 0); } s->dim = dim; return s; } /* Set some default values and whatever */ int gsl_monte_plain_init (gsl_monte_plain_state * s) { size_t i; for (i = 0; i < s->dim; i++) { s->x[i] = 0.0; } return GSL_SUCCESS; } void gsl_monte_plain_free (gsl_monte_plain_state * s) { free (s->x); free (s); }
{ "alphanum_fraction": 0.5566949897, "avg_line_length": 22.4539473684, "ext": "c", "hexsha": "cab3ae2c59e7120e8445aaf70fb535ffcfdb7475", "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/monte/plain.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/monte/plain.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/monte/plain.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": 966, "size": 3413 }
#if !defined(PETIGAGRID_H) #define PETIGAGRID_H #include <petsc.h> #if !defined(LGMap) #define LGMap ISLocalToGlobalMapping #endif typedef struct _n_IGA_Grid *IGA_Grid; struct _n_IGA_Grid { MPI_Comm comm; PetscInt dim,dof; PetscInt sizes[3]; PetscInt local_start[3]; PetscInt local_width[3]; PetscInt ghost_start[3]; PetscInt ghost_width[3]; AO ao; LGMap lgmap; PetscLayout map; Vec lvec,gvec,nvec; VecScatter g2l,l2g,g2n; }; PETSC_EXTERN PetscErrorCode IGA_Grid_Create(MPI_Comm,IGA_Grid*); PETSC_EXTERN PetscErrorCode IGA_Grid_Init(IGA_Grid, PetscInt,PetscInt, const PetscInt[], const PetscInt[], const PetscInt[], const PetscInt[], const PetscInt[]); PETSC_EXTERN PetscErrorCode IGA_Grid_Reset(IGA_Grid); PETSC_EXTERN PetscErrorCode IGA_Grid_Destroy(IGA_Grid*); PETSC_EXTERN PetscErrorCode IGA_Grid_LocalIndices(IGA_Grid,PetscInt,PetscInt*,PetscInt*[]); PETSC_EXTERN PetscErrorCode IGA_Grid_GhostIndices(IGA_Grid,PetscInt,PetscInt*,PetscInt*[]); PETSC_EXTERN PetscErrorCode IGA_Grid_SetAO(IGA_Grid,AO); PETSC_EXTERN PetscErrorCode IGA_Grid_GetAO(IGA_Grid,AO*); PETSC_EXTERN PetscErrorCode IGA_Grid_SetLGMap(IGA_Grid,LGMap); PETSC_EXTERN PetscErrorCode IGA_Grid_GetLGMap(IGA_Grid,LGMap*); PETSC_EXTERN PetscErrorCode IGA_Grid_GetLayout(IGA_Grid,PetscLayout*); PETSC_EXTERN PetscErrorCode IGA_Grid_GetVecLocal (IGA_Grid,const VecType,Vec*); PETSC_EXTERN PetscErrorCode IGA_Grid_GetVecGlobal (IGA_Grid,const VecType,Vec*); PETSC_EXTERN PetscErrorCode IGA_Grid_GetVecNatural(IGA_Grid,const VecType,Vec*); PETSC_EXTERN PetscErrorCode IGA_Grid_GetScatterG2L(IGA_Grid,VecScatter*); PETSC_EXTERN PetscErrorCode IGA_Grid_GetScatterL2G(IGA_Grid,VecScatter*); PETSC_EXTERN PetscErrorCode IGA_Grid_GetScatterG2N(IGA_Grid,VecScatter*); PETSC_EXTERN PetscErrorCode IGA_Grid_GlobalToLocal(IGA_Grid,Vec,Vec); PETSC_EXTERN PetscErrorCode IGA_Grid_LocalToGlobal(IGA_Grid,Vec,Vec,InsertMode); PETSC_EXTERN PetscErrorCode IGA_Grid_NaturalToGlobal(IGA_Grid,Vec,Vec); PETSC_EXTERN PetscErrorCode IGA_Grid_GlobalToNatural(IGA_Grid,Vec,Vec); PETSC_EXTERN PetscErrorCode IGA_Grid_NewScatterApp(IGA_Grid g, const PetscInt[], const PetscInt[], const PetscInt[], const PetscInt[], Vec*,VecScatter*,VecScatter*); #endif/*PETIGAGRID_H*/
{ "alphanum_fraction": 0.6692913386, "avg_line_length": 43.65625, "ext": "h", "hexsha": "9ed4e980da268cc276ed790cda48dbe9b093ba84", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "dalcinl/PetIGA", "max_forks_repo_path": "src/petigagrid.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "dalcinl/PetIGA", "max_issues_repo_path": "src/petigagrid.h", "max_line_length": 91, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "dalcinl/PetIGA", "max_stars_repo_path": "src/petigagrid.h", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:56:49.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-19T17:19:43.000Z", "num_tokens": 675, "size": 2794 }
#include <cstdlib> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_sf_gamma.h> #include <complex> #include <ctime> #include <vector> #define MAXIT 100000000 #define EPS 1e-12 #define FPMIN 1.0e-12 using namespace std; typedef complex<double> cdouble; #define REAL(z,i) ((z)[i][0]) #define IMAG(z,i) ((z)[i][1]) cdouble lngamma( cdouble ); cdouble gamma( cdouble ); cdouble betai( cdouble, cdouble, cdouble ); cdouble upperbetai( cdouble, cdouble, cdouble ); cdouble betacf( cdouble, cdouble, cdouble ); void nrerror(const char[]);
{ "alphanum_fraction": 0.7214532872, "avg_line_length": 22.2307692308, "ext": "h", "hexsha": "1020d884552b72ef2e3cb7058d16689fbfcf8fc5", "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": "cc198157f8727bf79224ea679c98672b140b786c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sarabjeet29/Nipah", "max_forks_repo_path": "nipah/betainc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "cc198157f8727bf79224ea679c98672b140b786c", "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": "sarabjeet29/Nipah", "max_issues_repo_path": "nipah/betainc.h", "max_line_length": 48, "max_stars_count": null, "max_stars_repo_head_hexsha": "cc198157f8727bf79224ea679c98672b140b786c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sarabjeet29/Nipah", "max_stars_repo_path": "nipah/betainc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 177, "size": 578 }
#pragma once #include <cstddef> #include <gsl/gsl> #include <iterator> #include <limits> #include "../math/General.h" #include "Concepts.h" namespace utils { using concepts::DefaultConstructible, concepts::Integral, concepts::Copyable, concepts::Movable, concepts::NotMovable, concepts::ConstructibleFrom; /// @brief A simple Ring Buffer implementation. /// Supports resizing, writing, reading, erasing, and provides mutable and immutable /// random access iterators. /// /// # Iterator Invalidation /// * Iterators are lazily evaluated, so will only ever be invalidated at their current state. /// Performing any mutating operation (mutating the iterator, not the underlying data) on them /// will re-sync them with their associated `RingBuffer`. /// The following operations will invalidate an iterator's current state: /// - Read-only operations: never /// - clear: always /// - reserve: only if the `RingBuffer` changed capacity /// - erase: Erased elements and all following elements /// - push_back, emplace_back: only `end()` /// - insert, emplace: only the element at the position inserted/emplaced /// - pop_back: the element removed and `end()` /// /// @tparam T - The type to store in the `RingBuffer`; Must be Default Constructible template<DefaultConstructible T> class RingBuffer { public: /// Default capacity of `RingBuffer` static const constexpr size_t DEFAULT_CAPACITY = 16; /// @brief Random-Access Bidirectional iterator for `RingBuffer` /// @note All navigation operators are checked such that any movement past `begin()` or /// `end()` is ignored. class Iterator { public: using iterator_category = std::random_access_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = T; using pointer = value_type*; using reference = value_type&; constexpr explicit Iterator(pointer ptr, RingBuffer* containerPtr, size_t currentIndex) noexcept : mPtr(ptr), mContainerPtr(containerPtr), mCurrentIndex(currentIndex) { } constexpr Iterator(const Iterator& iter) noexcept = default; constexpr Iterator(Iterator&& iter) noexcept = default; ~Iterator() noexcept = default; /// @brief Returns the index in the `RingBuffer` that corresponds /// to the element this iterator points to /// /// @return The index corresponding with the element this points to [[nodiscard]] constexpr inline auto getIndex() const noexcept -> size_t { return mCurrentIndex; } constexpr auto operator=(const Iterator& iter) noexcept -> Iterator& = default; constexpr auto operator=(Iterator&& iter) noexcept -> Iterator& = default; constexpr inline auto operator==(const Iterator& rhs) const noexcept -> bool { return mPtr == rhs.mPtr; } constexpr inline auto operator!=(const Iterator& rhs) const noexcept -> bool { return mPtr != rhs.mPtr; } constexpr inline auto operator*() const noexcept -> reference { return *mPtr; } constexpr inline auto operator->() noexcept -> pointer { return mPtr; } constexpr inline auto operator++() noexcept -> Iterator& { mCurrentIndex++; if(mCurrentIndex >= mContainerPtr->capacity()) { mCurrentIndex = mContainerPtr->capacity(); mPtr = mContainerPtr->end().mPtr; } else { mPtr = &(*mContainerPtr)[mCurrentIndex]; } return *this; } constexpr inline auto operator++(int) noexcept -> Iterator { Iterator temp = *this; ++(*this); return temp; } constexpr inline auto operator--() noexcept -> Iterator& { if(mCurrentIndex == 0) { return *this; } else { mCurrentIndex--; mPtr = &(*mContainerPtr)[mCurrentIndex]; } return *this; } constexpr inline auto operator--(int) noexcept -> Iterator { Iterator temp = *this; --(*this); return temp; } constexpr inline auto operator+(Integral auto rhs) const noexcept -> Iterator { const auto diff = static_cast<size_t>(rhs); if(rhs < 0) { return std::move(*this - -rhs); } auto temp = *this; temp.mCurrentIndex += diff; if(temp.mCurrentIndex > temp.mContainerPtr->capacity()) { temp.mCurrentIndex = temp.mContainerPtr->capacity(); temp.mPtr = temp.mContainerPtr->end().mPtr; } else { temp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex]; } return temp; } constexpr inline auto operator+=(Integral auto rhs) noexcept -> Iterator& { *this = std::move(*this + rhs); return *this; } constexpr inline auto operator-(Integral auto rhs) const noexcept -> Iterator { const auto diff = static_cast<size_t>(rhs); if(rhs < 0) { return std::move(*this + -rhs); } auto temp = *this; if(diff > temp.mCurrentIndex) { temp.mPtr = temp.mContainerPtr->begin().mPtr; temp.mCurrentIndex = 0; } else { temp.mCurrentIndex -= diff; temp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex]; } return temp; } constexpr inline auto operator-=(Integral auto rhs) noexcept -> Iterator& { *this = std::move(*this - rhs); return *this; } constexpr inline auto operator-(const Iterator& rhs) const noexcept -> difference_type { return mPtr - rhs.mPtr; } constexpr inline auto operator[](Integral auto index) noexcept -> Iterator { return std::move(*this + index); } constexpr inline auto operator>(const Iterator& rhs) const noexcept -> bool { return mCurrentIndex > rhs.mCurrentIndex; } constexpr inline auto operator<(const Iterator& rhs) const noexcept -> bool { return mCurrentIndex < rhs.mCurrentIndex; } constexpr inline auto operator>=(const Iterator& rhs) const noexcept -> bool { return mCurrentIndex >= rhs.mCurrentIndex; } constexpr inline auto operator<=(const Iterator& rhs) const noexcept -> bool { return mCurrentIndex <= rhs.mCurrentIndex; } private: pointer mPtr; RingBuffer* mContainerPtr = nullptr; size_t mCurrentIndex = 0; }; /// @brief Read-only Random-Access Bidirectional iterator for `RingBuffer` /// @note All navigation operators are checked such that any movement past `begin()` or /// `end()` is ignored. class ConstIterator { public: using iterator_category = std::random_access_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = T; using pointer = const value_type*; using reference = const value_type&; constexpr explicit ConstIterator(pointer ptr, RingBuffer* containerPtr, size_t currentIndex) noexcept : mPtr(ptr), mContainerPtr(containerPtr), mCurrentIndex(currentIndex) { } constexpr ConstIterator(const ConstIterator& iter) noexcept = default; constexpr ConstIterator(ConstIterator&& iter) noexcept = default; ~ConstIterator() noexcept = default; /// @brief Returns the index in the `RingBuffer` that corresponds /// to the element this iterator points to /// /// @return The index corresponding with the element this points to [[nodiscard]] constexpr inline auto getIndex() const noexcept -> size_t { return mCurrentIndex; } constexpr auto operator=(const ConstIterator& iter) noexcept -> ConstIterator& = default; constexpr auto operator=(ConstIterator&& iter) noexcept -> ConstIterator& = default; constexpr inline auto operator==(const ConstIterator& rhs) const noexcept -> bool { return mPtr == rhs.mPtr; } constexpr inline auto operator!=(const ConstIterator& rhs) const noexcept -> bool { return mPtr != rhs.mPtr; } constexpr inline auto operator*() const noexcept -> reference { return *mPtr; } constexpr inline auto operator->() const noexcept -> pointer { return mPtr; } constexpr inline auto operator++() noexcept -> ConstIterator& { mCurrentIndex++; if(mCurrentIndex >= mContainerPtr->capacity()) { mCurrentIndex = mContainerPtr->capacity(); mPtr = mContainerPtr->end().mPtr; } else { mPtr = &(*mContainerPtr)[mCurrentIndex]; } return *this; } constexpr inline auto operator++(int) noexcept -> ConstIterator { ConstIterator temp = *this; ++(*this); return temp; } constexpr inline auto operator--() noexcept -> ConstIterator& { if(mCurrentIndex == 0) { return *this; } else { mCurrentIndex--; mPtr = &(*mContainerPtr)[mCurrentIndex]; } return *this; } constexpr inline auto operator--(int) noexcept -> ConstIterator { ConstIterator temp = *this; --(*this); return temp; } constexpr inline auto operator+(Integral auto rhs) const noexcept -> ConstIterator { const auto diff = static_cast<size_t>(rhs); if(rhs < 0) { return std::move(*this - -rhs); } auto temp = *this; temp.mCurrentIndex += diff; if(temp.mCurrentIndex > temp.mContainerPtr->capacity()) { temp.mCurrentIndex = temp.mContainerPtr->capacity(); temp.mPtr = temp.mContainerPtr->end().mPtr; } else { temp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex]; } return temp; } constexpr inline auto operator+=(Integral auto rhs) noexcept -> ConstIterator& { *this = std::move(*this + rhs); return *this; } constexpr inline auto operator-(Integral auto rhs) const noexcept -> ConstIterator { const auto diff = static_cast<size_t>(rhs); if(rhs < 0) { return std::move(*this + -rhs); } auto temp = *this; if(diff > temp.mCurrentIndex) { temp.mPtr = temp.mContainerPtr->begin().mPtr; temp.mCurrentIndex = 0; } else { temp.mCurrentIndex -= diff; temp.mPtr = &(*temp.mContainerPtr)[temp.mCurrentIndex]; } return temp; } constexpr inline auto operator-=(Integral auto rhs) noexcept -> ConstIterator& { *this = std::move(*this - rhs); return *this; } constexpr inline auto operator-(const ConstIterator& rhs) const noexcept -> difference_type { return mPtr - rhs.mPtr; } constexpr inline auto operator[](Integral auto index) const noexcept -> ConstIterator { return std::move(*this + index); } constexpr inline auto operator>(const ConstIterator& rhs) const noexcept -> bool { return mCurrentIndex > rhs.mCurrentIndex; } constexpr inline auto operator<(const ConstIterator& rhs) const noexcept -> bool { return mCurrentIndex < rhs.mCurrentIndex; } constexpr inline auto operator>=(const ConstIterator& rhs) const noexcept -> bool { return mCurrentIndex >= rhs.mCurrentIndex; } constexpr inline auto operator<=(const ConstIterator& rhs) const noexcept -> bool { return mCurrentIndex <= rhs.mCurrentIndex; } private: pointer mPtr; RingBuffer* mContainerPtr = nullptr; size_t mCurrentIndex = 0; }; /// @brief Creates a `RingBuffer` with default capacity RingBuffer() noexcept : mBuffer(new T[DEFAULT_CAPACITY_INTERNAL]) { } /// @brief Creates a `RingBuffer` with (at least) the given initial capacity /// /// @param initialCapacity - The initial capacity of the `RingBuffer` constexpr explicit RingBuffer(size_t initialCapacity) noexcept : mBuffer(new T[initialCapacity + 1]), mLoopIndex(initialCapacity), mCapacity(initialCapacity) { } /// @brief Constructs a new `RingBuffer` with the given initial capacity and /// fills it with `defaultValue` /// /// @param initialCapacity - The initial capacity of the `RingBuffer` /// @param defaultValue - The value to fill the `RingBuffer` with constexpr RingBuffer(size_t initialCapacity, const T& defaultValue) noexcept requires Copyable<T> : mBuffer(new T[initialCapacity + 1]), mLoopIndex(initialCapacity), mCapacity(initialCapacity) { for(auto i = 0ULL; i < mCapacity; ++i) { push_back(defaultValue); } } constexpr RingBuffer(const RingBuffer& buffer) noexcept requires Copyable<T> : mBuffer(new T[buffer.mCapacity + 1]), mWriteIndex(0ULL), // NOLINT mStartIndex(0ULL), // NOLINT mLoopIndex(buffer.mLoopIndex), mCapacity(buffer.mCapacity) { for(auto i = 0ULL; i < mCapacity; ++i) { push_back(buffer.mBuffer[i]); } mStartIndex = buffer.mStartIndex; // NOLINT(cppcoreguidelines-prefer-member-initializer) mWriteIndex = buffer.mWriteIndex; // NOLINT(cppcoreguidelines-prefer-member-initializer) mSize = buffer.mSize; // NOLINT(cppcoreguidelines-prefer-member-initializer) } constexpr RingBuffer(RingBuffer&& buffer) noexcept : mBuffer(std::move(buffer.mBuffer)), mStartIndex(buffer.mStartIndex), mLoopIndex(buffer.mLoopIndex), mCapacity(buffer.mCapacity), mSize(buffer.mSize) { buffer.mCapacity = 0ULL; buffer.mLoopIndex = 0ULL; buffer.mSize = 0ULL; buffer.mWriteIndex = 0ULL; buffer.mStartIndex = 0ULL; buffer.mBuffer = nullptr; } ~RingBuffer() noexcept = default; /// @brief Returns the element at the given index. /// @note This is not checked in the same manner as STL containers: /// if index >= capacity, the element at capacity - 1 is returned. /// /// @param index - The index of the desired element /// /// @return The element at the given index, or at capacity - 1 if index >= capacity [[nodiscard]] constexpr inline auto at(Integral auto index) noexcept -> T& { auto i = getAdjustedInternalIndex(index); if(i > mLoopIndex) { i = mLoopIndex; } return mBuffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } /// @brief Returns the first element in the `RingBuffer` /// /// @return The first element [[nodiscard]] constexpr inline auto front() noexcept -> T& { return mBuffer[mStartIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } /// @brief Returns the last element in the `RingBuffer` /// @note If <= 1 elements are in the `RingBuffer`, this will be the same as `front` /// /// @return The last element [[nodiscard]] constexpr inline auto back() noexcept -> T& { auto index = mWriteIndex - 1; if(mWriteIndex == 0) { if(mStartIndex == 0) { index = 0; } else { index = mLoopIndex; } } return mBuffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } /// @brief Returns a pointer to the underlying data in the `RingBuffer`. /// @note This is not sorted in any way to match the representation used by the `RingBuffer` /// /// @return A pointer to the underlying data [[nodiscard]] constexpr inline auto data() noexcept -> T* { return mBuffer; } /// @brief Returns whether the `RingBuffer` is empty /// /// @return `true` if the `RingBuffer` is empty, `false` otherwise [[nodiscard]] constexpr inline auto empty() noexcept -> bool { return mSize == 0; } /// @brief Returns the current number of elements in the `RingBuffer` /// /// @return The current number of elements [[nodiscard]] constexpr inline auto size() noexcept -> size_t { return mSize; } /// @brief Returns the maximum possible number of elements this `RingBuffer` could store /// if grown to maximum possible capacity /// /// @return The maximum possible number of storable elements [[nodiscard]] constexpr inline auto max_size() noexcept -> size_t { return std::numeric_limits<size_t>::max(); } /// @brief Returns the current capacity of the `RingBuffer`; /// the number of elements it can currently store /// /// @return The current capacity [[nodiscard]] constexpr inline auto capacity() noexcept -> size_t { return mCapacity; } /// @brief Reserves more storage for the `RingBuffer`. If `newCapacity` is > capacity, /// then the capacity of the `RingBuffer` will be extended until at least `newCapacity` /// elements can be stored. /// @note Memory contiguity is maintained, so no **elements** will be lost or invalidated. /// However, all iterators and references to elements will be invalidated. /// /// @param newCapacity - The new capacity of the `RingBuffer` constexpr inline auto reserve(size_t newCapacity) noexcept -> void { // we only need to do anything if `newCapacity` is actually larger than `mCapacity` if(newCapacity > mCapacity) { gsl::owner<T*> temp = new T[newCapacity]; // NOLINT auto span = gsl::make_span(temp, newCapacity); std::copy(begin(), end(), span.begin()); mBuffer.reset(temp); mStartIndex = 0; mWriteIndex = mLoopIndex + 1; mLoopIndex = newCapacity; mCapacity = newCapacity; } } /// @brief Erases all elements from the `RingBuffer` constexpr inline auto clear() noexcept -> void { mStartIndex = 0; mWriteIndex = 0; mSize = 0; } /// @brief Inserts the given element at the end of the `RingBuffer` /// @note if `size() == capacity()` then this loops and overwrites `front()` /// /// @param value - the element to insert constexpr inline auto push_back(const T& value) noexcept -> void requires Copyable<T> { // clang-format off mBuffer[mWriteIndex] = value; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on incrementIndices(); } /// @brief Inserts the given element at the end of the `RingBuffer` /// @note if `size() == capacity()` then this loops and overwrites `front()` /// /// @param value - the element to insert constexpr inline auto push_back(T&& value) noexcept -> void { // clang-format off mBuffer[mWriteIndex] = std::forward<T>(value); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on incrementIndices(); } /// @brief Constructs the given element in place at the end of the `RingBuffer` /// @note if `size() == capacity()` then this loops and overwrites `front()` /// /// @tparam Args - The types of the element's constructor arguments /// @param args - The constructor arguments for the element /// /// @return A reference to the element constructed at the end of the `RingBuffer` template<typename... Args> requires ConstructibleFrom<T, Args...> constexpr inline auto emplace_back(Args&&... args) noexcept -> T& requires Movable<T> { // clang-format off new (&mBuffer[mWriteIndex]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on incrementIndices(); auto index = mWriteIndex == 0 ? mLoopIndex : mWriteIndex - 1; return mBuffer[index]; // NOLINT } /// @brief Constructs the given element in place at the location /// indicated by the `Iterator` `position` /// /// @tparam Args - The types of the element's constructor arguments /// @param position - `Iterator` indicating where in the `RingBuffer` to construct the /// element /// @param args - The constructor arguments for the element /// /// @return A reference to the element constructed at the location indicated by `position` template<typename... Args> requires ConstructibleFrom<T, Args...> constexpr inline auto emplace(const Iterator& position, Args&&... args) noexcept -> T& { auto index = getAdjustedInternalIndex(position.getIndex()); // clang-format off new (&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on return mBuffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } /// @brief Constructs the given element in place at the location /// indicated by the `ConstIterator` `position` /// /// @tparam Args - The types of the element's constructor arguments /// @param position - `ConstIterator` indicating where in the `RingBuffer` to construct the /// element /// @param args - The constructor arguments for the element /// /// @return A reference to the element constructed at the location indicated by `position` template<typename... Args> constexpr inline auto emplace(const ConstIterator& position, Args&&... args) noexcept -> T& { auto index = getAdjustedInternalIndex(position.getIndex()); // clang-format off new (&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on return mBuffer[index]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } /// @brief Assigns the given element to the position indicated /// by the `Iterator` `position` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param position - `Iterator` indicating where in the `RingBuffer` to place the element /// @param element - The element to store in the `RingBuffer` constexpr inline auto insert(const Iterator& position, const T& element) noexcept -> void requires Copyable<T> { insert_internal(position.getIndex(), element); } /// @brief Assigns the given element to the position indicated /// by the `Iterator` `position` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param position - `Iterator` indicating where in the `RingBuffer` to place the element /// @param element - The element to store in the `RingBuffer` constexpr inline auto insert(const Iterator& position, T&& element) noexcept -> void { insert_internal(position.getIndex(), std::forward<T>(element)); } /// @brief Assigns the given element to the position indicated /// by the `ConstIterator` `position` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the /// element /// @param element - The element to store in the `RingBuffer` constexpr inline auto insert(const ConstIterator& position, const T& element) noexcept -> void requires Copyable<T> { insert_internal(position.getIndex(), element); } /// @brief Assigns the given element to the position indicated /// by the `ConstIterator` `position` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the /// element /// @param element - The element to store in the `RingBuffer` constexpr inline auto insert(const ConstIterator& position, T&& element) noexcept -> void { insert_internal(position.getIndex(), std::forward<T>(element)); } /// @brief Constructs the given element at the insertion position indicated /// by the `ConstIterator` `position` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the /// element /// @param args - The arguments to the constructor for /// the element to store in the `RingBuffer` template<typename... Args> requires ConstructibleFrom<T, Args...> constexpr inline auto insert_emplace(const Iterator& position, Args&&... args) noexcept -> T& { return insert_emplace_internal(position.getIndex(), args...); } /// @brief Constructs the given element at the insertion position indicated /// by the `ConstIterator` `position` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param position - `ConstIterator` indicating where in the `RingBuffer` to place the /// element /// @param args - The arguments to the constructor for /// the element to store in the `RingBuffer` template<typename... Args> requires ConstructibleFrom<T, Args...> constexpr inline auto insert_emplace(const ConstIterator& position, Args&&... args) noexcept -> T& { return insert_emplace_internal(position.getIndex(), args...); } /// @brief Erases the element at the given `position`, moving other elements backward /// in the buffer to maintain contiguity /// /// @param position - The element to erase /// /// @return `Iterator` pointing to the element after the one erased constexpr inline auto erase(const Iterator& position) noexcept -> Iterator { return erase_internal(position.getIndex()); } /// @brief Erases the element at the given `position`, moving other elements backward /// in the buffer to maintain contiguity /// /// @param position - The element to erase /// /// @return `Iterator` pointing to the element after the one erased constexpr inline auto erase(const ConstIterator& position) noexcept -> Iterator { return erase_internal(position.getIndex()); } /// @brief Erases the range of elements in [`first`, `last`) /// Returns an `Iterator` to the element after the last one erased /// @note In the case `first` >= `last`, no elements are erased and `last` is returned; /// /// @param first - The first element in the range to erase /// @param last - The last element in the range /// /// @return `Iterator` pointing to the element after the last one erased constexpr inline auto erase(const Iterator& first, const Iterator& last) noexcept -> Iterator { if(first >= last) { return last; } return erase_internal(first.getIndex(), last.getIndex()); } /// @brief Erases the range of elements in [`first`, `last`) /// Returns an `Iterator` to the element after the last one erased /// @note In the case `first` >= `last`, no elements are erased and `last` is returned; /// /// @param first - The first element in the range to erase /// @param last - The last element in the range /// /// @return `Iterator` pointing to the element after the last one erased constexpr inline auto erase(const ConstIterator& first, const ConstIterator& last) noexcept -> Iterator { if(first >= last) { return last; } return erase_internal(first.getIndex(), last.getIndex()); } /// @brief Removes the last element in the `RingBuffer` and returns it /// /// @return The last element in the `RingBuffer` [[nodiscard]] constexpr inline auto pop_back() noexcept -> T requires Copyable<T> { T _back = back(); erase(--end()); return _back; } /// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`, /// at the beginning /// /// @return The iterator, at the beginning [[nodiscard]] constexpr inline auto begin() -> Iterator { T* p = &mBuffer[mStartIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return Iterator(p, this, 0ULL); } /// @brief Returns a Random Access Bidirectional iterator over the `RingBuffer`, /// at the end /// /// @return The iterator, at the end [[nodiscard]] constexpr inline auto end() -> Iterator { T* p = &mBuffer[mWriteIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return Iterator(p, this, mSize); } /// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`, /// at the beginning /// /// @return The iterator, at the beginning [[nodiscard]] constexpr inline auto cbegin() -> ConstIterator { T* p = &mBuffer[mStartIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return ConstIterator(p, this, 0ULL); } /// @brief Returns a Random Access Bidirectional read-only iterator over the `RingBuffer`, /// at the end /// /// @return The iterator, at the end [[nodiscard]] constexpr inline auto cend() -> ConstIterator { T* p = &mBuffer[mWriteIndex]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return ConstIterator(p, this, mSize); } /// @brief Unchecked access-by-index operator /// /// @param index - The index to get the corresponding element for /// /// @return - The element at index [[nodiscard]] constexpr inline auto operator[](Integral auto index) noexcept -> T& { auto i = getAdjustedInternalIndex(index); return mBuffer[i]; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } constexpr auto operator=(const RingBuffer& buffer) noexcept -> RingBuffer& requires Copyable<T> { if(this == &buffer) { return *this; } mBuffer.reset(new T[buffer.mCapacity + 1]); // NOLINT mStartIndex = 0ULL; mWriteIndex = 0ULL; mCapacity = buffer.mCapacity; for(auto i = 0ULL; i < mCapacity; ++i) { push_back(buffer.mBuffer[i]); } mStartIndex = buffer.mStartIndex; mWriteIndex = buffer.mWriteIndex; mLoopIndex = buffer.mLoopIndex; mSize = buffer.mSize; return *this; } constexpr auto operator=(RingBuffer&& buffer) noexcept -> RingBuffer& { mBuffer = std::move(buffer.mBuffer); mWriteIndex = buffer.mWriteIndex; mStartIndex = buffer.mStartIndex; mLoopIndex = buffer.mLoopIndex; mCapacity = buffer.mCapacity; mSize = buffer.mSize; buffer.mBuffer = nullptr; buffer.mWriteIndex = 0ULL; buffer.mStartIndex = 0ULL; buffer.mCapacity = 0ULL; buffer.mSize = 0ULL; return *this; } private: static const constexpr size_t DEFAULT_CAPACITY_INTERNAL = DEFAULT_CAPACITY + 1; std::unique_ptr<T[]> mBuffer = new T[DEFAULT_CAPACITY_INTERNAL]; // NOLINT size_t mWriteIndex = 0; size_t mStartIndex = 0; size_t mLoopIndex = DEFAULT_CAPACITY; size_t mCapacity = DEFAULT_CAPACITY; size_t mSize = 0; /// @brief Converts the given `RingBuffer` index into the corresponding index into then /// underlying `T` array /// /// @param index - The `RingBuffer` index to convert /// /// @return The corresponding index into the underlying `T` array [[nodiscard]] constexpr inline auto getAdjustedInternalIndex(Integral auto index) const noexcept -> size_t { auto i = static_cast<size_t>(index); if(mStartIndex + i > mLoopIndex) { i = (mStartIndex + i) - (mLoopIndex + 1); } else { i += mStartIndex; } return i; } /// @brief Converts the given index into the underlying `T` array into /// a using facing index into the `RingBuffer` /// /// @param index - The internal index /// /// @return The corresponding user-facing index [[nodiscard]] constexpr inline auto getExternalIndexFromInternal(Integral auto index) const noexcept -> size_t { auto i = static_cast<size_t>(index); if(i > mStartIndex && i <= mLoopIndex) { return i - mStartIndex; } else if(i < mStartIndex) { return (mLoopIndex - mStartIndex) + i + 1; } else if(i == mStartIndex) { return 0; } else { return mSize; } } /// @brief Increments the start and write indices into the underlying `T` array, /// and the size property, maintaining the logical `RingBuffer` structure constexpr inline auto incrementIndices() noexcept -> void { mWriteIndex++; mSize = math::General::min(mSize + 1, mCapacity); // if write index is at start - 1, we need to push start forward to maintain // the "invalid" spacer element for this.end() if(mWriteIndex > mLoopIndex && mStartIndex == 0) { mWriteIndex = 0; mStartIndex = 1; } else if(mWriteIndex == mStartIndex) { mStartIndex++; if(mStartIndex > mLoopIndex) { mStartIndex = 0; } } } /// @brief Inserts the given element at the position indicated /// by the `externalIndex` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element /// at /// @param elem - The element to store in the `RingBuffer` constexpr inline auto insert_internal(size_t externalIndex, const T& elem) noexcept -> void requires Movable<T> { const auto index = getAdjustedInternalIndex(externalIndex); if(index == mWriteIndex) { emplace_back(elem); } else { auto numToMove = mSize - externalIndex; auto iter = begin() + externalIndex; if(mSize == mCapacity) [[likely]] { // NOLINT for(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) { *((end() - i) + 1) = std::move(*(iter + j)); } } else { for(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) { *(end() - i) = std::move(*(iter + j)); } } incrementIndices(); if(externalIndex == 0) { // clang-format off mBuffer[mStartIndex] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } else { // clang-format off mBuffer[index] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } } } /// @brief Inserts the given element at the position indicated /// by the `externalIndex` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element /// at /// @param elem - The element to store in the `RingBuffer` constexpr inline auto insert_internal(size_t externalIndex, const T& elem) noexcept -> void requires NotMovable<T> { const auto index = getAdjustedInternalIndex(externalIndex); if(index == mWriteIndex) { emplace_back(elem); } else { auto numToMove = mSize - externalIndex; auto iter = begin() + externalIndex; if(mSize == mCapacity) [[likely]] { // NOLINT for(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) { *((end() - i) + 1) = *(iter + j); } } else { for(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) { *(end() - i) = *(iter + j); } } incrementIndices(); if(externalIndex == 0) { // clang-format off mBuffer[mStartIndex] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } else { // clang-format off mBuffer[index] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } } } /// @brief Inserts the given element at the position indicated /// by the `externalIndex` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element /// at /// @param elem - The element to store in the `RingBuffer` constexpr inline auto insert_internal(size_t externalIndex, T&& elem) noexcept -> void requires Movable<T> { const auto index = getAdjustedInternalIndex(externalIndex); if(index == mWriteIndex) { emplace_back(elem); } else { auto numToMove = mSize - externalIndex; auto iter = begin() + externalIndex; if(mSize == mCapacity) [[likely]] { // NOLINT for(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) { *((end() - i) + 1) = std::move(*(iter + j)); } } else { for(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) { *(end() - i) = std::move(*(iter + j)); } } incrementIndices(); if(externalIndex == 0) { // clang-format off mBuffer[mStartIndex] = std::move(elem); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } else { // clang-format off mBuffer[index] = std::move(elem); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } } } /// @brief Inserts the given element at the position indicated /// by the `externalIndex` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element /// at /// @param elem - The element to store in the `RingBuffer` constexpr inline auto insert_internal(size_t externalIndex, T&& elem) noexcept -> void requires NotMovable<T> { const auto index = getAdjustedInternalIndex(externalIndex); if(index == mWriteIndex) { emplace_back(elem); } else { auto numToMove = mSize - externalIndex; auto iter = begin() + externalIndex; if(mSize == mCapacity) [[likely]] { // NOLINT for(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) { *((end() - i) + 1) = *(iter + j); } } else { for(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) { *(end() - i) = *(iter + j); } } incrementIndices(); if(externalIndex == 0) { // clang-format off mBuffer[mStartIndex] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } else { // clang-format off mBuffer[index] = elem; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } } } /// @brief Constructs the given element at the insertion position indicated /// by the `externalIndex` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element /// at /// @param args - The arguments to the constructor for /// the element to store in the `RingBuffer` template<typename... Args> requires ConstructibleFrom<T, Args...> constexpr inline auto insert_emplace_internal(size_t externalIndex, Args&&... args) noexcept -> T& requires Movable<T> { const auto index = getAdjustedInternalIndex(externalIndex); if(index == mWriteIndex) { return emplace_back(args...); } else { auto numToMove = mSize - externalIndex; auto iter = begin() + externalIndex; if(mSize == mCapacity) [[likely]] { // NOLINT for(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) { *((end() - i) + 1) = std::move(*(iter + j)); } } else { for(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) { *(end() - i) = std::move(*(iter + j)); } } incrementIndices(); if(externalIndex == 0) { // clang-format off new (&mBuffer[mStartIndex]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return mBuffer[mStartIndex];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } else { // clang-format off new(&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return mBuffer[index];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } } } /// @brief Constructs the given element at the insertion position indicated /// by the `externalIndex` /// @note if `size() == capacity()` this drops the last element out of the `RingBuffer` /// /// @param externalIndex - The user-facing index into the `RingBuffer` to insert the element /// at /// @param args - The arguments to the constructor for /// the element to store in the `RingBuffer` template<typename... Args> requires ConstructibleFrom<T, Args...> constexpr inline auto insert_emplace_internal(size_t externalIndex, Args&&... args) noexcept -> T& requires NotMovable<T> { const auto index = getAdjustedInternalIndex(externalIndex); if(index == mWriteIndex) { return emplace_back(args...); } else { auto numToMove = mSize - externalIndex; auto iter = begin() + externalIndex; if(mSize == mCapacity) [[likely]] { // NOLINT for(size_t i = 1ULL, j = numToMove - 2; i < numToMove; ++i, --j) { *((end() - i) + 1) = *(iter + j); } } else { for(size_t i = 0ULL, j = numToMove - 1; i < numToMove; ++i, --j) { *(end() - i) = *(iter + j); } } incrementIndices(); if(externalIndex == 0) { // clang-format off new (&mBuffer[mStartIndex]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return mBuffer[mStartIndex];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } else { // clang-format off new(&mBuffer[index]) T(args...); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) return mBuffer[index];// NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } } } /// @brief Erases the element at the given index, returning an `Iterator` to the element /// after the removed one /// /// @param index - The index to the element to remove. This should be a `RingBuffer` index: /// IE, not an interal one into the `T` array /// /// @return `Iterator` pointing to the element after the one removed [[nodiscard]] constexpr inline auto erase_internal(size_t index) noexcept -> Iterator { auto indexInternal = getAdjustedInternalIndex(index); if(indexInternal == mWriteIndex) [[unlikely]] { // NOLINT return end(); } else { auto numToMove = (mSize - 1) - index; mWriteIndex = indexInternal; mSize -= numToMove + 1; auto posToMove = index + 1; for(auto i = 0ULL; i < numToMove; ++i) { // clang-format off emplace_back(mBuffer[getAdjustedInternalIndex(posToMove + i)]); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } auto iter = begin() + getExternalIndexFromInternal(mWriteIndex); return iter; } } /// @brief Erases the range of elements in [`first`, `last`) /// Returns an `Iterator` to the element after the last one erased /// /// @param first - The first index in the range to erase. This should be a `RingBuffer` /// index: IE, not an internal one into the `T` array /// @param last - The last index` in the range to erase. This should be a `RingBuffer` /// index: IE, not an internal one into the `T` array /// /// @return `Iterator` pointing to the element after the last one erased [[nodiscard]] constexpr inline auto erase_internal(size_t first, size_t last) noexcept -> Iterator { auto firstInternal = getAdjustedInternalIndex(first); auto lastInternal = getAdjustedInternalIndex(last); if(lastInternal == mWriteIndex) { if(mWriteIndex == mLoopIndex) { mStartIndex--; mWriteIndex -= last - first; } else if(mWriteIndex < mStartIndex) { auto numToRemove = (last - first); auto numBeforeZero = numToRemove - mWriteIndex; auto numAfterZero = numToRemove - numBeforeZero; mStartIndex -= numBeforeZero; if(numAfterZero > 0) { mWriteIndex = mLoopIndex; numAfterZero--; mWriteIndex -= numAfterZero; } else { mWriteIndex -= numBeforeZero; } } else if(mWriteIndex > mStartIndex) { auto numToRemove = (last - first); mWriteIndex -= numToRemove; } mSize -= last - first; return end(); } else { auto numToMove = mSize - last; mWriteIndex = firstInternal; mSize -= numToMove + (last - first); auto posToMove = last; for(auto i = 0ULL; i < numToMove; ++i) { // clang-format off emplace_back(mBuffer[getAdjustedInternalIndex(posToMove + i)]); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) // clang-format on } auto iter = begin() + first; return iter; } } }; } // namespace utils
{ "alphanum_fraction": 0.6466952946, "avg_line_length": 35.6380566802, "ext": "h", "hexsha": "560a2808bb6e3d23458e2c7d3d7fc3059b13d041", "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": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "braxtons12/ray_tracer", "max_forks_repo_path": "src/utils/RingBuffer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "braxtons12/ray_tracer", "max_issues_repo_path": "src/utils/RingBuffer.h", "max_line_length": 128, "max_stars_count": null, "max_stars_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "braxtons12/ray_tracer", "max_stars_repo_path": "src/utils/RingBuffer.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 11488, "size": 44013 }
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #ifndef LIBND4J_GEMM_H #define LIBND4J_GEMM_H // work around conflict with OpenBLAS struct bfloat16; #define BFLOAT16 BFLOAT16 #include <cblas.h> #include <math/templatemath.h> #include <system/op_boilerplate.h> namespace sd { namespace blas { template <typename T> static void *transpose(int orderSource, int orderTarget, int rows, int cols, void *source); static inline int linearIndexC(int rows, int cols, int r, int c); static inline int linearIndexF(int rows, int cols, int r, int c); template <typename X, typename Y, typename Z> class GEMM { protected: public: static void op(int Order, int TransA, int TransB, int M, int N, int K, double alpha, void *A, int lda, void *B, int ldb, double beta, void *C, int ldc); }; template <typename X, typename Y, typename Z> class GEMV : public sd::blas::GEMM<X, Y, Z> { public: static void op(int TRANS, int M, int N, double alpha, void *vA, int lda, void *vX, int incx, double beta, void *vY, int incy); }; int SD_INLINE linearIndexC(int rows, int cols, int r, int c) { return (r * cols + c); } int SD_INLINE linearIndexF(int rows, int cols, int r, int c) { return (c * rows + r); } } // namespace blas } // namespace sd #endif // LIBND4J_GEMM_H
{ "alphanum_fraction": 0.6588124411, "avg_line_length": 33.15625, "ext": "h", "hexsha": "d299d00de10be749b40dc2928475c29af785e506", "lang": "C", "max_forks_count": 572, "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:46:46.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-12T22:13:57.000Z", "max_forks_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "steljord2/deeplearning4j", "max_forks_repo_path": "libnd4j/include/ops/gemm.h", "max_issues_count": 1685, "max_issues_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:45:15.000Z", "max_issues_repo_issues_event_min_datetime": "2019-06-12T17:41:33.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "steljord2/deeplearning4j", "max_issues_repo_path": "libnd4j/include/ops/gemm.h", "max_line_length": 117, "max_stars_count": 2206, "max_stars_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "steljord2/deeplearning4j", "max_stars_repo_path": "libnd4j/include/ops/gemm.h", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:14:27.000Z", "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:57:14.000Z", "num_tokens": 523, "size": 2122 }
#pragma once //============================================================================= // EXTERNAL DECLARATIONS //============================================================================= #include "Core/Game/IManagerComponent.h" #include "Core/Game/IManager.h" #include "Core/Game/IGameEngine.h" #include "Core/Components/ComponentBase.h" #include <gsl/span> namespace engine { //============================================================================= // CLASS GameManager //============================================================================= template<class TDerived> class GameManager : virtual public IManagerComponent , virtual public IManager { public: virtual void onAttached(const GameEngineRef &iGameEngine) override {} virtual void onDetached(const GameEngineRef &iGameEngine) override {} virtual gsl::span<IdType> interfaces() override { return TDerived::Interfaces; } }; } // namespace engine
{ "alphanum_fraction": 0.5111583422, "avg_line_length": 30.3548387097, "ext": "h", "hexsha": "a25a18a23f18a89843fd8c9678b44c4c4fca77b8", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "gaspardpetit/INF740-GameEngine", "max_forks_repo_path": "Engine/Game/GameManager.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "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": "gaspardpetit/INF740-GameEngine", "max_issues_repo_path": "Engine/Game/GameManager.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "gaspardpetit/INF740-GameEngine", "max_stars_repo_path": "Engine/Game/GameManager.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 154, "size": 941 }
/* NAME: read_data PURPOSE: read the data from the data input file CALLING SEQUENCE: read_data(inputfilename) INPUT: inputfilename - name of the data file OUPUT: reads everything into the right structures REVISION HISTORY: 2008-09-21 - Written Bovy */ #include <stdio.h> #include <stdbool.h> #include <math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <proj_gauss_main.h> #include <proj_gauss_mixtures.h> bool read_data(char inputfilename[]){ FILE *inputfile; if ( (inputfile= fopen(inputfilename,"r")) == NULL){ printf ("Opening the data file failed...\n"); return false; } //First count the number of datapoints N=0; while (feof(inputfile) ==0) if (getc(inputfile) == '\n') N++; printf("%i datapoints found in ",N); printf("%s", inputfilename); printf("\n"); //Then read the actual data fseek(inputfile,0,SEEK_SET); //allocate data data = (struct datapoint *) malloc(N*sizeof (struct datapoint)); if (data == NULL){ printf("Allocation of arrays failed, not enough free memory?\n"); exit(-1); } startdata = data; //current line holds a maximum of d+dV+d*d elements //First read the whole line double *curr_line = (double *) calloc(d+dV+d*d, sizeof (double) ); bool end_line; int ii=0,dd=0,di;//di is the dimension of the individual datapoints while (feof(inputfile) == 0){ char curr_value[20]=""; end_line = read_till_sep(curr_value,inputfile,'|'); *(curr_line++) = atof(curr_value); ++dd; if (end_line){ ++ii; curr_line -= dd; //Determine the dimension of the datapoint, di, from the equation di+di*(di+1)/2+d*di=dd, or, di = (int) ((-(3 + 2 * d) + sqrt((3 + 2 * d)*(3 + 2 * d)+8 * dd))/2); //then write data values to memory //first allocate the space for the data data->ww = gsl_vector_alloc(di); data->SS = gsl_matrix_alloc(di,di); data->RR = gsl_matrix_alloc(di,d); int dd1,dd2; for (dd1=0; dd1 != di; ++dd1) gsl_vector_set(data->ww,dd1,*(curr_line++)); for (dd1=0; dd1 != di; ++dd1) gsl_matrix_set(data->SS,dd1,dd1,*(curr_line++)); for (dd1=0; dd1 != di-1; ++dd1) for (dd2=dd1+1; dd2 != di; ++dd2){ gsl_matrix_set(data->SS,dd1,dd2,*curr_line); gsl_matrix_set(data->SS,dd2,dd1,*curr_line); curr_line++; } for (dd1=0; dd1 != di; ++dd1) for (dd2=0; dd2 != d; ++dd2) gsl_matrix_set(data->RR,dd1,dd2,*(curr_line++)); curr_line -= dd; dd = 0; data++; if (ii == N) break; } } data = startdata; fclose(inputfile); free(curr_line); return true; }
{ "alphanum_fraction": 0.6116541353, "avg_line_length": 27.1428571429, "ext": "c", "hexsha": "89f64d63eab3c2b8abae21b1691a54f396d6cc16", "lang": "C", "max_forks_count": 26, "max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z", "max_forks_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_forks_repo_path": "src/read_data.c", "max_issues_count": 24, "max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_issues_repo_path": "src/read_data.c", "max_line_length": 100, "max_stars_count": 73, "max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_stars_repo_path": "src/read_data.c", "max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z", "num_tokens": 832, "size": 2660 }
#include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_linalg.h> #define maxnd 10000 #define H 0.5 /* PROGRAM: simSFS AUTHOR: Athanasios Kousathanas VERSION: 1.0 Generate allele frequency vectors (AFVs) using Wright-Fisher transition matrix methods and sample to obtain site frequency spectra (SFS). Code implements methods described by Keightley and Eyre-Walker(2007). Features: Demography: 1-epoch or 2-epoch population changes Selection: only single s Compilation: use makefile or compile as gcc -O2 -o simSFS simSFS.v1.0.c -lm -lgsl -lgslcblas -w */ //////////////////////////////////////// //calculate allele frequency change, delta(q) //////////////////////////////////////// double selfn(double q, double s, double h) { double num, denom; num = s*q*(1-q)*(q + h*(1-2*q)); denom = 1 + 2.0*h*s*q*(1-q) + s*q*q; if (denom== 0) denom = .00000000000001; return( q + (num/denom)); } //////////////////////////////////////// //initialise rows of matrix (used by setupmatrix) //////////////////////////////////////// setuprow(double **a, double p, int row, int n){ double z; /*probability of zero failures*/ double x, y, temp1, temp2; int j; temp1 = 1.0 - p; if (temp1 == 0.0) temp1 = .000000000001; /*prevent zero divide*/ temp1 = p/temp1; /*First prevent negative log*/ if (temp1 <=0) temp1 = .000000000001; x = log(temp1); /*used for later multiplication of series*/ temp2 = 1.0-p; if (temp2<=0) temp2 = .000000000001; z = (double)n*log(temp2); if (z > 150) z = 150; a[row][0] = exp(z); y = a[row][0]; /*add up for later*/ for (j = 1;j<=n; j++) { z = z + log(((double)n + 1.0 - (double)j)/(double)j) + x; /* cumulative binomial coeff.*/ a[row][j] = exp(z); y = y + a[row][j]; /*add up*/ } if (y == 0.0) y = .0000000000001; for (j=0; j<=n; j++) a[row][j] = a[row][j]/y; } //////////////////////////////////////// //initialise transition matrix //////////////////////////////////////// setupmatrix(double **a, int n1, int n2, double s, double h){ int i; double p; for (i = 1; i<=n1 - 1; i++) /*do variable rows*/ { p = (double)i/(double)n1; p = selfn(p, s,h); setuprow(a, p, i, n2); } for (i = 0; i<=n2; i++) { /*do constant edges*/ a[0][i] = 0; a[n1][i] = 0; } a[0][0] = 1.0; /*do absorbing corners*/ a[n1][n2] = 1.0; } //////////////////////////////////////// //Perform matrix inversion //////////////////////////////////////// matrixinvert(int N, double **a,double *inverter){ int i, j, lotkin_signum; gsl_matrix *lotkin_a,*lotkin_inv; gsl_vector *x, *lotkin_b, *lotkin_x; gsl_permutation *lotkin_perm; /* allocate a, x, b */ lotkin_a = gsl_matrix_alloc(N-1, N-1); lotkin_inv = gsl_matrix_alloc(N-1, N-1); x = gsl_vector_alloc(N-1); lotkin_b = gsl_vector_alloc(N-1); lotkin_x = gsl_vector_alloc(N-1); gsl_matrix *identity=gsl_matrix_alloc(N-1, N-1); for (i = 0; i<=N-2; i++) { for (j = 0; j<=N-2; j++) { gsl_matrix_set( identity, i, i,1); } } for (i = 0; i<=N-2; i++) { for (j = 0; j<=N-2; j++) { gsl_matrix_set(lotkin_a,i,j,gsl_matrix_get(identity,i,j)-a[i+1][j+1]); } } /* LU decomposition and forward&backward substition */ //gsl_blas_dgemv(CblasNoTrans, 1.0, lotkin_a, x, 0.0, lotkin_b); lotkin_perm = gsl_permutation_alloc(N-1); gsl_linalg_LU_decomp(lotkin_a, lotkin_perm, &lotkin_signum); gsl_linalg_LU_solve(lotkin_a, lotkin_perm, lotkin_b, lotkin_x); gsl_linalg_LU_invert (lotkin_a,lotkin_perm, lotkin_inv); /*apparently the inversion adds +1 to the first element of the vector so I substract it*/ gsl_matrix_set(lotkin_inv,0,0,gsl_matrix_get(lotkin_inv,0,0)-1); for (i=0;i<=N-2;i++){ inverter[i+1]=gsl_matrix_get(lotkin_inv,0,i); } gsl_matrix_free(lotkin_a); gsl_matrix_free(lotkin_inv); gsl_vector_free(x); gsl_vector_free(lotkin_b); gsl_vector_free(lotkin_x); gsl_matrix_free(identity); gsl_permutation_free(lotkin_perm); } //////////////////////////////////////// //perform TM iteration for t generations //////////////////////////////////////// tmiterate(double **a,double *mut1, int t, int n1, int n2,int decay,double *sumf){ int k, i, j = 0; double z; double * steadystatefreq = (double*) calloc (maxnd+1, sizeof(double)); double * mut2 = (double*) calloc (maxnd+1, sizeof(double)); for (i=0; i<=n1; i++) steadystatefreq[i] = 0; for (k = 1; k<=t; k++) { /*t iterations*/ /* Increment steadystatefreq. distribution*/ for (i = 0; i<=n1; i++) { steadystatefreq[i] = steadystatefreq[i] + mut1[i]; } /* Perform matrix multiplication*/ for (i = 0; i<=n2; i++) { z = 0; for (j = 0; j<=n1; j++) { z = z + a[j][i]*mut1[j]; } mut2[i] = z; } /* Copy result of multiplication*/ for (i=0; i<=n2; i++) {mut1[i] = mut2[i]; if (decay==0){ sumf[i]+=mut1[i];} if(decay==1){sumf[i]=mut1[i];} } } free(steadystatefreq); free(mut2); } eqf_using_matrix_inversion(int n1,double s,double **a,double *egf_out){ setupmatrix(a, n1, n1, s, H); matrixinvert(n1,a,egf_out); } //////////////////////////////////////// //scale AFV for mutations eliminated by selection/not mutated //////////////////////////////////////// egf_scaling_s(int n1,double *v_s_in, double *v_s_out,double f0){ int n1d=2*n1; double sumx,sumy; int i; sumx=0; sumy=0; for (i=1;i<n1d;i++){ sumx+=v_s_in[i]; } for (i=1;i<n1d;i++){ v_s_out[i]/=sumx; sumy+=v_s_out[i]; } v_s_out[0]=(1-sumy)*(1-f0); } //////////////////////////////////////// //scale AFV for sites not mutated //////////////////////////////////////// egf_scaling_f0(int n1,double *fv,double f0){ int i; int n1d=2*n1; for (i=1;i<n1d;i++){ fv[i]*=(1-f0); } fv[0]+=f0; } //////////////////////////////////////// //binomial sampling from AFV to generate SFS //////////////////////////////////////// binomial_sampling(int n1,int n1b,int sample, double *invy,int *discrete,gsl_rng *rgen){ int s1,success; int i; double prob; /* based on equilibrium frequency vector (use it as a probability vector), I randomly generate numbers from 0 to n1d-1 for sample sites. */ gsl_ran_discrete_t *r= gsl_ran_discrete_preproc (n1,invy); for (i=0;i<sample;i++){ s1=gsl_ran_discrete (rgen, r); prob=(double)(s1)/n1; success=gsl_ran_binomial(rgen,prob,n1b+1); discrete[success]++; } gsl_ran_discrete_free(r); } output_sfs_to_file(int n1,int *sfs1,int *sfs2,char *filename,long seed){ int i; FILE *file; file = fopen(filename,"w"); fprintf(file,"#seed used: %d\n",seed); fprintf(file,"#neutral\n"); for (i=0;i<=n1;i++){ fprintf(file,"%d ",sfs1[i]); } fprintf(file,"\n#selected\n"); for (i=0;i<=n1;i++){ fprintf(file,"%d ",sfs2[i]); } fclose(file); } //////////////////////////////////////// //Calculate weighted average of two vectors // Normally vectors w(s) x(s) by N1 and N2 respectively //////////////////////////////////////// vector_average(int n1,int n2,double *fv1,double *fv2, double *fv_out){ int i; int n1d=n1*2; int n2d=n2*2; for (i=0;i<=n2d;i++){ fv_out[i]=(n1*fv1[i]+n2*fv2[i])/(n1+n2); } } ////////////////////////////////////// //Obtain AFV for 1-epoch model //////////////////////////////////////// calculate_FV_one_epoch(int n1,double s,double *FV){ int i=0; int n1d=2*n1; double **FVW = calloc(maxnd+1, sizeof(double *)); for(i = 0; i < maxnd+1; i++){ FVW[i] = calloc(maxnd+1, sizeof(double));} eqf_using_matrix_inversion(n1d,s,FVW,FV); FV[1]+=1; for(i = 0; i < maxnd+1; i++) free(FVW[i]); free(FVW); } //////////////////////////////////////// //Obtain AFV for 2-epoch model //////////////////////////////////////// calculate_FV_two_epoch(int n1,int n2,int t,double s,double *FV){ int i=0; double **egf_0 = calloc(maxnd+1, sizeof(double *)); for(i = 0; i < maxnd+1; i++){ egf_0[i] = calloc(maxnd+1, sizeof(double)); } double * FVW = (double*) calloc (maxnd+1, sizeof(double)); double * FVX = (double*) calloc (maxnd+1, sizeof(double)); double * startingfreq = (double*) calloc (maxnd+1, sizeof(double)); int n1d=n1*2; int n2d=n2*2; /* Contributions of mutations to AFV before the change in population size. */ //obtain AFV at equilibrium eqf_using_matrix_inversion(n1d,s,egf_0,FVW); FVW[1]+=1.0;//cumulative vector includes 1st mutant //perform change in population size N1->N2 setupmatrix(egf_0,n1d,n2d,s,H); tmiterate(egf_0,FVW,1, n1d, n2d,1,FVW); setupmatrix(egf_0,n2d,n2d,s,H); tmiterate(egf_0,FVW,t-1, n2d, n2d,1,FVW); //dumpvector(FVW,0,n2,"FVW"); /* Contributions of mutations to AFV after the change in population size. */ setupmatrix(egf_0,n2d,n2d,s,H); startingfreq[1]=1.0; tmiterate(egf_0,startingfreq, t-1, n2d, n2d,0,FVX); FVX[1]+=1.0;//cumulative vector includes 1st mutant //dumpvector(FVX,0,n2,"FVX"); /* averaging of vectors FVW (N1) and FVX(N2) */ vector_average(n1,n2,FVW,FVX,FV); for(i = 0; i < maxnd+1; i++){ free(egf_0[i]); } free(egf_0); free(FVX); free(FVW); free(startingfreq); } //////////////////////////////////////// //print given matrix //////////////////////////////////////// dumpmatrix(double **m, int s1, int rows, int s2, int cols, char *s){ int i, j; printf("\n%s\n", s); for (i = s1; i<=rows; i++) { for (j = s2; j<=cols; j++) { printf(" %2.3f", m[i][j]); } printf("\n"); } printf("\n"); } //////////////////////////////////////// //print given vector //////////////////////////////////////// dumpvector(double *v, int min, int max, char *s){ int i, control = 0; // printf("\n"); printf("%s", s); printf("\n"); for (i = min; i<=max; i++) { printf("%3d %lf ", i, v[i]); control++; if (control==5) { control = 0; printf("\n"); } } printf("\n"); } /* //////////////////////////////////////// MAIN START //////////////////////////////////////// */ int main(int argc, char **argv) { //initialise input variables and use default values int N1=100,n=10,sampleS=1000,sampleN=1000; int N2=N1; int t=N1; double f0=0.9,S=0; char outfile[maxnd+1]="sfs.out"; long seed=time (NULL) * getpid(); //other variables int option_index = 0; int c=0; static int verbose_flag; const gsl_rng_type * T; T = gsl_rng_taus; gsl_rng *rgen =gsl_rng_alloc(T); gsl_rng_set(rgen,seed); int * discrete0 = (int*) calloc (maxnd+1, sizeof(int)); int * discrete1 = (int*) calloc (maxnd+1, sizeof(int)); double * FV0 = (double*) calloc (maxnd+1, sizeof(double)); double * FVS = (double*) calloc (maxnd+1, sizeof(double)); //parse input while (1) { static struct option long_options[] = { {"h",no_argument, &verbose_flag, 1}, {"N1", required_argument,0, 'a'}, {"N2", required_argument,0, 'b'}, {"n", required_argument, 0, 'c'}, {"f0", required_argument, 0, 'd'}, {"s", required_argument, 0, 'e'}, {"LS", required_argument, 0, 'f'}, {"LN", required_argument, 0, 'g'}, {"t", required_argument, 0, 'h'}, {"o", required_argument, 0, 'i'}, {"seed", required_argument, 0, 'j'}, {NULL, 0, 0, 0} }; /* getopt_long stores the option index here. */ c = getopt_long_only (argc, argv, "", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) { printf("\ option\tdefault_value\tdescription\n\ N1\t100\tsize N1\n\ N2\t100\tsize N2\n\ t\t100\ttime since size change\n\ n\t10\tallele sample size\n\ f0\t0.9\t1-f0 is proportional to mutation rate\n\ s\t0\tselection coeffient\n\ LS\t1000\tno. neutral sites\n\ LN\t1000\tno. selected sites\n\ o\tsfs.out\toutput file\n\ seed\ttime*pid\tset seed for random generator\n\ "); } break; printf ("option %s", long_options[option_index].name); if (optarg) printf (" with arg %s", optarg); printf ("\n"); break; case 'a': N1=atoi(optarg); break; case 'b': N2=atoi(optarg); break; case 'c': n=atoi(optarg); break; case 'd': f0=atof(optarg); break; case 'e': S=atof(optarg); break; case 'f': sampleS=atoi(optarg); break; case 'g': sampleN=atoi(optarg); break; case 'h': t=atoi(optarg); break; case 'i': strncpy(outfile,optarg,maxnd+1); break; case 'j': seed=atoi(optarg); gsl_rng_set(rgen,seed); break; case '?': abort(); break; default: abort (); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); putchar ('\n'); } if (N1>1000||N2>1000){printf ("Use N1,N2 <1000\n"); abort();} /* calculate allele frequency vectors for neutral (FV0) and selected sites (FVS) */ if (N1==N2){ calculate_FV_one_epoch(N1,0.0,FV0); calculate_FV_one_epoch(N1,S,FVS); }else{ calculate_FV_two_epoch(N1,N2,t,0.0,FV0); calculate_FV_two_epoch(N1,N2,t,S,FVS); } /* scale FVS to include the frequency of sites at which mutations have been eliminated by selection or have not experienced a mutation */ egf_scaling_s(N2,FV0,FVS, f0); egf_scaling_f0(N2,FVS,f0); /* scale FV0 to account for sites that have never experienced a mutation. */ egf_scaling_s(N2,FV0, FV0,f0); egf_scaling_f0(N2,FV0,f0); /*sampling sample sampleN neutral sites from FV0 sample sampleS selected sites from FVS */ binomial_sampling(N2,n,sampleN,FV0,discrete0,rgen); binomial_sampling(N2,n,sampleS, FVS,discrete1,rgen); output_sfs_to_file(n,discrete0,discrete1,outfile,seed); //free vectors free(FV0); free(FVS); free(discrete0); free(discrete1); gsl_rng_free (rgen); return 0; } /* //////////////////////////////////////// END OF MAIN //////////////////////////////////////// */
{ "alphanum_fraction": 0.5578635015, "avg_line_length": 23.1116427432, "ext": "c", "hexsha": "417fe26be1b90db3601377d5e42f011089afe9be", "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": "8454615aaa863c84b4bb2300aa80ff053acae27d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kousathanas/simsfs", "max_forks_repo_path": "simSFS.v1.0.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8454615aaa863c84b4bb2300aa80ff053acae27d", "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": "kousathanas/simsfs", "max_issues_repo_path": "simSFS.v1.0.c", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "8454615aaa863c84b4bb2300aa80ff053acae27d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kousathanas/simsfs", "max_stars_repo_path": "simSFS.v1.0.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4729, "size": 14491 }
/*************************************************************************** * data_cf.h is part of Math Graphic Library * Copyright (C) 2007-2016 Alexey Balakin <mathgl.abalakin@gmail.ru> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 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 Library 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. * ***************************************************************************/ #ifndef _MGL_DATAC_CF_H_ #define _MGL_DATAC_CF_H_ //----------------------------------------------------------------------------- #include "mgl2/abstract.h" //----------------------------------------------------------------------------- #if MGL_HAVE_GSL #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #else struct gsl_vector; struct gsl_matrix; #endif //----------------------------------------------------------------------------- #ifdef __cplusplus class mglDataC; typedef mglDataC* HADT; extern "C" { #else typedef void *HADT; #endif /// Get integer power of x cmdual MGL_EXPORT_CONST mgl_ipowc(mdual x,int n); cmdual MGL_EXPORT mgl_ipowc_(mdual *x,int *n); /// Get complex number from string. Parse (%g,%g), {%g,%g} and [%g,%g] if adv!=0. cmdual MGL_EXPORT mgl_atoc(const char *s, int adv); /// Get exp(i*a) cmdual MGL_EXPORT_CONST mgl_expi(mdual a); /// Create HMDT object HADT MGL_EXPORT mgl_create_datac(); uintptr_t MGL_EXPORT mgl_create_datac_(); /// Create HMDT object with specified sizes HADT MGL_EXPORT mgl_create_datac_size(long nx, long ny, long nz); uintptr_t MGL_EXPORT mgl_create_datac_size_(int *nx, int *ny, int *nz); /// Create HMDT object with data from file HADT MGL_EXPORT mgl_create_datac_file(const char *fname); uintptr_t MGL_EXPORT mgl_create_datac_file_(const char *fname, int len); /// Delete HMDT object void MGL_EXPORT mgl_delete_datac(HADT dat); void MGL_EXPORT mgl_delete_datac_(uintptr_t *dat); /// Rearange data dimensions void MGL_EXPORT mgl_datac_rearrange(HADT dat, long mx,long my,long mz); void MGL_EXPORT mgl_datac_rearrange_(uintptr_t *dat, int *mx, int *my, int *mz); /// Link external data array (don't delete it at exit) void MGL_EXPORT mgl_datac_link(HADT dat, mdual *A,long mx,long my,long mz); void MGL_EXPORT mgl_datac_link_(uintptr_t *d, mdual *A, int *nx,int *ny,int *nz); /// Allocate memory and copy the data from the (float *) array void MGL_EXPORT mgl_datac_set_float(HADT dat, const float *A,long mx,long my,long mz); void MGL_EXPORT mgl_datac_set_float_(uintptr_t *dat, const float *A,int *NX,int *NY,int *NZ); /// Allocate memory and copy the data from the (double *) array void MGL_EXPORT mgl_datac_set_double(HADT dat, const double *A,long mx,long my,long mz); void MGL_EXPORT mgl_datac_set_double_(uintptr_t *dat, const double *A,int *NX,int *NY,int *NZ); /// Allocate memory and copy the data from the (dual *) array void MGL_EXPORT mgl_datac_set_complex(HADT dat, const mdual *A,long mx,long my,long mz); void MGL_EXPORT mgl_datac_set_complex_(uintptr_t *d, const mdual *A,int *NX,int *NY,int *NZ); /// Import data from abstract type void MGL_EXPORT mgl_datac_set(HADT dat, HCDT a); void MGL_EXPORT mgl_datac_set_(uintptr_t *dat, uintptr_t *a); /// Allocate memory and copy the data from the gsl_vector void MGL_EXPORT mgl_datac_set_vector(HADT dat, gsl_vector *v); /// Allocate memory and copy the data from the gsl_matrix void MGL_EXPORT mgl_datac_set_matrix(HADT dat, gsl_matrix *m); /// Set value of data element [i,j,k] void MGL_EXPORT mgl_datac_set_value(HADT dat, mdual v, long i, long j, long k); void MGL_EXPORT mgl_datac_set_value_(uintptr_t *d, mdual *v, int *i, int *j, int *k); /// Get value of data element [i,j,k] cmdual MGL_EXPORT mgl_datac_get_value(HCDT dat, long i, long j, long k); cmdual MGL_EXPORT mgl_datac_get_value_(uintptr_t *d, int *i, int *j, int *k); /// Allocate memory and scanf the data from the string void MGL_EXPORT mgl_datac_set_values(HADT dat, const char *val, long nx, long ny, long nz); void MGL_EXPORT mgl_datac_set_values_(uintptr_t *d, const char *val, int *nx, int *ny, int *nz, int l); /// Get array as solution of tridiagonal matrix solution a[i]*x[i-1]+b[i]*x[i]+c[i]*x[i+1]=d[i] /** String \a how may contain: * 'x', 'y', 'z' for solving along x-,y-,z-directions, or * 'h' for solving along hexagonal direction at x-y plain (need nx=ny), * 'c' for using periodical boundary conditions, * 'd' for diffraction/diffuse calculation. * NOTE: It work for flat data model only (i.e. for a[i,j]==a[i+nx*j]) */ HADT MGL_EXPORT mgl_datac_tridmat(HCDT A, HCDT B, HCDT C, HCDT D, const char *how); uintptr_t MGL_EXPORT mgl_datac_tridmat_(uintptr_t *A, uintptr_t *B, uintptr_t *C, uintptr_t *D, const char *how, int); /// Returns pointer to internal data array MGL_EXPORT mdual *mgl_datac_data(HADT dat); /// Returns pointer to data element [i,j,k] MGL_EXPORT mdual *mgl_datac_value(HADT dat, long i,long j,long k); /// Set the data from HCDT objects for real and imaginary parts void MGL_EXPORT mgl_datac_set_ri(HADT dat, HCDT re, HCDT im); void MGL_EXPORT mgl_datac_set_ri_(uintptr_t *dat, uintptr_t *re, uintptr_t *im); /// Set the data from HCDT objects as amplitude and phase of complex data void MGL_EXPORT mgl_datac_set_ap(HADT dat, HCDT abs, HCDT phi); void MGL_EXPORT mgl_datac_set_ap_(uintptr_t *dat, uintptr_t *abs, uintptr_t *phi); /// Read data from tab-separated text file with auto determining size int MGL_EXPORT mgl_datac_read(HADT dat, const char *fname); int MGL_EXPORT mgl_datac_read_(uintptr_t *d, const char *fname,int l); /// Read data from text file with size specified at beginning of the file int MGL_EXPORT mgl_datac_read_mat(HADT dat, const char *fname, long dim); int MGL_EXPORT mgl_datac_read_mat_(uintptr_t *dat, const char *fname, int *dim, int); /// Read data from text file with specifeid size int MGL_EXPORT mgl_datac_read_dim(HADT dat, const char *fname,long mx,long my,long mz); int MGL_EXPORT mgl_datac_read_dim_(uintptr_t *dat, const char *fname,int *mx,int *my,int *mz,int); /// Read data from tab-separated text files with auto determining size which filenames are result of sprintf(fname,templ,t) where t=from:step:to int MGL_EXPORT mgl_datac_read_range(HADT d, const char *templ, double from, double to, double step, int as_slice); int MGL_EXPORT mgl_datac_read_range_(uintptr_t *d, const char *fname, mreal *from, mreal *to, mreal *step, int *as_slice,int l); /// Read data from tab-separated text files with auto determining size which filenames are satisfied to template (like "t_*.dat") int MGL_EXPORT mgl_datac_read_all(HADT dat, const char *templ, int as_slice); int MGL_EXPORT mgl_datac_read_all_(uintptr_t *d, const char *fname, int *as_slice,int l); /// Save whole data array (for ns=-1) or only ns-th slice to text file void MGL_EXPORT mgl_datac_save(HCDT dat, const char *fname,long ns); void MGL_EXPORT mgl_datac_save_(uintptr_t *dat, const char *fname,int *ns,int); /// Read data array from HDF file (parse HDF4 and HDF5 files) int MGL_EXPORT mgl_datac_read_hdf(HADT d,const char *fname,const char *data); int MGL_EXPORT mgl_datac_read_hdf_(uintptr_t *d, const char *fname, const char *data,int l,int n); /// Save data to HDF file void MGL_EXPORT mgl_datac_save_hdf(HCDT d,const char *fname,const char *data,int rewrite); void MGL_EXPORT mgl_datac_save_hdf_(uintptr_t *d, const char *fname, const char *data, int *rewrite,int l,int n); /// Create or recreate the array with specified size and fill it by zero void MGL_EXPORT mgl_datac_create(HADT dat, long nx,long ny,long nz); void MGL_EXPORT mgl_datac_create_(uintptr_t *dat, int *nx,int *ny,int *nz); /// Transpose dimensions of the data (generalization of Transpose) void MGL_EXPORT mgl_datac_transpose(HADT dat, const char *dim); void MGL_EXPORT mgl_datac_transpose_(uintptr_t *dat, const char *dim,int); /// Get sub-array of the data with given fixed indexes HADT MGL_EXPORT mgl_datac_subdata(HCDT dat, long xx,long yy,long zz); uintptr_t MGL_EXPORT mgl_datac_subdata_(uintptr_t *dat, int *xx,int *yy,int *zz); /// Get sub-array of the data with given fixed indexes (like indirect access) HADT MGL_EXPORT mgl_datac_subdata_ext(HCDT dat, HCDT xx, HCDT yy, HCDT zz); uintptr_t MGL_EXPORT mgl_datac_subdata_ext_(uintptr_t *dat, uintptr_t *xx,uintptr_t *yy,uintptr_t *zz); /// Get column (or slice) of the data filled by formulas of named columns HADT MGL_EXPORT mgl_datac_column(HCDT dat, const char *eq); uintptr_t MGL_EXPORT mgl_datac_column_(uintptr_t *dat, const char *eq,int l); /// Get trace of the data array HADT MGL_EXPORT mgl_datac_trace(HCDT d); uintptr_t MGL_EXPORT mgl_datac_trace_(uintptr_t *d); /// Resize the data to new sizes HADT MGL_EXPORT mgl_datac_resize(HCDT dat, long mx,long my,long mz); uintptr_t MGL_EXPORT mgl_datac_resize_(uintptr_t *dat, int *mx,int *my,int *mz); /// Resize the data to new sizes of box [x1,x2]*[y1,y2]*[z1,z2] HADT MGL_EXPORT mgl_datac_resize_box(HCDT dat, long mx,long my,long mz,mreal x1,mreal x2,mreal y1,mreal y2,mreal z1,mreal z2); uintptr_t MGL_EXPORT mgl_datac_resize_box_(uintptr_t *dat, int *mx,int *my,int *mz,mreal *x1,mreal *x2,mreal *y1,mreal *y2,mreal *z1,mreal *z2); /// Get momentum (1D-array) of data along direction 'dir'. String looks like "x1" for median in x-direction, "x2" for width in x-dir and so on. HADT MGL_EXPORT mgl_datac_momentum(HCDT dat, char dir, const char *how); uintptr_t MGL_EXPORT mgl_datac_momentum_(uintptr_t *dat, char *dir, const char *how, int,int); /// Get array which values is result of interpolation this for coordinates from other arrays HADT MGL_EXPORT mgl_datac_evaluate(HCDT dat, HCDT idat, HCDT jdat, HCDT kdat, int norm); uintptr_t MGL_EXPORT mgl_datac_evaluate_(uintptr_t *dat, uintptr_t *idat, uintptr_t *jdat, uintptr_t *kdat, int *norm); /// Get array which is result of summation in given direction or directions HADT MGL_EXPORT mgl_datac_sum(HCDT dat, const char *dir); uintptr_t MGL_EXPORT mgl_datac_sum_(uintptr_t *dat, const char *dir,int); /// Get the data which is direct multiplication (like, d[i,j] = this[i]*a[j] and so on) HADT MGL_EXPORT mgl_datac_combine(HCDT dat1, HCDT dat2); uintptr_t MGL_EXPORT mgl_datac_combine_(uintptr_t *dat1, uintptr_t *dat2); /// Get data from sections ids, separated by value val along specified direction. /** If section id is negative then reverse order is used (i.e. -1 give last section). */ HADT MGL_EXPORT mgl_datac_section(HCDT dat, HCDT ids, char dir, mreal val); uintptr_t MGL_EXPORT mgl_datac_section_(uintptr_t *d, uintptr_t *ids, const char *dir, mreal *val,int); /// Get data from section id, separated by value val along specified direction. /** If section id is negative then reverse order is used (i.e. -1 give last section). */ HADT MGL_EXPORT mgl_datac_section_val(HCDT dat, long id, char dir, mreal val); uintptr_t MGL_EXPORT mgl_datac_section_val_(uintptr_t *d, int *id, const char *dir, mreal *val,int); /// Equidistantly fill the data to range [x1,x2] in direction dir void MGL_EXPORT mgl_datac_fill(HADT dat, mdual x1,mdual x2,char dir); void MGL_EXPORT mgl_datac_fill_(uintptr_t *dat, mdual *x1,mdual *x2,const char *dir,int); /// Modify the data by specified formula assuming x,y,z in range [r1,r2] void MGL_EXPORT mgl_datac_fill_eq(HMGL gr, HADT dat, const char *eq, HCDT vdat, HCDT wdat,const char *opt); void MGL_EXPORT mgl_datac_fill_eq_(uintptr_t *gr, uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,const char *opt, int, int); /// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2] using global spline void MGL_EXPORT mgl_datac_refill_gs(HADT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl); void MGL_EXPORT mgl_datac_refill_gs_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl); /// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2] void MGL_EXPORT mgl_datac_refill_x(HADT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl); void MGL_EXPORT mgl_datac_refill_x_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl); /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in range [x1,x2]*[y1,y2] void MGL_EXPORT mgl_datac_refill_xy(HADT dat, HCDT xdat, HCDT ydat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, long sl); void MGL_EXPORT mgl_datac_refill_xy_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, long *sl); /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in range [x1,x2]*[y1,y2]*[z1,z2] void MGL_EXPORT mgl_datac_refill_xyz(HADT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2); void MGL_EXPORT mgl_datac_refill_xyz_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, mreal *z1, mreal *z2); /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range void MGL_EXPORT mgl_datac_refill_gr(HMGL gr, HADT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, long sl, const char *opt); void MGL_EXPORT mgl_datac_refill_gr_(uintptr_t *gr, uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, long *sl, const char *opt,int); /// Modify the data by specified formula void MGL_EXPORT mgl_datac_modify(HADT dat, const char *eq,long dim); void MGL_EXPORT mgl_datac_modify_(uintptr_t *dat, const char *eq,int *dim,int); /// Modify the data by specified formula void MGL_EXPORT mgl_datac_modify_vw(HADT dat, const char *eq,HCDT vdat,HCDT wdat); void MGL_EXPORT mgl_datac_modify_vw_(uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,int); /// Limit the data to be inside [-v,v], keeping the original sign void MGL_EXPORT mgl_datac_limit(HADT dat, mreal v); void MGL_EXPORT mgl_datac_limit_(uintptr_t *dat, mreal *v); /// Put value to data element(s) void MGL_EXPORT mgl_datac_put_val(HADT dat, mdual val, long i, long j, long k); void MGL_EXPORT mgl_datac_put_val_(uintptr_t *dat, mdual *val, int *i, int *j, int *k); /// Put array to data element(s) void MGL_EXPORT mgl_datac_put_dat(HADT dat, HCDT val, long i, long j, long k); void MGL_EXPORT mgl_datac_put_dat_(uintptr_t *dat, uintptr_t *val, int *i, int *j, int *k); /// Reduce size of the data void MGL_EXPORT mgl_datac_squeeze(HADT dat, long rx,long ry,long rz,long smooth); void MGL_EXPORT mgl_datac_squeeze_(uintptr_t *dat, int *rx,int *ry,int *rz,int *smooth); /// Extend data dimensions void MGL_EXPORT mgl_datac_extend(HADT dat, long n1, long n2); void MGL_EXPORT mgl_datac_extend_(uintptr_t *dat, int *n1, int *n2); /// Insert data rows/columns/slices void MGL_EXPORT mgl_datac_insert(HADT dat, char dir, long at, long num); void MGL_EXPORT mgl_datac_insert_(uintptr_t *dat, const char *dir, int *at, int *num, int); /// Delete data rows/columns/slices void MGL_EXPORT mgl_datac_delete(HADT dat, char dir, long at, long num); void MGL_EXPORT mgl_datac_delete_(uintptr_t *dat, const char *dir, int *at, int *num, int); /// Joind another data array void MGL_EXPORT mgl_datac_join(HADT dat, HCDT d); void MGL_EXPORT mgl_datac_join_(uintptr_t *dat, uintptr_t *d); /// Smooth the data on specified direction or directions /** String \a dir may contain: * ‘x’, ‘y’, ‘z’ for 1st, 2nd or 3d dimension; * ‘dN’ for linear averaging over N points; * ‘3’ for linear averaging over 3 points; * ‘5’ for linear averaging over 5 points. * By default quadratic averaging over 5 points is used. */ void MGL_EXPORT mgl_datac_smooth(HADT d, const char *dirs, mreal delta); void MGL_EXPORT mgl_datac_smooth_(uintptr_t *dat, const char *dirs, mreal *delta,int); /// Cumulative summation the data in given direction or directions void MGL_EXPORT mgl_datac_cumsum(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_cumsum_(uintptr_t *dat, const char *dir,int); /// Integrate (cumulative summation) the data in given direction or directions void MGL_EXPORT mgl_datac_integral(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_integral_(uintptr_t *dat, const char *dir,int); /// Differentiate the data in given direction or directions void MGL_EXPORT mgl_datac_diff(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_diff_(uintptr_t *dat, const char *dir,int); /// Differentiate the parametrically specified data along direction v1 with v2,v3=const (v3 can be NULL) void MGL_EXPORT mgl_datac_diff_par(HADT dat, HCDT v1, HCDT v2, HCDT v3); void MGL_EXPORT mgl_datac_diff_par_(uintptr_t *dat, uintptr_t *v1, uintptr_t *v2, uintptr_t *v3); /// Double-differentiate (like Laplace operator) the data in given direction void MGL_EXPORT mgl_datac_diff2(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_diff2_(uintptr_t *dat, const char *dir,int); /// Swap left and right part of the data in given direction (useful for Fourier spectrum) void MGL_EXPORT mgl_datac_swap(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_swap_(uintptr_t *dat, const char *dir,int); /// Roll data along direction dir by num slices void MGL_EXPORT mgl_datac_roll(HADT dat, char dir, long num); void MGL_EXPORT mgl_datac_roll_(uintptr_t *dat, const char *dir, int *num, int); /// Mirror the data in given direction (useful for Fourier spectrum) void MGL_EXPORT mgl_datac_mirror(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_mirror_(uintptr_t *dat, const char *dir,int); /// Crop the data void MGL_EXPORT mgl_datac_crop(HADT dat, long n1, long n2, char dir); void MGL_EXPORT mgl_datac_crop_(uintptr_t *dat, int *n1, int *n2, const char *dir,int); /// Crop the data to be most optimal for FFT (i.e. to closest value of 2^n*3^m*5^l) void MGL_EXPORT mgl_datac_crop_opt(HADT dat, const char *how); void MGL_EXPORT mgl_datac_crop_opt_(uintptr_t *dat, const char *how,int); /// Multiply the data by other one for each element void MGL_EXPORT mgl_datac_mul_dat(HADT dat, HCDT d); void MGL_EXPORT mgl_datac_mul_dat_(uintptr_t *dat, uintptr_t *d); /// Divide the data by other one for each element void MGL_EXPORT mgl_datac_div_dat(HADT dat, HCDT d); void MGL_EXPORT mgl_datac_div_dat_(uintptr_t *dat, uintptr_t *d); /// Add the other data void MGL_EXPORT mgl_datac_add_dat(HADT dat, HCDT d); void MGL_EXPORT mgl_datac_add_dat_(uintptr_t *dat, uintptr_t *d); /// Subtract the other data void MGL_EXPORT mgl_datac_sub_dat(HADT dat, HCDT d); void MGL_EXPORT mgl_datac_sub_dat_(uintptr_t *dat, uintptr_t *d); /// Multiply each element by the number void MGL_EXPORT mgl_datac_mul_num(HADT dat, mdual d); void MGL_EXPORT mgl_datac_mul_num_(uintptr_t *dat, mdual *d); /// Divide each element by the number void MGL_EXPORT mgl_datac_div_num(HADT dat, mdual d); void MGL_EXPORT mgl_datac_div_num_(uintptr_t *dat, mdual *d); /// Add the number void MGL_EXPORT mgl_datac_add_num(HADT dat, mdual d); void MGL_EXPORT mgl_datac_add_num_(uintptr_t *dat, mdual *d); /// Subtract the number void MGL_EXPORT mgl_datac_sub_num(HADT dat, mdual d); void MGL_EXPORT mgl_datac_sub_num_(uintptr_t *dat, mdual *d); /// Apply Hankel transform void MGL_EXPORT mgl_datac_hankel(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_hankel_(uintptr_t *dat, const char *dir,int); /// Apply Sin-Fourier transform void MGL_EXPORT mgl_datac_sinfft(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_sinfft_(uintptr_t *dat, const char *dir,int); /// Apply Cos-Fourier transform void MGL_EXPORT mgl_datac_cosfft(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_cosfft_(uintptr_t *dat, const char *dir,int); /// Apply Fourier transform void MGL_EXPORT mgl_datac_fft(HADT dat, const char *dir); void MGL_EXPORT mgl_datac_fft_(uintptr_t *dat, const char *dir,int); /// Find correlation between 2 data arrays HADT MGL_EXPORT mgl_datac_correl(HCDT dat1, HCDT dat2, const char *dir); uintptr_t MGL_EXPORT mgl_datac_correl_(uintptr_t *dat1, uintptr_t *dat2, const char *dir,int); /// Calculate one step of diffraction by finite-difference method with parameter q void MGL_EXPORT mgl_datac_diffr(HADT dat, const char *how, mreal q); void MGL_EXPORT mgl_datac_diffr_(uintptr_t *d, const char *how, double q,int l); /// Apply wavelet transform /** Parameter \a dir may contain: * ‘x‘,‘y‘,‘z‘ for directions, * ‘d‘ for daubechies, ‘D‘ for centered daubechies, * ‘h‘ for haar, ‘H‘ for centered haar, * ‘b‘ for bspline, ‘B‘ for centered bspline, * ‘i‘ for applying inverse transform. */ void MGL_EXPORT mgl_datac_wavelet(HADT dat, const char *how, int k); void MGL_EXPORT mgl_datac_wavelet_(uintptr_t *d, const char *dir, int *k,int); /// Set as the data envelop void MGL_EXPORT mgl_datac_envelop(HADT dat, char dir); void MGL_EXPORT mgl_datac_envelop_(uintptr_t *dat, const char *dir, int); /// Get real part of data values HMDT MGL_EXPORT mgl_datac_real(HCDT dat); uintptr_t MGL_EXPORT mgl_datac_real_(uintptr_t *dat); /// Get imaginary part of data values HMDT MGL_EXPORT mgl_datac_imag(HCDT dat); uintptr_t MGL_EXPORT mgl_datac_imag_(uintptr_t *dat); /// Get absolute value of data values, i.e. |u| HMDT MGL_EXPORT mgl_datac_abs(HCDT dat); uintptr_t MGL_EXPORT mgl_datac_abs_(uintptr_t *dat); /// Get argument of data values HMDT MGL_EXPORT mgl_datac_arg(HCDT dat); uintptr_t MGL_EXPORT mgl_datac_arg_(uintptr_t *dat); /// Get square of absolute value of data values, i.e. |u|^2 HMDT MGL_EXPORT mgl_datac_norm(HCDT dat); uintptr_t MGL_EXPORT mgl_datac_norm_(uintptr_t *dat); /// Interpolate by linear function the data to given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1] cmdual MGL_EXPORT mgl_datac_linear(HCDT d, mreal x,mreal y,mreal z); cmdual MGL_EXPORT mgl_datac_linear_(uintptr_t *d, mreal *x,mreal *y,mreal *z); /// Interpolate by linear function the data and return its derivatives at given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1] cmdual MGL_EXPORT mgl_datac_linear_ext(HCDT d, mreal x,mreal y,mreal z, mdual *dx,mdual *dy,mdual *dz); cmdual MGL_EXPORT mgl_datac_linear_ext_(uintptr_t *d, mreal *x,mreal *y,mreal *z, mdual *dx,mdual *dy,mdual *dz); /// Interpolate by cubic spline the data to given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1] cmdual MGL_EXPORT mgl_datac_spline(HCDT dat, mreal x,mreal y,mreal z); cmdual MGL_EXPORT mgl_datac_spline_(uintptr_t *dat, mreal *x,mreal *y,mreal *z); /// Interpolate by cubic spline the data and return its derivatives at given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1] cmdual MGL_EXPORT mgl_datac_spline_ext(HCDT dat, mreal x,mreal y,mreal z, mdual *dx,mdual *dy,mdual *dz); cmdual MGL_EXPORT mgl_datac_spline_ext_(uintptr_t *dat, mreal *x,mreal *y,mreal *z, mdual *dx,mdual *dy,mdual *dz); /// Prepare coefficients for global spline interpolation HADT MGL_EXPORT mgl_gsplinec_init(HCDT x, HCDT v); uintptr_t MGL_EXPORT mgl_gspline_init_(uintptr_t *x, uintptr_t *v); /// Evaluate global spline (and its derivatives d1, d2 if not NULL) using prepared coefficients \a coef cmdual MGL_EXPORT mgl_gsplinec(HCDT coef, mreal dx, mdual *d1, mdual *d2); cmdual MGL_EXPORT mgl_gsplinec_(uintptr_t *c, mreal *dx, mdual *d1, mdual *d2); /// Find roots for set of nonlinear equations defined by textual formulas HADT MGL_EXPORT mgl_find_roots_txt_c(const char *func, const char *vars, HCDT ini); uintptr_t MGL_EXPORT mgl_find_roots_txt_c_(const char *func, const char *vars, uintptr_t *ini,int,int); #ifdef __cplusplus } #endif //----------------------------------------------------------------------------- #endif
{ "alphanum_fraction": 0.7380054129, "avg_line_length": 63.6710182768, "ext": "h", "hexsha": "17b1cf6fc8f4ed9b75484406cdbede91decf43c4", "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": "0fb94e86217afee2e637de694b0148b99b052ccf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "angelamsj/cruise-control", "max_forks_repo_path": "mathgl-2.4.3/include/mgl2/datac_cf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0fb94e86217afee2e637de694b0148b99b052ccf", "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": "angelamsj/cruise-control", "max_issues_repo_path": "mathgl-2.4.3/include/mgl2/datac_cf.h", "max_line_length": 188, "max_stars_count": null, "max_stars_repo_head_hexsha": "0fb94e86217afee2e637de694b0148b99b052ccf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "angelamsj/cruise-control", "max_stars_repo_path": "mathgl-2.4.3/include/mgl2/datac_cf.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7366, "size": 24386 }
/******************************************************************************* * * This file is part of the General Hidden Markov Model Library, * GHMM version __VERSION__, see http://ghmm.org * * Filename: ghmm/ghmm/randvar.c * Authors: Bernhard Knab, Benjamin Rich, Janne Grunau * * Copyright (C) 1998-2004 Alexander Schliep * Copyright (C) 1998-2001 ZAIK/ZPR, Universitaet zu Koeln * Copyright (C) 2002-2004 Max-Planck-Institut fuer Molekulare Genetik, * Berlin * * Contact: schliep@ghmm.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * This file is version $Revision: 2310 $ * from $Date: 2013-06-14 10:36:57 -0400 (Fri, 14 Jun 2013) $ * last change by $Author: ejb177 $. * *******************************************************************************/ #ifdef HAVE_CONFIG_H # include "../config.h" #endif #include <math.h> #include <float.h> #include <string.h> #ifdef HAVE_LIBPTHREAD # include <pthread.h> #endif /* HAVE_LIBPTHREAD */ #include "ghmm.h" #include "mes.h" #include "mprintf.h" #include "randvar.h" #include "rng.h" #ifdef DO_WITH_GSL # include <gsl/gsl_math.h> # include <gsl/gsl_sf_erf.h> # include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #endif /* DO_WITH_GSL */ #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) #else static double ighmm_erf (double x); static double ighmm_erfc (double x); #endif /* check for ISO C99 */ /* A list of already calculated values of the density function of a N(0,1)-distribution, with x in [0.00, 19.99] */ #define PDFLEN 2000 #define X_STEP_PDF 0.01 /* step size */ #define X_FAKT_PDF 100 /* equivalent to step size */ static double pdf_stdnormal[PDFLEN]; static int pdf_stdnormal_exists = 0; /* A list of already calulated values PHI of the Gauss distribution is read in, x in [-9.999, 0] */ #define X_STEP_PHI 0.001 /* step size */ #define X_FAKT_PHI 1000 /* equivalent to step size */ static double x_PHI_1 = -1.0; #ifndef M_SQRT1_2 #define M_SQRT1_2 0.70710678118654752440084436210 #endif /*============================================================================*/ /* needed by ighmm_gtail_pmue_interpol */ double ighmm_rand_get_xfaktphi () { return X_FAKT_PHI; } double ighmm_rand_get_xstepphi () { return X_STEP_PHI; } double ighmm_rand_get_philen () { #ifdef DO_WITH_GSL return 0 /*PHI_len*/; #else return ighmm_rand_get_xPHIless1 () / X_STEP_PHI; #endif } /*============================================================================*/ double ighmm_rand_get_PHI (double x) { #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) return (erf (x * M_SQRT1_2) + 1.0) / 2.0; #else return (ighmm_erf (x * M_SQRT1_2) + 1.0) / 2.0; #endif } /* randvar_get_PHI */ /*============================================================================*/ /* When is PHI[x,0,1] == 1? */ double ighmm_rand_get_xPHIless1 () { # define CUR_PROC "ighmm_rand_get_xPHIless1" if (x_PHI_1 == -1) { double low, up, half; low = 0; up = 100; while (up - low > 0.001) { half = (low + up) / 2.0; if (ighmm_rand_get_PHI (half) < 1.0) low = half; else up = half; } x_PHI_1 = low; } return (x_PHI_1); # undef CUR_PROC } /*============================================================================*/ double ighmm_rand_get_1overa (double x, double mean, double u) { /* Calulates 1/a(x, mean, u), with a = the integral from x til \infty over the Gauss density function */ # define CUR_PROC "ighmm_rand_get_1overa" double erfc_value; if (u <= 0.0) { GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n"); goto STOP; } #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) erfc_value = erfc ((x - mean) / sqrt (u * 2)); #else erfc_value = ighmm_erfc ((x - mean) / sqrt (u * 2)); #endif if (erfc_value <= DBL_MIN) { ighmm_mes (MES_WIN, "a ~= 0.0 critical! (mue = %.2f, u =%.2f)\n", mean, u); return (erfc_value); } else return (2.0 / erfc_value); STOP: return (-1.0); # undef CUR_PROC } /* ighmm_rand_get_1overa */ /*============================================================================*/ /* REMARK: The calulation of this density function was testet, by calculating the following integral sum for arbitrary mue and u: for (x = 0, x < ..., x += step(=0.01/0.001/0.0001)) isum += step * ighmm_rand_normal_density_pos(x, mue, u); In each case, the sum "converged" evidently towards 1! (BK, 14.6.99) CHANGE: Truncate at -EPS_NDT (const.h), so that x = 0 doesn't lead to a problem. (BK, 15.3.2000) */ double ighmm_rand_normal_density_pos (double x, double mean, double u) { # define CUR_PROC "ighmm_rand_normal_density_pos" return ighmm_rand_normal_density_trunc (x, mean, u, -GHMM_EPS_NDT); # undef CUR_PROC } /* double ighmm_rand_normal_density_pos */ /*============================================================================*/ double ighmm_rand_normal_density_trunc(double x, double mean, double u, double a) { # define CUR_PROC "ighmm_rand_normal_density_trunc" #ifndef DO_WITH_GSL double c; #endif /* DO_WITH_GSL */ if (u <= 0.0) { GHMM_LOG(LERROR, "u <= 0.0 not allowed"); goto STOP; } if (x < a) return 0.0; #ifdef DO_WITH_GSL /* move mean to the right position */ return gsl_ran_gaussian_tail_pdf(x - mean, a - mean, sqrt(u)); #else if ((c = ighmm_rand_get_1overa(a, mean, u)) == -1) { GHMM_LOG_QUEUED(LERROR); goto STOP; }; return c * ighmm_rand_normal_density(x, mean, u); #endif /* DO_WITH_GSL */ STOP: return -1.0; # undef CUR_PROC } /* double ighmm_rand_normal_density_trunc */ /*============================================================================*/ double ighmm_rand_normal_density (double x, double mean, double u) { # define CUR_PROC "ighmm_rand_normal_density" #ifndef DO_WITH_GSL double expo; #endif if (u <= 0.0) { GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n"); goto STOP; } /* The denominator is possibly < EPS??? Check that ? */ #ifdef DO_WITH_GSL /* double gsl_ran_gaussian_pdf (double x, double sigma) */ return gsl_ran_gaussian_pdf (x - mean, sqrt (u)); #else expo = exp (-1 * m_sqr (mean - x) / (2 * u)); return (1 / (sqrt (2 * PI * u)) * expo); #endif STOP: return (-1.0); # undef CUR_PROC } /* double ighmm_rand_normal_density */ /*============================================================================*/ /* covariance matrix is linearized */ double ighmm_rand_binormal_density(const double *x, double *mean, double *cov) { # define CUR_PROC "ighmm_rand_binormal_density" double rho; #ifndef DO_WITH_GSL double numerator,part1,part2,part3; #endif if (cov[0] <= 0.0 || cov[2 + 1] <= 0.0) { GHMM_LOG(LCONVERTED, "variance <= 0.0 not allowed\n"); goto STOP; } rho = cov[1] / ( sqrt (cov[0]) * sqrt (cov[2 + 1]) ); /* The denominator is possibly < EPS??? Check that ? */ #ifdef DO_WITH_GSL /* double gsl_ran_bivariate_gaussian_pdf (double x, double y, double sigma_x, double sigma_y, double rho) */ return gsl_ran_bivariate_gaussian_pdf (x[0], x[1], sqrt (cov[0]), sqrt (cov[2 + 1]), rho); #else part1 = (x[0] - mean[0]) / sqrt (cov[0]); part2 = (x[1] - mean[1]) / sqrt (cov[2 + 1]); part3 = m_sqr (part1) - 2 * part1 * part2 + m_sqr (part2); numerator = exp ( -1 * (part3) / ( 2 * (1 - m_sqr(rho)) ) ); return (numerator / ( 2 * PI * sqrt(1 - m_sqr(rho)) )); #endif STOP: return (-1.0); # undef CUR_PROC } /* double ighmm_rand_binormal_density */ /*============================================================================*/ /* matrices are linearized */ double ighmm_rand_multivariate_normal_density(int length, const double *x, double *mean, double *sigmainv, double det) { # define CUR_PROC "ighmm_rand_multivariate_normal_density" /* multivariate normal density function */ /* * length dimension of the random vetor * x point at which to evaluate the pdf * mean vector of means of size n * sigmainv inverse variance matrix of dimension n x n * det determinant of covariance matrix */ #ifdef DO_WITH_GSL int i, j; double ax,ay; gsl_vector *ym, *xm, *gmean; gsl_matrix *inv = gsl_matrix_alloc(length, length); for (i=0; i<length; ++i) { for (j=0; j<length; ++j) { gsl_matrix_set(inv, i, j, sigmainv[i*length+j]); } } xm = gsl_vector_alloc(length); gmean = gsl_vector_alloc(length); /*gsl_vector_memcpy(xm, x);*/ for (i=0; i<length; ++i) { gsl_vector_set(xm, i, x[i]); gsl_vector_set(gmean, i, mean[i]); } gsl_vector_sub(xm, gmean); ym = gsl_vector_alloc(length); gsl_blas_dsymv(CblasUpper, 1.0, inv, xm, 0.0, ym); gsl_matrix_free(inv); gsl_blas_ddot(xm, ym, &ay); gsl_vector_free(xm); gsl_vector_free(ym); ay = exp(-0.5*ay) / sqrt(pow((2*M_PI), length) * det); return ay; #else /* do without GSL */ int i, j; double ay, tempv; ay = 0; for (i=0; i<length; ++i) { tempv = 0; for (j=0; j<length; ++j) { tempv += (x[j]-mean[j])*sigmainv[j*length+i]; } ay += tempv*(x[i]-mean[i]); } ay = exp(-0.5*ay) / sqrt(pow((2*PI), length) * det); return ay; #endif # undef CUR_PROC } /* double ighmm_rand_multivariate_normal_density */ /*============================================================================*/ double ighmm_rand_uniform_density (double x, double max, double min) { # define CUR_PROC "ighmm_rand_uniform_density" double prob; if (max <= min) { GHMM_LOG(LCONVERTED, "max <= min not allowed \n"); goto STOP; } prob = 1.0/(max-min); if ( (x <= max) && (x>=min) ){ return prob; }else{ return 0.0; } STOP: return (-1.0); # undef CUR_PROC } /* double ighmm_rand_uniform_density */ /*============================================================================*/ /* special ghmm_cmodel pdf need it: smo->density==normal_approx: */ /* generates a table of of aequidistant samples of gaussian pdf */ static int randvar_init_pdf_stdnormal () { # define CUR_PROC "randvar_init_pdf_stdnormal" int i; double x = 0.00; for (i = 0; i < PDFLEN; i++) { pdf_stdnormal[i] = 1 / (sqrt (2 * PI)) * exp (-1 * x * x / 2); x += (double) X_STEP_PDF; } pdf_stdnormal_exists = 1; /* printf("pdf_stdnormal_exists = %d\n", pdf_stdnormal_exists); */ return (0); # undef CUR_PROC } /* randvar_init_pdf_stdnormal */ double ighmm_rand_normal_density_approx (double x, double mean, double u) { # define CUR_PROC "ighmm_rand_normal_density_approx" #ifdef HAVE_LIBPTHREAD static pthread_mutex_t lock; #endif /* HAVE_LIBPTHREAD */ int i; double y, z, pdf_x; if (u <= 0.0) { GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n"); goto STOP; } if (!pdf_stdnormal_exists) { #ifdef HAVE_LIBPTHREAD pthread_mutex_lock (&lock); /* Put on a lock, because the clustering is parallel */ #endif /* HAVE_LIBPTHREAD */ randvar_init_pdf_stdnormal (); #ifdef HAVE_LIBPTHREAD pthread_mutex_unlock (&lock); /* Take the lock off */ #endif /* HAVE_LIBPTHREAD */ } y = 1 / sqrt (u); z = fabs ((x - mean) * y); i = (int) (z * X_FAKT_PDF); /* linear interpolation: */ if (i >= PDFLEN - 1) { i = PDFLEN - 1; pdf_x = y * pdf_stdnormal[i]; } else pdf_x = y * (pdf_stdnormal[i] + (z - i * X_STEP_PDF) * (pdf_stdnormal[i + 1] - pdf_stdnormal[i]) / X_STEP_PDF); return (pdf_x); STOP: return (-1.0); # undef CUR_PROC } /* double ighmm_rand_normal_density_approx */ double ighmm_rand_dirichlet(int seed, int len, double *alpha, double *theta){ if (seed != 0) { GHMM_RNG_SET(RNG, seed); } #ifdef DO_WITH_GSL gsl_ran_dirichlet(RNG, len, alpha, theta); #else printf("not implemted without gsl. Compile with gsl to use dirichlet"); #endif } /*============================================================================*/ double ighmm_rand_std_normal (int seed) { # define CUR_PROC "ighmm_rand_std_normal" if (seed != 0) { GHMM_RNG_SET (RNG, seed); } #ifdef DO_WITH_GSL return (gsl_ran_gaussian (RNG, 1.0)); #else /* Use the polar Box-Mueller transform */ /* double x, y, r2; do { x = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0; y = 2.0 * GHMM_RNG_UNIFORM(RNG) - 1.0; r2 = (x * x) + (y * y); } while (r2 >= 1.0); return x * sqrt((-2.0 * log(r2)) / r2); */ double r2, theta; r2 = -2.0 * log (GHMM_RNG_UNIFORM (RNG)); /* r2 ~ chi-square(2) */ theta = 2.0 * PI * GHMM_RNG_UNIFORM (RNG); /* theta ~ uniform(0, 2 \pi) */ return sqrt (r2) * cos (theta); #endif # undef CUR_PROC } /* ighmm_rand_std_normal */ /*============================================================================*/ double ighmm_rand_normal(double mue, double u, int seed) { # define CUR_PROC "ighmm_rand_normal" if (seed != 0) { GHMM_RNG_SET(RNG, seed); } #ifdef DO_WITH_GSL return gsl_ran_gaussian(RNG, sqrt (u)) + mue; #else double x; x = sqrt(u) * ighmm_rand_std_normal(seed) + mue; return x; #endif # undef CUR_PROC } /* ighmm_rand_normal */ /*============================================================================*/ int ighmm_rand_multivariate_normal (int dim, double *x, double *mue, double *sigmacd, int seed) { # define CUR_PROC "ighmm_rand_multivariate_normal" /* generate random vector of multivariate normal * * dim number of dimensions * x space to store resulting vector in * mue vector of means * sigmacd linearized cholesky decomposition of cov matrix * seed RNG seed * * see Barr & Slezak, A Comparison of Multivariate Normal Generators */ int i, j; #ifdef DO_WITH_GSL gsl_vector *y = gsl_vector_alloc(dim); gsl_vector *xgsl = gsl_vector_alloc(dim); gsl_matrix *cd = gsl_matrix_alloc(dim, dim); #endif if (seed != 0) { GHMM_RNG_SET (RNG, seed); /* do something here */ return 0; } else { #ifdef DO_WITH_GSL /* cholesky decomposition matrix */ for (i=0;i<dim;i++) { for (j=0;j<dim;j++) { gsl_matrix_set(cd, i, j, sigmacd[i*dim+j]); } } /* generate a random vector N(O,I) */ for (i=0;i<dim;i++) { gsl_vector_set(y, i, ighmm_rand_std_normal(seed)); } /* multiply cd with y */ gsl_blas_dgemv(CblasNoTrans, 1.0, cd, y, 0.0, xgsl); for (i=0;i<dim;i++) { x[i] = gsl_vector_get(xgsl, i) + mue[i]; } gsl_vector_free(y); gsl_vector_free(xgsl); gsl_matrix_free(cd); #else /* multivariate random numbers without gsl */ double randuni; for (i=0;i<dim;i++) { randuni = ighmm_rand_std_normal(seed); for (j=0;j<dim;j++) { if (i==0) x[j] = mue[j]; x[j] += randuni * sigmacd[j*dim+i]; } } #endif return 0; } # undef CUR_PROC } /* ighmm_rand_multivariate_normal */ /*============================================================================*/ #ifndef DO_WITH_GSL # define C0 2.515517 # define C1 0.802853 # define C2 0.010328 # define D1 1.432788 # define D2 0.189269 # define D3 0.001308 #endif double ighmm_rand_normal_right (double a, double mue, double u, int seed) { # define CUR_PROC "ighmm_rand_normal_right" double x = -1; double sigma; #ifdef DO_WITH_GSL double s; #else double U, Us, Us1, Feps, t, T; #endif if (u <= 0.0) { GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n"); goto STOP; } sigma = sqrt(u); if (seed != 0) { GHMM_RNG_SET (RNG, seed); } #ifdef DO_WITH_GSL /* move boundary to lower values in order to achieve maximum at mue gsl_ran_gaussian_tail(generator, lower_boundary, sigma) */ return mue + gsl_ran_gaussian_tail(RNG, a - mue, sqrt (u)); #else /* DO_WITH_GSL */ /* Inverse transformation with restricted sampling by Fishman */ U = GHMM_RNG_UNIFORM(RNG); Feps = ighmm_rand_get_PHI((a-mue) / sigma); Us = Feps + (1-Feps) * U; Us1 = 1-Us; t = m_min (Us, Us1); t = sqrt (-log (t * t)); T = sigma * (t - (C0 + t * (C1 + t * C2)) / (1 + t * (D1 + t * (D2 + t * D3)))); if (Us < Us1) x = mue - T; else x = mue + T; #endif /* DO_WITH_GSL */ STOP: return x; # undef CUR_PROC } /* randvar_normal_pos */ /*============================================================================*/ double ighmm_rand_uniform_int (int seed, int K) { # define CUR_PROC "ighmm_rand_uniform_int" if (seed != 0) { GHMM_RNG_SET (RNG, seed); } #ifdef DO_WITH_GSL /* more direct solution than old version ! */ return (double) gsl_rng_uniform_int (RNG, K); #else return (double) ((int) (((double) K) * GHMM_RNG_UNIFORM (RNG))); #endif # undef CUR_PROC } /* ighmm_rand_uniform_int */ /*===========================================================================*/ double ighmm_rand_uniform_cont (int seed, double max, double min) { # define CUR_PROC "ighmm_rand_uniform_cont" if (max <= min) { GHMM_LOG(LCONVERTED, "max <= min not allowed\n"); goto STOP; } if (seed != 0) { GHMM_RNG_SET (RNG, seed); } #ifdef DO_WITH_GSL return (double)(((double)gsl_rng_uniform (RNG)*(max-min)) + min); #else return (double)((GHMM_RNG_UNIFORM (RNG))*(max-min) + min ); #endif STOP: return (-1.0); # undef CUR_PROC } /* ighmm_rand_uniform_cont */ /*============================================================================*/ /* cumalative distribution function of N(mean, u) */ double ighmm_rand_normal_cdf (double x, double mean, double u) { # define CUR_PROC "ighmm_rand_normal_cdf" if (u <= 0.0) { GHMM_LOG(LCONVERTED, "u <= 0.0 not allowed\n"); goto STOP; } #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* PHI(x)=erf(x/sqrt(2))/2+0.5 */ return (erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0; #else return (ighmm_erf ((x - mean) / sqrt (u * 2.0)) + 1.0) / 2.0; #endif /* Check for ISO C99 */ STOP: return (-1.0); # undef CUR_PROC } /* double ighmm_rand_normal_cdf */ /*============================================================================*/ /* cumalative distribution function of a-truncated N(mean, u) */ double ighmm_rand_normal_right_cdf (double x, double mean, double u, double a) { # define CUR_PROC "ighmm_rand_normal_right_cdf" if (x <= a) return (0.0); if (u <= a) { GHMM_LOG(LCONVERTED, "u <= a not allowed\n"); goto STOP; } #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* Function: int erfc (double x, gsl_sf_result * result) These routines compute the complementary error function erfc(x) = 1 - erf(x) = 2/\sqrt(\pi) \int_x^\infty \exp(-t^2). */ return 1.0 + (erf ((x - mean) / sqrt (u * 2)) - 1.0) / erfc ((a - mean) / sqrt (u * 2)); #else return 1.0 + (ighmm_erf ((x - mean) / sqrt (u * 2)) - 1.0) / ighmm_erfc ((a - mean) / sqrt (u * 2)); #endif /* Check for ISO C99 */ STOP: return (-1.0); # undef CUR_PROC } /* double ighmm_rand_normal_cdf */ /*============================================================================*/ /* cumalative distribution function of a uniform distribution in the range [min,max] */ double ighmm_rand_uniform_cdf (double x, double max, double min) { # define CUR_PROC "ighmm_rand_uniform_cdf" if (max <= min) { GHMM_LOG(LCONVERTED, "max <= min not allowed\n"); goto STOP; } if (x < min) { return 0.0; } if (x >= max) { return 1.0; } return (x-min)/(max-min); STOP: return (-1.0); # undef CUR_PROC } /* ighmm_rand_uniform_cdf */ #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) #else /* THIS WILL BE OBSOLETE WHEN WE USE ISO C99 */ /*=========================================================================== * * The following functions for the error function and the complementory * error function are taken from * http://www.mathematik.uni-bielefeld.de/~sillke/ALGORITHMS/special-functions/erf.c * and have following different copyright. * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* * ==================================================== * * Reference: * * W. J. Cody, * Rational Chebychev approximations for the * error function. * Mathematics of Computations 23 (1969) 631-637 * * W. J. Cody, * Performance evaluations of programs for the * error and complementary error function. * Transactions of the ACM on Mathematical Software, * 16:1 (March 1990) 38-46 * * W. J. Cody, * SPECFUN - A portable special function package, * In: New Computing environments; * Microcomputers in Large-Scale Scientific Computing, * A. Wouk, SIAM, 1987, 1-12 * * W. J. Cody, * http://www.netlib.org/specfun/erf. * * For calculations with complex arguments see: * * Walter Gautschi * "Efficient computation of the complex error function" * SIAM J. Numer. Anal. * 7:1 (1970), 187-198 * * J.A.C. Weideman * "Computation of the complex error function" * SIAM J. Numer. Anal. * 31:5 (1994), 1497-1518 * * ==================================================== */ /* double erf(double x) * double erfc(double x) * x * 2 |\ * erf(x) = --------- | exp(-t*t)dt * sqrt(pi) \| * 0 * * erfc(x) = 1-erf(x) * Note that * erf(-x) = -erf(x) * erfc(-x) = 2 - erfc(x) * * Method: * 1. For |x| in [0, 0.84375] * erf(x) = x + x*R(x^2) * erfc(x) = 1 - erf(x) if x in [-.84375,0.25] * = 0.5 + ((0.5-x)-x*R) if x in [0.25,0.84375] * where R = P/Q where P is an odd poly of degree 8 and * Q is an odd poly of degree 10. * -57.90 * | R - (erf(x)-x)/x | <= 2 * * * Remark. The formula is derived by noting * erf(x) = (2/sqrt(pi))*(x - x^3/3 + x^5/10 - x^7/42 + ....) * and that * 2/sqrt(pi) = 1.128379167095512573896158903121545171688 * is close to one. The interval is chosen because the fix * point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is * near 0.6174), and by some experiment, 0.84375 is chosen to * guarantee the error is less than one ulp for erf. * * 2. For |x| in [0.84375,1.25], let s = |x| - 1, and * c = 0.84506291151 rounded to single (24 bits) * erf(x) = sign(x) * (c + P1(s)/Q1(s)) * erfc(x) = (1-c) - P1(s)/Q1(s) if x > 0 * 1+(c+P1(s)/Q1(s)) if x < 0 * |P1/Q1 - (erf(|x|)-c)| <= 2**-59.06 * Remark: here we use the taylor series expansion at x=1. * erf(1+s) = erf(1) + s*Poly(s) * = 0.845.. + P1(s)/Q1(s) * That is, we use rational approximation to approximate * erf(1+s) - (c = (single)0.84506291151) * Note that |P1/Q1|< 0.078 for x in [0.84375,1.25] * where * P1(s) = degree 6 poly in s * Q1(s) = degree 6 poly in s * * 3. For x in [1.25,1/0.35(~2.857143)], * erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1) * erf(x) = 1 - erfc(x) * where * R1(z) = degree 7 poly in z, (z=1/x^2) * S1(z) = degree 8 poly in z * * 4. For x in [1/0.35,28] * erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0 * = 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6<x<0 * = 2.0 - tiny (if x <= -6) * erf(x) = sign(x)*(1.0 - erfc(x)) if x < 6, else * erf(x) = sign(x)*(1.0 - tiny) * where * R2(z) = degree 6 poly in z, (z=1/x^2) * S2(z) = degree 7 poly in z * * Note1: * To compute exp(-x*x-0.5625+R/S), let s be a single * precision number and s := x; then * -x*x = -s*s + (s-x)*(s+x) * exp(-x*x-0.5626+R/S) = * exp(-s*s-0.5625)*exp((s-x)*(s+x)+R/S); * Note2: * Here 4 and 5 make use of the asymptotic series * exp(-x*x) * erfc(x) ~ ---------- * ( 1 + Poly(1/x^2) ) * x*sqrt(pi) * We use rational approximation to approximate * g(s)=f(1/x^2) = log(erfc(x)*x) - x*x + 0.5625 * Here is the error bound for R1/S1 and R2/S2 * |R1/S1 - f(x)| < 2**(-62.57) * |R2/S2 - f(x)| < 2**(-61.52) * * 5. For inf > x >= 28 * erf(x) = sign(x) *(1 - tiny) (raise inexact) * erfc(x) = tiny*tiny (raise underflow) if x > 0 * = 2 - tiny if x<0 * * 7. Special case: * erf(0) = 0, erf(inf) = 1, erf(-inf) = -1, * erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2, * erfc/erf(NaN) is NaN */ static const double tiny = 1e-300, half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */ one = 1.00000000000000000000e+00, /* 0x3FF00000, 0x00000000 */ two = 2.00000000000000000000e+00, /* 0x40000000, 0x00000000 */ erx = 8.45062911510467529297e-01, /* 0x3FEB0AC1, 0x60000000 */ /* * Coefficients for approximation to erf on [0,0.84375] */ efx = 1.28379167095512586316e-01, /* 0x3FC06EBA, 0x8214DB69 */ efx8 = 1.02703333676410069053e+00, /* 0x3FF06EBA, 0x8214DB69 */ pp0 = 1.28379167095512558561e-01, /* 0x3FC06EBA, 0x8214DB68 */ pp1 = -3.25042107247001499370e-01, /* 0xBFD4CD7D, 0x691CB913 */ pp2 = -2.84817495755985104766e-02, /* 0xBF9D2A51, 0xDBD7194F */ pp3 = -5.77027029648944159157e-03, /* 0xBF77A291, 0x236668E4 */ pp4 = -2.37630166566501626084e-05, /* 0xBEF8EAD6, 0x120016AC */ qq1 = 3.97917223959155352819e-01, /* 0x3FD97779, 0xCDDADC09 */ qq2 = 6.50222499887672944485e-02, /* 0x3FB0A54C, 0x5536CEBA */ qq3 = 5.08130628187576562776e-03, /* 0x3F74D022, 0xC4D36B0F */ qq4 = 1.32494738004321644526e-04, /* 0x3F215DC9, 0x221C1A10 */ qq5 = -3.96022827877536812320e-06, /* 0xBED09C43, 0x42A26120 */ /* * Coefficients for approximation to erf in [0.84375,1.25] */ pa0 = -2.36211856075265944077e-03, /* 0xBF6359B8, 0xBEF77538 */ pa1 = 4.14856118683748331666e-01, /* 0x3FDA8D00, 0xAD92B34D */ pa2 = -3.72207876035701323847e-01, /* 0xBFD7D240, 0xFBB8C3F1 */ pa3 = 3.18346619901161753674e-01, /* 0x3FD45FCA, 0x805120E4 */ pa4 = -1.10894694282396677476e-01, /* 0xBFBC6398, 0x3D3E28EC */ pa5 = 3.54783043256182359371e-02, /* 0x3FA22A36, 0x599795EB */ pa6 = -2.16637559486879084300e-03, /* 0xBF61BF38, 0x0A96073F */ qa1 = 1.06420880400844228286e-01, /* 0x3FBB3E66, 0x18EEE323 */ qa2 = 5.40397917702171048937e-01, /* 0x3FE14AF0, 0x92EB6F33 */ qa3 = 7.18286544141962662868e-02, /* 0x3FB2635C, 0xD99FE9A7 */ qa4 = 1.26171219808761642112e-01, /* 0x3FC02660, 0xE763351F */ qa5 = 1.36370839120290507362e-02, /* 0x3F8BEDC2, 0x6B51DD1C */ qa6 = 1.19844998467991074170e-02, /* 0x3F888B54, 0x5735151D */ /* * Coefficients for approximation to erfc in [1.25,1/0.35] */ ra0 = -9.86494403484714822705e-03, /* 0xBF843412, 0x600D6435 */ ra1 = -6.93858572707181764372e-01, /* 0xBFE63416, 0xE4BA7360 */ ra2 = -1.05586262253232909814e+01, /* 0xC0251E04, 0x41B0E726 */ ra3 = -6.23753324503260060396e+01, /* 0xC04F300A, 0xE4CBA38D */ ra4 = -1.62396669462573470355e+02, /* 0xC0644CB1, 0x84282266 */ ra5 = -1.84605092906711035994e+02, /* 0xC067135C, 0xEBCCABB2 */ ra6 = -8.12874355063065934246e+01, /* 0xC0545265, 0x57E4D2F2 */ ra7 = -9.81432934416914548592e+00, /* 0xC023A0EF, 0xC69AC25C */ sa1 = 1.96512716674392571292e+01, /* 0x4033A6B9, 0xBD707687 */ sa2 = 1.37657754143519042600e+02, /* 0x4061350C, 0x526AE721 */ sa3 = 4.34565877475229228821e+02, /* 0x407B290D, 0xD58A1A71 */ sa4 = 6.45387271733267880336e+02, /* 0x40842B19, 0x21EC2868 */ sa5 = 4.29008140027567833386e+02, /* 0x407AD021, 0x57700314 */ sa6 = 1.08635005541779435134e+02, /* 0x405B28A3, 0xEE48AE2C */ sa7 = 6.57024977031928170135e+00, /* 0x401A47EF, 0x8E484A93 */ sa8 = -6.04244152148580987438e-02, /* 0xBFAEEFF2, 0xEE749A62 */ /* * Coefficients for approximation to erfc in [1/.35,28] */ rb0 = -9.86494292470009928597e-03, /* 0xBF843412, 0x39E86F4A */ rb1 = -7.99283237680523006574e-01, /* 0xBFE993BA, 0x70C285DE */ rb2 = -1.77579549177547519889e+01, /* 0xC031C209, 0x555F995A */ rb3 = -1.60636384855821916062e+02, /* 0xC064145D, 0x43C5ED98 */ rb4 = -6.37566443368389627722e+02, /* 0xC083EC88, 0x1375F228 */ rb5 = -1.02509513161107724954e+03, /* 0xC0900461, 0x6A2E5992 */ rb6 = -4.83519191608651397019e+02, /* 0xC07E384E, 0x9BDC383F */ sb1 = 3.03380607434824582924e+01, /* 0x403E568B, 0x261D5190 */ sb2 = 3.25792512996573918826e+02, /* 0x40745CAE, 0x221B9F0A */ sb3 = 1.53672958608443695994e+03, /* 0x409802EB, 0x189D5118 */ sb4 = 3.19985821950859553908e+03, /* 0x40A8FFB7, 0x688C246A */ sb5 = 2.55305040643316442583e+03, /* 0x40A3F219, 0xCEDF3BE6 */ sb6 = 4.74528541206955367215e+02, /* 0x407DA874, 0xE79FE763 */ sb7 = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */ static double ighmm_erf (double x) { double R,S,P,Q,s,y,z,r; double ax = fabs(x); #ifdef HAVE_IEEE754 if (!isfinite(x)) { if (isnan(x)) return x; /* erf(nan)=nan */ return (x==ax) ? 1 : -1; /* erf(+-inf)=+-1 */ } #endif if (ax < 0.84375) { /* |x|<0.84375 */ if (ax < 3.7252903e-9) { /* |x|<2**-28 */ if (ax < tiny) return 0.125*(8.0*x+efx8*x); /*avoid underflow */ return x + efx*x; } z = x*x; r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4))); s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5)))); y = r/s; return x + x*y; } if (ax < 1.25) { /* 0.84375 <= |x| < 1.25 */ s = ax-one; P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6))))); Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6))))); if (x>=0) return erx + P/Q; else return -erx - P/Q; } if (ax >= 6.0) { /* inf>|x|>=6 */ if (x>=0) return one-tiny; else return tiny-one; } s = one/(x*x); if (ax < 2.857142857) { /* |x| < 1/0.35 */ R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7)))))); S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8))))))); } else { /* |x| >= 1/0.35 */ R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6))))); S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7)))))); } z = (double)(float) ax; r = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S); if (x>=0) return one-r/ax; else return r/ax-one; } static double ighmm_erfc (double x) { double R,S,P,Q,s,y,z,r; double ax = fabs(x); #ifdef HAVE_IEEE754 if (!isfinite(x)) { if (isnan(x)) return x; /* erfc(nan)=nan */ return (x==ax) ? 0 : 2; /* erfc(+-inf)=0,2 */ } #endif if (ax < 0.84375) { /* |x|<0.84375 */ if (ax < 13.8777878e-18) /* |x|<2**-56 */ return one-x; z = x*x; r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4))); s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5)))); y = r/s; if (ax < 0.25) { /* x<1/4 */ return one-(x+x*y); } else { r = x*y; r += (x-half); return half - r ; } } if (ax < 1.25) { /* 0.84375 <= |x| < 1.25 */ s = fabs(x)-one; P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6))))); Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6))))); if (x>=0) { z = one-erx; return z - P/Q; } else { z = erx+P/Q; return one+z; } } if (ax < 28.0) { /* |x|<28 */ s = one/(x*x); if (ax < 2.857142857) { /* |x| < 1/.35 ~ 2.857143*/ R=ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7)))))); S=one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8))))))); } else { /* |x| >= 1/.35 ~ 2.857143 */ if (x < -6.0) return two-tiny;/* x < -6 */ R=rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6))))); S=one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7)))))); } z = (double)(float) ax; r = exp(-z*z-0.5625)*exp((z-ax)*(z+ax)+R/S); if (x>0) return r/ax; else return two-r/ax; } else { if(x>0) return tiny*tiny; else return two-tiny; } } #endif /* check for ISO C99 */
{ "alphanum_fraction": 0.5614150605, "avg_line_length": 30.7944700461, "ext": "c", "hexsha": "e56b71e01e7135d101c35b16089a28c183c38051", "lang": "C", "max_forks_count": 25, "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_line_length": 118, "max_stars_count": 7, "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/randvar.c", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "num_tokens": 11645, "size": 33412 }
/* vector/gsl_vector_long_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_LONG_DOUBLE_H__ #define __GSL_VECTOR_LONG_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_long_double.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; long double *data; gsl_block_long_double *block; int owner; } gsl_vector_long_double; typedef struct { gsl_vector_long_double vector; } _gsl_vector_long_double_view; typedef _gsl_vector_long_double_view gsl_vector_long_double_view; typedef struct { gsl_vector_long_double vector; } _gsl_vector_long_double_const_view; typedef const _gsl_vector_long_double_const_view gsl_vector_long_double_const_view; /* Allocation */ gsl_vector_long_double *gsl_vector_long_double_alloc (const size_t n); gsl_vector_long_double *gsl_vector_long_double_calloc (const size_t n); gsl_vector_long_double *gsl_vector_long_double_alloc_from_block (gsl_block_long_double * b, const size_t offset, const size_t n, const size_t stride); gsl_vector_long_double *gsl_vector_long_double_alloc_from_vector (gsl_vector_long_double * v, const size_t offset, const size_t n, const size_t stride); void gsl_vector_long_double_free (gsl_vector_long_double * v); /* Views */ _gsl_vector_long_double_view gsl_vector_long_double_view_array (long double *v, size_t n); _gsl_vector_long_double_view gsl_vector_long_double_view_array_with_stride (long double *base, size_t stride, size_t n); _gsl_vector_long_double_const_view gsl_vector_long_double_const_view_array (const long double *v, size_t n); _gsl_vector_long_double_const_view gsl_vector_long_double_const_view_array_with_stride (const long double *base, size_t stride, size_t n); _gsl_vector_long_double_view gsl_vector_long_double_subvector (gsl_vector_long_double *v, size_t i, size_t n); _gsl_vector_long_double_view gsl_vector_long_double_subvector_with_stride (gsl_vector_long_double *v, size_t i, size_t stride, size_t n); _gsl_vector_long_double_const_view gsl_vector_long_double_const_subvector (const gsl_vector_long_double *v, size_t i, size_t n); _gsl_vector_long_double_const_view gsl_vector_long_double_const_subvector_with_stride (const gsl_vector_long_double *v, size_t i, size_t stride, size_t n); /* Operations */ void gsl_vector_long_double_set_zero (gsl_vector_long_double * v); void gsl_vector_long_double_set_all (gsl_vector_long_double * v, long double x); int gsl_vector_long_double_set_basis (gsl_vector_long_double * v, size_t i); int gsl_vector_long_double_fread (FILE * stream, gsl_vector_long_double * v); int gsl_vector_long_double_fwrite (FILE * stream, const gsl_vector_long_double * v); int gsl_vector_long_double_fscanf (FILE * stream, gsl_vector_long_double * v); int gsl_vector_long_double_fprintf (FILE * stream, const gsl_vector_long_double * v, const char *format); int gsl_vector_long_double_memcpy (gsl_vector_long_double * dest, const gsl_vector_long_double * src); int gsl_vector_long_double_reverse (gsl_vector_long_double * v); int gsl_vector_long_double_swap (gsl_vector_long_double * v, gsl_vector_long_double * w); int gsl_vector_long_double_swap_elements (gsl_vector_long_double * v, const size_t i, const size_t j); long double gsl_vector_long_double_max (const gsl_vector_long_double * v); long double gsl_vector_long_double_min (const gsl_vector_long_double * v); void gsl_vector_long_double_minmax (const gsl_vector_long_double * v, long double * min_out, long double * max_out); size_t gsl_vector_long_double_max_index (const gsl_vector_long_double * v); size_t gsl_vector_long_double_min_index (const gsl_vector_long_double * v); void gsl_vector_long_double_minmax_index (const gsl_vector_long_double * v, size_t * imin, size_t * imax); int gsl_vector_long_double_add (gsl_vector_long_double * a, const gsl_vector_long_double * b); int gsl_vector_long_double_sub (gsl_vector_long_double * a, const gsl_vector_long_double * b); int gsl_vector_long_double_mul (gsl_vector_long_double * a, const gsl_vector_long_double * b); int gsl_vector_long_double_div (gsl_vector_long_double * a, const gsl_vector_long_double * b); int gsl_vector_long_double_scale (gsl_vector_long_double * a, const long double x); int gsl_vector_long_double_add_constant (gsl_vector_long_double * a, const long double x); int gsl_vector_long_double_axpby (const long double alpha, const gsl_vector_long_double * x, const long double beta, gsl_vector_long_double * y); long double gsl_vector_long_double_sum (const gsl_vector_long_double * a); int gsl_vector_long_double_equal (const gsl_vector_long_double * u, const gsl_vector_long_double * v); int gsl_vector_long_double_isnull (const gsl_vector_long_double * v); int gsl_vector_long_double_ispos (const gsl_vector_long_double * v); int gsl_vector_long_double_isneg (const gsl_vector_long_double * v); int gsl_vector_long_double_isnonneg (const gsl_vector_long_double * v); INLINE_DECL long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i); INLINE_DECL void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x); INLINE_DECL long double * gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i); INLINE_DECL const long double * gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } INLINE_FUN void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } INLINE_FUN long double * gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (long double *) (v->data + i * v->stride); } INLINE_FUN const long double * gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const long double *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_LONG_DOUBLE_H__ */
{ "alphanum_fraction": 0.71287359, "avg_line_length": 36.9055793991, "ext": "h", "hexsha": "369fcd53bec1aa683db3030bc26248390c5f2077", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-12-10T09:43:54.000Z", "max_forks_repo_forks_event_min_datetime": "2021-12-10T09:43:54.000Z", "max_forks_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "shakfu/pd-psl", "max_forks_repo_path": "include/gsl/gsl_vector_long_double.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "shakfu/pd-psl", "max_issues_repo_path": "include/gsl/gsl_vector_long_double.h", "max_line_length": 145, "max_stars_count": null, "max_stars_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "shakfu/pd-psl", "max_stars_repo_path": "include/gsl/gsl_vector_long_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1949, "size": 8599 }
/** * @file optimizers.h * @author Carl Boettiger <cboettig@gmail.com> * @date 22 April 2011 * * @section LICENSE * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_siman.h> /* set up parameters for this simulated annealing run */ #define N_TRIES 200 /* how many points do we try before stepping */ #define ITERS_FIXED_T 200 /* how many iterations for each T? */ #define STEP_SIZE .02 /* max step size in random walk */ #define K 1.0 /* Boltzmann constant */ #define T_INITIAL 0.05 /* initial temperature */ #define MU_T 1.004 /* damping factor for temperature */ #define T_MIN .008 /* setup parameters for multimin method*/ #define INIT_STEP .2 #define MAX_ITER 10000 #define ERR_TOL 1e-8 #define PRINT 1 #include <gsl/gsl_multimin.h> double optim_func (const gsl_vector *v, void *params); double multimin(gsl_vector *x, void * params); double siman(gsl_vector * x, void * params, gsl_rng * rng);
{ "alphanum_fraction": 0.7269524369, "avg_line_length": 34.7551020408, "ext": "h", "hexsha": "57b5e5c3c367822fe10f3fd31ebd9ee6025a6f1b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "cboettig/wrightscape", "max_forks_repo_path": "src/optimizers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "cboettig/wrightscape", "max_issues_repo_path": "src/optimizers.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "cboettig/wrightscape", "max_stars_repo_path": "src/optimizers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 443, "size": 1703 }
#ifndef __GSL_MATRIX_H__ #define __GSL_MATRIX_H__ #include <gsl/gsl_matrix_complex_long_double.h> #include <gsl/gsl_matrix_complex_double.h> #include <gsl/gsl_matrix_complex_float.h> #include <gsl/gsl_matrix_long_double.h> #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_matrix_float.h> #include <gsl/gsl_matrix_ulong.h> #include <gsl/gsl_matrix_long.h> #include <gsl/gsl_matrix_uint.h> #include <gsl/gsl_matrix_int.h> #include <gsl/gsl_matrix_ushort.h> #include <gsl/gsl_matrix_short.h> #include <gsl/gsl_matrix_uchar.h> #include <gsl/gsl_matrix_char.h> #endif /* __GSL_MATRIX_H__ */
{ "alphanum_fraction": 0.7976588629, "avg_line_length": 23, "ext": "h", "hexsha": "43c41169e56b0c5ec40d823981d9cc3df8ae606b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "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_matrix.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_matrix.h", "max_line_length": 47, "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_matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 170, "size": 598 }
/* Compile with: export LDLIBS="`pkg-config --libs gsl`" export CFLAGS="`pkg-config --cflags gsl` -g -Wall -std=gnu11 -O3" make gsl_erf */ #include <gsl/gsl_cdf.h> #include <stdio.h> int main(){ double bottom_tail = gsl_cdf_gaussian_P(-1.96, 1); printf("Area between [-1.96, 1.96]: %g\n", 1-2*bottom_tail); }
{ "alphanum_fraction": 0.6603773585, "avg_line_length": 24.4615384615, "ext": "c", "hexsha": "88b09605f539c6917aa30783b7ad5a08ce390e95", "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": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "catalingheorghe/learning-activities", "max_forks_repo_path": "progr/c/21st-century-c/21st-Century-Examples/gsl_erf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "catalingheorghe/learning-activities", "max_issues_repo_path": "progr/c/21st-century-c/21st-Century-Examples/gsl_erf.c", "max_line_length": 65, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "catalingheorghe/learning-activities", "max_stars_repo_path": "progr/c/21st-century-c/21st-Century-Examples/gsl_erf.c", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-10T11:24:07.000Z", "num_tokens": 113, "size": 318 }
// TRENTO: Reduced Thickness Event-by-event Nuclear Topology // Copyright 2015 Jonah E. Bernhard, J. Scott Moreland // TRENTO3D: Three-dimensional extension of TRENTO by Weiyao Ke // MIT License #ifndef ETA_H #define ETA_H #include <cmath> #include <vector> #include <gsl/gsl_fft_complex.h> /// GSL fft of complex array, z_i = x_i + j*y_i /// data are stored in one real array A that A[2i] = x_i and A[2i+1] = y_i #define REAL(z,i) ((z)[2*(i)]) #define IMAG(z,i) ((z)[2*(i)+1]) double const sqrt2 = std::sqrt(2); constexpr double TINY = 1e-12; constexpr int relative_skew_switch = 1; constexpr int absolute_skew_switch = 2; /// the mean of the rapidity distribution as function of Ta(x,y), /// Tb(x,y) and exp(y_beam). /// For the case both Ta and Tb are tiny small, mean = 0.0 is returned. /// For the case only Ta(Tb) = 0, it returns +(-)y_beam, /// For the case y_beam >> 1, mean ~ 0.5*log(Ta/Tb) double inline mean_function(double ta, double tb, double exp_ybeam){ if (ta < TINY && tb < TINY) return 0.; return 0.5 * std::log((ta*exp_ybeam + tb/exp_ybeam) / std::max(ta/exp_ybeam + tb*exp_ybeam, TINY)); } /// The coefficient of normalized width of the rapidity distribution /// Currently, it is simply a constant independent of Ta(x,y) and Tb(x,y) double inline std_function(double ta, double tb){ (void)ta; (void)tb; return 1.; } /// The normalized skewness as function of Ta(x,y) and Tb(x,y) double inline skew_function(double ta, double tb, int type_switch){ if (type_switch == relative_skew_switch) return (ta - tb)/std::max(ta + tb, TINY); else if(type_switch == absolute_skew_switch) return ta-tb; else return 0.; } /// A fast pseudorapidity to rapidity transformer using pretabulated values /// It returns the transfoamtion y(eta) and the jacobian dy/deta(eta) class fast_eta2y { private: double etamax_; double deta_; std::size_t neta_; std::vector<double> y_; std::vector<double> dydeta_; public: fast_eta2y(double J, double etamax, double deta) : etamax_(etamax), deta_(deta), neta_(std::ceil(2.*etamax_/(deta_+1e-15))+1), y_(neta_, 0.), dydeta_(neta_, 0.) { for (std::size_t ieta = 0; ieta < neta_; ++ieta) { double eta = -etamax_ + ieta*deta_; double Jsh = J*std::sinh(eta); double sq = std::sqrt(1. + Jsh*Jsh); y_[ieta] = std::log(sq + Jsh); dydeta_[ieta] = J*std::cosh(eta)/sq; } } double rapidity(double eta){ double steps = (eta + etamax_)/deta_; double xi = std::fmod(steps, 1.); std::size_t index = std::floor(steps); return y_[index]*(1. - xi) + y_[index+1]*xi; } double Jacobian(double eta){ double steps = (eta + etamax_)/deta_; double xi = std::fmod(steps, 1.); std::size_t index = std::floor(steps); return dydeta_[index]*(1. - xi) + dydeta_[index+1]*xi; } }; /// A class for cumulant generating function inversion /// This class handles inverse fourier transform the cumulant generating function /// A direct transformation F^{-1} exp(i*m*k-(std*k)^2/2-skew*(std*k)^3/6) results /// in an ill-behaved function. Instead, skew is replaced by skew*exp(-(std*k)^2/2). /// In this way higher order cumulant are included to regulated the function. /// The reconstruction range is taken to be [-3.33, 3.33]*std, which does not /// seem to be very large, however, by trail and error, this range elimiates /// oscillations at large rapidity and leaves the details close to mid-rapidity /// unchanged. We used GSL FFT library (more specialized library would be FFTW, /// e.g.), with 256 points. The transformed results are stored and interpolated. class cumulant_generating{ private: size_t const N; double * data, * dsdy; double eta_max; double deta; double center; public: cumulant_generating(): N(256), data(new double[2*N]), dsdy(new double[2*N]){}; /// This function set the mean, std and skew of the profile and use FFT to /// transform cumulant generating function at zero mean. void calculate_dsdy(double mean, double std, double skew){ double k1, k2, k3, amp, arg; // adaptive eta_max = 3.33*std; center = mean; eta_max = std*3.33; deta = 2.*eta_max/(N-1.); double fftmean = eta_max/std; for(size_t i=0;i<N;i++){ k1 = M_PI*(i-N/2.0)/eta_max*std; k2 = k1*k1; k3 = k2*k1; amp = std::exp(-k2/2.0); arg = fftmean*k1+skew/6.0*k3*amp; REAL(data,i) = amp*std::cos(arg); IMAG(data,i) = amp*std::sin(arg); } gsl_fft_complex_radix2_forward(data, 1, N); for(size_t i=0;i<N;i++){ dsdy[i] = REAL(data,i)*(2.0*static_cast<double>(i%2 == 0)-1.0); } } /// When interpolating the funtion, the mean is put back by simply shifting /// the function by y = y - mean + dy/2, the last term is correcting for /// interpolating bin edge instead of bin center double interp_dsdy(double y){ y = y-center+deta/2.; if (y < -eta_max || y >= eta_max) return 0.0; double xy = (y+eta_max)/deta; size_t iy = std::floor(xy); double ry = xy-iy; return dsdy[iy]*(1.-ry) + dsdy[iy+1]*ry; } }; #endif
{ "alphanum_fraction": 0.6506117693, "avg_line_length": 33.4350649351, "ext": "h", "hexsha": "bf683e05fc703aeeb86eb9ce368d28cdd364e2e1", "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": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "K-JW/trento", "max_forks_repo_path": "src/rapidity_profile.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "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": "K-JW/trento", "max_issues_repo_path": "src/rapidity_profile.h", "max_line_length": 101, "max_stars_count": 1, "max_stars_repo_head_hexsha": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "K-JW/trento", "max_stars_repo_path": "src/rapidity_profile.h", "max_stars_repo_stars_event_max_datetime": "2020-01-02T08:46:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-02T08:46:01.000Z", "num_tokens": 1598, "size": 5149 }
// // @author raver119@gmail.com // #ifndef LIBND4J_GEMM_H #define LIBND4J_GEMM_H #include <cblas.h> #include <templatemath.h> namespace nd4j { namespace blas { template <typename T> class GEMM { protected: static inline int linearIndexC(int rows, int cols, int r, int c); static inline int linearIndexF(int rows, int cols, int r, int c); static T* transpose(int orderSource, int orderTarget, int rows, int cols, T *source); public: static void op(int Order, int TransA, int TransB, int M, int N, int K, T alpha, T *A, int lda, T *B, int ldb, T beta, T *C, int ldc); }; template <typename T> class GEMV : public nd4j::blas::GEMM<T>{ public: static void op(int TRANS, int M, int N, T alpha, T* A, int lda, T* X, int incx, T beta, T* Y, int incy ); }; } } #endif //LIBND4J_GEMM_H
{ "alphanum_fraction": 0.5816435432, "avg_line_length": 23.425, "ext": "h", "hexsha": "1480ae770c2db1ee8fbf13c3019c666a89cf84c5", "lang": "C", "max_forks_count": 108, "max_forks_repo_forks_event_max_datetime": "2021-03-29T05:25:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-01-19T15:11:03.000Z", "max_forks_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rexwong/deeplearning4j", "max_forks_repo_path": "libnd4j/include/ops/gemm.h", "max_issues_count": 331, "max_issues_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38", "max_issues_repo_issues_event_max_datetime": "2018-06-08T07:16:15.000Z", "max_issues_repo_issues_event_min_datetime": "2016-03-07T21:26:26.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rexwong/deeplearning4j", "max_issues_repo_path": "libnd4j/include/ops/gemm.h", "max_line_length": 145, "max_stars_count": 97, "max_stars_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rexwong/deeplearning4j", "max_stars_repo_path": "libnd4j/include/ops/gemm.h", "max_stars_repo_stars_event_max_datetime": "2021-05-09T17:36:38.000Z", "max_stars_repo_stars_event_min_datetime": "2016-02-15T07:08:45.000Z", "num_tokens": 272, "size": 937 }
/** * Copyright 2019 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es> * * This file is part of Matrix Market Suite. * * Matrix Market Suite is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Matrix Market Suite is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>. */ #include <cblas.h> #include "ConjugateGradientSolver.h" #include <time.h> /* Include redundant execution header. */ #include "../../../include/ourRMTlib.h" int ipow(int base, int exp) { int result = 1; for (;;) { if (exp & 1) result *= base; exp >>= 1; if (!exp) break; base *= base; } return result; } int ConjugateGradientSolver(unsigned long *II, unsigned long *J, double *A, unsigned long M, unsigned long N, unsigned long long nz, double *b, unsigned long M_Vector, unsigned long N_Vector, unsigned long long nz_vector, double *x, int iterationNumber, int F, int *ret_code) { //A*x=b double *Ap=(double *) malloc(nz_vector * sizeof(double)); double *r=(double *) malloc(nz_vector * sizeof(double)); double *p=(double *) malloc(nz_vector * sizeof(double)); //double *x=(double *) calloc(nz_vector,sizeof(double)); //r = b-A*x //If we take x=0 the init multiplication is avoided and r=b memcpy(r, b, N*sizeof(double)); //p=r memcpy(p, r, N*sizeof(double)); //rsold = r'*r double rsold = cblas_ddot(N,r,1,r,1); double rs_0 = cblas_ddot(N,r,1,r,1); int stop = 0; double alphaCG = 0.0; double rsnew = 0.0, rsnew2 = 0.0; unsigned long k = 0, selfCG_k=0; unsigned long maxIterations = M*2; if(iterationNumber != 0 ){ maxIterations = iterationNumber; } int flag=0; while(!stop){ //if( ((k+1) % F == 0) ){ //execute CG reliably //if(k == pow((double)F, (double)(selfCG_k+1))){ if(k == ipow(F, (selfCG_k+1))){ //fprintf(stderr, "F:%d k:%lu selfCG_k:%lu \n",F,k, selfCG_k); //Ap=A*p cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, p, 1, 0.0, Ap, 1); //r=A*x cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, x, 1, 0.0, r, 1); //r=b-r cblas_dscal(N, -1, r, 1); //r = -r cblas_daxpy(N, 1, b, 1, r, 1); //r = r + b //alphaCG=r'*p /(p'*Ap) alphaCG = cblas_ddot(N,r,1,p,1)/cblas_ddot(N,p,1,Ap,1); //x=x+alphaCG*p cblas_daxpy(N,alphaCG,p,1,x,1); //r=r-alphaCG*Ap cblas_daxpy(N,-alphaCG,Ap,1,r,1); //rsnew = r'*r rsnew = cblas_ddot(N,r,1,r,1); //fprintf(stderr, "k:%ld F_iteration:%ld alphaCG:%.10f error:%.10f\n",k,selfCG_k,alphaCG, sqrt(rsnew)); // p=r+((-r'*Ap/(p'*Ap))*p) cblas_dscal(N, -(cblas_ddot(N,r,1,Ap,1)/cblas_ddot(N,p,1,Ap,1)), p, 1); cblas_daxpy(N,1.0,r,1,p,1); selfCG_k++; flag=0; }else{ //Ap=A*p cblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, p, 1, 0.0, Ap, 1); //alphaCG=rsold/(p'*Ap) alphaCG = rsold/cblas_ddot(N,p,1,Ap,1); //x=x+alphaCG*p cblas_daxpy(N,alphaCG,p,1,x,1); //r=r-alphaCG*Ap cblas_daxpy(N,-alphaCG,Ap,1,r,1); //rsnew = r'*r rsnew = cblas_ddot(N,r,1,r,1); //fprintf(stderr, "k:%ld alphaCG:%.10f error:%.10f\n",k,alphaCG, sqrt(rsnew)); //p=r+rsnew/rsold*p cblas_dscal(N, rsnew/rsold, p, 1); cblas_daxpy(N,1.0,r,1,p,1); rsold = rsnew; if(isnan(alphaCG)){ //checking whether alphaCG is nan! fprintf(stderr, "!!! alphaCG:%.10f\n", alphaCG); exit(-1); } } k++; //if((sqrt(rsnew)<=EPSILON)||(k == maxIterations)){ if(sqrt(rsnew)/sqrt(rs_0)<=EPSILON){ stop = 1; fprintf(stderr, "STOPPED by CG\n"); } } //memcpy(b, x, N*sizeof(double)); free(Ap); free(r); free(p); //free(x); fprintf(stderr, "[%s] Number of total iterations: %lu Number of iterations in SS step:%lu \n",__func__,k, selfCG_k); *ret_code=1; return 1; }
{ "alphanum_fraction": 0.5888494003, "avg_line_length": 24.3351351351, "ext": "c", "hexsha": "dd3e06069903e82ff588cf68e0542d39926c69c2", "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": "8e7ab9d3491e40d9e5e77f67956752cc1178b1b4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sanemarslan/RMTLib", "max_forks_repo_path": "applications/others/sscg/ConjugateGradientSolver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8e7ab9d3491e40d9e5e77f67956752cc1178b1b4", "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": "sanemarslan/RMTLib", "max_issues_repo_path": "applications/others/sscg/ConjugateGradientSolver.c", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "8e7ab9d3491e40d9e5e77f67956752cc1178b1b4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sanemarslan/RMTLib", "max_stars_repo_path": "applications/others/sscg/ConjugateGradientSolver.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1547, "size": 4502 }
// // Created by be107admin on 9/25/17. // #ifndef CIMPLE_GSL_LIBRARY_CIMPLE_EXTENSION_H #define CIMPLE_GSL_LIBRARY_CIMPLE_EXTENSION_H #include <gsl/gsl_blas.h> #include <gurobi_c.h> //////////////////////////////////////////////////////////////////////////////// // @fn gsl_matrix_from_array() // @brief Converts an array to a gsl matrix // @param gsl_matrix *matrix // @param double *array //////////////////////////////////////////////////////////////////////////////// void gsl_matrix_from_array(gsl_matrix *matrix,double *array, char* name); //////////////////////////////////////////////////////////////////////////////// // @fn gsl_vector_from_array() // @brief Converts an array to a gsl vector // @param gsl_matrix *matrix // @param double *array //////////////////////////////////////////////////////////////////////////////// void gsl_vector_from_array(gsl_vector *vector, double *array, char* name); //////////////////////////////////////////////////////////////////////////////// // @fn gsl_matrix_print() // @brief Prints a gsl matrix readable to the output // @param gsl_matrix *matrix // @param char *name //////////////////////////////////////////////////////////////////////////////// void gsl_matrix_print(gsl_matrix *matrix, char *name); //////////////////////////////////////////////////////////////////////////////// // @fn gsl_vector_print() // @brief Prints a gsl vector readable to the output // @param gsl_matrix *matrix // @param char *name //////////////////////////////////////////////////////////////////////////////// void gsl_vector_print(gsl_vector *vector, char *name); gsl_matrix * gsl_matrix_diag_from_vector(gsl_vector * X, double rest); int gsl_matrix_to_qpterm_gurobi(gsl_matrix *P, GRBmodel *model, size_t N); int gsl_vector_to_linterm_gurobi(gsl_vector *q, GRBmodel *model, size_t N); #endif //CIMPLE_GSL_LIBRARY_CIMPLE_EXTENSION_H
{ "alphanum_fraction": 0.5023898035, "avg_line_length": 37.66, "ext": "h", "hexsha": "4230c73bb355aa009677c920e506f9ed947771cf", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_path": "Interface/Cimple/cimple_gsl_library_extension.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_path": "Interface/Cimple/cimple_gsl_library_extension.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_path": "Interface/Cimple/cimple_gsl_library_extension.h", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "num_tokens": 351, "size": 1883 }
#ifndef OPERATOR_H #define OPERATOR_H #include <chrono> #include <iostream> #include <utility> #include <vector> #include <memory> #include <string> #include <sstream> #include <gsl/gsl_matrix.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_splinalg.h> #include "constants.h" using std::array; using std::pair; using std::shared_ptr; using std::tuple; using std::vector; using std::string; // Smart pointer to matrix using mat_operator = shared_ptr<gsl_spmatrix>; // Shorthand for template types using ComputeStatus = vector<pair<size_t, std::string>>; using ListCmu = const vector<mat_operator>; using VecPair = pair<gsl_vector *, gsl_vector *>; using VecTriplet = tuple<gsl_vector *, gsl_vector *, gsl_vector *>; // Generate operator L gsl_matrix *computeL(); // Generate operator C void computeC(); gsl_spmatrix *computeSingleC(size_t mu); void findValidCs(vector<bool>& toStore); void setFilenames(string& raw, string& compressed, size_t mu); gsl_spmatrix *loadMat(size_t mu); void storeMat(const gsl_spmatrix *C_mu, size_t mu); #endif // OPERATOR_H
{ "alphanum_fraction": 0.7509328358, "avg_line_length": 21.0196078431, "ext": "h", "hexsha": "12a326efd8869ecf044b681864ef3436d27f11db", "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/operators.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/operators.h", "max_line_length": 67, "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/operators.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": 279, "size": 1072 }
/** * * @file core_sgetrf_rectil.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @author Mathieu Faverge * @author Piotr Luszczek * @date 2009-11-15 * * @generated s Tue Jan 7 11:44:48 2014 * **/ #include <math.h> #include <cblas.h> #include <lapacke.h> #include "common.h" #define A(m, n) BLKADDR(A, float, m, n) void CORE_sgetrf_rectil_init(void); static inline void CORE_sgetrf_rectil_rec(const PLASMA_desc A, int *IPIV, int *info, float *pivot, int thidx, int thcnt, int column, int width, int ft, int lt); static inline void CORE_sgetrf_rectil_update(const PLASMA_desc A, int *IPIV, int column, int n1, int n2, int thidx, int thcnt, int ft, int lt); /***************************************************************************//** * * @ingroup CORE_float * * CORE_sgetrf_rectil computes a LU factorization of a general M-by-N * matrix A stored in CCRB layout using partial pivoting with row * interchanges. * * The factorization has the form * * A = P * L * U * * where P is a permutation matrix, L is lower triangular with unit * diagonal elements (lower trapezoidal if m > n), and U is upper * triangular (upper trapezoidal if m < n). * * This is the recursive version of the algorithm applied on tile layout. * * WARNINGS: * - The function CORE_sgetrf_rectil_init has to be called prior * to any call to this function. * - You cannot call this kernel on different matrices at the same * time. * - The matrix A cannot be more than one tile wide. * - The number of threads calling this function has to be excatly * the number defined by info[2] with each one of them a different * index between 0 included and info[2] excluded. * ******************************************************************************* * * @param[in,out] A * PLASMA descriptor of the matrix A to be factorized. * On entry, the M-by-N matrix to be factorized. * On exit, the factors L and U from the factorization * A = P*L*U; the unit diagonal elements of L are not stored. * * @param[out] IPIV * The pivot indices; for 0 <= i < min(M,N) stored in Fortran * mode (starting at 1), row i of the matrix was interchanged * with row IPIV(i). * On exit, each value IPIV[i] for 0 <= i < min(M,N) is * increased by A.i, which means A.i < IPIV[i] <= A.i+M. * * @param[in,out] info * Array of 3 integers. * - info[0], see returned value * - info[1], is the thread index 0 <= info[0] < info[2] * - info[2], on entry is the number of threads trying to * participate to the factorization, * on exit is the real number of threads used to * perform the factorization. * Info[2] threads, and exactly info[2], have to call this function * to avoid dead lock. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval -k, the k-th argument had an illegal value * \retval k if U(k,k) is exactly zero. The factorization * has been completed, but the factor U is exactly * singular, and division by zero will occur if it is used * to solve a system of equations. * */ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_sgetrf_rectil = PCORE_sgetrf_rectil #define CORE_sgetrf_rectil PCORE_sgetrf_rectil #endif int CORE_sgetrf_rectil(const PLASMA_desc A, int *IPIV, int *info) { int ft, lt; int thidx = info[1]; int thcnt = min( info[2], A.mt ); int minMN = min( A.m, A.n ); float pivot; info[0] = 0; info[2] = thcnt; if ( A.nt > 1 ) { coreblas_error(1, "Illegal value of A.nt"); info[0] = -1; return -1; } if ( thidx >= thcnt ) return 0; int q = A.mt / thcnt; int r = A.mt % thcnt; if (thidx < r) { q++; ft = thidx * q; lt = ft + q; } else { ft = r * (q + 1) + (thidx - r) * q; lt = ft + q; lt = min( lt, A.mt ); } CORE_sgetrf_rectil_rec( A, IPIV, info, &pivot, thidx, thcnt, 0, minMN, ft, lt); if ( A.n > minMN ) { CORE_sgetrf_rectil_update( A, IPIV, 0, minMN, A.n-minMN, thidx, thcnt, ft, lt); } return info[0]; } /******************************************************************* * Additional routines */ #define AMAX1BUF_SIZE (48 << 1) /* 48 threads should be enough for everybody */ static volatile float CORE_samax1buf[AMAX1BUF_SIZE]; static float sfmin; void CORE_sgetrf_rectil_init(void) { int i; for (i = 0; i < AMAX1BUF_SIZE; ++i) CORE_samax1buf[i] = -1.0; sfmin = LAPACKE_slamch_work('S'); } static void CORE_samax1_thread(float localamx, int thidx, int thcnt, int *thwinner, float *diagvalue, float *globalamx, int pividx, int *ipiv) { if (thidx == 0) { int i, j = 0; float curval = localamx, tmp; float curamx = fabsf(localamx); /* make sure everybody filled in their value */ for (i = 1; i < thcnt; ++i) { while (CORE_samax1buf[i << 1] == -1.0) { /* wait for thread i to store its value */ } } /* better not fuse the loop above and below to make sure data is sync'd */ for (i = 1; i < thcnt; ++i) { tmp = CORE_samax1buf[ (i << 1) + 1]; if (fabsf(tmp) > curamx) { curamx = fabsf(tmp); curval = tmp; j = i; } } if (0 == j) ipiv[0] = pividx; /* make sure everybody knows the amax value */ for (i = 1; i < thcnt; ++i) CORE_samax1buf[ (i << 1) + 1] = curval; CORE_samax1buf[0] = -j - 2.0; /* set the index of the winning thread */ CORE_samax1buf[1] = *diagvalue; /* set the index of the winning thread */ *thwinner = j; *globalamx = curval; for (i = 1; i < thcnt; ++i) CORE_samax1buf[i << 1] = -3.0; /* make sure everybody read the max value */ for (i = 1; i < thcnt; ++i) { while (CORE_samax1buf[i << 1] != -1.0) { } } CORE_samax1buf[0] = -1.0; } else { CORE_samax1buf[(thidx << 1) + 1] = localamx; CORE_samax1buf[thidx << 1] = -2.0; /* announce to thread 0 that local amax was stored */ while (CORE_samax1buf[0] == -1.0) { /* wait for thread 0 to finish calculating the global amax */ } while (CORE_samax1buf[thidx << 1] != -3.0) { /* wait for thread 0 to store amax */ } *thwinner = -CORE_samax1buf[0] - 2.0; *diagvalue = CORE_samax1buf[1]; *globalamx = CORE_samax1buf[(thidx << 1) + 1]; /* read the amax from the location adjacent to the one in the above loop */ CORE_samax1buf[thidx << 1] = -1.0; /* signal thread 0 that this thread is done reading */ if (thidx == *thwinner) ipiv[0] = pividx; while (CORE_samax1buf[0] != -1.0) { /* wait for thread 0 to finish */ } } } static void CORE_sbarrier_thread(int thidx, int thcnt) { int idum1, idum2; float ddum1 = 0.; float ddum2 = 0.; /* it's probably faster to implement a dedicated barrier */ CORE_samax1_thread( 1.0, thidx, thcnt, &idum1, &ddum1, &ddum2, 0, &idum2 ); } static inline void CORE_sgetrf_rectil_update(const PLASMA_desc A, int *IPIV, int column, int n1, int n2, int thidx, int thcnt, int ft, int lt) { int ld, lm, tmpM; int ip, j, it, i, ldft; float zone = 1.0; float mzone = -1.0; float *Atop, *Atop2, *U, *L; int offset = A.i; ldft = BLKLDD(A, 0); Atop = A(0, 0) + column * ldft; Atop2 = Atop + n1 * ldft; if (thidx == 0) { /* Swap to the right */ int *lipiv = IPIV+column; int idxMax = column+n1; for (j = column; j < idxMax; ++j, ++lipiv) { ip = (*lipiv) - offset - 1; if ( ip != j ) { it = ip / A.mb; i = ip % A.mb; ld = BLKLDD(A, it); cblas_sswap(n2, Atop2 + j, ldft, A(it, 0) + (column+n1)*ld + i, ld ); } } /* Trsm on the upper part */ U = Atop2 + column; cblas_strsm( CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, n1, n2, (zone), Atop + column, ldft, U, ldft ); /* Signal to other threads that they can start update */ CORE_sbarrier_thread( thidx, thcnt ); /* First tile */ L = Atop + column + n1; tmpM = min(ldft, A.m) - column - n1; /* Apply the GEMM */ cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, tmpM, n2, n1, (mzone), L, ldft, U, ldft, (zone), U + n1, ldft ); } else { ld = BLKLDD( A, ft ); L = A( ft, 0 ) + column * ld; lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb; U = Atop2 + column; /* Wait for pivoting and triangular solve to be finished * before to really start the update */ CORE_sbarrier_thread( thidx, thcnt ); /* First tile */ /* Apply the GEMM */ cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, lm, n2, n1, (mzone), L, ld, U, ldft, (zone), L + n1*ld, ld ); } /* Update the other blocks */ for( it = ft+1; it < lt; it++) { ld = BLKLDD( A, it ); L = A( it, 0 ) + column * ld; lm = it == A.mt-1 ? A.m - it * A.mb : A.mb; /* Apply the GEMM */ cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, lm, n2, n1, (mzone), L, ld, U, ldft, (zone), L + n1*ld, ld ); } } static void CORE_sgetrf_rectil_rec(const PLASMA_desc A, int *IPIV, int *info, float *pivot, int thidx, int thcnt, int column, int width, int ft, int lt) { int ld, jp, n1, n2, lm, tmpM, piv_sf; int ip, j, it, i, ldft; int max_i, max_it, thwin; float zone = 1.0; float mzone = -1.0; float tmp1; float tmp2 = 0.; float pivval; float *Atop, *Atop2, *U, *L; float abstmp1; int offset = A.i; ldft = BLKLDD(A, 0); Atop = A(0, 0) + column * ldft; if ( width > 1 ) { /* Assumption: N = min( M, N ); */ n1 = width / 2; n2 = width - n1; Atop2 = Atop + n1 * ldft; CORE_sgetrf_rectil_rec( A, IPIV, info, pivot, thidx, thcnt, column, n1, ft, lt ); if ( *info != 0 ) return; if (thidx == 0) { /* Swap to the right */ int *lipiv = IPIV+column; int idxMax = column+n1; for (j = column; j < idxMax; ++j, ++lipiv) { ip = (*lipiv) - offset - 1; if ( ip != j ) { it = ip / A.mb; i = ip % A.mb; ld = BLKLDD(A, it); cblas_sswap(n2, Atop2 + j, ldft, A(it, 0) + (column+n1)*ld + i, ld ); } } /* Trsm on the upper part */ U = Atop2 + column; cblas_strsm( CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, n1, n2, (zone), Atop + column, ldft, U, ldft ); /* SIgnal to other threads that they can start update */ CORE_sbarrier_thread( thidx, thcnt ); pivval = *pivot; if ( pivval == 0.0 ) { *info = column+n1; return; } else { if ( fabsf(pivval) >= sfmin ) { piv_sf = 1; pivval = 1.0 / pivval; } else { piv_sf = 0; } } /* First tile */ { L = Atop + column + n1; tmpM = min(ldft, A.m) - column - n1; /* Scale last column of L */ if ( piv_sf ) { cblas_sscal( tmpM, (pivval), L+(n1-1)*ldft, 1 ); } else { int i; Atop2 = L+(n1-1)*ldft; for( i=0; i < tmpM; i++, Atop2++) *Atop2 = *Atop2 / pivval; } /* Apply the GEMM */ cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, tmpM, n2, n1, (mzone), L, ldft, U, ldft, (zone), U + n1, ldft ); /* Search Max in first column of U+n1 */ tmp2 = U[n1]; max_it = ft; max_i = cblas_isamax( tmpM, U+n1, 1 ) + n1; tmp1 = U[max_i]; abstmp1 = fabsf(tmp1); max_i += column; } } else { pivval = *pivot; if ( pivval == 0.0 ) { *info = column+n1; return; } else { if ( fabsf(pivval) >= sfmin ) { piv_sf = 1; pivval = 1.0 / pivval; } else { piv_sf = 0; } } ld = BLKLDD( A, ft ); L = A( ft, 0 ) + column * ld; lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb; U = Atop2 + column; /* First tile */ /* Scale last column of L */ if ( piv_sf ) { cblas_sscal( lm, (pivval), L+(n1-1)*ld, 1 ); } else { int i; Atop2 = L+(n1-1)*ld; for( i=0; i < lm; i++, Atop2++) *Atop2 = *Atop2 / pivval; } /* Wait for pivoting and triangular solve to be finished * before to really start the update */ CORE_sbarrier_thread( thidx, thcnt ); /* Apply the GEMM */ cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, lm, n2, n1, (mzone), L, ld, U, ldft, (zone), L + n1*ld, ld ); /* Search Max in first column of L+n1*ld */ max_it = ft; max_i = cblas_isamax( lm, L+n1*ld, 1 ); tmp1 = L[n1*ld+max_i]; abstmp1 = fabsf(tmp1); } /* Update the other blocks */ for( it = ft+1; it < lt; it++) { ld = BLKLDD( A, it ); L = A( it, 0 ) + column * ld; lm = it == A.mt-1 ? A.m - it * A.mb : A.mb; /* Scale last column of L */ if ( piv_sf ) { cblas_sscal( lm, (pivval), L+(n1-1)*ld, 1 ); } else { int i; Atop2 = L+(n1-1)*ld; for( i=0; i < lm; i++, Atop2++) *Atop2 = *Atop2 / pivval; } /* Apply the GEMM */ cblas_sgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, lm, n2, n1, (mzone), L, ld, U, ldft, (zone), L + n1*ld, ld ); /* Search the max on the first column of L+n1*ld */ jp = cblas_isamax( lm, L+n1*ld, 1 ); if ( fabsf( L[n1*ld+jp] ) > abstmp1 ) { tmp1 = L[n1*ld+jp]; abstmp1 = fabsf(tmp1); max_i = jp; max_it = it; } } jp = offset + max_it*A.mb + max_i; CORE_samax1_thread( tmp1, thidx, thcnt, &thwin, &tmp2, pivot, jp + 1, IPIV + column + n1 ); if ( thidx == 0 ) { U[n1] = *pivot; /* all threads have the pivot element: no need for synchronization */ } if (thwin == thidx) { /* the thread that owns the best pivot */ if ( jp-offset != column+n1 ) /* if there is a need to exchange the pivot */ { ld = BLKLDD(A, max_it); Atop2 = A( max_it, 0 ) + (column + n1 )* ld + max_i; *Atop2 = tmp2; } } CORE_sgetrf_rectil_rec( A, IPIV, info, pivot, thidx, thcnt, column+n1, n2, ft, lt ); if ( *info != 0 ) return; if ( thidx == 0 ) { /* Swap to the left */ int *lipiv = IPIV+column+n1; int idxMax = column+width; for (j = column+n1; j < idxMax; ++j, ++lipiv) { ip = (*lipiv) - offset - 1; if ( ip != j ) { it = ip / A.mb; i = ip % A.mb; ld = BLKLDD(A, it); cblas_sswap(n1, Atop + j, ldft, A(it, 0) + column*ld + i, ld ); } } } } else if ( width == 1 ) { /* Search maximum for column 0 */ if ( column == 0 ) { if ( thidx == 0 ) tmp2 = Atop[column]; /* First tmp1 */ ld = BLKLDD(A, ft); Atop2 = A( ft, 0 ); lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb; max_it = ft; max_i = cblas_isamax( lm, Atop2, 1 ); tmp1 = Atop2[max_i]; abstmp1 = fabsf(tmp1); /* Update */ for( it = ft+1; it < lt; it++) { Atop2= A( it, 0 ); lm = it == A.mt-1 ? A.m - it * A.mb : A.mb; jp = cblas_isamax( lm, Atop2, 1 ); if ( fabsf(Atop2[jp]) > abstmp1 ) { tmp1 = Atop2[jp]; abstmp1 = fabsf(tmp1); max_i = jp; max_it = it; } } jp = offset + max_it*A.mb + max_i; CORE_samax1_thread( tmp1, thidx, thcnt, &thwin, &tmp2, pivot, jp + 1, IPIV + column ); if ( thidx == 0 ) { Atop[0] = *pivot; /* all threads have the pivot element: no need for synchronization */ } if (thwin == thidx) { /* the thread that owns the best pivot */ if ( jp-offset != 0 ) /* if there is a need to exchange the pivot */ { Atop2 = A( max_it, 0 ) + max_i; *Atop2 = tmp2; } } } CORE_sbarrier_thread( thidx, thcnt ); /* If it is the last column, we just scale */ if ( column == (min(A.m, A.n))-1 ) { pivval = *pivot; if ( pivval != 0.0 ) { if ( thidx == 0 ) { if ( fabsf(pivval) >= sfmin ) { pivval = 1.0 / pivval; /* * We guess than we never enter the function with m == A.mt-1 * because it means that there is only one thread */ lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb; cblas_sscal( lm - column - 1, (pivval), Atop+column+1, 1 ); for( it = ft+1; it < lt; it++) { ld = BLKLDD(A, it); Atop2 = A( it, 0 ) + column * ld; lm = it == A.mt-1 ? A.m - it * A.mb : A.mb; cblas_sscal( lm, (pivval), Atop2, 1 ); } } else { /* * We guess than we never enter the function with m == A.mt-1 * because it means that there is only one thread */ int i; Atop2 = Atop + column + 1; lm = ft == A.mt-1 ? A.m - ft * A.mb : A.mb; for( i=0; i < lm-column-1; i++, Atop2++) *Atop2 = *Atop2 / pivval; for( it = ft+1; it < lt; it++) { ld = BLKLDD(A, it); Atop2 = A( it, 0 ) + column * ld; lm = it == A.mt-1 ? A.m - it * A.mb : A.mb; for( i=0; i < lm; i++, Atop2++) *Atop2 = *Atop2 / pivval; } } } else { if ( fabsf(pivval) >= sfmin ) { pivval = 1.0 / pivval; for( it = ft; it < lt; it++) { ld = BLKLDD(A, it); Atop2 = A( it, 0 ) + column * ld; lm = it == A.mt-1 ? A.m - it * A.mb : A.mb; cblas_sscal( lm, (pivval), Atop2, 1 ); } } else { /* * We guess than we never enter the function with m == A.mt-1 * because it means that there is only one thread */ int i; for( it = ft; it < lt; it++) { ld = BLKLDD(A, it); Atop2 = A( it, 0 ) + column * ld; lm = it == A.mt-1 ? A.m - it * A.mb : A.mb; for( i=0; i < lm; i++, Atop2++) *Atop2 = *Atop2 / pivval; } } } } else { *info = column + 1; return; } } } }
{ "alphanum_fraction": 0.4068927418, "avg_line_length": 33.1436619718, "ext": "c", "hexsha": "fdc5eaac0c368e36ccd7d7f3cadfd1e42b316047", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_sgetrf_rectil.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_sgetrf_rectil.c", "max_line_length": 130, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_sgetrf_rectil.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6401, "size": 23532 }
#include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_odeiv2.h> #include <fastpm/libfastpm.h> #include <fastpm/logging.h> #define STEF_BOLT 2.85087e-48 // in units: [ h * (10^10Msun/h) * s^-3 * K^-4 ] #define rho_crit 27.7455 // rho_crit0 in mass/length #define LIGHT 9.715614e-15 // in units: [ h * (Mpc/h) * s^-1 ] #define kB 8.617333262145e-5 // boltzman in eV/K double HubbleDistance = 2997.92458; /* Mpc/h */ double HubbleConstant = 100.0; /* km/s / Mpc/h */ void fastpm_cosmology_init(FastPMCosmology * c) { /* prepare the interpolation object for FD tables. */ if (c->N_ncdm > 0) { FastPMFDInterp * FDinterp = malloc(sizeof(FDinterp[0])); fastpm_fd_interp_init(FDinterp); c->FDinterp = FDinterp; } // Compute Omega_ncdm(z=0) double Omega_ncdm_0; if (c->ncdm_matterlike) { Omega_ncdm_0 = 0; for (int i=0; i<c->N_ncdm; i++) { Omega_ncdm_0 += c->m_ncdm[i]; } Omega_ncdm_0 *= 1. / 93.14 / c->h / c->h; } else { Omega_ncdm_0 = Omega_ncdmTimesHubbleEaSq(1, c); } c->Omega_ncdm = Omega_ncdm_0; // Compute Omega_cdm assuming all ncdm is matter-like at z=0 c->Omega_cdm = c->Omega_m - Omega_ncdm_0; // Set Omega_Lambda at z=0 by closing Friedmann's equation c->Omega_Lambda = 1 - c->Omega_m - Omega_r(c) - c->Omega_k; } void fastpm_cosmology_destroy(FastPMCosmology * c) { if (c->FDinterp) { fastpm_fd_interp_destroy(c->FDinterp); free(c->FDinterp); } } double Omega_g(FastPMCosmology * c) { /* FIXME: This is really Omega_g0. Might want to redefine all Omegas in the code */ return 4 * STEF_BOLT * pow(c->T_cmb, 4) / pow(LIGHT, 3) / rho_crit / pow(c->h, 2); } double Gamma_nu(FastPMCosmology * c) { /* nu to photon temp ratio today */ if (c->N_nu == 0) { return 0; } else { return pow(4./11., 1./3.) * pow(c->N_eff / c->N_nu, 1./4.); } } double Omega_ur(FastPMCosmology * c) { /* Omega_ur0. This is the energy density of all massless nus */ int N_ur = c->N_nu - c->N_ncdm; // number of massless nus (different to CLASS defn) return 7./8. * N_ur * pow(Gamma_nu(c), 4) * Omega_g(c); } double Omega_r(FastPMCosmology * c) { /* Omega_r0. This is the energy density of all radiation-like particles. FIXME: really this is Omega_g+ur, not r, because it doesn't have ncdm,r in it and we define m with ncdm,m. this doesn't affect rest of code, but maybe redefine.*/ return Omega_g(c) + Omega_ur(c); } static double getFtable(int F_id, double y, FastPMCosmology * c) { /* Not using size as an arg, it's globally defined Gets the interpolated value of Ftable[F_id] at y F_id: 1 for F, 2 for F', 3 for F'' */ return fastpm_do_fd_interp(c->FDinterp, F_id, y); } static double Fconst(int ncdm_id, FastPMCosmology * c) { /* This is a cosmology dependent constant which is the argument divided by a of F, DF, DDF */ double T_nu = Gamma_nu(c) * c->T_cmb; return c->m_ncdm[ncdm_id] / (kB * T_nu); } double Omega_ncdm_iTimesHubbleEaSq(double a, int ncdm_id, FastPMCosmology * c) { /* Omega_ncdm_i(a) * E(a)^2 */ double A = 15. / pow(M_PI, 4) * pow(Gamma_nu(c), 4) * Omega_g(c); double Fc = Fconst(ncdm_id, c); double F = getFtable(1, Fc*a, c); //row 1 for F return A / (a*a*a*a) * F; } double Omega_ncdmTimesHubbleEaSq(double a, FastPMCosmology * c) { // sum over ncdm species double res = 0; for (int i=0; i<c->N_ncdm; i++) { res += Omega_ncdm_iTimesHubbleEaSq(a, i, c); } return res; } double DOmega_ncdmTimesHubbleEaSqDa(double a, FastPMCosmology * c) { double A = 15. / pow(M_PI, 4) * pow(Gamma_nu(c), 4) * Omega_g(c); double OncdmESq = Omega_ncdmTimesHubbleEaSq(a,c); double FcDF = 0; for (int i=0; i<c->N_ncdm; i++) { double Fc = Fconst(i, c); double DF = getFtable(2, Fc*a, c); FcDF += Fc * DF; //row 2 for F' } return -4. / a * OncdmESq + A / (a*a*a*a) * FcDF; } double D2Omega_ncdmTimesHubbleEaSqDa2(double a, FastPMCosmology * c) { double A = 15. / pow(M_PI, 4) * pow(Gamma_nu(c), 4) * Omega_g(c); double OncdmESq = Omega_ncdmTimesHubbleEaSq(a,c); double DOncdmESqDa = DOmega_ncdmTimesHubbleEaSqDa(a,c); double FcFcDDF = 0; for (int i=0; i<c->N_ncdm; i++) { double Fc = Fconst(i, c); double DDF = getFtable(3, Fc*a, c); FcFcDDF += Fc * Fc * DDF; //row 3 for F'' } return -12. / (a*a) * OncdmESq - 8. / a * DOncdmESqDa + A / (a*a*a*a) * FcFcDDF; } double Omega_DE_TimesHubbleEaSq(double a, FastPMCosmology * c) { /* Dark energy parameter as a function of a, times E^2(a). Using Chevalier-Linder-Polarski: w(z) = w0 + z/(1+z) wa. Omega_DE(z) E^2(z) = Omega_DE(0) * exp( 3 \int_0^z dx (1+w(x)) / (1+x) ) = Omega_Lambda * exp[ 3 ( -wa*z/(1+z) + (1+w0+wa)*ln(1+z) )]. */ double exponent = (a - 1) * c->wa - (1 + c->w0 + c->wa) * log(a); return c->Omega_Lambda * exp(3 * exponent); } double DOmega_DE_TimesHubbleEaSqDa(double a, FastPMCosmology * c) { return 3 * (c->wa - (1 + c->w0 + c->wa) / a) * Omega_DE_TimesHubbleEaSq(a, c); } double D2Omega_DE_TimesHubbleEaSqDa2(double a, FastPMCosmology * c) { double OdeESq = Omega_DE_TimesHubbleEaSq(a, c); double DOdeEsqDa = DOmega_DE_TimesHubbleEaSqDa(a, c); return DOdeEsqDa*DOdeEsqDa / c->Omega_Lambda + 3 * (1 + c->w0 + c->wa) / (a*a) * OdeESq; } double HubbleEa(double a, FastPMCosmology * c) { /* H(a) / H0 */ double Omega_ncdm_ESq; // contribution from ncdm if (c->ncdm_matterlike) { Omega_ncdm_ESq = c->Omega_ncdm / (a*a*a); } else { Omega_ncdm_ESq = Omega_ncdmTimesHubbleEaSq(a, c); } return sqrt(Omega_r(c) / (a*a*a*a) + c->Omega_cdm / (a*a*a) + c->Omega_k / (a*a) + Omega_DE_TimesHubbleEaSq(a, c) + Omega_ncdm_ESq); } double Omega_cdm_a(double a, FastPMCosmology * c) { /* as a func of a FIXME: remove the _a and put in 0s for today's value elsewhere */ double E = HubbleEa(a, c); return c->Omega_cdm / (a*a*a) / (E*E); } double Omega_m(double a, FastPMCosmology * c){ /* Total matter component (cdm + ncdm) assuming all ncdm is matter-like (for use in source term) */ double E = HubbleEa(a, c); return c->Omega_m / (a*a*a) / (E*E); } double Omega_source(double a, FastPMCosmology * c){ /* For use in source term of growth ODE and Poisson eqn */ if (c->ncdm_freestreaming){ return Omega_cdm_a(a, c); } else { return Omega_m(a, c); } } double DHubbleEaDa(double a, FastPMCosmology * c) { /* d E / d a*/ double E = HubbleEa(a, c); double DOdeESqDa = DOmega_DE_TimesHubbleEaSqDa(a, c); double DOncdmESqDa; // contribution from ncdm if (c->ncdm_matterlike) { DOncdmESqDa = - 3 * c->Omega_ncdm / pow(a,4); } else { DOncdmESqDa = DOmega_ncdmTimesHubbleEaSqDa(a, c); } return 0.5 / E * (- 4 * Omega_r(c) / pow(a,5) - 3 * c->Omega_cdm / pow(a,4) - 2 * c->Omega_k / pow(a,3) + DOdeESqDa + DOncdmESqDa); } double D2HubbleEaDa2(double a, FastPMCosmology * c) { double E = HubbleEa(a, c); double dEda = DHubbleEaDa(a, c); double D2OdeESqDa2 = D2Omega_DE_TimesHubbleEaSqDa2(a, c); double D2OncdmESqDa2; // contribution from ncdm if (c->ncdm_matterlike) { D2OncdmESqDa2 = 12 * c->Omega_ncdm / pow(a,5); } else { D2OncdmESqDa2 = D2Omega_ncdmTimesHubbleEaSqDa2(a, c); } return 0.5 / E * ( 20 * Omega_r(c) / pow(a,6) + 12 * c->Omega_cdm / pow(a,5) + 6 * c->Omega_k / pow(a,4) + D2OdeESqDa2 + D2OncdmESqDa2 - 2 * pow(dEda,2) ); } static double growth_int(double a, void *param) { double * p = (double*) param; double Omega_m = p[0]; double Omega_Lambda = p[1]; return pow(a / (Omega_m + (1 - Omega_m - Omega_Lambda) * a + Omega_Lambda * a * a * a), 1.5); } static double solve_growth_int(double a, FastPMCosmology * c) { /* NOTE that the analytic COLA growthDtemp() is 6 * pow(1 - c.OmegaM, 1.5) times growth() */ int WORKSIZE = 100000; double result, abserr; gsl_integration_workspace *workspace; gsl_function F; workspace = gsl_integration_workspace_alloc(WORKSIZE); F.function = &growth_int; F.params = (double[]) {c->Omega_m, c->Omega_Lambda}; gsl_integration_qag(&F, 0, a, 0, 1.0e-9, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); gsl_integration_workspace_free(workspace); return HubbleEa(a, c) * result; } static int growth_ode(double a, const double y[], double dyda[], void *params) { FastPMCosmology* c = (FastPMCosmology * ) params; const double E = HubbleEa(a, c); const double dEda = DHubbleEaDa(a, c); double dydlna[4]; dydlna[0] = y[1]; dydlna[1] = - (2. + a / E * dEda) * y[1] + 1.5 * Omega_source(a, c) * y[0]; dydlna[2] = y[3]; dydlna[3] = - (2. + a / E * dEda) * y[3] + 1.5 * Omega_source(a, c) * (y[2] - y[0]*y[0]); //divide by a to get dyda for (int i=0; i<4; i++){ dyda[i] = dydlna[i] / a; } return GSL_SUCCESS; } static ode_soln growth_ode_solve(double a, FastPMCosmology * c) { /* This returns an array of {d1, F1, d2, F2} (unnormalised) */ gsl_odeiv2_system F; F.function = &growth_ode; F.jacobian = NULL; F.dimension = 4; F.params = (void*) c; gsl_odeiv2_driver * drive = gsl_odeiv2_driver_alloc_standard_new(&F, gsl_odeiv2_step_rkf45, 1e-6, 1e-8, 1e-8, 1, 1); // assume matter domination double aini = 0.00625; // FIXME: need to make sure this is less than the starting a. For now using z=159. double yini[4]; yini[0] = aini; yini[1] = aini; yini[2] = - 3./7. * aini*aini; yini[3] = 2 * yini[2]; int status = gsl_odeiv2_driver_apply(drive, &aini, a, yini); if (status != GSL_SUCCESS) { fastpm_raise(-1, "Growth ODE unsuccesful at a=%g.", a); } gsl_odeiv2_driver_free(drive); ode_soln soln; soln.y0 = yini[0]; soln.y1 = yini[1]; soln.y2 = yini[2]; soln.y3 = yini[3]; return soln; } void fastpm_growth_info_init(FastPMGrowthInfo * growth_info, double a, FastPMCosmology * c) { growth_info->a = a; growth_info->c = c; switch (c->growth_mode) { case FASTPM_GROWTH_MODE_LCDM: { double d1 = solve_growth_int(a, c); double d1_a1 = solve_growth_int(1, c); double Om = Omega_m(a, c); growth_info->D1 = d1 / d1_a1; growth_info->f1 = pow(Om, 5./9.); growth_info->D2 = growth_info->D1 * growth_info->D1 * pow(Om/Omega_m(1, c), -1./143.); growth_info->f2 = 2 * pow(Om, 6./11.); break; } case FASTPM_GROWTH_MODE_ODE: { ode_soln soln = growth_ode_solve(a, c); ode_soln soln_a1 = growth_ode_solve(1, c); growth_info->D1 = soln.y0 / soln_a1.y0; growth_info->f1 = soln.y1 / soln.y0; /* f = d log D / d log a. Note soln.y1 is d d1 / d log a */ growth_info->D2 = soln.y2 / soln_a1.y2; growth_info->f2 = soln.y3 / soln.y2; break; } default: fastpm_raise(-1, "Please enter a valid growth mode.\n"); } } double DGrowthFactorDa(FastPMGrowthInfo * growth_info) { /* dD/da */ /* FIXME: Technically the ODE version should agree with LCDM version for Lambda+CDM background, but to ensure backwards compatibility both versions are here. */ double a = growth_info->a; FastPMCosmology * c = growth_info->c; double ans = 0; switch (c->growth_mode) { case FASTPM_GROWTH_MODE_LCDM: { double E = HubbleEa(a, c); double EI = solve_growth_int(1.0, c); double t1 = DHubbleEaDa(a, c) * growth_info->D1 / E; double t2 = E * pow(a * E, -3) / EI; ans = t1 + t2; break; } case FASTPM_GROWTH_MODE_ODE: ans = growth_info->f1 * growth_info->D1 / growth_info->a; break; default: fastpm_raise(-1, "Please enter a valid growth mode.\n"); } return ans; } double D2GrowthFactorDa2(FastPMGrowthInfo * growth_info) { /* d^2 D1 / da^2 */ /* FIXME: Technically the ODE version should agree with LCDM version for Lambda+CDM background, but to ensure backwards compatibility both versions are here. */ double a = growth_info->a; FastPMCosmology * c = growth_info->c; double ans = 0; switch (c->growth_mode) { case FASTPM_GROWTH_MODE_LCDM: { double d2Eda2 = D2HubbleEaDa2(a, c); double dEda = DHubbleEaDa(a, c); double E = HubbleEa(a, c); double EI = solve_growth_int(1., c); double t1 = d2Eda2 * growth_info->D1 / E; double t2 = (dEda + 3 / a * E) * pow(a * E, -3) / EI; ans = t1 - t2; break; } case FASTPM_GROWTH_MODE_ODE: { double E = HubbleEa(a, c); double dEda = DHubbleEaDa(a, c); double D1 = growth_info->D1; double f1 = growth_info->f1; ans -= (3. + a / E * dEda) * f1; ans += 1.5 * Omega_source(a, c); ans *= D1 / (a*a); break; } default: fastpm_raise(-1, "Please enter a valid growth mode.\n"); } return ans; } static double comoving_distance_int(double a, void * params) { FastPMCosmology * c = (FastPMCosmology * ) params; return 1. / (a * a * HubbleEa(a, c)); } double ComovingDistance(double a, FastPMCosmology * c) { /* We tested using ln_a doesn't seem to improve accuracy */ int WORKSIZE = 100000; double result, abserr; gsl_integration_workspace *workspace; gsl_function F; workspace = gsl_integration_workspace_alloc(WORKSIZE); F.function = &comoving_distance_int; F.params = (void*) c; gsl_integration_qag(&F, a, 1., 0, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); //lowered tol by /10 to avoid error from round off (maybe I need to make my paras more accurate) gsl_integration_workspace_free(workspace); return result; } #ifdef TEST_COSMOLOGY int main() { /* the old COLA growthDtemp is 6 * pow(1 - c.OmegaM, 1.5) times growth */ double a; FastPMCosmology c[1] = {{ .OmegaM = 0.3, .OmegaLambda = 0.7 }}; printf("OmegaM D dD/da d2D/da2 D2 E dE/dA d2E/da2 \n"); for(c->OmegaM = 0.1; c->OmegaM < 0.6; c->OmegaM += 0.1) { double f = 6 * pow(1 - c->OmegaM, 1.5); c->OmegaLambda = 1 - c->OmegaM; c->w0 = -1; c->wa = 0; double a = 0.8; printf("%g %g %g %g %g %g %g %g %g\n", c->OmegaM, ComovingDistance(a, c), GrowthFactor(a, c), DGrowthFactorDa(a, c), D2GrowthFactorDa2(a, c), GrowthFactor2(a, c), HubbleEa(a, c), DHubbleEaDa(a, c), D2HubbleEaDa2(a, c) ); } } #endif
{ "alphanum_fraction": 0.5691292047, "avg_line_length": 30.8236434109, "ext": "c", "hexsha": "68c6542c4dea0ce25479401ffd68f978a3b32d15", "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/cosmology.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/cosmology.c", "max_line_length": 111, "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/cosmology.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5344, "size": 15905 }
#ifndef _ROTATION_H__ #define _ROTATION_H__ #include <mpi.h> #include <omp.h> #include <blas.h> #include <vector> #include <stdlib.h> #include <math.h> /* ************************************************** */ // interface for FORTRAN CODE #define FORTRAN(MYFUN) (MYFUN##_) extern "C" { void FORTRAN(idd_random_transf_init)(int *nsteps, int *n, double *w, int *keep); void FORTRAN(idd_random_transf)(double *x, double *y, double *w); void FORTRAN(idd_random_transf_inverse)(double *x, double *y, double *w); } #define RROT_INIT FORTRAN(idd_random_transf_init) #define RROT FORTRAN(idd_random_transf) #define RROT_INV FORTRAN(idd_random_transf_inverse) /* ************************************************** */ using namespace std; void generateRotation(int dim, vector<double> &w ); void generateRotation(int dim, vector<double> &w, MPI_Comm comm); void rotatePoints(const double *points, int numof_points, int dim, vector<double> &w, // output double *newPoints); void inverseRotatePoints(const double *points, int numof_points, int dim, vector<double> &w, // output double *newPoints); void newRotatePoints(double *points, int numof_points, int dim, vector<double> &w); void newInverseRotatePoints(double *points, int numof_points, int dim, vector<double> &w); /* void generateRotation(int dim, double *R); void generateRotation(int dim, double *R, MPI_Comm comm); void rotatePoints(double *points, int numof_points, int dim, double *MatRotation, // output double *newPoints); void inverseRotatePoints(double *points, int numof_points, int dim, double *MatRotation, // output double *newPoints); */ #endif
{ "alphanum_fraction": 0.6717467761, "avg_line_length": 25.0882352941, "ext": "h", "hexsha": "8eecaac5423e08633995722ea2c3773818a94bd7", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-10-08T20:02:46.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-11T22:29:45.000Z", "max_forks_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maumueller/rehashing", "max_forks_repo_path": "benchmark/askit_release/rkdtsrc/include/binTree/rotation.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_issues_repo_issues_event_max_datetime": "2020-10-09T04:27:39.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-06T09:47:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "maumueller/rehashing", "max_issues_repo_path": "benchmark/askit_release/rkdtsrc/include/binTree/rotation.h", "max_line_length": 90, "max_stars_count": 20, "max_stars_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maumueller/rehashing", "max_stars_repo_path": "benchmark/askit_release/rkdtsrc/include/binTree/rotation.h", "max_stars_repo_stars_event_max_datetime": "2021-09-22T20:48:29.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-14T20:08:08.000Z", "num_tokens": 421, "size": 1706 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" #ifdef MHM extern struct kindata_in { MyFloat Pos[3]; MyFloat Hsml; MyFloat Density; MyFloat Energy; int Index; int Task; } *KinDataIn, *KinDataGet; void kinetic_feedback_mhm(void) { long long ntot, ntotleft; int ndone; int *noffset, *nbuffer, *nsend, *nsend_local, *numlist, *ndonelist; int i, j, n; int maxfill; int level, ngrp, sendTask, recvTask; int nexport; MPI_Status status; noffset = mymalloc(sizeof(int) * NTask); /* offsets of bunches in common list */ nbuffer = mymalloc(sizeof(int) * NTask); nsend_local = mymalloc(sizeof(int) * NTask); nsend = mymalloc(sizeof(int) * NTask * NTask); ndonelist = mymalloc(sizeof(int) * NTask); for(n = 0, NumSphUpdate = 0; n < N_gas; n++) { if(P[n].Type == 0) { if(P[n].Ti_endstep == All.Ti_Current) NumSphUpdate++; } } numlist = mymalloc(NTask * sizeof(int) * NTask); MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD); for(i = 0, ntot = 0; i < NTask; i++) ntot += numlist[i]; myfree(numlist); i = 0; /* beginn with this index */ ntotleft = ntot; /* particles left for all tasks together */ while(ntotleft > 0) { for(j = 0; j < NTask; j++) nsend_local[j] = 0; /* do local particles and prepare export list */ for(nexport = 0, ndone = 0; i < N_gas && nexport < All.BunchSizeKinetic - NTask; i++) if(P[i].Type == 0) if(P[i].Ti_endstep == All.Ti_Current) { ndone++; for(j = 0; j < NTask; j++) Exportflag[j] = 0; kinetic_evaluate(i, 0); for(j = 0; j < NTask; j++) { if(Exportflag[j]) { KinDataIn[nexport].Pos[0] = P[i].Pos[0]; KinDataIn[nexport].Pos[1] = P[i].Pos[1]; KinDataIn[nexport].Pos[2] = P[i].Pos[2]; KinDataIn[nexport].Density = SphP[i].Density; KinDataIn[nexport].Energy = SphP[i].FeedbackEnergy; KinDataIn[nexport].Hsml = PPP[i].Hsml; KinDataIn[nexport].Index = i; KinDataIn[nexport].Task = j; nexport++; nsend_local[j]++; } } } qsort(KinDataIn, nexport, sizeof(struct kindata_in), kin_compare_key); for(j = 1, noffset[0] = 0; j < NTask; j++) noffset[j] = noffset[j - 1] + nsend_local[j - 1]; MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD); /* now do the particles that need to be exported */ for(level = 1; level < (1 << PTask); level++) { for(j = 0; j < NTask; j++) nbuffer[j] = 0; for(ngrp = level; ngrp < (1 << PTask); ngrp++) { maxfill = 0; for(j = 0; j < NTask; j++) { if((j ^ ngrp) < NTask) if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j]) maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j]; } if(maxfill >= All.BunchSizeDensity) break; sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0) { /* get the particles */ MPI_Sendrecv(&KinDataIn[noffset[recvTask]], nsend_local[recvTask] * sizeof(struct kindata_in), MPI_BYTE, recvTask, TAG_DENS_A, &KinDataGet[nbuffer[ThisTask]], nsend[recvTask * NTask + ThisTask] * sizeof(struct kindata_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, &status); } } for(j = 0; j < NTask; j++) if((j ^ ngrp) < NTask) nbuffer[j] += nsend[(j ^ ngrp) * NTask + j]; } for(j = 0; j < nbuffer[ThisTask]; j++) kinetic_evaluate(j, 1); level = ngrp - 1; } MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD); for(j = 0; j < NTask; j++) ntotleft -= ndonelist[j]; } myfree(ndonelist); myfree(nsend); myfree(nsend_local); myfree(nbuffer); myfree(noffset); } /*! This function represents the core of the SPH density computation. The * target particle may either be local, or reside in the communication * buffer. */ void kinetic_evaluate(int target, int mode) { int j, n; int startnode, numngb, numngb_inbox; double h, h2, hinv, hinv3; double rho, weight, wk, energy, delta_v; double dx, dy, dz, r, r2, u; double dvx, dvy, dvz; MyFloat *pos; if(mode == 0) { pos = P[target].Pos; h = PPP[target].Hsml; rho = SphP[target].Density; energy = SphP[target].FeedbackEnergy; } else { pos = KinDataGet[target].Pos; h = KinDataGet[target].Hsml; rho = KinDataGet[target].Density; energy = KinDataGet[target].Energy; } h2 = h * h; hinv = 1.0 / h; #ifndef TWODIMS hinv3 = hinv * hinv * hinv; #else hinv3 = hinv * hinv / boxSize_Z; #endif startnode = All.MaxPart; numngb = 0; do { numngb_inbox = ngb_treefind_variable(&pos[0], h, &startnode); for(n = 0; n < numngb_inbox; n++) { j = Ngblist[n]; dx = pos[0] - P[j].Pos[0]; dy = pos[1] - P[j].Pos[1]; dz = pos[2] - P[j].Pos[2]; #ifdef PERIODIC /* now find the closest image in the given box size */ if(dx > boxHalf_X) dx -= boxSize_X; if(dx < -boxHalf_X) dx += boxSize_X; if(dy > boxHalf_Y) dy -= boxSize_Y; if(dy < -boxHalf_Y) dy += boxSize_Y; if(dz > boxHalf_Z) dz -= boxSize_Z; if(dz < -boxHalf_Z) dz += boxSize_Z; #endif r2 = dx * dx + dy * dy + dz * dz; if(r2 < h2) { r = sqrt(r2); if(r > 0) { u = r * hinv; if(u < 0.5) wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u); else wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u); weight = wk * P[j].Mass / rho; delta_v = sqrt(2 * energy * weight / P[j].Mass); dvx = delta_v * (-dx) / r; dvy = delta_v * (-dy) / r; dvz = delta_v * (-dz) / r; P[j].Vel[0] += dvx; P[j].Vel[1] += dvy; P[j].Vel[2] += dvz; SphP[j].VelPred[0] += dvx; SphP[j].VelPred[1] += dvy; SphP[j].VelPred[2] += dvz; } } } } while(startnode >= 0); } /*! This routine is a comparison kernel used in a sort routine to group * particles that are exported to the same processor. */ int kin_compare_key(const void *a, const void *b) { if(((struct kindata_in *) a)->Task < (((struct kindata_in *) b)->Task)) return -1; if(((struct kindata_in *) a)->Task > (((struct kindata_in *) b)->Task)) return +1; return 0; } #endif
{ "alphanum_fraction": 0.5703042228, "avg_line_length": 21.950166113, "ext": "c", "hexsha": "7b312c6ec3e920c14940e15f21d0e7fbfa9d29e1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/kinfb_mhm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/kinfb_mhm.c", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/kinfb_mhm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2271, "size": 6607 }
/* specfunc/test_bessel.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_test.h> #include <gsl/gsl_sf.h> #include "test_sf.h" static double J[100]; static double Y[100]; static double I[100]; static double K[100]; int test_bessel(void) { gsl_sf_result r; int i; int s = 0; int sa; TEST_SF(s, gsl_sf_bessel_J0_e, (0.1, &r), 0.99750156206604003230, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J0_e, (2.0, &r), 0.22389077914123566805, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J0_e, (100.0, &r), 0.019985850304223122424, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J0_e, (1.0e+10, &r), 2.1755917502468917269e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (0.1, &r), 0.04993752603624199756, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (2.0, &r), 0.57672480775687338720, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (100.0, &r), -0.07714535201411215803, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_J1_e, (1.0e+10, &r), -7.676508175684157103e-06, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (4, 0.1, &r), 2.6028648545684032338e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (5, 2.0, &r), 0.007039629755871685484, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (10, 20.0, &r), 0.18648255802394508321, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (100, 100.0, &r), 0.09636667329586155967, TEST_TOL0, GSL_SUCCESS); /* exercise the BUG#3 problem */ TEST_SF(s, gsl_sf_bessel_Jn_e, (2, 900.0, &r), -0.019974345269680646400, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (2, 15000.0, &r), -0.0020455820181216382666, TEST_TOL4, GSL_SUCCESS); #ifdef TEST_LARGE TEST_SF(s, gsl_sf_bessel_Jn_e, (0, 1.0e+10, &r), 2.1755917502468917269e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (1, 1.0e+10, &r), -7.676508175684157103e-06, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jn_e, (0, 20000, &r), 0.00556597490495494615709982972, TEST_TOL4, GSL_SUCCESS); #endif /* Testcase demonstrating long calculation time: Time spent in gsl_sf_bessel_J_CF1 for large x<1000 and n<5 grows in proportion to x Jonny Taylor <j.m.taylor@durham.ac.uk> */ TEST_SF(s, gsl_sf_bessel_Jn_e, (45, 900.0, &r), 0.02562434700634278108, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (0.1, &r), -1.5342386513503668441, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (2, &r), 0.5103756726497451196, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (256.0, &r), -0.03381290171792454909 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y0_e, (4294967296.0, &r), 3.657903190017678681e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (0.1, &r), -6.45895109470202698800, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (2, &r), -0.10703243154093754689, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (100.0, &r), -0.020372312002759793305, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Y1_e, (4294967296.0, &r), 0.000011612249378370766284, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (4, 0.1, &r), -305832.29793353160319, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (5, 2, &r), -9.935989128481974981, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (100, 100.0, &r), -0.16692141141757650654, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (100, 4294967296.0, &r), 3.657889671577715808e-06, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (1000, 4294967296.0, &r), 3.656551321485397501e-06, 2.0e-05, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Yn_e, (2, 15000.0, &r), -0.006185217273358617849, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (1e-10, &r), 0.99999999990000000001, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (0.1, &r), 0.90710092578230109640, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (2, &r), 0.30850832255367103953, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (100.0, &r), 0.03994437929909668265, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_scaled_e, (65536.0, &r), 0.0015583712551952223537, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (0.1, &r), 0.04529844680880932501, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (2, &r), 0.21526928924893765916, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (100.0, &r), 0.03974415302513025267, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_scaled_e, (65536.0, &r), 0.0015583593657207350452, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( -4, 0.1, &r), 2.3575258620054605307e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 4, 0.1, &r), 2.3575258620054605307e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 5, 2.0, &r), 0.0013297610941881578142, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 100, 100.0, &r), 1.7266862628167695785e-22, TEST_TOL0, GSL_SUCCESS); /* BJG: the "exact" values in the following two tests were originally computed from the taylor series for I_nu using "long double" and rescaling. The last few digits were inaccurate due to cumulative roundoff. BJG: 2006/05 I have now replaced these with the term asymptotic expansion from A&S 9.7.1 which should be fully accurate. */ TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 2, 1e7, &r), 1.261566024466416433e-4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_scaled_e, ( 2, 1e8, &r), 3.989422729212649531e-5, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_e, (0.1, &r), 1.0025015629340956014, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_e, (2.0, &r), 2.2795853023360672674, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I0_e, (100.0, &r), 1.0737517071310738235e+42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_e, (0.1, &r), 0.05006252604709269211, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_e, (2.0, &r), 1.59063685463732906340, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_I1_e, (100.0, &r), 1.0683693903381624812e+42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_e, ( 4, 0.1, &r), 2.6054690212996573677e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_e, ( 5, 2.0, &r), 0.009825679323131702321, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_In_e, ( 100, 100.0, &r), 4.641534941616199114e+21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (0.1, &r), 2.6823261022628943831, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (1.95, &r), 0.8513330938802157074894, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (2.0, &r), 0.8415682150707714179, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (6.0, &r), 0.50186313086214003217346, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_scaled_e, (100.0, &r), 0.1251756216591265789, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (0.1, &r), 10.890182683049696574, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (1.95, &r), 1.050086915104152747182, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (2.0, &r), 1.0334768470686885732, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (6.0, &r), 0.5421759102771335382849, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_scaled_e, (100.0, &r), 0.1257999504795785293, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_scaled_e, ( 4, 0.1, &r), 530040.2483725626207, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_scaled_e, ( 5, 2.0, &r), 69.68655087607675118, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_scaled_e, ( 100, 100.0, &r), 2.0475736731166756813e+19, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_e, (0.1, &r), 2.4270690247020166125, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_e, (1.95, &r), 0.1211226255426818887894, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_e, (2.0, &r), 0.11389387274953343565, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K0_e, (100.0, &r), 4.656628229175902019e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_e, (0.1, &r), 9.853844780870606135, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_e, (1.95, &r), 0.1494001409315894276793, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_e, (2.0, &r), 0.13986588181652242728, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_K1_e, (100.0, &r), 4.679853735636909287e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_e, ( 4, 0.1, &r), 479600.2497925682849, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_e, ( 5, 2.0, &r), 9.431049100596467443, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Kn_e, ( 100, 100.0, &r), 7.617129630494085416e-25, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (-10.0, &r), -0.05440211108893698134, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (0.001, &r), 0.9999998333333416667, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, ( 1.0, &r), 0.84147098480789650670, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, ( 10.0, &r), -0.05440211108893698134, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (100.0, &r), -0.005063656411097587937, TEST_TOL1, GSL_SUCCESS); #ifdef FIXME TEST_SF(s, gsl_sf_bessel_j0_e, (1048576.0, &r), 3.1518281938718287624e-07, TEST_TOL2, GSL_SUCCESS); #endif /* these values are from Mathematica */ #ifdef FIXME TEST_SF(s, gsl_sf_bessel_j0_e, (1.0e18, &r), -9.9296932074040507620955e-19, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j0_e, (1.0e20, &r), -6.4525128526578084420581e-21, TEST_TOL0, GSL_SUCCESS); #endif TEST_SF(s, gsl_sf_bessel_j1_e, (-10.0, &r), -0.07846694179875154709, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, (0.01, &r), 0.003333300000119047399, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, ( 1.0, &r), 0.30116867893975678925, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, ( 10.0, &r), 0.07846694179875154709, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, (100.0, &r), -0.008673825286987815220, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j1_e, (1048576.0, &r), -9.000855242905546158e-07, TEST_TOL0, GSL_SUCCESS); /*TEST_SF(s, gsl_sf_bessel_j1_e, (1.0e18, &r), -1.183719902187107336049e-19, TEST_TOL0, GSL_SUCCESS);*/ TEST_SF(s, gsl_sf_bessel_j2_e, (-10.0, &r), 0.07794219362856244547, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (0.01, &r), 6.666619047751322551e-06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, ( 1.0, &r), 0.06203505201137386110, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, ( 10.0, &r), 0.07794219362856244547, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (100.0, &r), 0.004803441652487953480, TEST_TOL1, GSL_SUCCESS); #if 0 /* bug #45730; the bug should be fixed, but these tests are disabled since error computation is not correct for these inputs */ TEST_SF(s, gsl_sf_bessel_j2_e, (1048576.0, &r), -3.1518539455252413111e-07, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (-1.0e22, &r), 5.23214785395139e-23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (-1.0e21, &r), 7.449501119831337e-22, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (-1.0e20, &r), 7.639704044417282e-21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (-1.0e19, &r), -3.749051695507179e-20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (1.0e19, &r), -3.749051695507179e-20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (1.0e20, &r), 7.639704044417282e-21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (1.0e21, &r), 7.449501119831337e-22, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_j2_e, (1.0e22, &r), 5.23214785395139e-23, TEST_TOL2, GSL_SUCCESS); #endif TEST_SF(s, gsl_sf_bessel_jl_e, (0, 0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (1, 10.0, &r), 0.07846694179875154709000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (5, 1.0, &r), 0.00009256115861125816357, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (10, 10.0, &r), 0.06460515449256426427, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (100, 100.0, &r), 0.010880477011438336539, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (2000, 1048576.0, &r), 7.449384239168568534e-07, TEST_SQRT_TOL0, GSL_SUCCESS); /* related to BUG#3 problem */ TEST_SF(s, gsl_sf_bessel_jl_e, (2, 900.0, &r), -0.0011089115568832940086, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (2, 15000.0, &r), -0.00005955592033075750554, TEST_TOL4, GSL_SUCCESS); /* Bug report by Mario Santos, value computed from AS 10.1.8 */ TEST_SF(s, gsl_sf_bessel_jl_e, (100, 1000.0, &r), -0.00025326311230945818285, TEST_TOL4, GSL_SUCCESS); /* Bug reported by Koichi Takahashi <ktakahashi@molsci.org>, computed from Pari besseljh(n,x) and AS 10.1.1 */ TEST_SF(s, gsl_sf_bessel_jl_e, (30, 3878.62, &r), -0.00023285567034330878410434732790, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (49, 9912.63, &r), 5.2043354544842669214485107019E-5 , TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (49, 9950.35, &r), 5.0077368819565969286578715503E-5 , TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_jl_e, (52, 9930.51, &r), -7.4838588266727718650124475651E-6 , TEST_TOL4, GSL_SUCCESS); /* bug report #37209 */ TEST_SF(s, gsl_sf_bessel_jl_e, (364, 36.62, &r), 1.118907148986954E-318, TEST_TOL0, GSL_SUCCESS); /*TEST_SF(s, gsl_sf_bessel_jl_e, (149, 1.0, &r), 2.6599182755508469E-307, TEST_TOL0, GSL_SUCCESS);*/ TEST_SF(s, gsl_sf_bessel_y0_e, (0.001, &r), -999.99950000004166670, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, ( 1.0, &r), -0.5403023058681397174, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, ( 10.0, &r), 0.08390715290764524523, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, (100.0, &r), -0.008623188722876839341, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, (65536.0, &r), 0.000011014324202158573930, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y0_e, (4294967296.0, &r), 2.0649445131370357007e-10, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, ( 0.01, &r), -10000.499987500069444, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, ( 1.0, &r), -1.3817732906760362241, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, ( 10.0, &r), 0.06279282637970150586, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, (100.0, &r), 0.004977424523868819543, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y1_e, (4294967296.0, &r), 1.0756463271573404688e-10, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, ( 0.01, &r), -3.0000500012499791668e+06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, ( 1.0, &r), -3.605017566159968955, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, ( 10.0, &r), -0.06506930499373479347, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, (100.0, &r), 0.008772511458592903927, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_y2_e, (4294967296.0, &r), -2.0649445123857054207e-10, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (0, 0.01, &r), -99.995000041666528, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (0, 1.0, &r), -0.54030230586813972, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (1, 10.0, &r), 0.062792826379701506, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (5, 1.0, &r), -999.44034339223641, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (10, 0.01, &r), -6.5473079797378378e+30, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (10, 10.0, &r), -0.172453672088057849, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (100, 1.0, &r), -6.6830794632586775e+186, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (100, 100.0, &r), -0.0229838504915622811, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_yl_e, (2000, 1048576.0, &r), 5.9545201447146155e-07, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (0.1, &r), 0.9063462346100907067, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (2.0, &r), 0.24542109027781645493, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i0_scaled_e, (100.0, &r), 0.005000000000000000000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (0.1, &r), 0.030191419289002226846, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (2.0, &r), 0.131868364583275317610, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i1_scaled_e, (100.0, &r), 0.004950000000000000000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (0.1, &r), 0.0006036559400239012567, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (2.0, &r), 0.0476185434029034785100, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_i2_scaled_e, (100.0, &r), 0.0048515000000000000000, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 0, 0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 1, 0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 4, 0.001, &r), 1.0571434341190365013e-15, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 4, 0.1, &r), 9.579352242057134927e-08, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 5, 2.0, &r), 0.0004851564602127540059, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 5, 100.0, &r), 0.004300446777500000000, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_il_scaled_e, ( 100, 100.0, &r), 1.3898161964299132789e-23, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k0_scaled_e, (0.1, &r), 15.707963267948966192, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k0_scaled_e, (2.0, &r), 0.7853981633974483096, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k0_scaled_e, (100.0, &r), 0.015707963267948966192, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k1_scaled_e, (0.1, &r), 172.78759594743862812, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k1_scaled_e, (2.0, &r), 1.1780972450961724644, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k1_scaled_e, (100.0, &r), 0.015865042900628455854, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k2_scaled_e, (0.1, &r), 5199.335841691107810, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k2_scaled_e, (2.0, &r), 2.5525440310417070063, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_k2_scaled_e, (100.0, &r), 0.016183914554967819868, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 4, 1.0/256.0, &r), 1.8205599816961954439e+14, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 4, 1.0/8.0, &r), 6.1173217814406597530e+06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 5, 2.0, &r), 138.10735829492005119, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_kl_scaled_e, ( 100, 100.0, &r), 3.985930768060258219e+18, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.0001, 1.0, &r), 0.7652115411876708497, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.0001, 10.0, &r), -0.2459270166445205, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.0009765625, 10.0, &r), -0.2458500798634692, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.75, 1.0, &r), 0.5586524932048917478, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (0.75, 10.0, &r), -0.04968928974751508135, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, ( 1.0, 0.001, &r), 0.0004999999375000026, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, ( 1.0, 1.0, &r), 0.4400505857449335160, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, ( 1.75, 1.0, &r), 0.168593922545763170103, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (30.0, 1.0, &r), 3.482869794251482902e-42, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (30.0, 100.0, &r), 0.08146012958117222297, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (10.0, 1.0, &r), 2.6306151236874532070e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (10.0, 100.0, &r), -0.05473217693547201474, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (10.2, 100.0, &r), -0.03548919161046526864, TEST_TOL2, GSL_SUCCESS); /* related to BUG#3 problem */ TEST_SF(s, gsl_sf_bessel_Jnu_e, (2.0, 900.0, &r), -0.019974345269680646400, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (2.0, 15000.0, &r), -0.0020455820181216382666, TEST_TOL4, GSL_SUCCESS); /* Jnu for negative integer nu */ TEST_SF(s, gsl_sf_bessel_Jnu_e, (-13, 4.3966088395743909188e-1, &r), -4.4808688873945295916e-19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-43, 3.2953184511924683369e-1, &r), -3.4985116870357066158e-87, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8, 3.5081119129046332101e-1, &r), 2.2148387185334257376e-11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-17, 1.6717234250796879247e-1, &r), -1.3336696368048418208e-33, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-20, 1.0085435516296562067e-1, &r), 4.6463938513369299663e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 1.0423882905853389231e-1, &r), -7.0211488877617616588e-69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-10, 2.014635069337132169e-1, &r), 2.9614218635575180136e-17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-23, 3.3470953660313309239e-1, &r), -5.3786691977970313226e-41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-13, 1.796487688043502395e-2, &r), -3.9796275104402232636e-37, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-30, 4.3851505455005663023e-1, &r), 6.3723816221242007043e-53, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-31, 2.9134673992671269075e-1, &r), -1.4108323502121482121e-60, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-28, 7.6696967407852829575e-1, &r), 7.2211466723046636958e-42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6, 1.9829576302527197691e-2, &r), 1.3193561299244410609e-15, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 4.1513019703157674847e-1, &r), 4.362149422492811209e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-19, 1.3033500482689031834e-2, &r), -2.4071043287214877014e-59, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4, 7.2050154387915780891e-1, &r), 6.8377203227324865568e-4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-36, 9.058436592111083308e-1, &r), 1.1063535538518134862e-54, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-37, 4.4893454860671838425e-2, &r), -7.1436404620419702996e-105, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-25, 1.4253284590439372148e-1, &r), -1.3532982149810467304e-54, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-35, 6.8075538970323047806e-1, &r), -4.0087398199591044218e-57, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-9, 6.9978823056579836732e-2, &r), -2.1657760307485265867e-19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-30, 8.3903642499214990225e-1, &r), 1.8046736761082165751e-44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-43, 6.543891152683782553e-1, &r), -2.2618181452671187564e-74, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1, 2.557673774862201033e-1, &r), -1.2684081505646766845e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-21, 2.3961944728579204361e-1, &r), -8.7037441094405713341e-40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-13, 3.7732868931080794955e-1, &r), -6.1458679923678486123e-20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-33, 3.8478064679256785588e-1, &r), -2.7471851206170506902e-61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-50, 8.3045728127372512419e-1, &r), 2.6904315506244885678e-84, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-33, 3.4391840270211572065e-1, &r), -6.7604474418522862789e-63, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-23, 4.4699489157302132678e-1, &r), -4.1674520864249550489e-38, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-23, 8.6894302936681315656e-1, &r), -1.8080036072447165775e-31, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 2.3997647040322801696e-1, &r), 1.2775332144705955465e-46, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4, 9.7688590680055575385e-1, &r), 2.260676935437026869e-3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-20, 8.9090003293395823104e-1, &r), 3.8525697232471553813e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-37, 9.4057990133775869779e-1, &r), -5.4483632006108552908e-56, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1, 2.6641070579761597867e-1, &r), -1.3202706692617745567e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-7, 9.8878610880180753494e-1, &r), -1.3892626129288932172e-6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 3.1042396387236895292e-1, &r), 7.4291433893935351027e-86, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-18, 6.8722270094498481586e-1, &r), 6.9210950943508574463e-25, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-16, 1.6113707818439830316e-2, &r), 1.5066992425677873707e-47, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-31, 3.0720392023079679622e-1, &r), -7.2938615192106070364e-60, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8, 3.4957196590626821859e-1, &r), 2.153068469114375124e-11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4, 9.9805150837159144851e-1, &r), 2.4578749047519916152e-3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8, 8.4538260733781281419e-1, &r), 2.4776262290872395403e-8, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-21, 7.8935512795174026579e-1, &r), -6.4516652247824702208e-29, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-32, 3.4859401756229795902e-1, &r), 1.9985100102959434086e-60, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-28, 9.2530929240293814377e-1, &r), 1.3798987861611642315e-39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-32, 5.7276907866586953775e-1, &r), 1.5890407703711501803e-53, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-16, 8.6364032267280037696e-1, &r), 6.9097436254460436398e-20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 8.1065458967451038451e-2, &r), 6.2316950805227520253e-58, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-17, 6.946415511078842723e-1, &r), -4.3495405983099048944e-23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-14, 2.7619565270505476723e-1, &r), 1.0511271746088180311e-23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-7, 8.579791601466317093e-2, &r), -5.3039175204559594309e-14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-50, 7.4681490716561041968e-1, &r), 1.3331741219055661824e-86, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-30, 9.6631424224612452556e-1, &r), 1.2465815577059566852e-42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-14, 2.6745819874317492788e-1, &r), 6.7024985048974981757e-24, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 3.6947309321414497419e-1, &r), 6.4975710352073715961e-38, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-49, 2.3389602803779083655e-2, &r), -3.5281224467005794333e-158, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-48, 7.7482504299905127354e-1, &r), 1.3711857024107478291e-81, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-30, 6.5337950709230049969e-1, &r), 9.9749347191786840601e-48, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 5.4117488569210959438e-1, &r), -3.8843890347204927665e-48, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-50, 9.4038774092645791075e-1, &r), 1.3455212768163778034e-81, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1, 5.627399919447310892e-1, &r), -2.703780920058947009e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-35, 7.9925999507829895011e-2, &r), -1.1060656306690664139e-89, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-10, 2.8875439067692705135e-3, &r), 1.0844833648855202142e-35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-31, 2.7645446745852278572e-1, &r), -2.7740931384652548129e-61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-12, 8.5374968606378578252e-1, &r), 7.5366644001760905687e-14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-11, 2.2997159465452075155e-1, &r), -1.1626579415654480052e-18, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-47, 5.8616043503503357359e-1, &r), -3.4270544836018351049e-85, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 8.4884849730214263521e-1, &r), 1.8679667366331791405e-33, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 5.3943176031162412158e-1, &r), 3.5300994115064965228e-38, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3, 9.3387179309343112648e-1, &r), -1.6062668879215016378e-2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-20, 5.5061917642540109891e-1, &r), 2.5629166990385734238e-30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 2.9315675715515822781e-1, &r), 5.1505442739915338391e-49, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6, 8.9079715253593128884e-1, &r), 1.0539758479683914316e-5, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-30, 9.1220250697048036241e-2, &r), 2.2291985671052015068e-73, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-49, 3.2934552845357396486e-1, &r), -6.7628009346158039786e-102, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-20, 6.2008856084878849548e-3, &r), 2.7691703032688977815e-69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-23, 7.1620177578706903472e-1, &r), -2.124755495743639839e-33, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 5.1124413385957329246e-1, &r), -7.462204354283390559e-49, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-23, 6.7405321505832900803e-1, &r), -5.2689769204867120958e-34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-31, 7.6828173704641609615e-2, &r), -1.600162678935095954e-78, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4, 7.8546641070654814244e-1, &r), 9.610534504452577567e-4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-39, 7.8708523270381710591e-1, &r), -7.8237015591341025437e-63, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8, 1.1973778137874968338e-1, &r), 4.0918170073170305674e-15, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 7.9699790929323855652e-1, &r), 1.4309765990568672215e-30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-11, 4.4800161319259052168e-1, &r), -1.7773520138988139169e-15, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-39, 9.2637892745877041811e-1, &r), -4.4944192865215894733e-60, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 4.6475617572623309956e-1, &r), -4.7026155154566357963e-50, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-25, 4.6435749048262147537e-1, &r), -8.9952935327704632698e-42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-28, 9.6511079209639008185e-1, &r), 4.4842768640542298547e-39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-36, 3.8411791760130458261e-2, &r), 4.296403338839098526e-104, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6, 2.891145018145052606e-1, &r), 1.2636012998902815302e-8, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-43, 3.0866754076112185885e-1, &r), -2.1010663709383681337e-88, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-44, 8.3972445789951961023e-1, &r), 9.7813493638738341846e-72, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 8.2307293342676789357e-1, &r), 2.9041436661554638719e-30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-12, 9.8857250941935924585e-1, &r), 4.357505306871049656e-13, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-47, 9.9901153675544108048e-1, &r), -2.6090278787375958472e-74, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-44, 2.8286777063559952163e-1, &r), 1.5832896249242322418e-92, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-10, 9.7638349947419439863e-1, &r), 2.0735913941162063742e-10, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-36, 4.6452631984005212745e-1, &r), 4.0190510760125038996e-65, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-25, 8.2954737598010312336e-1, &r), -1.7855017422981225812e-35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 4.2326977999795604681e-1, &r), -3.1249531389372439734e-51, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-9, 6.339167576518494852e-1, &r), -8.8082994072251150317e-11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-27, 7.4535258299077637954e-1, &r), -2.4368032520208918805e-40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-45, 8.0998976704970278418e-1, &r), -1.8024726219976677441e-74, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 5.3437414610693284794e-1, &r), 2.8159486268019058346e-38, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-19, 3.6987646459831328184e-1, &r), -9.7200835901252686409e-32, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-49, 4.7308684164506190021e-1, &r), -3.4438316393709775799e-94, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 8.4616849424460901479e-1, &r), 1.4469107537397962381e-67, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-39, 8.6819804427642418616e-1, &r), -3.5837055310896411954e-61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-28, 4.1490163307722590922e-1, &r), 2.448154551562710141e-49, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-25, 6.312651668273163642e-1, &r), -1.9374739456138691106e-38, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-32, 5.3525470388026220677e-1, &r), 1.8191207037881755277e-54, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-13, 9.2605599515408535679e-3, &r), -7.2212651931099339154e-41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-37, 4.8798589647640992562e-1, &r), -1.5614996577959031121e-66, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-37, 2.2096551301466541766e-2, &r), -2.9050812034192451665e-116, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 1.8092873560926168207e-1, &r), 1.0575388628113044972e-95, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 4.2954143428969324083e-1, &r), 1.7857221060719548205e-36, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-41, 1.7704659657689619579e-1, &r), -2.017674513721498041e-93, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3, 8.8755155653793053987e-1, &r), -1.3862799262620708632e-2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1, 6.7617657704638521874e-1, &r), -3.1913053561511127823e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-34, 6.4464304038438048178e-1, &r), 6.4622314654558520448e-56, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-41, 7.2625991432244163042e-1, &r), -2.7337118024791538344e-68, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3, 6.357184822423154937e-1, &r), -5.2186206749718741014e-3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6, 8.4999778579632777264e-1, &r), 7.9757193518631922586e-6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-47, 4.9270801771231759268e-1, &r), -9.7743102162756354643e-89, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-44, 3.0382431918975667824e-1, &r), 3.6749344196700669304e-91, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-21, 8.3709075395163832807e-1, &r), -2.2120291813240017972e-28, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-13, 2.2926361048823468174e-1, &r), -9.4684470339645238166e-23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2, 7.7595731076113971064e-1, &r), 7.1557648504788709828e-2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-13, 8.3155666144468474085e-1, &r), -1.760187305034807398e-15, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 8.9229820511590331545e-1, &r), 1.8952192929209682492e-36, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-9, 4.3091918823985208523e-1, &r), -2.7448142505229531657e-12, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-45, 7.6232573842954975111e-1, &r), -1.177044451508791199e-75, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-47, 8.5370192783467777094e-1, &r), -1.6168449888151601463e-77, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-17, 7.0917926374340919579e-1, &r), -6.1835780259077271289e-23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-48, 5.3177634068823620691e-1, &r), 1.9544175507861216812e-89, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-20, 8.6236563774769292261e-1, &r), 2.0102896278761019978e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-47, 1.9398034049650767996e-1, &r), -9.1928516850183758066e-108, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 1.9059407555598432968e-1, &r), 3.0818305203000064476e-44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-28, 1.177497340192600765e-1, &r), 1.1853471604859571152e-64, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-44, 5.4411719229619710879e-1, &r), 5.0099597095462268336e-80, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 8.4096736569723091858e-1, &r), 4.6598891827094030103e-30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-14, 5.7336031747513286455e-1, &r), 2.8892068362904543886e-19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 4.3701161637218456507e-1, &r), 2.2572337854881401663e-40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-16, 5.5950502438849852065e-1, &r), 6.6952184074205206877e-23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-15, 7.2135709344094709909e-1, &r), -1.724936657760223936e-19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 8.9503358993826252397e-1, &r), 1.5285906153951174029e-66, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-34, 8.8842662562391397862e-1, &r), 3.5115599466639988263e-51, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 7.1820429322328243568e-1, &r), 3.3906734873299682373e-35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 6.9983283703407621113e-1, &r), 4.9840979255532732037e-71, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 3.4956023377394930027e-1, &r), -1.2169918834421082937e-53, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 3.1780802172157483391e-1, &r), 1.0816638066322224274e-43, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 6.6747313617191922586e-1, &r), 6.8258422034194326368e-72, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 9.8281798409069473598e-1, &r), -1.2641970706335426485e-40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-48, 9.3933236478420901552e-1, &r), 1.4126090419557425431e-77, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-33, 7.9969562813573452357e-1, &r), -8.3521436185818779821e-51, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4, 1.749832037277650746e-1, &r), 2.4377505307831309992e-6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-12, 7.4928517324325015606e-1, &r), 1.578984980873870348e-14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-50, 6.8668643284952988717e-1, &r), 2.0060641365741957198e-88, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 4.628453813124784986e-1, &r), 7.3802979097358757591e-44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-17, 1.3398796901656815413e-1, &r), -3.1005014564142463477e-35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-21, 4.3589737907768555406e-1, &r), -2.4897620016130572781e-34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-49, 9.3471214811043877923e-1, &r), -1.0635172631183545319e-79, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-12, 6.2842914244476056474e-1, &r), 1.919020727030761691e-15, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-44, 3.9902397275715061045e-1, &r), 5.9381636725852262522e-86, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-38, 7.4844742354073981342e-1, &r), 1.1452741249870059158e-61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 1.7024143837455386901e-1, &r), 2.5696433432212310518e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-35, 2.4663778723047911984e-1, &r), -1.4846380265631517846e-72, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 3.4675532474808813305e-1, &r), 7.7576502065450687145e-84, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-42, 9.7015007293565236242e-1, &r), 4.5073367850753509233e-65, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-18, 5.8064934044500015204e-1, &r), 3.3392049842730194442e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4, 8.9712869996285071984e-1, &r), 1.6201373653351794808e-3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-14, 4.7509593095794841351e-1, &r), 2.0819777331649343154e-20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 1.9971440277743206076e-1, &r), 1.5567772398263651029e-48, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2, 3.1326041354180815314e-1, &r), 1.2166506426643152762e-2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-21, 7.1780328035546876532e-1, &r), -8.7820775346034440302e-30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-40, 3.4783624449708255548e-1, &r), 5.0330128895858604038e-79, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 4.6025606383259078342e-1, &r), 7.8278566159609528116e-40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-37, 6.8329209514074967672e-1, &r), -4.0018049034521909865e-61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 3.1644447969459523952e-1, &r), 3.757803139189680586e-48, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-49, 3.8814659649103508174e-1, &r), -2.1178321069354253493e-98, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-33, 2.2586340634075651258e-1, &r), -6.3690605699693325702e-69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-31, 1.1833425544176035201e-1, &r), -1.0457450400633015896e-72, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-7, 4.716233225505345007e-1, &r), -7.9892591292002198427e-9, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-28, 4.0216249780484400656e-1, &r), 1.0224868057823447281e-49, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-39, 2.1728515555094074309e-1, &r), -1.2424793343150735922e-84, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-10, 1.5286805658821812372e-1, &r), 1.8744497113230339685e-18, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2, 4.2012489177724585853e-1, &r), 2.1740379601921820516e-2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3, 5.4168160735476556955e-1, &r), -3.2509626190739798323e-3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 6.0999547254418081401e-1, &r), 9.6515399655293906821e-41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-31, 9.3599472437451867441e-1, &r), -7.236873645285246215e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2, 8.9238535456317991508e-2, &r), 9.9477909077321557346e-4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-41, 3.3286697432119768766e-1, &r), -3.5168501713472066379e-82, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 1.3103200887095798302e-2, &r), 4.1630610278945554747e-84, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-7, 6.8545576155223653312e-1, &r), -1.0860095433456484207e-7, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-33, 7.4597656684747976078e-1, &r), -8.4232256181114982289e-52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-35, 9.5265851504353628581e-1, &r), -5.1260638475279101845e-52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-5, 1.9993324513780069188e-2, &r), -8.319296787329444617e-13, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-15, 7.291071285552115835e-2, &r), -2.0411952376466778385e-34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-5, 4.307852573603263607e-1, &r), -3.8336545021181925733e-6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8, 3.0719264454074178501e-1, &r), 7.6627991262305533713e-12, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-7, 2.9261260328577001029e-1, &r), -2.8395431884068098274e-10, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-36, 3.4285828911893011822e-1, &r), 7.1807133181285014617e-70, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-22, 2.1687887653368606307e-1, &r), 5.2860475778514174667e-43, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 7.2816755037040510323e-1, &r), 4.7187086299885949165e-35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-18, 2.0826276232560462604e-2, &r), 3.2368741843295077202e-52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-9, 6.8082174052201672454e-1, &r), -1.6719854980400483279e-10, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 1.1998114825675920571e-1, &r), 4.2119340347581322841e-59, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-9, 5.9197600088654039875e-1, &r), -4.7631865156190005935e-11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-30, 1.2367288101522705215e-1, &r), 2.0588316029270585207e-69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-7, 8.3266930505292536647e-1, &r), -4.2096524602233328394e-7, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-18, 4.360196631312459384e-1, &r), 1.9281550661128359168e-28, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-13, 9.8501660515145040901e-1, &r), -1.5833136710018445626e-14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 9.3281324180154613247e-1, &r), -2.7828395455119501545e-41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-50, 8.9831019278310796215e-1, &r), 1.3646576617083900982e-82, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-34, 8.1153956230382506493e-1, &r), 1.6192058088789772833e-52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-15, 9.5908894233909785027e-1, &r), -1.2293883538807523551e-17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-28, 4.7478353398916835208e-1, &r), 1.0667274838088242221e-47, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-26, 3.1425431663890729964e-1, &r), 3.137014371489532261e-48, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 6.8861856868877100233e-1, &r), -4.2000859317520628674e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-16, 6.9807655407582355921e-1, &r), 2.3026948238804970982e-21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-15, 1.9223628937777433793e-1, &r), -4.2201734817670464106e-28, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-24, 7.91209811831343471e-1, &r), 3.458241440092889033e-34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-12, 2.8881796002183274727e-1, &r), 1.7143390913163291276e-19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-34, 3.6891378721647167497e-1, &r), 3.7139793083014182422e-64, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-20, 8.4841223828616526898e-1, &r), 1.4510812436551651903e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-23, 2.2490195812594682131e-1, &r), -5.7468688920782767025e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-18, 2.2504144134842978217e-1, &r), 1.3048322081397375779e-33, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-41, 8.9085721717774902491e-1, &r), -1.1841910084346823163e-64, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-14, 3.5776817082613807574e-1, &r), 3.9325021938284721675e-22, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-17, 4.6898364389788035003e-1, &r), -5.492570150236103145e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6, 7.4085998179632632531e-1, &r), 3.5186865149767756957e-6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-29, 8.1247678941673114604e-1, &r), -5.0783189409391835819e-43, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6, 1.7590874156867732351e-2, &r), 6.4299450335557031571e-16, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6, 4.1122931368227349961e-2, &r), 1.0494595145859932593e-13, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-18, 3.4357780610013843947e-2, &r), 2.6519427947417673311e-48, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8, 7.2901630769663700817e-1, &r), 7.6159005881302088369e-9, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-40, 6.2434787548617066655e-1, &r), 7.297739135890827566e-69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-37, 2.5717302633809380684e-1, &r), -7.9671811532819427071e-77, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-12, 4.4871088635019795091e-1, &r), 3.3823657137507787902e-17, TEST_TOL2, GSL_SUCCESS); /* Jnu for negative nu */ TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.7408502287167772557e+1, 4.3891036254061936271e-2, &r), -1.5118966152679114528e+42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.0369289750688261206e+1, 8.617077861907621132e-1, &r), 1.3458137581188368176e+61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.6398263821779503158, 5.7108775125890870648e-1, &r), -1.1073338178875224514e+2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.0743837616631487936e+1, 2.2372123946196517647e-1, &r), 1.3987244312547157439e+37, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.7297952956642177128e+1, 2.8440280848533973972e-1, &r), -5.5832331287880973953e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.3507072230824139103e+1, 9.7008738913549467403e-1, &r), -9.9108981827284991851e+12, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.4663106025697138284e+1, 9.6739483983540323655e-1, &r), 2.5305841722999151766e+67, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.7450767905208691173e+1, 5.2288309478685515663e-3, &r), -3.4541920228396234708e+180, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.8736914274754280581e+1, 4.4318942692773250336e-1, &r), 1.2783291424623089209e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.4560791710276042462e+1, 5.6595841783863809163e-1, &r), 1.7364781221343685309e+56, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.8723165418996042381e+1, 2.4003201116391659975e-1, &r), 8.229650479070536446e+54, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.1780816480084454714e+1, 3.5000033756039229564e-1, &r), -8.9158096963672457852e+56, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8.3572537806135923827, 8.994859317735841446e-1, &r), 2.4471474432717596765e+6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.9179499652113791027e+1, 7.3466044408596358731e-1, &r), -1.0446080588162613503e+82, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.0204535104461498585e+1, 1.3316368076269799096e-1, &r), 1.6723180404777533538e+93, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.9597169419874779916e+1, 8.3895848736941180651e-1, &r), -1.9885394381212418599e+80, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.2228113163441444643e+1, 7.2360070820350912315e-1, &r), 3.7033741801434815187e+12, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.3252347726870680973e+1, 4.7042383176138740544e-2, &r), -2.2524439080867705956e+121, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.8363275112470146292e+1, 3.5406545166014987925e-1, &r), 7.0915928368505654149e+95, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.4031313414732363799e+1, 1.7077658851102128503e-1, &r), 4.2707681524978432343e+46, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.4994220322161396103e+1, 7.6004498361697560048e-2, &r), 8.3491267575601512811e+85, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.5842451866339926986e+1, 7.1655842470093644641e-1, &r), -1.4956016465164596038e+18, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.3303969013414183336e+1, 3.4261981308825774017e-1, &r), -1.7313464383524562686e+84, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.9620214546900609668e+1, 8.9559048893071335969e-2, &r), -6.5439278427877993956e+69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.9267775155252921091e+1, 4.9173394917277714574e-1, &r), -2.7879726255003962141e+68, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.085805422677201981e+1, 7.1844728658692273953e-2, &r), 1.7330833141098585591e+21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.3205222720657600449e+1, 2.0938011160695718605e-1, &r), -1.2855953290893319419e+93, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.1761832688338363731e-1, 4.0692821730479031008e-1, &r), 1.0616114810207300625, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.4176152886105712673e+1, 7.3083748089885469319e-1, &r), 2.3708170326600879156e+51, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.7495316392965243753e+1, 3.6374757654471397858e-1, &r), -2.4050181588419272908e+26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.4363999308889822481e+1, 2.2964635433363436307e-1, &r), 1.4858445128296594446e+23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.5945782535187393546e+1, 5.5004988492253222851e-1, &r), -5.3196903529172738965e+19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.6539439893219625339e+1, 5.4022213494661757887e-1, &r), 3.4606719889912371036e+40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.9104819423206076833e+1, 8.7581079115207012305e-1, &r), -8.3806822204633705862e+57, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.1344422530419629852e+1, 1.8412292138063948156e-1, &r), -1.3032526695489281999e+18, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.2479004807998664153e+1, 7.628052499161305046e-1, &r), 3.8593605090529013702e+67, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.7234292208462683278e+1, 5.6929354834881763134e-1, &r), -1.3560087920173394791e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.9852923491811760298e+1, 2.1764339448558498796e-2, &r), -3.1065720979758225192e+88, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.9470737712526065987e+1, 9.1397839227827761003e-1, &r), -4.9854244578384505794e+39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.4879459756439547254e+1, 8.7694253508024822462e-1, &r), 4.0540656704233640216e+31, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-8.6562240771489400173e-1, 6.4882619355798588927e-1, &r), 9.5827819637209987022e-2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.4096305256724256786e+1, 1.1837901256079790395e-1, &r), 1.5389662008468777023e+26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.3739240782592000796e+1, 1.1830951764837136725e-1, &r), -5.4851415830067607572e+25, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-7.7683272384817803185e-1, 2.0897180603218726575e-1, &r), 1.3452855819917342033, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.9007825894244022613e+1, 8.0804305816981973945e-1, &r), -1.9558153171413640836e+78, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.224872379992519031, 9.4716012050013901355e-1, &r), -8.7507643021583199242e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-5.0807600398060325807e+1, 6.1902119795226148946e-1, &r), 1.9558680407989173708e+89, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.2130610423140110162e+1, 7.2184881647444607846e-1, &r), 3.0709609117301881893e+67, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.1186300874143057513e+1, 1.3944550368322800884e-1, &r), -1.2405415201132534983e+95, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.1777582295815773824e+1, 7.6178874271077561762e-1, &r), -7.1748063501973138583e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.2185912810368133222e+1, 3.959510541558671016e-1, &r), 1.196451653185591802e+56, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.2976006083946226988e+1, 4.5739390828369379657e-1, &r), 1.0599129365585919882e+77, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.0412232215064606945e+1, 6.7510758855896918145e-1, &r), 2.4302601636670462267e+45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.8388188389747281955e+1, 8.9233979909724013718e-1, &r), 9.1410432331502484426e+20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-2.4298840569257253701e+1, 6.8042862360863559591e-1, &r), 4.0995648850574613979e+33, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.8834735272673504063e+1, 4.2324469410479691518e-1, &r), 7.0355133597135130631e+69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.6091840934431606344e+1, 1.7508918790902548661e-1, &r), 8.7456315137421979067e+103, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.9754264394942756728, 1.558717798933954111e-2, &r), -3.551027943747170162e+2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.7168594342366560374e+1, 6.976373865080374073e-1, &r), -1.1036447967023475572e+58, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.5379944292029245754e+1, 5.3150471205968938472e-2, &r), -1.0469743921754287032e+126, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-1.153181439556533474e+1, 1.8204366094125528818e-1, &r), -4.0986515168430307785e+18, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-4.9939680334734766385e+1, 8.132277926604580844e-1, &r), -9.5179038651143567503e+80, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-3.5986707652967270442e+1, 5.5665988728905782182e-1, &r), -1.27797927382078249e+58, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Jnu_e, (-6.7046620273111013832, 1.059530133767196237e-1, &r), 3.8106055649273069958e+10, TEST_TOL2, GSL_SUCCESS); /* Ynu */ TEST_SF(s, gsl_sf_bessel_Ynu_e, (0.0001, 1.0, &r), 0.08813676933044478439, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (0.0001,10.0, &r), 0.05570979797521875261, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 0.75, 1.0, &r), -0.6218694174429746383, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 0.75, 10.0, &r), 0.24757063446760384953, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 1.0, 0.001, &r), -636.6221672311394281, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, ( 1.0, 1.0, &r), -0.7812128213002887165, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (30.0, 1.0, &r), -3.0481287832256432162e+39, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (30.0, 100.0, &r), 0.006138839212010033452, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (10.0, 1.0, &r), -1.2161801427868918929e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (10.0, 100.0, &r), 0.05833157423641492875, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (10.2, 100.0, &r), 0.07169383985546287091, TEST_TOL2, GSL_SUCCESS); /* Ynu for negative integer nu */ TEST_SF(s, gsl_sf_bessel_Ynu_e, (-13, 4.3966088395743909188e-1, &r), 5.4675723318993574107e+16, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-43, 3.2953184511924683369e-1, &r), 2.115977780575035527e+84, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-8, 3.5081119129046332101e-1, &r), -1.7982193624366780622e+9, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-17, 1.6717234250796879247e-1, &r), 1.4040223280006382933e+31, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-20, 1.0085435516296562067e-1, &r), -3.4253870177732383503e+42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-29, 1.0423882905853389231e-1, &r), 1.5633159385709367033e+66, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-10, 2.014635069337132169e-1, &r), -1.0750753223600878559e+15, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-23, 3.3470953660313309239e-1, &r), 2.5733184597190491073e+38, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-13, 1.796487688043502395e-2, &r), 6.1526862287828618145e+34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-30, 4.3851505455005663023e-1, &r), -1.6652274019860697168e+50, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-31, 2.9134673992671269075e-1, &r), 7.2783380837435004727e+57, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-28, 7.6696967407852829575e-1, &r), -1.5748860170624112485e+39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6, 1.9829576302527197691e-2, &r), -4.0210481843848071758e+13, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-26, 4.1513019703157674847e-1, &r), -2.806930683617814941e+42, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-19, 1.3033500482689031834e-2, &r), 6.9598794107689745713e+56, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4, 7.2050154387915780891e-1, &r), -1.1846384548732517149e+2, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-36, 9.058436592111083308e-1, &r), -7.994500359474016123e+51, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-37, 4.4893454860671838425e-2, &r), 1.2042846052782773184e+102, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-25, 1.4253284590439372148e-1, &r), 9.4085712788480443733e+51, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-35, 6.8075538970323047806e-1, &r), 2.2691146737122039815e+54, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-9, 6.9978823056579836732e-2, &r), 1.6330796519846810927e+17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-30, 8.3903642499214990225e-1, &r), -5.8816651774415705482e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-43, 6.543891152683782553e-1, &r), 3.2732133353307485906e+71, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1, 2.557673774862201033e-1, &r), 2.648397359834244179, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-21, 2.3961944728579204361e-1, &r), 1.7416186098234671613e+37, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-13, 3.7732868931080794955e-1, &r), 3.9857279826655584502e+17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-33, 3.8478064679256785588e-1, &r), 3.5113798569950397588e+58, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-50, 8.3045728127372512419e-1, &r), -2.3665632218557611716e+81, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-33, 3.4391840270211572065e-1, &r), 1.4268698281593046704e+60, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-23, 4.4699489157302132678e-1, &r), 3.3214969951131331346e+35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-23, 8.6894302936681315656e-1, &r), 7.6600878858980858273e+28, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-24, 2.3997647040322801696e-1, &r), -1.0382177146462655416e+44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4, 9.7688590680055575385e-1, &r), -3.6396008802115138586e+1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-20, 8.9090003293395823104e-1, &r), -4.1352523331280200421e+23, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-37, 9.4057990133775869779e-1, &r), 1.5795116292393394486e+53, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1, 2.6641070579761597867e-1, &r), 2.5520015187867893496, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-7, 9.8878610880180753494e-1, &r), 3.3070534106551277147e+4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-42, 3.1042396387236895292e-1, &r), -1.0201733293438510046e+83, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-18, 6.8722270094498481586e-1, &r), -2.556940038138305942e+22, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-16, 1.6113707818439830316e-2, &r), -1.3203947711040991975e+45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-31, 3.0720392023079679622e-1, &r), 1.4078366532641984096e+57, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-8, 3.4957196590626821859e-1, &r), -1.8497964339362348508e+9, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4, 9.9805150837159144851e-1, &r), -3.35276446088454154e+1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-8, 8.4538260733781281419e-1, &r), -1.6151126896511724021e+6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-21, 7.8935512795174026579e-1, &r), 2.3510763338498465525e+26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-32, 3.4859401756229795902e-1, &r), -4.9775956770188671631e+57, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-28, 9.2530929240293814377e-1, &r), -8.2429457360543127639e+36, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-32, 5.7276907866586953775e-1, &r), -6.2608710158624288778e+50, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-16, 8.6364032267280037696e-1, &r), -2.8833961453891338766e+17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-24, 8.1065458967451038451e-2, &r), -2.1283114054434655701e+55, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-17, 6.946415511078842723e-1, &r), 4.3084587997971578431e+20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-14, 2.7619565270505476723e-1, &r), -2.1634745597658813187e+21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-7, 8.579791601466317093e-2, &r), 8.5741016888820088808e+11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-50, 7.4681490716561041968e-1, &r), -4.7757514561562387813e+83, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-30, 9.6631424224612452556e-1, &r), -8.5159643935229761718e+39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-14, 2.6745819874317492788e-1, &r), -3.3928529652241947717e+21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-22, 3.6947309321414497419e-1, &r), -2.2270901208692386374e+35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-49, 2.3389602803779083655e-2, &r), 1.8412401963717225375e+155, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-48, 7.7482504299905127354e-1, &r), -4.8369236019321535917e+78, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-30, 6.5337950709230049969e-1, &r), -1.0639517934361092802e+45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-29, 5.4117488569210959438e-1, &r), 2.8262145810872807871e+45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-50, 9.4038774092645791075e-1, &r), -4.7322361571978865664e+78, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1, 5.627399919447310892e-1, &r), 1.3310580822914015523, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-35, 7.9925999507829895011e-2, &r), 8.2224704007424584626e+86, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-10, 2.8875439067692705135e-3, &r), -2.9351293887447581255e+33, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-31, 2.7645446745852278572e-1, &r), 3.7015590625912763344e+58, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-12, 8.5374968606378578252e-1, &r), -3.528575811542778544e+11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-11, 2.2997159465452075155e-1, &r), 2.4894373648370412225e+16, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-47, 5.8616043503503357359e-1, &r), 1.9763554381308657733e+82, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-24, 8.4884849730214263521e-1, &r), -7.1046392480541118407e+30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-24, 5.3943176031162412158e-1, &r), -3.7580440656007599181e+35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3, 9.3387179309343112648e-1, &r), 7.0202042170209205589, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-20, 5.5061917642540109891e-1, &r), -6.2122754555889405012e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-26, 2.9315675715515822781e-1, &r), -2.3771210812024680281e+46, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6, 8.9079715253593128884e-1, &r), -5.091626137833991034e+3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-30, 9.1220250697048036241e-2, &r), -4.7597279133940392868e+70, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-20, 6.2008856084878849548e-3, &r), -5.7473876046110789338e+66, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-23, 7.1620177578706903472e-1, &r), 6.5166498927440582853e+30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-29, 5.1124413385957329246e-1, &r), 1.4711351369242792138e+46, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-23, 6.7405321505832900803e-1, &r), 2.627743272609579819e+31, TEST_TOL2, GSL_SUCCESS); /* Ynu for negative nu */ TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.7408502287167772557e+1, 4.3891036254061936271e-2, &r), 4.469714143570654497e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.0369289750688261206e+1, 8.617077861907621132e-1, &r), -5.8595434076664310948e+60, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.6398263821779503158, 5.7108775125890870648e-1, &r), -5.2034221685931678753e+1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.0743837616631487936e+1, 2.2372123946196517647e-1, &r), 1.345588718040376054e+37, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.7297952956642177128e+1, 2.8440280848533973972e-1, &r), 4.1115735370678699359e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.3507072230824139103e+1, 9.7008738913549467403e-1, &r), -2.202372544321863968e+11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.4663106025697138284e+1, 9.6739483983540323655e-1, &r), 1.4235309894056948387e+67, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.7450767905208691173e+1, 5.2288309478685515663e-3, &r), 5.3855142705411361919e+179, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.8736914274754280581e+1, 4.4318942692773250336e-1, &r), 1.1773204343097478161e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.4560791710276042462e+1, 5.6595841783863809163e-1, &r), 3.3572924118396673305e+55, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.8723165418996042381e+1, 2.4003201116391659975e-1, &r), 6.9471556080056038434e+54, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.1780816480084454714e+1, 3.5000033756039229564e-1, &r), -1.0833823624917670056e+57, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-8.3572537806135923827, 8.994859317735841446e-1, &r), -1.1774337302489088463e+6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.9179499652113791027e+1, 7.3466044408596358731e-1, &r), 1.6517722024836217581e+82, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.0204535104461498585e+1, 1.3316368076269799096e-1, &r), -2.2341067840937606376e+93, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.9597169419874779916e+1, 8.3895848736941180651e-1, &r), -6.2662143656762004053e+79, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.2228113163441444643e+1, 7.2360070820350912315e-1, &r), -4.2511898289085272856e+12, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.3252347726870680973e+1, 4.7042383176138740544e-2, &r), 2.2194603264543665848e+121, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.8363275112470146292e+1, 3.5406545166014987925e-1, &r), -3.248353813678515594e+95, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.4031313414732363799e+1, 1.7077658851102128503e-1, &r), -4.3273454620971397041e+47, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.4994220322161396103e+1, 7.6004498361697560048e-2, &r), 4.5976914154279708742e+87, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.5842451866339926986e+1, 7.1655842470093644641e-1, &r), -2.7708334780004236249e+18, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.3303969013414183336e+1, 3.4261981308825774017e-1, &r), 1.2252074327758681488e+84, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.9620214546900609668e+1, 8.9559048893071335969e-2, &r), -2.5960278365111086141e+69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.9267775155252921091e+1, 4.9173394917277714574e-1, &r), 2.4927765540337657002e+68, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.085805422677201981e+1, 7.1844728658692273953e-2, &r), 3.6253005874483288876e+21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.3205222720657600449e+1, 2.0938011160695718605e-1, &r), 1.7097593469426311991e+93, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.1761832688338363731e-1, 4.0692821730479031008e-1, &r), -3.9929527887838440231e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.4176152886105712673e+1, 7.3083748089885469319e-1, &r), -3.8375532995220739134e+51, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.4363999308889822481e+1, 2.2964635433363436307e-1, &r), -6.7651597483976020212e+22, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.5945782535187393546e+1, 5.5004988492253222851e-1, &r), -3.0929200048995927397e+20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.6539439893219625339e+1, 5.4022213494661757887e-1, &r), 4.3099923396955639095e+39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.9104819423206076833e+1, 8.7581079115207012305e-1, &r), 2.4523357879118971691e+58, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.1344422530419629852e+1, 1.8412292138063948156e-1, &r), 6.9306682864864401354e+17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.2479004807998664153e+1, 7.628052499161305046e-1, &r), -2.5492681017463054894e+66, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.7234292208462683278e+1, 5.6929354834881763134e-1, &r), 1.4969074140226347429e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.9852923491811760298e+1, 2.1764339448558498796e-2, &r), -6.237969203121440244e+88, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.9470737712526065987e+1, 9.1397839227827761003e-1, &r), 4.5960647034986138864e+38, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.4879459756439547254e+1, 8.7694253508024822462e-1, &r), 1.0188843810269963844e+32, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-8.6562240771489400173e-1, 6.4882619355798588927e-1, &r), 1.1287689391130420057, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.4096305256724256786e+1, 1.1837901256079790395e-1, &r), -4.9304578916106509819e+26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.3739240782592000796e+1, 1.1830951764837136725e-1, &r), -5.1263258788046229045e+25, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-7.7683272384817803185e-1, 2.0897180603218726575e-1, &r), 1.881590189544752977, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.9007825894244022613e+1, 8.0804305816981973945e-1, &r), 7.9534669124448258162e+79, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.224872379992519031, 9.4716012050013901355e-1, &r), 5.2709059549031973037e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-5.0807600398060325807e+1, 6.1902119795226148946e-1, &r), 2.8318147090250448397e+89, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.2130610423140110162e+1, 7.2184881647444607846e-1, &r), -7.0593986791573883029e+67, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.1186300874143057513e+1, 1.3944550368322800884e-1, &r), 1.8718282789345414439e+95, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.1777582295815773824e+1, 7.6178874271077561762e-1, &r), -8.5399447567722731535e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.2185912810368133222e+1, 3.959510541558671016e-1, &r), -1.8100903248905368685e+56, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.2976006083946226988e+1, 4.5739390828369379657e-1, &r), 1.4034454523109119588e+78, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.0412232215064606945e+1, 6.7510758855896918145e-1, &r), -6.8761190595978173779e+44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.8388188389747281955e+1, 8.9233979909724013718e-1, &r), -3.3498674090203423756e+20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.4298840569257253701e+1, 6.8042862360863559591e-1, &r), -3.0013837000776612869e+33, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.8834735272673504063e+1, 4.2324469410479691518e-1, &r), 1.2310766881467564871e+70, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.6091840934431606344e+1, 1.7508918790902548661e-1, &r), -2.946550933505149671e+104, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.9754264394942756728, 1.558717798933954111e-2, &r), -4.5906289772187980725e+3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.7168594342366560374e+1, 6.976373865080374073e-1, &r), 1.8851114888349680045e+58, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.5379944292029245754e+1, 5.3150471205968938472e-2, &r), 4.1473845726043547937e+125, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.153181439556533474e+1, 1.8204366094125528818e-1, &r), -4.1102104914739582156e+17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.9939680334734766385e+1, 8.132277926604580844e-1, &r), -4.9623796120191838477e+81, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.5986707652967270442e+1, 5.5665988728905782182e-1, &r), -3.058579118813851873e+59, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6.7046620273111013832, 1.059530133767196237e-1, &r), 2.8547617693483259231e+10, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.154578607200052944e+1, 4.5282605452993561522e-1, &r), -4.6204765000245865931e+31, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.3955292370868357326e+1, 5.3774303067450442349e-1, &r), -3.285152670384139907e+35, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.2209824848466094111e+1, 5.9504757613868441576e-1, &r), -3.8856592501211432238e+50, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.0825185544715207495e+1, 7.5398610386439322567e-1, &r), 2.3035172984979776888e+64, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.1910588368134692781e+1, 5.1283495159288225414e-1, &r), -1.3438429765742294157e+52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6.7113819006700078322, 4.0393307486388760775e-1, &r), 3.8345193040174093796e+6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.8693610985720627242e+1, 3.4777341593350738095e-1, &r), 1.2557150749869300709e+50, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.3640245743314574591e+1, 9.6025287507519664839e-1, &r), -3.8943763839931542689e+28, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.8083409800395899615e+1, 1.4391402197265332926e-1, &r), -9.9126133627220300984e+113, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.8105478052324389543e+1, 4.891514010318381566e-1, &r), -1.2271238830087142465e+66, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.5311996069559305006e+1, 9.5766172213158543809e-1, &r), 3.7577671642248517421e+31, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.0646798215967974621e+1, 9.3310976056897272996e-1, &r), 1.5913395046591416208e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.9802221662384415773e+1, 8.0558698100484531078e-1, &r), -1.3410097300803423969e+61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.6307175589532141033e+1, 8.5581965580057553716e-1, &r), -8.2913043528862589862e+72, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.0008133602203088381e+1, 8.8260963451522902618e-1, &r), -4.3184875964228242059e+8, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.2307910802466458785e+1, 6.782808128445430142e-1, &r), -1.4119756731193528077e+69, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.0130438814666196845e+1, 2.1277791687648788154e-1, &r), -1.02690311217639001e+15, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.9533803019889111726e+1, 3.9334897500975715385e-1, &r), -6.4704382293897894852e+28, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.3895956090712434265e+1, 8.0661260505451797979e-1, &r), -4.3815146159956971318e+14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.4635165127833994625e+1, 3.7945739040607276532e-1, &r), 1.5929485514781295968e+20, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.8560967136543055351e+1, 7.9600892022399284277e-1, &r), 1.1465774145795382248e+39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6.2108119261932190115, 8.7806601388332832487e-1, &r), -7.4701969028629161594e+3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6.9950977953230716109, 5.8978625225697869088e-1, &r), 1.1808677382965817331e+6, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.2481246429363894157e+1, 7.2704916561624886813e-1, &r), -7.5667536238826222942e+11, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-5.020982518214251176e+1, 7.5109544046044664159e-1, &r), -7.9040859853121739692e+83, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-8.9473034048334154025, 6.4213370686611774774e-2, &r), 2.6029884691597775763e+17, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.834075672586642874e+1, 6.4258947909888861139e-1, &r), -5.8405580195454874797e+61, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.4411381704857813062e+1, 1.2743783697917866926e-1, &r), -3.1773798568513309515e+105, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6.1687391291035845538, 7.8786722297686215495e-1, &r), -1.4219092995559599082e+4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.0704293950958482287e+1, 3.8531626603275482749e-1, &r), 1.5743246247238302576e+13, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.0571445654620545043e+1, 3.4876986634505808892e-1, &r), 7.0385234557024272162e+76, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.3563863522003561189, 9.7999452783586835833e-1, &r), -3.1893996030425450694e+1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.8492269674910402783e+1, 1.7152753186318347442e-1, &r), -6.0249928142043118768e+32, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.5363228484567149913e+1, 3.0542644930515794217e-1, &r), 1.3211507552477009856e+44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.3771144161000489935e+1, 7.3346736008344405886e-1, &r), -8.3124988094143057824e+14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.3761246233591030521e+1, 5.4968519162734822572e-1, &r), -6.0578774841300955332e+34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.2634961325802757898e+1, 6.6471162507224558099e-1, &r), 3.2082973398317013106e+30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.6563404270777516422e+1, 7.5273096421024420905e-1, &r), 3.7592589106971418602e+75, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.0848764148512049678e+1, 9.2286052929496267966e-1, &r), 3.2439553455961291223e+9, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.5455854142576014389e+1, 7.8971992208889605774e-1, &r), 1.3378630820768277448e+52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.2013968530863113871e+1, 1.9744029176545173315e-1, &r), -1.584787479000820067e+19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-5.6750075448691398076, 8.0444727938729491316e-1, &r), -2.10533382223663811e+3, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.8429830608986305295e+1, 8.2140563165026789468e-1, &r), -1.1405415108194473062e+21, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.346426407446347328e+1, 8.5111501099434108204e-1, &r), 8.7606083372225198285e+28, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.9593848458448579212e+1, 1.2641237816367966816e-1, &r), -6.4135079973931874203e+64, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.7086231381348987822e+1, 3.9893860083544831831e-1, &r), 7.515835122388342095e+24, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.8484417257406457732, 6.0748406712157845873e-1, &r), -2.7380610022426281822, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.1822890333552359573e+1, 5.0020129878524173631e-1, &r), -1.7231227888225767619e+52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-6.2862753931112845805, 7.9353453932163968388e-1, &r), -1.342401423092805412e+4, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.5508352825172743548, 7.3200379508076835206e-1, &r), -4.0497851981930665643e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-7.6325669923999446014, 6.3959118408264715884e-2, &r), -8.0591625416199259092e+13, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.7217355888852626548e+1, 8.2439297912634420605e-1, &r), 4.2640264465349061973e+55, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.9216632463077931365e+1, 2.1243165065073566651e-2, &r), 7.2753341407348563956e+121, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.0310494244455808579e+1, 5.6409661087945220564e-1, &r), -8.0236717760932647636e+27, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.2561355227860967802e+1, 6.1429304168687688441e-1, &r), 1.095939957156354534e+71, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.348280958534689123e+1, 1.3878791555680588964e-1, &r), 1.4127166630922246712e+47, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.266908051943509346, 9.1043177038683039605e-1, &r), 7.9342040586370876107, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.6453677594081999426e+1, 7.3766130024218803361e-1, &r), -2.8496103761067379068e+18, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.0292370302033138277e+1, 2.7545919896373212095e-1, &r), -9.9081192322574702806e+13, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.788826873303230097e+1, 2.2855276522975392381e-1, &r), -4.2068889321668479948e+53, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.1401875376696767087e+1, 6.6522142928175599046e-2, &r), 5.4702914219176701268e+108, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.9306765177660380865e+1, 2.0291343278160599375e-1, &r), 4.3752403877947450222e+34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.9778989699515361126e+1, 5.0069816606055756877e-2, &r), -5.0144871285761887467e+77, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.3484350943085112332e+1, 2.5580340114657331489e-2, &r), 8.660979419407748338e+32, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.8885950309653823971e+1, 2.705230773944354062e-1, &r), 7.0729128795400209404e+102, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.6140505254948262834e+1, 5.635769797194365065e-1, &r), -1.691181704671511378e+39, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.36353791993838395e+1, 7.8601342847547894355e-1, &r), -4.184570564713370597e+30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.8043892058273381078e+1, 9.6661631483018731188e-1, &r), -5.2799069238255343804e+54, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.0627792568626186656e+1, 2.7801894968851888201e-1, &r), 4.6951098613000862734e+34, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.7821819326414013127e+1, 7.0072053744106375522e-1, &r), -3.2969189837617817178e+59, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.1895350862490616295e+1, 6.3819566879323744549e-1, &r), -7.4877627933750167273e+12, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.1564822793166119652e+1, 8.7089052441788146841e-1, &r), -4.362095115786654673e+62, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-5.6988133455245986782, 1.0513161628614675752e-1, &r), -2.6315584241050780179e+8, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-5.04236829179067909, 2.1606414592833118122e-2, &r), 6.6460848251254935943e+10, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-8.5815569416794001464e-1, 3.2800854133020344342e-1, &r), 1.7278337309129555492, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-7.4540158508402344121, 3.3591301584669540366e-1, &r), 4.6958147873473343296e+7, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.1342269410012557907e+1, 7.2248859912133702972e-1, &r), 8.4210802265866850829e+65, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-4.0890888214378787004e+1, 4.6015468690527406659e-2, &r), 1.5760625185685568109e+114, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.4949019201278440062e+1, 5.5379096162817544569e-1, &r), 2.4017690399425079403e+57, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.5581474535040863099, 8.6545078146345742122e-1, &r), -4.2518863856194071801e-1, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-1.6450819423469368818e+1, 4.0968007844676920681e-1, &r), -4.7316334255824816328e+22, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-2.4534051152698170766e+1, 9.2462004307970597256e-1, &r), 8.0009048223739294629e+29, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-9.5846016059057764355, 1.4980322293854772757e-1, &r), -7.3726783694247075753e+14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Ynu_e, (-3.1840530425923939329e+1, 9.3847997261021697482e-1, &r), -3.8745468671462878671e+43, TEST_TOL2, GSL_SUCCESS); /* Inu */ TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (0.0001,10.0, &r), 0.12783333709581669672, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, ( 1.0, 0.001, &r), 0.0004995003123542213370, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, ( 1.0, 1.0, &r), 0.20791041534970844887, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (30.0, 1.0, &r), 1.3021094983785914437e-42, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (30.0, 100.0, &r), 0.0004486987756920986146, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (10.0, 1.0, &r), 1.0127529864692066036e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (10.0, 100.0, &r), 0.024176682718258828365, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_scaled_e, (10.2, 100.0, &r), 0.023691628843913810043, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (0.0001,10.0, &r), 2815.7166269770030352, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, ( 1.0, 0.001, &r), 0.0005000000625000026042, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, ( 1.0, 1.0, &r), 0.5651591039924850272, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (30.0, 1.0, &r), 3.539500588106447747e-42, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (30.0, 100.0, &r), 1.2061548704498434006e+40, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (10.0, 1.0, &r), 2.7529480398368736252e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (10.0, 100.0, &r), 6.498975524720147799e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Inu_e, (10.2, 100.0, &r), 6.368587361287030443e+41, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (0.0001,10.0, &r), 0.3916319346235421817, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, ( 1.0, 0.001, &r), 1000.9967345590684524, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, ( 1.0, 1.0, &r), 1.6361534862632582465, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (30.0, 1.0, &r), 1.2792629867539753925e+40, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (30.0, 100.0, &r), 10.673443449954850040, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 1.0, &r), 4.912296520990198599e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 100.0, &r), 0.20578687173955779807, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 1000.0, &r), 0.04165905142800565788, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.0, 1.0e+8, &r), 0.00012533147624060789938, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_scaled_e, (10.2, 100.0, &r), 0.20995808355244385075, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (0.0001,0.001, &r), 7.023689431812884141, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (0.0001,10.0, &r), 0.000017780062324654874306, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, ( 1.0, 0.001, &r), 999.9962381560855743, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, ( 1.0, 1.0, &r), 0.6019072301972345747, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.0, 0.001, &r), 1.8579455483904008064e+38, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.0, 1.0, &r), 1.8071328990102945469e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.0, 100.0, &r), 7.655427977388100611e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (10.2, 100.0, &r), 7.810600225948217841e-45, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (30.0, 1.0, &r), 4.706145526783626883e+39, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_Knu_e, (30.0, 100.0, &r), 3.970602055959398739e-43, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (0.0001,1.0e-100, &r), 5.439794449319847, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (0.0001,0.0001, &r), 2.232835507214331, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (0.0001,10.0, &r), -10.93743282256098, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 1.0e-100, &r), 230.2585092994045, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 1.0e-10, &r), 23.025850929940456840, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 0.001, &r), 6.907751517131146, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, ( 1.0, 1.0, &r), -0.5076519482107523309, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (30.0, 1.0e-100, &r), 6999.113586185543475, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (30.0, 1.0, &r), 91.34968784026325464, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (30.0, 100.0, &r), -97.63224126416760932, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (100.0, 1.0e-100, &r), 23453.606706185466825, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (100.0, 1.0, &r), 427.7532510250188083, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (100.0, 100.0, &r), -55.53422771502921431, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (1000.0, 1.0e-100, &r), 236856.183755993135, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (10000.0, 1.0e-100, &r), 2.39161558914890695e+06, TEST_TOL0, GSL_SUCCESS); /* [bug #31528] gsl_sf_bessel_lnKnu overflows for large nu */ TEST_SF(s, gsl_sf_bessel_lnKnu_e, (180.0, 2.2, &r), 735.1994170369583930752590258, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_lnKnu_e, (3500.5, 1500.0, &r), 1731.220077116482710070986699, TEST_TOL1, GSL_SUCCESS); sa = 0; gsl_sf_bessel_Jn_array(3, 38, 1.0, J); sa += ( test_sf_frac_diff(J[0], 0.0195633539826684059190 ) > TEST_TOL1); sa += ( test_sf_frac_diff(J[1], 0.0024766389641099550438 ) > TEST_TOL1); sa += ( test_sf_frac_diff(J[10], 1.9256167644801728904e-14 ) > TEST_TOL1); sa += ( test_sf_frac_diff(J[35], 6.911232970971626272e-57 ) > TEST_TOL1); gsl_test(sa, " gsl_sf_bessel_Jn_array"); s += sa; sa = 0; gsl_sf_bessel_Yn_array(3, 38, 1.0, Y); sa += ( test_sf_frac_diff(Y[0], -5.821517605964728848 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[1], -33.27842302897211870 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[10], -1.2753618701519837595e+12 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[35], -1.2124435663593357154e+54 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_Yn_array"); s += sa; sa = 0; gsl_sf_bessel_In_scaled_array(3, 38, 1.0, I); sa += ( test_sf_frac_diff(I[0], 0.0081553077728142938170 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(I[1], 0.0010069302573377758637 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(I[10], 7.341518665628926244e-15 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(I[35], 2.5753065298357542893e-57 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_In_scaled_array"); s += sa; sa = 0; gsl_sf_bessel_In_array(3, 38, 1.0, Y); sa += ( test_sf_frac_diff(Y[0], 0.0221684249243319024760 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[1], 0.0027371202210468663251 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[10], 1.9956316782072007564e-14 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[35], 7.000408942764452901e-57 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_In_array"); s += sa; sa = 0; gsl_sf_bessel_Kn_array(3, 38, 1.0, K); sa += ( test_sf_frac_diff(K[0], 7.101262824737944506 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[1], 44.23241584706284452 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[10], 1.9215763927929940846e+12 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[35], 1.8789385023806051223e+54 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_Kn_array"); s += sa; sa = 0; gsl_sf_bessel_Kn_scaled_array(3, 38, 1.0, K); sa += ( test_sf_frac_diff(K[0], 19.303233695596904277 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[1], 120.23617222591483717 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[10], 5.223386190525076473e+12 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[35], 5.107484387813251411e+54 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_Kn_scaled_array"); s += sa; sa = 0; gsl_sf_bessel_jl_array(50, 1.0, J); sa += ( test_sf_frac_diff(J[0], 0.84147098480789650670 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(J[1], 0.30116867893975678925 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(J[10], 7.116552640047313024e-11 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(J[50], 3.615274717489787311e-81 ) > TEST_TOL2 ); gsl_test(sa, " gsl_sf_bessel_jl_array"); s += sa; sa = 0; gsl_sf_bessel_jl_steed_array(99, 1.0, J); sa += ( test_sf_frac_diff(J[0], 0.84147098480789650670 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[1], 0.30116867893975678925 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[10], 7.116552640047313024e-11 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[50], 3.615274717489787311e-81 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(J[80], 1.136352423414503264e-144 ) > TEST_TOL1 ); gsl_test(sa, " gsl_sf_bessel_jl_steed_array"); s += sa; sa = 0; gsl_sf_bessel_yl_array(50, 1.0, Y); sa += ( test_sf_frac_diff(Y[0], -0.5403023058681397174 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[1], -1.3817732906760362241 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[10], -6.722150082562084436e+08 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(Y[50], -2.7391922846297571576e+78 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_yl_array"); s += sa; { double Y0[1]; sa = 0; gsl_sf_bessel_yl_array(0, 1.0, Y0); sa += ( test_sf_frac_diff(Y0[0], -0.5403023058681397174 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_yl_array (lmax=0)"); s += sa; } sa = 0; gsl_sf_bessel_il_scaled_array(50, 1.0, I); sa += ( test_sf_frac_diff(I[0], 0.43233235838169365410 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[1], 0.13533528323661269189 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[10], 2.7343719371837065460e-11 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[50], 1.3429606061892023653e-81 ) > TEST_TOL2 ); gsl_test(sa, " gsl_sf_bessel_il_scaled_array"); s += sa; sa = 0; gsl_sf_bessel_il_scaled_array(50, 0.0, I); sa += ( test_sf_frac_diff(I[0], 1.0 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[1], 0.0 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[10], 0.0 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(I[50], 0.0 ) > TEST_TOL2 ); gsl_test(sa, " gsl_sf_bessel_il_scaled_array (L=0)"); s += sa; sa = 0; gsl_sf_bessel_kl_scaled_array(50, 1.0, K); sa += ( test_sf_frac_diff(K[0], 1.5707963267948966192 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[1], 3.1415926535897932385 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[10], 2.7231075458948147010e+09 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(K[50], 1.1578440432804522544e+79 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_kl_scaled_array"); s += sa; { double K0[1]; sa = 0; gsl_sf_bessel_kl_scaled_array(0, 1.0, K0); sa += ( test_sf_frac_diff(K[0], 1.5707963267948966192 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_bessel_kl_scaled_array (lmax=0)"); s += sa; } sa = 0; sa += ( gsl_sf_bessel_zero_J0_e(0, &r) != GSL_EINVAL ); sa += ( r.val != 0.0 ); s += sa; TEST_SF(s, gsl_sf_bessel_zero_J0_e, ( 1, &r), 2.404825557695771, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, ( 2, &r), 5.520078110286304, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, (20, &r), 62.048469190227081, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, (25, &r), 77.756025630388058, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J0_e, (100, &r), 313.37426607752784, TEST_TOL1, GSL_SUCCESS); sa = 0; sa += ( gsl_sf_bessel_zero_J1_e(0, &r) != GSL_SUCCESS ); sa += ( r.val != 0.0 ); s += sa; TEST_SF(s, gsl_sf_bessel_zero_J1_e, ( 1, &r), 3.831705970207512, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, ( 2, &r), 7.015586669815619, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, (20, &r), 63.61135669848124, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, (25, &r), 79.32048717547630, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_J1_e, (100, &r), 314.9434728377672, TEST_TOL2, GSL_SUCCESS); sa = 0; sa += ( gsl_sf_bessel_zero_Jnu_e(0.0, 0, &r) != GSL_EINVAL ); sa += ( r.val != 0.0 ); s += sa; TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 1, &r), 2.404825557695771, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 2, &r), 5.520078110286304, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 20, &r), 62.048469190227081, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 25, &r), 77.756025630388058, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (0.0, 100, &r), 313.37426607752784, TEST_TOL1, GSL_SUCCESS); sa = 0; sa += ( gsl_sf_bessel_zero_Jnu_e(1.0, 0, &r) != GSL_SUCCESS ); sa += (r.val != 0.0); s += sa; TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 1, &r), 4.4934094579090641, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 1, &r), 8.7714838159599540, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 2, &r), 7.7252518369377072, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 2, &r), 12.338604197466944, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 3, &r), 10.904121659428900, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 3, &r), 15.700174079711671, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 4, &r), 14.066193912831473, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 4, &r), 18.980133875179921, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 5, &r), 17.220755271930768, TEST_TOL1, GSL_SUCCESS); /* Something wrong with the tolerances on these */ TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 5, &r), 22.217799896561268, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 8.0, 5, &r), 26.266814641176644, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (20.0, 5, &r), 41.413065513892636, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 6, &r), 20.371302959287563, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 6, &r), 25.430341154222704, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 8.0, 6, &r), 29.545659670998550, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 7, &r), 23.519452498689007, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 7, &r), 28.626618307291138, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 8.0, 7, &r), 32.795800037341462, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 8, &r), 26.666054258812674, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 8, &r), 31.811716724047763, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (10.0, 8, &r), 38.761807017881651, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 9, &r), 29.811598790892959, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 9, &r), 34.988781294559295, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (10.0, 9, &r), 42.004190236671805, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 1.5, 10, &r), 32.956389039822477, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 10, &r), 38.159868561967132, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 10, &r), 52.017241278881633, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 11, &r), 41.326383254047406, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 11, &r), 55.289204146560061, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 12, &r), 44.4893191232197314, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 12, &r), 58.5458289043850856, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 13, &r), 47.6493998066970948, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 13, &r), 61.7897598959450550, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 14, &r), 50.8071652030063595, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 14, &r), 65.0230502510422545, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 15, &r), 53.9630265583781707, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 15, &r), 68.2473219964207837, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 16, &r), 57.1173027815042647, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 16, &r), 71.4638758850226630, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 17, &r), 60.2702450729428077, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 17, &r), 74.6737687121404241, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 18, &r), 63.4220540458757799, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 18, &r), 77.8778689734863729, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 19, &r), 66.5728918871182703, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 19, &r), 81.0768977206328326, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 20, &r), 69.722891161716742, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (15.0, 20, &r), 84.271459069716442, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 23.0, 11, &r), 65.843393469524653, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 30.0, 11, &r), 74.797306585175426, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 32.0, 15, &r), 90.913637691861741, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 50.0, 15, &r), 113.69747988073942, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 5.0, 22, &r), 76.020793430591605, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 10.0, 22, &r), 83.439189796105756, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, ( 12.0, 22, &r), 86.345496520534055, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (100.0, 22, &r), 199.82150220122519, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_bessel_zero_Jnu_e, (500.0, 22, &r), 649.34132440891735, TEST_TOL2, GSL_SUCCESS); sa = 0; for(i=0; i<100; i++) { J[i] = i/10.0; } gsl_sf_bessel_sequence_Jnu_e(2.0, GSL_MODE_DEFAULT, 100, J); sa += ( test_sf_frac_diff(J[1], 0.0012489586587999188454 ) > TEST_TOL1 ); sa += ( test_sf_frac_diff(J[20], 0.3528340286156377192 ) > TEST_TOL4 ); sa += ( test_sf_frac_diff(J[50], 0.0465651162777522155 ) > TEST_TOL4 ); gsl_test(sa, " gsl_sf_sequence_Jnu_e(2)"); s += sa; sa = 0; for(i=0; i<100; i++) { J[i] = i; } gsl_sf_bessel_sequence_Jnu_e(12.0, GSL_MODE_DEFAULT, 100, J); sa += ( test_sf_frac_diff(J[1], 4.999718179448405289e-13 ) > TEST_TOL1 ); sa += ( test_sf_frac_diff(J[5], 7.627813166084551355e-05 ) > TEST_TOL1 ); sa += ( test_sf_frac_diff(J[7], 2.655620035894568062e-03 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[10], 6.337025497015601509e-02 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[15], 0.23666584405476805591 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[30], 0.14825335109966010021 ) > TEST_TOL3 ); sa += ( test_sf_frac_diff(J[70], 0.04109913716555364262 ) > TEST_TOL4 ); sa += ( test_sf_frac_diff(J[99], -0.0015052760501176728 ) > TEST_TOL5 ); gsl_test(sa, " gsl_sf_sequence_Jnu_e(12)"); s += sa; sa = 0; for(i=0; i<100; i++) { J[i] = i * 20; } gsl_sf_bessel_sequence_Jnu_e(1000.0, GSL_MODE_DEFAULT, 100, J); sa += ( test_sf_frac_diff(J[50], 0.04473067294796404088 ) > TEST_TOL5 ); sa += ( test_sf_frac_diff(J[99], 0.01400619760349853902 ) > TEST_TOL6 ); gsl_test(sa, " gsl_sf_sequence_Jnu_e(1000)"); s += sa; return s; }
{ "alphanum_fraction": 0.7530211679, "avg_line_length": 95.151540383, "ext": "c", "hexsha": "6810da410fa22044acc08eaba4a84154bf4f081c", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/specfunc/test_bessel.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/specfunc/test_bessel.c", "max_line_length": 146, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/test_bessel.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": 49934, "size": 114277 }
#ifndef _MU_NSQ_ #define _MU_NSQ_ #include <vector> #include <iostream> #include <nuSQuIDS/nuSQuIDS.h> #include <gsl/gsl_deriv.h> #include "exCross.h" namespace musquids { using nusquids::nuSQUIDS; using nusquids::marray; /// \brief This class implements muon energy loss into nuSQuIDS. class muSQUIDS: public nuSQUIDS { private: std::vector<double> inv_lambda; marray<double,2> dScalardE; /// The following variables are to evaluate the derivative of the scalar flux std::shared_ptr<gsl_spline> scalar_spline; std::shared_ptr<gsl_interp_accel> scalar_spline_acc; std::vector<double> tmp_scalar_state; protected: /// \brief Here we will calculate the muon flux derivative void AddToPreDerive(double x){ for(size_t si=0; si<dScalardE.extent(0); si++){ for(size_t ei; ei<dScalardE.extent(1); ei++){ tmp_scalar_state[ei] = state[ei].scalar[si]; } gsl_spline_init(scalar_spline.get(),E_range.get_data(),tmp_scalar_state.data(),ne); gsl_interp_accel_reset(scalar_spline_acc.get()); for(size_t ei; ei<dScalardE.extent(1); ei++){ dScalardE[si][ei] = gsl_spline_eval_deriv(scalar_spline.get(),E_range[ei],scalar_spline_acc.get()); } } } protected: double EnergyLoss(double Emuon) const { // From T. Gaisser Cosmic Ray book // From http://pdg.lbl.gov/2015/AtomicNuclearProperties/ // Good from Emuon>10Gev double RadDensH=4.405e5; // gr/cm^2 // current_density in gr/cm^3 // coeffcients in MeV/cm^2 return (((-1.9-0.08*log(Emuon/params.muon_mass))-(Emuon/params.MeV)/RadDensH)*current_density)*(params.MeV/params.cm); } double Fmue(double Emuon, double Enu) const { // Fits to muon decay spectrum including spin double z = Enu/Emuon; return (1.79779466e-02*pow(z,4)+1.20239959e+01*pow(z,3.)-2.38837016e+01*z*z+1.17861335e+01*z+5.85725324e-02)/Emuon; } double Fmumu(double Emuon, double Enu) const { // Fits to muon decay spectrum including spin double z = Enu/Emuon; return (-0.24794224*pow(z,4.)+4.51300659*pow(z,3.)-6.2556965*z*z-0.03647084*z+2.02480429)/Emuon; } double lambda(double Emuon) const { return Emuon*params.muon_lifetime/params.muon_mass; } protected: // These scalar functions will manage the muon decay and energy loss double GammaScalar(unsigned int ei,unsigned int index_scalar) const { double muon_decay_term=inv_lambda[ei]; return nuSQUIDS::GammaScalar(ei,index_scalar) + muon_decay_term; } double InteractionsScalar(unsigned int ei,unsigned int index_scalar) const { double muon_energy_loss_terms=EnergyLoss(E_range[ei])*dScalardE[index_scalar][ei]; return nuSQUIDS::InteractionsScalar(ei,index_scalar) + muon_energy_loss_terms; } // This rho function will add the neutrinos from muon decay squids::SU_vector InteractionsRho(unsigned int ei,unsigned int index_rho) const { squids::SU_vector from_muon_decay_terms(nsun); double muon_decay_to_muon_integral = 0.; double muon_decay_to_e_integral = 0.; unsigned int other_index_rho = (index_rho == 0) ? 1 : 0; for(unsigned int em = ei+1; em < ne; em++){ // loop in the tau neutrino energies muon_decay_to_muon_integral += state[em].scalar[index_rho]*Fmumu(E_range[em],E_range[ei])*inv_lambda[em]*delE[em-1]; muon_decay_to_e_integral += state[em].scalar[other_index_rho]*Fmue(E_range[em],E_range[ei])*inv_lambda[em]*delE[em-1]; } from_muon_decay_terms += evol_b1_proj[index_rho][1][ei]*muon_decay_to_muon_integral; from_muon_decay_terms += evol_b1_proj[index_rho][0][ei]*muon_decay_to_e_integral; return nuSQUIDS::InteractionsRho(ei,index_rho) + from_muon_decay_terms; } public: muSQUIDS(){} muSQUIDS(marray<double,1> E_range, int numneu=3, nusquids::NeutrinoType NT=nusquids::both,bool iinteraction=true): nuSQUIDS(E_range,numneu,NT,iinteraction,std::make_shared<nusquids::NeutrinoDISCrossSectionsFromTablesExtended>()), scalar_spline(gsl_spline_alloc(gsl_interp_cspline,E_range.size()),[](gsl_spline* t){ gsl_spline_free(t);}), scalar_spline_acc(gsl_interp_accel_alloc(),[](gsl_interp_accel* t){ gsl_interp_accel_free(t);}) { // resetting squids nodes to the right scalar size ini(ne,numneu,nrhos,2,Get_t()); // initializing the muon decay lenght inv_lambda.resize(ne); for(unsigned int ei=0; ei<ne; ei++) inv_lambda[ei] = 1./lambda(E_range[ei]); // initializing the scalar derivative matrix dScalardE.resize(std::vector<size_t>{nscalars,ne}); std::fill(dScalardE.begin(),dScalardE.end(),0); // initializing the scalar temporary state tmp_scalar_state.resize(ne); std::fill(tmp_scalar_state.begin(),tmp_scalar_state.end(),0); } void Set_initial_state(const marray<double,2>& muon_flux,const marray<double,3>& neutrino_state,nusquids::Basis basis) { nuSQUIDS::Set_initial_state(neutrino_state,basis); for(unsigned int ie = 0; ie < ne; ie++){ for(unsigned int ir = 0; ir < nscalars; ir++){ state[ie].scalar[ir] = muon_flux[ie][ir]; } } } double GetMuonFlux(unsigned int ie, unsigned int irho){ return state[ie].scalar[irho]; } }; } // close musquids namespace #endif
{ "alphanum_fraction": 0.6911519199, "avg_line_length": 43.4758064516, "ext": "h", "hexsha": "5dc2a6de9462507d4c273b1a535198508fab685e", "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": "9b154d29618c275ee6ea78810ab1f6576cfd8fe6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "arguelles/muSQuIDS", "max_forks_repo_path": "inc/muSQuIDS.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9b154d29618c275ee6ea78810ab1f6576cfd8fe6", "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": "arguelles/muSQuIDS", "max_issues_repo_path": "inc/muSQuIDS.h", "max_line_length": 126, "max_stars_count": null, "max_stars_repo_head_hexsha": "9b154d29618c275ee6ea78810ab1f6576cfd8fe6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "arguelles/muSQuIDS", "max_stars_repo_path": "inc/muSQuIDS.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1582, "size": 5391 }
/* Program to trace back a refined halo through a set of snapshots (contains code overhead, since it is based on a copy of trhalomult.c) icc -lm -lgsl -lgslcblas -o ../bin/altix/trace trace.c lmfit-2.2-icc/lmmin.o lmfit-2.2-icc/lm_eval.o libgad-icc.o KdTree-icc.o -I/usr/local/gsl-1.6 icc -lm -lgsl -lgslcblas -o ../bin/altix/trace trace.c -lgad-altix-icc KdTree-icc.o -I/usr/local/gsl-1.6 icc -lm -lgsl -lgslcblas -o ../bin/altix/trace_nopot trace.c -lgad-altix-icc-nopot KdTree-icc.o -I/usr/local/gsl-1.6 -DNOPOT adhara: icc -g -O2 -lm -lgsl -lgslcblas -o ../bin/other64/trace trace.c -lgad-adhara-icc adhara/KdTree-icc.o stan: gcc -lm -lgsl -lgslcblas -o ~/bin/trace trace.c -lgad-stan stan/KdTree.o -L/home/albireo/oser/libraries/stan/GSL/lib -L./lib/ gcc -lm -lgsl -lgslcblas -o ~/bin/trace-winds trace.c -lgad-stan-winds stan/KdTree-winds.o -L/home/albireo/oser/libraries/stan/GSL/lib -L./lib/ -DWINDS gcc -fopenmp -lm -lgsl -lgslcblas -o ~/bin/trace trace.c -lgad-stan stan/KdTree.o -L/home/albireo/oser/libraries/stan/GSL/lib -L./lib/ stan/ompfuncs.o */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <string.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_linalg.h> //#include "./lmfit-2.2/lmmin.h" //#include "./lmfit-2.2/lm_eval.h" #include "./lmmin.h" #include "./lm_eval.h" #include "libgad.h" #include "KdTree.h" #define PI 3.14159265358979323846 #define GAP2BORDER 10000 //min distance to boarders to ignore periodic boundaries #define INCLUDE 0 //(friends + INCLUDE*kpc/h) are used to determine CM #define NBOX 4 #define TRACE_FACTOR 2.0 //TRACE_FACTOR times virial radius will be traced back to IC #define h0 0.72 #define DIM 512 #define ENVDENSRAD (4000 * h0) #define INERTIA_START_RAD 0.4 #define INERTIA_USE_PART_TYPE 16 #define CM_USE_PART_TYPE 16 #define VA_USE_PART_TYPE 16 #define MIN_PARTICLE_COUNT 30 #define MAX_STAR_DIST (30*h0) #define GRIDSIZE 1000 #define WORKSPACE 0.25 //workspace for WORKSPACE*numpart particles is allocated, if glibc or segmentation fault occur, try to compile with a larger fraction #define LARGE_WS 8 #define ADDSTAR_BUF 1000000 #define ADDGAS_BUF 1000000 #define kNN 50 #define MIN(a, b) ((a)<(b)?(a):(b)) #define MAX(a, b) ((a)>(b)?(a):(b)) #define ABS(a) ((a) >= 0 ? (a) : -(a)) #define CMP(a,b) ((a)>(b)?(1):(-1)) #define PB(a,b) ((a)>(b)?((a)-(b)):(a)) #define MOVE(a,b) PB((a)+((b)/2),(b)) #define MOVEB(a) MOVE((a),boxsz) #define MV(a,b) ((a)+(b)/2)%(b) #define SOFTENING 0.40 #define G 6.6742e-11 #define Msun 1.989e30 #define kpc 3.08567758128e19 #define MAXNHALOES 30000 #define MAXINT 10000000 #define NUMTIMESTEPS 94 #define NUMTRACE 50 #define ACC_FRAC 0.1 #define DENS_THRESH 1e-3 //Threshold for maxtemp of gas particles to be set double cdens; struct particle {int ind;float dist;}; clock_t t[2]; struct star{ int id; float dist; float gasdist; float frac; float idist; float ifrac; float ifrac_rhalf; int isnap; int snap; float a; int fnd; float a_acc; #ifdef POTENTIAL float pot; #endif }; struct gaspart{ int id; float maxtemp; float Tvir; float Tvir_acc; float a_maxtemp; float frac_maxtemp; float a_acc; float T_acc; float a_star; }; int cmp_star_id(const void *a, const void *b) { struct star *x= (struct star*)a; struct star *y= (struct star*)b; if (x->id > y->id) return 1; if (x->id < y->id) return -1; return 0; } int cmp_gas_id(const void *a, const void *b) { struct gaspart *x= (struct gaspart*)a; struct gaspart *y= (struct gaspart*)b; if (x->id > y->id) return 1; if (x->id < y->id) return -1; return 0; } double fitfct(double t, double *p) { return log10((p[0]) / ((t/p[1]) * SQR(1+t/p[1]))); } void dumprintout ( int n_par, double* par, int m_dat, double* fvec, void *data, int iflag, int iter, int nfev ) { // dummy function to catch fitting output } void usage() { fprintf(stderr,"Trace v0.02\n"); fprintf(stderr,"-f <snapshot basefilename>\n"); fprintf(stderr,"-i <startindex> <endindex>\n"); fprintf(stderr,"if you want to search for CM in an area around the given coordinates\n"); fprintf(stderr,"add -sr <radius> to include particles for the search with distance to cm < radius\n"); fprintf(stderr,"-n <name of the halo>\n"); fprintf(stderr,"-cm <center of mass X Y Z>\n"); fprintf(stderr,"-ui <bitcode for particle types to use for computation of Inertia Tensor>\n"); fprintf(stderr,"-uva <bitcode for particle types to use for computation of Velocity Anisotropy>\n"); fprintf(stderr,"-ucm <bitcode for particle types to use for computation of Center of Mass>\n"); fprintf(stderr,"-cut <create Gadget-file for every halo>\n"); fprintf(stderr,"-tf <trace factor>\n"); fprintf(stderr,"-mincnt <minimum number of particles for CM-Search>\n"); fprintf(stderr,"-ntr <Number of particles to trace back>\n"); fprintf(stderr,"-cont <do not owerwrite existing files>\n"); exit(1); } float step() { float tm; t[1]=clock(); tm=(float)(t[1]-t[0])/CLOCKS_PER_SEC; t[0]=clock(); return tm; } /* int cmp (struct particle *a, struct particle *b) { if (a[0].dist > b[0].dist) return 1; else return -1; } */ int cmp (struct particle *a, struct particle *b) { return CMP(a[0].dist,b[0].dist); } int cmpind (struct particle *a, struct particle *b) { return CMP(a[0].ind,b[0].ind); } int compare (float *a, float *b) { if (*a > *b) return 1; else return -1; } int coord512 (int *result, long index) { int c[3]; int i; result[0]=floor(index%262144/512.0); result[1]=(index%512); result[2]=floor(index/262144.0); for (i=0; i<3; i++) if ((result[i]<0) || (result[i]>512)) return 1; return 0; } int main (int argc, char *argv[]) { typedef float fltarr[3]; struct particle *part, *vpart; gadpart *part_ev; struct star *stars; struct gaspart *gas; struct header ic, evolved, out; FILE *fp, *outf; char cmfile[80],icfile[80],snapfile[256], basename[256],snfile[80],friendsfile[80],idlfile[80],asciifile[80],gridfile[80],jrfile[80], outfile[80], gadfile[80], starfile[80], prefix[20]; unsigned int numpart=0, nummass=0; int blocksize,i,j,k,l,m,n,h,dum,tr_halo=0,tr_halo_cnt = 0,id,halo,checknpart,mindum,nhalo,count,notrace=0; int *tr_halo_id,*tr_halo_i, ca[3], size[3]; fltarr *pos_ev,*pos_ic,*vel, *outpos, *outvel; float *mass_ev, *mass_dum,*mass_ic,dist,maxdist,*distance,halomass,halorad, halolmd, *outmass; double posdum,max[3],min[3],srad=25, icmin[3], icmax[3], envdens, bgdens; float lmd,vcm[3]={0,0,0},jcm[3]={0,0,0},J[3]={0,0,0}, torq[3],rdum[3], vdum[3], massdum; int *id_ev,*id_ic,*iclus, halonpart, *outid; float tm,linkle,od, tr_factor, maxstardist=0; double boxsz,cm[3]={0,0,0}, masstot, gridsize, rlog[50], p[50], err[50], d, rad_ratio; double cvel[3]; short pb[3]={0,0,0}; int minbox[3], maxbox[3], szbox[3], ****grid, ***gridsz, boxind[3], alignf; int nfun, npar, dojr=0, vcnt=0, use_inertia, use_va, use_cm; double par[2],ddum, dx512, ddum1, totj, rotvel, peakrotvel, peakr, vmass, sqrenvdensrad, sfl=SOFTENING; int cutgad=0, idum, donotoverwrite=0, test=0, *cid, numalloc, numtrace; fltarr *hcm; int debug=0, maxhaloes, minpartcnt; int startind, endind, snapind, starcnt=0, gascnt=0, totalstarcnt=0, totalgascnt=0, dostars=1; int addstar[ADDSTAR_BUF]; int addgas[ADDGAS_BUF]; double meff, effrad; double ll = 0.8; int doFOF = 1; int doascii = 0; int singlefile=0; double GAP=GAP2BORDER; double conv_dist=1.0; double conv_mass=1.0; // float timestep[NUMTIMESTEPS]; t[0]=clock(); dx512=72000.0/512.0; rad_ratio=INERTIA_START_RAD; use_inertia=INERTIA_USE_PART_TYPE; use_va=VA_USE_PART_TYPE; use_cm=CM_USE_PART_TYPE; gridsize=GRIDSIZE; maxhaloes=MAXNHALOES; minpartcnt=MIN_PARTICLE_COUNT; numtrace=NUMTRACE; maxstardist=MAX_STAR_DIST; sprintf(prefix,"m"); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //filenames are ignored if given as command line parameters strcpy(gridfile,"<none>"); strcpy(cmfile,"<none>"); strcpy(basename,""); strcpy(icfile,""); strcpy(idlfile,"idlinp.dat"); strcpy(asciifile,"ascii.dat"); tr_factor=TRACE_FACTOR; // tr_halo=123; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! i=1; if (argc==1) usage(); while (i<argc) { if (!strcmp(argv[i],"-f")) { i++; strcpy(basename,argv[i]); i++; } else if (*argv[i]!='-') { startind=endind=1; singlefile=1; strcpy(basename,argv[i]); i++; } else if (!strcmp(argv[i],"-i")) { i++; startind=atoi(argv[i]); i++; endind=atoi(argv[i]); i++; if (startind>endind) { int intdum=startind; startind=endind; endind=intdum; } } else if (!strcmp(argv[i],"-n")) { i++; strcpy(prefix,argv[i]); i++; } else if (!strcmp(argv[i],"-debug")) { i++; debug=1; } else if (!strcmp(argv[i],"-test")) { i++; test=1; } else if (!strcmp(argv[i],"-cont")) { i++; donotoverwrite=1; } else if (!strcmp(argv[i],"-gap")) { i++; GAP=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-dc")) { i++; conv_dist=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-mc")) { i++; conv_mass=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-nofof")) { i++; doFOF=0; } else if (!strcmp(argv[i],"-pfof")) { i++; doFOF= doFOF | 2; } else if (!strcmp(argv[i],"-cutfof")) { i++; doFOF= doFOF | 4; //not yet implemented } else if (!strcmp(argv[i],"-idl")) { i++; strcpy(idlfile,argv[i]); i++; } else if (!strcmp(argv[i],"-ascii")) { i++; doascii = 1; strcpy(asciifile,argv[i]); i++; } else if (!strcmp(argv[i],"-da")) { i++; doascii = 1; } else if (!strcmp(argv[i],"-gr")) { i++; strcpy(gridfile,argv[i]); i++; } else if (!strcmp(argv[i],"-mincnt")) { i++; minpartcnt=atoi(argv[i]); i++; } else if (!strcmp(argv[i],"-ntr")) { i++; numtrace=atoi(argv[i]); i++; } else if (!strcmp(argv[i],"-sr")) { i++; srad=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-gs")) { i++; gridsize=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-r")) { i++; rad_ratio=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-soft")) { i++; sfl=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-ll")) { i++; ll=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-ui")) { i++; use_inertia=atoi(argv[i]); i++; } else if (!strcmp(argv[i],"-uva")) { i++; use_va=atoi(argv[i]); i++; } else if (!strcmp(argv[i],"-ucm")) { i++; use_cm=atoi(argv[i]); i++; } else if (!strcmp(argv[i],"-use")) { i++; use_cm=atoi(argv[i]); use_va=use_cm; use_inertia=use_cm; i++; } else if (!strcmp(argv[i],"-jr")) { i++; dojr=1; strcpy(jrfile,argv[i]); i++; } else if (!strcmp(argv[i],"-cut")) { i++; cutgad=1; } else if (!strcmp(argv[i],"-tr")) { i++; notrace=1; } else if (!strcmp(argv[i],"-ds")) { i++; dostars=0; } else if (!strcmp(argv[i],"-msd")) { i++; maxstardist=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-tf")) { i++; tr_factor=atof(argv[i]); i++; } else if (!strcmp(argv[i],"-cm")) { i++; cm[0]=atof(argv[i++]); cm[1]=atof(argv[i++]); cm[2]=atof(argv[i++]); // cmset=1; } else { usage(); } } cid=(int *) calloc(numtrace, sizeof(int)); /* fp=fopen("times.dat", "r"); if (fp!=NULL) { for (i=0; i<NUMTIMESTEPS; i++) fscanf(fp,"%f", &timestep[i]); fclose(fp); } else printf("times.dat not found\n"); */ dum=0; sqrenvdensrad=SQR(ENVDENSRAD); if (debug) printf("comencing main loop...\n");fflush(stdout); /************************************************************************************/ /* Start of main loop */ /************************************************************************************/ for (snapind=endind; snapind>=startind; snapind--) { if (debug) {printf("Ind: %d %d %d\n", snapind, endind, startind);fflush(stdout);} sprintf(snapfile,"%s%03d", basename, snapind); if (singlefile) strcpy(snapfile, basename); /* if (access(outfile, 0)!=0) { printf("File %s does not exits!\n", snapfile); continue; } */ // numpart=readgadget(snapfile, &evolved, &pos_ev, &vel, &id_ev, &mass_ev); numpart=readgadget_part(snapfile, &evolved, &part_ev); if (numpart==0) { extern int libgaderr; fprintf(stderr,"LibGad Error Code: %d\n", libgaderr); continue; } convertunits(&evolved, part_ev, conv_mass, conv_dist); if (evolved.npart[0]==0) {dostars=0;} if (debug) {printf("numpart %d\n", numpart);fflush(stdout);} #ifndef NOGAS if ((debug) && (evolved.npart[0]) ) {printf("sph: %g %g\n", part_ev[0].sph->u, part_ev[0].sph->rho);fflush(stdout);} #endif printf("SnapInd: %d\nStart CM search at %f %f %f\n",snapind, cm[0], cm[1], cm[2]); if (cid[0]) { k=0; for (j=0; j<3; j++) cm[j]=0; masstot=0; qsort(cid, numtrace, sizeof(int), cmp_int); for (i=evolved.npart[0]; i< numpart; i++) { int *fnd=bsearch(&part_ev[i].id,cid, numtrace, sizeof(int), cmp_int); if (fnd!=NULL) { for (j=0; j<3; j++) { if (pb[j]) cm[j]+=MOVE(part_ev[i].pos[j], boxsz)*part_ev[i].mass; else cm[j]+=part_ev[i].pos[j]*part_ev[i].mass; } masstot+=part_ev[i].mass; k++; } if (k==numtrace) break; } // if (debug) printf("CID %d\n", cid); //set start CM for (j=0; j<3; j++) { cm[j]=cm[j]/masstot; if (pb[j]) cm[j]==MOVE(cm[j],boxsz); } } cdens=(5.36e-8) * evolved.hubparam * evolved.hubparam; cdens=cdens*(evolved.omegal+evolved.omega0*pow(evolved.time,-3)); bgdens=cdens*evolved.omega0; if (debug) {printf("...\n");fflush(stdout);} tr_halo_cnt=0; /* for (k=0; k<3; k++) { cm[k]=hcm[trhalo][k]; x=floor(cm[0]/gridsize); y=floor(cm[1]/gridsize); z=floor(cm[2]/gridsize); } */ sprintf(idlfile ,"%s_%03d.idl",prefix, snapind); sprintf(asciifile ,"%s_%03d.ascii",prefix, snapind); sprintf( jrfile ,"%s_%03d.jr", prefix, snapind); sprintf(outfile ,"%s_%03d.tr", prefix, snapind); sprintf(gadfile ,"%s_%03d.gad",prefix, snapind); if ((access(outfile, 0)==0) && (donotoverwrite)) { continue; } if (singlefile) { sprintf(idlfile ,"%s.idl",prefix); sprintf(asciifile ,"%s.ascii",prefix); sprintf( jrfile ,"%s.jr", prefix); sprintf(outfile ,"%s.tr", prefix); sprintf(gadfile ,"%s.gad",prefix); outf=stdout; } else outf=fopen(outfile, "w"); fprintf(outf, "ucm %d ui %d uva %d\n", use_cm, use_inertia, use_va); pb[0]=0; pb[1]=0; pb[2]=0; masstot=0; double icm[3]; for (k=0; k<3; k++) //check whether periodic boundaries are needed { if ((cm[k]<GAP) || (cm[k]>(evolved.boxsize-GAP))) { pb[k]=1; cm[k]=MOVE(cm[k],boxsz); } icm[k]=cm[k]; } /* index=(int *) malloc((int)(numpart*(WORKSPACE*LARGE_WS))*sizeof(int)); if (index==NULL) { fprintf(stderr, "memory allocation failed (index)\n"); exit(1); } icnt=0; for (i=(x-NBOX); i <= (x+NBOX); i++) for (j=(y-NBOX); j <= (y+NBOX); j++) for (k=(z-NBOX); k <= (z+NBOX); k++) { if (icnt>=(WORKSPACE*LARGE_WS*numpart-1)) { fprintf(stderr, "out of memory (index), increase WORKSPACE and recompile\n"); exit(1); } dist=sqrt(pow(x-i,2)+pow(y-j,2)+pow(z-k,2)); if (dist<(NBOX+1)) { for (l=1; l <= grid[(i+n)%n][(j+n)%n][(k+n)%n][0]; l++) { index[icnt++]=grid[(i+n)%n][(j+n)%n][(k+n)%n][l]; } } } //printf("halo %d %d x %d y %d z %d\n", tr_halo , icnt, x[tr_halo], y[tr_halo], z[tr_halo]); index=realloc(index, sizeof(int)*icnt); */ if (debug) {printf("search Center\n");fflush(stdout);} int iteration=0; double searchrad=srad/1.5; float allocsize=WORKSPACE/8; if (srad>0) do { tr_halo_cnt=0; for (k=0; k<3; k++) cm[k]=icm[k]; searchrad*=1.5; allocsize=MIN(8*allocsize, WORKSPACE* LARGE_WS); if (srad>0) { tr_halo_id=(int *)malloc((int)(numpart*allocsize)*sizeof(int)); tr_halo_i =(int *)malloc((int)(numpart*allocsize)*sizeof(int)); if ((tr_halo_id==NULL) || (tr_halo_i==NULL)) { fprintf(stderr, "memory allocation failed\n"); exit(2); } maxdist=searchrad*searchrad; if (debug) {printf("!\n");fflush(stdout);} for (i=0; i < numpart; i++) { // i=index[l]; dist=0; for (j=0; j<3; j++) if (pb[j]) dist+=pow(MOVE(part_ev[i].pos[j],boxsz)-cm[j],2); else dist+=pow(part_ev[i].pos[j]-cm[j],2); // if (debug) {printf("%%");fflush(stdout);} int type= part_ev[i].type; if ((dist<maxdist) && ( (1<<type) & use_cm) ) { tr_halo_id[tr_halo_cnt]=part_ev[i].id; tr_halo_i[tr_halo_cnt++]=i; } if (tr_halo_cnt>=(allocsize*numpart-1)) { fprintf(stderr, "out of memory (<srad), increase WORKSPACE and recompile!\n"); exit(1); } } // tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt); // tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt); } if (++iteration>3) { tr_halo_cnt=0; } if (debug) {printf("iteration %d\n", iteration);fflush(stdout);} if (tr_halo_cnt < minpartcnt) { break; } if (srad>0) { maxdist=searchrad; count=tr_halo_cnt; do { masstot=0; maxdist*=0.92; for (j=0; j<3; j++){rdum[j]=cm[j];} cm[0]=0; cm[1]=0; cm[2]=0; for (i=0; i < count; i++) { for (j=0; j<3; j++) { if (pb[j]) cm[j]+=MOVEB(part_ev[tr_halo_i[i]].pos[j]) * part_ev[tr_halo_i[i]].mass; else cm[j]+=part_ev[tr_halo_i[i]].pos[j]*part_ev[tr_halo_i[i]].mass; } masstot+=part_ev[tr_halo_i[i]].mass; } for (j=0; j<3; j++) cm[j]=cm[j]/(masstot); dum=0; for (i=0; i < count; i++) // { dist=0; for (j=0; j<3; j++) { if (pb[j]) dist += pow((MOVE(part_ev[tr_halo_i[i]].pos[j],boxsz)-cm[j]),2); else dist += pow((part_ev[tr_halo_i[i]].pos[j]-cm[j]),2); } dist=sqrt(dist); if (dist < maxdist) { tr_halo_i[dum]=tr_halo_i[i]; dum++; } } count=dum; if ((count<50) && (cvel[0]==0)) { masstot=0; for (i=0; i< count; i++) { for (j=0; j<3; j++) { cvel[j] += part_ev[tr_halo_i[i]].vel[j] * part_ev[tr_halo_i[i]].mass; } masstot+= part_ev[tr_halo_i[i]].mass; } for (j=0; j<3; j++) cvel[j]=cvel[j]/(masstot); } } while (count>5); free(tr_halo_id); free(tr_halo_i); } } while ((ABS(cm[0]-icm[0])>(searchrad/2)) || (ABS(cm[1]-icm[1])>(searchrad/2)) || (ABS(cm[2]-icm[2])>(searchrad/2)) ); if (debug) {printf("Center Found\n");fflush(stdout);} if ((tr_halo_cnt < minpartcnt) && (srad>0)) { fprintf(outf, "%g %g %g <No Halo found>\n" ,cm[0], cm[1], cm[2]); // free(index); free(tr_halo_id); free(tr_halo_i); fclose(outf); continue; } maxdist=GAP*GAP; numalloc=(int)(numpart); part= (struct particle *)malloc(sizeof(struct particle)*numalloc); vpart=(struct particle *)malloc(sizeof(struct particle)*numalloc); if ((part==NULL) || (vpart==NULL)) { fprintf(stderr,"memory allocation failed!\n"); exit(1); } if (debug) {printf("memmory allocated\n");fflush(stdout);} count=0; envdens=0; for (i=0; i< numpart; i++) { // i=index[l]; dist=0; for (j=0; j<3; j++) { if (pb[j]) dist += pow((MOVE(part_ev[i].pos[j],boxsz)-cm[j]),2); else dist += pow((part_ev[i].pos[j]-cm[j]),2); if (dist>maxdist) break; } if (dist < sqrenvdensrad) { envdens+=part_ev[i].mass; } if (dist < maxdist) { dist=sqrt(dist); part[count].dist=dist; part[count++].ind=i; } if (count>=numalloc) { fprintf(stderr, "increase Workspace!\n"); exit(1); } } if (debug) {printf("Close particles chosen\n");fflush(stdout);} // qsort(&part[0],count,sizeof(struct particle), (__compar_fn_t)cmp); //sort particles by distance to CM of halo qsort(&part[0],count,sizeof(struct particle), cmp); //sort particles by distance to CM of halo // part=realloc(part,sizeof(struct particle)*count); masstot=0; i=0; od=201; effrad=30*evolved.hubparam; meff=0; peakrotvel=0; double b_mass=0; double dm_mass=0; while ((od > 200) || (i<5)) //Add mass until overdensity drops below 200 { int ind= part[i].ind; masstot+=part_ev[ind].mass; if ((part_ev[ind].type == 0) ||(part_ev[ind].type == 4)) { b_mass += part_ev[ind].mass; } else { dm_mass+= part_ev[ind].mass; } if ((part[i].dist < effrad) && ( (1<<part_ev[ind].type) & use_cm ) ) { meff +=part_ev[ind].mass; } od=masstot/(pow(part[i].dist*evolved.time,3)*(4.0/3.0)*PI*cdens); //printf("i %d od %f\n",i,od); rotvel=sqrt((masstot/(part[i].dist*evolved.time))*(G*Msun*1e10/kpc))*1e-3; if (rotvel > peakrotvel) { peakrotvel= rotvel; peakr=part[i].dist; } vpart[i].dist=part[i].dist; vpart[i].ind=part[i].ind; i++; if (i > count) { fp=fopen("error_trhalo.dat","a"); fprintf(fp,"Halo %d is making trouble\n",snapind); fclose(fp); printf("halo %d is making trouble\n",snapind); break; } } if (debug) {fprintf(outf,"Virial radius calculated\n");fflush(stdout);} if (use_cm==1) fprintf(outf,"Gas mass inside 30 kpc %f\n", meff); if (use_cm==16) fprintf(outf,"Stellar mass inside 30 kpc %f\n", meff); if (use_cm==17) fprintf(outf,"Baryonic mass inside 30 kpc %f\n", meff); masstot-=part_ev[part[i-1].ind].mass; if ((part_ev[part[i-1].ind].type == 0) ||(part_ev[part[i-1].ind].type == 4)) { b_mass -= part_ev[part[i-1].ind].mass; } else { dm_mass-= part_ev[part[i-1].ind].mass; } dum=i-1; vcnt=i; halorad=part[vcnt-1].dist; vpart=realloc(vpart,sizeof(struct particle)*vcnt); // qsort(&vpart[0],vcnt,sizeof(struct particle),(__compar_fn_t)cmpind); qsort(&vpart[0],vcnt,sizeof(struct particle),cmpind); j=0; k=0; while (k<numtrace) { if (part[j].ind>evolved.npart[0]) { cid[k++]=part_ev[part[j].ind].id; } if ((++j) > vcnt) { fprintf(stderr, "not enough DM particles inside the virial radius (%d).\n", k); numtrace=k; } } if (debug) {printf("Innermost DM particles determined\n");fflush(stdout);} envdens=envdens/((4.0/3.0)*PI*pow(ENVDENSRAD*evolved.time,3)); for (j=0; j<3; j++) { if (pb[j]) { cm[j]=MOVE(cm[j],boxsz); fprintf(outf,"!!!periodic boundaries used in Dimension %d !!!\n",j); } } vmass=masstot; fprintf(outf,"redshift: %f\naexp: %f\n", 1./evolved.time - 1,evolved.time); fprintf(outf,"\n halo in snapshot %5d consists of %5d particles, virial Mass/h %5.2f\n rad %5.2f od %4.2f\n",snapind,vcnt,masstot,halorad,od); fprintf(outf," Baryonic Mass/h %5.2f\n DM Mass/h %5.2f \n\n",b_mass, dm_mass); fprintf(outf,"Center of Mass : %12.2f %12.2f %12.2f\n",cm[0],cm[1],cm[2]); fprintf(outf,"shift to cm-file: %+12.2f %+12.2f %+12.2f\n",cm[0]-icm[0],cm[1]-icm[1],cm[2]-icm[2]); fprintf(outf,"CM Vel : %12.2f %12.2f %12.2f\n",cvel[0],cvel[1],cvel[2]); fprintf(outf,"particles in box: %d\n",count); fprintf(outf,"Environmental Radius: %f \n", ENVDENSRAD); fprintf(outf,"Environmental OD: %f %f\n", envdens/cdens, envdens/bgdens); fprintf(outf,"Peakrotvel: %f at %f kpc\n",peakrotvel, peakr); fprintf(outf," Rotvel: %f at Rvir\n",rotvel); tr_halo_id=(int *)malloc(count*sizeof(int)); tr_halo_i =(int *)malloc(count*sizeof(int)); if ((tr_halo_id==NULL) || (tr_halo_i==NULL)) { fprintf(stderr, "memory allocation failed (tr_halo_?)\n"); exit(2); } tr_halo_cnt=0; if (cutgad) { gadpart *outpart= (gadpart *) malloc (sizeof(gadpart)* vcnt); if ((outpart==NULL) ) { fprintf(stderr, "memory allocation failed (outpart)\n"); exit(2); } // outpos =(fltarr *)malloc(sizeof(fltarr)*i); // outvel =(fltarr *)malloc(sizeof(fltarr)*i); // outid =(int *)malloc(sizeof(int)*i); // outmass =(float *)malloc(sizeof(float)*i); out=evolved; for (i=0; i<6; i++) { out.npart[i]=0; out.nall[i]=0; } i=0; while (i<vcnt) { dist=vpart[i].dist; k=vpart[i].ind; outpart[i]=part_ev[k]; for (j=0; j<3; j++) { if (pb[j]) outpart[i].pos[j]=MOVEB(outpart[i].pos[j]) - MOVEB(cm[j]); else outpart[i].pos[j]=(outpart[i].pos[j]) - (cm[j]); outpart[i].vel[j] -= cvel[j]; } // dum=0; // for (l=0; l<6; l++) // { // dum+=evolved.npart[l]; // if (k<dum) break; // } out.npart[outpart[i].type]++; out.nall[outpart[i].type]++; i++; } if (debug) {printf("...writing output file %d %d\n", vcnt, i);fflush(stdout);} // if (debug) {printf("...data-test %g %g %g\n", outpart[0].sph->rho, outpart[0].sph->u, outpart[0].pot);fflush(stdout);} writegadget_part(gadfile, out, outpart); if (debug) {printf("Gadget File written\n");fflush(stdout);} free(outpart); // free(outpos); // free(outvel); // free(outid); // free(outmass); } maxdist=halorad*tr_factor; double hmeff=0; double galmass=0; double gasmass=0; double DMmass=0; double innertotm=0; double galrad=0; double gsfr=0; double meanage=0; int nstars_gal=0; dist=0; i=0; // for (j=0; j<50; j++) // { // p[j]=0; // err[j]=0; // rlog[j]=0; // } while (dist<maxdist) { dist=part[i].dist; m=part_ev[part[i].ind].type; if ((m==4) && (dostars) && (dist < halorad) && (snapind==endind)) totalstarcnt++; else if ((m==0) && (dostars) && (dist < (halorad * ACC_FRAC)) && (snapind==endind)) totalgascnt++; // if ((dist<halorad) && (m>0) && (m<4) && (dist>sfl)) // { // d=log10(dist); // j=floor(d/(log10(halorad)/50)); // err[j]++; // p[j]+=part_ev[part[i].ind].mass; // } if ( ((1<<m) & use_cm) && (hmeff < (meff/2.0)) ) { hmeff+=part_ev[part[i].ind].mass; effrad=dist; } if ((dist < (halorad * 0.1) ) ) { innertotm+=part_ev[part[i].ind].mass; if ((m==4)) { galmass+= part_ev[part[i].ind].mass; double redsh = (1/part_ev[part[i].ind].stellarage) - 1; double sage = TIMEDIFF(redsh, (1/evolved.time)-1 ); meanage += sage; nstars_gal++; } else if ((m==0)) { gasmass+= part_ev[part[i].ind].mass; gsfr+= part_ev[part[i].ind].sph->sfr; } else if ((m==1)) DMmass+= part_ev[part[i].ind].mass; } i++; } meanage /= nstars_gal; if (debug) {printf("totalstarcnt %d\ntotalgascnt %d\n", totalstarcnt,totalgascnt);fflush(stdout);} if (use_cm&16) { i=0; double mdum=0; double total_mass=0; double dm_mass=0; dist=0; while (dist<maxdist) { total_mass += part_ev[part[i].ind].mass; dist=part[i].dist; m=part_ev[part[i].ind].type; if (m==4) { if (mdum < (galmass/2.0)) { mdum+=part_ev[part[i].ind].mass; galrad=dist; } else break; } else if ((m>0) && (m<4)) { dm_mass += part_ev[part[i].ind].mass; } i++; } fprintf(outf,"3D half-mass-galaxy radius: %g\n", galrad); fprintf(outf,"total mass inside 3D half-mass-galaxy radius: %6g\n", total_mass); fprintf(outf,"stellar mass inside 3D half-mass-galaxy radius: %6g\n", mdum); fprintf(outf,"dark matter mass inside 3D half-mass-galaxy radius: %6g\n", dm_mass); } fprintf(outf,"hmeff: %f \neffrad: %f\n", hmeff, effrad); fprintf(outf,"Galaxy mass (M_star < 10 %% Rvir): %f \n", galmass); fprintf(outf,"mean age: %g \n", meanage); fprintf(outf,"SFR (< 10 %% Rvir): %g \n", gsfr); fprintf(outf,"specific SFR (< 10 %% Rvir): %g \n", gsfr / galmass); fprintf(outf,"Gas mass (M_gas < 10 %% Rvir): %f \n", gasmass); fprintf(outf,"darkmatter mass (M_dm < 10 %% Rvir): %f \n", DMmass); fprintf(outf,"Total mass < 10 %% Rvir: %f \n", innertotm); if (debug) {printf("Stars: %d\ni %d\n",totalstarcnt, i);fflush(stdout);} /****************************************************************************************/ /*Find Star Particles inside Rvir********************************************************/ if (dostars) { if (debug) {printf("%d %d %d\n", snapind, endind, (snapind==endind));fflush(stdout);} if (snapind==endind) { starcnt=totalstarcnt; gascnt =totalgascnt; stars = (struct star*) calloc(starcnt, sizeof(struct star)); gas = (struct gaspart*) calloc(gascnt, sizeof(struct gaspart)); if (debug) {printf("Memory for Stars allocated\n");fflush(stdout);} j=0; l=0; k=0; while ( (j<starcnt) || (k<gascnt) ) { // idum=0; // for (m=0; m<6; m++) // { // idum+=evolved.npart[m]; // if (idum>part[l].ind) break; // } if (j>starcnt) exit(1); m = part_ev[part[l].ind].type; if ((m==4) && (part[l].dist < halorad)) { stars[j].id =part_ev[part[l].ind].id; stars[j].idist=part[l].dist; stars[j].ifrac=part[l].dist/halorad; stars[j].ifrac_rhalf=part[l].dist/galrad; stars[j].isnap=snapind; stars[j].dist=part[l].dist; stars[j].frac=part[l].dist/halorad; if (stars[j].frac < ACC_FRAC) stars[j].a_acc=evolved.time; else stars[j].a_acc=0; stars[j].snap=snapind; stars[j].a=evolved.time; #ifdef POTENTIAL stars[j].pot=part_ev[part[l].ind].pot; #endif j++; } else if ((m==0) && (part[l].dist < halorad * ACC_FRAC)) { gas[k].id = part_ev[part[l].ind].id; double temp = temperature(part_ev[part[l].ind]); float vcirc = sqrt((vmass/(halorad * evolved.time))*(G*Msun*1e10/kpc))*1e-3; gas[k].Tvir_acc = SQR(vcirc / 167.) * 1e6; double rho = part_ev[part[l].ind].sph->rho * SQR(HUB) * pow(evolved.time, -3); if (rho < DENS_THRESH) { gas[k].maxtemp = temp; gas[k].a_maxtemp = evolved.time; gas[k].frac_maxtemp = part[l].dist / halorad; gas[k].Tvir = SQR(vcirc / 167.) * 1e6; } else { gas[k].maxtemp = 0; gas[k].a_maxtemp = 0; gas[k].frac_maxtemp = 0; gas[k].Tvir = 0; } gas[k].a_acc = evolved.time; gas[k].T_acc = temp; gas[k].a_star = 0; k++; } l++; } if (debug) {printf("sorting initial stars and gas...\n");fflush(stdout);} // qsort(stars, starcnt, sizeof(struct star), (__compar_fn_t)cmp_star_id); qsort(stars, starcnt, sizeof(struct star) , cmp_star_id); qsort(gas , gascnt , sizeof(struct gaspart), cmp_gas_id); if (debug) {printf("Stars sorted\n");fflush(stdout);} } else { j=0; l=0; k=0; n=0; h=0; struct star stardum; struct gaspart gasdum; if (debug) {printf("Search Stars..%d\n", starcnt);fflush(stdout);} while ( ( (j<starcnt) || (k<gascnt) ) && (l < count)) { // idum=0; // for (m=0; m<6; m++) // { // idum+=evolved.npart[m]; // if (idum>part[l].ind) break; // } m= part_ev[part[l].ind].type; // if (debug) {printf("#");fflush(stdout);} if ((m==0) || (m==4)) { stardum.id=part_ev[part[l].ind].id; struct star *fnd=bsearch(&stardum, stars, starcnt, sizeof(struct star), cmp_star_id); if (fnd!=NULL) { j++; // if (debug) {printf("Found one!...\n");fflush(stdout);} if (m==4) { fnd->dist=part[l].dist; fnd->frac=part[l].dist/halorad; if (fnd->frac < ACC_FRAC) fnd->a_acc=evolved.time; fnd->a=evolved.time; fnd->snap=snapind; #ifdef POTENTIAL fnd->pot=part_ev[part[l].ind].pot; #endif } else { fnd->fnd=1; fnd->gasdist=part[l].dist; if ( (fnd->ifrac <= ACC_FRAC) ) { addgas[h++]=l; if (h>=ADDGAS_BUF) {fprintf(stderr, "Increase ADDGAS_BUF\n");exit(1);} } } } else { if (m==4) { addstar[n++]=l; if (n>=ADDSTAR_BUF) {fprintf(stderr, "Increase ADDSTAR_BUF\n");exit(1);} } else { gasdum.id=part_ev[part[l].ind].id; struct gaspart *fndgas=bsearch(&gasdum, gas, gascnt, sizeof(struct gaspart), cmp_gas_id); if (fndgas != NULL) { double temp = temperature(part_ev[part[l].ind]); double rho = part_ev[part[l].ind].sph->rho * SQR(HUB) * pow(evolved.time, -3); if ((fndgas->maxtemp < temp) && (rho < DENS_THRESH)) { fndgas->maxtemp = temp; float vcirc = sqrt((vmass/(halorad * evolved.time))*(G*Msun*1e10/kpc))*1e-3; fndgas->Tvir = SQR(vcirc / 167.) * 1e6; fndgas->a_maxtemp = evolved.time; fndgas->frac_maxtemp = part[l].dist/halorad; } if (part[l].dist < (halorad * ACC_FRAC)) { fndgas->a_acc = evolved.time; fndgas->T_acc = temp; float vcirc = sqrt((vmass/(halorad * evolved.time))*(G*Msun*1e10/kpc))*1e-3; fndgas->Tvir_acc = SQR(vcirc / 167.) * 1e6; } k++; } } } // j++; } l++; } if (debug) {printf("Write Stars to list %d..\n",n);fflush(stdout);} if (n) { totalstarcnt+=n; stars=realloc(stars, totalstarcnt* sizeof(struct star)); k=totalstarcnt-1; while (k>=n) { stars[k]=stars[k-n]; k--; } for (k=0; k<n; k++) { stars[k].id =part_ev[part[addstar[k]].ind].id; stars[k].idist=part[addstar[k]].dist; stars[k].ifrac=part[addstar[k]].dist / halorad; stars[k].ifrac_rhalf=part[addstar[k]].dist / galrad; stars[k].isnap=snapind; stars[k].dist=part[addstar[k]].dist; stars[k].frac=part[addstar[k]].dist/halorad; if (stars[k].frac < ACC_FRAC) stars[k].a_acc=evolved.time; else stars[k].a_acc=0; stars[k].snap=snapind; stars[k].a=evolved.time; #ifdef POTENTIAL stars[k].pot=part_ev[part[addstar[k]].ind].pot; #endif } starcnt+=n; } if (h) { totalgascnt+=h; gas= realloc(gas, totalgascnt * sizeof(struct gaspart)); k=totalgascnt-1; while (k>=h) { gas[k] = gas[k-h]; k--; } for ( k = 0; k < h; k++ ) { idum = addgas[k]; gas[k].id = part_ev[part[idum].ind].id; double temp = temperature(part_ev[part[idum].ind]); float vcirc = sqrt((vmass/(halorad * evolved.time ))*(G*Msun*1e10/kpc))*1e-3; double rho = part_ev[part[idum].ind].sph->rho * SQR(HUB) * pow(evolved.time, -3); if (rho < DENS_THRESH) { gas[k].maxtemp = temp; gas[k].Tvir = SQR(vcirc / 167.) * 1e6; gas[k].a_maxtemp = evolved.time; gas[k].frac_maxtemp = part[idum].dist / halorad; } else { gas[k].maxtemp = 0; gas[k].Tvir = 0; gas[k].a_maxtemp = 0; gas[k].frac_maxtemp = 0; } if (part[idum].dist < (halorad * ACC_FRAC)) { gas[k].a_acc = evolved.time; gas[k].T_acc = temp; gas[k].Tvir_acc = SQR(vcirc / 167.) * 1e6; } else { gas[k].a_acc=0; gas[k].T_acc=0; gas[k].Tvir_acc=0; } gas[k].a_star = evolved.time; } gascnt+=h; } j=0; k=starcnt-1; while ((stars[k].fnd) && (k)) {k--;} l=0; if (debug) {printf("resorting Stars \n");fflush(stdout);} while (j<k) { if (stars[j].fnd) { stardum=stars[j]; stars[j]=stars[k]; stars[k]=stardum; while ((stars[k].fnd) && (k)) {k--;} } j++; } if (!stars[j].fnd) j++; starcnt=j; // qsort(stars, starcnt, sizeof(struct star), (__compar_fn_t)cmp_star_id); qsort(stars, starcnt, sizeof(struct star), cmp_star_id); qsort(gas, gascnt, sizeof(struct gaspart), cmp_gas_id); } } /****************************************************************************************/ if (debug) printf("fitting...\n");fflush(stdout); // nfun=0; // k=0; // d=log10(halorad)/50; // for (j=0; j<50; j++) // { // if (err[j]!=0) // { // err[nfun]=1/sqrt(sqrt(err[j])); // if (k==0) { // rlog[nfun]=(pow(10, ((j+1)*d )))/2; // p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3)))); // // printf("j %d\n", j); // // } // else { // ddum=p[j]; // rlog[nfun]=(pow(10, ((j+1)*d )) + pow(10, (k*d)))/2; // p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3)) - pow(10, (k*d*3)))); // if (p[nfun]<0) fprintf(outf,"%f %e %e \n", ddum, pow(10, ((j+1)*d*3)), pow(10, (k*d*3)) ); // } // /* // if (rlog[nfun] < SOFTENING) // { // err[nfun]*=10; // printf("S %d\n", nfun); // } // */ // k=j+1; // nfun++; // } else { // // p[j]=0; // // err[j]=1e10; // } // // // } // // for (j=0; j<nfun; j++) // { // p[j]=log10(p[j]); // } // // // auxiliary settings for fitting: // // lm_control_type control; // lm_data_type data; // lm_initialize_control(&control); // // data.user_func = fitfct; // data.user_t = rlog; // data.user_y = p; //--------------------------------------------------- // // par[0]=1; // par[1]=10; // lm_minimize(nfun, 2, par, err, lm_evaluate_default, dumprintout, &data, &control); // printf("%f %f\n", d, pow(10,d*50)); i--; FILE *fp2; if (doascii) { fp2=fopen(asciifile,"w"); } fp=fopen(idlfile,"w"); fprintf(fp," %d %f %f %f %f %f\n",i,masstot,halorad,cm[0],cm[1],cm[2]); dist=0; i=0; while (dist < maxdist) { tr_halo_id[tr_halo_cnt]=part_ev[part[i].ind].id; tr_halo_i[tr_halo_cnt++]=part[i].ind; dist=part[i].dist; double temp; if (part_ev[part[i].ind].type == 0) { temp = temperature(part_ev[part[i].ind]); } else { temp=0; } fltarr veldum, raddum; for ( j = 0; j < 3; j++ ) { veldum[j] = part_ev[part[i].ind].vel[j] - cvel[j]; raddum[j] = part_ev[part[i].ind].pos[j] - cm[j]; } double vrad = radvel(veldum, raddum); fprintf(fp,"%f %f %6d %3d %9.7g %8.2f\n",dist, part_ev[part[i].ind].mass, part_ev[part[i].ind].id, part_ev[part[i].ind].type, temp, vrad); if (doascii) { for (j=0; j<3; j++) fprintf(fp2, "%12g ", part_ev[part[i].ind].pos[j]-cm[j]); for (j=0; j<3; j++) fprintf(fp2, "%12g ", part_ev[part[i].ind].vel[j]-cvel[j]); fprintf(fp2, " %6d ", part_ev[part[i].ind].id); fprintf(fp2, " %6g ", part_ev[part[i].ind].mass); fprintf(fp2, "\n"); } i++; } fprintf(outf,"number of particles within %f times virial radius %d\n", tr_factor ,i); if (doascii) { fclose(fp2); } fclose(fp); if (debug) printf("realloc...\n");fflush(stdout); tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt); tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt); /**********************************************************************************************************************************************/ if (debug) printf("lambda...\n");fflush(stdout); // for (l=-5; l<=5; l++) { count=vcnt; //+l*300; for (k=0; k<3; k++) { jcm[k]=0; vcm[k]=0; J[k]=0; } totj=0; massdum=0; for (j=0; j < count; j++) { for (k=0; k<3; k++) { vcm[k]+=(part_ev[part[j].ind].vel[k] * sqrt(evolved.time)*part_ev[part[j].ind].mass); if (pb[k]) jcm[k]+=(MOVE(part_ev[part[j].ind].pos[k],boxsz)*part_ev[part[j].ind].mass); else jcm[k]+=(part_ev[part[j].ind].pos[k]*part_ev[part[j].ind].mass); } massdum+=part_ev[part[j].ind].mass; } for (k=0; k<3; k++) { vcm[k]=vcm[k]/massdum; jcm[k]=jcm[k]/massdum; jcm[k]=jcm[k]; //test //jcm[k]=cm[k]; } if (dojr) fp=fopen(jrfile,"w"); for (j=0; j < count; j++) { for (k=0; k<3; k++) { if (pb[k]) rdum[k]=MOVE(part_ev[part[j].ind].pos[k],boxsz)-jcm[k]; else rdum[k]=part_ev[part[j].ind].pos[k]-jcm[k]; vdum[k]=part_ev[part[j].ind].vel[k]-vcm[k]; vdum[k] *= sqrt(evolved.time); } torq[0]=(rdum[1]*vdum[2]-rdum[2]*vdum[1]); torq[1]=(rdum[2]*vdum[0]-rdum[0]*vdum[2]); torq[2]=(rdum[0]*vdum[1]-rdum[1]*vdum[0]); ddum=0; for (k=0; k<3; k++) { J[k]+=torq[k]*part_ev[part[j].ind].mass; ddum+=torq[k]*torq[k]; } totj+=sqrt(ddum)*part_ev[part[j].ind].mass; ddum=0; ddum1=0; for (k=0; k<3; k++) {ddum+=SQR(rdum[k]); ddum1+=SQR(torq[k]);} if (dojr) fprintf(fp,"%g %g\n", sqrt(ddum), sqrt(ddum1)*part_ev[part[j].ind].mass); } if (dojr) fclose(fp); lmd=0; for (k=0; k<3; k++) {lmd+=J[k]*J[k];} lmd=(sqrt(lmd)*1e10*(Msun/evolved.hubparam)*1e3*(kpc/evolved.hubparam))/(sqrt(2)*part[count-1].dist*(kpc/evolved.hubparam)*massdum*1e10*(Msun/evolved.hubparam)); // lmd=(totj*1e10*(Msun/evolved.hubparam)*1e3*(kpc/evolved.hubparam))/(sqrt(2)*part[count-1].dist*(kpc/evolved.hubparam)*massdum*1e10*(Msun/evolved.hubparam)); lmd=lmd/sqrt(G*massdum*1e10*(Msun/evolved.hubparam)/(part[count-1].dist*(kpc/evolved.hubparam))); fprintf(outf,"Spin: lamda %e r %g\n",lmd, part[count-1].dist); if (debug) printf("ui...\n");fflush(stdout); /*************************************************************************************************************************************************************/ double q=1, s=1; double Pi[3]={0.0, 0.0, 0.0}; double Pi_PHI=0; double Pi_RR=0; double delta; if (use_inertia) { maxdist=rad_ratio*halorad; if ((use_inertia&16)) { maxdist=galrad; // maxdist=10 * HUB; //think about it (used in feldmann 2010) } double s_old; gsl_matrix *I = gsl_matrix_alloc (3, 3); gsl_vector *eval = gsl_vector_alloc (3); gsl_matrix *evec = gsl_matrix_alloc (3, 3); gsl_matrix *LU = gsl_matrix_alloc (3, 3); gsl_matrix *inv = gsl_matrix_alloc (3, 3); gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3); gsl_matrix *rotation = gsl_matrix_alloc (3, 3); gsl_matrix_set_identity(rotation); gsl_matrix *resultmatrix = gsl_matrix_alloc (3, 3); gsl_matrix_set_zero(I); struct gadpart *wpart; wpart= (struct gadpart *)malloc(sizeof(struct gadpart)*vcnt); m=0; for (k=0; k < vcnt; k++) { l=part[k].ind; wpart[k]=part_ev[l]; for (j=0; j < 3; j++) { if (pb[j]) wpart[k].pos[j]=MOVEB(part_ev[l].pos[j])-MOVEB(cm[j]); else wpart[k].pos[j]=part_ev[l].pos[j]-cm[j]; wpart[k].vel[j] -= cvel[j]; } } do { s_old=s; gsl_matrix_set_zero(I); for (k=0; k < vcnt; k++) { l=part[k].ind; for (i=0; i < 3; i++) for (j=i; j < 3; j++) { ddum =wpart[k].pos[i] * wpart[k].pos[j]; dist =SQR(wpart[k].pos[0])+SQR(wpart[k].pos[1]/q)+SQR(wpart[k].pos[2]/s); ddum/= dist; if ((sqrt(dist)<maxdist) && ((1<<wpart[k].type)&use_inertia)) { gsl_matrix_set(I,i,j, gsl_matrix_get(I,i,j)+ddum); if (i!=j) gsl_matrix_set(I,j,i, gsl_matrix_get(I,j,i)+ddum); } } } gsl_eigen_symmv (I, eval, evec, w); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_DESC); gsl_matrix_memcpy(LU, evec); /* for (i=0; i < 3; i++) { for (j=0; j < 3; j++) printf("%15.4g", gsl_matrix_get(I,i,j)); printf("\n"); } */ for (i=0; i < 3; i++) { double eval_i = gsl_vector_get (eval, i); // gsl_vector_view evec_i = gsl_matrix_column (evec, i); if (i==0) ddum = sqrt(eval_i); else if (i==1) q=sqrt(eval_i)/ddum; else s=sqrt(eval_i)/ddum; //printf ("Ratio = %g\n", sqrt(eval_i)/ddum); // printf ("eigenvector = \n"); // gsl_vector_fprintf (stdout, &evec_i.vector, "%g"); } gsl_permutation *perm = gsl_permutation_alloc (3); int sign; gsl_linalg_LU_decomp (LU, perm, &sign); gsl_linalg_LU_invert (LU, perm, inv); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, inv, rotation, 0.0, resultmatrix); gsl_matrix_memcpy (rotation, resultmatrix); //Rotate Particles gsl_vector *oldpos = gsl_vector_alloc (3); gsl_vector *newpos = gsl_vector_alloc (3); gsl_vector *oldvel = gsl_vector_alloc (3); gsl_vector *newvel = gsl_vector_alloc (3); ddum=0; for (k=0; k < vcnt; k++) { for (i=0; i<3; i++) { gsl_vector_set(oldpos, i, wpart[k].pos[i]); gsl_vector_set(oldvel, i, wpart[k].vel[i]); } gsl_blas_dgemv( CblasNoTrans, 1.0, inv, oldpos, 0.0, newpos); gsl_blas_dgemv( CblasNoTrans, 1.0, inv, oldvel, 0.0, newvel); //ddum += gsl_blas_dnrm2 (oldvel) - gsl_blas_dnrm2 (newvel); for (i=0; i<3; i++) { wpart[k].pos[i]=gsl_vector_get(newpos, i); wpart[k].vel[i]=gsl_vector_get(newvel, i); } } //printf("%g\n", ddum); gsl_vector_free(oldpos); gsl_vector_free(newpos); gsl_vector_free(oldvel); gsl_vector_free(newvel); gsl_permutation_free(perm); } while ((ABS(s_old-s)/s) > 1e-2); char rotgadfile[128]; if (singlefile) { sprintf(rotgadfile ,"%s.rot",prefix); } else sprintf( rotgadfile, "%s_%03d.rot", prefix, snapind); FILE *matrixf=fopen(rotgadfile,"w"); gsl_matrix_fwrite (matrixf, rotation); fclose(matrixf); fprintf(outf,"longest axis = %g * R_vir\nq = %g\ns = %g\n", rad_ratio, q, s); /***********************************************************************************************************************************/ /*Density Profile Fit *********************************************************************************************************/ gadpart_dist * gpart =malloc(vcnt* sizeof(gadpart_dist)); for (i=0; i< vcnt; i++) { gpart[i].part=wpart[i]; for (j=0; j<3; j++) { gpart[i].part.vel[j] *= sqrt(evolved.time); } gpart[i].dist = sqrt(SQR(gpart[i].part.pos[0]) + SQR(gpart[i].part.pos[1]) + SQR(gpart[i].part.pos[2])) * evolved.time; } qsort(gpart, vcnt, sizeof(gadpart_dist), cmp_dist); double rcs; double concentration = nfwfit(par, gpart, vcnt, halorad * evolved.time, sfl*evolved.time, &rcs); fprintf(outf,"Delta_c %f Scale Radius %f Concentration factor c %f\n", par[0], par[1], halorad/par[1]); fprintf(outf,"Error NFW: %6g\n", rcs); double gamma = densproffit(par, gpart, vcnt, galrad*evolved.time, sfl*evolved.time, &rcs, 63); fprintf(outf,"logarithmic slope of density profile: %6g\n", gamma); fprintf(outf,"rho0 of fit: %6g\n", par[0]); fprintf(outf,"Error profile-fit: %6g\n", rcs); /***********************************************************************************************************************************/ //*********************************************** //Calculate projected half-mass-radii and VA if (use_cm == 16) { for (j=0; j<3; j++) { int dim[3]; dim[0]=j; dim[1]=(j+1)%3; dim[2]=(j+2)%3; for (i=0; i< vcnt; i++) gpart[i].dist=sqrt(SQR(gpart[i].part.pos[dim[1]]) + SQR(gpart[i].part.pos[dim[2]])); // fprintf(outf,"%g\n", gpart[10].dist); // qsort(gpart, vcnt, sizeof(gadpart_dist),(__compar_fn_t) cmp_dist); qsort(gpart, vcnt, sizeof(gadpart_dist), cmp_dist); /* r_e apperture */ int count=0; double prad=0; double mdum=0; double veltot=0; double sqrveltot=0; k=0; while (mdum < (galmass/2.0)) { if (gpart[k].part.type == 4) { mdum+=gpart[k].part.mass; prad =gpart[k].dist; veltot += gpart[k].part.vel[dim[0]] * gpart[k].part.mass; sqrveltot+= SQR(gpart[k].part.vel[dim[0]]) *gpart[k].part.mass; count++; } k++; } double halfmassrad = gpart[k-1].dist; double velmean = veltot / mdum; double sqrvelmean= sqrveltot / mdum; double sigm = sqrvelmean - SQR(velmean); fprintf(outf,"DIM %d (%d)| projected hm-radius: %6g | mean velocity variance %6g\n", j, count, prad, sqrt(sigm)); /* 1/2 * r_e aperture */ count = 0; prad = 0; mdum = 0; veltot= 0; double total_mass= 0; sqrveltot = 0; k = 0; while (gpart[k].dist <= (halfmassrad / 2.)) { if (gpart[k].part.type == 4) { mdum+=gpart[k].part.mass; prad =gpart[k].dist; veltot += gpart[k].part.vel[dim[0]] * gpart[k].part.mass; sqrveltot+= SQR(gpart[k].part.vel[dim[0]]) *gpart[k].part.mass; count++; } total_mass += gpart[k].part.mass; k++; } velmean = veltot / mdum; sqrvelmean = sqrveltot / mdum; sigm = sqrvelmean - SQR(velmean); fprintf(outf,"0.5 * R_1/2 aperture: DIM %d (%d)| projected hm-radius: %6g | mean velocity variance %6g | proj. stellar mass %6g | total proj. mass %6g\n", j, count, prad, sqrt(sigm), mdum, total_mass); /* 1 kpc fixed radius */ count = 0; prad = 0; mdum = 0; veltot= 0; sqrveltot = 0; k = 0; while (gpart[k].dist <= ( 1. * evolved.time )) { if (gpart[k].part.type == 4) { mdum+=gpart[k].part.mass; prad =gpart[k].dist; veltot += gpart[k].part.vel[dim[0]] * gpart[k].part.mass; sqrveltot+= SQR(gpart[k].part.vel[dim[0]]) *gpart[k].part.mass; count++; } k++; } velmean = veltot / mdum; sqrvelmean = sqrveltot / mdum; sigm = sqrvelmean - SQR(velmean); fprintf(outf,"1 kpc fixed: DIM %d (%d)| projected hm-radius: %6g | mean velocity variance %6g | proj. stellar mass %6g\n", j, count, prad, sqrt(sigm), mdum); } } free(gpart); if (debug) printf("uva...\n");fflush(stdout); /*************************************************************************************/ /*Calculate Velocity anisotropy */ gadpart * vapart=malloc(vcnt* sizeof(gadpart)); gadpart_dist * dpart =malloc(vcnt* sizeof(gadpart_dist)); int num_va=0; for (i=0; i< vcnt; i++) { if ((1<<(wpart[i].type))&use_va) { // cpygadpart(&vapart[num_va] , &wpart[i]); // cpygadpart(&dpart[num_va].part, &wpart[i]); vapart[num_va]=wpart[i]; dpart[num_va].part=wpart[i]; dpart[num_va].dist=sqrt(SQR(wpart[i].pos[0])+SQR(wpart[i].pos[1]/q)+SQR(wpart[i].pos[2]/s)); num_va++; } } if (debug) printf("particles copied for VA-calculation...\n");fflush(stdout); if (num_va > 50) { // qsort(&dpart[0], num_va, sizeof(gadpart_dist), (__compar_fn_t) cmp_dist); qsort(&dpart[0], num_va, sizeof(gadpart_dist), cmp_dist); int distnum= gadsearch(dpart, maxdist, 0, num_va); // dpart= realloc(dpart, distnum*sizeof(gadpart_dist)); if ((test) && (distnum==-1) ) printf("!num_va: %d %f %f %d\n", num_va, q, s, snapind); if (debug) printf("Build Tree...\n");fflush(stdout); KdNode * root; initKdNode(&root, NULL); buildKdTree(root, vapart, num_va, 0); if (debug) printf("Tree built...\n");fflush(stdout); if (debug) { printf("check Tree...%d ?= %d\n", checkKdTree(root), num_va); printf("min: %f %f %f %f %f\n", root->min, root->down->min, root->up->min, root->down->down->min, root->up->up->min); printf("max: %f %f %f %f %f\n", root->max, root->down->max, root->up->max, root->down->down->max, root->up->up->max); printf("dim: %d %d %d %d %d\n", root->dim, root->down->dim, root->up->dim, root->down->down->dim, root->up->up->dim); fflush(stdout); } for (i=0; i<3; i++) Pi[j]=0; int incstep; if (distnum<120) incstep=1; else if (distnum<300) incstep=5; else if (distnum<500) incstep=10; else if (distnum<5000) incstep=30; else if (distnum<100000) incstep=50; else incstep=250; for (i=0; i<distnum; i+=incstep) { masstot=0; gadpart_dist * knn; double knndist=findkNN(root, &dpart[i].part, 0.5, &knn, kNN); double meanv[3]={0.0, 0.0, 0.0}; double sqrmv[3]={0.0, 0.0, 0.0}; double R = sqrt(SQR(dpart[i].part.pos[0])+SQR(dpart[i].part.pos[1])); double ang; double vR,vR2, vRsum; double vPHI, vPHI2, vPHIsum; for (j=0; j<3; j++) { meanv[j]=dpart[i].part.vel[j]*dpart[i].part.mass; sqrmv[j]=SQR(dpart[i].part.vel[j])*dpart[i].part.mass; } ang = atan2(dpart[i].part.pos[1], dpart[i].part.pos[0]); vR = dpart[i].part.vel[0]* cos(ang)+ dpart[i].part.vel[1]* sin(ang); vR2 = SQR(vR)*dpart[i].part.mass; vRsum = vR*dpart[i].part.mass; vPHI = -dpart[i].part.vel[0]*sin(ang)+dpart[i].part.vel[1]*cos(ang); vPHI2 = SQR(vPHI)*dpart[i].part.mass; vPHIsum= vPHI*dpart[i].part.mass; masstot=dpart[i].part.mass; for (k=0; k<kNN; k++) { for (j=0; j<3; j++) { meanv[j]+=knn[k].part.vel[j]*knn[k].part.mass; sqrmv[j]+=SQR(knn[k].part.vel[j])*knn[k].part.mass; } ang = atan2(knn[k].part.pos[1], knn[k].part.pos[1]); vR = knn[k].part.vel[0]* cos(ang)+ knn[k].part.vel[1]* sin(ang); vR2 += SQR(vR)*knn[k].part.mass; vRsum += vR*knn[k].part.mass; vPHI = -knn[k].part.vel[0]*sin(ang)+ knn[k].part.vel[1]* cos(ang); vPHI2 += SQR(vPHI)*knn[k].part.mass; vPHIsum+= vPHI*knn[k].part.mass; masstot+=knn[k].part.mass; } for (j=0; j<3; j++) { meanv[j]=meanv[j]/masstot; sqrmv[j]=sqrmv[j]/masstot; double sigma=(sqrmv[j]-SQR(meanv[j])); Pi[j]+=(sqrmv[j]-SQR(meanv[j])); if (sigma < 0) printf("!sigmaerror!%g %g %g %g %g\n",sqrmv[j], meanv[j], SQR(meanv[j]), sigma, masstot); } vR2 = vR2/masstot; vRsum = vRsum/masstot; vPHI2 = vPHI2/masstot; vPHIsum= vPHIsum/masstot; Pi_RR += vR2-SQR(vRsum); Pi_PHI+= vPHI2-SQR(vPHIsum); // printf("%5d %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g\n", i, dpart[i].dist, knndist, dpart[i].part.pos[0], dpart[i].part.pos[1], dpart[i].part.pos[2], Pi[i][0], Pi[i][1], Pi[i][2]); free(knn); } fprintf(outf, "PI %g %g %g\n", Pi[0], Pi[1], Pi[2]); double mPi=(Pi[0]+Pi[1])/2; delta= (mPi-Pi[2])/mPi; fprintf(outf, "delta %g\n", delta); if (doFOF) { if (debug) printf("look for central FOF-group...\n");fflush(stdout); gadpart **FOF; int nFOF = 0; int *done = NULL; unsigned int buffer = 0; fltarr center ={0.0, 0.0, 0.0}; // findGadparts(root, center, 3 * ll, &FOF, &nFOF, &buffer); // // findGadparts(root, center, ll, &FOF, &nFOF, &buffer); // qsort(FOF, nFOF, sizeof(gadpart *), cmp_pointer_id ); // if (debug) printf("innermost particles determined and sorted...%d\n", nFOF);fflush(stdout); // //testing // // if (debug) printf("sorted...\n");fflush(stdout); findFOF(root, center, ll, &FOF, &nFOF, &buffer); if (debug) printf("central FOF-group determined...%d\n", nFOF);fflush(stdout); // FILE* tmp; // tmp = fopen("ids.tmp","w"); // for ( i = 0; i < nFOF; i++ ) // { // int *fnd; // fnd = bsearch( &(FOF[i] -> id), done, ndone, sizeof(int), cmp_int ); // if (fnd == NULL) fprintf(tmp,"%d\n", FOF[i] -> id); // } // fclose(tmp); double FOFmass = 0; double FOFcenter[3] = { 0., 0., 0.}; for ( i = 0; i < nFOF; i++ ) { FOFmass += FOF[i] -> mass; for ( j = 0; j < 3; j++) FOFcenter[j] += FOF[i] -> pos[j] * FOF[i] -> mass; } double FOFdist = 0; for ( j = 0; j < 3; j++) { FOFcenter[j] /= FOFmass; FOFdist += SQR(FOFcenter[j]); } FOFdist = sqrt(FOFdist); fprintf(outf, "FOF-Mass: %f\n", FOFmass); fprintf(outf, "FOF-center: %f %f %f\n", FOFcenter[0], FOFcenter[1], FOFcenter[2]); fprintf(outf, "FOF-offset: %f\n", FOFdist); if (use_cm&16) { i=0; double mdum=0; double fofrad=0; dist=0; while (dist<halorad) { dist=part[i].dist; m=part_ev[part[i].ind].type; if (m==4) { if (mdum < (FOFmass/2.0)) { mdum+=part_ev[part[i].ind].mass; fofrad=dist; } else break; } i++; } fprintf(outf,"3D-half-mass-FOF radius: %g\n", fofrad); } if (doFOF & 2) { char FOFfile[128]; if (singlefile) { sprintf(FOFfile ,"%s.fof",prefix); } else { sprintf(FOFfile ,"%s_%03d.fof",prefix, snapind); } FILE *FOFfp = fopen(FOFfile, "w"); for ( i = 0; i < nFOF; i++ ) { fprintf(FOFfp, "%d\n", FOF[i] -> id); } fclose(FOFfp); } free(FOF); } free(root); } free(vapart); free(dpart); /*************************************************************************************/ /* if (cutgad) { out=evolved; qsort(&wpart[0],vcnt,sizeof(struct gadpart),cmp_type); for (i=0; i<6; i++) { out.npart[i]=0; out.nall[i]=0; } i=0; while (i<vcnt) { l=wpart[i].type; out.npart[l]++; out.nall[l]++; i++; } char rotgadfile[128]; sprintf( rotgadfile, "%s_%03d_rot.gad", prefix, snapind); writegadget_part(rotgadfile, out, wpart); } */ gsl_matrix_free(I); gsl_matrix_free(evec); gsl_matrix_free(LU); gsl_matrix_free(inv); gsl_matrix_free(resultmatrix); gsl_matrix_free(rotation); gsl_vector_free(eval); gsl_eigen_symmv_free(w); free(wpart); } /*************************************************************************************************************************************************************/ // endloop: fprintf(outf,"\n\n%g %g %g %g %g %g %d %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g\n",cm[0],cm[1],cm[2],cm[0]-icm[0],cm[1]-icm[1],cm[2]-icm[2],vcnt,halorad, vmass ,par[0], par[1], halorad/par[1],(envdens/bgdens)-1,peakrotvel,peakr,rotvel,lmd, rad_ratio, q, s, Pi[0], Pi[1], Pi[2], Pi_RR, Pi_PHI); } fclose(outf); free(part); free(vpart); free(tr_halo_i); free(tr_halo_id); // free(index); #ifndef NOGAS free(part_ev[0].sph); #endif free(part_ev); // free(pos_ev); // free(id_ev); // free(mass_ev); // free(vel); } /**********************************************************************************************************************************************/ qsort(stars, totalstarcnt, sizeof(struct star), cmp_star_id); if (dostars) { sprintf(starfile ,"%s.stars.insitu",prefix); outf=fopen(starfile, "w"); for (i = 0; i < totalstarcnt; i++) { fprintf(outf,"%8d %4d %8.2f %8.2f %8.7f %8.2f %4d %8.7f %1d %8.7f %8.7f %8.7f %8.7f\n", stars[i].id, stars[i].isnap, stars[i].idist, stars[i].dist, stars[i].frac, stars[i].gasdist, stars[i].snap, stars[i].a, stars[i].fnd, stars[i].a_acc #ifdef POTENTIAL ,stars[i].pot #else , 0. #endif , stars[i].ifrac, stars[i].ifrac_rhalf); } fclose(outf); sprintf(starfile ,"%s.gas.data",prefix); outf=fopen(starfile, "w"); for (i = 0; i < totalgascnt; i++) { fprintf(outf,"%8d %8.4g %8.4g %8.4g %8.7f %8.7f %8.7f %8.4g %8.7f\n", gas[i].id, gas[i].maxtemp, gas[i].Tvir, gas[i].Tvir_acc, gas[i].a_maxtemp, gas[i].frac_maxtemp, gas[i].a_acc, gas[i].T_acc, gas[i].a_star); } fclose(outf); } printf("Time needed: %.2f sec\n",((float)clock())/CLOCKS_PER_SEC); return 0; }
{ "alphanum_fraction": 0.5354693334, "avg_line_length": 27.9664213431, "ext": "c", "hexsha": "fac1d1cf6d3081ae7767a101a29d014982d824d3", "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": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lgo33/GadTools", "max_forks_repo_path": "trace.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_issues_repo_issues_event_max_datetime": "2017-01-12T14:40:32.000Z", "max_issues_repo_issues_event_min_datetime": "2017-01-12T14:40:32.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Fette3lke/GadTools", "max_issues_repo_path": "trace.c", "max_line_length": 307, "max_stars_count": null, "max_stars_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Fette3lke/GadTools", "max_stars_repo_path": "trace.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 21252, "size": 60799 }
/* roots/bisection.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* bisection.c -- bisection root finding algorithm */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include "roots.h" typedef struct { double f_lower, f_upper; } bisection_state_t; static int bisection_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper); static int bisection_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper); static int bisection_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper) { bisection_state_t * state = (bisection_state_t *) vstate; double f_lower, f_upper ; *root = 0.5 * (x_lower + x_upper) ; SAFE_FUNC_CALL (f, x_lower, &f_lower); SAFE_FUNC_CALL (f, x_upper, &f_upper); state->f_lower = f_lower; state->f_upper = f_upper; if ((f_lower < 0.0 && f_upper < 0.0) || (f_lower > 0.0 && f_upper > 0.0)) { GSL_ERROR ("endpoints do not straddle y=0", GSL_EINVAL); } return GSL_SUCCESS; } static int bisection_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper) { bisection_state_t * state = (bisection_state_t *) vstate; double x_bisect, f_bisect; const double x_left = *x_lower ; const double x_right = *x_upper ; const double f_lower = state->f_lower; const double f_upper = state->f_upper; if (f_lower == 0.0) { *root = x_left ; *x_upper = x_left; return GSL_SUCCESS; } if (f_upper == 0.0) { *root = x_right ; *x_lower = x_right; return GSL_SUCCESS; } x_bisect = (x_left + x_right) / 2.0; SAFE_FUNC_CALL (f, x_bisect, &f_bisect); if (f_bisect == 0.0) { *root = x_bisect; *x_lower = x_bisect; *x_upper = x_bisect; return GSL_SUCCESS; } /* Discard the half of the interval which doesn't contain the root. */ if ((f_lower > 0.0 && f_bisect < 0.0) || (f_lower < 0.0 && f_bisect > 0.0)) { *root = 0.5 * (x_left + x_bisect) ; *x_upper = x_bisect; state->f_upper = f_bisect; } else { *root = 0.5 * (x_bisect + x_right) ; *x_lower = x_bisect; state->f_lower = f_bisect; } return GSL_SUCCESS; } static const gsl_root_fsolver_type bisection_type = {"bisection", /* name */ sizeof (bisection_state_t), &bisection_init, &bisection_iterate}; const gsl_root_fsolver_type * gsl_root_fsolver_bisection = &bisection_type;
{ "alphanum_fraction": 0.6592421174, "avg_line_length": 25.6074074074, "ext": "c", "hexsha": "9665b736997c06520f5f7b9996622351a6a500dd", "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/roots/bisection.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/roots/bisection.c", "max_line_length": 114, "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/roots/bisection.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": 1051, "size": 3457 }
/** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include "aXe_grism.h" #include "aXe_utils.h" #include "spce_PET.h" #include "inout_aper.h" #include "trace_conf.h" #include "aper_conf.h" #include "spc_sex.h" #include "disp_conf.h" #include "spc_wl_calib.h" #include "drz2pet_utils.h" #include "fitsio.h" #define AXE_IMAGE_PATH "AXE_IMAGE_PATH" #define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH" #define AXE_DRIZZLE_PATH "AXE_DRIZZLE_PATH" #define AXE_CONFIG_PATH "AXE_CONFIG_PATH" int main(int argc, char *argv[]) { //char *opt; char option_value[MAXCHAR]; char grism_image[MAXCHAR]; char grism_image_path[MAXCHAR]; char conf_file[MAXCHAR]; char conf_file_path[MAXCHAR]; char aper_file[MAXCHAR]; char aper_file_path[MAXCHAR]; char PET_file[MAXCHAR]; char PET_file_path[MAXCHAR]; //char label[MAXCHAR]; char hdu_name[MAXCHAR]; char keyword[FLEN_COMMENT]; int i; //int j, flags; object **oblist; observation *obs=NULL,*wobs=NULL; ap_pixel *result = NULL; //d_point pixel; aperture_conf *conf; //dispstruct *disp; //calib_function *wl_calibration; //FITScards *cards; int f_status = 0; int bckmode = 0; int opt_extr=0; fitsfile *PET_fitsptr; //fitsfile ME_fitsptr; int index=0; int extver=0; int exp_ext=0; int con_ext=0; int wht_ext=0; int mod_ext=0; int var_ext=0; char list_file[MAXCHAR]; char list_file_path[MAXCHAR]; FILE *Filelist; static char Buffer[LINE_LEN_MAX]; char *WorkPtr; char *WorkPtr2; //double refpntx, refpnty, xoffs; double lambda0, dlambda; char extname[FLEN_COMMENT]; if ((argc < 3) || (get_online_option2("help", option_value, argc, argv))) { fprintf(stdout, "aXe_DRZ2PET Version %s:\n" " aXe task that produces one Object or Background Pixel Extraction\n" " Table (-bck option) from a set of images created with aXe_DRIZZLE.\n" " The image list as well as input aperture file (AF) and the aXe\n" " config are all automatically created by the aXe_DRIZZLE task.\n" " The format and the usage of the PET's created with aXe_DRZ2PET\n" " is identical to the PET's created by aXe_AF2PET.\n" "\n" " The image list is looked for in the current directory.\n" " The images listed in the image list, the aXe config file and the\n" " aperture file are looked for in$AXE_DRIZZLE_PATH.\n" " All outputs are writen to $AXE_DRIZZLE_PATH\n" "\n" "Example:\n" " aXe_DRZ2PET [image list filename] [aXe config filename] [options]\n" "\n" "Options:\n" " -bck - generating a PET for the drizzled background images\n" " created by aXE_DRIZZLE using a BAF file instead\n" " of a OAF file.\n" " -in_AF=[string] - overwrite the automatically generated name\n" " of the input aperture file\n" " -out_PET=[string] - overwrite the automatically generated name\n" " of the output PET\n" "\n", RELEASE); exit(1); } fprintf(stdout, "aXe_DRZ2PET: Starting...\n"); index = 0; strcpy (list_file_path, argv[++index]); strcpy (list_file, list_file_path); /* Get the configuration file name */ strcpy(conf_file, argv[++index]); build_path(AXE_CONFIG_PATH, conf_file, conf_file_path); conf = get_aperture_descriptor(conf_file_path); // check the background flagg if (get_online_option2("bck", option_value, argc, argv)) bckmode = 1; // check the background flagg if (get_online_option2("opt_extr", option_value, argc, argv)) opt_extr = 1; /* Fix the PET file name */ if ((get_online_option2("out_PET", option_value, argc, argv))) { strcpy (PET_file, option_value); strcpy (PET_file_path, option_value); } else { strcpy(PET_file, list_file); if (bckmode) { replace_file_extension(list_file, PET_file, ".fits", ".BCK.PET.fits", -1); } else { replace_file_extension(list_file, PET_file, ".fits", ".PET.fits", -1); } build_path(AXE_DRIZZLE_PATH, PET_file, PET_file_path); } /* Fix the aperture file name */ if ((get_online_option2("in_AF", option_value, argc, argv))){ strcpy (aper_file, option_value); strcpy (aper_file_path, option_value); } else { if (bckmode){ replace_file_extension(list_file, aper_file, ".list", ".BAF", -1);} else{ replace_file_extension(list_file, aper_file, ".list", ".OAF", -1);} build_path(AXE_DRIZZLE_PATH, aper_file, aper_file_path); } // give feedback onto the screen: // report on input and output // and also on specific parameter fprintf(stdout, "aXe_DRZ2PET: Input Image List: %s\n", list_file_path); fprintf(stdout, "aXe_DRZ2PET: Input configuration file name: %s\n", conf_file_path); fprintf(stdout, "aXe_DRZ2PET: Input aperture file name: %s\n", aper_file_path); fprintf(stdout, "aXe_DRZ2PET: Output Pixel Extraction Table \n" " (PET) file name: %s\n", PET_file_path); if (opt_extr) fprintf(stdout,"aXe_DRZ2PET: Computing optimal weights.\n\n"); /* Loading the object list */ fprintf(stdout, "aXe_DRZ2PET: Loading object list..."); oblist = file_to_object_list_seq(aper_file_path, obs); fprintf(stdout, "%d objects loaded.\n\n", object_list_size(oblist)); /* Create a new empty PET file */ create_PET(PET_file_path, 1); PET_fitsptr = create_PET_opened(PET_file_path, 1); fprintf(stdout, "aXe_DRZ2PET: Checking files ... "); // check whether all necessary extensions do exist i = 0; Filelist = fopen (list_file_path, "r"); if (NULL == Filelist){ aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Could not open %s\n", list_file_path); } while (NULL != fgets (Buffer, LINE_LEN_MAX, Filelist)){ // cut leading white spaces: WorkPtr = Buffer; while (isspace ((int) *WorkPtr)) WorkPtr++; // if (0 == strlen (WorkPtr)) if (0 == strlen (WorkPtr) || Buffer[0] == '#') continue; // cut after first item: WorkPtr2 = WorkPtr; while (!isspace ((int) *WorkPtr2)) WorkPtr2++; *WorkPtr2 = '\0'; WorkPtr2 = NULL; // detemrine the full name of the drizzled grism image strcpy (grism_image,WorkPtr); build_path (AXE_DRIZZLE_PATH, grism_image, grism_image_path); // find the extension numbers for SCI, ERR, CON and load them // into the structure 'obs' get_extension_numbers(grism_image_path, conf,conf->optkey1,conf->optval1); sprintf (hdu_name, "CON"); con_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); sprintf (hdu_name, "EXPT"); exp_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); if (conf->science_numext < 0 || conf->errors_numext < 0 || con_ext < 0 || exp_ext < 0) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_DRZ2PET: Grism file: %s does not have all necessary extensions!\n", grism_image_path); if (opt_extr) { sprintf (hdu_name, "MOD"); mod_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); // sprintf (hdu_name, "VAR"); // var_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, //conf->optkey1,conf->optval1,extver); var_ext=-1; // if (mod_ext < 0 || var_ext < 0) // aXe_message (aXe_M_FATAL, __FILE__, __LINE__, // "aXe_DRZ2PET: Grism file: %s does not have necessary extensions for optimale extraction!\n", // grism_image_path); } } fclose(Filelist); fprintf(stdout, "Done\n\n"); i = 0; Filelist = fopen (list_file_path, "r"); if (NULL == Filelist){ aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Could not open %s\n", list_file_path); } while (NULL != fgets (Buffer, LINE_LEN_MAX, Filelist)){ // cut leading white spaces: WorkPtr = Buffer; while (isspace ((int) *WorkPtr)) WorkPtr++; // if (0 == strlen (WorkPtr)) if (0 == strlen (WorkPtr) || Buffer[0] == '#') continue; // cut after first item: WorkPtr2 = WorkPtr; while (!isspace ((int) *WorkPtr2)) WorkPtr2++; *WorkPtr2 = '\0'; WorkPtr2 = NULL; // detemrine the full name of the drizzled grism image strcpy (grism_image,WorkPtr); build_path (AXE_DRIZZLE_PATH, grism_image, grism_image_path); fprintf(stdout, "aXe_DRZ2PET: Input data file name: %s\n", grism_image_path); // find the extension numbers for SCI, ERR, CON and load them // into the structure 'obs' get_extension_numbers(grism_image_path, conf,conf->optkey1,conf->optval1); sprintf (hdu_name, "CON"); con_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); obs = load_image_t(grism_image_path, conf->science_numext, conf->errors_numext, con_ext, conf->dqmask, 1.0, 0.0); // find the extension numbers for EXPT and load it // into the structure 'wobs' sprintf (hdu_name, "EXPT"); exp_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); sprintf (hdu_name, "MOD"); mod_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); sprintf (hdu_name, "VAR"); var_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); // preliminar for inverse variance weighting!! // var_ext=conf->errors_numext; fprintf(stdout, "aXe_DRZ2PET: Using exts %i,%i,%i as SCI,ERR,DQ\n", exp_ext,mod_ext,var_ext); wobs = load_image_t(grism_image_path,exp_ext,mod_ext, var_ext , -1, 1.0, 0.0); // normalize the exposure times to // generate the weights normalize_weight(wobs, oblist[i], opt_extr); // get initial wavelength and dispersion // either from the configuration file an // according descriptor if (conf->drz_resol > 0.0){ dlambda = conf->drz_resol; } else{ sprintf (keyword, "DLAMBDA"); dlambda = (double)get_float_from_keyword(grism_image_path, 2, keyword); } if (conf->drz_lamb0 > 0.0){ lambda0 = conf->drz_lamb0; } else{ sprintf (keyword, "LAMBDA0"); lambda0 = (double)get_float_from_keyword(grism_image_path, 2, keyword); } // built the new vector with PET pixels result = (ap_pixel*) make_spc_drztable(obs, wobs, oblist[i], lambda0, dlambda); // compose the name of the new extension and generate this extension get_ID_num(grism_image,extname); strcat(extname,"A"); add_ALL_to_PET(result, extname, PET_fitsptr, 0); // copy the keywords OBJECTID and BEAMID to the PET extension drzprep_fitstrans(grism_image_path, conf->science_numext, PET_fitsptr); // cards = get_FITS_cards(grism_image_path, conf->science_numext); // put_FITS_cards_opened(PET_fitsptr, cards); // free_FITScards(cards); // determine he extension number of the weight // image and store the new weights there sprintf (hdu_name, "WHT"); wht_ext = get_hdunum_from_hduname(grism_image_path, hdu_name, conf->optkey1,conf->optval1,extver); if (wht_ext < 0){ wht_ext = gsl_to_FITSimage (wobs->grism, grism_image_path, 0, hdu_name); fprintf(stdout, "aXe_DRZ2PET: Weights written to %s %i\n", grism_image_path, wht_ext); } else{ wht_ext = gsl_to_FITSimageHDU (wobs->grism, grism_image_path, 0, hdu_name, wht_ext); fprintf(stdout, "aXe_DRZ2PET: Weights replaced in %s %i\n", grism_image_path, wht_ext); } // free the memory if (result!=NULL) { free(result); result = NULL; } free_observation(obs); free_observation(wobs); i++; } if (oblist != NULL) free_oblist(oblist); fclose(Filelist); fits_close_file(PET_fitsptr, &f_status); if (f_status) { aXe_message(aXe_M_FATAL, __FILE__, __LINE__, "aXe_DRZ2PET: " "Error closing PET: %s ", PET_file_path); } else { transport_cont_modname(grism_image_path, PET_file_path); fprintf(stdout, "aXe_DRZ2PET: PET file %s closed.\n", PET_file_path); } fprintf(stdout, "aXe_DRZ2PET: Done...\n"); exit(0); }
{ "alphanum_fraction": 0.6354981036, "avg_line_length": 31.6642156863, "ext": "c", "hexsha": "b25741ee9dc011a5600926b959d0887057870b0d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/aXe_DRZ2PET.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/aXe_DRZ2PET.c", "max_line_length": 107, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/aXe_DRZ2PET.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3784, "size": 12919 }
#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 restart_MCMC(MCMC_info *MCMC) { SID_log("Resetting MCMC structure for a fresh run...", SID_LOG_OPEN); MCMC->flag_integrate_on = GBP_FALSE; MCMC->flag_analysis_on = GBP_TRUE; MCMC->first_map_call = GBP_TRUE; MCMC->first_link_call = GBP_TRUE; MCMC->flag_init_chain = GBP_TRUE; MCMC->first_chain_call = GBP_TRUE; MCMC->first_parameter_call = GBP_TRUE; MCMC->first_likelihood_call = GBP_TRUE; MCMC->ln_likelihood_last = 0.; MCMC->ln_likelihood_new = 0.; MCMC->ln_likelihood_chain = 0.; MCMC->n_success = 0; MCMC->n_propositions = 0; MCMC->n_map_calls = 0; free_MCMC_covariance(MCMC); free_MCMC_arrays(MCMC); SID_log("Done.", SID_LOG_CLOSE); }
{ "alphanum_fraction": 0.6478733927, "avg_line_length": 28.8857142857, "ext": "c", "hexsha": "b8c6260790b3f1df569d62b1dd9773ee8cc01ac1", "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/restart_MCMC.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/restart_MCMC.c", "max_line_length": 73, "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/restart_MCMC.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": 320, "size": 1011 }